An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(agents): run the side panel on Qwen Code, in beta, behind a safe mode that drops every setting of your own and a startup line read back to prove the denies took
Shahriareb03dd480cd2
diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.tsindex e958118..2ce7fe6 100644--- a/src/daemon/agent/config.test.ts+++ b/src/daemon/agent/config.test.ts@@ -33,6 +33,7 @@ const DEFAULTS: AgentConfig = {vibe: { bin: 'vibe' },grok: { bin: 'grok' },cursor: { bin: 'cursor-agent' },+ qwen: { bin: 'qwen' },},requireApproval: ['page.submitForm'],};diff --git a/src/daemon/agent/runners/fixtures/qwen/error.hand-written.jsonl b/src/daemon/agent/runners/fixtures/qwen/error.hand-written.jsonlnew file mode 100644index 0000000..654555f--- /dev/null+++ b/src/daemon/agent/runners/fixtures/qwen/error.hand-written.jsonl@@ -0,0 +1,3 @@+# Hand-written; the CLI was not installed. validateNonInterActiveAuth.ts emits the auth failure as+# a terminal result in stream-json mode rather than on stderr.+{"type":"result","subtype":"error_during_execution","uuid":"3c2d3e4f-0000-4000-8000-000000000001","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","is_error":true,"duration_ms":40,"duration_api_ms":0,"num_turns":0,"usage":{"input_tokens":0,"output_tokens":0},"permission_denials":[],"error":{"message":"No auth type is selected. Please configure an auth type (e.g. via settings or `--auth-type`) before running in non-interactive mode."}}diff --git a/src/daemon/agent/runners/fixtures/qwen/escaped.hand-written.jsonl b/src/daemon/agent/runners/fixtures/qwen/escaped.hand-written.jsonlnew file mode 100644index 0000000..b53aaca--- /dev/null+++ b/src/daemon/agent/runners/fixtures/qwen/escaped.hand-written.jsonl@@ -0,0 +1,8 @@+# Hand-written; the CLI was not installed. Three init lines that each mean the containment did not+# take: a denied built-in still registered, a second MCP server loaded, and the approval mode the+# run was started in replaced. Each is read on its own, by a fresh reader.+{"type":"system","subtype":"init","uuid":"4c2d3e4f-0000-4000-8000-000000000001","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","tools":["todo_write","run_shell_command","mcp__browsentic__page_getPageInfo"],"mcp_servers":[{"name":"browsentic","status":"connected"}],"permission_mode":"default"}+{"type":"system","subtype":"init","uuid":"4c2d3e4f-0000-4000-8000-000000000002","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","tools":["todo_write"],"mcp_servers":[{"name":"browsentic","status":"connected"},{"name":"node-repl","status":"connected"}],"permission_mode":"default"}+{"type":"system","subtype":"init","uuid":"4c2d3e4f-0000-4000-8000-000000000003","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","tools":["todo_write"],"mcp_servers":[{"name":"browsentic","status":"connected"}],"permission_mode":"yolo"}+{"type":"system","subtype":"init","uuid":"4c2d3e4f-0000-4000-8000-000000000004","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","tools":["todo_write","computer_use__screenshot"],"mcp_servers":[{"name":"browsentic","status":"connected"}],"permission_mode":"default"}+{"type":"system","subtype":"tool_set_refreshed","uuid":"4c2d3e4f-0000-4000-8000-000000000005","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","permission_mode":"auto"}diff --git a/src/daemon/agent/runners/fixtures/qwen/tools.hand-written.jsonl b/src/daemon/agent/runners/fixtures/qwen/tools.hand-written.jsonlnew file mode 100644index 0000000..0908507--- /dev/null+++ b/src/daemon/agent/runners/fixtures/qwen/tools.hand-written.jsonl@@ -0,0 +1,7 @@+# Hand-written; the CLI was not installed. A research run's own web search, beside an MCP call the+# daemon already draws itself, and a delta belonging to a sub-agent's message.+{"type":"stream_event","uuid":"2c2d3e4f-0000-4000-8000-000000000001","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_web_1","name":"web_search"}}}+{"type":"stream_event","uuid":"2c2d3e4f-0000-4000-8000-000000000002","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_mcp_1","name":"mcp__browsentic__page_getPageInfo"}}}+{"type":"stream_event","uuid":"2c2d3e4f-0000-4000-8000-000000000003","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":"toolu_mcp_1","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a sub-agent said this"}}}+{"type":"vibe_check","note":"an event type this reader has never heard of"}+not json at alldiff --git a/src/daemon/agent/runners/fixtures/qwen/turn.hand-written.jsonl b/src/daemon/agent/runners/fixtures/qwen/turn.hand-written.jsonlnew file mode 100644index 0000000..1b47ca4--- /dev/null+++ b/src/daemon/agent/runners/fixtures/qwen/turn.hand-written.jsonl@@ -0,0 +1,13 @@+# Hand-written from the reader and from qwen-code v0.24.4's own types: the CLI was not installed.+# packages/cli/src/nonInteractive/types.ts for the message shapes, nonInteractiveHelpers.ts:222+# for the init line. A contained run registers neither the shell nor the disk, so `tools` is short.+{"type":"system","subtype":"init","uuid":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","cwd":"/Users/you/.browsentic/agents/qwen/run","tools":["todo_write","ask_user_question","exit_plan_mode","tool_search","tool_call","mcp__browsentic__page_getPageInfo","mcp__browsentic__page_clickElement"],"mcp_servers":[{"name":"browsentic","status":"connected"}],"model":"qwen3-coder-plus","permission_mode":"default","slash_commands":[],"qwen_code_version":"0.24.4","agents":[]}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000001","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"message_start","message":{"id":"msg_01","role":"assistant","model":"qwen3-coder-plus","content":[]}}}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000002","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000003","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The page "}}}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000004","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"the price is in the header"}}}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000005","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"costs $40."}}}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000006","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"content_block_stop","index":0}}+{"type":"assistant","uuid":"1c2d3e4f-0000-4000-8000-000000000007","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"message":{"id":"msg_01","type":"message","role":"assistant","model":"qwen3-coder-plus","content":[{"type":"text","text":"The page costs $40."}],"usage":{"input_tokens":2100,"output_tokens":18,"cache_read_input_tokens":8000}}}+{"type":"stream_event","uuid":"1c2d3e4f-0000-4000-8000-000000000008","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","parent_tool_use_id":null,"event":{"type":"message_stop"}}+{"type":"result","subtype":"success","uuid":"1c2d3e4f-0000-4000-8000-000000000009","session_id":"9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31","is_error":false,"duration_ms":4210,"duration_api_ms":3900,"num_turns":3,"result":"The page costs $40.","usage":{"input_tokens":2100,"output_tokens":18,"cache_read_input_tokens":8000},"permission_denials":[]}diff --git a/src/daemon/agent/runners/index.test.ts b/src/daemon/agent/runners/index.test.tsindex 5673ad1..b70de47 100644--- a/src/daemon/agent/runners/index.test.ts+++ b/src/daemon/agent/runners/index.test.ts@@ -42,6 +42,7 @@ const configWith = (agents: Partial<Record<AgentKind, AgentSettings>>, agent: Agvibe: { bin: join(bin, 'vibe') },grok: { bin: join(bin, 'grok') },cursor: { bin: join(bin, 'cursor-agent') },+ qwen: { bin: join(bin, 'qwen') },...agents,},requireApproval: [],@@ -74,7 +75,7 @@ describe('the registry', () => {describe('readiness probes', () => {beforeAll(() => {mkdirSync(bin, { recursive: true });- for (const name of ['claude', 'claude-next', 'codex', 'agy', 'vibe', 'grok', 'cursor-agent']) stub(name);+ for (const name of ['claude', 'claude-next', 'codex', 'agy', 'vibe', 'grok', 'cursor-agent', 'qwen']) stub(name);stub('codex-expired', { prints: 'licence expired', exit: 3 });});@@ -84,6 +85,7 @@ describe('readiness probes', () => {rmSync(join(homedir(), '.grok'), { recursive: true, force: true });vi.stubEnv('XAI_API_KEY', '');vi.stubEnv('GROK_HOME', '');+ vi.stubEnv('QWEN_API_KEY', 'qwen-key');});afterEach(() => {@@ -139,7 +141,7 @@ describe('readiness probes', () => {test('probes are reused for half a minute, even when only the active agent changed', async () => {await agentState(configWith({}), { refresh: true });const again = await agentState(configWith({}, 'antigravity'));- expect([rounds(), again.active]).toEqual([[['agy', 'claude', 'codex', 'cursor-agent', 'grok', 'vibe']], 'antigravity']);+ expect([rounds(), again.active]).toEqual([[['agy', 'claude', 'codex', 'cursor-agent', 'grok', 'qwen', 'vibe']], 'antigravity']);});test('asking for a refresh probes again', async () => {@@ -152,8 +154,8 @@ describe('readiness probes', () => {await agentState(configWith({}), { refresh: true });await agentState(configWith({ claude: { bin: join(bin, 'claude-next') } }));expect(rounds()).toEqual([- ['agy', 'claude', 'codex', 'cursor-agent', 'grok', 'vibe'],- ['agy', 'claude-next', 'codex', 'cursor-agent', 'grok', 'vibe'],+ ['agy', 'claude', 'codex', 'cursor-agent', 'grok', 'qwen', 'vibe'],+ ['agy', 'claude-next', 'codex', 'cursor-agent', 'grok', 'qwen', 'vibe'],]);});diff --git a/src/daemon/agent/runners/index.ts b/src/daemon/agent/runners/index.tsindex 75a7b05..60feafe 100644--- a/src/daemon/agent/runners/index.ts+++ b/src/daemon/agent/runners/index.ts@@ -16,6 +16,7 @@ import { claudeRunner } from './claude';import { codexRunner } from './codex';import { cursorRunner } from './cursor';import { grokRunner } from './grok';+import { qwenRunner } from './qwen';import type { McpServer, Runner } from './types';import { vibeRunner } from './vibe';@@ -26,6 +27,7 @@ export const RUNNERS: Record<AgentKind, Runner> = {vibe: vibeRunner,grok: grokRunner,cursor: cursorRunner,+ qwen: qwenRunner,};const cliPath = join(dirname(fileURLToPath(import.meta.url)), 'cli.js');diff --git a/src/daemon/agent/runners/qwen.test.ts b/src/daemon/agent/runners/qwen.test.tsnew file mode 100644index 0000000..242e0ce--- /dev/null+++ b/src/daemon/agent/runners/qwen.test.ts@@ -0,0 +1,339 @@+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { stateDir } from '../../lockfile';+import { qwenRunner } from './qwen';+import { jsonContext, readThrough, shown, streamContext, transcript, valuesOf, valueOf } from './fixtures/support';++const settings = { bin: 'qwen' };+const stream = (overrides: Parameters<typeof streamContext>[1] = {}) => qwenRunner.stream(streamContext(settings, overrides));+const task = (overrides: Parameters<typeof jsonContext>[1] = {}) => qwenRunner.json(jsonContext(settings, overrides));+const read = (name: string, only?: Parameters<typeof readThrough>[2]) => readThrough(qwenRunner, transcript('qwen', name), only);+/** One line of a transcript by what it is, so an added event never shifts a test onto another line. */+const lineOf = (name: string, type: string, nth = 0) =>+ transcript('qwen', name).filter((raw) => (JSON.parse(raw) as { type?: string }).type === type)[nth];++const SESSION = '9a1d0f22-4c7e-4c1b-9b1e-2f6c5d8a0b31';+const RESUME = '0199b1c2-3d4e-5f60-7182-93a4b5c6d7e8';++// check() reads the environment and ~/.qwen, and the machine running the tests has its own of both.+const home = join(stateDir, 'qwen-home');++beforeEach(() => {+ rmSync(home, { recursive: true, force: true });+ mkdirSync(home, { recursive: true });+ vi.stubEnv('HOME', home);+ vi.stubEnv('QWEN_HOME', '');+ for (const name of ['QWEN_API_KEY', 'OPENAI_API_KEY', 'DASHSCOPE_API_KEY', 'BAILIAN_CODING_PLAN_API_KEY']) {+ vi.stubEnv(name, '');+ }+});++afterEach(() => {+ vi.unstubAllEnvs();+ rmSync(home, { recursive: true, force: true });+});++describe('a streamed run', () => {+ test('a fresh run purges the ambient config, allows one server, and denies the machine', () => {+ expect(shown(stream())).toMatchInlineSnapshot(`+ {+ "args": [+ "-p",+ "what does this page cost",+ "--safe-mode",+ "--output-format",+ "stream-json",+ "--include-partial-messages",+ "--approval-mode",+ "default",+ "--mcp-config",+ "{"mcpServers":{"browsentic":{"command":"/usr/local/bin/node","args":["/usr/local/lib/node_modules/browsentic/dist/cli.js","mcp"],"env":{"BROWSENTIC_AGENT_RUN":"run-1"}}}}",+ "--allowed-mcp-server-names",+ "browsentic",+ "--allowed-tools",+ "mcp__browsentic",+ "--exclude-tools",+ "Bash",+ "exec",+ "Edit",+ "Read",+ "zoom_image",+ "monitor",+ "lsp",+ "save_memory",+ "skill",+ "agent",+ "create_sub_session",+ "workflow",+ "send_message",+ "team_create",+ "team_delete",+ "cron_create",+ "cron_list",+ "cron_delete",+ "loop_wakeup",+ "propose_goal",+ "artifact",+ "record_artifact",+ "record_source",+ "image_gen",+ "read_mcp_resource",+ "web_search",+ "web_fetch",+ "--append-system-prompt",+ "You are Browsentic.",+ "--session-id",+ "<uuid>",+ ],+ "cwd": "<state>/agents/qwen/run",+ "env": {+ "BROWSENTIC_AGENT_RUN": "run-1",+ },+ }+ `);+ });++ test('nothing is written to disk, which is the whole point of this runner', () => {+ expect([stream().files, task().files]).toEqual([undefined, undefined]);+ });++ test('the prompt leads, so no array-typed flag can swallow it', () => {+ expect([stream().args[0], stream().args[1]]).toEqual(['-p', 'what does this page cost']);+ expect([task().args[0], task().args[1]]).toEqual(['-p', 'summarize this']);+ });++ test('a resumed turn names the session it is continuing, and mints none of its own', () => {+ const args = stream({ sessionId: RESUME }).args;+ expect([valueOf(args, '--resume'), args.includes('--session-id')]).toEqual([RESUME, false]);+ });++ test('a fresh turn mints a session id rather than being told one', () => {+ const first = valueOf(stream().args, '--session-id');+ expect(first).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);+ expect(valueOf(stream().args, '--session-id')).not.toBe(first);+ });++ test('research switches the web tools from the deny list to the allow list', () => {+ const plain = stream();+ const research = stream({ research: true });+ expect([+ valuesOf(plain.args, '--exclude-tools').includes('web_search'),+ valuesOf(plain.args, '--allowed-tools').includes('web_search'),+ valuesOf(research.args, '--exclude-tools').includes('web_search'),+ valuesOf(research.args, '--allowed-tools').includes('web_search'),+ ]).toEqual([true, false, false, true]);+ });++ test('the model is passed only when one is pinned', () => {+ expect([valueOf(stream().args, '--model'), valueOf(stream({ settings: { ...settings, model: 'qwen3.7-plus' } }).args, '--model')]).toEqual([+ undefined,+ 'qwen3.7-plus',+ ]);+ });++ test('an effort is dropped, because this CLI has no flag for one', () => {+ expect([qwenRunner.efforts, stream({ settings: { ...settings, effort: 'high' } }).args.includes('--effort')]).toEqual([[], false]);+ });++ test('a one-shot loads no MCP server at all, and reaches no browser', () => {+ const args = task().args;+ expect([valueOf(args, '--mcp-config'), args.includes('--allowed-mcp-server-names')]).toEqual(['{"mcpServers":{}}', false]);+ });++ test('a task that is handed a file may open that one, and nothing else that reads', () => {+ const denied = (reads: boolean) => valuesOf(task({ reads }).args, '--exclude-tools');+ expect([denied(false).includes('Read'), denied(true).includes('Read'), denied(true).includes('grep_search')]).toEqual([true, false, true]);+ expect(valuesOf(task({ reads: true }).args, '--allowed-tools')).toEqual(['read_file']);+ });++ // Sessions are filed under ~/.qwen/projects/<sanitized-cwd>, so a conversation that moved would+ // resume into a transcript Qwen files somewhere else. Vibe, Grok and Cursor all need the opposite.+ test('every conversation runs in the same directory, and no task shares it', () => {+ expect([stream().cwd, stream({ conversation: 'conversation-2', runId: 'run-2' }).cwd]).toEqual([+ qwenRunner.workspace('run'),+ qwenRunner.workspace('run'),+ ]);+ expect(qwenRunner.workspace('run')).not.toBe(qwenRunner.workspace('task'));+ });+});++describe('reading the stream', () => {+ test('a turn reports its session, its text, what it spent, and that it is done', () => {+ expect(read('turn.hand-written.jsonl')).toEqual([+ ['session', SESSION],+ ['text', 'The page '],+ ['text', 'costs $40.'],+ ['usage', { contextTokens: 10118, outputTokens: 18 }],+ ['session', SESSION],+ ['done', 'end_turn'],+ ]);+ });++ test("the model's thinking is not said out loud", () => {+ expect(read('turn.hand-written.jsonl', 'text').map(([, text]) => text).join('')).toBe('The page costs $40.');+ });++ // The assistant line repeats what the deltas already said; only its usage is new.+ test('the closing usage is not counted twice', () => {+ expect(read('turn.hand-written.jsonl', 'usage')).toHaveLength(1);+ });++ test('a run with no assistant usage still reports what the result said', () => {+ const calls = readThrough(qwenRunner, [lineOf('turn.hand-written.jsonl', 'result')], 'usage');+ expect(calls).toEqual([['usage', { contextTokens: 10118, outputTokens: 18 }]]);+ });++ test("a research run's own web search is drawn, and a browser call is left to the daemon", () => {+ expect(read('tools.hand-written.jsonl', 'tool')).toEqual([['tool', 'toolu_web_1', 'web_search']]);+ });++ test("a sub-agent's text does not reach the panel", () => {+ expect(read('tools.hand-written.jsonl', 'text')).toEqual([]);+ });++ test('an unknown event and an unparseable line are both ignored', () => {+ expect(read('tools.hand-written.jsonl').filter(([signal]) => signal === 'fail')).toEqual([]);+ });++ test('an auth failure arrives as a result, not on stderr, and says what to do', () => {+ const [[signal, code, message]] = read('error.hand-written.jsonl', 'fail');+ expect([signal, code]).toEqual(['fail', 'AGENT_FAILED']);+ expect(message).toContain('/auth');+ });+});++// --safe-mode ignores --core-tools, so the built-ins are closed by deny rules and the init line —+// which names every tool that actually registered — is what proves they took.+describe('the init line is read back as proof', () => {+ const failOf = (nth: number) => readThrough(qwenRunner, [lineOf('escaped.hand-written.jsonl', 'system', nth)], 'fail');++ test('a denied built-in that registered anyway stops the run before the model sees it', () => {+ const [[, code, message]] = failOf(0);+ expect([code, message]).toEqual(['AGENT_UNSAFE', expect.stringContaining('run_shell_command')]);+ });++ test("a second MCP server beside Browsentic's own stops the run", () => {+ const [[, code, message]] = failOf(1);+ expect([code, message]).toEqual(['AGENT_UNSAFE', expect.stringContaining('node-repl')]);+ });++ test('an approval mode Browsentic did not ask for stops the run', () => {+ const [[, code, message]] = failOf(2);+ expect([code, message]).toEqual(['AGENT_UNSAFE', expect.stringContaining('yolo')]);+ });++ // The deny list cannot name a tool that does not exist yet, so the families are matched too.+ test('a tool from a dangerous family Browsentic never knew to deny stops the run', () => {+ const [[, code, message]] = failOf(3);+ expect([code, message]).toEqual(['AGENT_UNSAFE', expect.stringContaining('computer_use__screenshot')]);+ });++ // The mode can be switched mid-session, and Qwen re-announces the session when it is.+ test('a later line that reports a switched approval mode stops the run too', () => {+ const [[, code, message]] = failOf(4);+ expect([code, message]).toEqual(['AGENT_UNSAFE', expect.stringContaining('auto')]);+ });++ test('a contained init line lets the run go on, and still reports the session', () => {+ expect(readThrough(qwenRunner, [lineOf('turn.hand-written.jsonl', 'system')])).toEqual([['session', SESSION]]);+ });+});++describe('a one-shot answer', () => {+ const array = (...messages: unknown[]) => JSON.stringify(messages);++ test('the answer is the last result in the array the CLI prints', () => {+ const stdout = array(+ { type: 'system', subtype: 'init', session_id: SESSION },+ { type: 'result', subtype: 'success', is_error: false, result: 'a first answer' },+ { type: 'result', subtype: 'success', is_error: false, result: 'the last answer' },+ );+ expect(qwenRunner.answer(stdout)).toEqual({ text: 'the last answer' });+ });++ test('a failed one-shot reports the CLI’s own sentence', () => {+ const stdout = array({ type: 'result', subtype: 'error_during_execution', is_error: true, error: { message: 'model overloaded' } });+ expect(qwenRunner.answer(stdout)).toEqual({ error: 'model overloaded' });+ });++ test('output that is not an array of messages is no answer at all', () => {+ expect([qwenRunner.answer('not json'), qwenRunner.answer('{"type":"result"}'), qwenRunner.answer('[]')]).toEqual([{}, {}, {}]);+ });+});++describe('what the CLI says when it cannot start', () => {+ test('the -p deprecation notice is not mistaken for a failure', () => {+ expect(qwenRunner.hint?.('[DEPRECATED] --prompt: Use the positional prompt instead.\n')).toBeNull();+ });++ test('no configured provider says which two ways there are to configure one', () => {+ const hint = qwenRunner.hint?.('No auth type is selected. Please configure an auth type');+ expect(hint).toContain('/auth');+ expect(hint).toContain('OPENAI_API_KEY');+ });++ test('a session id the CLI refuses is reported as a Browsentic bug, because Browsentic minted it', () => {+ expect(qwenRunner.hint?.(`Error: Session Id ${SESSION} already exists (active or archived).`)).toContain('bug in Browsentic');+ });++ test('a flag this Qwen does not know asks for an update', () => {+ expect(qwenRunner.hint?.('Unknown argument: safe-mode')).toContain('npm i -g @qwen-code/qwen-code');+ });++ test('anything else is left alone', () => {+ expect(qwenRunner.hint?.('Killed: 9')).toBeNull();+ });+});++describe('readiness', () => {+ const problem = async () => (await qwenRunner.check?.({ bin: 'qwen' })) ?? null;++ test('with no provider anywhere, the fix names both ways to configure one', async () => {+ const found = await problem();+ expect([found?.code, found?.fix]).toEqual(['AGENT_NEEDS_PERMISSION', expect.stringContaining('/auth')]);+ });++ test('a key the run can still see is enough', async () => {+ vi.stubEnv('OPENAI_API_KEY', 'sk-test');+ expect(await problem()).toBeNull();+ });++ // ANTHROPIC_ and GEMINI_ are auth types Qwen accepts, but sealEnv does not hand them to a run,+ // so a popup that called this ready would be promising a login that cannot happen.+ test('a key the run would never be given does not count as configured', async () => {+ vi.stubEnv('ANTHROPIC_API_KEY', 'sk-ant-test');+ expect((await problem())?.code).toBe('AGENT_NEEDS_PERMISSION');+ });++ test('a provider-specific key declared in settings counts too', async () => {+ vi.stubEnv('BAILIAN_CODING_PLAN_API_KEY', 'sk-bailian');+ expect(await problem()).toBeNull();+ });++ test('a provider declared on disk counts, whichever key it names', async () => {+ mkdirSync(join(home, '.qwen'), { recursive: true });+ writeFileSync(join(home, '.qwen', 'settings.json'), JSON.stringify({ modelProviders: { openai: { models: [] } } }));+ expect(await problem()).toBeNull();+ });++ // A popup that wrongly says "needs setup" blocks a working agent; the run's own hint catches the+ // opposite case.+ test('a settings file that cannot be read is assumed to configure one', async () => {+ mkdirSync(join(home, '.qwen', 'settings.json'), { recursive: true });+ expect(await problem()).toBeNull();+ });++ test('Browsentic cannot obtain a key, so it does not offer to', () => {+ expect(qwenRunner.grant).toBeUndefined();+ });+});++test('the skill picker looks where Qwen keeps the user’s own skills', () => {+ expect(qwenRunner.skillDirs?.()).toEqual([join(home, '.qwen', 'skills'), join(home, '.agents', 'skills')]);+});++test('a QWEN_HOME of the user’s own is honoured', () => {+ vi.stubEnv('QWEN_HOME', '/elsewhere/qwen');+ expect(qwenRunner.skillDirs?.()?.[0]).toBe(join('/elsewhere/qwen', 'skills'));+});diff --git a/src/daemon/agent/runners/qwen.ts b/src/daemon/agent/runners/qwen.tsnew file mode 100644index 0000000..649b70b--- /dev/null+++ b/src/daemon/agent/runners/qwen.ts@@ -0,0 +1,387 @@+import { randomUUID } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import type { AgentProblem } from '@/lib/agents/catalog';+import { stateDir } from '../../lockfile';+import { log } from '../../log';+import { MCP_SERVER_NAME } from './claude';+import { parseJsonLine } from './util';+import type { JsonContext, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';++/**+ * Qwen takes every setting a run needs as a flag, so this runner writes nothing to disk.+ *+ * `--safe-mode` is what makes that safe: it drops the user's hooks, extensions, bundled skills,+ * settings-sourced MCP servers, `.mcp.json` and permission rules, while keeping `--mcp-config` —+ * an explicit per-invocation argument rather than ambient state. It is Qwen's `--strict-mcp-config`+ * and then some. Its one cost is that it also ignores `--core-tools`, the fail-closed allowlist+ * over Qwen's twenty-one core tools, so the built-ins are closed with deny rules instead and the+ * `init` line is read back to prove they took.+ */++/** The shell and the disk. `Read` and `Edit` are Qwen's own meta-rules, each covering several tools. */+const MACHINE = ['Bash', 'exec', 'Edit', 'Read', 'zoom_image', 'monitor', 'lsp', 'save_memory'];++/**+ * Not the shell, but a way around the gate. `skill` is the one that matters: Qwen ships bundled+ * browser-use and computer-use skills, and the first drives a second browser Browsentic never sees+ * while the second runs `qwen mcp add --scope user` and `npm install` by itself on first use.+ * Browsentic's own skill picker reads SKILL.md off disk, so denying the tool costs it nothing.+ */+const ESCAPES = [+ 'skill',+ 'agent',+ 'create_sub_session',+ 'workflow',+ 'send_message',+ 'team_create',+ 'team_delete',+ 'cron_create',+ 'cron_list',+ 'cron_delete',+ 'loop_wakeup',+ 'propose_goal',+ 'artifact',+ 'record_artifact',+ 'record_source',+ 'image_gen',+ 'read_mcp_resource',+];++const WEB_TOOLS = ['web_search', 'web_fetch'];++const READ_TOOL = 'read_file';++/** The rest of what `Read` covers, for a one-shot that may open its own scratch file and nothing else. */+const OTHER_READS = ['grep_search', 'glob', 'list_directory'];++/** Qwen's default is `auto`, which spends an LLM classifier call per tool call; this one just refuses. */+const APPROVAL = 'default';++/**+ * Families that hand a run the machine, whether or not this version of Browsentic knew to name+ * them. A deny list cannot be fail-closed the way `--core-tools` would have been, so the `init`+ * line — which names every tool that actually registered — is read back against this.+ */+const DANGEROUS =+ /^(run_shell_command|exec|edit|write_file|notebook_edit|read_file|grep_search|glob|list_directory|agent|skill|monitor|save_memory|lsp|zoom_image|image_gen|workflow|send_message|create_sub_session|propose_goal|cron_|team_|computer_use__|omni_)/;++const qwenHome = () => process.env.QWEN_HOME || join(homedir(), '.qwen');++const INSTALL = 'npm i -g @qwen-code/qwen-code';++/** The env keys that select an auth type on their own, narrowed to what a sealed run can still see. */+const AUTH_KEYS = ['QWEN_API_KEY', 'OPENAI_API_KEY', 'DASHSCOPE_API_KEY'];++const AUTH_PREFIX = /^(QWEN_|DASHSCOPE_|BAILIAN_|OPENAI_).*(API_KEY|TOKEN)$/;++interface Usage {+ input_tokens?: number;+ cache_creation_input_tokens?: number;+ cache_read_input_tokens?: number;+ output_tokens?: number;+}++interface Block {+ type?: string;+ id?: string;+ name?: string;+}++type Line =+ | {+ type: 'system';+ subtype?: string;+ session_id?: string;+ tools?: string[];+ mcp_servers?: { name?: string; status?: string }[];+ permission_mode?: string;+ }+ | {+ type: 'assistant';+ session_id?: string;+ parent_tool_use_id?: string | null;+ message?: { usage?: Usage };+ }+ | {+ type: 'stream_event';+ parent_tool_use_id?: string | null;+ event?: { type?: string; delta?: { type?: string; text?: string }; content_block?: Block };+ }+ | {+ type: 'result';+ subtype?: string;+ session_id?: string;+ is_error?: boolean;+ result?: string;+ usage?: Usage;+ error?: { message?: string };+ };++export const qwenRunner: Runner = {+ kind: 'qwen',+ versionArgs: ['--version'],+ // No reasoning-effort flag; the model id is the only lever.+ efforts: [],++ // Sessions are filed under ~/.qwen/projects/<sanitized-cwd>, so a resume only finds the+ // conversation it began in when this stays put.+ workspace: (mode: RunMode) => join(stateDir, 'agents', 'qwen', mode),++ skillDirs: () => [join(qwenHome(), 'skills'), join(homedir(), '.agents', 'skills')],++ stream(context: StreamContext): Plan {+ const { settings, research } = context;+ return {+ cwd: this.workspace('run'),+ env: { BROWSENTIC_AGENT_RUN: context.runId },+ args: [+ // First, and a string-typed flag: an array-typed flag upstream would swallow a positional+ // prompt, and the bare positional Qwen now prefers is exactly that.+ '-p',+ context.instruction,+ '--safe-mode',+ '--output-format',+ 'stream-json',+ '--include-partial-messages',+ '--approval-mode',+ APPROVAL,+ '--mcp-config',+ JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: context.mcp } }),+ // Only this server may load, whatever else the user gave Qwen itself.+ '--allowed-mcp-server-names',+ MCP_SERVER_NAME,+ // A headless turn refuses anything it would have prompted for, so what a run may do has+ // to be auto-approved by name. One entry covers every tool the server offers.+ '--allowed-tools',+ `mcp__${MCP_SERVER_NAME}`,+ ...(research ? WEB_TOOLS : []),+ '--exclude-tools',+ ...MACHINE,+ ...ESCAPES,+ ...(research ? [] : WEB_TOOLS),+ '--append-system-prompt',+ context.systemPrompt,+ ...(context.sessionId ? ['--resume', context.sessionId] : ['--session-id', randomUUID()]),+ ...(settings.model ? ['--model', settings.model] : []),+ ],+ };+ },++ reader(): StreamReader {+ // Qwen has no message_delta, so a message's usage arrives once, on the assistant line that+ // closes it. The terminal result repeats the run's total, which is only worth reporting when+ // no assistant line carried one.+ let prompt = 0;+ let generated = 0;+ let counted = false;++ const promptOf = (usage: Usage) =>+ (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);++ const report = (usage: Usage, sink: StreamSink) => {+ counted = true;+ prompt = promptOf(usage);+ generated += usage.output_tokens ?? 0;+ sink.usage({ contextTokens: prompt + (usage.output_tokens ?? 0), outputTokens: generated });+ };++ return (line, sink) => {+ const message = parseJsonLine<Line>(line);+ if (!message) return;++ switch (message.type) {+ case 'system': {+ if (message.session_id) sink.session(message.session_id);+ // Qwen re-announces the session whenever the tool set is refreshed, so this is read+ // back on every such line, not only the first.+ if (!message.tools && !message.mcp_servers && !message.permission_mode) return;+ const unsafe = escaped(message);+ if (unsafe) return sink.fail('AGENT_UNSAFE', unsafe);+ log(`qwen session ${message.session_id} up, ${message.tools?.length ?? 0} tools registered`);+ return;+ }++ case 'stream_event': {+ if (message.parent_tool_use_id) return;+ const event = message.event;+ if (event?.type === 'content_block_delta' && event.delta?.type === 'text_delta' && event.delta.text) {+ return sink.text(event.delta.text);+ }+ if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {+ const name = event.content_block.name ?? 'tool';+ // The daemon already puts its own MCP calls on the timeline; repeating them double-draws.+ if (WEB_TOOLS.includes(name)) sink.tool(event.content_block.id ?? randomUUID(), name);+ }+ return;+ }++ case 'assistant':+ if (message.parent_tool_use_id) return;+ if (message.message?.usage) report(message.message.usage, sink);+ return;++ case 'result':+ if (message.session_id) sink.session(message.session_id);+ if (!counted && message.usage) report(message.usage, sink);+ if (message.is_error) {+ return sink.fail(+ 'AGENT_FAILED',+ explain(message.error?.message) ?? (message.result?.trim() || 'Qwen Code reported an error'),+ );+ }+ return sink.done(message.subtype === 'success' ? 'end_turn' : message.subtype || 'end_turn');+ }+ };+ },++ json(context: JsonContext): Plan {+ const { settings, reads } = context;+ const denied = reads ? [...MACHINE.filter((tool) => tool !== 'Read'), ...OTHER_READS] : MACHINE;+ return {+ cwd: this.workspace('task'),+ args: [+ '-p',+ context.prompt,+ '--safe-mode',+ '--output-format',+ 'json',+ '--approval-mode',+ APPROVAL,+ // Safe mode drops the user's own servers, so an empty set here means a one-shot loads none+ // at all and cannot reach the browser however the daemon is configured.+ '--mcp-config',+ '{"mcpServers":{}}',+ ...(reads ? ['--allowed-tools', READ_TOOL] : []),+ '--exclude-tools',+ ...denied,+ ...ESCAPES,+ ...WEB_TOOLS,+ ...(settings.model ? ['--model', settings.model] : []),+ ],+ };+ },++ answer(stdout: string) {+ const answer = lastResult(stdout);+ if (!answer) return {};+ if (answer.is_error) {+ return { error: explain(answer.error?.message) ?? (answer.result?.trim() || 'Qwen Code reported an error') };+ }+ return { text: typeof answer.result === 'string' ? answer.result : undefined };+ },++ hint(stderrTail: string) {+ // `-p` is soft-deprecated in favour of a bare positional, which array-typed flags would swallow.+ const tail = stderrTail.replace(/^.*Use the positional prompt instead.*$/gm, '').trim();+ if (/No auth type is selected|API key not found|not authenticated/i.test(tail)) {+ return (+ 'Qwen Code is installed but has no model provider configured. Run "qwen" and use /auth, ' ++ 'or export OPENAI_API_KEY with OPENAI_BASE_URL, then try again.'+ );+ }+ if (/Session Id .* already exists/i.test(tail)) {+ return `Qwen Code refused the session id Browsentic minted. This is a bug in Browsentic — please report it. (${tail})`;+ }+ if (/unknown argument|unknown option|invalid values|not a valid choice/i.test(tail)) {+ return `Your Qwen Code does not understand the flags Browsentic uses. Update it (${INSTALL}), then try again. (${tail})`;+ }+ return null;+ },++ async check(): Promise<AgentProblem | null> {+ const named = Object.entries(process.env).some(([name, value]) => value && AUTH_PREFIX.test(name));+ if (named || AUTH_KEYS.some((name) => process.env[name])) return null;+ if (configured()) return null;+ return {+ code: 'AGENT_NEEDS_PERMISSION',+ message: 'Qwen Code is installed but has no model provider configured.',+ // Qwen OAuth's free tier ended on 2026-04-15 and new requests are rejected, so "just log in"+ // is no longer true for this CLI.+ fix: 'qwen → /auth (or export OPENAI_API_KEY and OPENAI_BASE_URL)',+ };+ },+};++/**+ * What the `init` line has to say for the run to be contained: nothing that reaches the machine+ * still registered, no MCP server but ours, and the approval mode we asked for. Returns the+ * sentence to fail with, or undefined when the run may go on.+ */+function escaped(init: { tools?: string[]; mcp_servers?: { name?: string }[]; permission_mode?: string }): string | undefined {+ const denied = new Set([...MACHINE, ...ESCAPES]);+ const live = (init.tools ?? []).filter((tool) => denied.has(tool) || DANGEROUS.test(tool));+ if (live.length) {+ return (+ `Qwen Code registered ${live.join(', ')} for this run, which Browsentic denied, so the run was stopped before the model saw them. ` ++ 'Update Qwen Code and Browsentic; if it persists, please report it.'+ );+ }++ const others = (init.mcp_servers ?? []).map((server) => server.name).filter((name) => name && name !== MCP_SERVER_NAME);+ if (others.length) {+ return (+ `Qwen Code loaded the MCP server${others.length > 1 ? 's' : ''} ${others.join(', ')} beside Browsentic's own, which would reach the browser outside this run's gate, so the run was stopped. ` ++ 'Update Qwen Code and Browsentic; if it persists, please report it.'+ );+ }++ if (init.permission_mode && init.permission_mode !== APPROVAL) {+ return (+ `Qwen Code started this run in "${init.permission_mode}" rather than "${APPROVAL}", which approves what Browsentic asked it to refuse, so the run was stopped. ` ++ 'Update Qwen Code and Browsentic; if it persists, please report it.'+ );+ }++ return undefined;+}++/** Qwen's own sentence, with what to do about it where Browsentic knows. */+function explain(message: string | undefined): string | undefined {+ if (!message) return undefined;+ if (/No auth type is selected|API key not found/i.test(message)) {+ return (+ 'Qwen Code has no model provider configured. Run "qwen" and use /auth, or export OPENAI_API_KEY ' ++ `with OPENAI_BASE_URL, then try again. (${oneLine(message)})`+ );+ }+ if (/qwen-oauth|Qwen OAuth/i.test(message)) {+ return `Qwen OAuth's free tier was discontinued, so its requests are rejected. Configure another provider with /auth. (${oneLine(message)})`;+ }+ if (/rate limit|429|quota/i.test(message)) {+ return `The provider behind Qwen Code is rate-limiting this account. Wait and try again. (${oneLine(message)})`;+ }+ if (/unknown model|model not found/i.test(message)) {+ return `${oneLine(message)} Pick another model for Qwen Code in the Browsentic popup, then try again.`;+ }+ return oneLine(message);+}++const oneLine = (message: string) => message.replace(/\s+/g, ' ').trim().slice(0, 240);++/** A provider declared on disk, whose key Qwen reads itself. Unreadable counts as configured. */+function configured(): boolean {+ let parsed: { modelProviders?: unknown; security?: { auth?: unknown }; env?: unknown };+ try {+ parsed = JSON.parse(readFileSync(join(qwenHome(), 'settings.json'), 'utf8')) as typeof parsed;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== 'ENOENT';+ }+ return Boolean(parsed.modelProviders || parsed.security?.auth || parsed.env);+}++/** `--output-format json` prints an array of every message, so the answer is its last result. */+function lastResult(stdout: string): Extract<Line, { type: 'result' }> | null {+ let messages: unknown;+ try {+ messages = JSON.parse(stdout);+ } catch {+ return null;+ }+ if (!Array.isArray(messages)) return null;+ for (const message of [...messages].reverse()) {+ if ((message as Line | null)?.type === 'result') return message as Extract<Line, { type: 'result' }>;+ }+ return null;+}diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 002dd74..a3fe967 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -36,7 +36,7 @@ const USAGE = `browsentic ${pkg.version} — hand your real browser to the agentbrowsentic revoke [id] unpair one browser by the id "sessions" prints, or all of thembrowsentic agent show which agent runs the side panel, and which are installed- browsentic agent <name> switch to claude, codex, antigravity, vibe, grok or cursor+ browsentic agent <name> switch to claude, codex, antigravity, vibe, grok, cursor or qwenbrowsentic agent fix <name> let Browsentic fix what that agent still needsbrowsentic agent model <name> [model] pin that agent's model, or omit it for the CLI's defaultdiff --git a/src/daemon/guardrails/spawn.test.ts b/src/daemon/guardrails/spawn.test.tsindex 17ad9af..83eec0d 100644--- a/src/daemon/guardrails/spawn.test.ts+++ b/src/daemon/guardrails/spawn.test.ts@@ -120,6 +120,8 @@ describe('spawn containment', () => {const grokTask = planOf('grok', 'task');const cursorRun = planOf('cursor', 'run');const cursorTask = planOf('cursor', 'task');+ const qwenRun = planOf('qwen', 'run');+ const qwenTask = planOf('qwen', 'task');const rewriting = (plan: Plan, path: string, edit: (content: string) => string): Plan => ({...plan,files: plan.files?.map((file) => (file.path === path ? { ...file, content: edit(file.content) } : file)),@@ -315,6 +317,59 @@ describe('spawn containment', () => {expect(vetPlan('cursor', 'task', opened, stateDir)).toHaveLength(1);});+ // Without --safe-mode the user's own MCP servers, hooks, extensions and permission rules load+ // beside the ones Browsentic passed, and their own browsentic entry reaches the browser ungated.+ test('dropping --safe-mode is caught on both qwen modes', () => {+ expect(vetPlan('qwen', 'run', without(qwenRun, '--safe-mode'), stateDir)).toHaveLength(1);+ expect(vetPlan('qwen', 'task', without(qwenTask, '--safe-mode'), stateDir)).toHaveLength(1);+ });++ test('--bare, which reads like --safe-mode but un-denies the shell, is caught', () => {+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--bare'), stateDir)).toHaveLength(1);+ });++ test('--yolo and its -y alias are caught', () => {+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--yolo'), stateDir)).toHaveLength(1);+ expect(vetPlan('qwen', 'run', plus(qwenRun, '-y'), stateDir)).toHaveLength(1);+ });++ test('skipping TLS verification is caught', () => {+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--insecure'), stateDir)).toHaveLength(1);+ });++ // The classifier mode approves what the deny list exists to refuse, and the inline spelling+ // would slip past a check that only reads the value after the flag.+ test('a later approval mode, in either spelling, is caught', () => {+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--approval-mode', 'auto'), stateDir)).toHaveLength(1);+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--approval-mode=auto'), stateDir)).toHaveLength(1);+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--approval-mode=yolo'), stateDir)).toHaveLength(1);+ });++ test('a second MCP server named for qwen is caught', () => {+ expect(vetPlan('qwen', 'run', plus(qwenRun, '--allowed-mcp-server-names', 'node-repl'), stateDir)).toHaveLength(1);+ });++ // Qwen ships bundled browser-use and computer-use skills, so `skill` is a second browser and+ // an unasked npm install, not a convenience.+ test('un-denying the shell, the sub-agent or the skill tool is caught', () => {+ expect(vetPlan('qwen', 'run', without(qwenRun, 'Bash'), stateDir)).toHaveLength(1);+ expect(vetPlan('qwen', 'run', without(qwenRun, 'agent'), stateDir)).toHaveLength(1);+ expect(vetPlan('qwen', 'run', without(qwenRun, 'skill'), stateDir)).toHaveLength(1);+ });++ test('a qwen run that could read the disk is caught', () => {+ expect(vetPlan('qwen', 'run', without(qwenRun, 'Read'), stateDir)).toHaveLength(1);+ });++ test('a qwen task that could reach an MCP server is caught', () => {+ expect(vetPlan('qwen', 'task', swapped(qwenTask, '{"mcpServers":{}}', '{"mcpServers":{"browsentic":{}}}'), stateDir)).toHaveLength(1);+ });++ test('a qwen run with web tools, or a task that reads a file, is still contained', () => {+ expect(vetPlan('qwen', 'run', planOf('qwen', 'run', { research: true }), stateDir)).toEqual([]);+ expect(vetPlan('qwen', 'task', planOf('qwen', 'task', { reads: true }), stateDir)).toEqual([]);+ });+test('running outside the state dir is caught', () => {expect(vetPlan('antigravity', 'run', { ...agyRun, cwd: '/tmp/anywhere' }, stateDir)).toHaveLength(1);});diff --git a/src/daemon/guardrails/spawn.ts b/src/daemon/guardrails/spawn.tsindex 4bfead9..b9b7c74 100644--- a/src/daemon/guardrails/spawn.ts+++ b/src/daemon/guardrails/spawn.ts@@ -108,6 +108,7 @@ interface Containment {const FORBIDDEN: readonly RegExp[] = [/^--dangerously/i,/^--yolo$/i,+ /^-y$/,/^--force$/i,/^-f$/,/^--auto-approve$/i,@@ -125,6 +126,13 @@ const FORBIDDEN: readonly RegExp[] = [/** Local tools no run may ever have, whatever else it is allowed. */const NEVER = ['Bash', 'Edit', 'Write', 'NotebookEdit', 'Glob', 'Grep', 'Task'];+/**+ * The same, as Qwen spells it. `Edit` is its meta-rule for edit, write_file and notebook_edit;+ * `agent` is its sub-agent tool and `skill` reaches its bundled browser-use and computer-use+ * skills, which drive a second browser and install packages outside this run's gate.+ */+const NEVER_QWEN = ['Bash', 'exec', 'Edit', 'agent', 'skill', 'monitor'];+/*** Grok takes these only from its environment. It loads Claude Code's and Cursor's MCP servers* by default — the user's own `browsentic` entry among them, which reaches the browser without@@ -271,6 +279,48 @@ export const CONTAINMENT: Record<AgentKind, Containment> = {},},},++ qwen: {+ localTools: 'allowlist',+ // The documented way to point Qwen at a provider is OPENAI_API_KEY with OPENAI_BASE_URL, so+ // sealing that prefix would seal most installs out of their own model; Codex already keeps it.+ // ANTHROPIC_ and GEMINI_ are auth types Qwen accepts and this does not hand it.+ keepsEnv: ['QWEN_', 'DASHSCOPE_', 'BAILIAN_', 'OPENAI_'],+ // `--bare` reads like a quieter --safe-mode and is the one flag that switches off the+ // non-interactive refusal of shell, edit and write; `--insecure` drops TLS verification.+ forbidden: [/^--bare$/i, /^--insecure$/i, /^--approval-mode=(?!default$)/i],+ note:+ 'per-run tool allowlist over an explicit deny list, and only one MCP server may load; ' ++ 'the built-ins are closed by deny rules rather than by --core-tools, whose fail-closed ' ++ 'allowlist --safe-mode silently ignores, so a built-in a future Qwen release adds would ' ++ 'register — the init line names every tool that did, and the reader stops the run on one ' ++ 'Browsentic did not ask for',+ run: {+ // Without it the user's own MCP servers, hooks, extensions and permission rules all load.+ required: ['--safe-mode', '--include-partial-messages'],+ pairs: [+ ['--approval-mode', 'default'],+ ['--output-format', 'stream-json'],+ ['--allowed-mcp-server-names', 'browsentic'],+ ],+ // A browser run reads pages, never the disk. `Read` and `Edit` are Qwen's own meta-rules.+ denies: { flag: '--exclude-tools', tools: [...NEVER_QWEN, 'Read'] },+ files: [],+ },+ task: {+ required: ['--safe-mode'],+ pairs: [+ ['--approval-mode', 'default'],+ ['--output-format', 'json'],+ // Safe mode drops the user's own servers, so an empty set is the whole MCP surface:+ // a one-shot cannot reach the browser at all. `Read` is left out of the deny list —+ // some tasks are handed a file in the scratch workspace.+ ['--mcp-config', '{"mcpServers":{}}'],+ ],+ denies: { flag: '--exclude-tools', tools: NEVER_QWEN },+ files: [],+ },+ },};/**@@ -355,6 +405,7 @@ const SECRET_PREFIX: readonly string[] = ['STRIPE_', 'SLACK_', 'TWILIO_', 'SENDGRID_', 'SENTRY_', 'DATADOG_', 'PAGERDUTY_','DATABASE_', 'POSTGRES_', 'PGPASS', 'MYSQL_', 'REDIS_', 'MONGO_', 'SUPABASE_','OPENAI_', 'ANTHROPIC_', 'GEMINI_', 'CLAUDE_', 'CODEX_', 'ANTIGRAVITY_', 'MISTRAL_', 'XAI_', 'GROK_', 'CURSOR_', 'HF_', 'HUGGINGFACE_',+ 'QWEN_', 'DASHSCOPE_', 'BAILIAN_','VERCEL_', 'NETLIFY_', 'CLOUDFLARE_', 'FLY_', 'HEROKU_', 'RAILWAY_',];diff --git a/src/extension/components/agent-marks.tsx b/src/extension/components/agent-marks.tsxindex e409577..de55aa0 100644--- a/src/extension/components/agent-marks.tsx+++ b/src/extension/components/agent-marks.tsx@@ -28,6 +28,10 @@ const MARKS: Record<AgentKind, { viewBox: string; path: string }> = {viewBox: '0 0 24 24',path: 'M11.925 24l10.425-6-10.425-6L1.5 18l10.425 6zM22.35 18V6L11.925 0v12l10.425 6zM11.925 12V0L1.5 6v12l10.425-6z',},+ qwen: {+ viewBox: '0 0 24 24',+ path: 'M23.919 14.545 20.817 9.17l1.47-2.544a.56.56 0 0 0 0-.566l-1.633-2.83a.57.57 0 0 0-.49-.283h-6.207L12.487.402a.57.57 0 0 0-.49-.284H8.732a.56.56 0 0 0-.49.284L5.139 5.775h-2.94a.56.56 0 0 0-.49.284L.077 8.887a.56.56 0 0 0 0 .567L3.18 14.83l-1.47 2.545a.56.56 0 0 0 0 .566l1.634 2.83a.57.57 0 0 0 .49.283h6.205l1.47 2.545a.57.57 0 0 0 .49.284h3.266a.57.57 0 0 0 .49-.284l3.104-5.375h2.94a.57.57 0 0 0 .49-.283l1.634-2.828a.55.55 0 0 0-.004-.568M8.733.686l1.634 2.828-1.634 2.828H21.8L20.164 9.17H7.425L5.63 6.06Zm1.306 19.801-6.205-.002 1.634-2.83h3.265L2.201 6.344h3.267q3.182 5.517 6.367 11.032zm10.124-5.66L18.53 12l-6.532 11.315-1.634-2.83c2.129-3.673 4.25-7.351 6.373-11.028h3.592l3.102 5.374z',+ },};/** The vendor's mark in the current text colour, so it follows the row's state and the theme. */diff --git a/src/lib/agents/catalog.ts b/src/lib/agents/catalog.tsindex 6da9176..88ef6cc 100644--- a/src/lib/agents/catalog.ts+++ b/src/lib/agents/catalog.ts@@ -1,4 +1,4 @@-export const AGENT_KINDS = ['claude', 'codex', 'antigravity', 'vibe', 'grok', 'cursor'] as const;+export const AGENT_KINDS = ['claude', 'codex', 'antigravity', 'vibe', 'grok', 'cursor', 'qwen'] as const;export type AgentKind = (typeof AGENT_KINDS)[number];@@ -76,6 +76,18 @@ export const AGENTS: Record<AgentKind, AgentDescriptor> = {models: ['composer-2.5', 'claude-opus-4-8', 'gpt-5', 'sonnet-4-thinking'],beta: true,},+ qwen: {+ kind: 'qwen',+ label: 'Qwen Code',+ vendor: 'Alibaba',+ bin: 'qwen',+ install: 'npm i -g @qwen-code/qwen-code',+ docs: 'https://qwenlm.github.io/qwen-code-docs/en/',+ // Which of these an account can reach depends on the provider it is pointed at, and no+ // subcommand lists them, so these are curated.+ models: ['qwen3-coder-plus', 'qwen3.7-plus', 'qwen3.6-plus', 'qwen3-max-2026-01-23'],+ beta: true,+ },};export const AGENT_LIST: AgentDescriptor[] = AGENT_KINDS.map((kind) => AGENTS[kind]);