diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index b9c967a9..e1ca8c44 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -41,8 +41,28 @@ and talks to its Gateway. Nothing here downloads or builds anything. - **Fallback.** Without the component the host says so (`/api/agent/status`, a `notice` frame) and the chat runs on the direct path with the model the user picked. +## Modes (the Mode menu) + +The chat's Mode menu is real Harness behaviour. Each turn the page sends the chat's mode (`mode` in the `/api/chat/stream` +body); before the prompt reaches the Harness the bridge puts that chat's session into the matching permission preset with the +Harness's own `/permission` command (`commands/execute`), reads the session's `permissions` projection back, and refuses to +start the turn (typed error `mode-unavailable`) if it does not match. The preset table is ours (profile entry `permission`); +the Harness's own `read-only`, `workspace-write` and `danger-full-access` presets are not offered. + +| Menu | Preset | Harness sandbox | Approval policy | What it means | +| --- | --- | --- | --- | --- | +| Manual (default) | `strata-manual` | `read-only` | `ask` | The sandbox denies every file change, so the agent must request a one-shot widening (`sandbox_permissions`), and that request is the Approve/Deny card. Reads and read-only commands run without a question. | +| Plan | `strata-plan` | `read-only` | `never` | Nothing can change. A request to widen is rejected without asking anyone, so no Approve card is ever shown; the card ends "Not allowed in this mode". The agent reads, plans and answers. | +| Bypass | `strata-bypass` | `workspace-write` | `never` | Writes and commands inside the workspace (and the Harness's permitted temp areas) run without a question. Anything wider, such as `danger-full-access` or a path outside the workspace, is refused, again without a question. | + +- The mode is read once per turn. Changing the menu during a turn affects the next turn; the running one keeps the permissions it started with. +- An unknown or missing value (an older stored `auto` or `accept-edits`) is Manual, never something looser. +- The session keeps its preset across host restarts (it is a durable event in the Harness record); the page's choice is stored with the chat. +- Nothing in the three presets is `danger-full-access`. If Bypass should mean "also outside the workspace", change `MODE_PRESETS.bypass` in `profile.mjs` to `danger-full-access` + `never`; that is the Harness's own "full access without approval prompts" bundle. +- Windows: the read-only shell runs PowerShell in Constrained Language Mode. A shell command can fail inside Manual or Plan for reasons that have nothing to do with approvals (the card shows the PowerShell error). + ## Tests -`tests/agent-events.test.mjs` (pure), `tests/agent-bridge.test.mjs` and `tests/agent-host.test.mjs` (need a built Harness: +`tests/agent-events.test.mjs` (pure), `tests/agent-bridge.test.mjs`, `tests/agent-modes.test.mjs` and `tests/agent-host.test.mjs` (need a built Harness: `STRATA_HARNESS_DIR=`, otherwise they skip and say so). The model in those tests is `tests/helpers/scripted-worker.mjs`. `scripts/agent-flow.mjs` drives the real app in Chrome and takes screenshots. diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 0117612b..35edc281 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -19,7 +19,7 @@ import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import { GatewayClient } from './gateway-client.mjs'; import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs'; -import { buildProfile, routeFor } from './profile.mjs'; +import { buildProfile, routeFor, MODE_PRESETS, modeOf } from './profile.mjs'; import { TurnProjector } from './events.mjs'; export class AgentUnavailable extends Error { @@ -175,6 +175,28 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance return { sessionId: created.sessionId, fresh: true }; } + /** + * Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and + * check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be + * confirmed the turn fails closed with a typed error instead of running with unknown permissions. + */ + async function applyMode(runtime, sessionId, mode) { + const want = MODE_PRESETS[mode].key; + const read = async () => { + const r = await runtime.gw.rpc('session/projections', { request: { sessionId, keys: ['permissions'] } }); + 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}"`); + } 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'); + } + } + /** * Run one agent turn for a Strata chat and stream it as frames. * `signal` means the client went away: the turn keeps running (that is not Stop). @@ -187,7 +209,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance try { return await runTurnInner(c, options); } finally { c.starting = false; } } - async function runTurnInner(c, { chatId, message, workspacePath, choice = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal }) { + async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal }) { let send = onFrame; signal?.addEventListener('abort', () => { send = () => {}; }, { once: true }); const emit = frame => { try { send(frame); } catch { send = () => {}; } }; @@ -208,7 +230,12 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance c.route = `${route.route}/${route.modelId}`; c.routeGeneration = runtime.generation; } - const projector = new TurnProjector(); + // The chat's permission mode is read once, here, for this whole turn. A change the user makes while the + // turn runs applies to the next one, so a running turn never sees its permissions move under it. + const appliedMode = modeOf(mode); + await applyMode(runtime, sessionId, appliedMode); + + const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval }); const turn = { sessionId, projector, route, requestId, live: false, lastSeq: -1, ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false, @@ -226,7 +253,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance notifyIdle(); } - emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, sessionId, requestId, skills: [] }); + emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [] }); turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, { onItem: item => { diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs index bfc7cf4b..6ed6bb05 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -18,6 +18,9 @@ export function toolScope(name) { return 'connected'; } +/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */ +export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.'; + const clip = (value, max) => { const text = String(value ?? ''); return text.length > max ? `${text.slice(0, max - 1)}…` : text; @@ -52,8 +55,15 @@ export function resultText(message) { * It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin. */ export class TurnProjector { - constructor({ startedAt = Date.now() } = {}) { + /** + * `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so + * no question ever reaches the person: the card goes straight from running to denied, without a moment where it + * offers Approve and Deny buttons that would do nothing. + */ + constructor({ startedAt = Date.now(), policy = 'ask' } = {}) { this.startedAt = startedAt; + this.policy = policy; + this.byPolicy = new Set(); // callIds the approval policy rejected without asking this.tools = new Map(); // callId -> { card, calledAt } this.tokensIn = 0; this.tokensOut = 0; @@ -116,6 +126,7 @@ export class TurnProjector { case 'approval/asked': { if (!d.callId) break; this.asked.set(d.id, d.callId); + if (this.policy === 'never') break; const entry = this.tools.get(d.callId); const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) }; const frame = this.#card(d.callId, patch); @@ -124,6 +135,12 @@ export class TurnProjector { } case 'approval/decided': { const callId = this.asked.get(d.id); + if (callId && this.policy === 'never' && d.outcome !== 'allowed-once') { + this.byPolicy.add(callId); this.denied.add(callId); + const frame = this.#card(callId, { state: 'denied', result: NOT_IN_MODE }); + if (frame) out.push(frame); + break; + } const frame = callId ? this.decide(callId, d.outcome) : null; if (frame) out.push(frame); break; @@ -136,7 +153,7 @@ export class TurnProjector { const denied = this.denied.has(callId); const frame = this.#card(callId, { state: denied ? 'denied' : isError ? 'error' : 'done', - result: resultText(d.message), + result: this.byPolicy.has(callId) ? NOT_IN_MODE : resultText(d.message), durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt), }); if (frame) out.push(frame); @@ -154,7 +171,8 @@ export class TurnProjector { /** An approval was decided. `outcome` is the Harness vocabulary. */ decide(callId, outcome) { if (!this.tools.has(callId)) return null; - if (outcome === 'allowed-once') return this.#card(callId, { state: 'running' }); + // `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked). + if (outcome === 'allowed-once') return this.#card(callId, { state: 'running', approved: true }); this.denied.add(callId); return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' }); } diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs index 162af9ea..135aa91c 100644 --- a/apps/host/server/agent/harness-runtime.mjs +++ b/apps/host/server/agent/harness-runtime.mjs @@ -27,7 +27,9 @@ export function agentEnvironment(base = process.env, extra = {}) { if (v === undefined || !KEEP.test(k) || SECRET_NAME.test(k)) continue; out[k] = v; } - return { ...out, DSH_TELEMETRY_DISABLED: '1', ...extra }; + // DSH_PERMISSION_MODE is the composition default for a session no chat mode has touched (a child agent, a + // seeded session): the strictest sandbox, which matches the Manual preset, never the Harness's wider default. + return { ...out, DSH_TELEMETRY_DISABLED: '1', DSH_PERMISSION_MODE: 'read-only', ...extra }; } /** diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index eca41c72..65264e08 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -24,6 +24,22 @@ const PROTOCOL = { 'openai-chat': 'openai-completions', 'openai-responses': 'ope /** A conservative window for an API model whose connection does not report one. */ 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 + * plan read-only sandbox + never: nothing can change, and the agent is told not to ask + * bypass workspace-write + never: changes inside the workspace without prompts; anything wider is refused + */ +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.' }, + 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: 'workspace-write', approval: 'never', name: 'Bypass', description: 'Changes inside the workspace without asking. Nothing outside the workspace.' }, +}); +export const DEFAULT_MODE = 'manual'; +/** 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); + 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. */ @@ -97,6 +113,8 @@ export function buildProfile({ local = [], connections = [] }) { const entries = [ ...(defaultRoute ? [{ id: 'agent-default-model', name: '@deepseek-ai/dsh-agent-default-model', config: { provider: defaultRoute.route, model: defaultRoute.modelId } }] : []), { 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 } }, // 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 c75d9a86..8bf105ad 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -464,7 +464,7 @@ 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, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal }); + 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 }); 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) { diff --git a/apps/host/tests/agent-bridge.test.mjs b/apps/host/tests/agent-bridge.test.mjs index 46c90080..2ebb5d7a 100644 --- a/apps/host/tests/agent-bridge.test.mjs +++ b/apps/host/tests/agent-bridge.test.mjs @@ -40,7 +40,7 @@ async function rig(t, { connections = [], dataDir } = {}) { const frames = []; const answerWith = opts.answer; // 'approve' | 'deny' | undefined const promise = bridge.runTurn({ - chatId, message, workspacePath: ws, choice: opts.choice ?? null, history: opts.history ?? [], + chatId, message, workspacePath: ws, choice: opts.choice ?? null, mode: opts.mode ?? null, history: opts.history ?? [], onFrame: f => { frames.push(f); opts.onFrame?.(f); @@ -218,7 +218,8 @@ test('an API connection becomes a route; its key reaches the model by reference assert.ok(r.worker.requests.length >= 1); // The shell tool the agent runs must not see the key. - const env = r.run('chat-api', 'SCRIPT:envdump envdump.txt', { choice: { connectionId: 'abcd1234-conn', modelId: 'cloud-model' }, answer: 'approve' }); + // Bypass: the dump is a plain in-workspace write, which Manual would (rightly) make the person approve first. + const env = r.run('chat-api', 'SCRIPT:envdump envdump.txt', { choice: { connectionId: 'abcd1234-conn', modelId: 'cloud-model' }, mode: 'bypass' }); await env.promise; assert.ok(existsSync(join(r.ws, 'envdump.txt')), 'the env dump tool must have run'); const dump = readFileSync(join(r.ws, 'envdump.txt'), 'utf8'); diff --git a/apps/host/tests/agent-events.test.mjs b/apps/host/tests/agent-events.test.mjs index f7231495..2cdefffd 100644 --- a/apps/host/tests/agent-events.test.mjs +++ b/apps/host/tests/agent-events.test.mjs @@ -52,7 +52,7 @@ test('routeFor picks the chat\'s own choice', () => { test('the agent environment keeps what a shell needs and drops ambient credentials', () => { const env = agentEnvironment({ PATH: '/bin', HOME: '/h', OPENAI_API_KEY: 'x', GITHUB_TOKEN: 'y', AWS_SECRET_ACCESS_KEY: 'z', SSH_AUTH_SOCK: 's', SystemRoot: 'C:\\Windows' }, { STRATA_API_KEY_X: 'k' }); - assert.deepEqual(Object.keys(env).sort(), ['DSH_TELEMETRY_DISABLED', 'HOME', 'PATH', 'STRATA_API_KEY_X', 'SystemRoot']); + assert.deepEqual(Object.keys(env).sort(), ['DSH_PERMISSION_MODE', 'DSH_TELEMETRY_DISABLED', 'HOME', 'PATH', 'STRATA_API_KEY_X', 'SystemRoot']); }); test('redact removes secret values and launch tokens from log text', () => { diff --git a/apps/host/tests/agent-host.test.mjs b/apps/host/tests/agent-host.test.mjs index 9761adf0..7335f89f 100644 --- a/apps/host/tests/agent-host.test.mjs +++ b/apps/host/tests/agent-host.test.mjs @@ -200,3 +200,32 @@ test('without the agent component the chat says so and still uses the model the // The direct path used the API model the chat picked, nothing else. assert.ok(s.worker.requests.length >= 1 && s.worker.requests.every(q => q.model === 'cloud-model')); }); + +test('Mode over HTTP: the chat body carries the Mode menu choice; Plan refuses a write, Bypass writes, Manual asks', { skip }, async t => { + const s = await setup(t); + const body = (sessionId, message, mode) => ({ sessionId, message, remoteModel: s.remoteModel, workspaceId: null, history: [], ...(mode ? { mode } : {}) }); + + const plan = await s.host.chat(body('chat-h-plan', 'SCRIPT:retrywrite plan-http.txt x', 'plan')); + assert.equal(plan.find(f => f.type === 'start').mode, 'plan'); + assert.equal(existsSync(join(s.ws, 'plan-http.txt')), false); + assert.ok(!toolStates(plan).includes('proposed')); + assert.equal(toolStates(plan).at(-1), 'denied'); + + const bypass = await s.host.chat(body('chat-h-bypass', 'SCRIPT:retrywrite bypass-http.txt x', 'bypass')); + assert.equal(lines(join(s.ws, 'bypass-http.txt')), 1); + assert.ok(!toolStates(bypass).includes('proposed')); + + // No mode in the body (an older page) is Manual: it asks. + let asked = false; + const manual = await s.host.chat(body('chat-h-manual', 'SCRIPT:retrywrite manual-http.txt x'), async f => { + if (f.type === 'agent-tool' && f.tool.state === 'proposed' && !asked) { + asked = true; + assert.equal(existsSync(join(s.ws, 'manual-http.txt')), false); + await s.host.post('/api/chat/approval', { sessionId: 'chat-h-manual', toolId: f.tool.id, decision: 'approve' }); + } + }); + assert.ok(asked); + assert.equal(manual.find(f => f.type === 'start').mode, 'manual'); + assert.equal(lines(join(s.ws, 'manual-http.txt')), 1); + assert.equal(manual.filter(f => f.type === 'agent-tool').at(-1).tool.approved, true); +}); diff --git a/apps/host/tests/agent-modes.test.mjs b/apps/host/tests/agent-modes.test.mjs new file mode 100644 index 00000000..94834e19 --- /dev/null +++ b/apps/host/tests/agent-modes.test.mjs @@ -0,0 +1,236 @@ +/** + * The chat Mode menu (Manual / Plan / Bypass) as real Harness behaviour. + * + * The Harness is real: its process, its sandbox, its approval gate, its tools, its `/permission` command. + * Only the model is scripted (tests/helpers/scripted-worker.mjs), and it behaves like a careful model: when the + * sandbox denies a change and offers an escalation, it retries the exact call once with `sandbox_permissions`. + * Every test checks the file on disk, not only the frames, because the frames are what the Harness reports. + * + * Needs STRATA_HARNESS_DIR (a built Harness); without it these tests skip, loudly. + */ +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 { MODE_PRESETS, modeOf, buildProfile } from '../server/agent/profile.mjs'; +import { NOT_IN_MODE, TurnProjector } 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 sleep = ms => new Promise(r => setTimeout(r, ms)); +const lines = file => readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).length; +const tools = frames => frames.filter(f => f.type === 'agent-tool'); +const states = frames => tools(frames).map(f => f.tool.state); +const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join(''); + +async function rig(t) { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-modes-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + /** One turn in `mode`; `answer` decides what the person says to an approval card (approve | deny | undefined = nobody answers). */ + const run = async (chatId, message, { mode, answer, onFrame } = {}) => { + const frames = []; + await bridge.runTurn({ + chatId, message, workspacePath: ws, mode, + onFrame: f => { + frames.push(f); 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 })); + }, + }); + return frames; + }; + /** The preset the Harness itself reports for the chat's session. */ + const preset = async chatId => { + const { rt } = bridge._debug(); + const r = await rt.gw.rpc('session/projections', { request: { sessionId: bridge.sessionOf(chatId), keys: ['permissions'] } }); + return r.values.permissions.currentValue; + }; + return { worker, bridge, dir, ws, run, preset }; +} + +test('mode mapping: three presets, the strictest 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']); + assert.deepEqual([MODE_PRESETS.plan.sandbox, MODE_PRESETS.plan.approval], ['read-only', 'never']); + assert.deepEqual([MODE_PRESETS.bypass.sandbox, MODE_PRESETS.bypass.approval], ['workspace-write', '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)); + // No preset gives full access to the machine, 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.ok(!Object.values(entry.config.presets).some(p => p.sandbox === 'danger-full-access')); +}); + +test('projection: under "never" no card ever offers Approve; "ask" marks the approved card', () => { + const call = { type: 'event', event: { seq: 1, time: 1, type: 'tool/call', data: { callId: 'c1', name: 'write', arguments: { file_path: 'x.txt', content: 'x' } } } }; + const asked = { type: 'event', event: { seq: 2, time: 2, type: 'approval/asked', data: { id: 'a1', callId: 'c1', reason: 'escalate sandbox to workspace-write: because' } } }; + const rejected = { type: 'event', event: { seq: 3, time: 3, type: 'approval/decided', data: { id: 'a1', outcome: 'rejected' } } }; + const failed = { type: 'event', event: { seq: 4, time: 4, type: 'tool/result', data: { message: { toolCallId: 'c1', isError: true, content: [{ type: 'text', text: 'Error: the user rejected escalating' }] } } } }; + const never = new TurnProjector({ policy: 'never' }); + const frames = [call, asked, rejected, failed].flatMap(i => never.consume(i)); + assert.deepEqual(frames.map(f => f.tool.state), ['running', 'denied', 'denied']); + assert.ok(frames.every(f => !f.tool.approved)); + assert.equal(frames.at(-1).tool.result, NOT_IN_MODE); + + const ask = new TurnProjector({ policy: 'ask' }); + const ok = { type: 'event', event: { seq: 3, time: 3, type: 'approval/decided', data: { id: 'a1', outcome: 'allowed-once' } } }; + const done = { type: 'event', event: { seq: 4, time: 4, type: 'tool/result', data: { message: { toolCallId: 'c1', isError: false, content: [{ type: 'text', text: 'Created file' }] } } } }; + const f2 = [call, asked, ok, done].flatMap(i => ask.consume(i)); + assert.deepEqual(f2.map(f => f.tool.state), ['running', 'proposed', 'running', 'done']); + assert.equal(f2.at(-1).tool.approved, true); + // A call that never asked finishes without the flag. + const plain = new TurnProjector({ policy: 'ask' }); + const f3 = [call, done].flatMap(i => plain.consume(i)); + assert.equal(f3.at(-1).tool.state, 'done'); assert.equal(f3.at(-1).tool.approved, undefined); +}); + +test('MODE Manual: an in-workspace write is held for the person, and runs once after Approve', { skip }, async t => { + const r = await rig(t); + let fileWhileAsking = null; + const frames = await r.run('m-manual-write', 'SCRIPT:retrywrite approved.txt hello', { + mode: 'manual', answer: 'approve', + onFrame: f => { if (f.type === 'agent-tool' && f.tool.state === 'proposed') fileWhileAsking = existsSync(join(r.ws, 'approved.txt')); }, + }); + assert.equal(fileWhileAsking, false, 'the file must not exist while the card is asking'); + const final = tools(frames).at(-1).tool; + assert.equal(final.state, 'done'); assert.equal(final.approved, true); assert.equal(final.scope, 'write'); + assert.ok(states(frames).includes('proposed')); + assert.equal(lines(join(r.ws, 'approved.txt')), 1); + assert.equal(frames.find(f => f.type === 'start').mode, 'manual'); + assert.equal(await r.preset('m-manual-write'), MODE_PRESETS.manual.key); + assert.equal(frames.at(-1).type, 'done'); +}); + +test('MODE Manual: Deny leaves the file absent, and a shell command that writes is held too', { skip }, async t => { + const r = await rig(t); + const denied = await r.run('m-manual-deny', 'SCRIPT:retrywrite denied.txt nope', { mode: 'manual', answer: 'deny' }); + assert.equal(existsSync(join(r.ws, 'denied.txt')), false); + assert.equal(states(denied).at(-1), 'denied'); + assert.equal(denied.at(-1).type, 'done'); + + const shell = await r.run('m-manual-shell', 'SCRIPT:retryshell shell.txt via-shell', { mode: 'manual', answer: 'approve' }); + assert.ok(states(shell).includes('proposed'), 'the shell write asked first'); + const card = tools(shell).at(-1).tool; + assert.equal(card.scope, 'shell'); assert.equal(card.state, 'done'); assert.equal(card.approved, true); + assert.equal(lines(join(r.ws, 'shell.txt')), 1); +}); + +test('MODE Manual: reading needs no question', { skip }, async t => { + const r = await rig(t); + writeFileSync(join(r.ws, 'notes.txt'), 'plain notes\n'); + const frames = await r.run('m-manual-read', 'SCRIPT:read notes.txt', { mode: 'manual' }); + assert.deepEqual([...new Set(states(frames))], ['running', 'done']); + assert.equal(tools(frames).at(-1).tool.approved, undefined); + assert.match(tools(frames).at(-1).tool.result, /plain notes/); +}); + +test('MODE Plan: a write is refused with no question, the file never appears, reading still works', { skip }, async t => { + const r = await rig(t); + const frames = await r.run('m-plan', 'SCRIPT:retrywrite plan.txt nope', { mode: 'plan' }); + assert.equal(existsSync(join(r.ws, 'plan.txt')), false); + assert.ok(!states(frames).includes('proposed'), 'Plan never shows an Approve card'); + assert.equal(states(frames).at(-1), 'denied'); + assert.equal(tools(frames).at(-1).tool.result, NOT_IN_MODE); + assert.equal(frames.at(-1).type, 'done', 'the turn still settles; the agent answers'); + assert.equal(await r.preset('m-plan'), MODE_PRESETS.plan.key); + assert.equal(r.bridge.status().pendingApprovals, 0); + + const shell = await r.run('m-plan-shell', 'SCRIPT:retryshell plan-shell.txt nope', { mode: 'plan' }); + assert.equal(existsSync(join(r.ws, 'plan-shell.txt')), false); + assert.ok(!states(shell).includes('proposed')); + + writeFileSync(join(r.ws, 'readme.txt'), 'readable in plan mode\n'); + const read = await r.run('m-plan-read', 'SCRIPT:read readme.txt', { mode: 'plan' }); + assert.equal(tools(read).at(-1).tool.state, 'done'); + assert.match(tools(read).at(-1).tool.result, /readable in plan mode/); +}); + +test('MODE Bypass: an in-workspace write runs without asking, and full access is still refused', { skip }, async t => { + const r = await rig(t); + const frames = await r.run('m-bypass', 'SCRIPT:retrywrite free.txt hello', { mode: 'bypass' }); + assert.ok(!states(frames).includes('proposed'), 'Bypass asks nothing'); + assert.equal(lines(join(r.ws, 'free.txt')), 1); + const card = tools(frames).at(-1).tool; + assert.equal(card.state, 'done'); assert.equal(card.approved, undefined, 'it ran; nobody approved it'); + assert.equal(await r.preset('m-bypass'), MODE_PRESETS.bypass.key); + + const shell = await r.run('m-bypass-shell', 'SCRIPT:retryshell free-shell.txt hello', { mode: 'bypass' }); + assert.ok(!states(shell).includes('proposed')); + assert.equal(lines(join(r.ws, 'free-shell.txt')), 1); + + // Bypass does not hand out the machine: a call that asks for danger-full-access is refused without a prompt. + const wide = await r.run('m-bypass-wide', 'SCRIPT:tool wide.txt x', { mode: 'bypass' }); + assert.ok(!states(wide).includes('proposed')); + assert.equal(existsSync(join(r.ws, 'wide.txt')), false); + assert.equal(states(wide).at(-1), 'denied'); +}); + +test('MODE the choice follows the chat: it changes on the next turn, keeps the session, and an unknown value is Manual', { skip }, async t => { + const r = await rig(t); + await r.run('m-switch', 'SCRIPT:echo one', { mode: 'manual' }); + const session = r.bridge.sessionOf('m-switch'); + assert.equal(await r.preset('m-switch'), MODE_PRESETS.manual.key); + await r.run('m-switch', 'SCRIPT:echo two', { mode: 'plan' }); + assert.equal(await r.preset('m-switch'), MODE_PRESETS.plan.key); + const bypass = await r.run('m-switch', 'SCRIPT:retrywrite switched.txt hi', { mode: 'bypass' }); + assert.equal(lines(join(r.ws, 'switched.txt')), 1); + assert.ok(!states(bypass).includes('proposed')); + // Back to Manual: asks again, on the same session, and the earlier turns are still its history. + const manual = await r.run('m-switch', 'SCRIPT:retrywrite switched-again.txt hi', { mode: 'manual', answer: 'approve' }); + assert.ok(states(manual).includes('proposed')); + assert.equal(r.bridge.sessionOf('m-switch'), session); + // A mode the app does not offer (older stored value) or none at all is Manual, never something looser. + for (const [chat, mode] of [['m-odd-1', 'auto'], ['m-odd-2', undefined], ['m-odd-3', 'danger-full-access']]) { + const f = await r.run(chat, 'SCRIPT:retrywrite odd.txt x', { mode, answer: 'deny' }); + assert.ok(states(f).includes('proposed'), `${mode} asks like Manual`); + } + assert.equal(existsSync(join(r.ws, 'odd.txt')), false); +}); + +test('MODE changing the mode while a turn runs does not touch that turn', { skip }, async t => { + const r = await rig(t); + const frames = []; + const slow = r.bridge.runTurn({ chatId: 'm-mid', message: 'SCRIPT:slow 120', workspacePath: r.ws, mode: 'manual', onFrame: f => frames.push(f) }); + for (let i = 0; i < 200 && frames.filter(f => f.type === 'delta').length < 3; i++) await sleep(50); + 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/); + 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' }); + assert.equal(await r.preset('m-mid'), MODE_PRESETS.manual.key); + await slow; + assert.equal(frames.filter(f => f.type === 'delta').length, 120, 'the running turn completed untouched'); + assert.equal(frames.at(-1).finishReason, 'stop'); + // And the new choice is what the next turn uses. + await r.run('m-mid', 'SCRIPT:echo z', { mode: 'bypass' }); + assert.equal(await r.preset('m-mid'), MODE_PRESETS.bypass.key); +}); + +test('MODE the mode survives a restart of the agent process: the chat resumes in the mode it is asked for', { skip }, async t => { + const r = await rig(t); + await r.run('m-restart', 'SCRIPT:echo one', { mode: 'plan' }); + const session = r.bridge.sessionOf('m-restart'); + await r.bridge.close(); + // A new bridge over the same data directory: the persisted session is resumed, then put in the requested mode. + const worker2 = r.worker; + const bridge2 = createAgentBridge({ dataDir: r.dir, localInstances: () => [{ id: 'inst-1', label: 'Scripted', baseUrl: worker2.url, modelId: 'scripted-model', context: 32768 }], connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(() => bridge2.close()); + const frames = []; + await bridge2.runTurn({ chatId: 'm-restart', message: 'SCRIPT:retrywrite resumed.txt hi', workspacePath: r.ws, mode: 'bypass', onFrame: f => frames.push(f) }); + assert.equal(bridge2.sessionOf('m-restart'), session, 'the same session'); + assert.equal(lines(join(r.ws, 'resumed.txt')), 1); + const { rt } = bridge2._debug(); + const now = await rt.gw.rpc('session/projections', { request: { sessionId: session, keys: ['permissions'] } }); + assert.equal(now.values.permissions.currentValue, MODE_PRESETS.bypass.key); +}); diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs index 62f12d5f..fbda13a8 100644 --- a/apps/host/tests/helpers/scripted-worker.mjs +++ b/apps/host/tests/helpers/scripted-worker.mjs @@ -17,6 +17,10 @@ * SCRIPT:echo replies with * SCRIPT:ask one ask_user_question call (the agent asking the person something) * SCRIPT:envdump one shell call that writes the shell's environment to + * SCRIPT:retrywrite the `write` tool, like a careful model: when the sandbox denies it and offers + * an escalation, retry once with `sandbox_permissions: workspace-write` + * SCRIPT:retryshell the same with the shell tool (an in-workspace append) + * SCRIPT:read the `read` tool on * * A request whose last message is a tool result is answered with a text that quotes the result. */ @@ -53,6 +57,8 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = authSha: req.headers.authorization ? createHash('sha256').update(req.headers.authorization).digest('hex') : null, promptChars: raw.length, }); + const shellName = () => (body.tools ?? []).find(t => ['bash', 'pwsh'].includes(t.function?.name))?.function?.name ?? 'bash'; + const shellCommand = (file, value) => (shellName() === 'pwsh' ? `Add-Content -Path '${file}' -Value '${value}'` : `echo ${value} >> ${file}`); let closed = false; res.on('close', () => { if (!res.writableEnded) { closed = true; aborted++; } }); @@ -64,12 +70,32 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: 100 + messages.length, completion_tokens: tokens, total_tokens: 100 + messages.length + tokens } })}\n\n`); res.write('data: [DONE]\n\n'); res.end(); }; + const toolCall = async (name, call) => { + send({ role: 'assistant', content: '', reasoning_content: `I will use ${name}.` }); + await delay(chunkDelayMs); + const argsJson = JSON.stringify(call); + send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name, arguments: '' } }] }); + for (let i = 0; i < argsJson.length; i += 17) { send({ tool_calls: [{ index: 0, function: { arguments: argsJson.slice(i, i + 17) } }] }); await delay(5); } + return finish('tool_calls', 30); + }; const say = async (parts, tokens) => { send({ role: 'assistant', content: '' }); for (const p of parts) { if (closed) return; send({ content: p }); await delay(chunkDelayMs); } if (!closed) finish('stop', tokens ?? parts.length); }; + // A model that read "[sandbox: escalation available ...]" retries the exact call once with the narrowest wider mode. + // Only this prompt's own tool results count: a chat that has run tools before carries older ones. + const promptAt = messages.findLastIndex(m => m.role === 'user' && /SCRIPT:/.test(text(m))); + const toolMessages = messages.slice(promptAt + 1).filter(m => m.role === 'tool'); + if (last.role === 'tool' && ['retrywrite', 'retryshell'].includes(directive?.[1]) && toolMessages.length === 1 && /escalation available/.test(text(last))) { + const [file, ...rest] = (directive[2] ?? '').trim().split(/\s+/); + const value = rest.join(' ') || 'run'; + return toolCall(directive[1] === 'retrywrite' ? 'write' : shellName(), directive[1] === 'retrywrite' + ? { file_path: file, content: `${value} +`, sandbox_permissions: 'workspace-write', justification: 'The user asked for this file to be written.' } + : { command: shellCommand(file, value), description: `Append one line to ${file}`, sandbox_permissions: 'workspace-write', justification: 'The user asked for this file to be written.' }); + } if (last.role === 'tool') { const result = text(last).replace(/\s+/g, ' ').slice(0, 120); return say(['Tool finished. ', `Result: ${result}`]); @@ -82,6 +108,15 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = return say(Array.from({ length: n }, (_, i) => `w${i} `)); } if (name === 'echo') return say([args]); + if (name === 'retrywrite' || name === 'retryshell') { + const [file, ...rest] = args.split(/\s+/); + const value = rest.join(' ') || 'run'; + return name === 'retrywrite' + ? toolCall('write', { file_path: file, content: `${value} +` }) + : toolCall(shellName(), { command: shellCommand(file, value), description: `Append one line to ${file}` }); + } + if (name === 'read') return toolCall('read', { file_path: args }); 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' }] }] }) } }] });