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): DeepSeek Harness (beta) runs the side panel over ACP, in a dsh home of Browsentic's own with every tool row switched off but the browser's, and only a panel that knows it is told of it
Shahriare4f699202b9e
diff --git a/src/daemon/agent/config.test.ts b/src/daemon/agent/config.test.tsindex 4e19550..d4bd30e 100644--- a/src/daemon/agent/config.test.ts+++ b/src/daemon/agent/config.test.ts@@ -39,6 +39,7 @@ const DEFAULTS: AgentConfig = {cursor: { bin: 'cursor-agent' },qwen: { bin: 'qwen' },opencode: { bin: 'opencode' },+ deepseek: { bin: 'dsh' },},requireApproval: ['page.submitForm'],};diff --git a/src/daemon/agent/runners/deepseek.ts b/src/daemon/agent/runners/deepseek.tsnew file mode 100644index 0000000..65dd9e8--- /dev/null+++ b/src/daemon/agent/runners/deepseek.ts@@ -0,0 +1,397 @@+import { mkdirSync, readdirSync, 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 { acpConversation, type ConfigOption, type ModelEntry, type Update } from './acp';+import { MCP_SERVER_NAME } from './claude';+import { conversationDir, effortOf, parseJsonLine, sweepRunDirs } from './util';+import type { JsonContext, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';++/**+ * DeepSeek Harness is a tree of plugins, each a row of a profile, and containment is a patch over+ * that tree: every row that gives the model a tool of its own is switched off, so the shell, the+ * disk, the web, sub-agents and scripted workflows are never offered at all. The patch is written+ * as JSON, which a YAML loader reads as it is and which can carry no `!!js` expression.+ *+ * Runs keep a dsh home of their own, so nothing of the user's composes into one — their home patch,+ * their profiles' plugins, their AGENTS.md and skills — and borrow only the sign-in, by pointing+ * the credentials row at the file `dsh web` keeps it in.+ *+ * A streamed turn is held over ACP (`--profile acp`), which takes the browser's MCP server with the+ * session. One-shots, and a turn ACP would not hold, run once through `--profile headless --json`.+ */++/** Rows that hand the model a tool, or run work of its own beside the turn. A row a profile lacks fails the whole patch. */+const SWITCHED_OFF = [+ 'tool-bash', 'tool-pwsh', 'tool-jobs', 'tool-fs', 'tool-fs-search',+ 'tool-skill', 'skill', 'skill-filesystem',+ 'tool-subagent', 'tool-subagent-fork', 'tool-subagent-control', 'tool-subagent-list-agents',+ 'tool-workflow', 'workflow-ptc', 'ptc-runtime',+ 'tool-goal', 'goal', 'goal-round-driver', 'command-goal', 'tool-working-directory',+ 'plan-mode', 'mcp-resources', 'user-questions', 'commands', 'command-feedback', 'command-compact',+ 'otel', 'session-telemetry-otel',+];++/** The web tools, offered on a research run alone. */+const WEB = 'tool-web';+const WEB_TOOLS = ['web_fetch', 'web_search'];++/** A run's to-do list stays inside the turn. */+const TODO = 'tool-todo';++const PATCH = 'browsentic.patch.yml';+const TASK_PATCH = 'task.patch.yml';+const INSTRUCTIONS = 'AGENTS.md';++/** dsh calls itself a coding agent unless told otherwise. `{{model}}` is its own placeholder. */+const PERSONA = "You are Browsentic's browser agent, powered by the {{model}} model.";++/** Claude Code's 25,000-token MCP ceiling. dsh cuts a result at 12,500 into a file the run has no tool to read. */+const RESULT_TOKENS = 25_000;++/** Browsentic's prompt runs well past dsh's 64 KiB budget for workspace instructions. */+const INSTRUCTION_BYTES = 256 * 1024;++/** An MCP call dsh makes is abandoned at the SDK's 60 s, and the server is told it was cancelled. Measured on 0.2.1-rc.2. */+const LIMITS = { callMs: 60_000 };++const INSTALL = 'npm i -g @deepseek-ai/dsh';+const SIGN_IN = 'dsh web';+const PROVIDERS = { account: 'deepseek-account', key: 'deepseek-official' } as const;+const DEFAULT_MODEL = 'deepseek-flash';++/** Headless switches the sign-in off altogether, so every patch switches these rows back on. */+const SIGN_IN_ROWS = ['authorization', 'deepseek-account'];++/** A one-shot the file analyst runs may read a file, and change nothing. */+const READ_ONLY = { read: true, readImage: false, write: false, edit: false };++const root = () => join(stateDir, 'agents', 'deepseek');+const runHome = () => join(root(), 'home');+const taskHome = () => join(root(), 'task-home');+/** Kept empty: dsh reads AGENTS.md and skills from it. */+const agentsHome = () => join(root(), 'agents-home');++/** Where the user's own dsh keeps the sign-in `dsh web` wrote. */+const userHome = () => process.env.DSH_HOME || join(homedir(), '.dsh');+const credentials = () => join(userHome(), '.credentials.yaml');++/** Bins whose dsh would not hold a conversation, whose turns run headless until the daemon restarts. */+const noConversation = new Set<string>();++type Row = { id: string; disabled?: boolean; config?: Record<string, unknown> } | { insert: { id: string; name: string; config: Record<string, unknown> }[] };++interface Route {+ provider: string;+ model: string;+ effort?: string;+}++interface HeadlessEvent {+ type?: string;+ sessionId?: string;+ phase?: string;+ text?: string;+ message?: string;+ callId?: string;+ tool?: string;+ status?: string;+ result?: unknown;+ usage?: { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number };+ reason?: { kind?: string; error?: { message?: string; code?: string } };+}++export const deepseekRunner: Runner = {+ kind: 'deepseek',+ versionArgs: ['--version'],+ efforts: ['off', 'low', 'high', 'max'],+ delivery: () => 'on-demand',+ limits: LIMITS,++ workspace: (mode: RunMode) => join(root(), mode),++ skillDirs: () => [join(userHome(), 'skills'), join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')],++ /** Headless, for a dsh that would not hold the turn over ACP: one turn, the browser's server mounted by the patch. */+ stream(context: StreamContext): Plan {+ const turn = turnOf(context);+ // Headless names its sessions `session-…` and ACP does not, so a session ACP began is not resumed here.+ const resume = context.sessionId?.startsWith('session-') ? ['--session-id', context.sessionId] : [];+ const chosen = { provider: provider(), model: context.settings.model ?? DEFAULT_MODEL, effort: effortOf(context.settings, this.efforts) };+ return {+ ...turn,+ files: [+ { path: PATCH, content: patch([...runRows(context, chosen), insertServer(context.mcp)]) },+ { path: INSTRUCTIONS, content: context.systemPrompt },+ ],+ args: ['--profile', 'headless', '--patch', join(turn.cwd, PATCH), ...resume, '--json', '-'],+ input: context.instruction,+ };+ },++ converse(context: StreamContext) {+ const { bin } = context.settings;+ if (noConversation.has(bin)) return null;+ const turn = turnOf(context);+ // A session opens on a model the route surely has; the turn then asks for the one the side panel pinned, by name.+ const opening = { provider: provider(), model: DEFAULT_MODEL };+ const plan: Plan = {+ ...turn,+ files: [+ { path: PATCH, content: patch([...runRows(context, opening), { id: 'acp', config: { provider: opening.provider, model: opening.model } }]) },+ { path: INSTRUCTIONS, content: context.systemPrompt },+ ],+ args: ['--profile', 'acp', '--patch', join(turn.cwd, PATCH)],+ };+ return acpConversation(context, {+ plan,+ label: 'DeepSeek Harness',+ // A resumed session reconnects only the servers it is handed, and the run id lives in theirs.+ mcpServers: [acpServer(context.mcp)],+ declined: () => noConversation.add(bin),+ explain,+ stoppedFor,+ effortOption: 'reasoning_effort',+ models: modelsOffered,+ own: (name) => name.startsWith(`mcp__${MCP_SERVER_NAME}__`),+ drawn: WEB_TOOLS,+ quiet: ['todo_write'],+ ran,+ // Its servers have listed their tools before `session/new` answers.+ settleMs: 0,+ paragraphs: true,+ });+ },++ reader(): StreamReader {+ let spoke = false;+ let generated = 0;+ const calls = new Map<string, string>();++ return (line, sink) => {+ const event = parseJsonLine<HeadlessEvent>(line);+ if (!event) return;+ switch (event.type) {+ case 'session':+ if (event.sessionId) sink.session(event.sessionId);+ return;+ case 'text':+ if (!event.text) return;+ sink.text(spoke ? `\n\n${event.text}` : event.text);+ spoke = true;+ return;+ case 'tool_call':+ if (!event.callId || !event.tool) return;+ calls.set(event.callId, event.tool);+ if (WEB_TOOLS.includes(event.tool)) sink.tool(event.callId, event.tool);+ return;+ case 'tool_result':+ return onResult(event, calls, sink);+ case 'status':+ if (event.phase === 'step_end' && event.usage) {+ const { inputTokens = 0, outputTokens = 0, cacheReadTokens = 0, cacheWriteTokens = 0 } = event.usage;+ generated += outputTokens;+ sink.usage({ contextTokens: inputTokens + cacheReadTokens + cacheWriteTokens + outputTokens, outputTokens: generated });+ }+ if (event.phase === 'turn_end') return ended(event, sink);+ return;+ case 'error':+ return sink.fail('AGENT_FAILED', explain(event.message));+ }+ };+ },++ json(context: JsonContext): Plan {+ const cwd = this.workspace('task');+ mkdirSync(taskHome(), { recursive: true });+ sweepSessions(taskHome());+ const off = [...SWITCHED_OFF, WEB, TODO].filter((id) => !(context.reads && id === 'tool-fs'));+ const rows: Row[] = [+ ...off.map((id) => ({ id, disabled: true })),+ ...signIn(),+ defaultModel({ provider: provider(), model: context.settings.model ?? DEFAULT_MODEL, effort: effortOf(context.settings, this.efforts) }),+ instructionsRow(TASK_PATCH),+ ...(context.reads ? [{ id: 'tool-fs', config: READ_ONLY }] : []),+ ];+ return {+ cwd,+ env: environment(cwd, taskHome()),+ files: [{ path: TASK_PATCH, content: patch(rows) }],+ args: ['--profile', 'headless', '--patch', join(cwd, TASK_PATCH), '--json', '-'],+ input: context.prompt,+ };+ },++ answer(stdout: string) {+ let text: string | undefined;+ for (const line of stdout.split('\n')) {+ const event = parseJsonLine<HeadlessEvent>(line);+ if (event?.type === 'error') return { error: explain(event.message) };+ if (event?.type === 'status' && event.phase === 'turn_end' && event.reason?.kind === 'error') return { error: explain(event.reason.error?.message) };+ if (event?.type === 'final' && event.text) text = event.text;+ }+ return { text };+ },++ hint(stderrTail: string) {+ const said = /dsh: ([A-Z_]+): (.+)/.exec(stderrTail);+ if (/patch: entry .+ not found/i.test(stderrTail)) {+ return `Your DeepSeek Harness has changed in a way this Browsentic has not been checked against. Update both (${INSTALL}), then try again. (${stderrTail.trim()})`;+ }+ return said ? explain(said[2]) : null;+ },++ async check(): Promise<AgentProblem | null> {+ if (signedIn('account') || signedIn('key') || process.env.DEEPSEEK_API_KEY) return null;+ return {+ code: 'AGENT_NEEDS_PERMISSION',+ message: 'DeepSeek Harness is not signed in to a DeepSeek account, and no DEEPSEEK_API_KEY is set.',+ fix: SIGN_IN,+ };+ },+};++/** What every streamed turn starts from: its conversation's folder, and the run's own dsh home. */+function turnOf(context: StreamContext): Omit<Plan, 'args' | 'files'> {+ const base = deepseekRunner.workspace('run');+ sweepRunDirs(base);+ mkdirSync(runHome(), { recursive: true });+ const cwd = conversationDir(base, context.conversation ?? context.runId);+ return { cwd, env: environment(cwd, runHome()) };+}++function environment(cwd: string, home: string): Record<string, string> {+ mkdirSync(agentsHome(), { recursive: true });+ return {+ DSH_HOME: home,+ DSH_AGENTS_HOME: agentsHome(),+ DSH_PERMISSION_MODE: 'read-only',+ DSH_TELEMETRY_MODE: 'DISABLED',+ DSH_TELEMETRY_DISABLED: '1',+ PWD: cwd,+ };+}++/** A sign-in `dsh web` wrote, as an account record or a stored key. Only the key names are read. */+function signedIn(as: 'account' | 'key'): boolean {+ try {+ const text = readFileSync(credentials(), 'utf8');+ return as === 'account' ? /^\s+deepseek-account-platform\/default:/m.test(text) : /^\s+DEEPSEEK_API_KEY:/m.test(text);+ } catch {+ return false;+ }+}++/** A DeepSeek account where there is one, which is how `dsh web` signs in, and an API key otherwise. */+const provider = () => (signedIn('account') ? PROVIDERS.account : PROVIDERS.key);++/** The user's sign-in, and the rows headless needs to use it. */+const signIn = (): Row[] => [+ { id: 'credentials', disabled: false, config: { path: credentials() } },+ ...SIGN_IN_ROWS.map((id) => ({ id, disabled: false })),+];++function runRows(context: StreamContext, turn: Route): Row[] {+ return [+ ...[...SWITCHED_OFF, ...(context.research ? [] : [WEB])].map((id) => ({ id, disabled: true })),+ ...signIn(),+ defaultModel(turn),+ instructionsRow(PATCH),+ { id: 'system-prompt', config: { personaPrefix: PERSONA } },+ { id: 'spill-policy', config: { maxInlineTokens: RESULT_TOKENS } },+ ];+}++const defaultModel = ({ provider: through, model, effort }: Route): Row => ({+ id: 'agent-default-model',+ config: { provider: through, model, ...(effort ? { reasoningEffort: effort } : {}) },+});++/** AGENTS.md from the run's own folder alone: the patch file marks it as the project's root, so no folder above is searched. */+const instructionsRow = (marker: string): Row => ({+ id: 'agent-instructions',+ config: { maxBytes: INSTRUCTION_BYTES, projectRootMarkers: [marker], localInstructionFileCandidates: [] },+});++const patch = (rows: Row[]) => `${JSON.stringify(rows, null, 1)}\n`;++const acpServer = (mcp: McpServer) => ({+ name: MCP_SERVER_NAME,+ command: mcp.command,+ args: mcp.args,+ env: Object.entries(mcp.env).map(([name, value]) => ({ name, value })),+});++const insertServer = (mcp: McpServer): Row => ({+ insert: [+ {+ id: `mcp-${MCP_SERVER_NAME}`,+ name: '@deepseek-ai/dsh-mcp-client',+ config: { serverName: MCP_SERVER_NAME, transport: 'stdio', command: mcp.command, args: mcp.args, env: mcp.env },+ },+ ],+});++/**+ * dsh lists its models under each provider, each value a `[provider, model]` pair sent back as+ * JSON. A setting names the model alone, so the current provider's is the one picked.+ */+function modelsOffered(choice: ConfigOption | undefined): ModelEntry[] {+ const values = (choice?.options ?? []).flatMap((offered) => offered.options ?? [offered]).flatMap((offered) => (offered.value ? [offered.value] : []));+ const pairs = values.flatMap((value) => {+ const pair = parseJsonLine<unknown>(value);+ return Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string' ? [{ provider: pair[0], id: pair[1], value }] : [];+ });+ const current = parseJsonLine<unknown>(choice?.currentValue ?? '');+ const provider = Array.isArray(current) ? current[0] : undefined;+ return [...pairs.filter((pair) => pair.provider === provider), ...pairs.filter((pair) => pair.provider !== provider)].map(({ id, value }) => ({ id, value }));+}++/** A tool the model only named, which dsh answers as unknown, never ran; any other call that finished did. */+function ran(update: Update): boolean {+ if (update.status === 'completed') return true;+ return !/unknown tool/i.test(JSON.stringify(update.content ?? ''));+}++function onResult(event: HeadlessEvent, calls: Map<string, string>, sink: StreamSink): void {+ const id = event.callId;+ const name = id ? calls.get(id) : undefined;+ if (!id || !name) return;+ if (WEB_TOOLS.includes(name)) return sink.toolResult(id, event.status === 'completed');+ if (name.startsWith(`mcp__${MCP_SERVER_NAME}__`) || name === 'todo_write') return;+ if (event.status === 'completed' || !/unknown tool/i.test(JSON.stringify(event.result ?? ''))) sink.fail('AGENT_UNSAFE', stoppedFor(name));+}++function ended(event: HeadlessEvent, sink: StreamSink): void {+ const kind = event.reason?.kind;+ if (kind === 'error') return sink.fail('AGENT_FAILED', explain(event.reason?.error?.message));+ if (kind === 'cancelled' || kind === 'aborted') return sink.fail('CANCELLED', 'Run cancelled.');+ sink.done(kind === 'completed' || !kind ? 'end_turn' : kind);+}++function explain(message: string | undefined): string {+ if (!message) return 'DeepSeek Harness stopped without saying why.';+ if (/sign in to deepseek|MISSING_CREDENTIAL|no API key for provider/i.test(message)) {+ return `DeepSeek Harness is not signed in. Run "${SIGN_IN}" and sign in with your DeepSeek account, or set DEEPSEEK_API_KEY. (${oneLine(message)})`;+ }+ return `DeepSeek Harness: ${oneLine(message)}`;+}++const stoppedFor = (tool: string) =>+ `DeepSeek Harness ran its own ${tool} tool in this run, which Browsentic switched off, so the run was stopped. ` ++ 'Update DeepSeek Harness and Browsentic; if it persists, please report it.';++const oneLine = (text: string) => text.replace(/\s+/g, ' ').trim();++/** Headless keeps every one-shot as a session; a day's are enough for anyone looking into one. */+function sweepSessions(home: string): void {+ const sessions = join(home, 'sessions');+ let folders: string[];+ try {+ folders = readdirSync(sessions);+ } catch {+ return;+ }+ for (const folder of folders) sweepRunDirs(join(sessions, folder));+}diff --git a/src/daemon/agent/runners/index.test.ts b/src/daemon/agent/runners/index.test.tsindex 8a1883e..44a125b 100644--- a/src/daemon/agent/runners/index.test.ts+++ b/src/daemon/agent/runners/index.test.ts@@ -43,6 +43,7 @@ const configWith = (agents: Partial<Record<AgentKind, AgentSettings>>, agent: Agcursor: { bin: join(bin, 'cursor-agent') },qwen: { bin: join(bin, 'qwen') },opencode: { bin: join(bin, 'opencode') },+ deepseek: { bin: join(bin, 'dsh') },...agents,},requireApproval: [],@@ -82,7 +83,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', 'qwen', 'opencode']) stub(name);+ for (const name of ['claude', 'claude-next', 'codex', 'agy', 'vibe', 'grok', 'cursor-agent', 'qwen', 'opencode', 'dsh']) stub(name);stub('opencode2', { prints: 'opencode v2.0.32' });stub('codex-expired', { prints: 'licence expired', exit: 3 });});@@ -175,7 +176,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', 'opencode', 'qwen', 'vibe']], 'antigravity']);+ expect([rounds(), again.active]).toEqual([[['agy', 'claude', 'codex', 'cursor-agent', 'dsh', 'grok', 'opencode', 'qwen', 'vibe']], 'antigravity']);});test('asking for a refresh probes again', async () => {@@ -188,8 +189,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', 'opencode', 'qwen', 'vibe'],- ['agy', 'claude-next', 'codex', 'cursor-agent', 'grok', 'opencode', 'qwen', 'vibe'],+ ['agy', 'claude', 'codex', 'cursor-agent', 'dsh', 'grok', 'opencode', 'qwen', 'vibe'],+ ['agy', 'claude-next', 'codex', 'cursor-agent', 'dsh', 'grok', 'opencode', 'qwen', 'vibe'],]);});diff --git a/src/daemon/agent/runners/index.ts b/src/daemon/agent/runners/index.tsindex 6eebb11..fc63523 100644--- a/src/daemon/agent/runners/index.ts+++ b/src/daemon/agent/runners/index.ts@@ -15,6 +15,7 @@ import { claudeRunner } from './claude';import { codexRunner } from './codex';import { spawnCli, stopTree, type CliProcess } from './command';import { cursorRunner } from './cursor';+import { deepseekRunner } from './deepseek';import { grokRunner } from './grok';import { modelsFor, refreshModels } from './models';import { opencodeRunner } from './opencode';@@ -32,6 +33,7 @@ export const RUNNERS: Record<AgentKind, Runner> = {cursor: cursorRunner,qwen: qwenRunner,opencode: opencodeRunner,+ deepseek: deepseekRunner,};const cliPath = join(dirname(fileURLToPath(import.meta.url)), 'cli.js');diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 20bcd09..81fe02b 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -68,7 +68,7 @@ const USAGE = `browsentic ${pkg.version} — Browsentic Bridge, the half of Browbrowsentic revoke [id] unpair one browser by the id "sessions" prints, or all of them; it stays out until you reconnect itbrowsentic agent show which agent runs the side panel, and which are installed- browsentic agent <name> switch to claude, codex, antigravity, vibe, grok, cursor, qwen or opencode+ browsentic agent <name> switch to claude, codex, antigravity, vibe, grok, cursor, qwen, opencode or deepseekbrowsentic 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 defaultbrowsentic agent models <name> list the models that agent offers; --refresh asks its CLI againdiff --git a/src/daemon/guardrails/spawn.test.ts b/src/daemon/guardrails/spawn.test.tsindex 8457122..eb976ac 100644--- a/src/daemon/guardrails/spawn.test.ts+++ b/src/daemon/guardrails/spawn.test.ts@@ -583,6 +583,71 @@ describe('spawn containment', () => {});});+ describe('DeepSeek Harness', () => {+ const turn = planOf('deepseek', 'conversation');+ const fallback = planOf('deepseek', 'run');+ const oneShot = planOf('deepseek', 'task');+ const PATCH = 'browsentic.patch.yml';+ type Row = Record<string, unknown>;+ const repatched = (plan: Plan, edit: (rows: Row[]) => Row[], path = PATCH): Plan =>+ rewriting(plan, path, (content) => JSON.stringify(edit(JSON.parse(content) as Row[])));++ test('its turn, the headless run it falls back to, and its one-shots are contained, on research and reading a file too', () => {+ for (const [mode, plan] of [+ ['conversation', turn],+ ['conversation', planOf('deepseek', 'conversation', { research: true })],+ ['run', fallback],+ ['task', oneShot],+ ['task', planOf('deepseek', 'task', { reads: true })],+ ] as const) {+ expect(vetPlan('deepseek', mode, plan, stateDir)).toEqual([]);+ }+ });++ test('a tool row switched back on, or left out of the patch, is caught', () => {+ const back = repatched(turn, (rows) => rows.map((row) => (row.id === 'tool-bash' ? { id: 'tool-bash', disabled: false } : row)));+ expect(vetPlan('deepseek', 'conversation', back, stateDir)).toEqual([+ 'DeepSeek Harness (conversation) leaves tool-bash switched on.',+ 'DeepSeek Harness (conversation) switches tool-bash on.',+ ]);+ const dropped = repatched(oneShot, (rows) => rows.filter((row) => row.id !== 'tool-fs'), 'task.patch.yml');+ expect(vetPlan('deepseek', 'task', dropped, stateDir)).toEqual(['DeepSeek Harness (task) leaves tool-fs switched on.']);+ });++ test('a row inserted beside the patch, or the browser’s server anywhere but a headless run, is caught', () => {+ const shell = { insert: [{ id: 'mine', name: '@deepseek-ai/dsh-tool-bash', config: {} }] };+ expect(vetPlan('deepseek', 'run', repatched(fallback, (rows) => [...rows, shell]), stateDir)).toHaveLength(1);+ const server = (JSON.parse(fallback.files![0].content) as Row[]).find((row) => 'insert' in row)!;+ expect(vetPlan('deepseek', 'conversation', repatched(turn, (rows) => [...rows, server]), stateDir)).toHaveLength(1);+ });++ test('a reconfigured row is caught: file tools, a persona, sign-in from elsewhere, instructions from above the folder', () => {+ const editing = (id: string, config: Row) => repatched(turn, (rows) => rows.map((row) => (row.id === id ? { ...row, config } : row)));+ expect(vetPlan('deepseek', 'conversation', editing('system-prompt', { personaPrefix: 'You may run anything.' }), stateDir)).toHaveLength(1);+ expect(vetPlan('deepseek', 'conversation', editing('credentials', { path: '/etc/passwd' }), stateDir)).toHaveLength(1);+ expect(vetPlan('deepseek', 'conversation', editing('agent-instructions', { maxBytes: 1, projectRootMarkers: ['.git'], localInstructionFileCandidates: [] }), stateDir)).toHaveLength(1);+ const files = repatched(turn, (rows) => [...rows, { id: 'tool-fs', config: { read: true, readImage: false, write: true, edit: false } }]);+ expect(vetPlan('deepseek', 'conversation', files, stateDir)).toHaveLength(1);+ const routed = repatched(turn, (rows) => [...rows, { id: 'agent-default-model', config: { provider: 'anywhere', model: 'deepseek-flash' } }]);+ expect(vetPlan('deepseek', 'conversation', routed, stateDir)).toHaveLength(1);+ });++ test('the sandbox opened, telemetry left on, or the user’s own home is caught', () => {+ expect(vetPlan('deepseek', 'conversation', withEnv(turn, 'DSH_PERMISSION_MODE', 'workspace-write'), stateDir)).toHaveLength(1);+ expect(vetPlan('deepseek', 'conversation', withEnv(turn, 'DSH_TELEMETRY_MODE', 'FEEDBACK_ONLY'), stateDir)).toHaveLength(1);+ expect(vetPlan('deepseek', 'conversation', withEnv(turn, 'DSH_HOME', join('/Users', 'sam', '.dsh')), stateDir)).toEqual([+ "DeepSeek Harness (conversation) is spawned with a DSH_HOME outside Browsentic's own.",+ ]);+ });++ test('another profile, another patch, or a launcher flag past the patch is caught', () => {+ expect(vetPlan('deepseek', 'conversation', swapped(turn, 'acp', 'web'), stateDir)).toHaveLength(1);+ expect(vetPlan('deepseek', 'conversation', swapped(turn, turn.args[3], '/tmp/other.yml'), stateDir)).not.toEqual([]);+ expect(vetPlan('deepseek', 'conversation', plus(turn, '--from-default-profile', 'web'), stateDir)).toHaveLength(2);+ expect(vetPlan('deepseek', 'task', plus(oneShot, '--session-id', 'session-1'), stateDir)).toHaveLength(1);+ });+ });+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 f68af42..dad8e3f 100644--- a/src/daemon/guardrails/spawn.ts+++ b/src/daemon/guardrails/spawn.ts@@ -242,6 +242,158 @@ const openCode2 =return problems;};+/**+ * Rows of a DeepSeek Harness profile that give the model a tool of its own, or run work beside the+ * turn: the shell, the disk, skills, sub-agents, scripted workflows, goals, its own commands and+ * questions, and the telemetry exporters. The web rows are left to a run in research mode.+ */+const DEEPSEEK_OFF = [+ 'tool-bash', 'tool-pwsh', 'tool-jobs', 'tool-fs', 'tool-fs-search',+ 'tool-skill', 'skill', 'skill-filesystem',+ 'tool-subagent', 'tool-subagent-fork', 'tool-subagent-control', 'tool-subagent-list-agents',+ 'tool-workflow', 'workflow-ptc', 'ptc-runtime',+ 'tool-goal', 'goal', 'goal-round-driver', 'command-goal', 'tool-working-directory',+ 'plan-mode', 'mcp-resources', 'user-questions', 'commands', 'command-feedback', 'command-compact',+ 'otel', 'session-telemetry-otel',+];++const DEEPSEEK_SIGN_IN = ['credentials', 'authorization', 'deepseek-account'];++const DEEPSEEK_PROVIDERS = ['deepseek-account', 'deepseek-official'];++const DEEPSEEK_EFFORTS = ['off', 'low', 'high', 'max'];++const DEEPSEEK_PERSONA = "You are Browsentic's browser agent, powered by the {{model}} model.";++/** dsh's own environment switches: a sandbox for whatever might still run, and no telemetry. */+const DEEPSEEK_SEALED = { DSH_PERMISSION_MODE: 'read-only', DSH_TELEMETRY_MODE: 'DISABLED', DSH_TELEMETRY_DISABLED: '1' };++interface DeepseekRow {+ id?: unknown;+ name?: unknown;+ disabled?: unknown;+ config?: Record<string, unknown>;+ insert?: DeepseekRow[];+}++const sameJson = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);++/**+ * A DeepSeek Harness plan read rather than searched. Its argv is exactly a profile and a patch; its+ * homes are Browsentic's own, so none of the user's patches, AGENTS.md or skills compose into it;+ * and the patch switches off every row that hands the model a tool. Beyond those it may switch the+ * sign-in back on, point the credentials row at the user's file, pick a route, keep instructions+ * to the run's folder, set the persona and the result ceiling, give a one-shot a read-only `read`+ * and a headless run the browser's server: anything else is refused.+ */+const deepseek =+ (mode: SpawnMode) =>+ (plan: SpawnPlan): string[] => {+ const problems: string[] = [];+ const profile = mode === 'conversation' ? 'acp' : 'headless';+ const patchFile = mode === 'task' ? 'task.patch.yml' : 'browsentic.patch.yml';+ const patchPath = posix.join(plan.cwd, patchFile) === plan.args[3] || win32.join(plan.cwd, patchFile) === plan.args[3] ? plan.args[3] : undefined;+ const tail = plan.args.slice(4);+ const shaped =+ plan.args[0] === '--profile' && plan.args[1] === profile && plan.args[2] === '--patch' && patchPath !== undefined &&+ (mode === 'conversation'+ ? tail.length === 0+ : sameJson(tail.slice(-2), ['--json', '-']) && (tail.length === 2 || (mode === 'run' && tail.length === 4 && tail[0] === '--session-id')));+ if (!shaped) problems.push(`is spawned other than as \`dsh --profile ${profile} --patch <its ${patchFile}>\``);++ const owner = deepseekRoot(plan.cwd);+ for (const name of ['DSH_HOME', 'DSH_AGENTS_HOME']) {+ const value = plan.env?.[name];+ if (!owner || !value || !within(value, owner)) problems.push(`is spawned with a ${name} outside Browsentic's own`);+ }++ let rows: DeepseekRow[];+ try {+ rows = JSON.parse(plan.files?.find((file) => file.path === patchFile)?.content ?? '') as DeepseekRow[];+ if (!Array.isArray(rows)) throw new Error('not a list');+ } catch {+ return [...problems, `writes a ${patchFile} that is not a readable list of rows`];+ }++ const switchedOff = new Set(rows.filter((row) => row.disabled === true && Object.keys(row).length === 2).map((row) => row.id));+ const missing = DEEPSEEK_OFF.filter((id) => !switchedOff.has(id) && !(mode === 'task' && id === 'tool-fs' && readOnly(rows)));+ if (missing.length) problems.push(`leaves ${missing.join(', ')} switched on`);+ for (const row of rows) {+ const clause = deepseekRow(row, mode);+ if (clause) problems.push(clause);+ }+ return problems;+ };++/** Whether the one-shot's patch gives it `read` and no other file tool. */+const readOnly = (rows: DeepseekRow[]) =>+ rows.some((row) => row.id === 'tool-fs' && sameJson(row.config, { read: true, readImage: false, write: false, edit: false }) && row.disabled === undefined);++/** What is wrong with one row of the patch, or null when it is a row the plan may carry. */+function deepseekRow(row: DeepseekRow, mode: SpawnMode): string | null {+ if (row.insert !== undefined) {+ const [server, ...others] = Array.isArray(row.insert) ? row.insert : [];+ const config = server?.config ?? {};+ const browser =+ mode === 'run' && others.length === 0 && Object.keys(row).length === 1 &&+ server?.name === '@deepseek-ai/dsh-mcp-client' && config.serverName === 'browsentic' && config.transport === 'stdio' &&+ Array.isArray(config.args) && config.args.at(-1) === 'mcp' &&+ typeof (config.env as Record<string, unknown> | undefined)?.BROWSENTIC_AGENT_RUN === 'string';+ return browser ? null : 'inserts a row other than the browser’s own server';+ }+ const { id, disabled, config } = row;+ if (typeof id !== 'string') return 'carries a row with no id';+ if (disabled === true) return config === undefined && Object.keys(row).length === 2 ? null : `switches ${id} off with a config besides`;+ if (disabled === false && !DEEPSEEK_SIGN_IN.includes(id)) return `switches ${id} on`;+ if (config === undefined) return disabled === false ? null : `carries a ${id} row that does nothing`;+ switch (id) {+ case 'credentials':+ return Object.keys(config).join() === 'path' && typeof config.path === 'string' && /[\\/]\.credentials\.yaml$/.test(config.path) ? null : 'points the credentials row elsewhere than a sign-in file';+ case 'agent-default-model':+ case 'acp': {+ const known = Object.keys(config).every((key) => ['provider', 'model', ...(id === 'acp' ? [] : ['reasoningEffort'])].includes(key));+ const fits =+ DEEPSEEK_PROVIDERS.includes(config.provider as string) && isModelId(config.model) &&+ (config.reasoningEffort === undefined || DEEPSEEK_EFFORTS.includes(config.reasoningEffort as string));+ return known && fits && (id !== 'acp' || mode === 'conversation') ? null : `picks a route through ${id} it may not`;+ }+ case 'agent-instructions': {+ const marker = mode === 'task' ? 'task.patch.yml' : 'browsentic.patch.yml';+ const keys = Object.keys(config).sort().join();+ return keys === 'localInstructionFileCandidates,maxBytes,projectRootMarkers' && typeof config.maxBytes === 'number' &&+ sameJson(config.projectRootMarkers, [marker]) && sameJson(config.localInstructionFileCandidates, [])+ ? null+ : 'lets workspace instructions come from beyond the run’s own folder';+ }+ case 'system-prompt':+ return sameJson(config, { personaPrefix: DEEPSEEK_PERSONA }) ? null : 'rewrites the system prompt’s persona';+ case 'spill-policy':+ return Object.keys(config).join() === 'maxInlineTokens' && typeof config.maxInlineTokens === 'number' ? null : 'reconfigures the result ceiling';+ case 'tool-fs':+ return mode === 'task' && sameJson(config, { read: true, readImage: false, write: false, edit: false }) ? null : 'gives the model file tools';+ default:+ return `reconfigures ${id}`;+ }+}++/** The `agents/deepseek` folder a plan's working directory lies in, whose homes are the only ones it may use. */+function deepseekRoot(cwd: string): string | undefined {+ const path = cwd.includes('\\') ? win32 : posix;+ for (let dir = cwd; path.dirname(dir) !== dir; dir = path.dirname(dir)) {+ if (path.basename(dir) === 'deepseek' && path.basename(path.dirname(dir)) === 'agents') return dir;+ }+ return undefined;+}++const deepseekRules = (mode: SpawnMode): Requirements => ({+ required: [],+ pairs: [],+ env: DEEPSEEK_SEALED,+ envIsCwd: ['PWD'],+ inspect: deepseek(mode),+ files: mode === 'task' ? ['task.patch.yml'] : ['browsentic.patch.yml', 'AGENTS.md'],+});+const openCode2Rules = (mode: SpawnMode): Requirements => ({required: mode === 'conversation' ? ['acp'] : ['--standalone'],pairs:@@ -513,6 +665,21 @@ export const CONTAINMENT: Record<AgentKind, Containment> = {],conversation: openCode2Rules('conversation'),},++ deepseek: {+ localTools: 'allowlist',+ // A run signs in with the user's dsh sign-in, through the patch; DEEPSEEK_API_KEY is the other route dsh reads.+ keepsEnv: ['DEEPSEEK_'],+ // Its own launcher flags would load another profile or patch, or rewrite a profile, beside the vetted one.+ forbidden: [/^--profile=/i, /^--patch=/i, /^--from-default-profile/i, /^--dump/i],+ note:+ 'a per-run patch over its plugin tree that switches off every row giving the model a tool of its own — shell, files, ' ++ 'skills, sub-agents, workflows — so the model is offered the browser alone; runs keep a dsh home of Browsentic’s, ' ++ 'so the user’s own patches, AGENTS.md and skills never compose in, and borrow only the sign-in',+ run: deepseekRules('run'),+ task: deepseekRules('task'),+ conversation: deepseekRules('conversation'),+ },};/**@@ -631,7 +798,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_', 'OPENCODE_',+ 'QWEN_', 'DASHSCOPE_', 'BAILIAN_', 'OPENCODE_', 'DEEPSEEK_', 'DSH_','VERCEL_', 'NETLIFY_', 'CLOUDFLARE_', 'FLY_', 'HEROKU_', 'RAILWAY_',];diff --git a/src/daemon/test/agent-protocol.test.ts b/src/daemon/test/agent-protocol.test.tsnew file mode 100644index 0000000..47e1530--- /dev/null+++ b/src/daemon/test/agent-protocol.test.ts@@ -0,0 +1,79 @@+import { rmSync } from 'node:fs';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';+import { AGENT_PROTOCOL, SOCKET_PROTOCOL_VERSION } from '@/lib/actions/protocol';+import { clearAuth } from '../auth-store';+import { configPath, writeActiveAgent } from '../agent/config';+import { startDaemon, type Daemon } from '../daemon';+import { readLockfile } from '../lockfile';+import { RemoteBridge } from '../remote-bridge';+import { FakeBrowser, type Profile } from './fake-browser';++const chrome: Profile = { origin: 'chrome-extension://abcdefghijklmnopabcdefghijklmnop', installId: 'install-chrome-0001', browser: 'Google Chrome' };+const older = { ...chrome, protocolVersion: AGENT_PROTOCOL.deepseek! - 1 };++let daemon: Daemon;+let opened: { close(): unknown }[] = [];++beforeAll(async () => {+ daemon = await startDaemon({ version: '0.0.0-test', idleExit: false });+});++afterAll(async () => {+ await daemon?.stop();+});++beforeEach(() => {+ rmSync(configPath, { force: true });+});++afterEach(async () => {+ for (const each of opened) each.close();+ opened = [];+ await new Promise((resolve) => setTimeout(resolve, 20));+ clearAuth();+});++async function pair(profile: Profile): Promise<FakeBrowser> {+ const control = await RemoteBridge.connect(daemon.port, readLockfile()!.token);+ opened.push(control);+ const { code } = await control.pair();+ const browser = await FakeBrowser.connect(daemon.port, profile, { kind: 'pair', code });+ opened.push(browser);+ return browser;+}++// A store copy updates when its browser decides to, and an older panel looks every agent up by kind.+describe('an agent newer than the extension', () => {+ test('is never sent to an older panel: the state and the skill catalog are refused instead', async () => {+ writeActiveAgent('deepseek');+ const browser = await pair(older);+ const [state] = await browser.frames('agentInfo');+ const [catalog] = await browser.frames('skillCatalog');+ for (const { result } of [state, catalog]) {+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.error).toMatchObject({ code: 'UNSUPPORTED', message: expect.stringMatching(/^DeepSeek Harness needs a newer Browsentic extension/) });+ }+ });++ test('refuses that panel a run, with a word to update', async () => {+ writeActiveAgent('deepseek');+ const browser = await pair(older);+ browser.tell({ t: 'instruct', id: 'run-old', text: 'what does this page cost' });+ const [run] = await browser.frames('run');+ expect(run.event).toMatchObject({ kind: 'error', code: 'AGENT_UNUSABLE' });+ });++ test('is left out of the agents an older panel is told of while another one is active', async () => {+ writeActiveAgent('claude');+ const browser = await pair(older);+ const [state] = await browser.frames('agentInfo');+ expect(state.result.ok && state.result.data.runners.map((runner) => runner.kind)).not.toContain('deepseek');+ });++ test('reaches a panel that knows it', async () => {+ writeActiveAgent('deepseek');+ const browser = await pair({ ...chrome, protocolVersion: SOCKET_PROTOCOL_VERSION });+ const [state] = await browser.frames('agentInfo');+ expect(state.result.ok && state.result.data).toMatchObject({ active: 'deepseek', runners: expect.arrayContaining([expect.objectContaining({ kind: 'deepseek' })]) });+ });+});diff --git a/src/extension/components/agent-marks.tsx b/src/extension/components/agent-marks.tsxindex 3a49429..0e9f309 100644--- a/src/extension/components/agent-marks.tsx+++ b/src/extension/components/agent-marks.tsx@@ -36,6 +36,11 @@ const MARKS: Record<AgentKind, { viewBox: string; path: string }> = {viewBox: '128 96 256 320',path: 'M384 416H128V96H384V416ZM320 160H192V352H320V160Z',},+ // Not DeepSeek's own mark, which its brand rules keep for itself: the letters it suggests, DSH.+ deepseek: {+ viewBox: '0 -8 28 28',+ path: 'M0 0H5L8 3V9L5 12H0ZM2 2V10H4.2L6 8.2V3.8L4.2 2ZM10 0H18V2H12V5H18V12H10V10H16V7H10ZM20 0H22V5H26V0H28V12H26V7H22V12H20Z',+ },};/** A plain prompt, for an agent a newer Bridge can run and this build has no mark for. */diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.tsindex 49a213b..f62b2a0 100644--- a/src/lib/actions/protocol.ts+++ b/src/lib/actions/protocol.ts@@ -24,7 +24,7 @@ export const ANDROID_PROTOCOL = 23;* The first protocol whose extension knows each agent added since the compatibility window opened.* An older panel looks every agent up by kind, so it is never told about one it does not know.*/-export const AGENT_PROTOCOL: Partial<Record<AgentKind, number>> = {};+export const AGENT_PROTOCOL: Partial<Record<AgentKind, number>> = { deepseek: 25 };/*** The oldest extension the daemon lets in. A store copy updates when its browser decides to, so itdiff --git a/src/lib/agents/catalog.ts b/src/lib/agents/catalog.tsindex 997dd04..5801345 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', 'qwen', 'opencode'] as const;+export const AGENT_KINDS = ['claude', 'codex', 'antigravity', 'vibe', 'grok', 'cursor', 'qwen', 'opencode', 'deepseek'] as const;export type AgentKind = (typeof AGENT_KINDS)[number];@@ -100,6 +100,17 @@ export const AGENTS: Record<AgentKind, AgentDescriptor> = {models: ['anthropic/claude-opus-5-5', 'anthropic/claude-sonnet-5', 'openai/gpt-5.6', 'google/gemini-3.1-pro-preview'],beta: true,},+ deepseek: {+ kind: 'deepseek',+ label: 'DeepSeek Harness',+ vendor: 'DeepSeek',+ bin: 'dsh',+ install: 'npm i -g @deepseek-ai/dsh',+ docs: 'https://deepseek-harness.github.io/deepseek-harness/',+ // The same ids on a DeepSeek account and on an API key. Only deepseek-flash reads a screenshot.+ models: ['deepseek-flash', 'deepseek-v4-pro'],+ beta: true,+ },};export const AGENT_LIST: AgentDescriptor[] = AGENT_KINDS.map((kind) => AGENTS[kind]);