Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(browser): add durable Browser AI Agent and 1Password credentials
trohitg3c4e7b0b5239
diff --git a/.env.template b/.env.templateindex 702fc704..c5b74b13 100644--- a/.env.template+++ b/.env.template@@ -99,6 +99,24 @@ TEMPORAL_AGENT_WORKFLOW_ENABLED=true# false + restart — activities route back to the manager worker# unchanged.TEMPORAL_WORKER_POOL_ENABLED=true+# Distributed browser setup: docs-internal/browser_agent_deployment.md.+# Owner queues remain mandatory when the generic worker pool is disabled.+DISTRIBUTED_MODE=false+# DATABASE_URL=postgresql+asyncpg://opencompany:...@database:5432/opencompany+# BROWSER_REPLICA_ID=backend-a+# BROWSER_REPLICA_URL=http://backend-a:5678+# Stable physical machine identity across container restarts:+# BROWSER_MACHINE_ID=machine-a+# Shared forwarding secret (defaults to SECRET_KEY):+# BROWSER_ROUTER_SECRET=...+ONEPASSWORD_CLI_VERSION=2.40.0+ONEPASSWORD_AUTH_MODE=desktop+# ONEPASSWORD_CLI_PATH=/absolute/path/to/op+# ONEPASSWORD_ACCOUNT=account.1password.com+ONEPASSWORD_READ_TIMEOUT_SECONDS=30+# Distributed mode requires ONEPASSWORD_AUTH_MODE=service_account.+# Inject OP_SERVICE_ACCOUNT_TOKEN using trusted deployment secret configuration.+# Never put it in node parameters, graph JSON or serialized Settings.# Deployment topology hint: local (dev laptop; sleeps; halved per-queue# concurrency) | cloud (company deploy VM) | self_hosted. Drives worker# identity strings in the Temporal Web UI and per-mode concurrencydiff --git a/.gitignore b/.gitignoreindex 1ff74ec3..1ff0c44a 100644--- a/.gitignore+++ b/.gitignore@@ -210,3 +210,6 @@ desktop/vendor/desktop/build/icon.pngdesktop/test-results/desktop/playwright-report/++# Isolated integration-test runtimes and disposable databases.+/.test-runtime/diff --git a/CLAUDE.md b/CLAUDE.mdindex 1feb9eb7..bcd55e04 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -9,6 +9,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| Document | Description ||----------|-------------|+| **[Browser AI Agent deployment](./docs-internal/browser_agent_deployment.md)** | Shared creation recipe, local/distributed prerequisites, PostgreSQL offline transfer, exclusive browser ownership, owner recovery, direct task history and release gates. Browser effects route to owner queues even with worker pools disabled. Direct tasks use the existing native agent/Workspace path and remain separate from deployment Start/Stop/Resume. |+| **[1Password credentials](./docs-internal/onepassword_credentials.md)** | CLI-first approved API/login bindings, pinned executable verification, desktop/service-account authorization, metadata-only catalogues, Activity-local resolution, protected CDP login and the local-only OAuth/CLI compatibility boundary. No resolved values in models, Temporal inputs, viewer captures or task history. || **[Frontend Architecture](./docs-internal/frontend_architecture.md)** | Current frontend stack (React 19 + Vite + Tailwind v4 + shadcn/ui + Radix + RHF/zod + TanStack Query + Zustand). Tokens, primitives, forms, credentials exemplar, ownership boundary, `uiHints` catalogue. Brand: the Open Council mark and the outlined Newsreader wordmark are SVG paths in `client/src/components/brand/geometry.ts`, drawn in the text colour by `brand/Logo.tsx`; the favicon (`client/public/opencompany-icon.svg`), the desktop icon (`desktop/build/icon.svg`) and the icon-only logo SVGs in `media/brand/` embed its `MARK_PATH` verbatim (`brand/__tests__/appIcons.test.ts`), so change the mark there, paste the new path into each, and render the square PNGs beside those SVGs again (`media/brand/README.md` says how). || **[UI Migration Plan](./docs-internal/ARCHIVE/ui_migration_plan.md)** | *Archived.* antd → shadcn/ui migration completion log (Waves 1–10). Current state lives in [Frontend Architecture](./docs-internal/frontend_architecture.md) and [Theme System](./docs-internal/theme_system.md). || **[Temporal Cleanup & Resilience Plan (Waves 15-18)](./docs-internal/ARCHIVE/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md)** | *Archived — all four waves shipped.* 15 dead-code retirement (Redis-Streams branch in event_waiter, APScheduler cron stack, orphaned `connection_status` factory), 16 per-queue task routing (`TemporalWorkerPool`), 17 resilience hardening (cron `catchup_window`, SDK interceptors, `DEPLOYMENT_MODE`, periodic heartbeats; the one-shot LLM-step retry it records was later reverted to unlimited-with-backoff), 18 worker performance tuning. Current settings live in [Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md). |diff --git a/README.md b/README.mdindex d646f7c8..303663f6 100644--- a/README.md+++ b/README.md@@ -131,11 +131,12 @@ Nothing here is a black box. What an employee learns lives in its memory, its no- **Connections** to Gmail, Google Calendar, Drive, Sheets, Tasks, Contacts, Microsoft 365, any email account, WhatsApp, WhatsApp Business, Telegram, Discord, X, Stripe, GitHub, Vercel, Cloudflare, Google Cloud, your Android phone, a browser, web search, scrapers, and a knowledge base: 140+ tools in all.- **Models** from OpenAI, Anthropic, Google, xAI, DeepSeek, Kimi, Mistral, Groq, Cerebras, Sarvam, and OpenRouter, or run local models for free with Ollama, LM Studio, or any OpenAI-compatible server such as llama.cpp or vLLM.-- **A live browser workspace** in Home and Dev mode: watch an employee browse, take control to sign in or help, then hand control back. It opens your installed Chrome, Edge or Chromium in a dedicated OpenCompany profile, keeping sessions between tasks without using your personal profile. [Browser runtime](docs-internal/browser.md) | [Workspace interface](docs-internal/browser_workspace.md).+- **A Browser AI Agent and live browser workspace** in Home and Dev mode: give it a task beside the browser or through employee chat, watch it work, take control to sign in or help, then hand control back. It uses your installed Chrome, Edge or Chromium in a dedicated OpenCompany profile and preserves existing Browser nodes. Direct tasks have their own recent history and Cancel control. [Browser runtime](docs-internal/browser.md) | [Workspace interface](docs-internal/browser_workspace.md).+- **1Password credential bindings** for supported API keys and configured website logins. Local access uses desktop authorization; distributed deployments use scoped service accounts. Website passwords are filled privately while browser observations are paused. MFA and multi-step login use human takeover. [Credential setup and compatibility](docs-internal/onepassword_credentials.md).- **Speech and translation**, so employees can listen, talk, and work in other languages.- **A local Android phone workspace** on Windows x64: set up a persistent emulator, watch it live, use it yourself, or let an AI agent use the **Android** tool. Optional setup requires SDK license acceptance; iOS is not yet supported. [Setup, controls and troubleshooting](docs/mobile-workspace.md).- **78 skills** that ship ready to use, and a place to drop your own.-- **Built to keep running.** Employees survive restarts and catch up on missed schedules. For newly started Temporal generations, Stop lets current work finish, retains its result, and Resume continues with the next pending action. Home, chat and canvas use the same control. [Stop and Resume behavior](docs-internal/temporal-workflow-control.md). Your API keys are stored encrypted on your machine. Add a login for shared or cloud use; one command deploys to Google Cloud.+- **Built to keep running.** Employees survive restarts and catch up on missed schedules. For newly started Temporal generations, Stop lets current work finish, retains its result, and Resume continues with the next pending action. Home, chat and canvas use the same control. [Stop and Resume behavior](docs-internal/temporal-workflow-control.md). Local credentials remain encrypted on your machine. Multi-machine Browser deployments require PostgreSQL, shared storage, external Temporal and 1Password bindings; an unavailable browser keeps its owner and waits for recovery. [Deployment, migration and release checks](docs-internal/browser_agent_deployment.md).- **A canvas you will want to look at**, with 12 visual themes.## For Developersdiff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 29a671b8..ab802701 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -260,7 +260,7 @@ const DashboardContent: React.FC = () => {return false;}, [canvasLock.locked, canvasLock.reason]);const [globalModelDefaults, setGlobalModelDefaults] = React.useState<{ provider: string; model: string } | null>(null);- const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId: currentWorkflow?.id ?? 'new', screenToFlowPosition: reactFlowInstance.screenToFlowPosition });+ const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, edges, setEdges, saveNodeParameters, globalModelDefaults, workflowId: currentWorkflow?.id ?? 'new', screenToFlowPosition: reactFlowInstance.screenToFlowPosition });// Palette drop creates nodes AND persists their default parameters —// an HTML5 drop that React Flow's nodesDraggable/Connectable cannot// block, so it goes through the shared guard.diff --git a/client/src/components/browser/BrowserTasks.tsx b/client/src/components/browser/BrowserTasks.tsxnew file mode 100644index 00000000..95b94fd7--- /dev/null+++ b/client/src/components/browser/BrowserTasks.tsx@@ -0,0 +1,130 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Button } from '@/components/ui/button';+import { buildApiUrl } from '@/config/api';+import type { WorkspaceFileRef } from '@/types/workspaceFiles';+import { createBrowserAgent } from '@/services/browserAgentApi';+import { useAppStore } from '@/store/useAppStore';++interface Agent { node_id: string; label: string }+interface Task {+ invocation_id: string; submission_id: string; node_id: string; prompt: string; status: string;+ result?: { response?: string; artifacts?: WorkspaceFileRef[]; error?: string } | null;+ created_at?: string;+ owner_available?: boolean; detail?: string;+}+const active = new Set(['queued', 'accepted', 'pending', 'running', 'started', 'waiting', 'cancel_requested']);++async function request<T>(path: string, init?: RequestInit): Promise<T> {+ const response = await fetch(buildApiUrl(path), { credentials: 'include', ...init });+ const body = await response.json();+ if (!response.ok) throw new Error(typeof body.detail === 'string' ? body.detail : 'Browser task request failed.');+ return body;+}++export default function BrowserTasks({ workflowId, browserNodeId, visible }: { workflowId: string; browserNodeId: string; visible: boolean }) {+ const [agents, setAgents] = useState<Agent[] | null>(null);+ const [selected, setSelected] = useState('');+ const agentId = agents?.some((agent) => agent.node_id === selected) ? selected : agents?.[0]?.node_id;+ const [prompt, setPrompt] = useState('');+ const [items, setItems] = useState<Task[]>([]);+ const [cursor, setCursor] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const [expanded, setExpanded] = useState(false);+ const pending = useRef<{ prompt: string; agent: string; id: string } | null>(null);+ const olderPages = useRef(false);+ const mounted = useRef(true);+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);++ const discover = useCallback(async () => {+ const query = new URLSearchParams({ workflow_id: workflowId, browser_node_id: browserNodeId });+ const result = await request<{ agents: Agent[] }>(`/api/browser/tasks/discovery?${query}`);+ if (mounted.current) setAgents(result.agents);+ }, [workflowId, browserNodeId]);+ const history = useCallback(async (next?: string) => {+ const query = new URLSearchParams({ workflow_id: workflowId, limit: '20' });+ if (agentId) query.set('node_id', agentId);+ if (next) query.set('cursor', next);+ const result = await request<{ items: Task[]; next_cursor: string | null }>(`/api/browser/tasks/history?${query}`);+ if (mounted.current) {+ setItems((previous) => next ? [...previous, ...result.items.filter((item) => !previous.some((old) => old.invocation_id === item.invocation_id))]+ : olderPages.current ? [...result.items, ...previous.filter((old) => !result.items.some((item) => item.invocation_id === old.invocation_id))] : result.items);+ if (next || !olderPages.current) setCursor(result.next_cursor);+ if (next) olderPages.current = true;+ }+ }, [workflowId, agentId]);+ useEffect(() => { void discover().catch(() => { if (mounted.current) setError('Browser tasks are temporarily unavailable.'); }); }, [discover]);+ useEffect(() => { olderPages.current = false; setItems([]); setCursor(null); }, [agentId]);+ useEffect(() => {+ if (!visible || !agentId) return;+ let polling = false;+ const update = async () => {+ if (polling) return;+ polling = true;+ try { await history(); } catch { /* A subsequent refresh resynchronizes history. */ }+ finally { polling = false; }+ };+ void update();+ const timer = setInterval(() => void update(), 3000);+ return () => clearInterval(timer);+ }, [visible, agentId, history]);++ const addAgent = async () => {+ setBusy(true); setError('');+ try {+ const result = await createBrowserAgent({ workflow_id: workflowId, browser_node_id: browserNodeId });+ useAppStore.getState().adoptSavedOperations(workflowId, result.operations);+ await discover();+ } catch (cause) { if (mounted.current) setError(cause instanceof Error ? cause.message : 'Could not add the Browser AI Agent.'); }+ finally { if (mounted.current) setBusy(false); }+ };+ const submit = async () => {+ if (!agentId || !prompt.trim()) return;+ setBusy(true); setError('');+ if (pending.current?.prompt !== prompt || pending.current?.agent !== agentId) pending.current = { prompt, agent: agentId, id: crypto.randomUUID() };+ try {+ await request('/api/browser/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ workflow_id: workflowId, agent_node_id: agentId, prompt, submission_id: pending.current.id }) });+ pending.current = null;+ if (mounted.current) { setPrompt(''); setExpanded(true); }+ await history();+ } catch (cause) { if (mounted.current) setError(cause instanceof Error ? cause.message : 'Could not submit the task.'); }+ finally { if (mounted.current) setBusy(false); }+ };+ const cancel = async (task: Task) => {+ setError('');+ try {+ const query = new URLSearchParams({ workflow_id: workflowId, agent_node_id: task.node_id });+ await request(`/api/browser/tasks/${encodeURIComponent(task.submission_id)}?${query}`, { method: 'DELETE' });+ await history();+ } catch (cause) { if (mounted.current) setError(cause instanceof Error ? cause.message : 'Could not cancel the task.'); }+ };++ if (agents === null) return <section aria-label="Browser AI tasks" className="shrink-0 border-t border-border-default px-3 py-2 text-xs text-fg-muted">+ <p>{error || 'Loading Browser AI Agent…'}</p>+ {error && <Button size="sm" variant="outline" onClick={() => { setError(''); void discover().catch(() => setError('Browser tasks are temporarily unavailable.')); }}>Retry task connection</Button>}+ </section>;+ return <section aria-label="Browser AI tasks" className="shrink-0 border-t border-border-default bg-bg-panel px-3 py-2 text-xs">+ {!agentId ? <div className="flex items-center justify-between gap-3"><span className="text-fg-muted">Give this browser a task with a Browser AI Agent.</span><Button size="sm" variant="outline" disabled={busy} onClick={() => void addAgent()}>{busy ? 'Adding…' : 'Add Browser AI Agent'}</Button></div> : <>+ {agents.length > 1 && <select aria-label="Browser AI Agent" value={agentId} onChange={(event) => setSelected(event.target.value)} className="mb-2 w-full rounded border border-border-default bg-bg-panel p-1">{agents.map((agent) => <option key={agent.node_id} value={agent.node_id}>{agent.label || 'Browser AI Agent'}</option>)}</select>}+ <form className="flex items-end gap-2" onSubmit={(event) => { event.preventDefault(); void submit(); }}>+ <textarea aria-label="Browser task" placeholder="Describe a task for this browser…" maxLength={20000} rows={2} className="min-w-0 flex-1 resize-y rounded border border-border-default bg-bg-panel p-2 outline-none focus-visible:ring-2 focus-visible:ring-ring" value={prompt} onChange={(event) => setPrompt(event.target.value)} disabled={busy} />+ <Button type="submit" size="sm" disabled={busy || !prompt.trim()}>{busy ? 'Submitting…' : 'Run task'}</Button>+ </form>+ <button type="button" className="mt-2 text-fg-muted hover:text-fg-default" aria-expanded={expanded} onClick={() => setExpanded((value) => !value)}>Recent tasks{items.some((item) => active.has(item.status)) ? ' · task in progress' : ''}</button>+ {expanded && <div className="mt-2 max-h-60 space-y-2 overflow-y-auto">+ {items.length === 0 && <p className="text-fg-muted">No recent browser tasks.</p>}+ {items.map((task) => <article key={task.invocation_id} className="rounded border border-border-default p-2">+ <div className="flex items-start justify-between gap-2"><p className="whitespace-pre-wrap break-words">{task.prompt}</p>{active.has(task.status) && <Button size="sm" variant="ghost" onClick={() => void cancel(task)}>Cancel task</Button>}</div>+ <p className="mt-1 text-fg-muted">{task.status.replaceAll('_', ' ')}</p>+ {task.owner_available === false && active.has(task.status) && <p className="mt-1 text-fg-muted">{task.detail || 'Browser unavailable — waiting for its owner.'}</p>}+ {task.result?.response && <p className="mt-2 whitespace-pre-wrap break-words">{task.result.response}</p>}+ {task.result?.error && <p className="mt-2 text-destructive">{task.result.error}</p>}+ {task.result?.artifacts?.map((file) => file.url?.startsWith('/api/') ? <a key={file.path} href={buildApiUrl(file.url)} download={file.filename} className="mt-1 block underline">{file.filename}</a> : null)}+ </article>)}+ {cursor && <Button size="sm" variant="outline" onClick={() => void history(cursor).catch(() => setError('Could not load older tasks.'))}>Load older tasks</Button>}+ </div>}+ </>}+ {error && <p role="alert" className="mt-2 text-destructive">{error}</p>}+ </section>;+}diff --git a/client/src/components/browser/BrowserWorkspace.tsx b/client/src/components/browser/BrowserWorkspace.tsxindex 9368e271..0a3ef78c 100644--- a/client/src/components/browser/BrowserWorkspace.tsx+++ b/client/src/components/browser/BrowserWorkspace.tsx@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button';import { buildApiUrl } from '@/config/api';import { useWebSocketActions } from '@/contexts/WebSocketContext';import { browserModifiers, browserPoint, decodeBrowserFrame, type BrowserFrameHeader } from './protocol';+import BrowserTasks from './BrowserTasks';export interface BrowserWorkspaceProps {workflowId?: string | null;@@ -16,6 +17,7 @@ type Phase = 'connecting' | 'idle' | 'live' | 'error';interface BrowserState {state: string;challenge_required?: boolean;+ sensitive_login?: boolean;controller?: string | null;request?: { message?: string; reason?: string } | null;}@@ -35,6 +37,7 @@ export default function BrowserWorkspace({ workflowId, nodes, visible = true }:</select>)}<BrowserSessionView key={`${workflowId}:${nodeId}`} workflowId={workflowId} nodeId={nodeId} visible={visible} />+ <BrowserTasks key={`tasks:${workflowId}:${nodeId}`} workflowId={workflowId} browserNodeId={nodeId} visible={visible} /></div>);}@@ -63,6 +66,7 @@ function BrowserSessionView({ workflowId, nodeId, visible }: { workflowId: strinconst [address, setAddress] = useState('');const [hasFrame, setHasFrame] = useState(false);const [starting, setStarting] = useState(false);+ const [stopping, setStopping] = useState(false);const [installing, setInstalling] = useState(false);const [attempt, setAttempt] = useState(0);const [dialog, setDialog] = useState<{ kind: string; message: string } | null>(null);@@ -126,6 +130,10 @@ function BrowserSessionView({ workflowId, nodeId, visible }: { workflowId: strinif (message.type === 'page') setAddress(message.url || '');if (message.type === 'tabs') setTabs(message.tabs || []);if (message.type === 'dialog') { setDialog(message); setPromptText(''); }+ if (message.type === 'sensitive') {+ streamEpoch += 1; setHasFrame(false); frameRef.current = null; setDialog(null); setTabs([]); setAddress('');+ setState((previous) => ({ ...previous, sensitive_login: !!message.enabled }));+ }if (message.type === 'error') {setError(message.message || 'Browser request failed.', message.code === 'screencast');if (message.code === 'screencast' && message.retrying === false) {@@ -264,6 +272,19 @@ function BrowserSessionView({ workflowId, nodeId, visible }: { workflowId: strinif (mountedRef.current) setError(cause instanceof Error ? cause.message : 'Could not start the browser.');} finally { if (mountedRef.current) setStarting(false); }};+ const closeProtectedBrowser = async () => {+ setStopping(true); setError('');+ try {+ const result = await sendRequest<{ success: boolean; error?: string }>('browser_session_stop', { workflow_id: workflowId, node_id: nodeId }, 60_000);+ if (!result.success) throw new Error(result.error || 'Could not close the browser.');+ if (mountedRef.current) {+ setHasFrame(false); frameRef.current = null; setTabs([]); setAddress(''); setDialog(null);+ setState({ state: 'idle' }); setPhase('idle');+ }+ } catch (cause) {+ if (mountedRef.current) setError(cause instanceof Error ? cause.message : 'Could not close the browser.');+ } finally { if (mountedRef.current) setStopping(false); }+ };const point = (clientX: number, clientY: number) => {const rect = surfaceRef.current?.getBoundingClientRect(); const frame = frameRef.current;return rect && frame ? browserPoint(clientX - rect.left, clientY - rect.top, rect.width, rect.height, frame.width, frame.height, frame.header) : null;@@ -316,7 +337,7 @@ function BrowserSessionView({ workflowId, nodeId, visible }: { workflowId: strinreturn (<FullView label="Browser" toolbar={<><span role="status" className="min-w-0 flex-1 truncate text-xs text-fg-muted" title={statusLabel}>{installing ? 'Installing browser…' : starting ? 'Starting browser…' : statusLabel}</span>- {phase === 'live' && <Button size="sm" variant="outline" disabled={takingControl} onClick={() => {+ {phase === 'live' && !state.sensitive_login && <Button size="sm" variant="outline" disabled={takingControl} onClick={() => {setError('');if (control) send({ type: 'control_release' });else { setTakingControl(true); send({ type: 'control_request', ...(state.controller === 'other' ? { force: true } : {}) }); }@@ -343,7 +364,8 @@ function BrowserSessionView({ workflowId, nodeId, visible }: { workflowId: strinonCompositionEnd={(e) => { if (control && e.data) send({ type: 'insert_text', text: e.data }); }}><canvas ref={canvasRef} aria-label="Browser screenshot" className="absolute inset-0 h-full w-full object-contain" style={{ visibility: hasFrame ? 'visible' : 'hidden' }} />{!hasFrame && <div className="relative flex max-w-80 flex-col items-center gap-3 p-6 text-center text-sm text-fg-muted"><Globe aria-hidden className="size-6" />- <span>{phase === 'live' ? 'Waiting for the browser picture…' : phase === 'idle' ? 'The browser will appear when the employee uses it. You can also open it now.' : statusLabel}</span>+ <span>{state.sensitive_login ? 'Browser observations are paused during protected login.' : phase === 'live' ? 'Waiting for the browser picture…' : phase === 'idle' ? 'The browser will appear when the employee uses it. You can also open it now.' : statusLabel}</span>+ {state.sensitive_login && <Button variant="outline" disabled={stopping || !isReady} onClick={() => void closeProtectedBrowser()}>{stopping ? 'Closing…' : 'Close browser for manual login'}</Button>}{phase === 'idle' && <Button variant="outline" disabled={starting || installing || !isReady} onClick={() => void start()}>{starting ? 'Starting…' : installing ? 'Installing…' : 'Start browser'}</Button>}{phase === 'error' && <Button variant="outline" onClick={() => setAttempt((n) => n + 1)}>Reconnect</Button>}</div>}diff --git a/client/src/components/browser/__tests__/BrowserTasks.test.tsx b/client/src/components/browser/__tests__/BrowserTasks.test.tsxnew file mode 100644index 00000000..d0eb6df8--- /dev/null+++ b/client/src/components/browser/__tests__/BrowserTasks.test.tsx@@ -0,0 +1,60 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const { createAgent, adopt } = vi.hoisted(() => ({ createAgent: vi.fn(), adopt: vi.fn() }));+vi.mock('@/services/browserAgentApi', () => ({ createBrowserAgent: createAgent }));+vi.mock('@/store/useAppStore', () => ({ useAppStore: { getState: () => ({ adoptSavedOperations: adopt }) } }));+import BrowserTasks from '../BrowserTasks';++const task = { invocation_id: 'inv', submission_id: 'sub', node_id: 'agent', prompt: 'Read my account', status: 'running' };+const response = (body: unknown, ok = true) => ({ ok, json: async () => body });+let fetchMock: ReturnType<typeof vi.fn>;++beforeEach(() => {+ createAgent.mockReset(); adopt.mockReset();+ fetchMock = vi.fn(async (url: string) => response(url.includes('discovery') ? { agents: [{ node_id: 'agent', label: 'Browser AI Agent' }] } : { items: [task], next_cursor: null }));+ vi.stubGlobal('fetch', fetchMock);+});+afterEach(() => vi.unstubAllGlobals());++describe('direct Browser tasks', () => {+ it('submits through Workspace admission and shows isolated recent history', async () => {+ render(<BrowserTasks workflowId="wf" browserNodeId="browser" visible />);+ fireEvent.change(await screen.findByLabelText('Browser task'), { target: { value: 'Read my account' } });+ fireEvent.click(screen.getByRole('button', { name: 'Run task' }));+ await waitFor(() => expect(fetchMock.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(true));+ const [, init] = fetchMock.mock.calls.find(([, init]) => init?.method === 'POST')!;+ expect(JSON.parse(init.body)).toMatchObject({ workflow_id: 'wf', agent_node_id: 'agent', prompt: 'Read my account' });+ expect(screen.getByText('Read my account')).toBeInTheDocument();+ expect(screen.getByLabelText('Browser task')).toHaveValue('');+ });+ it('reuses the submission ID when a response is lost', async () => {+ const submitted: string[] = [];+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) => {+ if (init?.method === 'POST') { submitted.push(JSON.parse(init.body as string).submission_id); if (submitted.length === 1) throw new Error('Connection lost'); return response({ status: 'accepted' }); }+ return response(url.includes('discovery') ? { agents: [{ node_id: 'agent', label: 'Agent' }] } : { items: [], next_cursor: null });+ });+ render(<BrowserTasks workflowId="wf" browserNodeId="browser" visible />);+ fireEvent.change(await screen.findByLabelText('Browser task'), { target: { value: 'Read an issue' } });+ fireEvent.click(screen.getByRole('button', { name: 'Run task' }));+ await screen.findByRole('alert');+ fireEvent.click(screen.getByRole('button', { name: 'Run task' }));+ await waitFor(() => expect(submitted).toHaveLength(2));+ expect(submitted[0]).toBe(submitted[1]);+ });+ it('cancels the admitted task by its server identity', async () => {+ render(<BrowserTasks workflowId="wf" browserNodeId="browser" visible />);+ await screen.findByLabelText('Browser task');+ fireEvent.click(screen.getByRole('button', { name: /Recent tasks/ }));+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel task' }));+ await waitFor(() => expect(fetchMock.mock.calls.some(([url, init]) => url.includes('/tasks/sub?') && init?.method === 'DELETE')).toBe(true));+ });+ it('adds the agent through the shared saved-graph recipe', async () => {+ fetchMock.mockResolvedValue(response({ agents: [] }));+ createAgent.mockResolvedValue({ node_ids: { agent: 'new' }, operations: ['saved-operation'] });+ render(<BrowserTasks workflowId="wf" browserNodeId="browser" visible />);+ fireEvent.click(await screen.findByRole('button', { name: 'Add Browser AI Agent' }));+ await waitFor(() => expect(createAgent).toHaveBeenCalledWith({ workflow_id: 'wf', browser_node_id: 'browser' }));+ expect(adopt).toHaveBeenCalledWith('wf', ['saved-operation']);+ });+});diff --git a/client/src/components/browser/__tests__/BrowserWorkspace.test.tsx b/client/src/components/browser/__tests__/BrowserWorkspace.test.tsxindex f6230920..c65ed379 100644--- a/client/src/components/browser/__tests__/BrowserWorkspace.test.tsx+++ b/client/src/components/browser/__tests__/BrowserWorkspace.test.tsx@@ -248,4 +248,18 @@ describe('browser frame and input lifecycle boundaries', () => {await act(async () => loads[1]());expect(socket.sent.filter((m) => m.type === 'ack')).toHaveLength(10);});+ it('discards a pending picture during protected login and exposes authorized close for manual recovery', async () => {+ const { frame, loads, draw } = mockFrameRenderer(true);+ render(<BrowserWorkspace workflowId="wf" nodes={nodes} />);+ const socket = MockSocket.instances[0];+ act(() => { socket.open(); socket.message({ type: 'state', state: 'agent' }); socket.onmessage?.({ data: frame.buffer }); });+ await waitFor(() => expect(loads).toHaveLength(1));+ act(() => socket.message({ type: 'sensitive', enabled: true }));+ await act(async () => loads[0]());+ expect(draw).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: 'Take control' })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Close browser for manual login' }));+ await waitFor(() => expect(actions.sendRequest).toHaveBeenCalledWith('browser_session_stop', { workflow_id: 'wf', node_id: 'browser-1' }, 60_000));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Start browser' })).toBeInTheDocument());+ });});diff --git a/client/src/components/credentials/PanelRenderer.tsx b/client/src/components/credentials/PanelRenderer.tsxindex 09b0dab5..1a001494 100644--- a/client/src/components/credentials/PanelRenderer.tsx+++ b/client/src/components/credentials/PanelRenderer.tsx@@ -85,6 +85,10 @@ const PanelRenderer: React.FC<Props> = ({ config, visible, showTechnicalSections);}+ if (config.unsupportedReason) {+ return <EmptyState icon={<AlertTriangle className="h-8 w-8 text-warning" />} message={config.unsupportedReason} />;+ }+return (<Suspense fallback={<PanelFallback />}>{/* Provider identity resets transient errors/reveal state. Mode changesdiff --git a/client/src/components/credentials/catalogueAdapter.ts b/client/src/components/credentials/catalogueAdapter.tsindex ef58676a..ecc14d3e 100644--- a/client/src/components/credentials/catalogueAdapter.ts+++ b/client/src/components/credentials/catalogueAdapter.ts@@ -177,6 +177,9 @@ export function rehydrateProvider(entry: ServerProviderConfig): ProviderConfig {stored: entry.stored,account_label: entry.account_label ?? null,endpoints: entry.endpoints,+ sourceSupported: entry.sourceSupported,+ sourceRequired: entry.sourceRequired,+ unsupportedReason: entry.unsupported_reason,};}diff --git a/client/src/components/credentials/panels/ApiKeyPanel.tsx b/client/src/components/credentials/panels/ApiKeyPanel.tsxindex 9029f15f..85b5efc8 100644--- a/client/src/components/credentials/panels/ApiKeyPanel.tsx+++ b/client/src/components/credentials/panels/ApiKeyPanel.tsx@@ -3,7 +3,7 @@* Composes: Card header + ApiKeyInput. Config-driven, zero per-provider JSX.*/-import React from 'react';+import React, { useEffect, useState } from 'react';import { CheckCircle } from 'lucide-react';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';@@ -21,6 +21,9 @@ import { CREDENTIAL_PROBE_REQUEST_TIMEOUT } from '@/contexts/WebSocketContext';import type { ServerEndpointSummary } from '@/hooks/useCatalogueQuery';import type { CredentialPanelProps } from '../PanelRenderer';import EndpointList from './EndpointList';+import OnePasswordField from './OnePasswordField';+import OnePasswordSetup from './OnePasswordSetup';+import { Button } from '@/components/ui/button';const ApiKeyPanel: React.FC<CredentialPanelProps> = ({config,@@ -48,6 +51,9 @@ const ApiKeyPanel: React.FC<CredentialPanelProps> = ({// defaults do NOT flip it to true.const validated = endpoints ? Boolean(config.stored) : panel.stored;const busy = panel.loading !== null;+ const [sourceMode, setSourceMode] = useState<'local' | 'onepassword'>(config.sourceRequired ? 'onepassword' : 'local');+ const source = panel.sources?.[field?.key ?? 'apiKey'];+ useEffect(() => { if (source || config.sourceRequired) setSourceMode('onepassword'); }, [source, config.sourceRequired]);// Every field goes out under its catalogue key; the backend Credential// decides what each means. A rejected save carries its reason in@@ -66,6 +72,15 @@ const ApiKeyPanel: React.FC<CredentialPanelProps> = ({}};const refreshEndpoint = async (endpoint: ServerEndpointSummary) => {+ const stored = await panel.actions.sendWs('get_stored_api_key', { provider: endpoint.ref });+ if (stored?.credentialSource?.source === 'onepassword') {+ const res = await panel.actions.sendWs('onepassword_endpoint_validate', {+ provider: endpoint.ref, reference: stored.credentialSource.reference,+ base_url: stored.credentialSource.base_url, label: endpoint.label,+ }, CREDENTIAL_PROBE_REQUEST_TIMEOUT);+ if (!res?.valid) panel.setError(res?.error || 'Could not refresh the 1Password endpoint.');+ return;+ }const res = await panel.actions.sendWs('validate_api_key', {provider: config.id,api_key: endpoint.base_url || endpoint.ref,@@ -109,10 +124,19 @@ const ApiKeyPanel: React.FC<CredentialPanelProps> = ({)}</CardHeader><CardContent>+ {config.sourceSupported && <div className="mb-4 flex gap-2">+ {!config.sourceRequired && <Button variant={sourceMode === 'local' ? 'secondary' : 'ghost'} size="sm" onClick={() => setSourceMode('local')}>Local credential</Button>}+ <Button variant={sourceMode === 'onepassword' ? 'secondary' : 'ghost'} size="sm" onClick={() => setSourceMode('onepassword')}>1Password</Button>+ </div>}{endpoints && config.instructions && (<p className="text-xs text-muted-foreground">{config.instructions}</p>)}- {field && !endpoints && (+ {sourceMode === 'onepassword' && config.sourceSupported && <>+ <OnePasswordSetup visible={visible} />+ <OnePasswordField provider={config.id} saved={source} endpoint={Boolean(endpoints)} onError={panel.setError} onSaved={() => panel.setStored(true)} />+ </>}+ {sourceMode === 'onepassword' && source && !endpoints && <Button className="mt-3" variant="ghost" size="sm" onClick={() => panel.actions.remove(config.id)}>Remove 1Password binding</Button>}+ {field && !endpoints && sourceMode === 'local' && (<ApiKeyInputvalue={inputValue}onChange={(v) => panel.form.setFieldValue(field.key, v)}@@ -159,7 +183,7 @@ const ApiKeyPanel: React.FC<CredentialPanelProps> = ({path because these are operator metadata, not credentialsto probe upstream. Save writes via the same auth_servicepath the primary uses (panel.actions.save). */}- {(endpoints ? config.fields ?? [] : secondaryFields).map((sf) => (+ {(endpoints && sourceMode !== 'local' ? [] : endpoints ? config.fields ?? [] : secondaryFields).map((sf) => (<SecondaryFieldRowkey={sf.key}fieldKey={sf.key}@@ -176,11 +200,11 @@ const ApiKeyPanel: React.FC<CredentialPanelProps> = ({{endpoints && (<>- <div className="flex justify-end">+ {sourceMode === 'local' && <div className="flex justify-end"><ActionButton intent="save" onClick={addEndpoint} disabled={busy || !inputValue.trim()}>Add endpoint</ActionButton>- </div>+ </div>}<EndpointList endpoints={endpoints} busy={busy} onRefresh={refreshEndpoint} onRemove={removeEndpoint} /></>)}diff --git a/client/src/components/credentials/panels/BrowserLoginBindings.tsx b/client/src/components/credentials/panels/BrowserLoginBindings.tsxnew file mode 100644index 00000000..c15b7dce--- /dev/null+++ b/client/src/components/credentials/panels/BrowserLoginBindings.tsx@@ -0,0 +1,147 @@+import React, { useId, useState } from 'react';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { Loader2, Trash2 } from 'lucide-react';+import { ActionButton } from '@/components/ui/action-button';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import {+ AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,+ AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { useWebSocketActions } from '@/contexts/WebSocketContext';+import OnePasswordSetup from './OnePasswordSetup';++interface Binding {+ id: string; label: string; origin: string;+ profile_id?: string | null; employee_id?: string | null; workflow_id?: string | null;+ success_origin: string; success_path: string; success_selector?: string;+}+interface Values {+ label: string; origin: string; username_reference: string; password_reference: string;+ success_origin: string; success_path: string; success_selector: string; profile_id: string;+}+type Draft = Values & { binding_id?: string; employee_id?: string | null; workflow_id?: string | null };+interface Result { success?: boolean; error?: string }+const QUERY_KEY = ['browserCredentialBindings'];+const empty = (): Draft => ({ label: '', origin: '', username_reference: '', password_reference: '',+ success_origin: '', success_path: '', success_selector: '', profile_id: '' });+const fields: { key: keyof Values; label: string; placeholder?: string; maxLength: number; required?: boolean; type?: string }[] = [+ { key: 'label', label: 'Login label', placeholder: 'Work account', maxLength: 128, required: true },+ { key: 'origin', label: 'Exact login origin', placeholder: 'https://accounts.example.com', maxLength: 2048, required: true, type: 'url' },+ { key: 'username_reference', label: 'Username 1Password reference', placeholder: 'op://vault-ID/item-ID/username', maxLength: 512, required: true },+ { key: 'password_reference', label: 'Password 1Password reference', placeholder: 'op://vault-ID/item-ID/password', maxLength: 512, required: true },+ { key: 'success_origin', label: 'Successful login origin (optional)', placeholder: 'Defaults to login origin', maxLength: 2048, type: 'url' },+ { key: 'success_path', label: 'Successful login path', placeholder: '/account', maxLength: 1024, required: true },+ { key: 'success_selector', label: 'Successful login selector (optional)', placeholder: '[data-account-menu]', maxLength: 512 },+];++/** Saved rows contain only metadata. A replacement always takes fresh references. */+export default function BrowserLoginBindings({ visible, profiles }: {+ visible: boolean; profiles: { id: string; name: string }[];+}) {+ const { sendRequest, isReady } = useWebSocketActions();+ const queryClient = useQueryClient();+ const id = useId();+ const [draft, setDraft] = useState<Draft | null>(null);+ const [doomed, setDoomed] = useState<Binding | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const bindings = useQuery({+ queryKey: QUERY_KEY,+ queryFn: async () => {+ const result = await sendRequest<Result & { bindings?: Binding[] }>('browser_credential_bindings_list');+ if (result.success === false) throw new Error(result.error || 'Could not load website logins.');+ return result.bindings ?? [];+ },+ enabled: isReady && visible, staleTime: 0, refetchOnMount: 'always',+ });+ const change = async (command: string, data: Record<string, unknown>): Promise<boolean> => {+ setBusy(true); setError('');+ try {+ const result = await sendRequest<Result>(command, data);+ if (result.success === false) throw new Error(result.error || 'Could not save this change.');+ await queryClient.invalidateQueries({ queryKey: QUERY_KEY });+ await queryClient.invalidateQueries({ queryKey: ['credentialCatalogue'] });+ return true;+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : 'Could not save this change.');+ return false;+ } finally { setBusy(false); }+ };+ const save = async (event: React.FormEvent) => {+ event.preventDefault();+ if (!draft || busy || !isReady) return;+ if (await change('browser_credential_binding_save', {+ ...draft, label: draft.label.trim(),+ success_origin: draft.success_origin || draft.origin,+ profile_id: draft.profile_id || null,+ })) setDraft(null);+ };+ const replace = (binding: Binding) => {+ setError('');+ setDraft({ ...empty(), binding_id: binding.id, label: binding.label, origin: binding.origin,+ profile_id: binding.profile_id || '', employee_id: binding.employee_id, workflow_id: binding.workflow_id,+ success_origin: binding.success_origin, success_path: binding.success_path, success_selector: binding.success_selector || '' });+ };++ return <section aria-label="1Password website logins" className="flex flex-col gap-3 border-t border-border pt-4">+ <div className="flex items-center justify-between gap-3">+ <h3 className="m-0 text-sm font-medium">1Password website logins</h3>+ {!draft && <ActionButton intent="secret" disabled={!isReady || busy} onClick={() => { setError(''); setDraft(empty()); }}>Add website login</ActionButton>}+ </div>+ <p className="m-0 text-xs text-muted-foreground">Save username and password field references using vault and item IDs. The browser reads credentials privately when an approved login needs them. Multi-step login and MFA use Take control.</p>+ <OnePasswordSetup visible={visible} />+ {!isReady ? <p className="m-0 text-xs text-muted-foreground">Reconnect to manage website logins.</p>+ : bindings.isPending ? <Loader2 aria-label="Loading website logins" className="size-4 animate-spin text-muted-foreground" />+ : bindings.isError ? <p role="alert" className="m-0 text-sm text-destructive">{bindings.error.message}</p>+ : (bindings.data ?? []).length === 0 ? <p className="m-0 text-xs text-muted-foreground">No website login bindings saved.</p>+ : <ul className="m-0 flex list-none flex-col gap-2 p-0">{bindings.data?.map((binding) => <li key={binding.id} className="flex flex-wrap items-center gap-3 rounded-md border border-border bg-card p-3">+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium">{binding.label}</span>+ <span className="truncate text-xs text-muted-foreground">{binding.origin}</span>+ {binding.profile_id && <span className="text-xs text-muted-foreground">Profile: {profiles.find((profile) => profile.id === binding.profile_id)?.name || 'Saved profile'}</span>}+ {(binding.employee_id || binding.workflow_id) && <span className="text-xs text-muted-foreground">Restricted to its saved employee or workflow.</span>}+ </div>+ <Button variant="outline" size="sm" disabled={busy || !isReady} aria-label={`Replace ${binding.label}`} onClick={() => replace(binding)}>Replace references</Button>+ <Button variant="ghost" size="icon-sm" disabled={busy || !isReady} aria-label={`Remove website login ${binding.label}`} onClick={() => setDoomed(binding)}><Trash2 aria-hidden /></Button>+ </li>)}</ul>}++ {draft && <form onSubmit={(event) => void save(event)} className="rounded-md border border-border p-3">+ <fieldset disabled={busy || !isReady} className="m-0 flex min-w-0 flex-col gap-3 border-0 p-0">+ <legend className="mb-3 text-sm font-medium">{draft.binding_id ? 'Replace website login' : 'Add website login'}</legend>+ {draft.binding_id && <p className="m-0 text-xs text-muted-foreground">Enter both references again. Saved reference fields are kept private.</p>}+ {fields.map((field) => <div key={field.key} className="flex flex-col gap-2">+ <Label htmlFor={`${id}-${field.key}`}>{field.label}</Label>+ <Input id={`${id}-${field.key}`} type={field.type || 'text'} value={draft[field.key]}+ onChange={(event) => setDraft({ ...draft, [field.key]: event.target.value })}+ required={field.required} maxLength={field.maxLength} placeholder={field.placeholder} autoComplete="off" spellCheck={false} />+ </div>)}+ <p className="m-0 text-xs text-muted-foreground">Origins use only the scheme and host, plus a port when needed. The success path is exact and excludes queries and fragments.</p>+ <div className="flex flex-col gap-2">+ <Label htmlFor={`${id}-profile`}>Restrict to browser profile (optional)</Label>+ <select id={`${id}-profile`} value={draft.profile_id} onChange={(event) => setDraft({ ...draft, profile_id: event.target.value })}+ className="h-9 rounded-md border border-input bg-transparent px-3 text-sm">+ <option value="">All my browser profiles</option>+ {draft.profile_id && !profiles.some((profile) => profile.id === draft.profile_id) && <option value={draft.profile_id}>Saved profile</option>}+ {profiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name}</option>)}+ </select>+ </div>+ <div className="flex gap-2">+ <ActionButton intent="secret" type="submit" disabled={!draft.label.trim() || !draft.origin || !draft.username_reference || !draft.password_reference || !draft.success_path}>{busy ? 'Saving…' : 'Save website login'}</ActionButton>+ <Button variant="ghost" onClick={() => { setDraft(null); setError(''); }}>Cancel</Button>+ </div>+ </fieldset>+ </form>}+ {error && <p role="alert" className="m-0 text-sm text-destructive">{error}</p>}+ <AlertDialog open={doomed !== null} onOpenChange={(open) => !open && setDoomed(null)}>+ <AlertDialogContent>+ <AlertDialogHeader><AlertDialogTitle>Remove {doomed?.label}?</AlertDialogTitle><AlertDialogDescription>Its saved reference association is removed from OpenCompany. Future browser tasks will need another login binding.</AlertDialogDescription></AlertDialogHeader>+ <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => {+ const binding = doomed; setDoomed(null);+ if (binding) void change('browser_credential_binding_delete', { binding_id: binding.id });+ }}>Remove login</AlertDialogAction></AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </section>;+}diff --git a/client/src/components/credentials/panels/BrowserProfilesPanel.tsx b/client/src/components/credentials/panels/BrowserProfilesPanel.tsxindex f29d769c..64f9d1c6 100644--- a/client/src/components/credentials/panels/BrowserProfilesPanel.tsx+++ b/client/src/components/credentials/panels/BrowserProfilesPanel.tsx@@ -31,6 +31,7 @@ import { Input } from '@/components/ui/input';import { buildApiUrl } from '@/config/api';import { useWebSocketActions } from '@/contexts/WebSocketContext';import type { ProviderConfig } from '../types';+import BrowserLoginBindings from './BrowserLoginBindings';interface BrowserSite {domain: string;@@ -191,6 +192,8 @@ const BrowserProfilesPanel: React.FC<{ config: ProviderConfig; visible: boolean</ul>)}+ <BrowserLoginBindings visible={visible} profiles={list} />+<inputref={fileInput}type="file"diff --git a/client/src/components/credentials/panels/OnePasswordField.tsx b/client/src/components/credentials/panels/OnePasswordField.tsxnew file mode 100644index 00000000..d8b57527--- /dev/null+++ b/client/src/components/credentials/panels/OnePasswordField.tsx@@ -0,0 +1,61 @@+import { useEffect, useState } from 'react';+import { useQueryClient } from '@tanstack/react-query';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { ActionButton } from '@/components/ui/action-button';+import { useWebSocket } from '@/contexts/WebSocketContext';+import { CREDENTIAL_PROBE_REQUEST_TIMEOUT } from '@/contexts/WebSocketContext';+import { queryKeys } from '@/lib/queryConfig';+import type { SavedCredentialSource } from '../useCredentialPanel';++/** References are operator configuration. Resolved values never reach this form. */+export default function OnePasswordField({ provider, saved, endpoint = false, onError, onSaved }: {+ provider: string;+ saved?: SavedCredentialSource;+ endpoint?: boolean;+ onError: (message: string) => void;+ onSaved: () => void;+}) {+ const { sendRequest } = useWebSocket();+ const queryClient = useQueryClient();+ const [reference, setReference] = useState(saved?.reference ?? '');+ const [slug, setSlug] = useState('');+ const [baseUrl, setBaseUrl] = useState('');+ const [busy, setBusy] = useState(false);+ useEffect(() => setReference(saved?.reference ?? ''), [saved?.reference]);+ const validate = async () => {+ setBusy(true);+ try {+ const result = await sendRequest<{ success?: boolean; valid?: boolean; error?: string; message?: string }>(+ endpoint ? 'onepassword_endpoint_validate' : 'validate_api_key',+ endpoint+ ? { provider: `openai_compatible:${slug}`, reference, base_url: baseUrl, label: slug }+ : { provider, credential_source: 'onepassword', reference },+ CREDENTIAL_PROBE_REQUEST_TIMEOUT,+ );+ if (result.valid) {+ onSaved();+ await queryClient.invalidateQueries({ queryKey: queryKeys.credentialValues.byProvider(provider).queryKey });+ await queryClient.invalidateQueries({ queryKey: ['credentialCatalogue'] });+ if (endpoint) { setReference(''); setSlug(''); setBaseUrl(''); }+ } else onError(result.error || result.message || 'Could not validate the 1Password binding.');+ } catch (error) {+ onError(error instanceof Error ? error.message : 'Could not validate the binding.');+ } finally { setBusy(false); }+ };+ return <div className="flex flex-col gap-3">+ <p className="text-xs text-muted-foreground">Authorize 1Password on this runtime. OpenCompany saves the reference and reads the field only when needed.</p>+ {endpoint && <>+ <Label htmlFor={`op-slug-${provider}`}>Endpoint name</Label>+ <Input id={`op-slug-${provider}`} value={slug} onChange={(event) => setSlug(event.target.value)} placeholder="my-model-server" />+ <Label htmlFor={`op-url-${provider}`}>Base URL</Label>+ <Input id={`op-url-${provider}`} value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} placeholder="https://models.example.com/v1" />+ </>}+ <Label htmlFor={`op-ref-${provider}`}>1Password field reference</Label>+ <Input id={`op-ref-${provider}`} value={reference} onChange={(event) => setReference(event.target.value)} placeholder="op://vault-ID/item-ID/field" autoComplete="off" />+ <p className="text-xs text-muted-foreground">Use vault and item IDs. Passwords and API keys stay out of the form.</p>+ <ActionButton intent="secret" disabled={busy || !reference || (endpoint && (!slug || !baseUrl))} onClick={validate}>+ {busy ? 'Validating…' : endpoint ? 'Add 1Password endpoint' : 'Validate 1Password binding'}+ </ActionButton>+ </div>;+}diff --git a/client/src/components/credentials/panels/OnePasswordSetup.tsx b/client/src/components/credentials/panels/OnePasswordSetup.tsxnew file mode 100644index 00000000..d1a34db8--- /dev/null+++ b/client/src/components/credentials/panels/OnePasswordSetup.tsx@@ -0,0 +1,39 @@+import { useState } from 'react';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useWebSocketActions } from '@/contexts/WebSocketContext';+import { Button } from '@/components/ui/button';++type Status = { available?: boolean; error?: string; version?: string; auth_mode?: string; success?: boolean };++/** Installation/version checks never read a field or trigger vault authorization. */+export default function OnePasswordSetup({ visible = true }: { visible?: boolean }) {+ const { sendRequest, isReady } = useWebSocketActions();+ const queryClient = useQueryClient();+ const [installing, setInstalling] = useState(false);+ const [error, setError] = useState('');+ const status = useQuery({+ queryKey: ['onepasswordStatus'],+ queryFn: () => sendRequest<Status>('onepassword_status'),+ enabled: visible && isReady,+ staleTime: 30_000,+ retry: false,+ });+ const install = async () => {+ setInstalling(true); setError('');+ try {+ const result = await sendRequest<Status>('onepassword_install', {}, 180_000);+ if (!result.available) setError(result.error || 'Could not install the verified CLI.');+ await queryClient.invalidateQueries({ queryKey: ['onepasswordStatus'] });+ } catch (failure) { setError(failure instanceof Error ? failure.message : 'Could not install the CLI.'); }+ finally { setInstalling(false); }+ };+ return <div className="mb-3 flex flex-col gap-2 text-xs text-muted-foreground">+ {status.data?.available+ ? <p>1Password CLI {status.data.version} · {status.data.auth_mode === 'service_account' ? 'Service account' : 'Desktop authorization'}</p>+ : <><p>{status.data?.error || 'Checking 1Password CLI…'}</p>+ <Button variant="outline" size="sm" disabled={installing || !isReady} onClick={install}>{installing ? 'Installing…' : 'Install verified CLI'}</Button>+ </>}+ {error && <p role="alert" className="text-destructive">{error}</p>}+ <a className="underline" href="https://www.1password.dev/cli/get-started" target="_blank" rel="noreferrer">Configure 1Password authorization</a>+ </div>;+}diff --git a/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsx b/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsxnew file mode 100644index 00000000..9c5081be--- /dev/null+++ b/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsx@@ -0,0 +1,113 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';++const mocks = vi.hoisted(() => ({ sendRequest: vi.fn(), ready: true }));+vi.mock('@/contexts/WebSocketContext', () => ({+ useWebSocketActions: () => ({ sendRequest: mocks.sendRequest, isReady: mocks.ready }),+}));++import BrowserLoginBindings from '../BrowserLoginBindings';++const username = `op://${'a'.repeat(26)}/${'b'.repeat(26)}/username`;+const password = `op://${'a'.repeat(26)}/${'b'.repeat(26)}/password`;+const binding = { id: 'login-1', label: 'Account', origin: 'https://accounts.example.com',+ profile_id: 'work', employee_id: 'employee-1', workflow_id: 'workflow-1',+ success_origin: 'https://app.example.com', success_path: '/account', success_selector: '[data-account]' };++function mount(visible = true) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ const element = (shown: boolean) => <QueryClientProvider client={client}><BrowserLoginBindings visible={shown} profiles={[{ id: 'work', name: 'Work' }]} /></QueryClientProvider>;+ const view = render(element(visible));+ return { client, change: (shown: boolean) => view.rerender(element(shown)) };+}++beforeEach(() => {+ mocks.ready = true;+ mocks.sendRequest.mockReset();+ mocks.sendRequest.mockImplementation(async (command: string) => command === 'browser_credential_bindings_list' ? { bindings: [] } : {});+});++async function fillReferences(user: ReturnType<typeof userEvent.setup>) {+ await user.type(screen.getByLabelText('Username 1Password reference'), username);+ await user.type(screen.getByLabelText('Password 1Password reference'), password);+}++describe('BrowserLoginBindings', () => {+ it('lists metadata and replaces references without retrieving or prefilling saved credentials', async () => {+ mocks.sendRequest.mockImplementation(async (command: string) => command === 'browser_credential_bindings_list'+ ? { bindings: [{ ...binding, username_reference: 'PRIVATE-REF', password_reference: 'SECRET-CANARY' }] } : {});+ const user = userEvent.setup();+ mount();+ expect(await screen.findByText('Account')).toBeInTheDocument();+ expect(screen.getByText('Profile: Work')).toBeInTheDocument();+ expect(screen.queryByText('SECRET-CANARY')).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Replace Account' }));+ expect(screen.getByLabelText('Username 1Password reference')).toHaveValue('');+ expect(screen.getByLabelText('Password 1Password reference')).toHaveValue('');+ expect(screen.getByRole('button', { name: 'Save website login' })).toBeDisabled();+ await fillReferences(user);+ await user.click(screen.getByRole('button', { name: 'Save website login' }));+ await waitFor(() => expect(mocks.sendRequest).toHaveBeenCalledWith('browser_credential_binding_save', {+ binding_id: 'login-1', label: 'Account', origin: binding.origin, username_reference: username, password_reference: password,+ success_origin: binding.success_origin, success_path: binding.success_path, success_selector: binding.success_selector,+ profile_id: 'work', employee_id: 'employee-1', workflow_id: 'workflow-1',+ }));+ await waitFor(() => expect(screen.queryByLabelText('Password 1Password reference')).not.toBeInTheDocument());+ expect(mocks.sendRequest.mock.calls.every(([command]) => !['get_api_key', 'validate_api_key', 'onepassword_endpoint_validate'].includes(command))).toBe(true);+ });++ it('creates an exact-origin binding with an optional profile and refreshes metadata', async () => {+ const user = userEvent.setup();+ const { client } = mount();+ const invalidate = vi.spyOn(client, 'invalidateQueries');+ await screen.findByText('No website login bindings saved.');+ await user.click(screen.getByRole('button', { name: 'Add website login' }));+ await user.type(screen.getByLabelText('Login label'), ' Work account ');+ await user.type(screen.getByLabelText('Exact login origin'), binding.origin);+ await fillReferences(user);+ await user.type(screen.getByLabelText('Successful login path'), '/dashboard');+ await user.type(screen.getByLabelText('Successful login selector (optional)'), '#signed-in');+ await user.selectOptions(screen.getByLabelText('Restrict to browser profile (optional)'), 'work');+ await user.click(screen.getByRole('button', { name: 'Save website login' }));+ await waitFor(() => expect(mocks.sendRequest).toHaveBeenCalledWith('browser_credential_binding_save', {+ label: 'Work account', origin: binding.origin, username_reference: username, password_reference: password,+ success_origin: binding.origin, success_path: '/dashboard', success_selector: '#signed-in', profile_id: 'work',+ }));+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ['browserCredentialBindings'] });+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ['credentialCatalogue'] });+ });++ it('requires confirmation before removing a binding and sends only its opaque ID', async () => {+ mocks.sendRequest.mockImplementation(async (command: string) => command === 'browser_credential_bindings_list' ? { bindings: [binding] } : {});+ const user = userEvent.setup();+ mount();+ await user.click(await screen.findByRole('button', { name: 'Remove website login Account' }));+ expect(mocks.sendRequest).not.toHaveBeenCalledWith('browser_credential_binding_delete', expect.anything());+ await user.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Remove login' }));+ await waitFor(() => expect(mocks.sendRequest).toHaveBeenCalledWith('browser_credential_binding_delete', { binding_id: 'login-1' }));+ });++ it('keeps the draft on a safe server validation failure', async () => {+ mocks.sendRequest.mockImplementation(async (command: string) => command === 'browser_credential_bindings_list'+ ? { bindings: [binding] } : { success: false, error: 'Use vault and item IDs.' });+ const user = userEvent.setup();+ mount();+ await user.click(await screen.findByRole('button', { name: 'Replace Account' }));+ await fillReferences(user);+ await user.click(screen.getByRole('button', { name: 'Save website login' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Use vault and item IDs.');+ expect(screen.getByLabelText('Password 1Password reference')).toHaveValue(password);+ expect(screen.getByRole('button', { name: 'Save website login' })).toBeEnabled();+ });++ it('does not load a hidden or disconnected panel', async () => {+ const view = mount(false);+ expect(mocks.sendRequest).not.toHaveBeenCalled();+ mocks.ready = false;+ view.change(true);+ expect(screen.getByRole('button', { name: 'Add website login' })).toBeDisabled();+ expect(mocks.sendRequest).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/credentials/panels/__tests__/OnePasswordField.test.tsx b/client/src/components/credentials/panels/__tests__/OnePasswordField.test.tsxnew file mode 100644index 00000000..bf69a7a1--- /dev/null+++ b/client/src/components/credentials/panels/__tests__/OnePasswordField.test.tsx@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';++const sendRequest = vi.fn();+vi.mock('@/contexts/WebSocketContext', () => ({ useWebSocket: () => ({ sendRequest }), CREDENTIAL_PROBE_REQUEST_TIMEOUT: 60_000 }));+import OnePasswordField from '../OnePasswordField';++const REF = `op://${'a'.repeat(26)}/${'b'.repeat(26)}/credential`;+const onSaved = vi.fn();+const onError = vi.fn();+function panel(endpoint = false, saved = false) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={client}><OnePasswordField provider={endpoint ? 'openai_compatible' : 'openai'} endpoint={endpoint} saved={saved ? { source: 'onepassword', reference: REF } : undefined} onSaved={onSaved} onError={onError} /></QueryClientProvider>);+}++describe('1Password credential enrollment', () => {+ beforeEach(() => { sendRequest.mockReset(); onSaved.mockReset(); onError.mockReset(); });+ it('loads saved references and submits no resolved API key', async () => {+ sendRequest.mockResolvedValue({ success: true, valid: true });+ panel(false, true);+ expect(screen.getByLabelText('1Password field reference')).toHaveValue(REF);+ await userEvent.click(screen.getByRole('button', { name: 'Validate 1Password binding' }));+ expect(sendRequest).toHaveBeenCalledWith('validate_api_key', { provider: 'openai', credential_source: 'onepassword', reference: REF }, 60_000);+ await waitFor(() => expect(onSaved).toHaveBeenCalledOnce());+ expect(screen.queryByDisplayValue('secret')).not.toBeInTheDocument();+ });+ it('keeps the reference and exposes a safe validation failure', async () => {+ sendRequest.mockResolvedValue({ success: false, valid: false, error: 'Authorize the runtime.' });+ panel(false, true);+ await userEvent.click(screen.getByRole('button', { name: 'Validate 1Password binding' }));+ expect(onError).toHaveBeenCalledWith('Authorize the runtime.');+ expect(onSaved).not.toHaveBeenCalled();+ expect(screen.getByLabelText('1Password field reference')).toHaveValue(REF);+ });+ it('enrolls a public endpoint with an ID reference and clears the add form', async () => {+ sendRequest.mockResolvedValue({ success: true, valid: true });+ panel(true);+ await userEvent.type(screen.getByLabelText('Endpoint name'), 'my-server');+ await userEvent.type(screen.getByLabelText('Base URL'), 'https://models.example.com/v1');+ await userEvent.type(screen.getByLabelText('1Password field reference'), REF);+ await userEvent.click(screen.getByRole('button', { name: 'Add 1Password endpoint' }));+ expect(sendRequest).toHaveBeenCalledWith('onepassword_endpoint_validate', { provider: 'openai_compatible:my-server', reference: REF, base_url: 'https://models.example.com/v1', label: 'my-server' }, 60_000);+ await waitFor(() => expect(screen.getByLabelText('1Password field reference')).toHaveValue(''));+ });+});diff --git a/client/src/components/credentials/types.ts b/client/src/components/credentials/types.tsindex 7281ee43..3a8f675e 100644--- a/client/src/components/credentials/types.ts+++ b/client/src/components/credentials/types.ts@@ -132,6 +132,10 @@ export interface ProviderConfig {* endpoints). Present only for such providers; the panel then adds rows* instead of storing one value. */endpoints?: ServerEndpointSummary[];+ /** Server capability, never inferred from a provider name. */+ sourceSupported?: boolean;+ sourceRequired?: boolean;+ unsupportedReason?: string;}// ============================================================================diff --git a/client/src/components/credentials/useCredentialPanel.ts b/client/src/components/credentials/useCredentialPanel.tsindex f939cb41..600cb29e 100644--- a/client/src/components/credentials/useCredentialPanel.ts+++ b/client/src/components/credentials/useCredentialPanel.ts@@ -25,6 +25,16 @@ import { queryKeys, STALE_TIME } from '../../lib/queryConfig';import type { ProviderConfig } from './types';export type CredentialFormValues = Record<string, string>;+export interface SavedCredentialSource {+ source: 'onepassword';+ reference: string;+ base_url?: string;+}+interface CredentialValues {+ values: CredentialFormValues;+ hadStored: boolean;+ sources?: Record<string, SavedCredentialSource>;+}const EMPTY_VALUES: CredentialFormValues = {};@@ -66,26 +76,28 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {// install. ``hadStored`` tracks the real server state separately so// the validated/connected badge stays honest — pre-filled defaults// do NOT flip it to true.- const credentialValuesQuery = useQuery<{ values: CredentialFormValues; hadStored: boolean }, Error>({+ const credentialValuesQuery = useQuery<CredentialValues, Error>({queryKey: queryKeys.credentialValues.byProvider(config.id).queryKey,queryFn: async () => {if (!config.fields) return { values: EMPTY_VALUES, hadStored: false };const results = await Promise.all(config.fields.map(async (field) => {const storeKey = field.key === 'apiKey' ? config.id : field.key;- const r = await sendRequest<{ hasKey: boolean; apiKey?: string }>(+ const r = await sendRequest<{ hasKey: boolean; apiKey?: string; credentialSource?: SavedCredentialSource }>('get_stored_api_key', { provider: storeKey },);- return { key: field.key, hasKey: r.hasKey, apiKey: r.apiKey };+ return { key: field.key, hasKey: r.hasKey, apiKey: r.apiKey, source: r.credentialSource };}),);const next: CredentialFormValues = {};let hadStored = false;+ const sources: Record<string, SavedCredentialSource> = {};for (const r of results) {if (r.apiKey) next[r.key] = r.apiKey;if (r.hasKey) hadStored = true;+ if (r.source) sources[r.key] = r.source;}- return { values: next, hadStored };+ return { values: next, hadStored, sources };},enabled: visible && isConnected && !!config.fields,staleTime: STALE_TIME.FOREVER,@@ -111,11 +123,12 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {// preserve `hadStored` verbatim.const writeValues = useCallback((updater: (prev: CredentialFormValues) => CredentialFormValues) => {- qc.setQueryData<{ values: CredentialFormValues; hadStored: boolean }>(+ qc.setQueryData<CredentialValues>(queryKeys.credentialValues.byProvider(providerKey).queryKey,(prev) => ({values: updater(prev?.values ?? EMPTY_VALUES),hadStored: prev?.hadStored ?? false,+ sources: prev?.sources,}),);},@@ -219,6 +232,7 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {return {form, values, loading, error, stored, setStored, setError,+ sources: credentialValuesQuery.data?.sources ?? {},verificationCode,execute, actions, isConnected,getProviderDefaults, saveProviderDefaults,diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex cbb86496..658902c4 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -1241,6 +1241,23 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chibreak;}+ case 'browser_invalidated': {+ // Cross-replica NOTIFY contains only identifiers. Read the actual+ // Browser state through the authenticated application API.+ const identity = data as { workflow_id?: string; node_id?: string };+ const socket = wsRef.current;+ if (socket && identity?.workflow_id === useAppStore.getState().currentWorkflow?.id && identity.node_id) {+ void sendOnSocket<{ session?: { state?: string } }>(socket, {+ type: 'browser_session', workflow_id: identity.workflow_id, node_id: identity.node_id,+ }, REQUEST_TIMEOUT).then((response) => {+ if (response.session?.state === 'awaiting_user' && identity.workflow_id === useAppStore.getState().currentWorkflow?.id) {+ useCanvasDockStore.getState().showBrowser();+ }+ }).catch(() => { /* Owner outage: the Browser viewer reports availability. */ });+ }+ break;+ }+case 'browser_updated': {// CloudEvents-typed browser control change from// server/nodes/browser/_events.py: identity + state only; the livediff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex cc7cd904..b33675fa 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -132,6 +132,9 @@ export interface ServerProviderConfig {account_label?: string | null;/** Saved rows, for a provider that holds several (server-resolved). */endpoints?: ServerEndpointSummary[];+ sourceSupported?: boolean;+ sourceRequired?: boolean;+ unsupported_reason?: string;/** Server-resolved: the provider is usable right now. Equal to `stored`* unless the provider declares a live check (WhatsApp's pairing, the* IMAP/SMTP account's keys). */diff --git a/client/src/hooks/useDragAndDrop.ts b/client/src/hooks/useDragAndDrop.tsindex 41ffbbb2..c96db6b9 100644--- a/client/src/hooks/useDragAndDrop.ts+++ b/client/src/hooks/useDragAndDrop.ts@@ -1,5 +1,9 @@import { useCallback } from 'react';-import { Node } from 'reactflow';+import { Edge, Node } from 'reactflow';+import { toast } from 'sonner';+import { useAppStore } from '../store/useAppStore';+import { createBrowserAgent } from '../services/browserAgentApi';+import { addSavedNodes, addSavedEdges } from '../lib/workflowOps';import { snapToGrid, getDefaultNodePosition, nextNodeInstanceId } from '../utils/workflow';import { theme } from '../styles/theme';import { getCachedNodeSpec } from '../lib/nodeSpec';@@ -17,6 +21,8 @@ const isAgentType = (nodeType: string): boolean => {interface UseDragAndDropProps {nodes: Node[];setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;+ edges?: Edge[];+ setEdges?: (edges: Edge[] | ((edges: Edge[]) => Edge[])) => void;saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;globalModelDefaults?: { provider: string; model: string } | null;workflowId: string;@@ -51,7 +57,7 @@ export const generateUniqueLabel = (displayName: string, nodeType: string, existreturn `${displayName} ${suffix}`;};-export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId, screenToFlowPosition }: UseDragAndDropProps) => {+export const useDragAndDrop = ({ nodes, setNodes, edges = [], setEdges, saveNodeParameters, globalModelDefaults, workflowId, screenToFlowPosition }: UseDragAndDropProps) => {const onDragOver = useCallback((event: React.DragEvent) => {event.preventDefault();event.dataTransfer.dropEffect = 'move';@@ -85,6 +91,25 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModeposition = getDefaultNodePosition(nodes.length);}+ if (nodeData.type === 'browser_agent') {+ const store = useAppStore.getState();+ if (!setEdges || !store.currentWorkflow || store.currentWorkflow.id !== workflowId) {+ toast.error('Open a workflow before adding Browser AI Agent.');+ return;+ }+ store.updateWorkflow({ nodes, edges });+ if (!(await useAppStore.getState().saveWorkflow())) return;+ if (useAppStore.getState().currentWorkflow?.id !== workflowId) return;+ const result = await createBrowserAgent({ workflow_id: workflowId, position: [position.x, position.y],+ ...(globalModelDefaults || {}) });+ useAppStore.getState().adoptSavedOperations(workflowId, result.operations);+ if (useAppStore.getState().currentWorkflow?.id === workflowId) {+ setNodes(current => addSavedNodes(current, result.operations));+ setEdges(current => addSavedEdges(current, result.operations));+ }+ return;+ }+// Get node definition to access displayNameconst nodeDef = resolveNodeDescription(nodeData.type);const displayName = nodeDef?.displayName || nodeData.type;@@ -122,9 +147,10 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModesetNodes((nds) => nds.concat(newNode));} catch (error) {console.error('Error dropping node:', error);+ toast.error(error instanceof Error ? error.message : 'Could not add node.');}},- [setNodes, nodes, saveNodeParameters, globalModelDefaults, workflowId, screenToFlowPosition]+ [setNodes, nodes, edges, setEdges, saveNodeParameters, globalModelDefaults, workflowId, screenToFlowPosition]);const handleComponentDragStart = useCallback((event: React.DragEvent, definition: any) => {diff --git a/client/src/services/__tests__/browserAgentApi.test.ts b/client/src/services/__tests__/browserAgentApi.test.tsnew file mode 100644index 00000000..295818e4--- /dev/null+++ b/client/src/services/__tests__/browserAgentApi.test.ts@@ -0,0 +1,26 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createBrowserAgent } from '../browserAgentApi';++afterEach(() => vi.unstubAllGlobals());++describe('saved Browser Agent creation', () => {+ it('retries a lost response with the same mutation identity and tool selection', async () => {+ const result = { node_ids: { agent: '7:browser_agent:1' }, operations: [] };+ const fetch = vi.fn().mockRejectedValueOnce(new TypeError('Lost response'))+ .mockResolvedValueOnce(new Response(JSON.stringify(result)));+ vi.stubGlobal('fetch', fetch);+ expect(await createBrowserAgent({ workflow_id: '7', browser_node_id: '7:browser:1' })).toEqual(result);+ expect(fetch).toHaveBeenCalledTimes(2);+ const first = fetch.mock.calls[0][1];+ expect(fetch.mock.calls[1][1].body).toBe(first.body);+ expect(first.credentials).toBe('include');+ expect(JSON.parse(first.body)).toMatchObject({ workflow_id: '7', browser_node_id: '7:browser:1', mutation_id: expect.any(String) });+ });++ it('surfaces a server rejection without submitting a second mutation', async () => {+ const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ detail: 'Browser access denied' }), { status: 404 }));+ vi.stubGlobal('fetch', fetch);+ await expect(createBrowserAgent({ workflow_id: '7' })).rejects.toThrow('Browser access denied');+ expect(fetch).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/services/browserAgentApi.ts b/client/src/services/browserAgentApi.tsnew file mode 100644index 00000000..1136e59f--- /dev/null+++ b/client/src/services/browserAgentApi.ts@@ -0,0 +1,29 @@+import { buildApiUrl } from '../config/api';+import type { WorkflowOperation } from '../lib/workflowOps';++export interface BrowserAgentCreation {+ workflow_id: string;+ browser_node_id?: string;+ position?: [number, number];+ provider?: string;+ model?: string;+}++export async function createBrowserAgent(input: BrowserAgentCreation): Promise<{ node_ids: Record<string, string>; operations: WorkflowOperation[] }> {+ const body = JSON.stringify({ ...input, mutation_id: crypto.randomUUID() });+ // A lost response retries the same saved mutation, never a second graph.+ for (let attempt = 0; ; attempt++) {+ let response: Response;+ try {+ response = await fetch(buildApiUrl('/api/browser/agents'), {+ method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body,+ });+ } catch (error) {+ if (attempt === 0) continue;+ throw error;+ }+ const result = await response.json();+ if (!response.ok) throw new Error(result.detail || 'Could not add Browser AI Agent.');+ return result;+ }+}diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex fc9ba5cb..7dce64a4 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -23,6 +23,18 @@ ways depending on the run's frozen settings flags:**Routing snapshot (`_temporal_routing_v1`).** The three dispatch flags — `TEMPORAL_PER_TYPE_DISPATCH`, `TEMPORAL_AGENT_WORKFLOW_ENABLED` and `TEMPORAL_WORKER_POOL_ENABLED` (which picks the task queue) — are read once by whoever starts the run and frozen into the workflow input under `_temporal_routing_v1` (`services/temporal/executor.py::capture_temporal_routing_input`). `TemporalExecutor.execute_workflow` captures them per run; `DeploymentManager` captures them when it registers a push/poll listener or creates a cron Schedule, and the listener hands the same snapshot to every run it spawns. `MachinaWorkflow.run` dispatches only from that snapshot (`_frozen_routing_from_input`) and never re-reads `Settings`, so changing a flag affects runs started, and triggers registered, afterwards — never a run already in flight. An input without a snapshot (or with an unknown version) gets `_SAFE_FROZEN_ROUTING`: agent workflow and per-type dispatch on, worker pool off. Locked by `tests/temporal/test_frozen_routing.py`.+**Browser owner routing (`browser_routing_version: 1`).** Distributed starts+also capture server-resolved `browser_bindings`, including profile, principal,+owner, runtime epoch and physical queue. The Browser queue overrides the+general pool switch, including when `TEMPORAL_WORKER_POOL_ENABLED=false`.+Only the registered backend owner consumes it; generic orchestration workers+exclude Browser Activities. Ordinary Browser nodes and native Browser Agent+tools share this path. Preparation can associate a new profile with an already+registered configured backend, but cannot register an orchestration worker as+a browser owner. Missing registrations fail admission; unavailable existing+owners keep their assignment. [Deployment and recovery](browser_agent_deployment.md)+defines the PostgreSQL, shared storage and external Temporal prerequisites.+## Execution Routing & Running`WorkflowService.execute_workflow` routes each run (`server/services/workflow.py`):@@ -716,14 +728,39 @@ the ingress and duplicate-trigger naming limits recorded in the### Direct Workspace tasks-A node class that declares `workspace_task = True` (the phone nodes in `server/nodes/mobile/`) can also run a single task outside any graph run. The Workspace's **Ask AI to use the phone** box posts to `/api/mobile/{workflow_id}/{node_id}/tasks` (`server/nodes/mobile/_router.py`), and `services/node_invocations.py::submit` admits the task.--- **Admission.** Each OpenCompany workflow has one long-lived `WorkspaceTaskControllerWorkflow` (`services/temporal/workspace_tasks_workflow.py`, Temporal id from `node_invocations.controller_id`), created on first use through Update-With-Start. Its `submit` Update checks the admission epoch, bounds the number of active tasks, deduplicates a retried submission by its id and prompt fingerprint, and starts one `NodeInvocationWorkflow` child per task (`services/temporal/node_invocation.py`). The child runs the node's per-type activity once, with no retry, and records the run through `workflow_runs.record_completion`.+A node class that declares `workspace_task = True` can run a task outside any+graph run. Phone nodes post to `/api/mobile/{workflow_id}/{node_id}/tasks`+(`server/nodes/mobile/_router.py`). The dedicated `browser_agent` task panel+posts to `/api/browser/tasks` (`server/routers/browser_tasks.py`). Both use+`services/node_invocations.py::submit`. Direct tasks are generation zero,+independent of deployed Start/Stop/Resume, and have their own Cancel and Reset+cleanup.++- **Admission.** Each OpenCompany workflow has one long-lived `WorkspaceTaskControllerWorkflow` (`services/temporal/workspace_tasks_workflow.py`, Temporal id from `node_invocations.controller_id`), created on first use through Update-With-Start. Its `submit` Update checks the admission epoch, bounds active tasks, deduplicates the submission UUID and fingerprint, and starts one `NodeInvocationWorkflow` child per task. New Browser payloads carry server-generated `dispatch_version: 1`, `dispatch_kind: native_agent` and `history_version: 1`; their idempotent history admission Activity completes before acceptance is acknowledged. Unversioned payloads retain the original single per-type Activity command path with no retry.+- **Native Browser execution.** The invocation starts `AgentWorkflow`, using the existing model/tool Activities. Preparation applies the submitted task after saved configuration and templates while preserving system instructions. `native_workspace_version: 1` permits Continue-As-New with generation-zero task identity, frozen tools, policies, owner bindings and transcript, without enrolling direct tasks in generation control or repeating completed turns. The task does not read/write deployed Context or employee chat. Completion is counted once at the invocation parent, including cancellation/error outcomes; agent children and rollover do not add completions.+- **Browser history.** `WorkspaceTaskRecord` is a projection, not the execution authority. Admission and lifecycle writes are idempotent and terminal states cannot regress. Recent tasks contain prompt, timestamps, bounded safe result/error and authorized relative artifact links, excluding tool transcripts and credentials. Pages default to 20 (maximum 100); terminal records expire after 35 days, while active records and history survive Reset. Workflow authorization protects historical records after node deletion. Retained terminal records also prevent resubmission after controller dedup or Temporal history expiration.- **Reset.** The controller's `reset` Update first fences new submissions by advancing the epoch. It then cancels every admitted child and waits for each to close, and runs the `workspace_tasks.reset_runtime` activity (`services/temporal/workspace_task_activities.py::reset_workspace_task_runtime`). That activity cancels invocations started before the controller existed and calls each Workspace-task node's `reset_execution_state`. The Update returns only after that cleanup. If cleanup fails, the fence stays in place, and retrying Reset resumes the same request. The workflow toolbar's Reset reaches the controller through `services/deployment/handlers.py::_reset_workspace_tasks`, even for a workflow that was never started; see [temporal-workflow-control.md](./temporal-workflow-control.md#workspace-tasks).- **Registration and rollover.** Both workflow classes are in `worker.py::_framework_workflows`, and every framework worker registers `reset_workspace_task_runtime`. The controller continues-as-new under history pressure, carrying its epoch and its bounded submission and reset records.- **Inside graph and agent runs.** Two patch markers give Workspace-task nodes their own activity options. `workspace-node-cancellation-v1` (`MachinaWorkflow`) uses the node class's `start_to_close_timeout` and `heartbeat_timeout`, and makes cancellation wait until the activity has finished cleaning up. `workspace-task-activity-policy-v1` (tool calls in `AgentWorkflow`) does the same and also applies the class's `retry_policy` and, with the worker pool on, its `task_queue`.-What the user sees, including what Reset leaves on the phone, is in [docs/mobile-workspace.md](../docs/mobile-workspace.md#resetting-phone-tasks).+Browser tasks hold the profile claim during reasoning, tools and human help.+Finalization waits for matching-token owner cleanup; stale cancellation cannot+release a newer task. Queued work has no schedule-to-start or schedule-to-close+deadline, so an owner outage consumes neither retry attempts nor model turns.+Start-to-close and heartbeat timeouts apply after pickup. Cancel/Reset can stay+pending until that owner recovers. Later mutating attempts are refused when the+prior effect is uncertain; recovery requires fresh observation and confirmation,+not profile transfer or a reset attempt identity. The active workflow/tool+association restores viewer access to the frozen profile across edits/restarts.++`tests/temporal/test_browser_workspace_replay.py` uses a native Temporal test+server with separate orchestration and two owner workers. Its model/browser+Activities are controlled fixtures. Set `TEMPORAL_TEST_CLI` to a provisioned+native Temporal executable to run the owner-routing, Continue-As-New,+cancellation/cleanup and SDK replay gate. Old replay fixtures remain required.++What the user sees is documented in [Mobile workspace](../docs/mobile-workspace.md#resetting-phone-tasks)+and [Browser workspace](browser_workspace.md#direct-browser-tasks).### Approved sendsdiff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.mdindex 8a3c665a..9ad0fce5 100644--- a/docs-internal/agent_architecture.md+++ b/docs-internal/agent_architecture.md@@ -22,6 +22,41 @@ Detailed architecture reference for how AI Agent (`aiAgent`) and Chat Agent (`ch## End-to-End Data Flow+### Browser AI Agent++`browser_agent` inherits `SpecializedAgentBase`, standard parameters, provider+selection/model inheritance, handles and the existing output envelope. It uses+the provider-neutral reasoning loop and its saved Browser tool; it does not+invoke Browser Use's Agent SDK. The private creation bundle is defined once+in `services/browser_agent_recipe.py` and reused by canvas creation, Agent+Builder and new employee Browser capabilities.++Employee chat delegates through the ordinary delegation schema. Direct tasks+are server-admitted Workspace invocations using the saved agent/tool binding:+`WorkspaceTaskControllerWorkflow → NodeInvocationWorkflow → AgentWorkflow`.+Their submitted prompt is applied after saved/template preparation, preserving+the saved Browser system role. Their conversation is isolated from employee+chat and deployed Context. A versioned native Workspace continuation permits+generation-zero Continue-As-New without enrolling direct tasks in deployment+Start/Stop/Resume. Cancel and Reset wait for owner cleanup; prepared tools,+policy and routing remain frozen across continuation.++A stable task token holds the Browser profile during reasoning, tool calls+and human assistance. Delegated agents have separate tokens. Both in-process+tool adapters forward trusted Browser bindings and task identity. The saved+policy is tightened by trusted `interaction=read_only` restrictions, including+Ask first; model arguments cannot relax it. The viewer remains attached to+the saved Browser tool, preserving takeover and the binary frame protocol.++1Password values are resolved inside the calling model Activity or browser+owner, never during catalogue reads or into Temporal inputs. Configured login+uses private CDP only while browser-use is suspended and page/capture channels+are gated; the model receives an opaque binding ID and safe status. Multi-step+login, MFA and passkeys use human assistance. See+[1Password credentials](./onepassword_credentials.md),+[Browser workspace](./browser_workspace.md) and+[Temporal control](./temporal-workflow-control.md).+```User clicks "Run" on AI Agent|@@ -545,7 +580,7 @@ authoritative agent list, or read `AI_AGENT_TYPES` in[`server/constants.py`](../server/constants.py) — do not hand-maintain acount here. The frozenset currently spans: the twobase agents (`aiAgent`, `chatAgent`), the specialized agents-(`android_agent`, `coding_agent`, `web_agent`, `task_agent`, `social_agent`,+(`android_agent`, `browser_agent`, `coding_agent`, `web_agent`, `task_agent`, `social_agent`,`travel_agent`, `tool_agent`, `productivity_agent`, `payments_agent`,`consumer_agent`, `autonomous_agent`), the 2 team leads(`orchestrator_agent`, `ai_employee`), the 2 CLI/REPL agents that bypass@@ -566,6 +601,12 @@ Two settings flags route agent execution through different Temporal paths (see [Both flags default to `true` in `.env.template`; the starter freezes theirvalues and the worker-pool routing flag into each execution's input.+Distributed Browser bindings additionally freeze an owner-specific queue.+That queue applies to Browser Activities even when worker pools are disabled;+generic orchestration workers cannot execute them. Direct `browser_agent`+Workspace tasks use the versioned native child path described above, while+older Workspace submissions retain their recorded single-Activity path.+`AgentWorkflow` executions carry messages in the single `MessageWire` shape;there is one engine and one wire standard, with no `llm_engine` or`message_wire_version` discriminator recorded (locked bydiff --git a/docs-internal/browser-controls.md b/docs-internal/browser-controls.mdindex 3932293b..df5a37ce 100644--- a/docs-internal/browser-controls.md+++ b/docs-internal/browser-controls.md@@ -66,6 +66,22 @@ destinations now obey the allowlist too. Read-only interaction still requireshuman help for clicks, typing and site changes; these changes do not inferbusiness-action approval from button text.+Ask first restrictions from the trusted tool adapter tighten saved full access+to read-only in both execution adapters. A model cannot undo that restriction,+nor can prepared native task parameters broaden a newly saved read-only policy.+Browser AI Agent tasks hold their profile claim during reasoning and human+assistance; a competing task receives `BrowserBusy` before an effect. Cleanup+is token matched and confirms daemon suspension before releasing the claim.++`credential_fill` is a mutating site action subject to these same policies,+budgets and uncertain-attempt refusal. It supports only an approved configured+username/password form with fresh element references and a separate submit+target. It gates CLI, viewer and WebMCP observations before secret resolution.+Targets are checked again after desktop authorization and before submission.+Uncertain outcomes keep capture paused and require close/reopen plus manual+login; the agent cannot replay the fill. `credential_bindings` only exposes+permitted opaque IDs and nonsecret login metadata.+### Challenge handoffGenerated scripts check for strong Google `/sorry` and corroborateddiff --git a/docs-internal/browser.md b/docs-internal/browser.mdindex 44c4a14c..d373734a 100644--- a/docs-internal/browser.md+++ b/docs-internal/browser.md@@ -17,12 +17,32 @@ agent-browser driver and separate `browserHarness` node are retired.| Live picture | `_stream.py` → `Page.startScreencast` → binary `/ws/browser` frames | One capture hub per running profile, bounded queues per viewer || Human input | `_live_control.py` → dedicated page CDP session | One ordered command worker per hub; independent of CLI and capture resizing || Session and profile requests | `_handlers.py` over the application's authenticated request socket | Resolve ownership and saved node settings before opening sessions |+| Configured website login | `_credentials.py` through a pinned private CDP page session | CLI daemon and observations are suspended before secrets are resolved |The native viewer is a streamed Chrome surface. Canvas URL items continue touse sandboxed iframe previews. Neither displaying a Canvas URL nor attaching aviewer silently starts a browser; **Start browser** explicitly opens an idlesession. Normal and Dev modes use the same viewer component.+## Browser AI Agent++`browser_agent` uses `SpecializedAgentBase`, the existing provider-neutral AI+runtime and the installed `browser-use==0.13.10` CLI. It is available on the+workflow canvas, through employee delegation, and beside the live browser.+Existing `browser` nodes and `web_agent` graphs keep their contracts.++Creation uses one atomic graph recipe: the agent, a private Browser tool,+Master Skill with the shipped browser skill, private Context and the existing+`visionAnalyze` tool. Selecting an existing saved Browser tool reuses it.+Intentionally deleted companion nodes are not recreated. The viewer stays+attached to the Browser tool; only that tool has `isBrowserPanel`.++Direct tasks use the existing Workspace controller and native agent workflow.+They have independent conversation/history, submission UUIDs and cancellation,+and do not deploy their prompt into saved Context or employee chat. See+[Browser workspace](browser_workspace.md#direct-browser-tasks) and+[deployment and recovery](browser_agent_deployment.md).+## Installation and configurationThe defaults `BROWSER_RUNTIME=system` and `BROWSER_FAMILY=chrome` discover@@ -132,6 +152,12 @@ WebMCP permissions, domain restrictions and private-network permission comefrom saved operator settings, not model-supplied tool arguments.`ProfileController` coordinates the profile lease and agent operation lock.+Browser AI Agent tasks also hold a stable, task-lifetime profile claim through+model reasoning, browser calls and human assistance. Competing tasks receive+`BrowserBusy` before browser effects. Cleanup checks the same task token, settles+admitted work and confirms daemon suspension before releasing the claim; a late+cancellation cannot release a newer task. The human-control lease remains+separate. Assigned tasks and protected-login gates prevent idle reaping.**Take control** waits for or interrupts an agent step before granting userownership. Human commands carry viewer and page generations and are checkedagain immediately before CDP dispatch. **Hand back**, hiding, blur and@@ -161,6 +187,12 @@ runs with `interaction: read_only`, set by the plugin's approval specthe agent reads pages and hands any change to the owner through`request_user`. The employee's instructions say when to call it.+The trusted per-call restriction is combined with saved policy monotonically:+either source can require read-only, and model arguments cannot relax it. This+applies to both the in-process and Temporal adapters. Versioned native tasks use+their prepared configuration/profile bindings; a subsequently saved read-only+policy can still tighten a prepared full-access policy.+While the agent waits in `request_user`, the plugin's node-state source(`services/employees/node_signals.py`) reports `awaiting_user`, and theemployee summary carries `browser_request` (`{node_id, reason, since}`, never@@ -187,6 +219,72 @@ legacy parameters from saved deployment snapshots. Use the current `browser`node for new graphs; the [retired harness reference](./browser_harness.md)exists to direct older links to the current implementation.+## Configured 1Password login++Enroll an approved website binding in Credentials as described in+[1Password credentials](onepassword_credentials.md). `credential_bindings`+lists permitted opaque IDs, labels, login origins and field names; it never+lists vault contents or secret references. `credential_fill` accepts that ID+and fresh username, password and separate submit references. The owner checks+principal, saved profile/workflow/employee scope, policy, exact top-frame+origin and current targets before retrieving values. Under Ask first/read-only,+the agent requests human login instead.++Automatic login supports a configured single username/password form with+saved success origin/path or selector cues. Before private resolution, the+runtime persists a nonsecret sensitive-login latch, confirms the browser-use+daemon has stopped, drains and stops live capture, and blocks page text,+snapshots, screenshots, vision, WebMCP and page/tab/dialog metadata. Credentials+are passed only to the existing private CDP transport. Assigned values are+checked exactly; a browser-normalized value is not submitted.++Only the separately selected submit action is allowed during this phase.+Completion requires the saved cues and absence of password fields before+ordinary operations resume, with a fresh observation required. Uncertain+suspension, target changes, unsuccessful confirmation or cancellation retain+the gate. **Close browser for manual login** confirms Chrome is stopped before+clearing it; reopen and use human takeover. MFA, passkeys and multi-step forms+use that handoff. This flow does not pass passwords through model input,+Temporal payloads, browser-use scripts, task results or viewer frames.++## Distributed ownership++Distributed mode stores permanent profile ownership, runtime epochs, task+claims and nonsecret assistance state in the shared application database.+Each configured backend replica runs one browser owner process and consumes+its own Browser Activity queue; orchestration workers do not consume those+queues. All Browser operations, saved profiles, uploaded session files,+open/stop requests and binary live streams are routed to the registered owner+through authenticated application endpoints. Signed forwarding binds the+principal, method, path, body and expiry, and the owner rechecks saved-resource+authorization. CDP addresses and owner URLs never come from client arguments.++Deleting a workflow routes employee-profile cleanup to that owner. An active+task, unavailable owner or unconfirmed Chrome shutdown leaves its profile+metadata/files intact for authorized cleanup after recovery; another replica+does not remove files underneath a running browser.++Ownership is not transferred on heartbeat expiry. The UI reports **Browser+unavailable — waiting for its owner.** Queued Activities remain on that owner's+queue. Recovery requires the same machine identity and an exclusive process+lock, advances the epoch explicitly and requires fresh observation. Chrome+tabs and element references are not recovered from Temporal. Sensitive-login+and nonsecret assistance state survive backend restart. Mutating Activity+attempts greater than one retain the refusal to replay an uncertain action.++The active task also persists its workflow/Browser-tool association. Viewer+routing uses that frozen profile after current saved-resource authorization,+even if profile parameters change mid-task or the local/backend owner restarts.+Matching release clears the+association; an ambiguous active association fails closed. A recovered runtime+restores the durable task token before later browser or profile effects.++Profile files have one writer. CLI homes, temporary files and PID state are+local to the owning machine/runtime, while artifacts use shared relative+FileRefs. Local SQLite remains supported; multi-machine deployment requires+PostgreSQL, shared storage and external Temporal. See the+[deployment guide](browser_agent_deployment.md) for setup and recovery.+## Troubleshooting and validation- **No Browser node listed:** save the workflow and browser node first. Normaldiff --git a/docs-internal/browser_agent_deployment.md b/docs-internal/browser_agent_deployment.mdnew file mode 100644index 00000000..fe431860--- /dev/null+++ b/docs-internal/browser_agent_deployment.md@@ -0,0 +1,221 @@+# Browser AI Agent deployment and recovery++`browser_agent` uses the existing agent/Workspace/Temporal frameworks and+browser-use `0.13.10`. The Browser tool remains the profile/viewer capability.+See [creation](./node_creation.md), [workspace](./browser_workspace.md),+[Temporal control](./temporal-workflow-control.md) and+[1Password credentials](./onepassword_credentials.md).++## Local deployment++Keep `DISTRIBUTED_MODE=false` and the existing local SQLite and embedded+Temporal setup. Existing encrypted credentials, OAuth refresh stores and CLI+login caches retain their local behavior. 1Password bindings are optional;+desktop authorization supports personal vaults. Install the tested CLI v2+`2.40.0` through the Credentials panel or the normal managed provisioning+handler, and enable 1Password desktop CLI integration on the backend machine.+An interactive desktop authorization must authorize the actual backend+subprocess, not merely another terminal's `op` session.++Add Browser AI Agent from the canvas palette, the saved Browser workspace,+or Agent Builder. The shared recipe creates its private Context, Browser,+Master Skill and vision tool. Existing employees gain the capability only+when the user adds it; no background upgrade rewrites existing graphs.++## Distributed prerequisites++Each backend has one browser-owner process (`WORKERS=1`). Separate+orchestration workers run the existing standalone Temporal worker and do not+register Browser ownership. Every participant uses the same PostgreSQL+application database, external Temporal service/namespace, authentication+keys, trusted owner-forwarding secret and authorized artifact storage.++Start from `.env.template`, override these values through deployment+configuration, and keep bootstrap secrets out of graph or node parameters:++```dotenv+DISTRIBUTED_MODE=true+DATABASE_URL=postgresql+asyncpg://opencompany:...@database:5432/opencompany+TEMPORAL_ENABLED=true+TEMPORAL_SERVER_ADDRESS=temporal.internal:7233+TEMPORAL_NAMESPACE=opencompany+TEMPORAL_AGENT_WORKFLOW_ENABLED=true+TEMPORAL_PER_TYPE_DISPATCH=true+WORKERS=1+BROWSER_REPLICA_ID=backend-a+BROWSER_REPLICA_URL=http://backend-a.internal:5678+BROWSER_MACHINE_ID=machine-a+BROWSER_ROUTER_SECRET=...shared trusted deployment secret...+ONEPASSWORD_AUTH_MODE=service_account+ONEPASSWORD_CLI_VERSION=2.40.0+```++Use a distinct stable replica ID and internal backend origin for each owner.+`BROWSER_MACHINE_ID` identifies its original physical machine and must survive+container restarts; absent an explicit value it uses the machine hostname.+Backend origins contain no path, credentials, query or fragment. They are+server configuration, never client-supplied addresses. Shared `SECRET_KEY`+is the forwarding-secret fallback; explicit `BROWSER_ROUTER_SECRET` permits+separate rotation. Use authenticated, trusted internal transport and normal+TLS termination between machines.++Provision `OP_SERVICE_ACCOUNT_TOKEN` from trusted deployment secret+configuration with read-only access to a dedicated automation vault. The+resolver passes it only to the private `op` child; Browser/Chrome children do+not inherit it. Connect environment variables are excluded. Static provider+keys and configured website logins require approved 1Password bindings.+Provision the verified CLI and resolver authorization on every backend and+orchestration worker that resolves provider keys. Website credentials resolve+only on their browser owner. Keep platform-specific executable installations+local to each runtime.+Cluster preflight and runtime reject inline/local/ambient credentials,+OAuth refresh stores and CLI-managed sessions without an audited static+adapter. Their local behavior is preserved; this release does not migrate+refresh tokens or write them back into the read-only vault.+Generic static bindings cover one API field. Connections requiring additional+credential fields also require an explicit audited adapter; their existing+local enrollment remains available.++Mount artifacts at the same relative workspace paths on replicas and workers.+FileRefs use authorized application routes rather than absolute filesystem+paths. Persistent browser profile storage must provide an exclusive writer+and proven cross-machine file-lock behavior. Owner process and Chrome profile+locks fence overlapping writers. Keep owner-local runtime/PID state local:+Chrome PID records are stable per owner/profile on its original machine;+browser-use daemon homes and temporary state are separate per runtime epoch.+Do not share these local directories between owners. Never put the+application or encrypted-credential SQLite databases on NFS/SMB.++Backend lifecycle starts an owner-specific Browser Activity worker even when+`TEMPORAL_WORKER_POOL_ENABLED=false`. Generic workers never consume owner+queues. Logical plugin Activity selection remains separate from physical+queue names. Frozen routing covers new ordinary Browser nodes as well as+Browser Agents; old recorded Temporal command paths retain their compatibility+branches. See [Temporal task routing](https://docs.temporal.io/task-routing).+Before enabling distributed mode, finish or cancel unversioned Browser work+using its existing local workers and confirm cleanup. Retaining old replay+branches does not route an already-recorded generic Browser Activity onto a+new owner queue. Distributed workers intentionally do not execute those+unowned Browser Activities.++## Offline SQLite transfer++Stop local writers, close browsers, finish/cancel direct tasks, and Reset+deployed workflows before transfer. Stop target writers too. The command is+an explicit export/import into an empty target, not live replication or a+token migration. Keep the export private: it contains application history+and approved secret-reference metadata.++From `server/`, with normal application configuration available:++```powershell+python -m tools.database_transfer export --sqlite C:/local/workflow.db --output C:/private/opencompany-transfer.json --offline+# Set DATABASE_URL to the new shared PostgreSQL database in trusted configuration.+python -m tools.database_transfer import --input C:/private/opencompany-transfer.json --offline+```++The current SQLModel schema is created through normal database startup.+Transfer preserves application IDs, graphs, parameters, account records,+bindings and terminal task history, and reseeds PostgreSQL integer sequences.+Inline credential fields, active Workspace tasks and unfinished Browser+claims are rejected. Local encrypted secrets, OAuth tables, caches, transient+routes and live owner registrations are excluded. Import refuses a nonempty+application target and commits in one transaction. Copy the associated+workspace artifacts and persistent browser profile files separately while+their writers are stopped. Existing Temporal histories are not exported by+this application database command.++Profile ownership and nonsecret sensitive-login/challenge state are retained.+Legacy profiles that predate ownership records receive original-machine+ownership during export; importing them does not permit another replica to+adopt them.+The manifest records the original local machine. When imported profiles have+owner `local`, import creates an unavailable owner registration for that+machine. Bootstrap that original machine's first cluster backend with+`BROWSER_REPLICA_ID=local` and the matching `BROWSER_MACHINE_ID`. Other+backends use distinct IDs. Registration explicitly renews the epoch and+requires observation; another machine cannot adopt these profiles silently.++PostgreSQL startup uses a transaction advisory lock for schema creation and+rejects missing columns before serving an incompatible schema. Existing+SQLite migrations remain local. Shared read/modify/write mutation and+reservation paths use transaction advisory locking to preserve their former+SQLite write-reservation semantics; portable compare-and-set claims remain+atomic. UTC timestamps accept the existing aware and naive UTC conventions.+Startup adds the nullable workflow/tool association columns for earlier+development owner-registry schemas. Other missing shared columns fail closed.++## Ownership, unavailability and cleanup++Profile ownership is permanent for this release. A stable task token holds+the profile during model reasoning, browser work and human assistance.+Competing tasks return `BrowserBusy` before browser effects. Human control+keeps its separate lease; a stale cancellation cannot release a newer task.++An offline owner's queued Activity remains on that owner's queue without+consuming retries or starting another model turn. The UI reports+**Browser unavailable — waiting for its owner.** Attempt/heartbeat timeouts+start after Activity pickup. Recovery renews the epoch on the original+machine, restores nonsecret control state and requires fresh observation;+Chrome tabs and element references are not restored by Temporal. Mutating+operations on retry attempts remain refused. An uncertain outcome requires+observation and effect confirmation before another irreversible action.+Use human assistance when the effect cannot be established.++Cancel and Reset wait for a confirmed owner cleanup receipt. Cleanup waits+for admitted browser work, stops/drains the CLI daemon, and retires Chrome if+daemon suspension cannot be confirmed. Reset can remain in progress while+the owner is unavailable. An operator restores the original owner; there is+no scheduler, automatic profile transfer or retry identity reset. Wrong+machine identity, a still-live owner process or failed cleanup stays+unavailable instead of creating a second writer.++Open/stop/profile controls, manual input, live binary WebSockets and cleanup+are proxied to the owner through authenticated application endpoints. Owners+recheck principal and resource authorization; CDP stays private. PostgreSQL+NOTIFY carries only Browser identifiers. Receiving replicas request current+state through authorized APIs; page contents, frames, secrets and owner URLs+never appear in invalidation messages. Task history is an authorized 35-day+terminal projection with 20 records per page (maximum 100), not the execution+authority. Active history survives Reset and retention cleanup.++Direct tasks are generation zero and independent of Start/Stop/Resume. Their+server-versioned native child uses saved Browser configuration, a separate+task transcript and frozen routing; Continue-As-New preserves completed model+turns and tools. `/api/browser/tasks` accepts only saved workflow/agent IDs,+the task and a submission UUID. Extra execution bindings are rejected. The+server resolves the saved Browser tool through `/discovery`; `/history`+returns metadata and bounded public results. Stable IDs and fingerprints+prevent duplicate submissions, including terminal records whose Temporal+history has expired. Cancel and historical status remain authorized through+the workflow after an agent is removed. Completion accounting occurs once+at the invocation parent boundary.++## Acceptance and release gate++Automated checks use controlled fixtures: exact configured form login,+capture gates and secret canaries, policy restrictions and handoff, reading+account data, preparing a change, task/cancellation isolation, two owner+queues, replay/Continue-As-New, PostgreSQL migration/concurrent claims and+identifier-only invalidation. Ordinary Browser/profile/cookie/viewer and old+agent/graph regressions remain required.++Run the isolated real-database tests separately from the legacy stubbed+`tests/` suite:++```powershell+python -m pytest -q integration_tests/test_browser_foundations.py+# A test PostgreSQL role must be allowed to create disposable databases.+$env:TEST_POSTGRES_URL='postgresql://[email protected]:55438/browser_integration'+python -m pytest -q integration_tests/test_postgresql_browser.py+```++Real 1Password desktop authorization/expiry and scoped service-account+rotation/revocation require configured test vaults on each supported platform.+Validate the target multi-machine storage locks, authenticated owner proxy+and viewer transport, owner outage/recovery and external Temporal namespace+before production release. External-account smoke tests remain explicitly+authorized: GitHub login with human MFA followed by a read-only issue+summary; Gmail human multi-step login followed by an invoice summary without+sending mail. Passing mocked or local fixture tests does not certify those+deployment/account gates.diff --git a/docs-internal/browser_harness.md b/docs-internal/browser_harness.mdindex af0a6931..155dc943 100644--- a/docs-internal/browser_harness.md+++ b/docs-internal/browser_harness.md@@ -8,7 +8,15 @@ Current documentation:- [Browser node flow](node-logic-flows/web_automation/browser.md): operations, operator settings, dispatch, outputs and legacy migration.- [Browser workspace](browser_workspace.md): live viewing, frame delivery, direct input and human control.-The current runtime launches installed Chrome/Edge/Chromium in a dedicated OpenCompany profile headless inside the workspace UI by default; it neither attaches to nor copies an already running, logged-in personal profile. Chrome for Testing is available only through explicit `BROWSER_RUNTIME=testing`; a separate desktop window requires `BROWSER_HEADLESS=false`. Agent/workflow operations use generated scripts through the isolated, pinned browser-use CLI and its persistent daemon; WebMCP and live viewer capture/control have native CDP paths. The presence of browser-harness machinery inside that dependency is separate from the retired OpenCompany node.+The current runtime launches installed Chrome/Edge/Chromium in a dedicated OpenCompany profile headless inside the workspace UI by default; it neither attaches to nor copies an already running, logged-in personal profile. Chrome for Testing is available only through explicit `BROWSER_RUNTIME=testing`; a separate desktop window requires `BROWSER_HEADLESS=false`. Ordinary agent/workflow operations use generated scripts through the isolated, pinned browser-use CLI and its persistent daemon; WebMCP and live viewer capture/control have native CDP paths. Configured 1Password form filling uses that existing private CDP connection only after the CLI daemon and observations are suspended. The presence of browser-harness machinery inside that dependency is separate from the retired OpenCompany node.++The dedicated `browser_agent` is an OpenCompany `SpecializedAgentBase` agent,+using the existing AI reasoning runtime and Browser tool. It does not adopt+the dependency's separate autonomous agent loop. Direct Workspace tasks,+durable ownership and protected-login setup are described in+[Browser workspace](browser_workspace.md),+[deployment](browser_agent_deployment.md) and+[1Password credentials](onepassword_credentials.md).[Saved-workflow migration](../server/services/workflow_migrations.py) renames `browserHarness` to `browser` and maps `goto` to `navigate`, `js` to `evaluate`, `doctor` to `diagnose`, and `tabs` to tab listing. Existing Python code is retained with a helper-compatibility warning. `evaluate` and `run_python` are now workflow-only; duplicate Browser tool edges created by migration are removed with a warning. See the node flow for complete parameter compatibility behavior.diff --git a/docs-internal/browser_workspace.md b/docs-internal/browser_workspace.mdindex 7cf7ec9d..32d59e4b 100644--- a/docs-internal/browser_workspace.md+++ b/docs-internal/browser_workspace.md@@ -61,6 +61,46 @@ browser calls the authorized `browser_session_open` handler. Unsaved workflowsmust be saved first. Adding a node to an existing workflow must also be savedbefore the server can authorize it.+## Direct Browser tasks++The task panel beside the selected Browser tool discovers connected+`browser_agent` nodes from the saved server graph. A standalone Browser tool+offers **Add Browser AI Agent**, which uses the same atomic creation recipe as+canvas and Agent Builder and adopts the returned saved graph operations.+Discovery never marks the agent itself as a Browser viewer node.++Choose an associated agent, enter a task and submit. The API resolves its+Browser tool, policy, profile and owner; the client sends saved IDs, prompt and+a submission UUID. Retrying a lost acknowledgement uses the same UUID. The task+runs through Workspace admission and native AI execution, independently of+workflow Start/Stop/Resume, employee chat and deployed Context. **Cancel** uses+the existing invocation cancellation and waits for owner cleanup. Reset keeps+history and can remain in progress while an owner is unavailable.++Recent tasks show prompt, lifecycle status, a bounded safe result/error and+authorized artifact links. This projection is separate from chat, excludes+tool transcripts and secret values, and uses stable invocation IDs. History+pages contain 20 records (API maximum 100); terminal entries expire after+35 days while active tasks remain. The UI polls current history and offers+older pages. A missing owner displays **Browser unavailable — waiting for its+owner.** Tasks stay queued for the existing owner and do not trigger another+model turn merely because a Browser Activity has not been picked up.++## Protected login observations++Configured 1Password login displays **Browser observations are paused during+protected login.** The server blocks capture refresh, drains pending frames+and raw metadata, and suppresses tabs, page addresses, dialogs and clipboard+content before retrieving credentials. A `sensitive` event invalidates pending+client image decodes and clears cached picture, address, tabs and dialogs.+The same gate applies to newly attached viewers and recovered owners.++If private submission cannot be confirmed, the gate remains in place. Use+**Close browser for manual login**, then **Start browser** and Take control to+finish login. Closing must be confirmed by the owner before the sensitive+latch clears. The normal handoff covers MFA, passkeys and multi-step login.+See [configured login](browser.md#configured-1password-login).+## When the agent asks for help`request_user` puts the profile's controller in `awaiting_user`. The viewer@@ -87,6 +127,13 @@ a big-endian uint16 JSON-header length, JSON metadata, and JPEG bytes.acknowledges each consumed or skipped frame so the server's two-frame windowdoes not stall. Object URLs are released after decoding and on cleanup.+In distributed mode the accepting backend proxies that same binary envelope+to the saved browser owner. Its signed internal attach binds the authenticated+principal and original attach body, and the owner reauthorizes the saved+target. This adds no public CDP endpoint and does not let clients select a+backend URL. Cross-replica invalidation uses identifiers followed by an+authorized refresh, never browser frames or private page payloads.+Frames fit the available surface without cropping. Input coordinates excludeletterboxing and map through the frame metadata to CDP page coordinates.ResizeObserver reports panel resizing; document visibility and dock visibilitydiff --git a/docs-internal/credentials_encryption.md b/docs-internal/credentials_encryption.mdindex b4ba566e..1345225e 100644--- a/docs-internal/credentials_encryption.md+++ b/docs-internal/credentials_encryption.md@@ -1,14 +1,39 @@# Encrypted Credentials System-API keys, OAuth tokens, and other secrets in OpenCompany are stored in a separate encrypted SQLite database (`credentials.db`) using Fernet (AES-128-CBC + HMAC-SHA256). The encryption key is derived from a server-scoped config key using PBKDF2HMAC with 600,000 iterations, following the n8n pattern.--This document covers the encryption pipeline, the two separate credential systems (OAuth vs API keys), the single-point-of-access rule, and the multi-backend abstraction.+Locally entered API keys, OAuth tokens, and other local secrets in OpenCompany are stored in a separate encrypted SQLite database (`credentials.db`) using Fernet (AES-128-CBC + HMAC-SHA256). The encryption key is derived from a server-scoped config key using PBKDF2HMAC with 600,000 iterations, following the n8n pattern.++This document covers local encryption, the separate OAuth and API-key stores, the single-point-of-access rule, and the legacy multi-backend abstraction. Approved 1Password sources use a separate runtime-resolution path through the same `AuthService`; see [1Password credentials](onepassword_credentials.md) for setup and supported providers.++## Credential-source boundary++| Source | Saved state | Runtime access |+| --- | --- | --- |+| Local API key or OAuth token | Ciphertext in the machine-local `credentials.db` | Existing `AuthService` local accessors and caches |+| 1Password API field | Approved ID reference, principal and model/endpoint metadata in the application database | `resolve_api_key` inside the calling Activity |+| 1Password website login | Approved username/password references, exact origin and resource restrictions in the application database | `resolve_browser_credentials` inside the browser owner while observations are gated |++`get_credential_source`, `has_valid_key`, `get_stored_models` and+`get_model_params` read source metadata without resolving 1Password values.+`get_api_key` retains local form behavior and does not return a resolved+1Password value. Provider runtime callers use `resolve_api_key` with the+trusted principal. Resolution rechecks enrollment after authorization waits;+there is no application-level cache of resolved 1Password values or fallback+to a local key when a binding is unavailable or revoked.++Distributed mode requires the shared PostgreSQL application database and+approved 1Password static bindings. Local encrypted keys, OAuth refresh stores,+ambient credentials and CLI-managed sessions remain local-only unless an+explicit static-secret adapter has been audited. Neither SQLite database may+be mounted over NFS/SMB. [Offline transfer](browser_agent_deployment.md#offline-sqlite-transfer)+preserves approved references and application IDs but excludes local secret+stores and token caches. The application database is therefore sensitive+metadata, even though approved references contain no resolved secret values.## Why a Separate DatabaseCredentials are isolated from the main `workflow.db` for three reasons:-1. **Blast radius**: a dump of `workflow.db` for debugging never contains secrets.+1. **Blast radius**: local credential ciphertext is kept out of `workflow.db`. Approved 1Password references and other private application data still require protected exports; legacy inline graph credentials must be removed before distributed transfer.2. **Independent backups**: `credentials.db` can be excluded from snapshots and SQLite dumps.3. **Backend pluggability**: the file-backed SQLite is designed to be swappable for OS keyring or AWS Secrets Manager without touching workflow storage (the abstraction exists but is not wired in yet; see [Multi-Backend Abstraction](#multi-backend-abstraction)).@@ -22,7 +47,8 @@ server/core/`-- config.py credential_backend, aws_secret_arn settings (read only by the uncalled create_backend)server/services/-`-- auth.py AuthService (single access point, caching)+|-- auth.py AuthService (source metadata, runtime resolution, local caches)+`-- credentials/ 1Password source storage, private CLI resolver and provisioning```## Cryptographic Pipeline@@ -68,7 +94,7 @@ CredentialsDatabase.initialize() -> creates tables, returns existing or new salcontainer.encryption_service().initialize(password=API_KEY_ENCRYPTION_KEY, salt=<bytes>)|v-AuthService caches decrypted credentials in memory-only dicts+AuthService caches decrypted local credentials in memory-only dicts|vRouters call AuthService.get_api_key() / get_oauth_tokens() ...@@ -130,13 +156,13 @@ How the pieces are wired:- `AuthService` maintains the memory-only decryption cache.- `CredentialsDatabase` is a DI singleton (`container.credentials_database()`). The container injects it into `AuthService` and into `UserAuthService` (which holds it but never uses it), and `main.py` resolves it at startup to create tables and read the salt. The container does not stop anything else from resolving it, so "routers and services go through `AuthService`" is a rule to follow, not something DI enforces.-The in-memory cache is important: decrypting on every request would be slow, and writing decrypted values to Redis would defeat the encryption. Each `AuthService` instance caches decrypted credentials in process memory only, and `AuthService.clear_cache()` flushes them on demand (`POST /api/auth/logout` calls it).+The local in-memory cache avoids repeated decryption without putting plaintext in Redis. Each `AuthService` instance caches decrypted local credentials in process memory only, and `AuthService.clear_cache()` flushes them on demand (`POST /api/auth/logout` calls it). These caches do not hold resolved 1Password values.## Multi-Backend AbstractionFor deployment flexibility, `credential_backends.py` defines an abstract interface intended to be selected via the `CREDENTIAL_BACKEND` env var.-**Status: not wired in.** Nothing in the server calls `create_backend()`, and `Settings.credential_backend` / `aws_secret_arn` / `aws_region` are read only inside it. `AuthService` always talks to `CredentialsDatabase` directly, so every install uses Fernet-encrypted SQLite and setting `CREDENTIAL_BACKEND` currently has no effect. The value is still validated: the field is a `Literal["fernet", "keyring", "aws"]`, so any other value fails `Settings` at startup. The rest of this section describes the abstraction as written.+**Status: not wired in.** Nothing in the server calls `create_backend()`, and `Settings.credential_backend` / `aws_secret_arn` / `aws_region` are read only inside it. Local secrets use `CredentialsDatabase`; setting `CREDENTIAL_BACKEND` currently has no effect. 1Password sources are selected per saved binding through `AuthService`, independently of this factory. The value is still validated: the field is a `Literal["fernet", "keyring", "aws"]`, so any other value fails `Settings` at startup. The rest of this section describes the abstraction as written.```pythonclass CredentialBackend(ABC):@@ -225,7 +251,12 @@ Do this before the first credential is saved. After that, never change `API_KEY_## Source of Truth-`CredentialsDatabase` (encrypted SQLite at `credentials.db`) is the **canonical source** for every credential. Two derived in-memory caches exist for performance, both invalidated atomically on every DB write/delete:+`CredentialsDatabase` (encrypted SQLite at `credentials.db`) is the canonical+source for local API keys and OAuth tokens. 1Password values remain in+1Password; approved references and catalogue metadata live in the application+database. Source-status versions include principal-scoped saved-row changes,+so catalogue refreshes across replicas do not need to resolve secrets. The+following caches describe the local path:- **Backend** (`server/services/auth.py`):- `_api_key_cache: Dict[str, ApiKeyCacheEntry]` keyed by `{session}_{provider}`. Single dataclass entry per provider carries decrypted key + models + `stored_at`. Replaces the previous pair of `_memory_cache` (key) + `_models_cache` (models) which shared the same key shape but had separate write/evict sites — invitation to drift.@@ -261,6 +292,8 @@ All credential providers come from the backend `get_credential_catalogue` handle## Related Docs+- [1Password credentials](onepassword_credentials.md) - source enrollment, runtime resolution, private login and compatibility+- [Browser deployment](browser_agent_deployment.md) - PostgreSQL prerequisites and offline transfer- [DESIGN.md](DESIGN.md) - overall security posture- [new_service_integration.md](ARCHIVE/new_service_integration.md) - where to put credentials for new service integrations- [status_broadcaster.md](status_broadcaster.md) - WebSocket handlers for credentials (get/save/delete)diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.mdindex fce754f6..d84b6153 100644--- a/docs-internal/node_creation.md+++ b/docs-internal/node_creation.md@@ -8,6 +8,39 @@ this file picks the right entry point based on what you're adding.## Decision tree+### Browser AI Agent creation++`browser_agent` is a `SpecializedAgentBase` plugin using the existing native+agent loop. Browser control stays in the pinned browser-use CLI (`0.13.10`).+`services/browser_agent_recipe.py` defines its complete creation bundle:+agent, one private Browser tool, private Context, Master Skill with the shipped+browser skill enabled, and `visionAnalyze`. Canvas drop and the workspace's+**Add Browser AI Agent** action call `POST /api/browser/agents`, which persists+the bundle atomically through `apply_graph_additions`. Agent Builder and new+employee Browser capabilities use the same recipe. Existing employees and+Browser/`web_agent` nodes retain their graphs.++Reuse an explicitly selected saved Browser tool. The server allocates IDs and+checks graph ownership and operator blocklists; transport retries use the same+mutation UUID. Repeating Add for an already associated Browser agent returns+its association without recreating a deliberately deleted Context or Skills+node. The viewer remains bound to the Browser tool; `browser_agent` must never+carry `isBrowserPanel`.++`services/browser_agent_recipe.py::browser_tool_id` requires exactly one+connected saved Browser tool before task admission. Creation returns allocated+`node_ids`, graph `operations`, `applied` and `saved_revision`; clients apply+those acknowledged operations through the existing graph update path. They+do not construct an executable task graph. Provider/model fields use standard+agent configuration and inheritance. Companion deletion remains an explicit+graph edit, not a trigger to rebuild the bundle.++See [Browser workspace](./browser_workspace.md),+[agent architecture](./agent_architecture.md) and+[distributed deployment](./browser_agent_deployment.md) for runtime contracts.++### General node selection+| You're adding… | Read this | Boilerplate ||---|---|---|| A simple action node (one HTTP call, no state) | [Quick start](./plugin_system.md#quick-start--adding-a-new-node) | folder under `server/nodes/<group>/<name>/` with `__init__.py` |diff --git a/docs-internal/onepassword_credentials.md b/docs-internal/onepassword_credentials.mdnew file mode 100644index 00000000..df0700e8--- /dev/null+++ b/docs-internal/onepassword_credentials.md@@ -0,0 +1,43 @@+# 1Password credential sources++OpenCompany retains its encrypted local credential database. A provider can instead enroll an approved 1Password field reference. The application database stores references, ownership, model metadata and public endpoint configuration; it never stores resolved values. Distributed mode accepts these static bindings and configured browser logins, and rejects local/inline/ambient secrets, OAuth refresh stores and machine-local CLI login sessions.++## Provisioning and authorization++The pin is **1Password CLI 2.40.0**, the official stable release dated 2026-10-01. Use the credential UI's installation command or `services.credentials.provision.ensure_cli()` during deployment provisioning. This follows the existing project-local `pooch` download pattern and downloads the versioned official archive into `<DATA_DIR>/packages/onepassword/2.40.0`.++The executable is verified **before execution**. Windows uses valid Authenticode with the 1Password/AgileBits publisher; macOS uses Apple's code-signing verification and the publisher Team ID. Linux requires GnuPG, the archive's `op.sig`, and an exact signature by fingerprint `3FEF9748469ADBE15DA7CA80AC2D62742012EA22`. Provisioning retrieves that exact public key into a private verification keyring. A verified install records its SHA-256, which subsequent reads check. An externally supplied executable must pass publisher verification too; manually installed Linux binaries need their corresponding `op.sig` and the approved verification key. No unverified binary receives a secret-service token.++Set `ONEPASSWORD_CLI_PATH` to an absolute path when using an operator-provisioned executable. `onepassword_status` verifies signature/integrity and the pinned version only: it does not sign in, enumerate a vault or resolve a field. Installation and status failures expose fixed error messages, without raw command streams.++Local defaults use `ONEPASSWORD_AUTH_MODE=desktop`. Enable CLI integration in the desktop app; optionally select an account with `ONEPASSWORD_ACCOUNT`. Desktop authorization is broader than an individual OpenCompany binding, so application ownership and binding restrictions are checked independently. A backend running under another operating-system user, a headless service, or an expired/denied desktop grant must be authorized appropriately; there is no fallback to a different account or old local key.++Distributed mode requires `ONEPASSWORD_AUTH_MODE=service_account`. Supply `OP_SERVICE_ACCOUNT_TOKEN` through trusted deployment configuration, using a dedicated automation vault with read-only field/item access. The private resolver passes it only to its own child process. It deliberately excludes Connect variables, session variables, ambient provider keys and debug options. Ordinary application subprocesses strip every case-insensitive `OP_*` variable after environment merges; browser processes retain their stricter existing allowlists. Never wrap browser-use in `op run` or generate a plaintext `op inject` template.++## Enrolling API credentials++Choose **1Password** in a supported provider's existing credential panel and enter `op://<vault-ID>/<item-ID>/<field>`. Named OpenAI-compatible endpoints additionally accept a public base URL and endpoint name. References require vault/item IDs; OTP query parameters and arbitrary CLI options are unsupported. Validation resolves privately, probes the upstream provider, and saves the reference and safe model metadata only after success.++The generic adapter supports a single static API key. Providers that need additional credential fields, custom validation, OAuth or CLI-managed sessions require an explicitly audited adapter and otherwise remain local-only; their existing local forms keep working. This includes multi-field WhatsApp Business credentials. Native model, Apify, Gemini managed-agent fallback, Mobile model and speech runtime callers use execution-time resolution with the trusted principal. Dictation availability and employee provider/endpoint catalogues use principal-scoped metadata only. Vertex project-based Application Default Credentials remain local-only.++`AuthService.get_credential_source`, `has_valid_key`, `get_stored_models` and `get_model_params` read saved metadata without resolving a field. `get_api_key` preserves the legacy local form behavior but returns no resolved value for a 1Password source. Only `resolve_api_key` is a runtime secret accessor. Provider Activities call it at execution time, with the authenticated principal; workflow preparation, catalogue reads and model dropdowns use metadata. Unavailable/revoked references fail explicitly and never fall back to an old key. Values have no application-level decrypted cache, so later resolution sees rotation and revocation.++The private subprocess uses fixed `op read --no-newline` arguments, no shell, closed stdin and bounded private output pipes. It preserves Unicode, leading/trailing whitespace and embedded newlines. Timeouts and cancellation terminate and wait for the child. Errors distinguish unavailable CLI, invalid references, authorization, rate limits and resolution failures through safe codes/messages; raw stdout/stderr are never logged, persisted or returned.++## Website login bindings++The **Browser profiles** panel enrolls username/password references with an exact login origin, a success origin/path and optional success selector. A binding may be restricted to a profile, workflow or employee; server resource authorization validates those restrictions. Saving a website binding does not retrieve a password or grant a desktop authorization. Model-visible discovery returns opaque IDs, labels, origins and supported fields, excluding vault/item references and values.++The browser owner first reads nonsecret metadata with `get_browser_credential_binding` and enforces policy, Ask first, task ownership and the current login target. It then persists a nonsecret sensitive-login latch, suspends the browser-use daemon and drains/gates captures and page metadata. Only after that can `resolve_browser_credentials` resolve values for the private CDP fill flow. Resolution rechecks ownership, scopes and the current enrollment after authorization waits. The browser revalidates the tab/frame/targets and origin before effects.++Passwords are filled through the existing private CDP connection. During this phase snapshots, page text, screenshots, vision, WebMCP and ordinary browser operations remain gated. A configured private success check ends the phase. An uncertain submit, changed target, failed suspension or unconfirmed completion retains the gate and requests human login. Ask first/read-only policies never receive an autofill bypass. Multi-step login, MFA and passkeys use existing human takeover.++## Verification and limits++Automated credential tests use fake subprocesses and nonsecret fixtures: no developer vault is read. Canaries cover exact value preservation, CLI argument/environment containment, bounded pipes, cancellation, safe errors, metadata-only reads, per-call rotation, scoped bindings, revoked enrollment during authorization, and absence of cluster fallback. Browser tests separately cover gated captures and private CDP login.++An isolated Windows smoke test provisioned the official 2.40.0 archive, verified its valid Agilebits publisher signature before executing it, and passed `ensure_cli()` plus `doctor()` with `{available: true, version: "2.40.0", auth_mode: "desktop"}`. This test only executed version inspection; it performed no desktop authorization, service-account authentication or vault access. The verifier excludes inherited PowerShell module paths so a backend launched from PowerShell 7 can also use the Windows PowerShell fallback safely. macOS/Linux publisher verification still needs platform acceptance.++Live desktop authorization remains a deployment acceptance check on the actual backend user/process and supported OS. A signed CLI pin does not establish vault permissions. Run explicitly authorized GitHub login/read-only issue summarization and Gmail human login/invoice summarization smoke tests only after controlled-fixture acceptance. Do not log actual credentials, vault contents or sign-in URLs during smoke testing.++Official references: [CLI installation and verification](https://www.1password.dev/cli/get-started), [release notes](https://app-updates.agilebits.com/product_history/CLI2), [read command](https://www.1password.dev/cli/reference/commands/read), [desktop authorization](https://www.1password.dev/cli/app-integration-security), [service accounts and Connect precedence](https://www.1password.dev/service-accounts/use-with-1password-cli).diff --git a/docs-internal/temporal-workflow-control.md b/docs-internal/temporal-workflow-control.mdindex 40b5fcd3..f275da57 100644--- a/docs-internal/temporal-workflow-control.md+++ b/docs-internal/temporal-workflow-control.md@@ -484,7 +484,7 @@ boot mid-reset can never sweep the namespace.## Workspace tasks-Phone tasks submitted directly from the Workspace run outside the control+Phone and Browser AI tasks submitted directly from the Workspace run outside the controlgeneration, under a per-workflow `WorkspaceTaskControllerWorkflow` (see[TEMPORAL_ARCHITECTURE.md → Direct Workspace tasks](./TEMPORAL_ARCHITECTURE.md#direct-workspace-tasks)).They can exist before the first Start and after a Reset. Pause and Resume do@@ -511,6 +511,83 @@ submissions. The control plane covers them in two places.controller is resetting, the payload reports `state: "resetting"` and turnsoff `can_start`, `can_pause`, `can_resume` and `can_edit`.+### Native Browser tasks++New Browser submissions carry server-generated `dispatch_version: 1`,+`history_version: 1` and `native_workspace_version: 1`. The controller persists+the history admission record before acknowledging acceptance, then starts+`NodeInvocationWorkflow → AgentWorkflow → model/tool Activities`. Existing+payloads without the dispatch version retain their single-Activity command+path. Submission UUIDs, stable invocation IDs, payload fingerprints and saved+workflow authorization remain the admission boundary; clients cannot submit+executable graphs, credential references or browser-owner addresses.++The submitted prompt is applied after saved configuration and template+preparation. It replaces the task prompt while preserving the Browser Agent's+system instructions. Generation-zero direct tasks use a separate transcript+and do not load or persist deployed Context. The narrow native Workspace+runtime capability allows Continue-As-New without enrolling these tasks in+Start/Stop/Resume generation control. Rollover carries the prepared payload,+transcript, tools, frozen policies, owner bindings, task token and authorized+artifact references; completed tool calls and model turns are not repeated.+Completion accounting remains at the invocation parent, once per task.++The API is `/api/browser/tasks`: POST accepts the saved workflow/agent IDs,+task prompt and submission UUID; GET `/discovery` resolves agents attached to+the selected saved Browser tool; GET `/history` returns recent tasks; GET and+DELETE `/{submission_id}` read status or cancel a task. History is a small+`WorkspaceTaskRecord` projection of Temporal execution, with idempotent+Activity writes and terminal compare-and-set protection. It stores bounded+public results and relative artifact references, excluding tool transcripts+and credential values. Pages default to 20 records and allow at most 100;+terminal records expire after 35 days while active records and Reset history+remain. Historical authorization uses the accessible workflow even after an+agent node is removed. Terminal projection records also prevent a repeated+submission from starting again after controller dedup eviction or expiration+of its Temporal execution history.++### Browser owners and confirmed cleanup++Distributed browser bindings freeze the profile, stable backend owner,+runtime epoch and owner-specific Activity queue. Browser Activities use that+queue even when the general worker-pool flag is disabled. Generic orchestration+workers do not register Browser Activities. Each backend registers and+heartbeats its owner before starting its dedicated Browser worker, using+logical plugin selection separately from the physical queue name. Ordinary+Browser nodes receive the same versioned owner routing; old inputs retain+their recorded routing behavior.++The native Agent child claims a profile for the entire task, including model+reasoning and human assistance. Competing tasks fail with `BrowserBusy`+before browser effects. A Continue-As-New reacquires the same token+idempotently and does not release the continuing task. Finalization routes+matching-token cleanup to the owner and waits for its receipt. Cancel and+Reset wait for the attached child and that cleanup; Reset does not resolve+mutable or deleted graph bindings again. An unavailable owner keeps its+ownership and leaves work queued with “Browser unavailable — waiting for its+owner.” Owner Activities have no schedule-to-close timeout; start-to-close+and heartbeat deadlines apply after pickup. Cleanup can therefore keep a+Reset in progress until the owner recovers.++Recovery retries retain the owner queue and attempt identity. The Browser+runtime refuses replay of mutating operations on later attempts and requires+fresh observation for uncertain effects. Renewed runtime epochs and nonsecret+assistance state are explicit owner metadata; Temporal does not restore+Chrome tabs or stale element references. No automatic profile transfer is+performed. Distributed deployment requires PostgreSQL, shared artifact+storage and an external shared Temporal service; local SQLite and embedded+Temporal remain supported.++The native integration gate in+`server/tests/temporal/test_browser_workspace_replay.py` runs separate+orchestration and two owner workers against a native Temporal test server.+It covers an absent owner, owner routing with worker pools disabled,+Continue-As-New, cancellation waiting for cleanup, artifact preservation and+SDK replay. Set `TEMPORAL_TEST_CLI` to a native Temporal binary to enable it;+the Activities are controlled fixtures and access no external accounts.+Existing replay fixtures continue to cover unversioned graph, agent and+invocation histories.+## Months-long generationsA controlled generation is expected to run — or stay paused — for months, sodiff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex c8e81813..ac5f4028 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -11,6 +11,7 @@"aiAgent","ai_employee","web_agent",+ "browser_agent","productivity_agent","coding_agent","social_agent",diff --git a/server/constants.py b/server/constants.pyindex 68dad8fb..1935b46f 100644--- a/server/constants.py+++ b/server/constants.py@@ -38,6 +38,7 @@ AI_AGENT_TYPES: FrozenSet[str] = frozenset("android_agent","coding_agent","web_agent",+ "browser_agent","task_agent","social_agent","travel_agent",diff --git a/server/core/config.py b/server/core/config.pyindex ee02014a..f4f54c3b 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -110,6 +110,17 @@ class Settings(BaseSettings):# and resolves under ``DATA_DIR`` like every other state path,# rather than being hardcoded inside a SQLAlchemy URL string.workflow_db_filename: str = Field(env="WORKFLOW_DB_FILENAME")+ database_url_override: Optional[str] = Field(default=None, validation_alias="DATABASE_URL")+ distributed_mode: bool = Field(default=False, validation_alias="DISTRIBUTED_MODE")+ browser_replica_id: Optional[str] = Field(default=None, max_length=120, validation_alias="BROWSER_REPLICA_ID")+ browser_machine_id: Optional[str] = Field(default=None, max_length=255, validation_alias="BROWSER_MACHINE_ID")+ browser_replica_url: Optional[str] = Field(default=None, validation_alias="BROWSER_REPLICA_URL")+ browser_router_secret: Optional[str] = Field(default=None, validation_alias="BROWSER_ROUTER_SECRET")+ onepassword_cli_path: Optional[str] = Field(default=None, validation_alias="ONEPASSWORD_CLI_PATH")+ onepassword_cli_version: str = Field(default="2.40.0", validation_alias="ONEPASSWORD_CLI_VERSION")+ onepassword_auth_mode: Literal["desktop", "service_account"] = Field(default="desktop", validation_alias="ONEPASSWORD_AUTH_MODE")+ onepassword_account: Optional[str] = Field(default=None, validation_alias="ONEPASSWORD_ACCOUNT")+ onepassword_read_timeout_seconds: float = Field(default=30, ge=1, le=300, validation_alias="ONEPASSWORD_READ_TIMEOUT_SECONDS")database_echo: bool = Field(default=False, env="DATABASE_ECHO")database_pool_size: int = Field(default=20, env="DATABASE_POOL_SIZE", ge=5, le=100)database_max_overflow: int = Field(default=30, env="DATABASE_MAX_OVERFLOW", ge=10, le=100)@@ -532,19 +543,42 @@ class Settings(BaseSettings):@propertydef database_url(self) -> str:- """Compose the SQLAlchemy URL from ``DATA_DIR`` + ``WORKFLOW_DB_FILENAME``.-- Always ``sqlite+aiosqlite:///<abspath>`` — the only DB engine- OpenCompany uses. Parent dir is mkdir'd here so the DB file can- be opened on first access without a separate bootstrap step.- Reads :meth:`_resolve_under_data` so the same DEV / daemon- toggle (``.env.dev`` swapping ``DATA_DIR=.opencompany``) that moves- every other state path moves ``workflow.db`` too.- """+ """Explicit shared PostgreSQL URL, or the existing local SQLite path."""+ if self.database_url_override:+ value = self.database_url_override+ if value.startswith("postgresql://"):+ value = "postgresql+asyncpg://" + value[len("postgresql://"):]+ if not value.startswith(("postgresql+asyncpg://", "sqlite+aiosqlite://")):+ raise ValueError("DATABASE_URL must use PostgreSQL asyncpg or SQLite aiosqlite")+ return valuedb_path = Path(self._resolve_under_data(self.workflow_db_filename))db_path.parent.mkdir(parents=True, exist_ok=True)return f"sqlite+aiosqlite:///{db_path}"+ @model_validator(mode="after")+ def _validate_distributed_browser(self):+ if not self.distributed_mode:+ return self+ from urllib.parse import urlsplit++ if not self.database_url.startswith("postgresql+asyncpg://"):+ raise ValueError("DISTRIBUTED_MODE requires a shared PostgreSQL DATABASE_URL")+ if not self.temporal_enabled or not self.temporal_agent_workflow_enabled or not self.temporal_per_type_dispatch:+ raise ValueError("Distributed Browser tasks require Temporal native agent and per-type dispatch")+ host = self.temporal_server_address.rsplit(":", 1)[0].strip("[]")+ if host in {"localhost", "127.0.0.1", "::1"}:+ raise ValueError("DISTRIBUTED_MODE requires an external shared TEMPORAL_SERVER_ADDRESS")+ if not self.browser_replica_id or not self.browser_replica_url:+ raise ValueError("DISTRIBUTED_MODE requires BROWSER_REPLICA_ID and BROWSER_REPLICA_URL")+ url = urlsplit(self.browser_replica_url)+ if url.scheme not in {"http", "https"} or not url.hostname or url.username or url.password or url.query or url.fragment or url.path not in {"", "/"}:+ raise ValueError("BROWSER_REPLICA_URL must be a trusted backend HTTP(S) origin")+ if self.workers != 1:+ raise ValueError("Each distributed backend replica must run one browser-owner process (WORKERS=1)")+ if self.onepassword_auth_mode != "service_account":+ raise ValueError("DISTRIBUTED_MODE requires ONEPASSWORD_AUTH_MODE=service_account")+ return self+@propertydef is_development(self) -> bool:"""Check if running in development mode."""@@ -595,6 +629,7 @@ class Settings(BaseSettings):# carrying ``TEMPORAL_BACKEND`` / ``TEMPORAL_BIND_LOCAL_ONLY`` /# etc. would raise ValidationError on startup."extra": "ignore",+ "populate_by_name": True,"env_parse_none_str": "none","env_nested_delimiter": "__",}diff --git a/server/core/database.py b/server/core/database.pyindex 9c346001..1b1083d5 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -75,6 +75,11 @@ from models.chat import ( # noqa: F401 - registers SQLModel tablesChatThread,)from models.cache import CacheEntry # SQLite-backed cache for Redis alternative+from models.workspace_tasks import WorkspaceTaskRecord # noqa: F401+from models.credential_sources import CredentialSource, BrowserCredentialBinding # noqa: F401+from models.browser_owners import BrowserOwner, BrowserProfileOwner, BrowserTransientRoute # noqa: F401+from models.browser_profiles import BrowserProfileRow # noqa: F401+from models.auth import User # noqa: F401from core.logging import get_loggerlogger = get_logger(__name__)@@ -145,17 +150,38 @@ class Database:# Create tablesasync with self.engine.begin() as conn:+ if self.engine.dialect.name == "postgresql":+ from core.shared_database import install_postgresql_timestamp_types+ install_postgresql_timestamp_types(SQLModel.metadata)+ await conn.execute(text("SELECT pg_advisory_xact_lock(763746822)"))await conn.run_sync(SQLModel.metadata.create_all)-- # Add missing columns to existing tables (simple migration)- await self._migrate_user_settings()- await self._migrate_agent_teams()- await self._migrate_workflow_controls()- await self._migrate_generation_scoped_runtime_data()- await self._migrate_chat_messages()- await self._migrate_chat_runs()- await self._migrate_approvals()- await self._migrate_employees()+ # Earlier development builds of the owner registry predate+ # the frozen viewer association. These nullable fields add no+ # ownership or task claims and preserve all recovery latches.+ from sqlalchemy import inspect as inspect_schema+ owner_columns = await conn.run_sync(lambda sync: {+ column["name"] for column in inspect_schema(sync).get_columns("browser_profile_owners")})+ for name in ("workflow_id", "browser_node_id"):+ if name not in owner_columns:+ await conn.execute(text(f"ALTER TABLE browser_profile_owners ADD COLUMN {name} VARCHAR(255)"))+ from models.browser_owners import BrowserProfileOwner+ for index in BrowserProfileOwner.__table__.indexes:+ await conn.run_sync(lambda sync, index=index: index.create(sync, checkfirst=True))++ # Existing SQLite upgrades retain their exact backfills. PostgreSQL+ # starts with the current SQLModel schema; legacy SQLite data is+ # moved explicitly by the offline database transfer command.+ if self.engine.dialect.name == "sqlite":+ await self._migrate_user_settings()+ await self._migrate_agent_teams()+ await self._migrate_workflow_controls()+ await self._migrate_generation_scoped_runtime_data()+ await self._migrate_chat_messages()+ await self._migrate_chat_runs()+ await self._migrate_approvals()+ await self._migrate_employees()+ else:+ await self._validate_shared_schema()logger.info("Database initialized successfully")@@ -163,6 +189,22 @@ class Database:logger.error("Database startup failed", error=str(e))raise+ async def _validate_shared_schema(self):+ """Fail before serving an incompatible shared schema; never mask drift."""+ from sqlalchemy import inspect as inspect_schema++ async with self.engine.connect() as connection:+ def missing(sync_connection):+ inspector = inspect_schema(sync_connection)+ absent = []+ for table in SQLModel.metadata.sorted_tables:+ names = {entry["name"] for entry in inspector.get_columns(table.name)}+ absent.extend(f"{table.name}.{column.name}" for column in table.columns if column.name not in names)+ return absent+ absent = await connection.run_sync(missing)+ if absent:+ raise RuntimeError("Shared database schema requires migration: " + ", ".join(absent))+async def allocate_identity(self, namespace: str) -> int:"""Atomically allocate the next positive integer in ``namespace``."""if not namespace or len(namespace) > 512:@@ -473,6 +515,10 @@ class Database:async with self.get_session() as session:if self.engine is not None and self.engine.dialect.name == "sqlite":await session.execute(text("BEGIN IMMEDIATE"))+ elif self.engine is not None and self.engine.dialect.name == "postgresql":+ # Match SQLite's existing write reservation for callers that+ # perform read/modify/write, including first-row creation.+ await session.execute(text("SELECT pg_advisory_xact_lock(763746821)"))yield sessionasync def _migrate_workflow_controls(self):@@ -704,6 +750,8 @@ class Database:await session.execute(text("BEGIN IMMEDIATE"))else:await session.begin()+ if self.engine is not None and self.engine.dialect.name == "postgresql":+ await session.execute(text("SELECT pg_advisory_xact_lock(763746821)"))if mutation_id:found = await session.execute(@@ -4094,14 +4142,13 @@ class Database:)}- await session.execute(- text(- "INSERT OR IGNORE INTO subagent_concurrency_counters "- "(root_execution_id, active_count, updated_at) "- "VALUES (:root, 0, CURRENT_TIMESTAMP)"- ),- {"root": root_execution_id},- )+ if self.engine.dialect.name == "postgresql":+ from sqlalchemy.dialects.postgresql import insert+ else:+ from sqlalchemy.dialects.sqlite import insert+ await session.execute(insert(SubagentConcurrencyCounter).values(+ root_execution_id=root_execution_id, active_count=0, updated_at=now+ ).on_conflict_do_nothing(index_elements=["root_execution_id"]))claimed = await session.execute(update(SubagentConcurrencyCounter).where(diff --git a/server/core/js_runtime.py b/server/core/js_runtime.pyindex c5826357..111241a4 100644--- a/server/core/js_runtime.py+++ b/server/core/js_runtime.py@@ -30,6 +30,7 @@ import jsonimport osimport shutilimport subprocess+from services.process_environment import without_onepassword_environmentimport sysfrom pathlib import Path@@ -111,7 +112,7 @@ def add_package(spec: str, *, trust: bool = False, root: Path | None = None) ->if trust:argv.append("--trust")argv.append(spec)- return subprocess.run(argv, capture_output=True, text=True)+ return subprocess.run(argv, capture_output=True, text=True, env=without_onepassword_environment())__all__ = [diff --git a/server/core/shared_database.py b/server/core/shared_database.pynew file mode 100644index 00000000..2fd4660b--- /dev/null+++ b/server/core/shared_database.py@@ -0,0 +1,30 @@+"""PostgreSQL timestamp compatibility for existing SQLModel UTC values."""+from datetime import datetime, timezone++from sqlalchemy import DateTime+from sqlalchemy.types import TypeDecorator+++class PostgreSQLUTCDateTime(TypeDecorator):+ """Keep SQLite unchanged; accept both existing UTC timestamp conventions."""+ impl = DateTime+ cache_ok = True++ def __init__(self, original: DateTime):+ super().__init__()+ self.original = original++ def load_dialect_impl(self, dialect):+ return dialect.type_descriptor(DateTime(timezone=True) if dialect.name == "postgresql" else self.original)++ def process_bind_param(self, value: datetime | None, dialect):+ if value is not None and dialect.name == "postgresql":+ return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)+ return value+++def install_postgresql_timestamp_types(metadata):+ for table in metadata.tables.values():+ for column in table.columns:+ if isinstance(column.type, DateTime):+ column.type = PostgreSQLUTCDateTime(column.type)diff --git a/server/integration_tests/test_browser_foundations.py b/server/integration_tests/test_browser_foundations.pynew file mode 100644index 00000000..601a3382--- /dev/null+++ b/server/integration_tests/test_browser_foundations.py@@ -0,0 +1,220 @@+"""Real application database/creation contracts, isolated from legacy stubs."""+import asyncio+from copy import deepcopy+from types import SimpleNamespace+from uuid import uuid4++import pytest+from fastapi import HTTPException+from sqlalchemy import select, text+from sqlmodel import SQLModel++import nodes # noqa: F401 - real plugin registry+from core.config import Settings+from core.database import Database+from models.database import NodeParameter+from routers import browser_agents+from services.browser_agent_recipe import browser_tool_id+from services.distributed_notifications import notification+from tools.database_transfer import export_manifest, import_manifest, validate_manifest+++def settings(**overrides):+ return Settings(_env_file=None, **{+ "host": "127.0.0.1", "port": 5678, "debug": False, "distributed_mode": False,+ "jwt_secret_key": "test-key-" * 8, "secret_key": "test-key-" * 8, "api_key_encryption_key": "test-key-" * 8,+ "cors_origins": [], "workflow_db_filename": "test.db", "temporal_enabled": False,+ "temporal_server_address": "127.0.0.1:7233", "temporal_namespace": "default", "temporal_task_queue": "test",+ "temporal_per_type_dispatch": True, "temporal_agent_workflow_enabled": True,+ "temporal_graceful_shutdown_seconds": 10, "temporal_frontend_grpc_port": 7233,+ "temporal_ui_port": 8233, "temporal_sqlite_path": "test.db", "temporal_terminate_running_on_startup": False,+ **overrides,+ })+++async def database(tmp_path):+ db = Database(settings(database_url_override=f"sqlite+aiosqlite:///{(tmp_path / 'source.db').as_posix()}"))+ await db.startup()+ try:+ yield db+ finally:+ await db.shutdown()+++async def saved_browser(database):+ await database.save_workflow(workflow_id="7", name="Browser", slug="Browser_7", data={+ "owner_id": "owner", "nodes": [{"id": "7:browser:1", "type": "browser", "data": {}, "position": {"x": 0, "y": 0}}], "edges": []})+ await database.save_node_parameters("7:browser:1", {"interaction": "read_only"})+++async def test_atomic_creation_concurrent_retry_reuses_selected_tool_and_deleted_context(database, monkeypatch):+ await saved_browser(database)+ monkeypatch.setattr(browser_agents, "container", SimpleNamespace(database=lambda: database))+ request = SimpleNamespace(state=SimpleNamespace(user_id="owner"))+ body = browser_agents.CreateBrowserAgent(workflow_id="7", browser_node_id="7:browser:1", mutation_id=uuid4(), provider="openai", model="inherited-model")+ first, retry = await asyncio.gather(browser_agents.create_browser_agent(body, request), browser_agents.create_browser_agent(body, request))+ assert first["node_ids"] == retry["node_ids"]+ assert sorted([first["applied"], retry["applied"]]) == [False, True]+ graph = (await database.get_workflow("7")).data+ assert sorted(node["type"] for node in graph["nodes"]) == ["browser", "browser_agent", "context", "masterSkill", "visionAnalyze"]+ ids = first["node_ids"]+ assert browser_tool_id(graph, ids["agent"]) == "7:browser:1"+ assert await database.get_node_parameters("7:browser:1") == {"interaction": "read_only"}+ assert (await database.get_node_parameters(ids["agent"]))["model"] == "inherited-model"+ assert (await database.get_node_parameters(ids["skills"]))["skills_config"]["browser-skill"]["enabled"] is True+ assert not any((node.get("data") or {}).get("isBrowserPanel") for node in graph["nodes"] if node["type"] == "browser_agent")+ context = ids["context"]+ graph["nodes"] = [node for node in graph["nodes"] if node["id"] != context]+ graph["edges"] = [edge for edge in graph["edges"] if edge["source"] != context]+ await database.save_workflow(workflow_id="7", name="Browser", slug="Browser_7", data=graph)+ second = await browser_agents.create_browser_agent(body.model_copy(update={"mutation_id": uuid4()}), request)+ assert second["node_ids"]["agent"] == ids["agent"]+ assert not second["operations"]+ assert not any(node["type"] == "context" for node in (await database.get_workflow("7")).data["nodes"])+ # Cached receipts remain authorized after graph ownership changes.+ graph["owner_id"] = "another-owner"+ await database.save_workflow(workflow_id="7", name="Browser", slug="Browser_7", data=graph)+ with pytest.raises(HTTPException) as exc:+ await browser_agents.create_browser_agent(body, request)+ assert exc.value.status_code == 404+++async def test_invalid_selected_tool_leaves_no_partial_companions(database, monkeypatch):+ await saved_browser(database)+ monkeypatch.setattr(browser_agents, "container", SimpleNamespace(database=lambda: database))+ with pytest.raises(HTTPException):+ await browser_agents.create_browser_agent(browser_agents.CreateBrowserAgent(workflow_id="7", browser_node_id="missing", mutation_id=uuid4()), SimpleNamespace(state=SimpleNamespace(user_id="owner")))+ assert len((await database.get_workflow("7")).data["nodes"]) == 1+ async with database.get_session() as session:+ assert len((await session.execute(select(NodeParameter))).scalars().all()) == 1+++async def test_offline_roundtrip_preserves_graph_ids_and_rejects_nonempty_target(database, tmp_path):+ await saved_browser(database)+ manifest = await export_manifest(database)+ assert "api_keys" not in manifest["tables"] and "browser_owners" not in manifest["tables"]+ target = Database(settings(database_url_override=f"sqlite+aiosqlite:///{(tmp_path / 'target.db').as_posix()}"))+ await target.startup()+ try:+ await import_manifest(target, manifest)+ assert (await target.get_workflow("7")).data == (await database.get_workflow("7")).data+ assert await target.get_node_parameters("7:browser:1") == {"interaction": "read_only"}+ with pytest.raises(ValueError, match="empty target"):+ await import_manifest(target, manifest)+ finally:+ await target.shutdown()+ invalid = deepcopy(manifest)+ invalid["tables"]["node_parameters"][0]["parameters"]["api_key"] = "SECRET_CANARY"+ with pytest.raises(ValueError, match="inline credentials"):+ validate_manifest(invalid)+ invalid = deepcopy(manifest)+ invalid["tables"]["oauth_tokens"] = []+ with pytest.raises(ValueError, match="excluded"):+ validate_manifest(invalid)+++async def test_offline_transfer_keeps_legacy_and_gated_profiles_on_original_machine(database, tmp_path):+ from models.browser_profiles import BrowserProfileRow+ from models.browser_owners import BrowserOwner, BrowserProfileOwner+ async with database.get_session() as session:+ session.add(BrowserProfileRow(id="legacy", owner_id="owner", name="Legacy"))+ session.add(BrowserProfileRow(id="gated", owner_id="owner", name="Gated"))+ session.add(BrowserProfileOwner(profile_id="gated", principal_id="owner", owner_id="local",+ sensitive_login=True, needs_observation=True, challenge_required=True))+ await session.commit()+ manifest = await export_manifest(database)+ owners = {row["profile_id"]: row for row in manifest["tables"]["browser_profile_owners"]}+ assert owners["legacy"]["owner_id"] == "local"+ assert owners["gated"]["sensitive_login"] is True+ target = Database(settings(database_url_override=f"sqlite+aiosqlite:///{(tmp_path / 'profiles.db').as_posix()}"))+ await target.startup()+ try:+ await import_manifest(target, manifest)+ async with target.get_session() as session:+ owner = await session.get(BrowserOwner, "local")+ assert owner.machine_id == manifest["local_owner_machine_id"]+ assert owner.runtime_epoch == "offline-import" and owner.heartbeat_at == 0+ assert (await session.get(BrowserProfileOwner, "gated")).sensitive_login is True+ finally:+ await target.shutdown()+++async def test_cluster_preflight_only_checks_incoming_capability_and_principal(database, monkeypatch):+ from unittest.mock import AsyncMock+ from core.container import container+ from services import node_registry+ from services.plugin.credential import CREDENTIAL_REGISTRY, ApiKeyCredential+ from services.credentials.preflight import assert_cluster_credentials+ from services.credentials.onepassword import CredentialSourceError+ classes = {"browser_agent": SimpleNamespace(credentials=[]),+ "static": SimpleNamespace(credentials=[CREDENTIAL_REGISTRY["openai"]]),+ "multi": SimpleNamespace(credentials=[type("MultiFieldCredential", (ApiKeyCredential,), {"extra_fields": ["app_secret"]})]),+ "oauth": SimpleNamespace(credentials=[object])}+ monkeypatch.setattr(node_registry, "get_node_class", classes.get)+ auth = SimpleNamespace(distributed_credentials=True, get_credential_source=AsyncMock(return_value={"source": "onepassword"}))+ monkeypatch.setattr(container, "auth_service", lambda: auth)+ graph = {"nodes": [{"id": "agent", "type": "browser_agent"}, {"id": "key", "type": "static"},+ {"id": "lead", "type": "oauth"}], "edges": [+ {"source": "key", "target": "agent", "targetHandle": "input-tools"},+ {"source": "agent", "target": "lead", "targetHandle": "input-teammates"}]}+ await assert_cluster_credentials(database, graph, {"node_id": "agent", "user_id": "member"})+ auth.get_credential_source.assert_awaited_once_with("openai", principal="member")+ with pytest.raises(CredentialSourceError, match="OAuth"):+ await assert_cluster_credentials(database, graph, {"user_id": "member"})+ with pytest.raises(CredentialSourceError, match="additional credential fields"):+ await assert_cluster_credentials(database, {"nodes": [{"id": "multi", "type": "multi"}]}, {"user_id": "member"})+++async def assert_owner_registry_upgrade(database):+ from models.browser_owners import BrowserProfileOwner+ async with database.get_session() as session:+ session.add(BrowserProfileOwner(profile_id="prototype-profile", principal_id="owner", owner_id="local",+ sensitive_login=True, needs_observation=True))+ await session.commit()+ async with database.engine.begin() as connection:+ await connection.execute(text("DROP INDEX IF EXISTS ix_browser_profile_owners_workflow_id"))+ await connection.execute(text("DROP INDEX IF EXISTS ix_browser_profile_owners_browser_node_id"))+ await connection.execute(text("ALTER TABLE browser_profile_owners DROP COLUMN workflow_id"))+ await connection.execute(text("ALTER TABLE browser_profile_owners DROP COLUMN browser_node_id"))+ await database.shutdown()+ await database.startup()+ async with database.get_session() as session:+ row = await session.get(BrowserProfileOwner, "prototype-profile")+ assert row.sensitive_login is True and row.needs_observation is True+ assert row.workflow_id is None and row.browser_node_id is None+++async def test_sqlite_owner_registry_upgrade_preserves_recovery_latches(database):+ await assert_owner_registry_upgrade(database)+++def test_postgresql_notification_excludes_page_and_secret_payloads():+ message = {"type": "browser_updated", "data": {"data": {+ "workflow_id": "7", "node_id": "7:browser:1", "session_id": "session", "state": "awaiting_user",+ "url": "SECRET_CANARY", "title": "SECRET_CANARY", "frames": ["SECRET_CANARY"]}}}+ assert notification(message, "replica") == {"origin": "replica", "kind": "browser_updated", "workflow_id": "7", "node_id": "7:browser:1", "session_id": "session"}+ assert notification({"type": "node_output", "output": "SECRET_CANARY"}, "replica") is None+++def test_cluster_settings_require_shared_prerequisites():+ from pydantic import ValidationError+ with pytest.raises(ValidationError, match="shared PostgreSQL"):+ settings(distributed_mode=True, database_url_override="sqlite+aiosqlite:///local.db")+ configured = settings(distributed_mode=True,+ database_url_override="postgresql://test:[email protected]/opencompany",+ temporal_server_address="temporal.test:7233", temporal_enabled=True,+ temporal_agent_workflow_enabled=True, temporal_per_type_dispatch=True,+ browser_replica_id="backend-a", browser_replica_url="http://backend-a.test:5678",+ onepassword_auth_mode="service_account", workers=1)+ assert configured.database_url.startswith("postgresql+asyncpg://")+++def test_every_shared_datetime_column_accepts_legacy_utc_conventions():+ from datetime import datetime, timezone+ from sqlalchemy.dialects.postgresql import dialect+ from core.shared_database import install_postgresql_timestamp_types, PostgreSQLUTCDateTime+ install_postgresql_timestamp_types(SQLModel.metadata)+ column = NodeParameter.__table__.c.created_at+ assert isinstance(column.type, PostgreSQLUTCDateTime)+ assert column.type.process_bind_param(datetime(2026, 10, 8), dialect()).tzinfo == timezone.utcdiff --git a/server/integration_tests/test_postgresql_browser.py b/server/integration_tests/test_postgresql_browser.pynew file mode 100644index 00000000..e3f77289--- /dev/null+++ b/server/integration_tests/test_postgresql_browser.py@@ -0,0 +1,134 @@+"""Real PostgreSQL migration, admission/claims and replica notifications.++Set TEST_POSTGRES_URL to a PostgreSQL database where the test role may create+temporary databases. Existing databases and tables are never cleared.+"""+import asyncio+import json+import os+from types import SimpleNamespace+from uuid import uuid4++import asyncpg+import pytest+from sqlalchemy import select++from core.database import Database+from integration_tests.test_browser_foundations import settings, saved_browser, assert_owner_registry_upgrade+from models.browser_owners import BrowserOwner, BrowserProfileOwner+from models.database import NodeParameter+from services.distributed_notifications import BrowserNotifications+from services.plugin import NodeUserError+from services.user_auth import UserAuthService+from services.workspace_task_history import admit, transition, list_tasks+from tools.database_transfer import export_manifest, import_manifest+++async def postgres():+ base = os.environ.get("TEST_POSTGRES_URL")+ if not base:+ pytest.skip("TEST_POSTGRES_URL is required for live shared database validation")+ admin = await asyncpg.connect(base.replace("postgresql+asyncpg://", "postgresql://"))+ name = "oc_browser_test_" + uuid4().hex+ await admin.execute(f'CREATE DATABASE "{name}"')+ from sqlalchemy.engine import make_url+ url = make_url(base).set(drivername="postgresql+asyncpg", database=name).render_as_string(hide_password=False)+ database = Database(settings(database_url_override=url))+ await database.startup()+ try:+ yield database+ finally:+ await database.shutdown()+ await admin.execute(f'DROP DATABASE "{name}"')+ await admin.close()+++async def test_postgresql_import_and_sequence_reseed(postgres, tmp_path):+ source = Database(settings(database_url_override=f"sqlite+aiosqlite:///{(tmp_path / 'transfer.db').as_posix()}"))+ await source.startup()+ try:+ await saved_browser(source)+ from models.browser_profiles import BrowserProfileRow+ async with source.get_session() as session:+ session.add(BrowserProfileRow(id="legacy-profile", owner_id="owner", name="Imported profile"))+ await session.commit()+ exported = await export_manifest(source)+ await import_manifest(postgres, exported)+ assert (await postgres.get_workflow("7")).data == (await source.get_workflow("7")).data+ original_id = exported["tables"]["node_parameters"][0]["id"]+ await postgres.save_node_parameters("7:visionAnalyze:1", {})+ async with postgres.get_session() as session:+ row = (await session.execute(select(NodeParameter).where(NodeParameter.node_id == "7:visionAnalyze:1"))).scalar_one()+ assert row.id > original_id+ assert (await session.get(BrowserProfileOwner, "legacy-profile")).owner_id == "local"+ assert (await session.get(BrowserOwner, "local")).machine_id == exported["local_owner_machine_id"]+ finally:+ await source.shutdown()+++async def test_postgresql_atomic_claims_and_stale_cleanup(postgres, monkeypatch):+ from nodes.browser._profiles import ProfileStore+ from services import browser_owners as owners+ cfg = SimpleNamespace(distributed_mode=False)+ monkeypatch.setattr(owners, "settings", lambda: cfg)+ profile = await ProfileStore(postgres).create("owner", "Concurrent claim")+ binding = await owners.bind_profile(postgres, profile.id, "owner")+ results = await asyncio.gather(+ owners.claim_browser_task(postgres, binding, "owner", "task-a"),+ owners.claim_browser_task(postgres, binding, "owner", "task-b"), return_exceptions=True)+ assert sum(isinstance(result, NodeUserError) for result in results) == 1+ winner = "task-a" if not isinstance(results[0], Exception) else "task-b"+ assert (await owners.cleanup_browser_task(postgres, binding, "stale-task"))["released"] is False+ async with postgres.get_session() as session:+ assert (await session.get(BrowserProfileOwner, profile.id)).task_id == winner+ await owners.cleanup_browser_task(postgres, binding, winner)+ async with postgres.get_session() as session:+ assert (await session.get(BrowserProfileOwner, profile.id)).task_id is None+++async def test_postgresql_owner_registry_upgrade_preserves_recovery_latches(postgres):+ await assert_owner_registry_upgrade(postgres)+++async def test_postgresql_first_owner_registration_is_exclusive(postgres):+ auth = UserAuthService(postgres, postgres.settings, None, None)+ results = await asyncio.gather(auth.register("[email protected]", "fixture-password", "A"),+ auth.register("[email protected]", "fixture-password", "B"))+ assert sum(user is not None and user.is_owner for user, _ in results) == 1+ assert sum(error is not None for _, error in results) == 1+++async def test_postgresql_history_admission_retry_and_terminal_updates(postgres):+ await saved_browser(postgres)+ payload = {"history_record": {"invocation_id": "invocation", "submission_id": str(uuid4()), "workflow_id": "7",+ "node_id": "removed", "principal": "owner", "fingerprint": "hash", "prompt": "Read fixture account"}}+ await asyncio.gather(admit(postgres, payload), admit(postgres, payload))+ await transition(postgres, {"invocation_id": "invocation", "status": "completed", "result": {"response": "done"}})+ await asyncio.gather(transition(postgres, {"invocation_id": "invocation", "status": "running"}),+ transition(postgres, {"invocation_id": "invocation", "status": "failed"}))+ rows = (await list_tasks(postgres, "owner", "7"))["items"]+ assert len(rows) == 1 and rows[0]["status"] == "completed" and rows[0]["result"]["response"] == "done"+++async def test_postgresql_replicas_deliver_identifier_only_invalidation(postgres):+ class Broadcaster:+ def __init__(self):+ self.messages, self.received = [], asyncio.Event()+ async def broadcast(self, message, **kwargs):+ self.messages.append(message)+ self.received.set()+ first, second = Broadcaster(), Broadcaster()+ a, b = BrowserNotifications(postgres, first), BrowserNotifications(postgres, second)+ await a.start()+ await b.start()+ try:+ await a.publish({"type": "browser_updated", "data": {"data": {"workflow_id": "7", "node_id": "7:browser:1",+ "session_id": "browser-session", "url": "SECRET_CANARY", "frames": "SECRET_CANARY"}}})+ await asyncio.wait_for(second.received.wait(), 5)+ assert first.messages == []+ assert second.messages == [{"type": "browser_invalidated", "data": {"workflow_id": "7", "node_id": "7:browser:1", "session_id": "browser-session"}}]+ assert "SECRET_CANARY" not in json.dumps(second.messages)+ finally:+ await a.stop()+ await b.stop()diff --git a/server/main.py b/server/main.pyindex 7956d722..3ab126b8 100644--- a/server/main.py+++ b/server/main.py@@ -75,7 +75,7 @@ _startup_log("Importing DI container + all services...")from core.container import container_startup_log("Importing routers...")-from routers import workflow, database, websocket, webhook, auth, credentials, schemas, workspace+from routers import workflow, database, websocket, webhook, auth, credentials, schemas, workspace, browser_agents, browser_tasks_startup_log("All imports complete")@@ -196,6 +196,9 @@ async def lifespan(app: FastAPI):# Start servicesawait container.database().startup()await container.cache().startup()+ from services import distributed_notifications+ from services.status_broadcaster import get_status_broadcaster+ await distributed_notifications.start(container.database(), get_status_broadcaster())_startup_log("Database + cache started")# Ends chat runs nothing will finish (never picked up, or their run@@ -531,6 +534,7 @@ async def lifespan(app: FastAPI):await container.chat_unifier().aclose()_startup_log("Lifespan shutdown: LLM clients closed")await container.cache().shutdown()+ await distributed_notifications.stop()_startup_log("Lifespan shutdown: cache closed")await container.database().shutdown()_startup_log("Lifespan shutdown complete")@@ -612,6 +616,8 @@ app.include_router(websocket.router)app.include_router(credentials.router) # Credentials panel - lazy per-tile icon endpoint (n8n pattern)app.include_router(schemas.router) # Per-node output schema endpoint (GET /api/schemas/nodes/{type}.json)app.include_router(workspace.router) # Per-workflow workspace file serving + uploads+app.include_router(browser_agents.router)+app.include_router(browser_tasks.router)# Desktop shell control surface — mounted only under OPENCOMPANY_DESKTOP=1# so the token-gated shutdown route does not exist on server deployments.diff --git a/server/middleware/auth.py b/server/middleware/auth.pyindex de6384fd..575af3ec 100644--- a/server/middleware/auth.py+++ b/server/middleware/auth.py@@ -24,6 +24,7 @@ PUBLIC_PATHS = frozenset("/api/auth/register","/api/auth/logout","/ws/internal", # Internal WebSocket for Temporal workers+ "/api/browser/owner/command", # Owner route verifies scoped signed forwarding itself.])diff --git a/server/models/browser_owners.py b/server/models/browser_owners.pynew file mode 100644index 00000000..6ae6c4ec--- /dev/null+++ b/server/models/browser_owners.py@@ -0,0 +1,41 @@+"""Durable browser routing and nonsecret control state."""+from datetime import datetime, timezone+from typing import Optional+import socket+from sqlmodel import Field, SQLModel++class BrowserOwner(SQLModel, table=True):+ __tablename__ = "browser_owners"+ owner_id: str = Field(primary_key=True, max_length=120)+ runtime_epoch: str = Field(max_length=40)+ machine_id: str = Field(default_factory=socket.gethostname, max_length=255)+ base_url: str = Field(max_length=1024)+ heartbeat_at: float+++class BrowserProfileOwner(SQLModel, table=True):+ __tablename__ = "browser_profile_owners"+ profile_id: str = Field(primary_key=True, max_length=64)+ principal_id: str = Field(index=True, max_length=255)+ owner_id: str = Field(index=True, max_length=120)+ runtime_epoch: Optional[str] = Field(default=None, max_length=40)+ task_id: Optional[str] = Field(default=None, max_length=1024)+ workflow_id: Optional[str] = Field(default=None, index=True, max_length=255)+ browser_node_id: Optional[str] = Field(default=None, index=True, max_length=255)+ sensitive_login: bool = False+ needs_observation: bool = False+ challenge_required: bool = False+ assistance_reason: Optional[str] = Field(default=None, max_length=40)+ assistance_message: Optional[str] = Field(default=None, max_length=500)+ assistance_deadline: Optional[float] = None+ updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))+++class BrowserTransientRoute(SQLModel, table=True):+ """Nonsecret routing for expiring login/import handles; no cookies here."""+ __tablename__ = "browser_transient_routes"+ handle_id: str = Field(primary_key=True, max_length=64)+ principal_id: str = Field(index=True, max_length=255)+ owner_id: str = Field(max_length=120)+ profile_id: Optional[str] = Field(default=None, max_length=64)+ expires_at: floatdiff --git a/server/models/browser_profiles.py b/server/models/browser_profiles.pynew file mode 100644index 00000000..36f07009--- /dev/null+++ b/server/models/browser_profiles.py@@ -0,0 +1,28 @@+"""Browser profile metadata. Profile files and cookie values stay outside SQL."""+from datetime import datetime, timezone+from typing import Any, Dict, List, Optional++from sqlalchemy import JSON, Column, UniqueConstraint, Index, func, text+from sqlmodel import Field, SQLModel+++def _utcnow() -> datetime:+ return datetime.now(timezone.utc)+++class BrowserProfileRow(SQLModel, table=True):+ __tablename__ = "browser_profiles"+ __table_args__ = (UniqueConstraint("owner_id", "workflow_id", "kind", name="uq_browser_profile_workflow"),)+ id: str = Field(primary_key=True, max_length=40)+ owner_id: str = Field(default="owner", index=True, max_length=255)+ name: str = Field(max_length=120)+ kind: str = Field(default="shared", max_length=20)+ workflow_id: Optional[str] = Field(default=None, index=True, max_length=255)+ chrome_major: Optional[int] = Field(default=None)+ sites: Optional[List[Dict[str, Any]]] = Field(default=None, sa_column=Column(JSON))+ created_at: datetime = Field(default_factory=_utcnow)+ updated_at: datetime = Field(default_factory=_utcnow)+++Index("uq_browser_profile_shared_name", BrowserProfileRow.owner_id, func.lower(BrowserProfileRow.name),+ unique=True, sqlite_where=text("kind = 'shared'"), postgresql_where=text("kind = 'shared'"))diff --git a/server/models/credential_sources.py b/server/models/credential_sources.pynew file mode 100644index 00000000..c542dd66--- /dev/null+++ b/server/models/credential_sources.py@@ -0,0 +1,41 @@+"""Nonsecret 1Password enrollment metadata, shared through the application DB."""++from datetime import datetime, timezone+from typing import Any, Dict, List, Optional++from sqlalchemy import Column, JSON, UniqueConstraint+from sqlmodel import Field, SQLModel+++class CredentialSource(SQLModel, table=True):+ __tablename__ = "credential_sources"+ __table_args__ = (UniqueConstraint("session_id", "provider"),)++ id: str = Field(primary_key=True, max_length=64)+ session_id: str = Field(default="default", index=True, max_length=255)+ owner_id: str = Field(index=True, max_length=255)+ provider: str = Field(index=True, max_length=255)+ reference: str = Field(max_length=512)+ models: List[str] = Field(default_factory=list, sa_column=Column(JSON, nullable=False))+ model_params: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))+ # Endpoints are public configuration, never secret-bearing URLs.+ base_url: Optional[str] = Field(default=None, max_length=2048)+ updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))+++class BrowserCredentialBinding(SQLModel, table=True):+ __tablename__ = "browser_credential_bindings"++ id: str = Field(primary_key=True, max_length=64)+ owner_id: str = Field(index=True, max_length=255)+ label: str = Field(max_length=128)+ origin: str = Field(max_length=2048)+ username_reference: str = Field(max_length=512)+ password_reference: str = Field(max_length=512)+ profile_id: Optional[str] = Field(default=None, max_length=255)+ employee_id: Optional[str] = Field(default=None, max_length=255)+ workflow_id: Optional[str] = Field(default=None, max_length=255)+ success_origin: str = Field(max_length=2048)+ success_path: str = Field(max_length=1024)+ success_selector: str = Field(default="", max_length=512)+ updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))diff --git a/server/models/workspace_tasks.py b/server/models/workspace_tasks.pynew file mode 100644index 00000000..ba832c0f--- /dev/null+++ b/server/models/workspace_tasks.py@@ -0,0 +1,25 @@+"""Small, non-transcript projection of durable Workspace task executions."""++from datetime import datetime, timezone+from typing import Any++from sqlalchemy import Column, DateTime, JSON+from sqlmodel import Field, SQLModel+++class WorkspaceTaskRecord(SQLModel, table=True):+ __tablename__ = "workspace_task_records"++ invocation_id: str = Field(primary_key=True, max_length=256)+ submission_id: str = Field(max_length=36)+ principal: str = Field(index=True, max_length=255)+ workflow_id: str = Field(index=True, max_length=255)+ node_id: str = Field(index=True, max_length=255)+ fingerprint: str = Field(max_length=128)+ prompt: str = Field(max_length=20000)+ status: str = Field(default="queued", index=True, max_length=32)+ result: dict[str, Any] | None = Field(default=None, sa_column=Column(JSON))+ browser_owner_ids: list[str] = Field(default_factory=list, sa_column=Column(JSON))+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), sa_column=Column(DateTime(timezone=True), index=True))+ updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), sa_column=Column(DateTime(timezone=True)))+ completed_at: datetime | None = Field(default=None, sa_column=Column(DateTime(timezone=True), index=True))diff --git a/server/nodes/README.md b/server/nodes/README.mdindex 41212d4c..3703aae7 100644--- a/server/nodes/README.md+++ b/server/nodes/README.md@@ -118,6 +118,12 @@ used when the execution's frozen worker-pool setting is enabled; with poolsdisabled the default worker receives the operation. The in-process executordoes not enforce Temporal Activity policies.+Distributed Browser Activities are an exception to the pool switch: their+frozen profile binding selects an owner-specific queue even with worker pools+disabled. Each backend runs that worker; generic orchestration workers must+exclude Browser Activities. Do not route browser effects onto a generic queue.+See [Browser deployment](../../docs-internal/browser_agent_deployment.md).+New deployment generations (`execution_control_version=1`) record resolvedtool bindings and these policies during agent preparation. Ordinary per-typeagent tools use that recorded policy, including attempt limits and@@ -612,11 +618,16 @@ Full reference: [docs-internal/plugin_system.md → "Self-contained plugin folde`model_config = ConfigDict(json_schema_extra={"groups": {...}})`.Main-entry fields stay top-level. Full spec in[`docs-internal/plugin_system.md`](../../docs-internal/plugin_system.md).-- **Never declare `api_key` as a Params field.** Credentials live in- the credentials DB via `ApiKeyCredential` / `OAuthCredential`- subclasses and auto-inject at execution time. Plugins that need the+- **Never declare `api_key` as a Params field.** Use `ApiKeyCredential` /+ `OAuthCredential` subclasses and `AuthService`. Local credentials use the+ encrypted database; approved 1Password bindings resolve privately at the+ calling Activity, with the trusted principal. Catalogue and form reads use+ saved source metadata. Plugins that need theinjected key read `ctx.raw["_raw_parameters"]["api_key"]` — it'sstashed before Pydantic validation strips it.+ Distributed mode requires an audited static-secret adapter and rejects+ local keys, inline secrets, OAuth refresh stores and CLI-managed sessions.+ See [1Password credentials](../../docs-internal/onepassword_credentials.md).- **`isConfigNode` is auto-derived — don't declare it.** Pluginswhose `group` tuple contains `"memory"` or `"tool"` automaticallyexport `uiHints.isConfigNode: True` (set by `_derive_auto_ui_hints`diff --git a/server/nodes/agent/_vertex.py b/server/nodes/agent/_vertex.pyindex ea2ff70c..9e651955 100644--- a/server/nodes/agent/_vertex.py+++ b/server/nodes/agent/_vertex.py@@ -107,6 +107,8 @@ def build_genai_client(api_key: str, project_id: str, location: str = DEFAULT_LOfrom google import genaiif project_id:+ from services.plugin.deps import get_ai_service+ get_ai_service().auth.require_local_credentials()# Enterprise Agent Platform surface — ADC auth (gcloud).return genai.Client(enterprise=True,@@ -138,7 +140,7 @@ def resolve_api_key_from_context(raw_context: dict) -> str:return ""-async def resolve_gemini_api_key_from_store() -> str:+async def resolve_gemini_api_key_from_store(raw_context: dict | None = None) -> str:"""Fetch the stored gemini credential for nodes outside AI_MODEL_TYPES.``vertex_agent_admin`` is not an agent/model type, so@@ -147,8 +149,11 @@ async def resolve_gemini_api_key_from_store() -> str:"""from services.plugin.deps import get_ai_service+ from services.credentials.onepassword import CredentialSourceErrortry:- key = await get_ai_service().auth.get_api_key("gemini", "default")+ key = await get_ai_service().auth.resolve_api_key("gemini", "default", principal=(raw_context or {}).get("user_id"))+ except CredentialSourceError:+ raiseexcept Exception: # noqa: BLE001 — missing key is handled by the callerreturn ""return key or ""diff --git a/server/nodes/agent/browser_agent/__init__.py b/server/nodes/agent/browser_agent/__init__.pynew file mode 100644index 00000000..77b36bca--- /dev/null+++ b/server/nodes/agent/browser_agent/__init__.py@@ -0,0 +1,55 @@+"""Native Browser AI Agent; browser control remains in its connected tool."""+from typing import Any, Optional++from pydantic import Field++from services.browser_agent_recipe import BROWSER_AGENT_ROLE, browser_tool_id+from services.plugin import NodeContext, Operation+from .._specialized import SpecializedAgentBase, SpecializedAgentParams+++class BrowserAgentParams(SpecializedAgentParams):+ system_message: Optional[str] = Field(default=BROWSER_AGENT_ROLE)+++class BrowserAgentNode(SpecializedAgentBase):+ type = "browser_agent"+ display_name = "Browser AI Agent"+ subtitle = "Browser tasks"+ description = "Complete browser tasks with saved policies, secure login and human takeover."+ group = ("agent",)+ workspace_task = True+ Params = BrowserAgentParams++ @Operation("execute", cost={"service": "specialized_agent", "action": "run", "count": 1})+ async def execute_op(self, ctx: NodeContext, params: BrowserAgentParams) -> Any:+ from services.plugin.deps import get_database+ from services.browser_owners import routing_for_node, claim_browser_task, cleanup_browser_task++ graph = {"nodes": ctx.raw.get("nodes", []), "edges": ctx.raw.get("edges", [])}+ tool = browser_tool_id(graph, ctx.node_id)+ database = get_database()+ principal = str(ctx.raw.get("user_id") or "owner")+ binding = await routing_for_node(database, ctx.workflow_id, tool, principal)+ execution = str(ctx.raw.get("execution_id") or ctx.raw.get("session_id") or ctx.node_id)+ invocation = ctx.raw.get("parent_task_id") or ctx.raw.get("team_task_id") or execution+ task_id = f"{invocation}:{ctx.node_id}"+ await claim_browser_task(database, binding, principal, task_id)+ ctx.raw["browser_bindings"] = {tool: binding}+ ctx.raw["_browser_task_id"] = task_id+ try:+ return await super().execute_op(ctx, params)+ finally:+ await cleanup_browser_task(database, binding, task_id)++ @classmethod+ async def reset_execution_state(cls, *, node_id: str, workflow_id: str, execution_id: str,+ generation: int, graph: dict, database: Any) -> dict:+ from services.browser_owners import routing_for_node, cleanup_browser_task++ if not execution_id:+ return {"reset": False}+ tool = browser_tool_id(graph, node_id)+ principal = str(graph.get("owner_id") or "owner")+ binding = await routing_for_node(database, workflow_id, tool, principal)+ return await cleanup_browser_task(database, binding, f"{execution_id}:{node_id}")diff --git a/server/nodes/agent/browser_agent/icon.svg b/server/nodes/agent/browser_agent/icon.svgnew file mode 100644index 00000000..e3529db3--- /dev/null+++ b/server/nodes/agent/browser_agent/icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="18" rx="3"/><path d="M2 8h20M5 5.5h.01M8 5.5h.01"/><circle cx="12" cy="14.5" r="4.5"/><path d="M7.5 14.5h9M12 10c-2 2-2 7 0 9 2-2 2-7 0-9Z"/></svg>diff --git a/server/nodes/agent/browser_agent/meta.json b/server/nodes/agent/browser_agent/meta.jsonnew file mode 100644index 00000000..7f4206ea--- /dev/null+++ b/server/nodes/agent/browser_agent/meta.json@@ -0,0 +1 @@+{"color":"#8be9fd"}diff --git a/server/nodes/agent/claude_code_agent/_oauth.py b/server/nodes/agent/claude_code_agent/_oauth.pyindex 4e0415da..fb1ec656 100644--- a/server/nodes/agent/claude_code_agent/_oauth.py+++ b/server/nodes/agent/claude_code_agent/_oauth.py@@ -38,6 +38,7 @@ from __future__ import annotationsimport asyncioimport jsonimport os+from services.process_environment import without_onepassword_environmentfrom typing import Any, Dictfrom core.js_runtime import add_package, shared_tree_bin@@ -125,7 +126,7 @@ def claude_binary_path() -> str:def _claude_env() -> Dict[str, str]:env = os.environ.copy()env["CLAUDE_CONFIG_DIR"] = str(OPENCOMPANY_CLAUDE_DIR)- return env+ return without_onepassword_environment(env)async def _run_auth(subcommand: str, *, timeout: float) -> Dict[str, Any]:diff --git a/server/nodes/agent/claude_code_agent/_pool.py b/server/nodes/agent/claude_code_agent/_pool.pyindex 02dce6be..e7a1b70a 100644--- a/server/nodes/agent/claude_code_agent/_pool.py+++ b/server/nodes/agent/claude_code_agent/_pool.py@@ -768,10 +768,11 @@ class ClaudeSessionPool:# Subprocess spawn — the VSCode-extension pattern. PIPE on# stdin/stdout/stderr; no PTY. The stdout-reader task below# parses each stream-json line into an event and dispatches it.+ from services.process_environment import without_onepassword_environmentprocess = await asyncio.create_subprocess_exec(*argv,cwd=str(cwd),- env=env,+ env=without_onepassword_environment(env),stdin=asyncio.subprocess.PIPE,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,diff --git a/server/nodes/agent/vertex_agent_admin/__init__.py b/server/nodes/agent/vertex_agent_admin/__init__.pyindex f72e6271..5ecd6e2a 100644--- a/server/nodes/agent/vertex_agent_admin/__init__.py+++ b/server/nodes/agent/vertex_agent_admin/__init__.py@@ -126,8 +126,8 @@ class VertexAgentAdminNode(ActionNode):Params = VertexAgentAdminParamsOutput = VertexAgentAdminOutput- async def _client(self, params: VertexAgentAdminParams) -> Any:- api_key = "" if params.project_id else await resolve_gemini_api_key_from_store()+ async def _client(self, params: VertexAgentAdminParams, ctx: NodeContext) -> Any:+ api_key = "" if params.project_id else await resolve_gemini_api_key_from_store(ctx.raw)return build_genai_client(api_key, params.project_id, params.location)@staticmethod@@ -144,7 +144,7 @@ class VertexAgentAdminNode(ActionNode):from services.status_broadcaster import get_status_broadcasteragent_id = self._require_agent_id(params)- client = await self._client(params)+ client = await self._client(params, ctx)await get_status_broadcaster().update_node_status(ctx.node_id,"executing",@@ -172,7 +172,7 @@ class VertexAgentAdminNode(ActionNode):@Operation("list", cost={"service": "vertex_agent", "action": "list", "count": 1})async def list_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:- client = await self._client(params)+ client = await self._client(params, ctx)try:response = await client.aio.agents.list()except Exception as exc: # noqa: BLE001 — mapped below@@ -191,7 +191,7 @@ class VertexAgentAdminNode(ActionNode):@Operation("get", cost={"service": "vertex_agent", "action": "get", "count": 1})async def get_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:agent_id = self._require_agent_id(params)- client = await self._client(params)+ client = await self._client(params, ctx)try:agent = await client.aio.agents.get(id=agent_id)except Exception as exc: # noqa: BLE001 — mapped below@@ -205,7 +205,7 @@ class VertexAgentAdminNode(ActionNode):@Operation("delete", cost={"service": "vertex_agent", "action": "delete", "count": 1})async def delete_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:agent_id = self._require_agent_id(params)- client = await self._client(params)+ client = await self._client(params, ctx)try:await client.aio.agents.delete(id=agent_id)except Exception as exc: # noqa: BLE001 — mapped belowdiff --git a/server/nodes/android/_dispatcher.py b/server/nodes/android/_dispatcher.pyindex 583e020f..7b11e31d 100644--- a/server/nodes/android/_dispatcher.py+++ b/server/nodes/android/_dispatcher.py@@ -4,6 +4,7 @@ import timeimport httpximport asyncioimport subprocess+from services.process_environment import without_onepassword_environmentfrom datetime import datetimefrom typing import Dict, Any, List@@ -169,6 +170,7 @@ class AndroidService:encoding="utf-8",errors="replace",timeout=5,+ env=without_onepassword_environment(),)except FileNotFoundError:logger.error("[Android] ADB not found in PATH")diff --git a/server/nodes/android/_router.py b/server/nodes/android/_router.pyindex cceb00fc..70928667 100644--- a/server/nodes/android/_router.py+++ b/server/nodes/android/_router.py@@ -1,6 +1,6 @@"""Android System Services routes."""-from fastapi import APIRouter, Depends, HTTPException, Query+from fastapi import APIRouter, Depends, Queryfrom pydantic import BaseModel, Fieldfrom typing import Dict, Any@@ -124,7 +124,8 @@ async def setup_port_forwarding(# list is passed to ``subprocess.run`` with ``shell=False`` (the default).cmd = ["adb", "-s", device_id, "forward", f"tcp:{local_port}", f"tcp:{device_port}"]- result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5)+ from services.process_environment import without_onepassword_environment+ result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, env=without_onepassword_environment())if result.returncode == 0:logger.info(f"[Android] Port forwarding setup: {device_id} tcp:{local_port} -> tcp:{device_port}")diff --git a/server/nodes/browser/__init__.py b/server/nodes/browser/__init__.pyindex 2bce7c87..486dddfd 100644--- a/server/nodes/browser/__init__.py+++ b/server/nodes/browser/__init__.py@@ -41,21 +41,21 @@ async def _shutdown_browser_runtime() -> None:runtime = peek_browser_runtime()if runtime is not None:await runtime.shutdown()+ from services.browser_owners import unregister_browser_owner+ await unregister_browser_owner()async def _on_workflow_deleted(database: Any, workflow_id: str) -> None:- import asyncio-- from ._profiles import ProfileStore, remove_profile_files+ from ._profiles import ProfileStorefrom ._runtime import peek_browser_runtimeruntime = peek_browser_runtime()if runtime is not None:for session in runtime.sessions_for_workflow(workflow_id):controller = runtime.controller(session.profile_id)- if controller is not None:+ if controller is not None and controller.task_id is None:await controller.release_lease(session.session_id)- runtime.forget_session(session.session_id)+ runtime.forget_session(session.session_id)# Employee profiles belong to their workflow; shared ones stay.store = ProfileStore(database)try:@@ -63,10 +63,46 @@ async def _on_workflow_deleted(database: Any, workflow_id: str) -> None:except Exception: # noqa: BLE001 - cleanup must not fail the deletedoomed = []for profile in doomed:- if runtime is not None:- await runtime.stop_profile(profile.id, reason="workflow deleted")- await store.delete(profile.owner_id, profile.id)- await asyncio.to_thread(remove_profile_files, profile.id)+ try:+ await _cleanup_deleted_workflow_profile(database, profile.owner_id, profile.id, workflow_id)+ except Exception:+ # Retain files and metadata when their owner cannot confirm cleanup.+ # The authorized profile panel can finish cleanup after recovery.+ continue+++async def _cleanup_deleted_workflow_profile(database: Any, principal: str, profile_id: str, workflow_id: str) -> Dict[str, Any]:+ import asyncio+ from services.plugin.base import NodeUserError+ from services.browser_owners import bind_profile, replica_id, assert_runtime_epoch, _persistent, BrowserProfileOwner+ from ._profiles import ProfileStore, remove_profile_files+ from ._runtime import get_browser_runtime+ profile = await ProfileStore(database).get(principal, profile_id)+ if profile.kind != "employee" or profile.workflow_id != workflow_id or await database.get_workflow(workflow_id) is not None:+ raise NodeUserError("Browser cleanup is not associated with a deleted workflow.")+ binding = await bind_profile(database, profile.id, principal)+ if binding["owner_id"] != replica_id():+ if not binding.get("available", False):+ return {"success": False, "deferred": True}+ from ._routing import forward_command+ return await forward_command(binding, principal, "cleanup_workflow_profile", {"profile_id": profile.id, "deleted_workflow_id": workflow_id})+ await assert_runtime_epoch(database)+ runtime = get_browser_runtime()+ controller = runtime.controller(profile.id)+ if controller is not None and controller.task_id is not None:+ return {"success": False, "deferred": True}+ if _persistent(database):+ async with database.get_session() as session:+ ownership = await session.get(BrowserProfileOwner, profile.id)+ if ownership is not None and ownership.task_id is not None:+ return {"success": False, "deferred": True}+ running = runtime.running(profile.id)+ await runtime.stop_profile(profile.id, reason="workflow deleted")+ if running is not None and running.chrome.is_running():+ return {"success": False, "deferred": True}+ await ProfileStore(database).delete(principal, profile.id)+ await asyncio.to_thread(remove_profile_files, profile.id)+ return {"success": True}def _home_state(workflow_id: str, node_id: str) -> Optional[Dict[str, Any]]:diff --git a/server/nodes/browser/_chrome.py b/server/nodes/browser/_chrome.pyindex 0a48b39d..234af8e4 100644--- a/server/nodes/browser/_chrome.py+++ b/server/nodes/browser/_chrome.py@@ -240,6 +240,12 @@ def sweep_orphan(pidfile: Path) -> bool:passreturn Falsekill_tree(pid)+ try:+ proc.wait(timeout=5)+ except psutil.NoSuchProcess:+ pass+ except psutil.Error:+ raise NodeUserError("The previous browser runtime has not stopped. Wait for owner recovery before reopening this profile.") from Nonetry:pidfile.unlink()except OSError:@@ -288,6 +294,13 @@ class ChromeProcess(BaseProcessSupervisor):@propertydef pidfile(self) -> Path:+ from services.browser_owners import settings, replica_id+ if getattr(settings(), "distributed_mode", False) is True:+ import tempfile+ import hashlib+ directory = Path(tempfile.gettempdir()) / "opencompany-browser-runtime" / hashlib.sha256(replica_id().encode()).hexdigest() / "chrome"+ directory.mkdir(parents=True, exist_ok=True)+ return directory / (hashlib.sha256(self.profile_id.encode()).hexdigest() + ".json")return self._root / "oc-chrome.json"# -- BaseProcessSupervisor surface ---------------------------------------@@ -311,20 +324,23 @@ class ChromeProcess(BaseProcessSupervisor):return chrome_env()def stdout_log(self, line: str) -> None:+ if getattr(self, "sensitive_login", False):+ returnself._logger.debug(line)def stderr_log(self, line: str) -> None:# Chrome is chatty on stderr (GPU, dbus, updater); none of it is an error of ours.- self._logger.debug(line)+ if not getattr(self, "sensitive_login", False):+ self._logger.debug(line)async def _pre_spawn(self) -> None:- sweep_orphan(self.pidfile)if not self._profile_lock.acquire():raise NodeUserError("This browser profile is open in another OpenCompany (for example the desktop app and a terminal ""install sharing a data folder). Close it there, or use another profile.")self._locked = True+ await asyncio.to_thread(sweep_orphan, self.pidfile)try:(self._user_data_dir / "DevToolsActivePort").unlink()except OSError:diff --git a/server/nodes/browser/_cli.py b/server/nodes/browser/_cli.pyindex 17fbcbf8..026cb702 100644--- a/server/nodes/browser/_cli.py+++ b/server/nodes/browser/_cli.py@@ -125,6 +125,10 @@ class BrowserUseCli:from core.paths import daemons_dir, safe_path_componentroot = daemons_dir() / "browser-use" / safe_path_component(self.profile_id, fallback="profile")+ from services.browser_owners import settings, replica_id, RUNTIME_EPOCH+ if getattr(settings(), "distributed_mode", False) is True:+ import tempfile+ root = Path(tempfile.gettempdir()) / "opencompany-browser-runtime" / safe_path_component(replica_id()) / RUNTIME_EPOCH / safe_path_component(self.profile_id)found = {name: root / name for name in ("home", "runtime", "tmp", "workspace", "config")}for path in found.values():path.mkdir(parents=True, exist_ok=True)@@ -243,6 +247,60 @@ class BrowserUseCli:await self._kill(proc)self.stop_daemon()+ async def suspend_for_credentials(self) -> bool:+ """Confirm the harness is gone before plaintext enters private CDP.++ Never accept an unreadable or unrelated PID as proof of suspension.+ This path receives no secrets and returns no daemon diagnostics.+ """+ import psutil+ if self._proc is not None:+ await self._kill(self._proc)+ if self._proc.returncode is None:+ return False+ pidfile = self.dirs()["runtime"] / "bu.pid"+ if not pidfile.exists():+ return True+ try:+ pid = int(pidfile.read_text().strip())+ process = psutil.Process(pid)+ if "browser_harness" not in " ".join(process.cmdline()).lower():+ return False+ daemon_home = process.environ().get("BH_HOME", "")+ if Path(daemon_home).resolve() != self.dirs()["home"].resolve():+ return False+ except psutil.NoSuchProcess:+ self.stop_daemon()+ return True+ except (OSError, ValueError, psutil.Error):+ return False+ self.stop_daemon()+ try:+ await asyncio.to_thread(process.wait, timeout=5)+ except psutil.NoSuchProcess:+ pass+ except psutil.Error:+ return False+ return not process.is_running()++ async def suspend_prior_epochs(self) -> bool:+ """Retire this machine's old profile daemons before starting new Chrome."""+ from services.browser_owners import settings, RUNTIME_EPOCH+ if getattr(settings(), "distributed_mode", False) is not True:+ return True+ current = self.dirs()["home"].parent+ for epoch in current.parent.parent.iterdir():+ if epoch.name == RUNTIME_EPOCH or len(epoch.name) != 32 or any(c not in "0123456789abcdef" for c in epoch.name):+ continue+ previous = epoch / current.name+ if not (previous / "runtime" / "bu.pid").is_file():+ continue+ old = BrowserUseCli(cli_path=self.cli_path, python_path=self.python_path, profile_id=self.profile_id, cdp_http_url="")+ old.dirs = lambda root=previous: {name: root / name for name in ("home", "runtime", "tmp", "workspace", "config")}+ if not await old.suspend_for_credentials():+ return False+ return True+async def doctor(self) -> Dict[str, Any]:"""browser-harness's own health report (``doctor --json``)."""stdout, stderr, code = await self._exec(diff --git a/server/nodes/browser/_controls.py b/server/nodes/browser/_controls.pyindex b439141d..82442de4 100644--- a/server/nodes/browser/_controls.py+++ b/server/nodes/browser/_controls.py@@ -16,8 +16,8 @@ from dataclasses import asdict, dataclass, fieldfrom typing import Any, Dict, Optional-_OBSERVATIONS = frozenset({"snapshot", "page_text", "page_info", "screenshot", "diagnose", "webmcp_list", "wait"})-_SITE_ACTIONS = frozenset({"navigate", "click", "hover", "type", "press", "select", "scroll", "back", "forward", "reload", "webmcp_call", "evaluate", "run_python"})+_OBSERVATIONS = frozenset({"snapshot", "page_text", "page_info", "screenshot", "diagnose", "webmcp_list", "wait", "credential_bindings"})+_SITE_ACTIONS = frozenset({"navigate", "click", "hover", "type", "press", "select", "scroll", "back", "forward", "reload", "webmcp_call", "evaluate", "run_python", "credential_fill"})_WINDOW_SECONDS = 60.0diff --git a/server/nodes/browser/_credentials.py b/server/nodes/browser/_credentials.pynew file mode 100644index 00000000..ad0379cc--- /dev/null+++ b/server/nodes/browser/_credentials.py@@ -0,0 +1,217 @@+"""Protected configured-form login over the existing private CDP connection.++The ordinary browser-use path never receives these values. All failures are+reported without raw subprocess, DOM, URL, or CDP exception content.+"""+from __future__ import annotations++import asyncio+from typing import Any+from urllib.parse import urlsplit+++def canonical_origin(url: str) -> str:+ parts = urlsplit(url)+ if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password:+ raise ValueError("Unsupported login origin")+ return f"{parts.scheme}://{parts.hostname.lower()}:{parts.port or (443 if parts.scheme == 'https' else 80)}"+++async def _page_origin(page: Any) -> str:+ tree = await page.send("Page.getFrameTree", timeout=5)+ return canonical_origin(tree["frameTree"]["frame"]["url"])+++async def _element(page: Any, backend_id: int, *, origin: str, kind: str) -> str:+ node = await page.send("DOM.resolveNode", {"backendNodeId": backend_id}, timeout=5)+ object_id = node["object"]["objectId"]+ result = await page.send("Runtime.callFunctionOn", {+ "objectId": object_id,+ "functionDeclaration": """function(origin, kind) {+ const w = this.ownerDocument && this.ownerDocument.defaultView;+ if (!w || w !== w.top || w.location.origin !== origin || !this.isConnected || this.disabled) return false;+ if (kind === 'password') return this.tagName === 'INPUT' && this.type === 'password';+ if (kind === 'username') return this.tagName === 'INPUT' && ['text', 'email', 'tel'].includes(this.type);+ return (this.tagName === 'BUTTON' && this.type === 'submit') || (this.tagName === 'INPUT' && this.type === 'submit');+ }""",+ "arguments": [{"value": origin}, {"value": kind}], "returnByValue": True,+ }, timeout=5)+ if result.get("exceptionDetails") or result.get("result", {}).get("value") is not True:+ raise ValueError("Login target changed")+ return object_id+++def _js_origin(url: str) -> str:+ parts = urlsplit(url)+ port = parts.port+ host = parts.hostname or ""+ if ":" in host:+ host = f"[{host}]"+ return f"{parts.scheme}://{host}" + (f":{port}" if port and port != (443 if parts.scheme == "https" else 80) else "")+++async def employee_scope(ctx: Any, auth: Any) -> str | None:+ database = getattr(auth, "database", None)+ if ctx.workflow_id and getattr(database, "engine", None) is not None:+ from services.employees.store import get_by_workflow+ employee = await get_by_workflow(database, ctx.workflow_id)+ if employee is not None and employee.owner_id == (ctx.user_id or "owner"):+ return employee.id+ return None+++async def scoped_bindings(ctx: Any, auth: Any, profile_id: str) -> list[dict]:+ from services.credentials.sources import CredentialSources+ employee = await employee_scope(ctx, auth)+ allowed = []+ for binding in await CredentialSources(auth.database).list_browser(ctx.user_id or "owner"):+ if binding.get("profile_id") and binding["profile_id"] != profile_id:+ continue+ if binding.get("workflow_id") and binding["workflow_id"] != ctx.workflow_id:+ continue+ if binding.get("employee_id") and binding["employee_id"] != employee:+ continue+ allowed.append({"id": binding["id"], "label": binding["label"], "origin": binding["origin"], "fields": ["username", "password"]})+ return allowed+++async def fill_credentials(ctx: Any, runtime: Any, call: Any, *, timeout: float) -> dict:+ from core.container import container+ from services.browser_owners import set_sensitive+ from services.plugin.deps import get_database++ controller = runtime.controller+ task_id = str(ctx.raw.get("_browser_task_id") or ctx.execution_id or "")+ if controller.task_id is not None and controller.task_id != task_id:+ return {"success": False, "error_type": "BrowserBusy", "error": "This profile belongs to another task."}+ page = None+ values = None+ gated = False+ try:+ if not call.credential_binding_id or not all((call.username_ref, call.password_ref, call.submit_ref)):+ raise ValueError("A configured binding and current login references are required")+ auth = container.auth_service()+ employee = await employee_scope(ctx, auth)+ binding = await auth.get_browser_credential_binding(call.credential_binding_id, ctx.user_id or "owner", profile_id=runtime.profile.id, workflow_id=ctx.workflow_id, employee_id=employee)+ if not binding.get("success_path") and not binding.get("success_selector"):+ raise ValueError("Configure an authenticated success path or selector before automatic login")+ target = controller.active_target_id+ refs = controller.refs.get(target or "", {})+ ids = [refs.get(ref) for ref in (call.username_ref, call.password_ref, call.submit_ref)]+ if not target or any(value is None for value in ids):+ raise ValueError("Take a fresh login snapshot")+ page = await runtime.page_session(target)+ origin = canonical_origin(binding["origin"])+ if await _page_origin(page) != origin:+ raise ValueError("This binding is not approved for the current website")+ initial_tree = await page.send("Page.getFrameTree", timeout=5)+ initial_loader = initial_tree["frameTree"]["frame"].get("loaderId")+ revision = controller.revision+ await set_sensitive(get_database(), runtime.profile.id, controller.task_id, True)+ await controller.set_sensitive_login(True)+ gated = True+ runtime.chrome.sensitive_login = True+ hub = getattr(runtime, "hub", None)+ if hub is not None:+ # Listener broadcasting is best effort; this privacy barrier is not.+ await hub.sensitive_barrier(True)+ webmcp = getattr(runtime, "webmcp", None)+ if hasattr(webmcp, "sensitive_barrier"):+ await webmcp.sensitive_barrier(True)+ if not await runtime.cli.suspend_for_credentials():+ raise ValueError("Browser daemon suspension could not be confirmed")+ js_origin = _js_origin(binding["origin"])+ objects = [await _element(page, int(node), origin=js_origin, kind=kind) for node, kind in zip(ids, ("username", "password", "submit"))]+ values = await auth.resolve_browser_credentials(call.credential_binding_id, ctx.user_id or "owner", profile_id=runtime.profile.id, workflow_id=ctx.workflow_id, employee_id=employee)+ if controller.active_target_id != target or controller.revision != revision + 1 or await _page_origin(page) != origin or controller._user_blocks_agent():+ raise ValueError("Browser control or login target changed during authorization")+ authorized_tree = await page.send("Page.getFrameTree", timeout=5)+ if initial_loader and authorized_tree["frameTree"]["frame"].get("loaderId") != initial_loader:+ raise ValueError("The login document changed during authorization")+ # Resolve and validate the same nodes again after an interactive CLI grant.+ objects = [await _element(page, int(node), origin=js_origin, kind=kind) for node, kind in zip(ids, ("username", "password", "submit"))]+ for object_id, field in zip(objects[:2], ("username", "password")):+ result = await page.send("Runtime.callFunctionOn", {+ "objectId": object_id,+ "functionDeclaration": """function(value, origin, kind) {+ if (!this.isConnected || this.disabled || this.tagName !== 'INPUT' || this.ownerDocument.defaultView.location.origin !== origin) return false;+ if (kind === 'password' ? this.type !== 'password' : !['text', 'email', 'tel'].includes(this.type)) return false;+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;+ setter.call(this, value);+ this.dispatchEvent(new Event('input', {bubbles:true}));+ this.dispatchEvent(new Event('change', {bubbles:true}));+ return this.value === value;+ }""", "arguments": [{"value": values[field]}, {"value": js_origin}, {"value": field}], "returnByValue": True,+ }, timeout=5)+ if result.get("exceptionDetails") or result.get("result", {}).get("value") is not True:+ raise ValueError("Login fill was not confirmed")+ if controller.active_target_id != target or controller._user_blocks_agent() or await _page_origin(page) != origin:+ raise ValueError("Browser target changed before submission")+ submission_tree = await page.send("Page.getFrameTree", timeout=5)+ if initial_loader and submission_tree["frameTree"]["frame"].get("loaderId") != initial_loader:+ raise ValueError("The login document changed before submission")+ objects[2] = await _element(page, int(ids[2]), origin=js_origin, kind="submit")+ submitted = await page.send("Runtime.callFunctionOn", {+ "objectId": objects[2], "functionDeclaration": """function(origin) {+ if (!this.isConnected || this.disabled || this.ownerDocument.defaultView.location.origin !== origin) return false;+ if (!((this.tagName === 'BUTTON' && this.type === 'submit') || (this.tagName === 'INPUT' && this.type === 'submit'))) return false;+ this.click(); return true;+ }""", "arguments": [{"value": js_origin}], "returnByValue": True,+ }, timeout=5)+ if submitted.get("exceptionDetails") or submitted.get("result", {}).get("value") is not True:+ raise ValueError("Login submission was not confirmed")+ deadline = asyncio.get_running_loop().time() + max(1, min(timeout, 45))+ success_origin = canonical_origin(binding.get("success_origin") or binding["origin"])+ while asyncio.get_running_loop().time() < deadline:+ if controller.active_target_id != target or controller._user_blocks_agent():+ break+ result = await page.send("Runtime.evaluate", {+ "expression": "(() => ({origin:location.origin,path:location.pathname,password:!!document.querySelector('input[type=password]')}))()", "returnByValue": True,+ }, timeout=5)+ facts = result.get("result", {}).get("value") or {}+ accepted = canonical_origin(facts.get("origin", "")) == success_origin and not facts.get("password")+ if accepted:+ current_tree = await page.send("Page.getFrameTree", timeout=5)+ changed_document = bool(initial_loader and current_tree["frameTree"]["frame"].get("loaderId") != initial_loader)+ if not changed_document:+ # SPA success cues alone must not expose the filled inputs.+ for object_id in objects[:2]:+ absent = await page.send("Runtime.callFunctionOn", {"objectId": object_id,+ "functionDeclaration": "function() { return !this.isConnected || this.value === ''; }", "returnByValue": True}, timeout=5)+ accepted = accepted and absent.get("result", {}).get("value") is True+ if binding.get("success_path"):+ accepted = accepted and facts.get("path") == binding["success_path"]+ if binding.get("success_selector"):+ import json+ cue = await page.send("Runtime.evaluate", {"expression": f"!!document.querySelector({json.dumps(binding['success_selector'])})", "returnByValue": True}, timeout=5)+ accepted = accepted and cue.get("result", {}).get("value") is True+ if accepted:+ # The harness logs URLs; do not resume it on a credential-bearing+ # redirect or a page that reflects a password into DOM metadata.+ document = await page.send("Runtime.evaluate", {"expression": "document.documentElement", "returnByValue": False}, timeout=5)+ clean = await page.send("Runtime.callFunctionOn", {"objectId": document["result"]["objectId"],+ "functionDeclaration": """function(password) {+ return ![location.href, this.outerHTML, this.innerText || ''].some(text =>+ text.includes(password) || text.includes(encodeURIComponent(password)));+ }""", "arguments": [{"value": values["password"]}], "returnByValue": True}, timeout=5)+ accepted = clean.get("result", {}).get("value") is True+ if accepted:+ if hasattr(webmcp, "sensitive_barrier"):+ await webmcp.sensitive_barrier(False)+ await set_sensitive(get_database(), runtime.profile.id, controller.task_id, False)+ await controller.set_sensitive_login(False)+ runtime.chrome.sensitive_login = False+ controller.refs.clear()+ controller.needs_observation = True+ return {"success": True}+ await asyncio.sleep(0.25)+ raise ValueError("Login completion was not confirmed")+ except asyncio.CancelledError:+ raise+ except Exception:+ # CDP/page errors may contain credential-bearing DOM or URLs.+ return {"success": False, "error_type": "login_required", "error": "Configured login could not be confirmed. Browser observations remain paused. Close and reopen this browser, then finish login manually." if gated else "Configured login is unavailable for this page. Finish login manually or check the saved binding and current references."}+ finally:+ values = None+ if page is not None:+ await page.detach()diff --git a/server/nodes/browser/_egress.py b/server/nodes/browser/_egress.pyindex b46e524a..30bbf1a9 100644--- a/server/nodes/browser/_egress.py+++ b/server/nodes/browser/_egress.py@@ -128,16 +128,20 @@ class EgressProxy:if loop is None:return- def _shutdown() -> None:+ async def _shutdown() -> None:if server is not None:server.close()- for task in asyncio.all_tasks(loop):+ await server.wait_closed()+ pending = [task for task in asyncio.all_tasks(loop) if task is not asyncio.current_task()]+ for task in pending:task.cancel()+ await asyncio.gather(*pending, return_exceptions=True)loop.call_soon(loop.stop)try:- loop.call_soon_threadsafe(_shutdown)- except RuntimeError:+ future = asyncio.run_coroutine_threadsafe(_shutdown(), loop)+ future.result(timeout=5)+ except (RuntimeError, TimeoutError):passif self._thread is not None:self._thread.join(timeout=5)diff --git a/server/nodes/browser/_extract.py b/server/nodes/browser/_extract.pyindex 3ba5df7e..4b61cba1 100644--- a/server/nodes/browser/_extract.py+++ b/server/nodes/browser/_extract.py@@ -19,6 +19,7 @@ import subprocessimport sysimport zipfilefrom pathlib import Path+from services.process_environment import without_onepassword_environmentclass UnsafeArchiveError(ValueError):@@ -37,9 +38,9 @@ def extract_zip(archive: Path, dest: Path) -> None:"""Extract ``archive`` into ``dest`` (created if missing)."""dest.mkdir(parents=True, exist_ok=True)if sys.platform == "darwin" and shutil.which("ditto"):- subprocess.run(["ditto", "-x", "-k", str(archive), str(dest)], check=True, capture_output=True)+ subprocess.run(["ditto", "-x", "-k", str(archive), str(dest)], check=True, capture_output=True, env=without_onepassword_environment())if shutil.which("xattr"):- subprocess.run(["xattr", "-dr", "com.apple.quarantine", str(dest)], check=False, capture_output=True)+ subprocess.run(["xattr", "-dr", "com.apple.quarantine", str(dest)], check=False, capture_output=True, env=without_onepassword_environment())return_extract_portable(archive, dest)diff --git a/server/nodes/browser/_handlers.py b/server/nodes/browser/_handlers.pyindex 5ed7fe91..0db6da07 100644--- a/server/nodes/browser/_handlers.py+++ b/server/nodes/browser/_handlers.py@@ -84,14 +84,15 @@ async def _session_for_node(owner_id: str, workflow_id: str, node_id: str, *, crsaved = await get_database().get_node_parameters(node_id) or {}cfg = BrowserParams.model_validate(saved)+ from services.browser_owners import routing_for_node+store = ProfileStore(get_database())try:- if cfg.profile_id:- profile = await store.get(owner_id, cfg.profile_id)- else:- workflow = await get_database().get_workflow(workflow_id)- name = getattr(workflow, "name", None) or "Browser"- profile = await store.default_for_workflow(owner_id, workflow_id, str(name))+ # A recovered task keeps its admitted profile even if the saved node+ # was edited while its owner was unavailable. This lookup is required+ # locally too: only distributed requests pass through route_handler.+ binding = await routing_for_node(get_database(), workflow_id, node_id, owner_id)+ profile = await store.get(owner_id, binding["profile_id"])except ProfileError as exc:raise NodeUserError(str(exc)) from excpolicy = runtime.base_policy(allow_private_network=cfg.allow_private_network, allowed_domains=parse_allowed_domains(cfg.allowed_domains))@@ -117,7 +118,8 @@ def _session_view(runtime: Any, session: Any) -> Dict[str, Any]:else:view["held_by_other"] = controller.lease_session is not Nonetab = controller.tabs.get(controller.active_target_id or "") or {}- view.update(url=tab.get("url"), title=tab.get("title"), tabs=len(controller.tabs))+ if not controller.sensitive_login:+ view.update(url=tab.get("url"), title=tab.get("title"), tabs=len(controller.tabs))return view@@ -267,7 +269,12 @@ async def handle_browser_profile_delete(data: Dict[str, Any], websocket: WebSockexcept ProfileError as exc:raise NodeUserError(str(exc)) from excruntime = get_browser_runtime()+ from services.browser_owners import assert_owner, bind_profile, _persistent+ if _persistent(get_database()):+ await assert_owner(get_database(), await bind_profile(get_database(), profile.id, owner), owner)controller = runtime.controller(profile.id)+ if controller is not None and controller.task_id is not None:+ raise NodeUserError("BrowserBusy: finish or cancel the task before deleting its profile.")if controller is not None and controller.lease_session is not None:raise NodeUserError(f"{profile.name!r} is in use by {controller.lease_session.label}. Stop it first.")await runtime.stop_profile(profile.id, reason="profile deleted")@@ -284,6 +291,12 @@ async def _running_profile(owner: str, profile_id: str, *, wait: float = 30.0) -profile = await ProfileStore(get_database()).get(owner, profile_id)except ProfileError as exc:raise NodeUserError(str(exc)) from exc+ from services.browser_owners import assert_owner, bind_profile, _persistent+ if _persistent(get_database()):+ await assert_owner(get_database(), await bind_profile(get_database(), profile.id, owner), owner)+ controller = get_browser_runtime().controller(profile.id)+ if controller is not None and controller.task_id is not None:+ raise NodeUserError("BrowserBusy: finish or cancel the task before changing its saved logins.")return profile, await get_browser_runtime().open(profile, wait=wait)@@ -297,6 +310,8 @@ async def handle_browser_profile_clear_site(data: Dict[str, Any], websocket: Webif not domain:raise NodeUserError("domain required")profile, running = await _running_profile(owner, str(data.get("profile_id") or ""))+ if running.controller.task_id is not None:+ raise NodeUserError("BrowserBusy: finish or cancel the task before clearing its logins.")cookies = (await running.cdp.send("Storage.getCookies")).get("cookies") or []for cookie in cookies:cookie_domain = str(cookie.get("domain") or "").lstrip(".").lower()@@ -331,6 +346,8 @@ async def handle_browser_profile_login_start(data: Dict[str, Any], websocket: Weif reason:raise NodeUserError(f"Cannot open {url}: {reason}.")profile, running = await _running_profile(owner, str(data.get("profile_id") or ""))+ if running.controller.task_id is not None:+ raise NodeUserError("BrowserBusy: use this task's Browser workspace to take control and log in.")login_id = f"login_{uuid.uuid4().hex[:12]}"session = runtime.register_session(BrowserSession(@@ -423,6 +440,8 @@ async def handle_browser_import_commit(data: Dict[str, Any], websocket: WebSockeraise NodeUserError("Pick at least one site to import.")profile, running = await _running_profile(owner, str(data.get("profile_id") or ""))controller = running.controller+ if controller.task_id is not None:+ raise NodeUserError("BrowserBusy: finish or cancel the task before importing logins.")if controller.lease_session is not None and controller.lease_session.kind == "node" and controller.state.value != "idle":raise NodeUserError(f"{profile.name!r} is busy ({controller.lease_session.label}); try again when it is idle.")result = await apply_jar(running, job.jar, domains)@@ -483,6 +502,8 @@ WS_HANDLERS: Dict[str, WSHandler] = {"browser_runtime_status": handle_browser_runtime_status,"browser_runtime_prepare": handle_browser_runtime_prepare,}+from ._routing import route_handler+WS_HANDLERS = {name: route_handler(name, handler) for name, handler in WS_HANDLERS.items()}async def load_browser_profiles(params: Dict[str, Any]) -> list:diff --git a/server/nodes/browser/_install_bu.py b/server/nodes/browser/_install_bu.pyindex 3313a04f..aa0e242f 100644--- a/server/nodes/browser/_install_bu.py+++ b/server/nodes/browser/_install_bu.py@@ -23,6 +23,7 @@ from typing import Dict, Optionalfrom core.logging import get_loggerfrom services.plugin.base import NodeUserError+from services.process_environment import without_onepassword_environmentfrom ._config import BrowserUsePin, get_config@@ -132,7 +133,7 @@ class BrowserUseInstaller:logger.info("[browser] installing %s", self.pin.spec)try:proc = await asyncio.create_subprocess_exec(- *argv, env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE+ *argv, env=without_onepassword_environment(env), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)try:_, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)diff --git a/server/nodes/browser/_install_chrome.py b/server/nodes/browser/_install_chrome.pyindex 11e23ba0..5f2567b1 100644--- a/server/nodes/browser/_install_chrome.py+++ b/server/nodes/browser/_install_chrome.py@@ -113,6 +113,7 @@ def _grant_sandbox_access(directory: Path) -> None:runs without it."""import subprocess+ from services.process_environment import without_onepassword_environmenttry:subprocess.run(@@ -120,6 +121,7 @@ def _grant_sandbox_access(directory: Path) -> None:check=False,capture_output=True,timeout=120,+ env=without_onepassword_environment(),)except (OSError, subprocess.TimeoutExpired) as exc:logger.debug("[browser] could not grant Chrome's sandbox access to %s: %s", directory, exc)diff --git a/server/nodes/browser/_live_control.py b/server/nodes/browser/_live_control.pyindex cd05126d..b64df5e8 100644--- a/server/nodes/browser/_live_control.py+++ b/server/nodes/browser/_live_control.py@@ -114,6 +114,7 @@ class LiveControlQueue:viewer = command.viewerreturn (not self._closed and not viewer.closed and viewer.visible+ and not getattr(self.controller, "sensitive_login", False)and (not owner or viewer.id not in self._blocked)and command.epoch == self._epochs.get(viewer.id, 0)and command.target == self._target()@@ -148,7 +149,7 @@ class LiveControlQueue:self._input_epoch = epochdef enqueue(self, viewer, message: dict, session) -> bool:- if self._closed or viewer.closed or not viewer.visible:+ if self._closed or viewer.closed or not viewer.visible or getattr(self.controller, "sensitive_login", False):return Falsekind = message.get("type")if kind == "control_request" and viewer.id in self._takeover_pending:diff --git a/server/nodes/browser/_profiles.py b/server/nodes/browser/_profiles.pyindex 86c06ac7..bb79ef0e 100644--- a/server/nodes/browser/_profiles.py+++ b/server/nodes/browser/_profiles.py@@ -26,8 +26,9 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, List, Optional-from sqlalchemy import JSON, Column, delete, select-from sqlmodel import Field, SQLModel+from sqlalchemy import delete, select+from sqlalchemy.exc import IntegrityError+from models.browser_profiles import BrowserProfileRowfrom core.logging import get_logger@@ -41,24 +42,6 @@ def _utcnow() -> datetime:return datetime.now(timezone.utc)-class BrowserProfileRow(SQLModel, table=True):- __tablename__ = "browser_profiles"-- id: str = Field(primary_key=True, max_length=40)- owner_id: str = Field(default="owner", index=True, max_length=255)- name: str = Field(max_length=120)- kind: str = Field(default="shared", max_length=20)- workflow_id: Optional[str] = Field(default=None, index=True, max_length=255)- #: Major version of the last Chrome that opened it. A profile written by- #: a newer Chrome must not be opened by an older one.- chrome_major: Optional[int] = Field(default=None)- #: Domains and cookie counts from the last time we looked (never values),- #: so the Credentials panel can show them without starting Chrome.- sites: Optional[List[Dict[str, Any]]] = Field(default=None, sa_column=Column(JSON))- created_at: datetime = Field(default_factory=_utcnow)- updated_at: datetime = Field(default_factory=_utcnow)--class ProfileError(ValueError):"""User-correctable profile problem (duplicate name, unknown id)."""@@ -239,7 +222,16 @@ class ProfileStore:existing = next(iter(rows), None)if existing is not None:return _from_row(existing)- return await self.create(owner_id, name, kind="employee", workflow_id=workflow_id)+ try:+ return await self.create(owner_id, name, kind="employee", workflow_id=workflow_id)+ except IntegrityError:+ # Another replica created the same workflow's profile first.+ async with self.database.get_session() as session:+ row = (await session.execute(select(BrowserProfileRow).where(+ BrowserProfileRow.owner_id == owner_id, BrowserProfileRow.workflow_id == workflow_id,+ BrowserProfileRow.kind == "employee"+ ))).scalar_one()+ return _from_row(row)async def employee_profiles_of(self, workflow_id: str) -> List[Profile]:"""Every owner's employee profile of a workflow (for its deletion)."""diff --git a/server/nodes/browser/_router.py b/server/nodes/browser/_router.pyindex fc1f1ba4..173d85ca 100644--- a/server/nodes/browser/_router.py+++ b/server/nodes/browser/_router.py@@ -20,6 +20,17 @@ from ._stream import browser_live_viewrouter = APIRouter()# Registered directly: include_router would add a pathless entry here.router.add_api_websocket_route("/ws/browser", browser_live_view)+router.add_api_websocket_route("/ws/browser/owner", browser_live_view)++[email protected]("/api/browser/owner/command")+async def route_owner_command(request: Request) -> Dict[str, Any]:+ from ._routing import owner_command+ from services.plugin.base import NodeUserError+ try:+ return await owner_command(request)+ except (NodeUserError, ValueError) as exc:+ raise HTTPException(status_code=403, detail="Browser owner request refused.") from None_CHUNK = 256 * 1024@@ -64,6 +75,13 @@ async def upload_session_file(chunks.append(chunk)if not total:raise HTTPException(status_code=400, detail="The file is empty.")+ from services.browser_owners import bind_profile, replica_id, settings+ if getattr(settings(), "distributed_mode", False) is True:+ from ._routing import forward_command+ import base64+ binding = await bind_profile(get_database(), profile_id, owner)+ if binding["owner_id"] != replica_id():+ return await forward_command(binding, owner, "session_file", {"profile_id": profile_id, "payload": base64.b64encode(b"".join(chunks)).decode()})try:jar = parse_session_file(b"".join(chunks))except CookieFormatError as exc:@@ -71,6 +89,8 @@ async def upload_session_file(finally:chunks.clear()job = get_import_jobs().add_file(owner, jar)+ from ._routing import record_handle+ await record_handle(job.id, owner, profile_id=profile_id)return {"success": True, "profile_id": profile_id, **job.to_wire()}diff --git a/server/nodes/browser/_routing.py b/server/nodes/browser/_routing.pynew file mode 100644index 00000000..8ba0f805--- /dev/null+++ b/server/nodes/browser/_routing.py@@ -0,0 +1,160 @@+"""Authenticated backend-to-owner routing for the existing Browser protocols."""+from __future__ import annotations++import asyncio+import json+import time+from functools import wraps+from types import SimpleNamespace+from typing import Any+from urllib.parse import urlsplit, urlunsplit++from services.browser_owners import (BrowserOwner, BrowserTransientRoute, bind_profile,+ replica_id, routing_for_node, settings, sign_forward, verify_forward)+from services.plugin.base import NodeUserError+from services.plugin.deps import get_database++COMMAND_PATH = "/api/browser/owner/command"+VIEW_PATH = "/ws/browser/owner"+++async def forward_command(binding: dict, principal: str, command: str, data: dict) -> dict:+ import httpx+ body = json.dumps({"command": command, "data": data}, separators=(",", ":")).encode()+ headers = {"X-Browser-Forward": sign_forward(principal, "POST", COMMAND_PATH, body), "Content-Type": "application/json"}+ try:+ async with httpx.AsyncClient(timeout=65, follow_redirects=False) as client:+ response = await client.post(binding["base_url"] + COMMAND_PATH, content=body, headers=headers)+ if response.status_code != 200:+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ return response.json()+ except (httpx.HTTPError, ValueError):+ raise NodeUserError("Browser unavailable — waiting for its owner.") from None+++async def record_handle(handle_id: str, principal: str, *, profile_id: str | None = None) -> None:+ if getattr(settings(), "distributed_mode", False) is not True:+ return+ async with get_database().get_session() as session:+ row = BrowserTransientRoute(handle_id=handle_id, principal_id=principal, owner_id=replica_id(), profile_id=profile_id, expires_at=time.time() + (300 if handle_id.startswith("imp_") else 3600))+ session.add(row)+ await session.commit()+++async def handle_binding(handle_id: str, principal: str) -> dict:+ async with get_database().get_session() as session:+ row = await session.get(BrowserTransientRoute, handle_id)+ if row is None or row.principal_id != principal or row.expires_at < time.time():+ raise NodeUserError("That browser login or import has expired.")+ owner = await session.get(BrowserOwner, row.owner_id)+ if owner is None:+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ return {"profile_id": row.profile_id, "owner_id": owner.owner_id, "base_url": owner.base_url}+++async def command_binding(principal: str, data: dict) -> dict | None:+ if data.get("workflow_id") and data.get("node_id"):+ return await routing_for_node(get_database(), str(data["workflow_id"]), str(data["node_id"]), principal)+ if data.get("import_id") or data.get("login_id"):+ return await handle_binding(str(data.get("import_id") or data["login_id"]), principal)+ if data.get("profile_id"):+ from ._profiles import ProfileStore+ profile = await ProfileStore(get_database()).get(principal, str(data["profile_id"]))+ return await bind_profile(get_database(), profile.id, principal)+ return None+++def route_handler(name: str, handler: Any) -> Any:+ @wraps(handler)+ async def routed(data: dict, websocket: Any) -> dict:+ if getattr(settings(), "distributed_mode", False) is not True:+ return await handler(data, websocket)+ from ._handlers import _authenticated_owner, _require_external_socket+ _require_external_socket(websocket)+ principal = _authenticated_owner(websocket)+ binding = await command_binding(principal, data)+ if binding is not None and binding["owner_id"] != replica_id():+ if getattr(websocket.state, "browser_forwarded", False):+ raise NodeUserError("Browser owner routing changed; retry after recovery.")+ return await forward_command(binding, principal, name, data)+ from services.browser_owners import assert_runtime_epoch+ await assert_runtime_epoch(get_database())+ result = await handler(data, websocket)+ if result.get("success"):+ handle = result.get("import_id") or result.get("login_id")+ if handle:+ await record_handle(str(handle), principal, profile_id=data.get("profile_id"))+ return result+ return routed+++async def owner_command(request: Any) -> dict:+ body = await request.body()+ if len(body) > 24 * 1024 * 1024:+ raise NodeUserError("Browser forwarding request is too large.")+ principal = verify_forward(request.headers.get("X-Browser-Forward", ""), "POST", COMMAND_PATH, body)+ payload = json.loads(body)+ command, data = payload.get("command"), payload.get("data")+ if not isinstance(data, dict):+ raise NodeUserError("Invalid browser command.")+ if command == "cleanup_workflow_profile":+ binding = await command_binding(principal, data)+ if binding is None or binding["owner_id"] != replica_id():+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ from . import _cleanup_deleted_workflow_profile+ return await _cleanup_deleted_workflow_profile(get_database(), principal, str(data.get("profile_id") or ""), str(data.get("deleted_workflow_id") or ""))+ if command == "cleanup_task":+ from services.browser_owners import cleanup_browser_task+ binding = await command_binding(principal, data)+ if binding is None or binding["owner_id"] != replica_id():+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ return await cleanup_browser_task(get_database(), {**binding, "principal_id": principal}, str(data.get("task_id") or ""))+ if command == "session_file":+ import base64+ from ._cookies import MAX_UPLOAD_BYTES, parse_session_file+ from ._imports import get_import_jobs+ binding = await command_binding(principal, data)+ if binding is None or binding["owner_id"] != replica_id():+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ raw = base64.b64decode(data.get("payload", ""), validate=True)+ if len(raw) > MAX_UPLOAD_BYTES:+ raise NodeUserError("Session file is too large.")+ job = get_import_jobs().add_file(principal, parse_session_file(raw))+ await record_handle(job.id, principal, profile_id=data["profile_id"])+ return {"success": True, "profile_id": data["profile_id"], **job.to_wire()}+ from ._handlers import WS_HANDLERS+ if command not in WS_HANDLERS:+ raise NodeUserError("Unknown browser command.")+ socket = SimpleNamespace(state=SimpleNamespace(user_id=principal, browser_forwarded=True), scope={"path": COMMAND_PATH}, headers={}, client=None)+ return await WS_HANDLERS[command](data, socket)+++async def proxy_view(websocket: Any, first: dict, principal: str, binding: dict) -> None:+ from websockets.asyncio.client import connect+ body = json.dumps(first, separators=(",", ":")).encode()+ parts = urlsplit(binding["base_url"])+ url = urlunsplit(("wss" if parts.scheme == "https" else "ws", parts.netloc, VIEW_PATH, "", ""))+ try:+ async with connect(url, additional_headers={"X-Browser-Forward": sign_forward(principal, "WS", VIEW_PATH, body)}, max_size=16 * 1024 * 1024, compression=None, open_timeout=10) as upstream:+ await upstream.send(body.decode())+ async def upstream_reader() -> None:+ async for message in upstream:+ if isinstance(message, bytes):+ await websocket.send_bytes(message)+ else:+ await websocket.send_text(message)+ async def downstream_reader() -> None:+ while True:+ message = await websocket.receive_text()+ if len(message) > 128 * 1024:+ raise NodeUserError("Browser input is too large.")+ await upstream.send(message)+ tasks = [asyncio.create_task(upstream_reader()), asyncio.create_task(downstream_reader())]+ try:+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ except Exception:+ await websocket.close(code=1013, reason="Browser unavailable — waiting for its owner.")diff --git a/server/nodes/browser/_runtime.py b/server/nodes/browser/_runtime.pyindex 69e86130..2372fe7d 100644--- a/server/nodes/browser/_runtime.py+++ b/server/nodes/browser/_runtime.py@@ -208,6 +208,21 @@ class BrowserRuntime:async def open(self, profile: Profile, *, wait: float = 60.0) -> ProfileRuntime:"""The profile's running browser, starting Chrome if needed."""+ from services.browser_owners import _persistent+ from services.plugin.deps import get_database+ if getattr(self._settings(), "distributed_mode", False) is True or _persistent(get_database()):+ from services.browser_owners import bind_profile, replica_id, RUNTIME_EPOCH+ from services.plugin.deps import get_database+ binding = await bind_profile(get_database(), profile.id, profile.owner_id)+ if binding["owner_id"] != replica_id() or binding["runtime_epoch"] != RUNTIME_EPOCH:+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ controller = self.controller_for(profile)+ if binding.get("profile_task_id"):+ controller.claim_task(str(binding["profile_task_id"]))+ controller.sensitive_login = bool(binding.get("sensitive_login"))+ controller.needs_observation |= bool(binding.get("needs_observation"))+ controller.challenge_required = bool(binding.get("challenge_required"))+ controller.recovered_assistance = binding.get("assistance")runtime = self._profiles.get(profile.id)if runtime is not None and runtime.running:return runtime@@ -276,8 +291,10 @@ class BrowserRuntime:cli = BrowserUseCli(cli_path=bu_paths["cli"], python_path=bu_paths["python"], profile_id=profile.id, cdp_http_url="http://127.0.0.1:0")- cli.stop_daemon() # one left from an earlier Chrome would point at a dead port+ if not await cli.suspend_prior_epochs() or not await cli.suspend_for_credentials():+ raise NodeUserError("The previous browser daemon has not stopped. Wait for owner recovery before reopening this profile.")+ chrome.sensitive_login = controller.sensitive_logincdp = await chrome.launch()cli.cdp_http_url = f"http://127.0.0.1:{chrome.port}"webmcp = WebMcpTracker()@@ -321,9 +338,11 @@ class BrowserRuntime:if runtime.provider == "testing":await session.send("Network.setUserAgentOverride", {"userAgent": ua, "userAgentMetadata": metadata}, timeout=10)await session.send("Page.enable", timeout=10)- await runtime.webmcp.attach(session.target_id, session)+ if not getattr(controller, "sensitive_login", False):+ await runtime.webmcp.attach(session.target_id, session)except (CDPError, CDPDisconnected, TimeoutError):- logger.debug("[browser] configuring page %s failed", target.get("targetId"), exc_info=True)+ if not getattr(controller, "sensitive_login", False):+ logger.debug("[browser] configuring page %s failed", target.get("targetId"), exc_info=True)finally:if waiting:try:@@ -343,7 +362,7 @@ class BrowserRuntime:previous = controller.tabs.get(info["targetId"])if previous and previous.get("url") != info.get("url"):controller.refs.pop(info["targetId"], None)- controller.tabs[info["targetId"]] = {"target_id": info["targetId"], "url": info.get("url"), "title": info.get("title")}+ controller.tabs[info["targetId"]] = {"target_id": info["targetId"]} if getattr(controller, "sensitive_login", False) else {"target_id": info["targetId"], "url": info.get("url"), "title": info.get("title")}asyncio.ensure_future(controller.emit("tabs", {"tabs": list(controller.tabs.values())}))def on_destroyed(params: Dict[str, Any]) -> None:@@ -362,7 +381,7 @@ class BrowserRuntime:await cdp.send("Target.setDiscoverTargets", {"discover": True})await cdp.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True})for page in await cdp.page_targets():- controller.tabs[page["targetId"]] = {"target_id": page["targetId"], "url": page.get("url"), "title": page.get("title")}+ controller.tabs[page["targetId"]] = {"target_id": page["targetId"]} if getattr(controller, "sensitive_login", False) else {"target_id": page["targetId"], "url": page.get("url"), "title": page.get("title")}session = await cdp.attach(page["targetId"])await configure(session, page, False)try:@@ -411,6 +430,12 @@ class BrowserRuntime:controller = runtime.controllerawait controller.release_lease()await self._teardown(runtime)+ if controller.sensitive_login and not runtime.chrome.is_running():+ from services.browser_owners import set_sensitive+ from services.plugin.deps import get_database+ await set_sensitive(get_database(), profile_id, controller.task_id, False)+ controller.sensitive_login = False+ controller.needs_observation = Truecontroller.tabs.clear()controller.active_target_id = Noneawait controller.emit("closed", {"reason": reason or "stopped"})diff --git a/server/nodes/browser/_session.py b/server/nodes/browser/_session.pyindex 793c8c33..37b7b5a8 100644--- a/server/nodes/browser/_session.py+++ b/server/nodes/browser/_session.py@@ -144,6 +144,9 @@ class ProfileController:self.pending: Optional[UserRequest] = Noneself.challenge_required = Falseself.needs_observation = False+ self.task_id: Optional[str] = None+ self.sensitive_login = False+ self.recovered_assistance: Optional[dict] = Noneself._challenge_message = ""self.viewers: set[str] = set()self.active_target_id: Optional[str] = None@@ -196,6 +199,7 @@ class ProfileController:"profile": {"id": self.profile_id, "name": self.profile_name},"request": self.pending.to_wire() if self.pending else None,"challenge_required": self.challenge_required,+ "sensitive_login": self.sensitive_login,"revision": self.revision,}@@ -209,6 +213,14 @@ class ProfileController:await self._broadcast()async def _broadcast(self) -> None:+ from services.browser_owners import persist_control+ from services.plugin.deps import get_database+ assistance = None+ if self.pending:+ assistance = {"reason": self.pending.reason, "message": self.pending.message,+ "deadline": time.time() + max(0, self.pending.deadline - time.monotonic())}+ await persist_control(get_database(), self.profile_id, self.task_id, challenge=self.challenge_required,+ needs_observation=self.needs_observation, assistance=assistance)session = self.lease_sessionif session is None:return@@ -253,10 +265,44 @@ class ProfileController:holder = self.lease_sessionif holder is None or holder.session_id == session.session_id:return True+ if self.task_id is not None:+ return Falseif self.state == ControlState.IDLE and self.pending is None and time.monotonic() - self.lease_renewed > LEASE_IDLE_SECONDS:return Truereturn False+ def claim_task(self, task_id: str) -> None:+ """Hold a profile through reasoning and assistance, not only input."""+ if self.task_id is not None and self.task_id != task_id:+ raise NodeUserError("BrowserBusy: this profile is already assigned to another task.")+ self.task_id = task_id++ async def release_task(self, task_id: str) -> bool:+ if self.task_id != task_id:+ return False+ await self.release_lease()+ self.task_id = None+ return True++ async def set_sensitive_login(self, enabled: bool) -> None:+ self.sensitive_login = enabled+ if enabled:+ self.tabs = {key: {"target_id": key} for key in self.tabs}+ self.revision += 1+ await self.emit("sensitive", {"enabled": enabled})+ await self._broadcast()++ async def restore_assistance(self, session: BrowserSession) -> None:+ saved, self.recovered_assistance = self.recovered_assistance, None+ if saved is None or self.pending is not None:+ return+ remaining = float(saved.get("deadline") or 0) - time.time()+ if remaining > 0 or self.challenge_required:+ await self.acquire_lease(session)+ await self._ensure_user_request(session, reason=str(saved.get("reason") or "other"),+ message=str(saved.get("message") or "Please finish this step."),+ timeout=max(60 if self.challenge_required else 0, remaining))+async def acquire_lease(self, session: BrowserSession, *, wait: float = LEASE_WAIT_SECONDS) -> None:if not self._lease_free_for(session):holder = self.lease_session@@ -407,6 +453,8 @@ class ProfileController:return self.challenge_required or self._user_claim or self.state in (ControlState.USER, ControlState.AWAITING_USER)async def take_over(self, viewer_id: str, *, force: bool = False, valid: Optional[Callable[[], bool]] = None) -> tuple[bool, str]:+ if self.sensitive_login:+ return False, "protected_login"if valid is not None and not valid():return False, "viewer_unavailable"if self.controller_viewer and self.controller_viewer != viewer_id and not force:@@ -478,7 +526,7 @@ class ProfileController:return Truedef can_inject_input(self, viewer_id: str) -> bool:- return self.state == ControlState.USER and self.controller_viewer == viewer_id+ return not self.sensitive_login and self.state == ControlState.USER and self.controller_viewer == viewer_iddef touch_user_input(self) -> None:now = time.monotonic()@@ -522,7 +570,7 @@ class ProfileController:self._resolve_pending("timeout", "")def idle_for(self) -> float:- busy = self.state != ControlState.IDLE or self.viewers or self.pending is not None+ busy = self.state != ControlState.IDLE or self.viewers or self.pending is not None or self.task_id is not None or self.sensitive_loginreturn 0.0 if busy else time.monotonic() - self.last_activitydiff --git a/server/nodes/browser/_stream.py b/server/nodes/browser/_stream.pyindex 58e11386..d8b3d7e5 100644--- a/server/nodes/browser/_stream.py+++ b/server/nodes/browser/_stream.py@@ -111,10 +111,14 @@ class Viewer:self._outstanding: Dict[int, float] = {}self._started_at = time.monotonic()self._first_frame = True+ self.privacy_blocked = False+ self._send_lock = asyncio.Lock()def send_json(self, message: Dict[str, Any]) -> None:if self.closed:return+ if self.privacy_blocked and message.get("type") in {"page", "tabs", "dialog", "clipboard", "error"}:+ returntry:self.control.put_nowait(message)except asyncio.QueueFull:@@ -123,7 +127,7 @@ class Viewer:def offer_frame(self, frame: bytes) -> bool:"""Keep the latest frame, including the final update inside an FPS interval."""- if self.closed or not self.visible:+ if self.closed or not self.visible or self.privacy_blocked:return Falseif self.pending is not None:self.metrics.count("replaced")@@ -165,7 +169,9 @@ class Viewer:captured_at = header.get("ts")if isinstance(captured_at, (int, float)):self.metrics.observe("capture_to_send", time.time() - captured_at)- await self.websocket.send_bytes(frame)+ async with self._send_lock:+ if not self.privacy_blocked:+ await self.websocket.send_bytes(frame)self.metrics.observe("socket_send", time.monotonic() - self.last_frame_at)if self._first_frame:self._first_frame = False@@ -213,6 +219,7 @@ class ScreencastHub:async def add(self, viewer: Viewer) -> None:self.viewers[viewer.id] = viewer+ viewer.privacy_blocked = getattr(self.controller, "sensitive_login", False)self.controller.viewer_attached(viewer.id)await self._refresh()@@ -250,13 +257,21 @@ class ScreencastHub:"type": "state", "state": snap["state"], "controller": snap["controller"],"request": snap["request"], "profile": snap["profile"],"challenge_required": snap["challenge_required"],+ "sensitive_login": snap.get("sensitive_login", False),}def tabs_message(self) -> Dict[str, Any]:+ if getattr(self.controller, "sensitive_login", False):+ return {"type": "tabs", "tabs": []}active = self.controller.active_target_idreturn {"type": "tabs", "tabs": [dict(t, active=t.get("target_id") == active) for t in self.controller.tabs.values()]}async def _on_controller(self, kind: str, payload: Dict[str, Any]) -> None:+ if kind == "sensitive":+ await self.sensitive_barrier(bool(payload.get("enabled")))+ return+ if getattr(self.controller, "sensitive_login", False) and kind in {"tabs", "page"}:+ returnif kind in ("tabs", "page"):self.commands.target_changed()if kind in ("state", "request", "control_moved"):@@ -292,7 +307,7 @@ class ScreencastHub:async def _refresh(self) -> None:async with self._lock:size = self._wanted_size()- if self.dead or size == (0, 0):+ if self.dead or size == (0, 0) or getattr(self.controller, "sensitive_login", False):self._cancel_retry()await self._stop_screencast_locked()return@@ -341,7 +356,7 @@ class ScreencastHub:async def _start_screencast_locked(self, size: tuple[int, int]) -> None:await self._stop_screencast_locked()- if not self.runtime.running:+ if not self.runtime.running or getattr(self.controller, "sensitive_login", False):returntry:session = await self.runtime.page_session(self.controller.active_target_id)@@ -411,7 +426,7 @@ class ScreencastHub:self._pending_acks.append((source, ack_id))started = time.monotonic()self.metrics.count("captured")- if not self.visible_viewers():+ if not self.visible_viewers() or getattr(self.controller, "sensitive_login", False):self._ack_now()returnself.seq = next(_FRAME_SEQUENCES)@@ -467,8 +482,36 @@ class ScreencastHub:task.add_done_callback(self._ack_tasks.discard)def _on_dialog(self, params: Dict[str, Any]) -> None:+ if getattr(self.controller, "sensitive_login", False):+ returnself.broadcast({"type": "dialog", "kind": params.get("type"), "message": str(params.get("message") or "")[:2000]})+ async def sensitive_barrier(self, enabled: bool) -> None:+ """Drain capture and sends before the resolver can retrieve secrets."""+ for viewer in list(self.viewers.values()):+ viewer.privacy_blocked = enabled+ viewer.pending = None+ if enabled:+ await self.commands.barrier(viewer.id)+ retained = []+ while not viewer.control.empty():+ message = viewer.control.get_nowait()+ if message.get("type") not in {"page", "tabs", "dialog", "clipboard", "error"}:+ retained.append(message)+ for message in retained:+ viewer.control.put_nowait(message)+ async with viewer._send_lock:+ pass+ viewer._outstanding.clear()+ viewer.inflight = 0+ viewer.send_json({"type": "sensitive", "enabled": enabled})+ viewer.send_json(self.state_message(viewer))+ if enabled:+ await self._stop_screencast()+ else:+ self.broadcast(self.tabs_message())+ await self._refresh()+# -- input ---------------------------------------------------------------------def _clamp(self, x: Any, y: Any) -> tuple[float, float]:@@ -599,6 +642,8 @@ class ScreencastHub:passasync def copy(self, viewer: Viewer) -> None:+ if getattr(self.controller, "sensitive_login", False):+ returnsession = self.commands.input_session(viewer)if not self.controller.can_inject_input(viewer.id) or session is None:return@@ -647,8 +692,9 @@ async def browser_live_view(websocket: WebSocket) -> None:from ._runtime import get_browser_runtime- owner = await authenticate_ws(websocket, settings=container.settings(), user_auth_service=container.user_auth_service)- if owner is None:+ forwarded = (getattr(websocket, "scope", {}) or {}).get("path") == "/ws/browser/owner"+ owner = None if forwarded else await authenticate_ws(websocket, settings=container.settings(), user_auth_service=container.user_auth_service)+ if owner is None and not forwarded:returnawait websocket.accept()@@ -661,6 +707,27 @@ async def browser_live_view(websocket: WebSocket) -> None:await websocket.close(code=CLOSE_ATTACH, reason="attach expected")returntry:+ from services.browser_owners import replica_id, settings, verify_forward, routing_for_node+ from services.plugin.deps import get_database+ if forwarded:+ body = json.dumps(first, separators=(",", ":")).encode()+ owner = verify_forward(websocket.headers.get("X-Browser-Forward", ""), "WS", "/ws/browser/owner", body)+ if getattr(settings(), "distributed_mode", False) is True:+ target = first.get("target") or {}+ from ._routing import handle_binding, proxy_view+ if target.get("kind") == "node":+ binding = await routing_for_node(get_database(), str(target.get("workflow_id") or ""), str(target.get("node_id") or ""), owner)+ elif target.get("kind") == "profile_login":+ binding = await handle_binding(str(target.get("login_id") or ""), owner)+ else:+ raise NodeUserError("Unknown live-view target")+ if binding["owner_id"] != replica_id():+ if forwarded:+ raise NodeUserError("Browser owner routing changed.")+ await proxy_view(websocket, first, owner, binding)+ return+ from services.browser_owners import assert_runtime_epoch+ await assert_runtime_epoch(get_database())session = await _resolve_attach(owner, first.get("target") or {})except NodeUserError as exc:await websocket.close(code=CLOSE_FORBIDDEN, reason=str(exc)[:120])diff --git a/server/nodes/browser/_system_browser.py b/server/nodes/browser/_system_browser.pyindex 72b00fcf..f3f8e17e 100644--- a/server/nodes/browser/_system_browser.py+++ b/server/nodes/browser/_system_browser.py@@ -141,9 +141,10 @@ def _windows_version(path: Path) -> str:async def browser_version(path: Path) -> str:+ from services.process_environment import without_onepassword_environmentif sys.platform == "win32":return await asyncio.to_thread(_windows_version, path)- process = await asyncio.create_subprocess_exec(str(path), "--version", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)+ process = await asyncio.create_subprocess_exec(str(path), "--version", env=without_onepassword_environment(), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)try:stdout, _ = await asyncio.wait_for(process.communicate(), timeout=5)except BaseException:diff --git a/server/nodes/browser/_webmcp.py b/server/nodes/browser/_webmcp.pyindex 669e18ea..f2485a64 100644--- a/server/nodes/browser/_webmcp.py+++ b/server/nodes/browser/_webmcp.py@@ -56,6 +56,7 @@ class WebMcpTracker:self._sessions: Dict[str, CDPSession] = {}self._pending: Dict[str, asyncio.Future] = {}self._early: Dict[str, Dict[str, Any]] = {}+ self._sensitive = False# -- wiring ---------------------------------------------------------------@@ -66,18 +67,34 @@ class WebMcpTracker:session.on("WebMCP.toolsRemoved", lambda p: self._removed(target_id, p))session.on("WebMCP.toolResponded", self._responded)session.on("Page.frameNavigated", lambda p: self._navigated(target_id, p))+ if self._sensitive:+ returntry:await session.send("WebMCP.enable", timeout=10)except CDPError as exc:if not exc.method_not_found:logger.debug("[browser] WebMCP.enable failed on %s: %s", target_id, exc)+ async def sensitive_barrier(self, enabled: bool) -> None:+ """Disable page-provided metadata before credential values are fetched."""+ self._sensitive = enabled+ self._tools.clear()+ self._early.clear()+ for session in list(self._sessions.values()):+ try:+ await session.send("WebMCP.disable" if enabled else "WebMCP.enable", timeout=5)+ except CDPError as exc:+ if not exc.method_not_found:+ raise RuntimeError("WebMCP suspension could not be confirmed") from None+def detach(self, target_id: str) -> None:self._sessions.pop(target_id, None)self._tools.pop(target_id, None)self._main_frames.pop(target_id, None)def _added(self, target_id: str, params: Dict[str, Any]) -> None:+ if self._sensitive:+ returnframes = self._tools.setdefault(target_id, {})for tool in params.get("tools") or []:name, frame = tool.get("name"), tool.get("frameId")@@ -102,6 +119,8 @@ class WebMcpTracker:self._tools.get(target_id, {}).pop(frame_id, None)def _responded(self, params: Dict[str, Any]) -> None:+ if self._sensitive:+ returninvocation = params.get("invocationId") or ""future = self._pending.get(invocation)if future is not None:@@ -118,7 +137,7 @@ class WebMcpTracker:def tools(self, target_id: Optional[str]) -> List[Dict[str, Any]]:"""The page's tools, shaped for the agent (no stack traces or node ids)."""- if not target_id:+ if self._sensitive or not target_id:return []out = []main = self._main_frames.get(target_id)@@ -152,6 +171,8 @@ class WebMcpTracker:mode: str = "read_only",timeout: float = INVOKE_TIMEOUT,) -> Dict[str, Any]:+ if self._sensitive:+ raise NodeUserError("Browser observations are paused during protected login.")if mode == "disabled":raise NodeUserError("WebMCP tools are turned off for this Browser node.")session = self._sessions.get(target_id or "")diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.pyindex ff83d531..805bf30b 100644--- a/server/nodes/browser/browser/__init__.py+++ b/server/nodes/browser/browser/__init__.py@@ -61,6 +61,8 @@ ModelOperation = Literal["webmcp_call","request_user","diagnose",+ "credential_fill",+ "credential_bindings",]NodeOperation = Literal["navigate",@@ -83,6 +85,8 @@ NodeOperation = Literal["webmcp_call","request_user","diagnose",+ "credential_fill",+ "credential_bindings","evaluate","run_python","close",@@ -90,7 +94,7 @@ NodeOperation = Literal[#: Permission policy. Retry safety and traffic accounting are separate:#: navigation can be permitted in read-only mode but cannot be blindly replayed.-MUTATING = frozenset({"click", "type", "press", "select", "back", "forward", "reload", "webmcp_call", "evaluate", "run_python"})+MUTATING = frozenset({"click", "type", "press", "select", "back", "forward", "reload", "webmcp_call", "evaluate", "run_python", "credential_fill"})#: Operations with a target element._TARGETED = {"click", "hover", "type", "select", "scroll", "page_text"}#: Only workflow nodes may run these; they are not in the model's schema.@@ -156,6 +160,10 @@ class BrowserToolInput(BaseModel):frame_id: str = Field(default="", description="Only when webmcp_list shows the same tool in several frames.", json_schema_extra=_show("webmcp_call"))reason: Literal["login", "captcha", "two_factor", "confirm", "other"] = Field(default="other", json_schema_extra=_show("request_user"))message: str = Field(default="", description="What the owner should do in the browser.", json_schema_extra=_show("request_user"))+ credential_binding_id: str = Field(default="", description="Opaque approved website-login binding ID. Never pass a password or 1Password reference.", json_schema_extra=_show("credential_fill"))+ username_ref: str = Field(default="", description="Username input ref from the current snapshot.", json_schema_extra=_show("credential_fill"))+ password_ref: str = Field(default="", description="Password input ref from the current snapshot.", json_schema_extra=_show("credential_fill"))+ submit_ref: str = Field(default="", description="A separately selected submit-button ref. Required for configured automatic login.", json_schema_extra=_show("credential_fill"))model_config = ConfigDict(extra="ignore")@@ -293,7 +301,17 @@ async def _config(ctx: NodeContext, params: BaseModel) -> BrowserParams:saved = await get_database().get_node_parameters(ctx.node_id)if saved is None:raise NodeUserError("This Browser node's settings could not be loaded. Save the workflow and try again.")- return BrowserParams.model_validate(saved)+ snapshot = ctx.raw.get("parameter_snapshot") or {}+ frozen = snapshot.get(ctx.node_id) if isinstance(snapshot, dict) else None+ versioned = ctx.raw.get("native_workspace_version") == 1 or ctx.raw.get("browser_runtime_version") == 1 or ctx.raw.get("browser_routing_version") == 1+ cfg = BrowserParams.model_validate(frozen if versioned and isinstance(frozen, dict) else saved)+ # This is the adapter's validated server configuration, never tool_args.+ # An employee's Ask first restriction must survive reloading saved settings.+ trusted = ctx.raw.get("_tool_config")+ trusted_interaction = trusted.interaction if isinstance(trusted, BrowserParams) else trusted.get("interaction") if isinstance(trusted, dict) else None+ if saved.get("interaction") == "read_only" or trusted_interaction == "read_only":+ cfg = cfg.model_copy(update={"interaction": "read_only"})+ return cfgasync def _profile_for(ctx: NodeContext, cfg: BrowserParams):@@ -304,6 +322,9 @@ async def _profile_for(ctx: NodeContext, cfg: BrowserParams):store = ProfileStore(get_database())owner = ctx.user_id or "owner"try:+ binding = ctx.raw.get("_browser_owner")+ if isinstance(binding, dict) and binding.get("profile_id"):+ return await store.get(owner, str(binding["profile_id"]))if cfg.profile_id:return await store.get(owner, cfg.profile_id)if ctx.workflow_id:@@ -332,6 +353,7 @@ class BrowserNode(ToolNode):group = ("browser", "tool")description = "A real Chrome the agent drives through its accessibility tree and a site's WebMCP tools; watch and take over live."component_kind = "square"+ usable_as_tool = Truetool_name = "browser"tool_schema_locked = Truetool_error_fields = frozenset({"success", "error_type", "retry_after", "next_action", "session_id", "profile", "url", "title", "tab_id"})@@ -384,6 +406,10 @@ class BrowserNode(ToolNode):return {"reset": False}controller = runtime.controller(session.profile_id)if controller is not None:+ if controller.task_id is not None:+ # The owning agent's reset hook carries its exact task token.+ # A legacy Browser hook must not release an unrelated task.+ return {"reset": False, "managed_by_agent": True}await controller.release_lease(session.session_id)return {"reset": True}@@ -412,6 +438,12 @@ class BrowserNode(ToolNode):runtime = get_browser_runtime()profile = await _profile_for(ctx, cfg)owner = ctx.user_id or "owner"+ task_id = str(ctx.raw.get("_browser_task_id") or ctx.execution_id or "")+ from services.browser_owners import assert_owner, bind_profile, _persistent+ from services.plugin.deps import get_database+ if ctx.raw.get("_browser_owner") or _persistent(get_database()):+ binding = ctx.raw.get("_browser_owner") or await bind_profile(get_database(), profile.id, owner)+ await assert_owner(get_database(), binding, owner, task_id)workflow_key = ctx.workflow_id or f"unsaved:{ctx.execution_id or 'run'}"policy = runtime.base_policy(allow_private_network=cfg.allow_private_network, allowed_domains=parse_allowed_domains(cfg.allowed_domains)@@ -424,6 +456,13 @@ class BrowserNode(ToolNode):BrowserSession(key=SessionKey(owner, workflow_key, ctx.node_id), profile_id=profile.id, label=label, policy=policy))out = BrowserOutput(operation=op, session_id=session.session_id, profile=profile.name)+ controller_lookup = getattr(runtime, "controller", None)+ existing_controller = controller_lookup(profile.id) if callable(controller_lookup) else controller_lookup+ if existing_controller is not None:+ if existing_controller.task_id is not None and existing_controller.task_id != task_id:+ return _failure(out, "BrowserBusy", "This browser profile is already assigned to another task.", next_action="wait")+ if existing_controller.sensitive_login and op not in {"request_user", "close", "credential_bindings"}:+ return _failure(out, "sensitive_login", "Browser observations are paused during a protected login. Close and reopen this browser to finish login manually.", next_action="request_user")budget = _TOOL_CALL_BUDGET if tool_call else 3600.0def remaining() -> float:@@ -441,12 +480,41 @@ class BrowserNode(ToolNode):out.notice = "The browser was closed."return out+ if op == "credential_bindings":+ from core.container import container+ from .._credentials import scoped_bindings+ out.data = {"bindings": await scoped_bindings(ctx, container.auth_service(), profile.id)}+ return out+if op == "diagnose":out.data = await _diagnose(runtime, profile)return outprt = await runtime.open(profile, wait=min(remaining(), 300.0))controller = prt.controller+ if controller.task_id is not None and controller.task_id != task_id:+ return _failure(out, "BrowserBusy", "This browser profile is already assigned to another task.", next_action="wait")+ await controller.restore_assistance(session)+ if controller.sensitive_login and op != "request_user":+ return _failure(out, "sensitive_login", "Browser observations are paused during a protected login. Ask the owner to finish login and hand the browser back.", next_action="request_user")+ if op == "credential_fill":+ from .._credentials import fill_credentials+ if controller.needs_observation:+ return _failure(out, "outcome_unknown", "Inspect a fresh snapshot before attempting login.", next_action="snapshot")+ async with controller.agent_op(session, interrupt=prt.cli.interrupt):+ decision = runtime.action_guard.admit(origin=_action_origin(op, call, controller), profile_id=profile.id,+ operation=op, arguments={"binding": call.credential_binding_id, "username_ref": call.username_ref,+ "password_ref": call.password_ref, "submit_ref": call.submit_ref},+ min_interval_ms=cfg.min_action_interval_ms, max_actions_per_minute=cfg.max_actions_per_minute,+ max_repeat_actions=cfg.max_repeat_actions)+ if decision is not None:+ return _failure(out, decision.error_type, decision.error, retry_after=decision.retry_after, next_action=decision.next_action)+ result = await fill_credentials(ctx, prt, call, timeout=min(float(cfg.op_timeout_s), remaining()))+ if result.get("success"):+ out.data = {"status": "authenticated"}+ out.notice = "Configured website login completed. Take a fresh snapshot."+ return out+ return _failure(out, result.get("error_type", "login_required"), result.get("error", "Please finish login manually."), next_action="request_user")if op == "request_user":wait = min(float(cfg.request_user_timeout_s), _TOOL_REQUEST_WAIT) if tool_call else float(cfg.request_user_timeout_s)@@ -549,6 +617,8 @@ def _action_arguments(op: str, call: BrowserToolInput, cfg: BrowserParams, contrdef _fill_page(out: BrowserOutput, controller: Any) -> None:+ if getattr(controller, "sensitive_login", False):+ returntab = controller.tabs.get(controller.active_target_id or "") or {}out.tab_id = controller.active_target_idout.url = out.url or tab.get("url")diff --git a/server/nodes/cloudflare/_service.py b/server/nodes/cloudflare/_service.pyindex 83260663..a015036c 100644--- a/server/nodes/cloudflare/_service.py+++ b/server/nodes/cloudflare/_service.py@@ -26,6 +26,7 @@ path) but stripped for login / whoami / logout (see :func:`login_env`).from __future__ import annotationsimport os+from services.process_environment import without_onepassword_environmentfrom pathlib import Pathfrom typing import Any, Dict, Optional@@ -102,7 +103,7 @@ def cf_env(token: Optional[str] = None, account_id: Optional[str] = None) -> Dicenv["CLOUDFLARE_API_TOKEN"] = tokenif account_id:env["CLOUDFLARE_ACCOUNT_ID"] = account_id- return env+ return without_onepassword_environment(env)def api_auth_headers(key: Optional[str], email: Optional[str]) -> Optional[Dict[str, str]]:@@ -143,7 +144,7 @@ def login_env() -> Dict[str, str]:env = cf_env()for var in _AMBIENT_CREDENTIAL_VARS:env.pop(var, None)- return env+ return without_onepassword_environment(env)def resolve_cf_light() -> Optional[str]:diff --git a/server/nodes/filesystem/_backend.py b/server/nodes/filesystem/_backend.pyindex a4cef28d..073cd1d1 100644--- a/server/nodes/filesystem/_backend.py+++ b/server/nodes/filesystem/_backend.py@@ -25,6 +25,8 @@ from typing import Any, Callable, Dict, Final, Optionalfrom uuid import uuid4from weakref import WeakValueDictionary+from services.process_environment import without_onepassword_environment+EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents"@@ -1053,7 +1055,7 @@ class WorkspaceBackend:stdin=subprocess.DEVNULL,text=True,timeout=effective_timeout,- env=self._env,+ env=without_onepassword_environment(self._env),cwd=str(self.cwd),)return self._shape_process_result(diff --git a/server/nodes/gcloud/_service.py b/server/nodes/gcloud/_service.pyindex 1c8ad08c..6da74797 100644--- a/server/nodes/gcloud/_service.py+++ b/server/nodes/gcloud/_service.py@@ -28,6 +28,7 @@ lands isolated at ``<DATA_DIR>/gcloud/application_default_credentials.json``).from __future__ import annotationsimport os+from services.process_environment import without_onepassword_environmentfrom typing import Any, Dict, Optional# Ambient credential/config env vars that would mask the pinned-config@@ -60,7 +61,7 @@ def gcloud_env() -> Dict[str, str]:env["CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK"] = "1"env["CLOUDSDK_CORE_DISABLE_USAGE_REPORTING"] = "1"env["NO_COLOR"] = "1"- return env+ return without_onepassword_environment(env)def login_env() -> Dict[str, str]:@@ -73,7 +74,7 @@ def login_env() -> Dict[str, str]:env = gcloud_env()for var in _AMBIENT_CREDENTIAL_VARS:env.pop(var, None)- return env+ return without_onepassword_environment(env)def resolve_gcloud_light() -> Optional[str]:diff --git a/server/nodes/github/_service.py b/server/nodes/github/_service.pyindex 9fd5e2fc..0c0dec83 100644--- a/server/nodes/github/_service.py+++ b/server/nodes/github/_service.py@@ -17,6 +17,7 @@ for ``gh auth login`` / ``status`` / ``logout`` (seefrom __future__ import annotationsimport os+from services.process_environment import without_onepassword_environmentfrom pathlib import Pathfrom typing import Dict, Optional@@ -33,7 +34,7 @@ def gh_env() -> Dict[str, str]:env["NO_COLOR"] = "1"env["GH_NO_UPDATE_NOTIFIER"] = "1"env["GH_PAGER"] = "cat"- return env+ return without_onepassword_environment(env)def login_env() -> Dict[str, str]:@@ -50,7 +51,7 @@ def login_env() -> Dict[str, str]:env.pop("GH_TOKEN", None)env.pop("GITHUB_TOKEN", None)env.pop("GH_PROMPT_DISABLED", None)- return env+ return without_onepassword_environment(env)def resolve_gh_light() -> Optional[str]:diff --git a/server/nodes/mobile/_node.py b/server/nodes/mobile/_node.pyindex 39230fd4..5ff0df9b 100644--- a/server/nodes/mobile/_node.py+++ b/server/nodes/mobile/_node.py@@ -99,7 +99,7 @@ async def resolve_model(ctx: NodeContext, params: MobileParams | None = None) ->if provider_ref not in adapters:raise NodeUserError(f"The selected provider '{provider_ref}' is not supported by the phone engine. Choose an OpenAI, Anthropic, or Gemini model in the global selector or this phone's settings")auth = get_ai_service().auth- key = await auth.get_api_key(provider_ref, "default")+ key = await auth.resolve_api_key(provider_ref, "default", principal=ctx.raw.get("user_id"))if not key:raise NodeUserError("Connect the selected model provider in Settings before running Mobile")model = selected_model or await get_default_model_async(provider_ref, database)@@ -109,7 +109,7 @@ async def resolve_model(ctx: NodeContext, params: MobileParams | None = None) ->if provider_ref in endpoint_variables:from services.llm.endpoints import base_url_key- endpoint = await auth.get_api_key(base_url_key(provider_ref), "default")+ endpoint = await auth.resolve_api_key(base_url_key(provider_ref), "default", principal=ctx.raw.get("user_id"))if endpoint:# Use the same saved endpoint as the native provider, unchanged.# It may contain credentials, so it travels only through private IPC.diff --git a/server/nodes/mobile/_process.py b/server/nodes/mobile/_process.pyindex 2de5f300..f54023f5 100644--- a/server/nodes/mobile/_process.py+++ b/server/nodes/mobile/_process.py@@ -8,6 +8,7 @@ import osimport reimport subprocessfrom typing import Callable+from services.process_environment import without_onepassword_environmentOUTPUT_TAIL_BYTES = 64 * 1024@@ -31,7 +32,7 @@ async def command(stdin=asyncio.subprocess.PIPE if input_text is not None else asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,- env=env,+ env=without_onepassword_environment(env),cwd=cwd,**hidden_options(),)diff --git a/server/nodes/mobile/_runtime.py b/server/nodes/mobile/_runtime.pyindex 655285f5..ae1d03d6 100644--- a/server/nodes/mobile/_runtime.py+++ b/server/nodes/mobile/_runtime.py@@ -9,6 +9,7 @@ import secretsimport socketimport timefrom pathlib import Path+from services.process_environment import without_onepassword_environmentfrom ._control import DeviceControl, Lease, MobileErrorfrom ._install import AVD_NAME, install_engine, create_device, engine_ready, sdk_tool, sdk_rootfrom ._paths import mobile_root, runtime_python@@ -306,7 +307,7 @@ class MobileRuntime:"-no-audio",stdout=log,stderr=log,- env=env,+ env=without_onepassword_environment(env),**hidden_options(),)finally:@@ -368,7 +369,7 @@ class MobileRuntime:)for name in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV"):env.pop(name, None)- return env+ return without_onepassword_environment(env)async def _start_driver(self):event("driver_starting")diff --git a/server/nodes/mobile/_video.py b/server/nodes/mobile/_video.pyindex 55a8e90e..e0e762b1 100644--- a/server/nodes/mobile/_video.py+++ b/server/nodes/mobile/_video.py@@ -10,6 +10,7 @@ import contextlibimport hashlibimport secretsfrom fastapi import WebSocket, WebSocketDisconnect+from services.process_environment import without_onepassword_environmentfrom ._control import MobileErrorfrom ._install import SCRCPY_SHA256, SCRCPY_VERSION, sdk_toolfrom ._paths import mobile_root@@ -85,6 +86,7 @@ async def stream_video(websocket: WebSocket, viewer: str) -> None:raise MobileError("video_tunnel_failed", "Invalid video tunnel port")proc = await asyncio.create_subprocess_exec(*server_arguments(serial, scid),+ env=without_onepassword_environment(),stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.DEVNULL,stderr=asyncio.subprocess.DEVNULL,diff --git a/server/nodes/model/_credentials.py b/server/nodes/model/_credentials.pyindex f16c57aa..c08940e5 100644--- a/server/nodes/model/_credentials.py+++ b/server/nodes/model/_credentials.py@@ -172,7 +172,7 @@ class _LocalLLM(_LLMApiKey):from services.llm.config import resolve_credentialfrom services.plugin.deps import get_auth_service- api_key = await get_auth_service().get_api_key(cls.id)+ api_key = await get_auth_service().resolve_api_key(cls.id, principal=user_id)return {"api_key": resolve_credential(cls.id, api_key)}@classmethod@@ -299,14 +299,14 @@ class OpenAICompatibleCredential(_LLMApiKey):return await save_llm_server(ref, candidate, user_key, display=label, label=label)@classmethod- async def catalogue_extras(cls) -> Dict[str, Any]:+ async def catalogue_extras(cls, *, principal: Optional[str] = None) -> Dict[str, Any]:"""``stored`` (any endpoint saved) plus the endpoint list for the panel."""from services.llm.endpoints import list_endpointsfrom services.plugin.deps import get_auth_serviceendpoints = [{"ref": e.ref, "label": e.label, "base_url": e.base_url, "kind": e.kind, "model_count": len(e.models)}- for e in await list_endpoints(get_auth_service())+ for e in await list_endpoints(get_auth_service(), **({"principal": principal} if principal is not None else {}))]return {"stored": bool(endpoints), "endpoints": endpoints}diff --git a/server/nodes/scraper/apify_actor/__init__.py b/server/nodes/scraper/apify_actor/__init__.pyindex 24b35c9e..7fefeb29 100644--- a/server/nodes/scraper/apify_actor/__init__.py+++ b/server/nodes/scraper/apify_actor/__init__.py@@ -20,13 +20,13 @@ from .._credentials import ApifyCredentiallogger = get_logger(__name__)-async def _get_apify_client():+async def _get_apify_client(*, principal: str | None = None):"""Return an authenticated Apify client, or None if no token saved."""from apify_client import ApifyClientAsync # lazy — optional depfrom services.plugin.deps import get_auth_serviceauth_service = get_auth_service()- api_token = await auth_service.get_api_key("apify", "default")+ api_token = await auth_service.resolve_api_key("apify", "default", principal=principal)if not api_token:return Nonereturn ApifyClientAsync(api_token)@@ -264,7 +264,7 @@ class ApifyActorNode(ActionNode):@Operation("run")async def run(self, ctx: NodeContext, params: ApifyActorParams) -> ApifyActorOutput:- client = await _get_apify_client()+ client = await _get_apify_client(principal=ctx.raw.get("user_id"))if not client:raise NodeUserError("Apify API token not configured. Please add your token in Credentials.",diff --git a/server/nodes/speech/_handlers.py b/server/nodes/speech/_handlers.pyindex 941bd6a2..6bb0d101 100644--- a/server/nodes/speech/_handlers.py+++ b/server/nodes/speech/_handlers.py@@ -41,14 +41,14 @@ def dictation_providers() -> list[str]:return [str(provider) for provider in configured if str(provider) in available]-async def dictation_provider() -> Optional[str]:+async def dictation_provider(*, principal: str | None = None) -> Optional[str]:"""The first dictation provider with a stored key, or None."""from core.container import containerauth = container.auth_service()for provider in dictation_providers():try:- if await auth.get_api_key(speech_config.credential_id(provider)):+ if await auth.has_valid_key(speech_config.credential_id(provider), principal=principal):return providerexcept Exception: # noqa: BLE001 - an unreadable key is no keylogger.warning("Dictation key could not be read", provider=provider, exc_info=True)@@ -74,7 +74,8 @@ async def handle_dictation_status(data: Dict[str, Any], websocket: WebSocket) ->"""``{available, provider}``: whether a recording can be turned intotext now."""await _owner_session(data, websocket)- provider = await dictation_provider()+ from services.authz.ws_surface import execution_principal+ provider = await dictation_provider(principal=execution_principal({}, websocket))return {"success": True, "available": provider is not None, "provider": provider}@@ -88,7 +89,9 @@ async def handle_transcribe_audio(data: Dict[str, Any], websocket: WebSocket) ->from services.workspace_locator import resolve_workspace_rootworkflow_id = await _owner_session(data, websocket)- provider = await dictation_provider()+ from services.authz.ws_surface import execution_principal+ principal = execution_principal({}, websocket)+ provider = await dictation_provider(principal=principal)if provider is None:return {"success": False, "error": "speech_unavailable"}rel = str(data.get("path") or "").replace("\\", "/")@@ -105,7 +108,7 @@ async def handle_transcribe_audio(data: Dict[str, Any], websocket: WebSocket) ->if isinstance(max_bytes, int) and size > max_bytes:raise NodeUserError("The recording is too long to transcribe. Record a shorter one.")try:- api_key = await container.auth_service().get_api_key(speech_config.credential_id(provider))+ api_key = await container.auth_service().resolve_api_key(speech_config.credential_id(provider), principal=principal)result = await _unifier.transcribe(provider=provider,api_key=str(api_key or ""),diff --git a/server/nodes/speech/_option_loaders.py b/server/nodes/speech/_option_loaders.pyindex 1ebca2d6..8df04594 100644--- a/server/nodes/speech/_option_loaders.py+++ b/server/nodes/speech/_option_loaders.py@@ -148,21 +148,25 @@ async def load_speech_voices(params: Dict[str, Any]) -> List[Dict[str, Any]]:try:from services.plugin.deps import get_auth_service+ from services.ws_handler_registry import current_load_options_principalfrom . import _unifier- api_key = await get_auth_service().get_api_key(- speech_config.credential_id(provider)+ api_key = await get_auth_service().resolve_api_key(+ speech_config.credential_id(provider), principal=current_load_options_principal())if not api_key:return staticvoices = await _unifier.list_voices(provider=provider, api_key=api_key)return [voice.as_option() for voice in voices] or staticexcept Exception as exc:+ from services.credentials.onepassword import CredentialSourceError+ if isinstance(exc, CredentialSourceError):+ raiselogger.warning("live voice lookup failed; falling back to the configured list",provider=provider,- error=str(exc),+ error=type(exc).__name__,)return staticdiff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.pyindex e2728eeb..f98a6063 100644--- a/server/nodes/tool/agent_builder/__init__.py+++ b/server/nodes/tool/agent_builder/__init__.py@@ -1199,6 +1199,14 @@ class AgentBuilderNode(ToolNode):nodes = [NewNode("agent", agent_type, label, specialist_params, position=(x + 300, y + 200)),NewNode("context", _CONTEXT_TYPE, "Context", position=(x + 300, y + 20), context_of="agent")]edges = [Edge("agent", _TEAMMATE_OUTPUT, str(caller), _TEAMMATES_INPUT)]+ if agent_type == "browser_agent":+ from services.browser_agent_recipe import BROWSER_AGENT_ROLE, browser_agent_additions+ if not {"browser", "visionAnalyze"}.issubset(_allowed_tool_types()) or "web_agent" in _allowlist_config().get("disabled_skill_folders", []):+ return _refused("add_subagent", "Browser tools or instructions are disabled by the operator.")+ specialist_params["system_message"] = BROWSER_AGENT_ROLE + "\n" + specialist_params["system_message"]+ bundle = browser_agent_additions(agent_parameters=specialist_params, position=(x + 300, y + 200))+ nodes = list(bundle.nodes)+ edges.extend(bundle.edges)for index, tool_type in enumerate(dict.fromkeys(params.tool_types)):if tool_type not in _allowed_tool_types():return _refused("add_subagent", f"The specialist cannot use '{tool_type}'. Inspect available tools first.")@@ -1210,10 +1218,15 @@ class AgentBuilderNode(ToolNode):validated = cls.Params.model_validate(config).model_dump(exclude_unset=True)except ValueError:return _refused("add_subagent", f"'{tool_type}' needs valid configuration. Inspect its node contract first.")+ if agent_type == "browser_agent" and tool_type in {"browser", "visionAnalyze"}:+ # These private tools are already present in the shared recipe.+ continueref = f"tool_{index}"nodes.append(NewNode(ref, tool_type, getattr(cls, "display_name", "") or tool_type, validated, position=(x + 160 + index * 170, y + 440)))edges.append(tool_edge(ref, "agent"))skill_config = {}+ if agent_type == "browser_agent":+ skill_config.update(next(node.params["skills_config"] for node in nodes if node.ref == "skills"))for name in dict.fromkeys(params.skill_names):skill = await _find_skill(database, name, employee=False)if skill is None:@@ -1223,15 +1236,19 @@ class AgentBuilderNode(ToolNode):from services.employees.policy import SKILL_TOOL_ENTRY, SKILL_TOOL_NAMEskill_config[SKILL_TOOL_NAME] = dict(SKILL_TOOL_ENTRY)- nodes.append(NewNode("skills", _MASTER_SKILL_TYPE, "Specialist skills", {"skill_folder": "assistant", "skills_config": skill_config}, position=(x + 20, y + 200)))- edges.append(skill_edge("skills", "agent"))+ if agent_type == "browser_agent":+ from dataclasses import replace+ nodes = [replace(node, params={**node.params, "skills_config": skill_config}) if node.ref == "skills" else node for node in nodes]+ else:+ nodes.append(NewNode("skills", _MASTER_SKILL_TYPE, "Specialist skills", {"skill_folder": "assistant", "skills_config": skill_config}, position=(x + 20, y + 200)))+ edges.append(skill_edge("skills", "agent"))additions = GraphAdditions(nodes=tuple(nodes), edges=tuple(edges),)grant_ids: List[str] = []if employee is not None and not existing:permission = await _permission(database, ctx, params, agent_type, [str(caller)], {- "purpose": specialist_params["system_message"], "tool_types": sorted(set(params.tool_types)),+ "purpose": specialist_params["system_message"], "tool_types": sorted(set(params.tool_types) | ({"browser", "visionAnalyze"} if agent_type == "browser_agent" else set())),"tool_parameters": params.tool_parameters, "skill_names": sorted(set(params.skill_names)),"model": specialist_params.get("model"), "provider": specialist_params.get("provider"),}, grant_ids)diff --git a/server/nodes/vercel/_service.py b/server/nodes/vercel/_service.pyindex 39711c59..ee85b53a 100644--- a/server/nodes/vercel/_service.py+++ b/server/nodes/vercel/_service.py@@ -16,6 +16,7 @@ helpers only — no plugin subpaths in ``core/paths.py``).from __future__ import annotationsimport os+from services.process_environment import without_onepassword_environmentimport refrom pathlib import Pathfrom typing import Dict, List, Optional@@ -65,7 +66,7 @@ def vercel_env(token: Optional[str] = None) -> Dict[str, str]:env["NO_COLOR"] = "1"if token:env["VERCEL_TOKEN"] = token- return env+ return without_onepassword_environment(env)async def stored_token() -> Optional[str]:diff --git a/server/pyproject.toml b/server/pyproject.tomlindex 734faf7f..c45fda59 100644--- a/server/pyproject.toml+++ b/server/pyproject.toml@@ -12,6 +12,7 @@ dependencies = [# Database"sqlmodel>=0.0.22","aiosqlite>=0.20.0",+ "asyncpg>=0.30.0,<1", # Shared application metadata for distributed deployments."greenlet>=3.0.0", # Required by SQLAlchemy asyncio on macOS ARM64# HTTP/WebSocketdiff --git a/server/routers/browser_agents.py b/server/routers/browser_agents.pynew file mode 100644index 00000000..f0da3e98--- /dev/null+++ b/server/routers/browser_agents.py@@ -0,0 +1,79 @@+"""Authorized atomic creation of the Browser AI Agent capability."""+from uuid import UUID++from fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, ConfigDict, Field+from sqlmodel import select++from core.container import container+from models.database import Workflow+from services.browser_agent_recipe import browser_agent_additions+from services.plugin import NodeUserError+from services.workflow_storage.mutate import apply_graph_additions++router = APIRouter(prefix="/api/browser/agents", tags=["browser"])+++class CreateBrowserAgent(BaseModel):+ workflow_id: str = Field(min_length=1, max_length=255)+ mutation_id: UUID+ browser_node_id: str | None = Field(default=None, max_length=255)+ position: tuple[float, float] = (0, 0)+ provider: str | None = Field(default=None, max_length=255)+ model: str | None = Field(default=None, max_length=255)+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)+++async def create_browser_agent(body: CreateBrowserAgent, request: Request):+ database = container.database()+ principal = str(getattr(request.state, "user_id", None) or "owner")++ async def authorize(session):+ saved = (await session.execute(select(Workflow).where(Workflow.id == body.workflow_id))).scalar_one_or_none()+ if saved is None or (saved.data.get("owner_id") and str(saved.data["owner_id"]) != principal):+ raise HTTPException(status_code=404, detail="Workflow not found")++ # A cached mutation receipt must not bypass authorization after access+ # was revoked. The transaction callback also checks at mutation time.+ async with database.get_session() as session:+ await authorize(session)+ from services.node_allowlist import get_node_allowlist_service+ from models.node_metadata import NODE_METADATA+ policy = get_node_allowlist_service().get_config()+ for kind in ("browser_agent", "browser", "masterSkill", "context", "visionAnalyze"):+ metadata = NODE_METADATA.get(kind) or {}+ groups = metadata.get("group") or []+ if isinstance(groups, str):+ groups = [groups]+ if kind in policy["disabled_nodes"] or set(groups).intersection(policy["disabled_groups"]):+ raise HTTPException(status_code=403, detail="Browser AI Agent is disabled by the operator")+ if "web_agent" in policy["disabled_skill_folders"]:+ raise HTTPException(status_code=403, detail="Browser instructions are disabled by the operator")++ def prepare(graph):+ if body.browser_node_id:+ node = next((node for node in graph.get("nodes", []) if node.get("id") == body.browser_node_id), None)+ if node is None or node.get("type") != "browser":+ raise NodeUserError("Select a saved Browser tool in this workflow.")+ nodes = {node["id"]: node for node in graph.get("nodes", [])}+ existing = next((edge["target"] for edge in graph.get("edges", [])+ if edge.get("source") == body.browser_node_id and edge.get("targetHandle") == "input-tools"+ and nodes.get(edge.get("target"), {}).get("type") == "browser_agent"), None)+ if existing:+ from services.graph_build import GraphAdditions+ return GraphAdditions(), {"agent": existing, "browser": body.browser_node_id}+ parameters = {key: value for key, value in {"provider": body.provider, "model": body.model}.items() if value is not None}+ return browser_agent_additions(agent_parameters=parameters, position=body.position,+ browser_node_id=body.browser_node_id), {}++ try:+ result = await apply_graph_additions(database, body.workflow_id, browser_agent_additions(),+ mutation_id=f"browser-agent:{principal}:{body.mutation_id}",+ prepare=prepare, authorize=authorize)+ except NodeUserError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from None+ if result is None:+ raise HTTPException(status_code=404, detail="Workflow not found")+ return {"node_ids": result.node_ids, "operations": result.operations, "applied": result.applied,+ "saved_revision": result.saved_revision}diff --git a/server/routers/browser_tasks.py b/server/routers/browser_tasks.pynew file mode 100644index 00000000..c7ddf760--- /dev/null+++ b/server/routers/browser_tasks.py@@ -0,0 +1,70 @@+"""Authorized Browser Workspace commands and recent task history."""++from fastapi import APIRouter, HTTPException, Query, Request+from pydantic import BaseModel, ConfigDict, Field+from uuid import UUID++router = APIRouter(prefix="/api/browser/tasks", tags=["browser"])+++class TaskSubmission(BaseModel):+ model_config = ConfigDict(extra="forbid")+ workflow_id: str = Field(min_length=1, max_length=255)+ agent_node_id: str = Field(min_length=1, max_length=255)+ prompt: str = Field(min_length=1, max_length=20000)+ submission_id: UUID+++def principal(request: Request) -> str:+ from constants import OWNER_PRINCIPAL_ID+ return str(getattr(request.state, "user_id", None) or OWNER_PRINCIPAL_ID)+++async def call(operation):+ from services.plugin import NodeUserError+ try:+ return await operation+ except NodeUserError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from None+ except ValueError:+ raise HTTPException(status_code=400, detail="Invalid submission identity") from None++[email protected]("/discovery")+async def discover(request: Request, workflow_id: str, browser_node_id: str):+ from services.browser_tasks import discovery+ from services.plugin.deps import get_database+ return await call(discovery(get_database(), principal(request), workflow_id, browser_node_id))+++async def submit_task(request: Request, body: TaskSubmission):+ from services.node_invocations import submit+ from services.authz.workflow_node import resolve_workflow_node+ from services.plugin import NodeUserError+ async def operation():+ _, _, node = await resolve_workflow_node(principal(request), body.workflow_id, body.agent_node_id)+ if node.get("type") != "browser_agent":+ raise NodeUserError("Select a Browser AI Agent")+ return await submit(principal(request), body.workflow_id, body.agent_node_id, body.prompt, str(body.submission_id))+ return await call(operation())++[email protected]("/history")+async def history(request: Request, workflow_id: str, node_id: str | None = None,+ cursor: str | None = None, limit: int = Query(20, ge=1, le=100)):+ from services.workspace_task_history import list_tasks+ from services.plugin.deps import get_database+ return await call(list_tasks(get_database(), principal(request), workflow_id, node_id=node_id, cursor=cursor, limit=limit))++[email protected]("/{submission_id}")+async def task_status(request: Request, submission_id: str, workflow_id: str, agent_node_id: str):+ from services.node_invocations import status+ return await call(status(principal(request), workflow_id, agent_node_id, submission_id))++[email protected]("/{submission_id}")+async def cancel_task(request: Request, submission_id: str, workflow_id: str, agent_node_id: str):+ from services.node_invocations import status+ return await call(status(principal(request), workflow_id, agent_node_id, submission_id, cancel=True))diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex f64994d4..928a9cc8 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -399,10 +399,12 @@ async def handle_get_credential_catalogue(data: Dict[str, Any], websocket: WebSofrom services.credential_registry import get_credential_registry, provider_connection_stateregistry = get_credential_registry()+ auth_service = container.auth_service()+ principal = execution_principal({}, websocket)since = data.get("since")# Includes live pairing state, which changes without a credential# mutation (see CredentialRegistry.get_live_version).- version = registry.get_live_version()+ version = registry.get_live_version() + "+" + await auth_service.credential_source_version(principal)if since and since == version:return {"unchanged": True, "version": version}@@ -415,9 +417,8 @@ async def handle_get_credential_catalogue(data: Dict[str, Any], websocket: WebSo# renders these flags and never checks key existence itself. The rules# live in services.credential_registry.provider_connection_state, which# the Normal-mode employee summaries share.- auth_service = container.auth_service()for provider in catalogue.get("providers", []):- provider.update(await provider_connection_state(provider, auth_service))+ provider.update(await provider_connection_state(provider, auth_service, principal=principal))return cataloguediff --git a/server/services/_supervisor/process.py b/server/services/_supervisor/process.pyindex 6ea8f9ff..92ffd34a 100644--- a/server/services/_supervisor/process.py+++ b/server/services/_supervisor/process.py@@ -18,6 +18,8 @@ from typing import Any, Optionalimport anyio+from services.process_environment import without_onepassword_environment+from .base import BaseSupervisorfrom .util import drain_stream, terminate_then_kill@@ -96,7 +98,7 @@ class BaseProcessSupervisor(BaseSupervisor):argv = self.argv()kwargs: dict[str, Any] = {"cwd": str(self.cwd()) if self.cwd() else None,- "env": self.env(),+ "env": without_onepassword_environment(self.env()),}if self.pipe_streams:kwargs["stdout"] = subprocess.PIPEdiff --git a/server/services/ai.py b/server/services/ai.pyindex c2756b4f..e3259a5c 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1214,6 +1214,8 @@ class AIService:# Stable per-run id so session-keyed tools (browser)# reuse one instance across the agent loop.config["execution_id"] = context.get("execution_id")+ config["_browser_task_id"] = context.get("_browser_task_id")+ config["_browser_owner"] = (context.get("browser_bindings") or {}).get(str(tool_node_id))config["root_execution_id"] = context.get("root_execution_id")config["delegation_depth"] = context.get("delegation_depth", 0)config["team_id"] = context.get("team_id")@@ -1985,6 +1987,8 @@ class AIService:# Stable per-run id so session-keyed tools (browser)# reuse one instance across the agent loop.config["execution_id"] = context.get("execution_id")+ config["_browser_task_id"] = context.get("_browser_task_id")+ config["_browser_owner"] = (context.get("browser_bindings") or {}).get(str(tool_node_id))config["root_execution_id"] = context.get("root_execution_id")config["delegation_depth"] = context.get("delegation_depth", 0)config["team_id"] = context.get("team_id")@@ -2595,6 +2599,7 @@ class AIService:"android_agent","coding_agent","web_agent",+ "browser_agent","task_agent","social_agent","travel_agent",diff --git a/server/services/auth.py b/server/services/auth.pyindex ebe6c348..edec863d 100644--- a/server/services/auth.py+++ b/server/services/auth.py@@ -75,6 +75,85 @@ class AuthService:# ``get_oauth_refresh_token()`` which reads from the DB.self._oauth_cache: Dict[str, Dict[str, Any]] = {}+ @property+ def distributed_credentials(self) -> bool:+ return bool(getattr(self.settings, "distributed_mode", False))++ def _sources(self):+ from services.credentials.sources import CredentialSources+ return CredentialSources(self.database)++ def require_local_credentials(self) -> None:+ if self.distributed_credentials:+ from services.credentials.onepassword import CredentialSourceError+ raise CredentialSourceError("unsupported_source", "Distributed execution requires an approved 1Password binding. Local, inline, ambient and OAuth credentials are unsupported.")++ async def get_credential_source(self, provider: str, session_id: str = "default", *, principal: Optional[str] = None) -> Optional[Dict[str, Any]]:+ """Saved metadata only. This method never reads 1Password values."""+ from services.credentials.onepassword import CredentialSourceError+ row = await self._sources().get(provider, session_id)+ if row is None:+ return None+ if principal is not None and row.owner_id != principal:+ raise CredentialSourceError("access_denied", "Credential binding access denied.")+ return {"source": "onepassword", "reference": row.reference, "models": list(row.models), "model_params": dict(row.model_params), "base_url": row.base_url}++ async def store_credential_source(self, provider: str, reference: str, *, principal: str, session_id: str = "default", models: Optional[List[str]] = None, model_params: Optional[Dict] = None, base_url: Optional[str] = None) -> bool:+ await self._sources().save(provider, reference, owner_id=principal, session_id=session_id, models=models, model_params=model_params, base_url=base_url)+ self._api_key_cache.pop(f"{session_id}_{provider}", None)+ self._bump_catalogue_version()+ return True++ async def credential_source_version(self, principal: str = "owner") -> str:+ """Cross-replica catalogue invalidation without resolving a credential."""+ import json+ rows = await self._sources().list()+ metadata = sorted((row.id, row.updated_at.isoformat()) for row in rows if row.owner_id == principal)+ return hashlib.sha256(json.dumps([principal, metadata], separators=(",", ":")).encode()).hexdigest()[:20]++ async def resolve_api_key(self, provider: str, session_id: str = "default", *, principal: Optional[str] = None) -> Optional[str]:+ """Runtime-only resolution. No application cache or source fallback."""+ from services.credentials.onepassword import CredentialSourceError, read_secret+ # Legacy trusted callers operate as the single-user owner. Omitting a+ # principal must never grant access to another user's source binding.+ principal = principal or "owner"+ source = await self.get_credential_source(provider, session_id, principal=principal)+ if source is not None:+ value = await read_secret(source["reference"], self.settings)+ current = await self.get_credential_source(provider, session_id, principal=principal)+ if current != source:+ raise CredentialSourceError("binding_changed", "The API credential binding changed during authorization. Retry using its current configuration.")+ return value+ # Endpoint URLs are public central metadata, never local secret rows.+ if provider.endswith("_proxy"):+ endpoint = await self.get_credential_source(provider[:-6], session_id, principal=principal)+ if endpoint is not None:+ if provider.startswith("openai_compatible:") and not endpoint.get("base_url"):+ from services.credentials.onepassword import CredentialSourceError+ raise CredentialSourceError("missing_endpoint", "The named endpoint has no approved base URL. Enroll it with a static 1Password credential.")+ return endpoint.get("base_url")+ self.require_local_credentials()+ return await self.get_api_key(provider, session_id)++ async def get_browser_credential_binding(self, binding_id: str, principal: str, *, profile_id: Optional[str] = None, workflow_id: Optional[str] = None, employee_id: Optional[str] = None) -> Dict:+ from services.credentials.sources import binding_metadata+ row = await self._sources().browser_binding(binding_id, principal, profile_id=profile_id, workflow_id=workflow_id, employee_id=employee_id)+ return binding_metadata(row)++ async def resolve_browser_credentials(self, binding_id: str, principal: str, *, profile_id: Optional[str] = None, workflow_id: Optional[str] = None, employee_id: Optional[str] = None) -> Dict:+ """Private browser-owner caller only, after its observation gate closes."""+ from services.credentials.onepassword import read_secret+ from services.credentials.sources import binding_metadata+ row = await self._sources().browser_binding(binding_id, principal, profile_id=profile_id, workflow_id=workflow_id, employee_id=employee_id)+ username = await read_secret(row.username_reference, self.settings)+ password = await read_secret(row.password_reference, self.settings)+ # Recheck enrollment after desktop authorization waits/edits/revocation.+ current = await self._sources().browser_binding(binding_id, principal, profile_id=profile_id, workflow_id=workflow_id, employee_id=employee_id)+ if current.model_dump() != row.model_dump():+ from services.credentials.onepassword import CredentialSourceError+ raise CredentialSourceError("binding_changed", "The login binding changed during authorization. Observe the page and retry.")+ return {**binding_metadata(row), "username": username, "password": password}+def hash_api_key(self, api_key: str) -> str:"""Create hash for API key identification."""return hashlib.sha256(api_key.encode()).hexdigest()[:16]@@ -126,6 +205,10 @@ class AuthService:Returns:True if stored successfully, False otherwise"""+ self.require_local_credentials()+ if await self.get_credential_source(provider, session_id):+ from services.credentials.onepassword import CredentialSourceError+ raise CredentialSourceError("binding_exists", "Remove the 1Password binding before replacing it with a local key.")try:cache_key = f"{session_id}_{provider}"@@ -161,7 +244,7 @@ class AuthService:logger.error("Failed to store API key", provider=provider, error=str(e))return False- async def get_model_params(self, provider: str, session_id: str = "default") -> Dict[str, Dict[str, Any]]:+ async def get_model_params(self, provider: str, session_id: str = "default", *, principal: Optional[str] = None) -> Dict[str, Dict[str, Any]]:"""Return per-model params (context_length etc.) for the provider.Reads straight from the credentials DB — there's no in-memory@@ -171,6 +254,11 @@ class AuthService:``model_registry.json``) and for any local provider that hasn'tbeen validated yet."""+ row = await self._sources().get(provider, session_id)+ if row is not None:+ return dict(row.model_params) if row.owner_id == (principal or "owner") else {}+ if self.distributed_credentials:+ return {}try:return await self.credentials_db.get_api_key_model_params(provider, session_id)except Exception as e:@@ -189,6 +277,10 @@ class AuthService:Returns:Decrypted API key or None if not found/expired"""+ if await self.get_credential_source(provider, session_id) is not None:+ return None+ if self.distributed_credentials:+ return Nonetry:cache_key = f"{session_id}_{provider}"@@ -215,7 +307,7 @@ class AuthService:logger.error("Failed to get API key", provider=provider, error=str(e))return None- async def list_key_scopes(self, provider: str) -> List[str]:+ async def list_key_scopes(self, provider: str, *, principal: Optional[str] = None) -> List[str]:"""List every session_id holding a key for one provider.Reads the database directly rather than the cache: the cache is@@ -229,12 +321,14 @@ class AuthService:Sorted list of session identifiers, empty on failure"""try:- return await self.credentials_db.list_key_scopes(provider)+ shared = {row.session_id for row in await self._sources().list(provider=provider) if row.owner_id == (principal or "owner")}+ local = set() if self.distributed_credentials else set(await self.credentials_db.list_key_scopes(provider))+ return sorted(shared | local)except Exception as e:logger.error("Failed to list key scopes", provider=provider, error=str(e))return []- async def list_api_key_providers(self, session_id: str = "default") -> List[str]:+ async def list_api_key_providers(self, session_id: str = "default", *, principal: Optional[str] = None) -> List[str]:"""List every provider name holding a key in one session.The other axis of :meth:`list_key_scopes`. Reads the database, not@@ -248,12 +342,14 @@ class AuthService:Provider names, empty on failure"""try:- return await self.credentials_db.list_api_keys(session_id)+ shared = {row.provider for row in await self._sources().list(session_id=session_id) if row.owner_id == (principal or "owner")}+ local = set() if self.distributed_credentials else set(await self.credentials_db.list_api_keys(session_id))+ return sorted(shared | local)except Exception as e:logger.error("Failed to list API key providers", session_id=session_id, error=str(e))return []- async def get_stored_models(self, provider: str, session_id: str = "default") -> List[str]:+ async def get_stored_models(self, provider: str, session_id: str = "default", *, principal: Optional[str] = None) -> List[str]:"""Get stored models for provider.Args:@@ -263,6 +359,11 @@ class AuthService:Returns:List of model names or empty list"""+ row = await self._sources().get(provider, session_id)+ if row is not None:+ return list(row.models) if row.owner_id == (principal or "owner") else []+ if self.distributed_credentials:+ return []try:cache_key = f"{session_id}_{provider}"@@ -290,7 +391,7 @@ class AuthService:logger.error("Failed to get stored models", provider=provider, error=str(e))return []- async def remove_api_key(self, provider: str, session_id: str = "default") -> bool:+ async def remove_api_key(self, provider: str, session_id: str = "default", *, principal: Optional[str] = None) -> bool:"""Remove API key from storage and cache.Args:@@ -300,6 +401,18 @@ class AuthService:Returns:True if removed successfully"""+ if await self.get_credential_source(provider, session_id, principal=principal):+ # Explicit Disconnect must not uncover an older local credential+ # shadowed by the source. Delete it while the binding still shields+ # runtime reads; distributed mode never opens the local DB.+ if not self.distributed_credentials:+ await self.credentials_db.delete_api_key(provider, session_id)+ await self._sources().delete(provider, session_id, principal)+ self._api_key_cache.pop(f"{session_id}_{provider}", None)+ self._bump_catalogue_version()+ return True+ if self.distributed_credentials:+ return Truetry:cache_key = f"{session_id}_{provider}"@@ -319,7 +432,7 @@ class AuthService:logger.error("Failed to remove API key", provider=provider, error=str(e))return False- async def has_valid_key(self, provider: str, session_id: str = "default") -> bool:+ async def has_valid_key(self, provider: str, session_id: str = "default", *, principal: Optional[str] = None) -> bool:"""Check if valid API key exists.Args:@@ -329,6 +442,9 @@ class AuthService:Returns:True if a valid key exists"""+ row = await self._sources().get(provider, session_id)+ if row is not None:+ return row.owner_id == (principal or "owner")api_key = await self.get_api_key(provider, session_id)return api_key is not None@@ -368,6 +484,7 @@ class AuthService:Returns:True if stored successfully"""+ self.require_local_credentials()try:cache_key = f"{customer_id}_{provider}"@@ -423,6 +540,7 @@ class AuthService:Dict with ``access_token``, ``email``, ``name``, ``scopes`` or``None`` if no tokens are stored."""+ self.require_local_credentials()try:cache_key = f"{customer_id}_{provider}"@@ -470,6 +588,7 @@ class AuthService:The decrypted refresh token, or ``None`` if no tokens arestored for ``(provider, customer_id)``."""+ self.require_local_credentials()try:tokens = await self.credentials_db.get_oauth_tokens(provider, customer_id)if tokens:diff --git a/server/services/browser_agent_recipe.py b/server/services/browser_agent_recipe.pynew file mode 100644index 00000000..dfd79add--- /dev/null+++ b/server/services/browser_agent_recipe.py@@ -0,0 +1,55 @@+"""The shared Browser Agent graph recipe and its saved resource binding."""+from __future__ import annotations++from pathlib import Path+from typing import Any, Mapping++from services.graph_build import GraphAdditions, NewNode, skill_edge, tool_edge+from services.plugin import NodeUserError++BROWSER_AGENT_ROLE = (+ "Complete browser tasks using your connected Browser tool and browser skill. "+ "Observe the page before acting and use current element references. Respect saved browser policy and Ask first. "+ "Use approved credential binding IDs; never ask for passwords in chat or reveal credential values. "+ "Use request_user for human login, MFA, challenges, uncertain outcomes or actions the policy requires the owner to perform. "+ "Do not repeat an uncertain action. Verify its outcome first. Use screenshots with visionAnalyze when text observation is insufficient. "+ "Return the result, evidence and any limitation in the standard agent response."+)+++def browser_tool_id(graph: Mapping[str, Any], agent_id: str) -> str:+ nodes = {node["id"]: node for node in graph.get("nodes", []) if node.get("id")}+ tools = {edge.get("source") for edge in graph.get("edges", [])+ if edge.get("target") == agent_id and edge.get("targetHandle") == "input-tools"+ and nodes.get(edge.get("source"), {}).get("type") == "browser"}+ if len(tools) != 1:+ raise NodeUserError("Browser AI Agent needs exactly one connected, saved Browser tool.")+ return str(next(iter(tools)))+++def browser_agent_additions(*, agent_parameters: Mapping[str, Any] | None = None,+ position: tuple[float, float] = (0, 0), agent_ref: str = "agent",+ browser_node_id: str | None = None, create_agent: bool = True,+ create_context: bool = True, create_skills: bool = True) -> GraphAdditions:+ x, y = position+ nodes, edges = [], []+ if create_agent:+ parameters = {"system_message": BROWSER_AGENT_ROLE, **dict(agent_parameters or {})}+ nodes.append(NewNode(agent_ref, "browser_agent", "Browser AI Agent", parameters, position=(x, y)))+ if create_context:+ nodes.append(NewNode("context", "context", "Browser context", position=(x, y - 180), context_of=agent_ref))+ browser_ref = browser_node_id or "browser"+ if browser_node_id is None:+ nodes.append(NewNode(browser_ref, "browser", "Browser", {}, position=(x - 240, y + 180)))+ edges.append(tool_edge(browser_ref, agent_ref))+ if create_skills:+ instructions = (Path(__file__).resolve().parents[1] / "skills/web_agent/browser-skill/SKILL.md").read_text(encoding="utf-8")+ nodes.append(NewNode("skills", "masterSkill", "Browser instructions", {+ "skill_folder": "web_agent", "skills_config": {+ "browser-skill": {"enabled": True, "instructions": instructions, "isCustomized": False},+ "skill": {"enabled": True, "instructions": "", "required": True, "isCustomized": False},+ }}, position=(x - 240, y)))+ edges.append(skill_edge("skills", agent_ref))+ nodes.append(NewNode("vision", "visionAnalyze", "Browser vision", {}, position=(x + 240, y + 180)))+ edges.append(tool_edge("vision", agent_ref))+ return GraphAdditions(nodes=tuple(nodes), edges=tuple(edges))diff --git a/server/services/browser_owners.py b/server/services/browser_owners.pynew file mode 100644index 00000000..996b7931--- /dev/null+++ b/server/services/browser_owners.py@@ -0,0 +1,386 @@+"""Durable profile ownership. A missing owner is never replaced automatically.++The shared application database holds routing and fencing metadata only.+Browser sockets, daemon state and process IDs remain on the owning machine.+"""+from __future__ import annotations++import asyncio+import hashlib+import hmac+import json+import time+import uuid+from datetime import datetime, timezone+from typing import Any, Optional+from urllib.parse import urlsplit++from sqlalchemy import select, update+from sqlalchemy.exc import IntegrityError++from services.plugin.base import NodeUserError++RUNTIME_EPOCH = uuid.uuid4().hex+_HEARTBEATS: dict[int, asyncio.Task] = {}+_PROCESS_LOCK: Any = None+++from models.browser_owners import BrowserOwner, BrowserProfileOwner, BrowserTransientRoute as BrowserTransientRoute+++def settings() -> Any:+ from core.container import container+ return container.settings()+++def replica_id() -> str:+ cfg = settings()+ if getattr(cfg, "distributed_mode", False) is not True:+ return "local"+ value = str(getattr(cfg, "browser_replica_id", "") or "")+ if getattr(cfg, "distributed_mode", False) is True and not value:+ raise NodeUserError("Distributed browser execution requires BROWSER_REPLICA_ID.")+ return value or "local"+++def owner_queue(owner_id: str) -> str:+ return "browser-owner-" + hashlib.sha256(owner_id.encode()).hexdigest()[:24]+++def machine_id() -> str:+ import socket+ return str(getattr(settings(), "browser_machine_id", "") or socket.gethostname())+++def _persistent(database: Any) -> bool:+ from sqlalchemy.ext.asyncio import AsyncEngine+ return isinstance(getattr(database, "engine", None), AsyncEngine)+++def _binding(profile: BrowserProfileOwner, owner: BrowserOwner) -> dict:+ return {"profile_id": profile.profile_id, "principal_id": profile.principal_id,+ "owner_id": owner.owner_id, "runtime_epoch": owner.runtime_epoch,+ "task_queue": owner_queue(owner.owner_id), "base_url": owner.base_url,+ "profile_task_id": profile.task_id,+ "sensitive_login": profile.sensitive_login, "needs_observation": profile.needs_observation,+ "challenge_required": profile.challenge_required,+ "assistance": {"reason": profile.assistance_reason, "message": profile.assistance_message, "deadline": profile.assistance_deadline} if profile.assistance_reason else None,+ "available": owner.heartbeat_at > time.time() - 35}+++async def register_browser_owner(database: Any) -> None:+ """Register this runtime and keep its fencing lease alive.++ A second process using a live replica ID is rejected. A recovered process+ may advance its own epoch only after the previous heartbeat has expired.+ """+ if getattr(settings(), "distributed_mode", False) is not True:+ return+ global _PROCESS_LOCK+ identity = replica_id()+ base = str(getattr(settings(), "browser_replica_url", "") or "").rstrip("/")+ parsed = urlsplit(base)+ if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:+ raise NodeUserError("BROWSER_REPLICA_URL must be a trusted backend http(s) URL.")+ if _PROCESS_LOCK is None:+ from nodes.browser._chrome import ProfileLock+ from nodes.browser._profiles import profiles_root+ lock_dir = profiles_root().parent / "owners"+ lock_dir.mkdir(parents=True, exist_ok=True)+ lock = ProfileLock(lock_dir / (hashlib.sha256(identity.encode()).hexdigest() + ".lock"))+ if not lock.acquire():+ raise NodeUserError("The browser owner process is still running. Wait for its recovery; it cannot be replaced.")+ _PROCESS_LOCK = lock+ async with database.get_session() as session:+ row = await session.get(BrowserOwner, identity, with_for_update=True)+ now = time.time()+ if row is not None and row.machine_id != machine_id():+ raise NodeUserError("Browser owner recovery is waiting for its original machine. A different machine requires explicit operator fencing; automatic profile transfer is disabled.")+ if row is not None and row.runtime_epoch != RUNTIME_EPOCH and row.heartbeat_at > now - 35:+ raise NodeUserError("Another live browser runtime uses BROWSER_REPLICA_ID; choose a unique replica ID.")+ if row is None:+ row = BrowserOwner(owner_id=identity, runtime_epoch=RUNTIME_EPOCH, machine_id=machine_id(), base_url=base, heartbeat_at=now)+ elif row.runtime_epoch != RUNTIME_EPOCH:+ await session.execute(update(BrowserProfileOwner).where(BrowserProfileOwner.owner_id == identity).values(needs_observation=True))+ row.runtime_epoch, row.base_url, row.heartbeat_at = RUNTIME_EPOCH, base, now+ session.add(row)+ await session.commit()+ key = id(database)+ if key not in _HEARTBEATS or _HEARTBEATS[key].done():+ async def heartbeat() -> None:+ while True:+ await asyncio.sleep(10)+ async with database.get_session() as session:+ result = await session.execute(update(BrowserOwner).where(+ BrowserOwner.owner_id == identity, BrowserOwner.runtime_epoch == RUNTIME_EPOCH+ ).values(heartbeat_at=time.time()))+ await session.commit()+ if result.rowcount != 1:+ return+ _HEARTBEATS[key] = asyncio.create_task(heartbeat(), name="browser-owner-heartbeat")+++async def unregister_browser_owner() -> None:+ """Called only after every owned Chrome has stopped."""+ global _PROCESS_LOCK+ tasks = list(_HEARTBEATS.values())+ _HEARTBEATS.clear()+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ if _PROCESS_LOCK is not None:+ _PROCESS_LOCK.release()+ _PROCESS_LOCK = None+++async def bind_profile(database: Any, profile_id: str, principal: str) -> dict:+ if getattr(settings(), "distributed_mode", False) is not True:+ result = {"profile_id": profile_id, "principal_id": principal, "owner_id": "local", "runtime_epoch": RUNTIME_EPOCH,+ "task_queue": None, "base_url": "", "available": True, "sensitive_login": False, "needs_observation": False}+ if _persistent(database):+ async with database.get_session() as session:+ row = await session.get(BrowserProfileOwner, profile_id)+ if row is None:+ row = BrowserProfileOwner(profile_id=profile_id, principal_id=principal, owner_id="local", runtime_epoch=RUNTIME_EPOCH)+ session.add(row)+ try:+ await session.commit()+ except IntegrityError:+ await session.rollback()+ row = await session.get(BrowserProfileOwner, profile_id)+ if row is None:+ raise+ elif row.runtime_epoch != RUNTIME_EPOCH:+ row.runtime_epoch = RUNTIME_EPOCH+ row.needs_observation = True+ await session.commit()+ if row.principal_id != principal:+ raise NodeUserError("Browser profile access denied.")+ result.update(sensitive_login=row.sensitive_login, needs_observation=row.needs_observation,+ profile_task_id=row.task_id,+ challenge_required=row.challenge_required,+ assistance={"reason": row.assistance_reason, "message": row.assistance_message, "deadline": row.assistance_deadline} if row.assistance_reason else None)+ return result+ async with database.get_session() as session:+ row = await session.get(BrowserProfileOwner, profile_id)+ if row is not None:+ if row.principal_id != principal:+ raise NodeUserError("Browser profile access denied.")+ owner = await session.get(BrowserOwner, row.owner_id)+ if owner is None:+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ return _binding(row, owner)+ try:+ async with database.get_session() as session:+ # Preparing metadata may run in an orchestration worker. Only+ # backend lifecycle owns runtime registration and its process lock.+ # Retain an unavailable registered owner rather than transferring.+ configured_owner = replica_id()+ if await session.get(BrowserOwner, configured_owner) is None:+ raise NodeUserError("Browser owner is not registered. Start its backend before submitting browser tasks.")+ row = BrowserProfileOwner(profile_id=profile_id, principal_id=principal, owner_id=configured_owner)+ session.add(row)+ await session.commit()+ except IntegrityError:+ pass # The winner remains the permanent owner.+ return await bind_profile(database, profile_id, principal)+++async def routing_for_node(database: Any, workflow_id: str, node_id: str, principal: str) -> dict:+ from nodes.browser._handlers import resolve_browser_node+ from nodes.browser._profiles import ProfileStore+ from nodes.browser.browser import BrowserParams+ await resolve_browser_node(principal, workflow_id, node_id)+ cfg = BrowserParams.model_validate(await database.get_node_parameters(node_id) or {})+ store = ProfileStore(database)+ active = []+ if _persistent(database):+ async with database.get_session() as session:+ active = (await session.execute(select(BrowserProfileOwner).where(+ BrowserProfileOwner.principal_id == principal, BrowserProfileOwner.workflow_id == workflow_id,+ BrowserProfileOwner.browser_node_id == node_id, BrowserProfileOwner.task_id.is_not(None)+ ))).scalars().all()+ if len(active) > 1:+ raise NodeUserError("Browser routing is ambiguous. Wait for active tasks to finish before opening this browser.")+ selected_profile = active[0].profile_id if active else cfg.profile_id+ if selected_profile:+ profile = await store.get(principal, selected_profile)+ else:+ workflow = await database.get_workflow(workflow_id)+ name = getattr(workflow, "name", None) or "Browser"+ profile = await store.default_for_workflow(principal, workflow_id, str(name))+ return {**await bind_profile(database, profile.id, principal), "workflow_id": workflow_id, "node_id": node_id,+ "browser_policy": {"allowed_domains": cfg.allowed_domains, "allow_private_network": cfg.allow_private_network}}+++async def assert_owner(database: Any, binding: dict, principal: str, task_id: Optional[str] = None) -> dict:+ current = await bind_profile(database, str(binding["profile_id"]), principal)+ if current["owner_id"] != replica_id():+ raise NodeUserError("Browser unavailable — waiting for its owner.")+ if _persistent(database):+ async with database.get_session() as session:+ if getattr(settings(), "distributed_mode", False) is True:+ owner = await session.get(BrowserOwner, current["owner_id"])+ if owner is None or owner.runtime_epoch != RUNTIME_EPOCH:+ raise NodeUserError("This browser runtime has been fenced.")+ row = await session.get(BrowserProfileOwner, current["profile_id"])+ if row.task_id is not None and row.task_id != task_id:+ raise NodeUserError("BrowserBusy: this profile is assigned to another task.")+ return current+++async def assert_runtime_epoch(database: Any) -> None:+ if getattr(settings(), "distributed_mode", False) is not True:+ return+ async with database.get_session() as session:+ owner = await session.get(BrowserOwner, replica_id())+ if owner is None or owner.runtime_epoch != RUNTIME_EPOCH:+ raise NodeUserError("This browser runtime has been fenced.")+++async def claim_browser_task(database: Any, binding: dict, principal: str, task_id: str) -> dict:+ current = {**binding, **await assert_owner(database, binding, principal, task_id)}+ if _persistent(database):+ async with database.get_session() as session:+ result = await session.execute(update(BrowserProfileOwner).where(+ BrowserProfileOwner.profile_id == binding["profile_id"],+ (BrowserProfileOwner.task_id.is_(None)) | (BrowserProfileOwner.task_id == task_id)+ ).values(task_id=task_id, workflow_id=binding.get("workflow_id"), browser_node_id=binding.get("node_id"),+ updated_at=datetime.now(timezone.utc)))+ await session.commit()+ if result.rowcount != 1:+ raise NodeUserError("BrowserBusy: this profile is assigned to another task.")+ from nodes.browser._profiles import ProfileStore+ from nodes.browser._runtime import get_browser_runtime+ runtime = get_browser_runtime()+ controller = None+ try:+ profile = await ProfileStore(database).get(principal, binding["profile_id"])+ controller = runtime.controller_for(profile)+ if controller.task_id is None and controller._op_lock.locked():+ raise NodeUserError("BrowserBusy: this profile is executing another browser step.")+ frozen_policy = current.get("browser_policy")+ session = None+ if isinstance(frozen_policy, dict) and binding.get("workflow_id") and binding.get("node_id"):+ from nodes.browser._session import BrowserSession, SessionKey+ from nodes.browser._netpolicy import parse_allowed_domains+ policy = runtime.base_policy(allow_private_network=bool(frozen_policy.get("allow_private_network")),+ allowed_domains=parse_allowed_domains(frozen_policy.get("allowed_domains", "")))+ session = BrowserSession(SessionKey(principal, binding["workflow_id"], binding["node_id"]), profile.id,+ label="Browser AI Agent", policy=policy)+ if not controller._lease_free_for(session):+ raise NodeUserError("BrowserBusy: this profile is in use by another browser session.")+ if controller.lease_session is not None and controller.lease_session.session_id != session.session_id:+ await controller.release_lease(controller.lease_session.session_id)+ controller.claim_task(task_id)+ current["profile_task_id"] = task_id+ controller.sensitive_login = bool(current.get("sensitive_login"))+ controller.needs_observation |= bool(current.get("needs_observation"))+ controller.challenge_required = bool(current.get("challenge_required"))+ controller._challenge_message = str((current.get("assistance") or {}).get("message") or "Please finish the browser challenge and hand control back.")+ controller.recovered_assistance = current.get("assistance")+ if session is not None:+ session = runtime.register_session(session)+ await controller.acquire_lease(session)+ except BaseException:+ if controller is not None and controller.task_id == task_id:+ await controller.release_task(task_id)+ if _persistent(database):+ async with database.get_session() as session:+ await session.execute(update(BrowserProfileOwner).where(BrowserProfileOwner.profile_id == binding["profile_id"],+ BrowserProfileOwner.task_id == task_id, BrowserProfileOwner.owner_id == replica_id()).values(task_id=None, workflow_id=None, browser_node_id=None))+ await session.commit()+ raise+ return {"claimed": True, "runtime_epoch": RUNTIME_EPOCH, "binding": current}+++async def persist_control(database: Any, profile_id: str, task_id: Optional[str], *, challenge: bool, needs_observation: bool, assistance: Optional[dict]) -> None:+ if not _persistent(database):+ return+ async with database.get_session() as session:+ await session.execute(update(BrowserProfileOwner).where(+ BrowserProfileOwner.profile_id == profile_id, BrowserProfileOwner.owner_id == replica_id(),+ BrowserProfileOwner.task_id == task_id+ ).values(challenge_required=challenge, needs_observation=needs_observation,+ assistance_reason=(assistance or {}).get("reason"), assistance_message=(assistance or {}).get("message"),+ assistance_deadline=(assistance or {}).get("deadline"), updated_at=datetime.now(timezone.utc)))+ await session.commit()+++async def release_browser_task(database: Any, binding: dict, task_id: str) -> dict:+ await assert_runtime_epoch(database)+ from nodes.browser._runtime import get_browser_runtime+ controller = get_browser_runtime().controller(binding["profile_id"])+ if controller is not None:+ await controller.release_task(task_id)+ if _persistent(database):+ async with database.get_session() as session:+ result = await session.execute(update(BrowserProfileOwner).where(+ BrowserProfileOwner.profile_id == binding["profile_id"], BrowserProfileOwner.task_id == task_id,+ BrowserProfileOwner.owner_id == replica_id()+ ).values(task_id=None, workflow_id=None, browser_node_id=None, updated_at=datetime.now(timezone.utc)))+ await session.commit()+ return {"released": result.rowcount == 1}+ return {"released": True}+++async def cleanup_browser_task(database: Any, binding: dict, task_id: str) -> dict:+ if getattr(settings(), "distributed_mode", False) is True and binding["owner_id"] != replica_id():+ from nodes.browser._routing import forward_command+ return await forward_command(binding, str(binding["principal_id"]), "cleanup_task", {"profile_id": binding["profile_id"], "task_id": task_id})+ await assert_runtime_epoch(database)+ from nodes.browser._runtime import get_browser_runtime+ runtime = get_browser_runtime()+ controller = runtime.controller(binding["profile_id"])+ if controller is not None and controller.task_id not in {None, task_id}:+ return {"released": False}+ running = runtime.running(binding["profile_id"]) if hasattr(runtime, "running") else None+ if running is not None and controller is not None and controller.task_id == task_id:+ # Wait for an admitted step to settle before releasing its lifetime claim.+ # Suspension confirms the daemon cannot finish an old command later.+ async with controller._op_lock:+ if not await running.cli.suspend_for_credentials():+ await runtime.stop_profile(binding["profile_id"], reason="task cleanup")+ if running.chrome.is_running():+ raise NodeUserError("Browser cleanup is waiting for the owner to stop its runtime.")+ return await release_browser_task(database, binding, task_id)+++async def set_sensitive(database: Any, profile_id: str, task_id: Optional[str], enabled: bool) -> None:+ await assert_runtime_epoch(database)+ if not _persistent(database):+ return+ async with database.get_session() as session:+ result = await session.execute(update(BrowserProfileOwner).where(+ BrowserProfileOwner.profile_id == profile_id, BrowserProfileOwner.owner_id == replica_id(),+ BrowserProfileOwner.task_id == task_id+ ).values(sensitive_login=enabled, updated_at=datetime.now(timezone.utc)))+ await session.commit()+ if result.rowcount != 1:+ raise NodeUserError("The browser task no longer owns this profile.")+++def sign_forward(principal: str, method: str, path: str, body: bytes) -> str:+ payload = json.dumps({"principal": principal, "method": method, "path": path,+ "body": hashlib.sha256(body).hexdigest(), "expires": int(time.time()) + 30}, separators=(",", ":"))+ import base64+ encoded = base64.urlsafe_b64encode(payload.encode()).decode()+ secret = str(getattr(settings(), "browser_router_secret", "") or settings().secret_key)+ signature = hmac.new(secret.encode(), encoded.encode(), hashlib.sha256).hexdigest()+ return encoded + "." + signature+++def verify_forward(token: str, method: str, path: str, body: bytes) -> str:+ import base64+ try:+ encoded, signature = token.split(".", 1)+ secret = str(getattr(settings(), "browser_router_secret", "") or settings().secret_key)+ expected = hmac.new(secret.encode(), encoded.encode(), hashlib.sha256).hexdigest()+ if not hmac.compare_digest(signature, expected):+ raise ValueError()+ payload = json.loads(base64.urlsafe_b64decode(encoded))+ if payload["expires"] < time.time() or payload["expires"] > time.time() + 35 or payload["method"] != method or payload["path"] != path or payload["body"] != hashlib.sha256(body).hexdigest():+ raise ValueError()+ return str(payload["principal"])+ except (ValueError, KeyError, TypeError):+ raise NodeUserError("Invalid browser owner authorization.") from Nonediff --git a/server/services/browser_tasks.py b/server/services/browser_tasks.pynew file mode 100644index 00000000..6fbd4c24--- /dev/null+++ b/server/services/browser_tasks.py@@ -0,0 +1,33 @@+"""Saved-graph Browser Agent discovery; no client executable graphs."""+++def browser_tool_for_agent(graph: dict, agent_node_id: str) -> dict:+ from services.plugin import NodeUserError+ nodes = {node["id"]: node for node in graph.get("nodes", []) if node.get("id")}+ agent = nodes.get(agent_node_id)+ if not agent or agent.get("type") != "browser_agent":+ raise NodeUserError("Select a Browser AI Agent")+ from services.browser_agent_recipe import browser_tool_id+ tool = nodes[browser_tool_id(graph, agent_node_id)]+ if (tool.get("data") or {}).get("disabled"):+ raise NodeUserError("Connect one enabled Browser tool before submitting a task")+ return tool+++async def discovery(database, principal: str, workflow_id: str, browser_node_id: str) -> dict:+ from services.authz.workflow_node import resolve_workflow_node+ await resolve_workflow_node(principal, workflow_id, browser_node_id, workspace_kind="browser")+ from services.workspace_task_history import authorize_workflow+ graph = await authorize_workflow(database, principal, workflow_id)+ agents = []+ for node in graph.get("nodes", []):+ if node.get("type") != "browser_agent" or (node.get("data") or {}).get("disabled"):+ continue+ from services.plugin import NodeUserError+ try:+ tool = browser_tool_for_agent(graph, node["id"])+ except NodeUserError:+ continue+ if tool["id"] == browser_node_id:+ agents.append({"node_id": node["id"], "label": (node.get("data") or {}).get("label") or "Browser AI Agent"})+ return {"browser_node_id": browser_node_id, "agents": agents}diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.pyindex a8379e0f..9cf3b169 100644--- a/server/services/cli_agent/service.py+++ b/server/services/cli_agent/service.py@@ -48,6 +48,7 @@ from services.cli_agent.mcp_server import (from services.cli_agent.protocol import BatchResult, SessionResultfrom services.cli_agent.session import AICliSessionfrom services.cli_agent.types import BaseAICliTaskSpec, ClaudeTaskSpec+from services.process_environment import without_onepassword_environmentlogger = get_logger(__name__)@@ -677,7 +678,7 @@ class AICliService:session_key,spec=task,cwd=cwd,- env=env,+ env=without_onepassword_environment(env),defaults=defaults,mcp_endpoint_url=mcp_endpoint_url,mcp_bearer_token=mcp_bearer_token,@@ -882,6 +883,7 @@ class AICliService:result = await anyio.run_process(["git", "-C", str(start), "rev-parse", "--show-toplevel"],check=False,+ env=without_onepassword_environment(),)except FileNotFoundError:# `git` not on PATH at all — fail-fast, nothing to fall back to.diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.pyindex fe6d49ad..0a5e2ef2 100644--- a/server/services/cli_agent/session.py+++ b/server/services/cli_agent/session.py@@ -60,6 +60,7 @@ from services.cli_agent.lockfile import remove_ide_lockfile, write_ide_lockfilefrom services.cli_agent.protocol import AICliProvider, CanonicalUsage, SessionResultfrom services.cli_agent.transports import PtyHandle, get_pty_transportfrom services.cli_agent.types import BaseAICliTaskSpec+from services.process_environment import without_onepassword_environmentlogger = get_logger(__name__)@@ -234,7 +235,7 @@ class AICliSession(BaseProcessSupervisor):parent_run_id = f"{self._workflow_id}:{self._node_id}:{self._batch_token[:8]}"e["OPENCOMPANY_PARENT_RUN_ID"] = parent_run_ide["MACHINA_PARENT_RUN_ID"] = parent_run_id # legacy child-process contract- return e+ return without_onepassword_environment(e)async def _pre_spawn(self) -> None:"""Create the per-task git worktree (non-memory-bound runs only)@@ -359,7 +360,7 @@ class AICliSession(BaseProcessSupervisor):self._pty_handle = await transport.spawn(argv,cwd=self.cwd() or self._repo_root,- env=self.env(),+ env=without_onepassword_environment(self.env()),)except FileNotFoundError:raisediff --git a/server/services/cli_agent/transports/posix.py b/server/services/cli_agent/transports/posix.pyindex 8b89c717..917fc192 100644--- a/server/services/cli_agent/transports/posix.py+++ b/server/services/cli_agent/transports/posix.py@@ -24,6 +24,7 @@ from pathlib import Pathfrom typing import Dict, List, Optionalfrom core.logging import get_logger+from services.process_environment import without_onepassword_environmentfrom .base import PtyHandle, PtyTransport@@ -180,7 +181,7 @@ class PosixPtyTransport(PtyTransport):lambda: PtyProcess.spawn( # type: ignore[attr-defined]argv,cwd=str(cwd),- env=env,+ env=without_onepassword_environment(env),# 80x24 default matches what Ink/most TUI libraries# expect on a non-terminal-attached spawn. We don't# render anywhere, so the dimensions are cosmetic.diff --git a/server/services/cli_agent/transports/windows.py b/server/services/cli_agent/transports/windows.pyindex f1c669ec..52c29824 100644--- a/server/services/cli_agent/transports/windows.py+++ b/server/services/cli_agent/transports/windows.py@@ -23,6 +23,7 @@ from pathlib import Pathfrom typing import Dict, List, Optionalfrom core.logging import get_logger+from services.process_environment import without_onepassword_environmentfrom .base import PtyHandle, PtyTransport@@ -176,7 +177,7 @@ class WindowsPtyTransport(PtyTransport):lambda: PtyProcess.spawn( # type: ignore[attr-defined]argv,cwd=str(cwd),- env=env,+ env=without_onepassword_environment(env),dimensions=(24, 80),),)diff --git a/server/services/cli_agent/worktree.py b/server/services/cli_agent/worktree.pyindex 4fcfaec4..0a21bcb9 100644--- a/server/services/cli_agent/worktree.py+++ b/server/services/cli_agent/worktree.py@@ -13,6 +13,7 @@ from __future__ import annotationsfrom pathlib import Pathimport anyio+from services.process_environment import without_onepassword_environmentasync def add_worktree(repo_root: Path, worktree_dir: Path, branch: str) -> Path:@@ -25,6 +26,7 @@ async def add_worktree(repo_root: Path, worktree_dir: Path, branch: str) -> Pathproc = await anyio.run_process(["git", "-C", str(repo_root), "worktree", "add", str(worktree_dir), "-b", branch],check=False,+ env=without_onepassword_environment(),)if proc.returncode != 0:err = (proc.stderr or b"").decode("utf-8", errors="replace").strip()@@ -37,4 +39,5 @@ async def remove_worktree(repo_root: Path, worktree_dir: Path) -> None:await anyio.run_process(["git", "-C", str(repo_root), "worktree", "remove", "--force", str(worktree_dir)],check=False,+ env=without_onepassword_environment(),)diff --git a/server/services/credential_registry.py b/server/services/credential_registry.pyindex 8f63b13d..85dc0231 100644--- a/server/services/credential_registry.py+++ b/server/services/credential_registry.py@@ -327,7 +327,7 @@ def _status_fingerprint(providers: List[Dict[str, Any]]) -> str:return ",".join(sorted(parts))-async def _connected_check(check: Dict[str, Any], auth_service: Any) -> bool:+async def _connected_check(check: Dict[str, Any], auth_service: Any, *, principal: Optional[str] = None) -> bool:"""Evaluate a provider's declarative ``connected_check``.``{"type": "status", "key": K, "field": F}``: the live status slot the@@ -347,14 +347,14 @@ async def _connected_check(check: Dict[str, Any], auth_service: Any) -> bool:if not keys:return Falsefor key in keys:- if not await auth_service.has_valid_key(str(key)):+ if not await auth_service.has_valid_key(str(key), **({"principal": principal} if principal is not None else {})):return Falsereturn Truelogger.warning("Unknown connected_check type in credential_providers.json", check_type=kind)return False-async def provider_connection_state(provider: Dict[str, Any], auth_service: Any) -> Dict[str, Any]:+async def provider_connection_state(provider: Dict[str, Any], auth_service: Any, *, principal: Optional[str] = None) -> Dict[str, Any]:"""Live credential state for one resolved catalogue provider.Returns ``{"stored", "connected", "account_label"}`` plus whatever the@@ -369,7 +369,7 @@ async def provider_connection_state(provider: Dict[str, Any], auth_service: Any)Shared by the ``get_credential_catalogue`` handler and the Normal-modeemployee summaries, so both answer "is this app connected" the same way."""- from services.plugin.credential import CREDENTIAL_REGISTRY+ from services.plugin.credential import CREDENTIAL_REGISTRY, ApiKeyCredential, Credentialpid = provider.get("id", "")kind = provider.get("kind", "")@@ -377,12 +377,19 @@ async def provider_connection_state(provider: Dict[str, Any], auth_service: Any)check = provider.get("connected_check")state: Dict[str, Any] = {}+ cred_cls = CREDENTIAL_REGISTRY.get(pid)+ supported = bool(cred_cls and issubclass(cred_cls, ApiKeyCredential) and not getattr(cred_cls, "extra_fields", ()) and (cred_cls.validate.__func__ is Credential.validate.__func__ or pid == "openai_compatible"))+ state["sourceSupported"] = supported+ state["sourceRequired"] = bool(getattr(auth_service, "distributed_credentials", False))+ if state["sourceRequired"] and not supported and not (check and check.get("type") == "builtin"):+ return {**state, "stored": False, "connected": False, "account_label": None, "unsupported_reason": "This connection requires local execution; distributed credentials support approved static API keys and browser logins."}tokens = Nonechecked: Dict[str, bool] = {}+ scope = {"principal": principal} if principal is not None else {}async def check_passes() -> bool:if "result" not in checked:- checked["result"] = await _connected_check(check, auth_service)+ checked["result"] = await _connected_check(check, auth_service, principal=principal)return checked["result"]# Declarative per-provider override for the "stored" check. Lets Telegram@@ -393,7 +400,7 @@ async def provider_connection_state(provider: Dict[str, Any], auth_service: Any)# OAuth flow completes.stored_check = provider.get("stored_check")if stored_check and stored_check.get("type") == "api_key":- state["stored"] = await auth_service.has_valid_key(stored_check.get("key", pid))+ state["stored"] = await auth_service.has_valid_key(stored_check.get("key", pid), **scope)elif status_hook:# Providers that declare ``status_hook`` in credential_providers.json# (the messaging, Google / Microsoft and CLI-login entries among@@ -401,7 +408,7 @@ async def provider_connection_state(provider: Dict[str, Any], auth_service: Any)tokens = await auth_service.get_oauth_tokens(status_hook)state["stored"] = tokens is not Noneelif kind == "apiKey":- state["stored"] = await auth_service.has_valid_key(pid)+ state["stored"] = await auth_service.has_valid_key(pid, **scope)elif kind == "oauth":tokens = await auth_service.get_oauth_tokens(pid)state["stored"] = tokens is not None@@ -417,7 +424,7 @@ async def provider_connection_state(provider: Dict[str, Any], auth_service: Any)cred_cls = CREDENTIAL_REGISTRY.get(pid)if cred_cls is not None:- extras = await cred_cls.catalogue_extras()+ extras = await cred_cls.catalogue_extras(**scope)if extras:state.update(extras)diff --git a/server/services/credentials/__init__.py b/server/services/credentials/__init__.pyindex 79ca5658..3ac87056 100644--- a/server/services/credentials/__init__.py+++ b/server/services/credentials/__init__.py@@ -15,4 +15,7 @@ from .handlers import WS_HANDLERS as _CREDENTIALS_WS_HANDLERS_register_ws_handlers(_CREDENTIALS_WS_HANDLERS)+from .enrollment import WS_HANDLERS as _SOURCE_WS_HANDLERS+_register_ws_handlers(_SOURCE_WS_HANDLERS)+__all__ = ["handlers"]diff --git a/server/services/credentials/enrollment.py b/server/services/credentials/enrollment.pynew file mode 100644index 00000000..24a6ee51--- /dev/null+++ b/server/services/credentials/enrollment.py@@ -0,0 +1,127 @@+"""Authenticated 1Password enrollment, metadata and installation commands."""++from __future__ import annotations++from typing import Any++from core.container import container+from services.authz.ws_surface import execution_principal+from services.ws_handler_registry import current_load_options_principal, register_option_loader, ws_handler++from .onepassword import CredentialSourceError, doctor, read_secret, validate_reference+from .sources import CredentialSources, public_base_url+++def _principal(websocket) -> str:+ if (getattr(websocket, "scope", {}) or {}).get("path") == "/ws/internal":+ raise CredentialSourceError("access_denied", "Credential enrollment requires an authenticated client.")+ return execution_principal({}, websocket)+++@ws_handler()+async def handle_onepassword_status(data: dict, websocket) -> dict:+ _principal(websocket)+ auth = container.auth_service()+ try:+ result = await doctor(auth.settings)+ except CredentialSourceError as exc:+ result = {"available": False, "error": str(exc), "code": exc.code}+ return {**result, "sourceRequired": auth.distributed_credentials}+++@ws_handler()+async def handle_onepassword_install(data: dict, websocket) -> dict:+ _principal(websocket)+ from .provision import ensure_cli+ await ensure_cli()+ return await handle_onepassword_status({}, websocket)+++@ws_handler("provider", "reference", "base_url")+async def handle_onepassword_endpoint_validate(data: dict, websocket) -> dict:+ """The supported static-key adapter for named OpenAI-compatible endpoints."""+ import re+ from services.llm.endpoints import SERVER_META_KEY, resolve_base_url+ from services.status_broadcaster import get_status_broadcaster+ principal = _principal(websocket)+ provider = str(data["provider"]).lower()+ if not re.fullmatch(r"openai_compatible:[a-z0-9][a-z0-9_-]{0,63}", provider):+ raise CredentialSourceError("unsupported_provider", "Use a named OpenAI-compatible endpoint reference.")+ reference = validate_reference(data["reference"])+ url = public_base_url(data["base_url"])+ auth = container.auth_service()+ await auth.get_credential_source(provider, principal=principal)+ key = await read_secret(reference, auth.settings)+ try:+ outcome = await resolve_base_url(url, api_key=key)+ except Exception:+ raise CredentialSourceError("probe_failed", "The endpoint probe failed. Check the endpoint and API credential.") from None+ if not outcome.ok:+ return {"success": False, "valid": False, "error": "The endpoint did not return an authorized OpenAI model list."}+ models = [str(model.id) for model in outcome.models if getattr(model, "id", None)]+ if any(key in model for model in models):+ raise CredentialSourceError("unsafe_metadata", "The endpoint returned unsafe model metadata.")+ label = str(data.get("label") or provider.split(":", 1)[1])[:128]+ params = {SERVER_META_KEY: {"label": label, "base_url": outcome.base_url, "kind": "generic"}}+ await auth.store_credential_source(provider, reference, principal=principal, models=models, model_params=params, base_url=outcome.base_url)+ await get_status_broadcaster().update_api_key_status(provider, valid=True, has_key=True, message="1Password binding validated", models=models)+ return {"valid": True, "provider": provider, "models": models, "message": "1Password binding validated"}+++@ws_handler()+async def handle_browser_credential_bindings_list(data: dict, websocket) -> dict:+ return {"bindings": await CredentialSources(container.auth_service().database).list_browser(_principal(websocket))}+++async def _validate_resource_scopes(principal: str, data: dict, database) -> None:+ if data.get("profile_id"):+ from nodes.browser._profiles import ProfileStore+ await ProfileStore(database).get(principal, str(data["profile_id"]))+ if data.get("workflow_id"):+ saved = await database.get_workflow(str(data["workflow_id"]))+ graph = saved.data if saved is not None and hasattr(saved, "data") else (saved or {}).get("data", {})+ if not saved or str(graph.get("owner_id") or "owner") != principal:+ raise CredentialSourceError("access_denied", "Workflow credential scope access denied.")+ if data.get("employee_id"):+ from models.employees import Employee+ async with database.get_session() as session:+ employee = await session.get(Employee, str(data["employee_id"]))+ owner = getattr(employee, "owner_id", None) if employee else None+ if str(owner or "") != principal:+ raise CredentialSourceError("access_denied", "Employee credential scope access denied.")+++@ws_handler("label", "origin", "username_reference", "password_reference", "success_path")+async def handle_browser_credential_binding_save(data: dict, websocket) -> dict:+ principal = _principal(websocket)+ auth = container.auth_service()+ await _validate_resource_scopes(principal, data, auth.database)+ # Saving a website binding never reads passwords or creates an auth grant.+ binding = await CredentialSources(auth.database).save_browser(principal, data)+ auth._bump_catalogue_version()+ return {"binding": binding}+++@ws_handler("binding_id")+async def handle_browser_credential_binding_delete(data: dict, websocket) -> dict:+ await CredentialSources(container.auth_service().database).delete_browser(_principal(websocket), str(data["binding_id"]))+ return {}+++async def browser_credential_bindings(params: dict[str, Any]) -> list[dict]:+ principal = current_load_options_principal()+ if not principal:+ return []+ bindings = await CredentialSources(container.auth_service().database).list_browser(principal)+ return [{"value": row["id"], "label": f'{row["label"]} ({row["origin"]})'} for row in bindings]+++register_option_loader("browserCredentialBindings", browser_credential_bindings)+WS_HANDLERS = {+ "onepassword_status": handle_onepassword_status,+ "onepassword_install": handle_onepassword_install,+ "onepassword_endpoint_validate": handle_onepassword_endpoint_validate,+ "browser_credential_bindings_list": handle_browser_credential_bindings_list,+ "browser_credential_binding_save": handle_browser_credential_binding_save,+ "browser_credential_binding_delete": handle_browser_credential_binding_delete,+}diff --git a/server/services/credentials/handlers.py b/server/services/credentials/handlers.pyindex 40b4091a..2274eb1b 100644--- a/server/services/credentials/handlers.py+++ b/server/services/credentials/handlers.py@@ -35,7 +35,7 @@ from services.ws_handler_registry import ws_handlerlogger = get_logger(__name__)-@ws_handler("provider", "api_key")+@ws_handler("provider")async def handle_validate_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:"""Validate and store an API key.@@ -50,7 +50,10 @@ async def handle_validate_api_key(data: Dict[str, Any], websocket: WebSocket) ->from services.plugin.credential import CREDENTIAL_REGISTRYprovider = data["provider"].lower()- normalized = dict(data, provider=provider)+ from services.authz.ws_surface import execution_principal+ if (getattr(websocket, "scope", {}) or {}).get("path") == "/ws/internal":+ return {"success": False, "error": "Credential enrollment requires an authenticated client."}+ normalized = dict(data, provider=provider, _principal=execution_principal({}, websocket))cred_cls = CREDENTIAL_REGISTRY.get(provider)if cred_cls is None:@@ -59,6 +62,10 @@ async def handle_validate_api_key(data: Dict[str, Any], websocket: WebSocket) ->"valid": False,"error": f"Unknown provider '{provider}' — no Credential class registered.",}+ if data.get("credential_source") == "onepassword":+ from services.plugin.credential import Credential+ if cred_cls.validate.__func__ is not Credential.validate.__func__:+ return {"success": False, "valid": False, "error": "Use the 1Password endpoint enrollment form for this connection."}return await cred_cls.validate(normalized)@@ -104,6 +111,10 @@ async def handle_get_stored_api_key(data: Dict[str, Any], websocket: WebSocket)auth_service = container.auth_service()provider = data["provider"].lower()+ from services.authz.ws_surface import execution_principal+ source = await auth_service.get_credential_source(provider, data.get("session_id", "default"), principal=execution_principal({}, websocket))+ if source is not None:+ return {"provider": provider, "hasKey": True, "credentialSource": source, "models": source["models"], "timestamp": time.time()}api_key = await auth_service.get_api_key(provider, data.get("session_id", "default"))if not api_key:default = _lookup_credential_default(provider)@@ -166,7 +177,8 @@ async def handle_delete_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dauth_service = container.auth_service()broadcaster = get_status_broadcaster()session_id = data.get("session_id", "default")- await auth_service.remove_api_key(provider, session_id)+ from services.authz.ws_surface import execution_principal+ await auth_service.remove_api_key(provider, session_id, principal=execution_principal({}, websocket))# A provider's Base URL row and its registered models belong to it:# deleting a named endpoint (or a local server's key) must leave# neither behind. Both are no-ops for a provider that has none.diff --git a/server/services/credentials/onepassword.py b/server/services/credentials/onepassword.pynew file mode 100644index 00000000..207c1c96--- /dev/null+++ b/server/services/credentials/onepassword.py@@ -0,0 +1,145 @@+"""Private CLI secret reader. No shell, secret arguments, logs or value cache."""++from __future__ import annotations++import asyncio+import os+import re+import shutil+from pathlib import Path++CLI_VERSION = "2.40.0"+# Vault/item IDs must be unambiguous. Field names/IDs can include a section.+_REFERENCE = re.compile(r"^op://[a-z0-9]{26}/[a-z0-9]{26}/[A-Za-z0-9_. -]+(?:/[A-Za-z0-9_. -]+)?$")+_SAFE_ENV = frozenset({"PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "LANG", "LC_ALL"})+++class CredentialSourceError(PermissionError):+ """Only fixed, safe messages may cross an execution or UI boundary."""++ def __init__(self, code: str, message: str):+ self.code = code+ self.reason = code+ super().__init__(message)+++def validate_reference(reference: str) -> str:+ if not isinstance(reference, str) or len(reference) > 512 or not _REFERENCE.fullmatch(reference):+ raise CredentialSourceError("invalid_reference", "Use an op:// reference with vault and item IDs and an approved field; query parameters are unsupported.")+ return reference+++def resolver_environment(settings) -> dict[str, str]:+ """Explicit auth mode; Connect/session/ambient API tokens are never inherited."""+ env = {key: value for key, value in os.environ.items() if key.upper() in _SAFE_ENV}+ mode = getattr(settings, "onepassword_auth_mode", "desktop")+ if getattr(settings, "distributed_mode", False) and mode != "service_account":+ raise CredentialSourceError("unsupported_auth", "Distributed credentials require 1Password service-account authentication.")+ if mode == "service_account":+ token = os.environ.get("OP_SERVICE_ACCOUNT_TOKEN")+ if not token:+ raise CredentialSourceError("authorization_required", "The 1Password service account is not configured on this runtime.")+ env["OP_SERVICE_ACCOUNT_TOKEN"] = token+ env["OP_BIOMETRIC_UNLOCK_ENABLED"] = "false"+ elif mode == "desktop":+ env["OP_BIOMETRIC_UNLOCK_ENABLED"] = "true"+ account = getattr(settings, "onepassword_account", None)+ if account:+ env["OP_ACCOUNT"] = str(account)+ else:+ raise CredentialSourceError("unsupported_auth", "Select desktop or service-account 1Password authentication.")+ return env+++async def _terminate(process) -> None:+ if process.returncode is None:+ try:+ process.terminate()+ except ProcessLookupError:+ pass+ try:+ await asyncio.wait_for(process.wait(), 3)+ except asyncio.TimeoutError:+ try:+ process.kill()+ except ProcessLookupError:+ pass+ await process.wait()+++async def _private_command(executable: str, args: tuple[str, ...], env: dict, timeout: float) -> bytes:+ try:+ process = await asyncio.create_subprocess_exec(executable, *args, env=env, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=65536)+ except (OSError, ValueError):+ raise CredentialSourceError("cli_unavailable", "1Password CLI is unavailable. Provision the pinned CLI before using this binding.") from None+ async def bounded_read(stream) -> bytes:+ chunks, size = [], 0+ while True:+ chunk = await stream.read(4096)+ if not chunk:+ return b"".join(chunks)+ size += len(chunk)+ if size > 65536:+ raise CredentialSourceError("invalid_value", "The credential response exceeds the supported size.")+ chunks.append(chunk)+ async def collect():+ output, error = await asyncio.gather(bounded_read(process.stdout), bounded_read(process.stderr))+ await process.wait()+ return output, error+ try:+ output, discarded_stderr = await asyncio.wait_for(collect(), timeout)+ except asyncio.TimeoutError:+ await _terminate(process)+ raise CredentialSourceError("timeout", "1Password authorization or secret resolution timed out. Try again after authorizing the runtime.") from None+ except BaseException:+ await asyncio.shield(_terminate(process))+ raise+ if process.returncode != 0:+ # CLI error streams may contain credentials or URLs. Never classify by+ # serializing their text, including on a provider validation failure.+ error_hint = discarded_stderr.decode("utf-8", errors="ignore").lower()+ if "429" in error_hint or "rate limit" in error_hint or "request limit" in error_hint:+ raise CredentialSourceError("rate_limited", "1Password service-account limits were reached. Retry after its quota recovers.")+ if "not signed in" in error_hint or "authorization" in error_hint or "biometric" in error_hint:+ raise CredentialSourceError("authorization_required", "Authorize the 1Password runtime before retrying this task.")+ raise CredentialSourceError("resolution_failed", "1Password could not resolve the approved field. Check authorization, vault access and the reference.")+ if len(output) > 65536:+ raise CredentialSourceError("invalid_value", "The credential exceeds the supported size.")+ return output+++def cli_path(settings) -> str:+ from .provision import managed_path+ configured = getattr(settings, "onepassword_cli_path", None)+ managed = managed_path()+ executable = configured or (str(managed) if managed.is_file() else shutil.which("op"))+ if not executable or not Path(executable).is_absolute() or not Path(executable).is_file():+ raise CredentialSourceError("cli_unavailable", "Install the pinned 1Password CLI and configure its absolute executable path.")+ return str(Path(executable).resolve())+++async def doctor(settings) -> dict:+ """Integrity/version check, never signs in, lists vaults or reads a field."""+ executable = cli_path(settings)+ from .provision import verify_install+ await asyncio.to_thread(verify_install, Path(executable))+ # Version verification does not require a service token or desktop grant.+ env = {key: value for key, value in os.environ.items() if key.upper() in _SAFE_ENV}+ version = (await _private_command(executable, ("--version",), env, 10)).decode("utf-8").strip()+ if version != CLI_VERSION or getattr(settings, "onepassword_cli_version", CLI_VERSION) != CLI_VERSION:+ raise CredentialSourceError("cli_version", f"Provision 1Password CLI {CLI_VERSION}; the installed version does not match the tested pin.")+ return {"available": True, "version": CLI_VERSION, "auth_mode": getattr(settings, "onepassword_auth_mode", "desktop")}+++async def read_secret(reference: str, settings) -> str:+ validate_reference(reference)+ executable = cli_path(settings)+ await doctor(settings)+ output = await _private_command(executable, ("read", "--no-newline", reference), resolver_environment(settings), float(getattr(settings, "onepassword_read_timeout_seconds", 30)))+ try:+ value = output.decode("utf-8")+ except UnicodeError:+ raise CredentialSourceError("invalid_value", "The credential must be UTF-8 text.") from None+ if not value:+ raise CredentialSourceError("missing_value", "The approved 1Password field is empty.")+ return valuediff --git a/server/services/credentials/preflight.py b/server/services/credentials/preflight.pynew file mode 100644index 00000000..d9d6d6aa--- /dev/null+++ b/server/services/credentials/preflight.py@@ -0,0 +1,62 @@+"""Distributed credential compatibility checked before durable admission."""++from __future__ import annotations++from .onepassword import CredentialSourceError+++async def assert_cluster_credentials(database, graph: dict, context: dict | None = None) -> None:+ from core.container import container+ from services.node_registry import get_node_class+ from services.plugin.credential import ApiKeyCredential, Credential++ auth = container.auth_service()+ if not auth.distributed_credentials:+ return+ context = context or {}+ nodes = {str(node.get("id")): node for node in graph.get("nodes", [])}+ target = context.get("node_id")+ selected = set(nodes)+ if target and str(target) in nodes:+ # Inspect only the capability's incoming tool/skill/model dependencies.+ # Outgoing teammate edges lead to unrelated employee capabilities.+ selected, pending = set(), [str(target)]+ handles = {"input-tools", "input-skill", "input-context", "input-memory", "input-teammates", "input-model", "input-llm"}+ links = [(str(edge.get("source")), str(edge.get("target"))) for edge in graph.get("edges", [])+ if (edge.get("targetHandle") or edge.get("target_handle")) in handles]+ while pending:+ current = pending.pop()+ if current in selected:+ continue+ selected.add(current)+ pending.extend(left for left, right in links if right == current)+ for node_id in selected:+ node = nodes.get(node_id, {})+ node_type = str(node.get("type") or (node.get("data") or {}).get("type") or "")+ cls = get_node_class(node_type)+ if cls is None:+ continue+ data = dict(node.get("data") or {})+ params = await database.get_node_parameters(node_id) or {}+ data.update(params)+ if any(data.get(key) for key in ("api_key", "apiKey", "access_token", "refresh_token")):+ raise CredentialSourceError("unsupported_source", "Remove inline credentials and configure approved 1Password bindings before distributed execution.")+ # CLI login/session caches are machine-local even if an auth class is+ # absent. These backends cannot be approved by storing a token in op.+ if node_type in {"claude_code_agent", "codex_agent", "gemini_cli_agent", "openai_codex", "google_gemini"} or getattr(cls, "cli_backend", None):+ raise CredentialSourceError("unsupported_source", "CLI-managed login connections require local execution.")+ for cred in getattr(cls, "credentials", ()) or ():+ if not isinstance(cred, type) or not issubclass(cred, ApiKeyCredential):+ raise CredentialSourceError("unsupported_source", "This workflow contains an OAuth or machine-local connection without a distributed static-secret adapter.")+ if getattr(cred, "extra_fields", ()) and cred.id != "openai_compatible":+ raise CredentialSourceError("unsupported_source", "This connection needs additional credential fields without an audited distributed adapter.")+ if cred.validate.__func__ is not Credential.validate.__func__:+ # Named endpoint has an explicit audited enrollment adapter.+ if cred.id == "openai_compatible":+ provider = str(data.get("endpoint") or "")+ else:+ raise CredentialSourceError("unsupported_source", "This connection has no audited distributed static-secret adapter.")+ else:+ provider = cred.id+ if not provider or not await auth.get_credential_source(provider, principal=str(context.get("user_id") or "owner")):+ raise CredentialSourceError("missing_binding", "Configure a 1Password binding for every connection used by this task.")diff --git a/server/services/credentials/provision.py b/server/services/credentials/provision.pynew file mode 100644index 00000000..fae35e22--- /dev/null+++ b/server/services/credentials/provision.py@@ -0,0 +1,126 @@+"""Pinned official CLI installation, using the existing pooch package pattern."""++from __future__ import annotations++import asyncio+import hashlib+import json+import os+import platform+import shutil+import stat+import subprocess+from pathlib import Path++import pooch+from services.process_environment import without_onepassword_environment++from .onepassword import CLI_VERSION, CredentialSourceError++_FINGERPRINT = "3FEF9748469ADBE15DA7CA80AC2D62742012EA22"+_LOCK = asyncio.Lock()+++def package_root() -> Path:+ from core.paths import package_dir+ return package_dir("onepassword") / CLI_VERSION+++def managed_path() -> Path:+ return package_root() / ("op.exe" if platform.system() == "Windows" else "op")+++def _run(arguments: list[str], extra_env: dict | None = None) -> subprocess.CompletedProcess:+ try:+ env = dict(os.environ)+ env.update(extra_env or {})+ env = without_onepassword_environment(env)+ # The backend may be launched from PowerShell 7. Its module path can+ # prevent Windows PowerShell 5.1 from loading its signature cmdlet.+ # Let the selected verifier use its own built-in module locations.+ env = {key: value for key, value in env.items() if key.upper() != "PSMODULEPATH"}+ result = subprocess.run(arguments, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=False, env=env)+ except (OSError, subprocess.TimeoutExpired):+ raise CredentialSourceError("verification_failed", "The CLI signature verification tool is unavailable or timed out.") from None+ if result.returncode:+ raise CredentialSourceError("verification_failed", "The CLI publisher signature could not be verified.")+ return result+++def verify_publisher(binary: Path, *, fetch_key: bool = False) -> None:+ """Never execute an unverified downloaded binary, even for --version."""+ if platform.system() == "Windows":+ powershell = shutil.which("pwsh") or shutil.which("powershell")+ if not powershell:+ raise CredentialSourceError("verification_failed", "PowerShell is required to verify the CLI publisher signature.")+ # Fixed script; the path comes from a private environment field,+ # never interpolated into PowerShell source.+ script = "$s=Get-AuthenticodeSignature -LiteralPath $env:OPENCOMPANY_SIGNATURE_TARGET; if ($s.Status -ne 'Valid' -or $s.SignerCertificate.Subject -notmatch '(?:^|,\\s*)O=(?:Agilebits(?: Inc\\.?)?|1Password Inc\\.?)(?:,|$)') { exit 1 }"+ _run([powershell, "-NoProfile", "-NonInteractive", "-Command", script], {"OPENCOMPANY_SIGNATURE_TARGET": str(binary)})+ elif platform.system() == "Darwin":+ _run(["/usr/bin/codesign", "--verify", "--strict", "--test-requirement", 'anchor apple generic and certificate leaf[subject.OU] = "2BUA8C4S2C"', str(binary)])+ else:+ gpg = shutil.which("gpg")+ signature = binary.with_name("op.sig")+ if not gpg or not signature.is_file():+ raise CredentialSourceError("verification_failed", "GnuPG and the official op.sig are required to verify this CLI binary.")+ keyring = package_root() / "verification-keyring"+ keyring.mkdir(parents=True, exist_ok=True)+ keyring.chmod(stat.S_IRWXU)+ if fetch_key:+ _run([gpg, "--batch", "--homedir", str(keyring), "--keyserver", "hkps://keyserver.ubuntu.com", "--recv-keys", _FINGERPRINT])+ result = _run([gpg, "--batch", "--homedir", str(keyring), "--status-fd", "1", "--verify", str(signature), str(binary)])+ valid = [line.split() for line in result.stdout.decode("ascii", errors="ignore").splitlines() if line.startswith("[GNUPG:] VALIDSIG ")]+ if not any(parts[2] == _FINGERPRINT or parts[-1] == _FINGERPRINT for parts in valid):+ raise CredentialSourceError("verification_failed", "The CLI was not signed by the approved 1Password publisher key.")+++def verify_install(binary: Path) -> None:+ manifest = package_root() / "verified.json"+ if binary.resolve() == managed_path().resolve() and manifest.is_file():+ try:+ metadata = json.loads(manifest.read_text())+ if metadata["version"] == CLI_VERSION and hashlib.sha256(binary.read_bytes()).hexdigest() == metadata["sha256"]:+ return+ except (KeyError, ValueError, OSError):+ pass+ verify_publisher(binary)+++def _fetch() -> Path:+ system = {"Windows": "windows", "Darwin": "darwin", "Linux": "linux"}.get(platform.system())+ arch = {"AMD64": "amd64", "x86_64": "amd64", "arm64": "arm64", "aarch64": "arm64", "x86": "386"}.get(platform.machine())+ if not system or not arch or (system == "windows" and arch == "arm64"):+ raise CredentialSourceError("unsupported_platform", "No approved CLI archive is configured for this platform.")+ root = package_root()+ root.mkdir(parents=True, exist_ok=True)+ name = f"op_{system}_{arch}_v{CLI_VERSION}.zip"+ extracted = pooch.retrieve(url=f"https://cache.agilebits.com/dist/1P/op2/pkg/v{CLI_VERSION}/{name}", known_hash=None, path=root, fname=name, processor=pooch.Unzip(), downloader=pooch.HTTPDownloader(timeout=120))+ binary_name = managed_path().name+ source = next((Path(path) for path in extracted if Path(path).name == binary_name), None)+ if source is None:+ raise CredentialSourceError("invalid_archive", "The official CLI archive did not contain the expected executable.")+ verify_publisher(source, fetch_key=True)+ target = managed_path()+ shutil.copy2(source, target)+ signature = source.with_name("op.sig")+ if signature.exists():+ shutil.copy2(signature, target.with_name("op.sig"))+ if system != "windows":+ target.chmod(stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)+ (root / "verified.json").write_text(json.dumps({"version": CLI_VERSION, "sha256": hashlib.sha256(target.read_bytes()).hexdigest()}))+ return target+++async def ensure_cli() -> Path:+ async with _LOCK:+ target = managed_path()+ if target.is_file():+ await asyncio.to_thread(verify_install, target)+ return target+ try:+ return await asyncio.to_thread(_fetch)+ except CredentialSourceError:+ raise+ except Exception:+ raise CredentialSourceError("install_failed", "The official CLI could not be provisioned. Check network and publisher verification prerequisites.") from Nonediff --git a/server/services/credentials/sources.py b/server/services/credentials/sources.pynew file mode 100644index 00000000..0fd04edd--- /dev/null+++ b/server/services/credentials/sources.py@@ -0,0 +1,160 @@+"""Saved enrollment metadata. Secret values never enter these transactions."""++from __future__ import annotations++import uuid+from datetime import datetime, timezone+from typing import Any+from urllib.parse import urlsplit, urlunsplit++from sqlalchemy.exc import IntegrityError+from sqlmodel import select++from models.credential_sources import BrowserCredentialBinding, CredentialSource+from .onepassword import CredentialSourceError, validate_reference+++def exact_origin(value: str) -> str:+ try:+ parsed = urlsplit(value)+ port = parsed.port+ except (TypeError, ValueError):+ raise CredentialSourceError("invalid_origin", "Enter an exact HTTP(S) origin without credentials, path, query or fragment.") from None+ if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ("", "/"):+ raise CredentialSourceError("invalid_origin", "Enter an exact HTTP(S) origin without credentials, path, query or fragment.")+ host = parsed.hostname.lower()+ if ":" in host:+ host = f"[{host}]"+ if port is not None and port != (443 if parsed.scheme == "https" else 80):+ host += f":{port}"+ return f"{parsed.scheme}://{host}"+++def public_base_url(value: str | None) -> str | None:+ if not value:+ return None+ try:+ parsed = urlsplit(value)+ parsed.port+ except (TypeError, ValueError):+ raise CredentialSourceError("invalid_endpoint", "Enter an HTTP(S) endpoint without credentials, query or fragment.") from None+ if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:+ raise CredentialSourceError("invalid_endpoint", "Enter an HTTP(S) endpoint without credentials, query or fragment.")+ return urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", ""))+++def binding_metadata(row: BrowserCredentialBinding) -> dict[str, Any]:+ return {name: getattr(row, name) for name in ("id", "label", "origin", "profile_id", "employee_id", "workflow_id", "success_origin", "success_path", "success_selector")}+++class CredentialSources:+ def __init__(self, database):+ self.database = database++ @property+ def available(self) -> bool:+ return callable(getattr(self.database, "get_session", None))++ async def get(self, provider: str, session_id: str = "default") -> CredentialSource | None:+ if not self.available:+ return None+ async with self.database.get_session() as session:+ return (await session.execute(select(CredentialSource).where(CredentialSource.provider == provider, CredentialSource.session_id == session_id))).scalar_one_or_none()++ async def list(self, *, provider: str | None = None, session_id: str | None = None) -> list[CredentialSource]:+ if not self.available:+ return []+ query = select(CredentialSource)+ if provider is not None:+ query = query.where(CredentialSource.provider == provider)+ if session_id is not None:+ query = query.where(CredentialSource.session_id == session_id)+ async with self.database.get_session() as session:+ return list((await session.execute(query)).scalars().all())++ async def save(self, provider: str, reference: str, *, owner_id: str, session_id: str = "default", models: list[str] | None = None, model_params: dict | None = None, base_url: str | None = None) -> None:+ validate_reference(reference)+ url = public_base_url(base_url)+ if not provider or len(provider) > 255 or not owner_id or not session_id:+ raise CredentialSourceError("invalid_binding", "A provider and authenticated owner are required.")+ for attempt in range(2):+ async with self.database.get_session() as session:+ row = (await session.execute(select(CredentialSource).where(CredentialSource.provider == provider, CredentialSource.session_id == session_id).with_for_update())).scalar_one_or_none()+ if row is not None and row.owner_id != owner_id:+ raise CredentialSourceError("access_denied", "Credential binding access denied.")+ if row is None:+ row = CredentialSource(id=uuid.uuid4().hex, provider=provider, owner_id=owner_id, session_id=session_id, reference=reference)+ session.add(row)+ row.reference, row.models, row.model_params, row.base_url = reference, list(models or []), dict(model_params or {}), url+ row.updated_at = datetime.now(timezone.utc)+ try:+ await session.commit()+ return+ except IntegrityError:+ await session.rollback()+ if attempt:+ raise CredentialSourceError("binding_conflict", "The credential binding changed concurrently. Reload and retry.") from None++ async def delete(self, provider: str, session_id: str = "default", principal: str | None = None) -> None:+ if not self.available:+ return+ async with self.database.get_session() as session:+ row = (await session.execute(select(CredentialSource).where(CredentialSource.provider == provider, CredentialSource.session_id == session_id).with_for_update())).scalar_one_or_none()+ if row is not None:+ if principal is not None and row.owner_id != principal:+ raise CredentialSourceError("access_denied", "Credential binding access denied.")+ await session.delete(row)+ await session.commit()++ async def browser_binding(self, binding_id: str, principal: str, *, profile_id: str | None = None, workflow_id: str | None = None, employee_id: str | None = None) -> BrowserCredentialBinding:+ if not principal or not binding_id or not self.available:+ raise CredentialSourceError("access_denied", "Browser credential binding access denied.")+ async with self.database.get_session() as session:+ row = await session.get(BrowserCredentialBinding, binding_id)+ if row is None or row.owner_id != str(principal) or (row.profile_id and row.profile_id != profile_id) or (row.workflow_id and row.workflow_id != workflow_id) or (row.employee_id and row.employee_id != employee_id):+ raise CredentialSourceError("access_denied", "Browser credential binding access denied.")+ return row++ async def list_browser(self, principal: str) -> list[dict]:+ async with self.database.get_session() as session:+ rows = (await session.execute(select(BrowserCredentialBinding).where(BrowserCredentialBinding.owner_id == principal).order_by(BrowserCredentialBinding.label, BrowserCredentialBinding.id))).scalars().all()+ return [binding_metadata(row) for row in rows]++ async def save_browser(self, principal: str, data: dict) -> dict:+ # caller validates ownership of optional workflow/profile/employee.+ origin = exact_origin(str(data.get("origin") or ""))+ success_origin = exact_origin(str(data.get("success_origin") or origin))+ path = str(data.get("success_path") or "")+ if not path.startswith("/") or "?" in path or "#" in path or len(path) > 1024:+ raise CredentialSourceError("invalid_success", "Configure an exact successful login path without a query or fragment.")+ label = str(data.get("label") or "").strip()+ selector = str(data.get("success_selector") or "")+ if not label or len(label) > 128 or len(selector) > 512:+ raise CredentialSourceError("invalid_binding", "Enter a label and a supported success selector.")+ username = validate_reference(data.get("username_reference"))+ password = validate_reference(data.get("password_reference"))+ async with self.database.get_session() as session:+ binding_id = str(data.get("binding_id") or uuid.uuid4().hex)+ row = await session.get(BrowserCredentialBinding, binding_id, with_for_update=True)+ if row is not None and row.owner_id != principal:+ raise CredentialSourceError("access_denied", "Browser credential binding access denied.")+ if row is None:+ row = BrowserCredentialBinding(id=binding_id, owner_id=principal, label=label, origin=origin, username_reference=username, password_reference=password, success_origin=success_origin, success_path=path)+ session.add(row)+ row.label, row.origin = label, origin+ row.username_reference, row.password_reference = username, password+ row.success_origin, row.success_path, row.success_selector = success_origin, path, selector+ for name in ("profile_id", "employee_id", "workflow_id"):+ setattr(row, name, str(data[name]) if data.get(name) else None)+ row.updated_at = datetime.now(timezone.utc)+ await session.commit()+ return binding_metadata(row)++ async def delete_browser(self, principal: str, binding_id: str) -> None:+ async with self.database.get_session() as session:+ row = await session.get(BrowserCredentialBinding, binding_id, with_for_update=True)+ if row is not None:+ if row.owner_id != principal:+ raise CredentialSourceError("access_denied", "Browser credential binding access denied.")+ await session.delete(row)+ await session.commit()diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.pyindex 09031641..8c1174ca 100644--- a/server/services/deployment/manager.py+++ b/server/services/deployment/manager.py@@ -206,6 +206,8 @@ class DeploymentManager:workflow_slug = await self._generation_slug(workflow_id, generation) or (wf and wf.slug) or workflow_id# Setup+ from services.credentials.preflight import assert_cluster_credentials+ await assert_cluster_credentials(self.database, {"nodes": nodes, "edges": edges}, {"user_id": user_id})deployment_id = f"deploy_{workflow_id}_{int(time.time() * 1000)}"self._status_callbacks[workflow_id] = status_callbackself._run_counters[workflow_id] = 0@@ -834,6 +836,7 @@ class DeploymentManager:from services.temporal.executor import (capture_temporal_routing_input,+ capture_browser_routing_input,)from services.workflow_naming import node_label_slug@@ -862,6 +865,7 @@ class DeploymentManager:"session_id": state.session_id,"user_id": state.user_id,**capture_temporal_routing_input(),+ **(await capture_browser_routing_input(workflow_id, state.nodes, state.user_id)),}if state.graph_version > 0 and state.generation > 0:listener_args.update(@@ -1029,7 +1033,7 @@ class DeploymentManager:if state is None:raise RuntimeError(f"No deployment state for workflow {workflow_id}")- from services.temporal.executor import capture_temporal_routing_input+ from services.temporal.executor import capture_temporal_routing_input, capture_browser_routing_inputfrom services.workflow_naming import node_label_slugtrigger_label = node_label_slug(node)@@ -1058,6 +1062,7 @@ class DeploymentManager:# routing snapshot, so its runs fell back to the safe default# (worker pool OFF) and silently bypassed per-queue rate limits.**capture_temporal_routing_input(),+ **(await capture_browser_routing_input(workflow_id, state.nodes, state.user_id)),}control_lookup = self.database.get_latest_workflow_control(workflow_id)diff --git a/server/services/distributed_notifications.py b/server/services/distributed_notifications.pynew file mode 100644index 00000000..3044f836--- /dev/null+++ b/server/services/distributed_notifications.py@@ -0,0 +1,121 @@+"""PostgreSQL identifier-only invalidation for Browser metadata on replicas."""+from __future__ import annotations++import asyncio+import json+import uuid++from sqlalchemy import text++CHANNEL = "opencompany_browser_invalidation"+_instance = None+++def notification(message: dict, origin: str) -> dict | None:+ kind = message.get("type")+ if kind not in {"browser_updated", "browser_profiles_updated"}:+ return None+ event = message.get("data") or {}+ data = event.get("data") or {}+ result = {"origin": origin, "kind": kind}+ if kind == "browser_updated":+ for key in ("workflow_id", "node_id", "session_id"):+ value = data.get(key)+ if not isinstance(value, str) or not value or len(value) > 512:+ return None+ result[key] = value+ return result+++class BrowserNotifications:+ def __init__(self, database, broadcaster):+ self.database, self.broadcaster = database, broadcaster+ self.origin = uuid.uuid4().hex+ self.task = None+ self.connection = None+ self.deliveries = set()+ self.stopped = False++ async def start(self):+ await self._connect()+ self.task = asyncio.create_task(self._listen(), name="browser-postgresql-invalidation")++ async def _connect(self):+ import asyncpg+ self.disconnected = asyncio.Event()+ url = self.database.engine.url.set(drivername="postgresql").render_as_string(hide_password=False)+ self.connection = await asyncpg.connect(url, timeout=10)+ self.connection.add_termination_listener(lambda _: self.disconnected.set())+ try:+ await self.connection.add_listener(CHANNEL, self._receive)+ except BaseException:+ await self.connection.close()+ raise++ async def _listen(self):+ while not self.stopped:+ await self.disconnected.wait()+ if self.stopped:+ return+ try:+ await self._connect()+ # NOTIFY is deliberately transient; reconnect requires a refresh.+ await self.broadcaster.broadcast({"type": "browser_profiles_updated", "data": {}}, shared=False)+ except Exception:+ # Metadata can be refreshed through the authorized APIs while+ # the dedicated listener reconnects; no task work is replayed.+ await asyncio.sleep(5)+ self.disconnected.set()++ def _receive(self, connection, pid, channel, payload):+ try:+ data = json.loads(payload)+ kind = data.get("kind")+ expected = {"origin", "kind"} | ({"workflow_id", "node_id", "session_id"} if kind == "browser_updated" else set())+ if kind not in {"browser_updated", "browser_profiles_updated"} or set(data) != expected:+ return+ if any(not isinstance(value, str) or not value or len(value) > 512 for value in data.values()) or data["origin"] == self.origin:+ return+ message = ({"type": "browser_invalidated", "data": {key: data[key] for key in ("workflow_id", "node_id", "session_id")}}+ if kind == "browser_updated" else {"type": "browser_profiles_updated", "data": {}})+ task = asyncio.create_task(self.broadcaster.broadcast(message, shared=False))+ self.deliveries.add(task)+ task.add_done_callback(self.deliveries.discard)+ except (ValueError, TypeError, AttributeError):+ return++ async def publish(self, message):+ data = notification(message, self.origin)+ if data is not None:+ async with self.database.engine.begin() as connection:+ await connection.execute(text("SELECT pg_notify(:channel, :payload)"),+ {"channel": CHANNEL, "payload": json.dumps(data)})++ async def stop(self):+ self.stopped = True+ if self.task:+ self.task.cancel()+ await asyncio.gather(self.task, return_exceptions=True)+ if self.connection and not self.connection.is_closed():+ await self.connection.close()+ if self.deliveries:+ await asyncio.gather(*self.deliveries, return_exceptions=True)+++async def start(database, broadcaster):+ global _instance+ if database.settings.distributed_mode:+ _instance = BrowserNotifications(database, broadcaster)+ await _instance.start()+++async def publish(message):+ if _instance:+ await _instance.publish(message)+++async def stop():+ global _instance+ if _instance:+ await _instance.stop()+ _instance = Nonediff --git a/server/services/employees/activation.py b/server/services/employees/activation.pyindex c4696d09..10a675ba 100644--- a/server/services/employees/activation.py+++ b/server/services/employees/activation.py@@ -30,7 +30,7 @@ async def activate_pending(database: Any, workflow_id: str | None = None) -> Nonif not blocked:from services.employees.start import heal_agent_modelsfrom services.employees.connections import Connections- await heal_agent_models(database, container.auth_service(), Connections(container.auth_service()), intent.workflow_id)+ await heal_agent_models(database, container.auth_service(), Connections(container.auth_service(), principal=intent.owner_id), intent.workflow_id)# The deployment control service arbitrates concurrent admissions# with this stable identity; no external calls inside our DB txn.result = await start_saved_workflow(intent.workflow_id, owner_id=intent.owner_id, idempotency_key=intent.id)diff --git a/server/services/employees/connections.py b/server/services/employees/connections.pyindex 789a2ac1..c97869e6 100644--- a/server/services/employees/connections.py+++ b/server/services/employees/connections.py@@ -19,8 +19,9 @@ _DISCONNECTED: Dict[str, Any] = {"stored": False, "connected": False, "account_lclass Connections:- def __init__(self, auth_service: Any) -> None:+ def __init__(self, auth_service: Any, *, principal: Optional[str] = None) -> None:self._auth = auth_service+ self.principal = principalself._registry = get_credential_registry()self._states: Dict[str, Dict[str, Any]] = {}@@ -34,7 +35,7 @@ class Connections:cached = dict(_DISCONNECTED)if provider is not None:try:- cached = await provider_connection_state(provider, self._auth)+ cached = await provider_connection_state(provider, self._auth, **({"principal": self.principal} if self.principal is not None else {}))except Exception:# One broken credential check must not take down a team# list; the app just reads as not connected.@@ -78,7 +79,7 @@ class Connections:try:from services.llm.endpoints import list_endpoints- usable += [endpoint.ref for endpoint in await list_endpoints(self._auth)]+ usable += [endpoint.ref for endpoint in await list_endpoints(self._auth, **({"principal": self.principal} if self.principal is not None else {}))]except Exception:logger.warning("Could not list OpenAI-compatible endpoints", exc_info=True)return usablediff --git a/server/services/employees/handlers.py b/server/services/employees/handlers.pyindex 454f920c..7b5cd9b0 100644--- a/server/services/employees/handlers.py+++ b/server/services/employees/handlers.py@@ -129,7 +129,7 @@ async def _talk_tools_for(auth_service: Any, row: Any) -> List[TalkTool]:from services.node_allowlist import is_hire_allowedapps = [app for app in (get_app(app_id) for app_id in row.apps or []) if app is not None]- return talk_tools(apps, owner_values=await owner_values_for(auth_service), allowed=is_hire_allowed)+ return talk_tools(apps, owner_values=await owner_values_for(auth_service, principal=getattr(row, "owner_id", None)), allowed=is_hire_allowed)async def _new_talk_agent(database: Any, workflow: Any, row: Any, state: TalkState, *, sends: bool = False) -> TalkAgent:diff --git a/server/services/employees/hire.py b/server/services/employees/hire.pyindex f787edd0..39c2fdd3 100644--- a/server/services/employees/hire.py+++ b/server/services/employees/hire.py@@ -100,9 +100,9 @@ def _resolve_apps(request: HireEmployeeRequest, connected: List[str]) -> tuple:return known, unsupported-async def owner_values_for(auth_service: Any) -> Dict[str, str]:+async def owner_values_for(auth_service: Any, *, principal: Optional[str] = None) -> Dict[str, str]:"""The owner's own addresses (for reports to them, and sending as them)."""- return await _owner_values(Connections(auth_service), auth_service)+ return await _owner_values(Connections(auth_service, principal=principal), auth_service)async def _owner_values(connections: Connections, auth_service: Any) -> Dict[str, str]:@@ -326,7 +326,7 @@ async def handle_hire_employee(data: Dict[str, Any], websocket: WebSocket) -> Diif answer is not None:return answer- connections = Connections(auth_service)+ connections = Connections(auth_service, principal=owner)connected = await connections.connected_app_ids()apps, unsupported = _resolve_apps(request, connected)row, claim_token = await store.claim_hire(diff --git a/server/services/employees/llm.py b/server/services/employees/llm.pyindex 112a2b86..1e65f9de 100644--- a/server/services/employees/llm.py+++ b/server/services/employees/llm.py@@ -61,7 +61,7 @@ def runs_locally(provider: str) -> bool:return bool(entry.get("runs_locally"))-async def _model_for(provider: str, database: Any, auth_service: Any, *, local: bool, endpoint_models: Optional[List[str]] = None) -> str:+async def _model_for(provider: str, database: Any, auth_service: Any, *, local: bool, endpoint_models: Optional[List[str]] = None, principal: Optional[str] = None) -> str:from services.llm.config import get_default_modeltry:@@ -74,7 +74,7 @@ async def _model_for(provider: str, database: Any, auth_service: Any, *, local:return endpoint_models[0]if local:try:- models = await auth_service.get_stored_models(provider)+ models = await auth_service.get_stored_models(provider, **({"principal": principal} if principal is not None else {}))except Exception:models = []if models:@@ -95,7 +95,8 @@ async def resolve_llm_choice(try:from services.llm.endpoints import list_endpoints- endpoints = await list_endpoints(auth_service)+ principal = getattr(connections, "principal", None)+ endpoints = await list_endpoints(auth_service, **({"principal": principal} if principal is not None else {}))except Exception:logger.warning("Could not list OpenAI-compatible endpoints", exc_info=True)endpoint_models = {endpoint.ref: list(endpoint.models) for endpoint in endpoints}@@ -110,7 +111,7 @@ async def resolve_llm_choice(async def choose(provider: str, model: Optional[str] = None) -> LLMChoice:local = runs_locally(provider)chosen = model or await _model_for(- provider, database, auth_service, local=local, endpoint_models=endpoint_models.get(provider)+ provider, database, auth_service, local=local, endpoint_models=endpoint_models.get(provider), principal=getattr(connections, "principal", None))return LLMChoice(provider=provider, model=chosen, local=local)@@ -136,10 +137,11 @@ async def employees_chat(*,max_tokens: int = SETUP_MAX_TOKENS,timeout: Optional[float] = None,+ principal: Optional[str] = None,) -> LLMResponse:"""One completion on the chosen model. Raises ``asyncio.TimeoutError``past the budget and ``NodeUserError`` for provider failures."""- api_key = await auth_service.get_api_key(choice.provider) or ""+ api_key = await auth_service.resolve_api_key(choice.provider, principal=principal) or ""try:from services.model_registry import get_model_registrydiff --git a/server/services/employees/setup.py b/server/services/employees/setup.pyindex eb30aa62..e446ae81 100644--- a/server/services/employees/setup.py+++ b/server/services/employees/setup.py@@ -166,7 +166,7 @@ async def _generate(request: SetupRequest, owner: str) -> Dict[str, Any]:database = container.database()auth_service = container.auth_service()- connections = Connections(auth_service)+ connections = Connections(auth_service, principal=owner)choice: Optional[LLMChoice] = await resolve_llm_choice(database, auth_service, connections)if choice is None:return _failure("no_ai_provider", request.token)@@ -182,7 +182,7 @@ async def _generate(request: SetupRequest, owner: str) -> Dict[str, Any]:if attempt == 1 and remaining < MIN_RETRY_SECONDS:breaktry:- response = await employees_chat(container.chat_unifier(), auth_service, choice, messages, timeout=remaining)+ response = await employees_chat(container.chat_unifier(), auth_service, choice, messages, timeout=remaining, principal=owner)except asyncio.TimeoutError:if kept is not None:breakdiff --git a/server/services/employees/start.py b/server/services/employees/start.pyindex 614d2fba..534c602f 100644--- a/server/services/employees/start.py+++ b/server/services/employees/start.py@@ -65,9 +65,10 @@ async def heal_agent_models(database: Any, auth_service: Any, connections: Conneendpoint_models = Noneif str(provider).startswith("openai_compatible:"):from services.llm.endpoints import list_endpoints- endpoint = next((entry for entry in await list_endpoints(auth_service) if entry.ref == provider), None)+ principal = getattr(connections, "principal", None)+ endpoint = next((entry for entry in await list_endpoints(auth_service, **({"principal": principal} if principal is not None else {})) if entry.ref == provider), None)endpoint_models = list(endpoint.models) if endpoint is not None else None- model = await _model_for(provider, database, auth_service, local=runs_locally(provider), endpoint_models=endpoint_models)+ model = await _model_for(provider, database, auth_service, local=runs_locally(provider), endpoint_models=endpoint_models, principal=getattr(connections, "principal", None))if model:await database.save_node_parameters(agent_id, {**params, "model": model})changed.append(agent_id)@@ -119,7 +120,7 @@ async def handle_start_employee(data: Dict[str, Any], websocket: WebSocket) -> Derror = team_approval_topology_error(getattr(workflow, "data", None), roles, params=params, team_plan=employee.team_plan)if error:return {"success": False, "error": error}- await heal_agent_models(database, auth_service, Connections(auth_service), workflow_id)+ await heal_agent_models(database, auth_service, Connections(auth_service, principal=execution_principal(data, websocket)), workflow_id)# An employee an older builder made comes up to the live Ask first rule# before it runs (services/employees/upgrade.py).from services.employees.upgrade import upgrade_employeediff --git a/server/services/employees/summaries.py b/server/services/employees/summaries.pyindex aeb0945e..409269b2 100644--- a/server/services/employees/summaries.py+++ b/server/services/employees/summaries.py@@ -403,10 +403,15 @@ async def list_employee_summaries(database: Any, *, auth_service: Any, owner_id:controls = await database.list_latest_workflow_controls(ids)pending = await _pending_counts(database, ids)done = await _done_today(database, ids)- connections = Connections(auth_service)- needs_ai = not await connections.has_ai()- return [- await _summary(+ connections_by_owner = {}+ summaries = []+ for workflow in workflows:+ principal = employee_owner(workflow, employees.get(workflow.id))+ if principal not in connections_by_owner:+ connection = Connections(auth_service, principal=principal)+ connections_by_owner[principal] = (connection, not await connection.has_ai())+ connections, needs_ai = connections_by_owner[principal]+ summaries.append(await _summary(workflow,employees.get(workflow.id),controls.get(workflow.id),@@ -414,9 +419,8 @@ async def list_employee_summaries(database: Any, *, auth_service: Any, owner_id:needs_ai=needs_ai,pending=pending.get(workflow.id, 0),done_today=done.get(workflow.id, 0),- )- for workflow in workflows- ]+ ))+ return summariesasync def _load_one(database: Any, workflow_id: str, *, auth_service: Any) -> Optional[tuple]:@@ -427,7 +431,7 @@ async def _load_one(database: Any, workflow_id: str, *, auth_service: Any) -> Opcontrol = await database.get_latest_workflow_control(workflow_id)pending = await _pending_counts(database, [workflow_id])done = await _done_today(database, [workflow_id])- connections = Connections(auth_service)+ connections = Connections(auth_service, principal=employee_owner(workflow, employee))summary = await _summary(workflow,employee,diff --git a/server/services/employees/team_recipe.py b/server/services/employees/team_recipe.pyindex 036df3ab..f49437e2 100644--- a/server/services/employees/team_recipe.py+++ b/server/services/employees/team_recipe.py@@ -30,7 +30,7 @@ class Responsibility:RESPONSIBILITIES = (- Responsibility("research", "web_agent", "Research", "Researches information", ("research", "search", "news", "brief", "web", "competitor", "investigat")),+ Responsibility("research", "web_agent", "Research", "Researches information", ("research", "search", "news", "brief", "web", "browser", "website", "competitor", "investigat")),Responsibility("calendar", "productivity_agent", "Appointments", "Checks your calendar and appointments", ("calendar", "appointment", "meeting", "book", "schedule")),Responsibility("coding", "coding_agent", "Development", "Builds and checks software", ("code", "coding", "software", "develop", "program", "github")),Responsibility("social", "social_agent", "Content", "Prepares content for your channels", ("social", "post", "content", "marketing", "instagram", "linkedin", "twitter")),@@ -136,6 +136,9 @@ def build_team(built: Any, inputs: Any) -> Any:members: list[dict[str, Any]] = []for index, responsibility in enumerate(selected, 1):node_type = responsibility.node_type+ if node_type == "web_agent" and (any(tool.type == "browser" for app in inputs.apps for tool in app.tools)+ or any(word in inputs.request.job.lower() for word in ("browser", "website"))):+ node_type = "browser_agent"if get_node_class(node_type) is None or not inputs.allowed(node_type):node_type = "aiAgent"if not inputs.allowed(node_type):@@ -150,6 +153,9 @@ def build_team(built: Any, inputs: Any) -> Any:)built.nodes.append(graph_node(member, node_type, member_label, (360 + 360 * index, -420), {"responsibility": responsibility.description}))built.parameters[member] = {"system_message": instruction, "prompt": "Complete your assigned task and submit the result for lead review.", **model}+ if node_type == "browser_agent":+ from services.browser_agent_recipe import BROWSER_AGENT_ROLE+ built.parameters[member]["system_message"] = BROWSER_AGENT_ROLE + "\n" + instructionbuilt.edges.append(Edge(member, "output-top", lead, "input-teammates").to_dict())context_id = ids.next(CONTEXT_TYPE)built.nodes.append(graph_node(context_id, CONTEXT_TYPE, labels.take(f"{responsibility.label} context"), (360 + 360 * index, -600), context_data(member)))@@ -194,6 +200,28 @@ def build_team(built: Any, inputs: Any) -> Any:recipient = recipient or next((member for member in members if member["role"] == "operations"), members[0])built.edges.append(tool_edge(tool, recipient["node_id"]).to_dict())recipient["tools"].append(tool)+ # Complete Browser specialists through the same recipe as canvas/Builder,+ # reusing the private Browser tool already assigned from the saved app.+ from services.browser_agent_recipe import browser_agent_additions+ from services.graph_build import add_to_graph+ for member in members:+ if member["node_type"] != "browser_agent":+ continue+ browser = next((tool for tool in member["tools"] if nodes[tool]["type"] == "browser"), None)+ position = next(node["position"] for node in built.nodes if node["id"] == member["node_id"])+ additions = browser_agent_additions(agent_ref=member["node_id"], browser_node_id=browser,+ create_agent=False, create_context=False, create_skills=False,+ position=(position["x"], position["y"]))+ if any(not inputs.allowed(node.type) for node in additions.nodes):+ raise BuildError("not_allowed", "Browser tools are not available")+ placed = add_to_graph(inputs.workflow_id, {"nodes": built.nodes, "edges": built.edges}, additions)+ built.nodes, built.edges = placed.graph["nodes"], placed.graph["edges"]+ built.parameters.update(placed.parameters)+ member["tools"].extend(node["id"] for node in placed.nodes)+ holder = roles[next(key for key, value in roles.items() if key.startswith("specialist_") and value == member["node_id"]) + "_skills"]+ default_skills = browser_agent_additions(create_agent=False, create_context=False).nodes+ config = next(node.params["skills_config"] for node in default_skills if node.type == "masterSkill")+ built.parameters[holder]["skills_config"].update(config)# Keep one memory per member. A legacy Talk line may share the worker's# memory: remove that binding and give each agent its own instance.memories = {node["id"] for node in built.nodes if node["type"] == "simpleMemory"}diff --git a/server/services/events/cli.py b/server/services/events/cli.pyindex 50ddd344..643d45fb 100644--- a/server/services/events/cli.py+++ b/server/services/events/cli.py@@ -16,6 +16,7 @@ import shutilfrom typing import Any, Dict, List, Optional, Typefrom services._supervisor.util import kill_tree+from services.process_environment import without_onepassword_environmentasync def run_cli_command(@@ -33,7 +34,8 @@ async def run_cli_command("""Run ``<binary> <argv> [api_key_arg <key>]`` once, return parsed JSON.``env``: optional process environment override. When None, the child- inherits the parent's environment (asyncio default).+ inherits ordinary parent variables. 1Password authentication variables+ are removed after any caller overrides, before spawning the child.``cwd``: optional working directory for the child. Needed by CLIswhose commands are directory-scoped (``vercel deploy`` deploys the@@ -96,7 +98,7 @@ async def run_cli_command(stdin=stdin,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,- env=env,+ env=without_onepassword_environment(env),cwd=cwd,)stdout, stderr = await asyncio.wait_for(proc.communicate(input=input), timeout=timeout)diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 0f40e468..6ebb47b9 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -508,7 +508,7 @@ async def _execute_delegated_agent(from constants import detect_ai_providerprovider = detect_ai_provider(node_type, child_params)- key = await ai_service.auth.get_api_key(provider, "default")+ key = await ai_service.auth.resolve_api_key(provider, "default", principal=str(config.get("user_id") or "owner"))if key:child_params["api_key"] = keylogger.debug(f"[Delegated Agent] Injected API key for provider={provider}")@@ -526,6 +526,9 @@ async def _execute_delegated_agent(# Schema-canonical key is snake_case; drop any pre-migration camelCase# mirror so the saved-params dict downstream uses the canonical key.child_params["system_message"] = task_description+ if node_type == "browser_agent":+ from services.browser_agent_recipe import BROWSER_AGENT_ROLE+ child_params["system_message"] = BROWSER_AGENT_ROLE + "\n" + task_descriptionchild_params.pop("systemMessage", None)child_params["prompt"] = task_context if task_context else task_descriptiondiff --git a/server/services/llm/endpoints.py b/server/services/llm/endpoints.pyindex 3d2ce5bc..bb32b473 100644--- a/server/services/llm/endpoints.py+++ b/server/services/llm/endpoints.py@@ -189,7 +189,7 @@ async def resolve_base_url(candidate: str, *, api_key: str, timeout: float = 10.)-async def list_endpoint_refs(auth: "AuthService") -> List[str]:+async def list_endpoint_refs(auth: "AuthService", *, principal: Optional[str] = None) -> List[str]:"""Every saved named endpoint, as provider references, sorted.Enumerated from the credential rows themselves rather than a separate@@ -198,7 +198,7 @@ async def list_endpoint_refs(auth: "AuthService") -> List[str]:prefix = f"{ENDPOINT_PROVIDER}:"return sorted(provider- for provider in await auth.list_api_key_providers()+ for provider in await auth.list_api_key_providers(**({"principal": principal} if principal is not None else {}))if provider.startswith(prefix) and not provider.endswith(BASE_URL_SUFFIX))@@ -218,18 +218,19 @@ class SavedEndpoint:models: List[str]-async def list_endpoints(auth: "AuthService") -> List[SavedEndpoint]:+async def list_endpoints(auth: "AuthService", *, principal: Optional[str] = None) -> List[SavedEndpoint]:"""Every saved named endpoint with its display metadata and models."""endpoints: List[SavedEndpoint] = []- for ref in await list_endpoint_refs(auth):- meta = (await auth.get_model_params(ref)).get(SERVER_META_KEY) or {}+ scope = {"principal": principal} if principal is not None else {}+ for ref in await list_endpoint_refs(auth, **scope):+ meta = (await auth.get_model_params(ref, **scope)).get(SERVER_META_KEY) or {}endpoints.append(SavedEndpoint(ref=ref,label=meta.get("label") or split_provider_ref(ref)[1],base_url=meta.get("base_url", ""),kind=meta.get("kind", "generic"),- models=list(await auth.get_stored_models(ref)),+ models=list(await auth.get_stored_models(ref, **scope)),))return endpointsdiff --git a/server/services/llm/unifier.py b/server/services/llm/unifier.pyindex 0c4fc3a7..95f0fcd4 100644--- a/server/services/llm/unifier.py+++ b/server/services/llm/unifier.py@@ -338,7 +338,7 @@ class ChatUnifier:# The base-URL row is keyed by the full reference, so each named# endpoint reads its own URL while sharing one registration.ref = provider_ref or spec.name- proxy_url = await self._auth.get_api_key(base_url_key(ref))+ proxy_url = await self._auth.resolve_api_key(base_url_key(ref))unconfigured = unconfigured_endpoint_message(ref)if unconfigured and not proxy_url:# A named endpoint exists only as its credential rows. Withoutdiff --git a/server/services/memory/vector_store.py b/server/services/memory/vector_store.pyindex 148c6985..0e343706 100644--- a/server/services/memory/vector_store.py+++ b/server/services/memory/vector_store.py@@ -511,7 +511,7 @@ async def get_memory_vector_store(if normalized == "openai" and resolved_key is None:if auth_service is not None:try:- auth_key = await auth_service.get_api_key(+ auth_key = await auth_service.resolve_api_key("openai","default",)diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex cd5a1271..cac478f9 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -160,7 +160,7 @@ class NodeExecutor:# Load, validate, enhance parametersparams = await self._prepare_parameters(node_id, node_type, parameters, session_id, tool_args=tool_args,- parameter_snapshot=context.get("parameter_snapshot"))+ parameter_snapshot=context.get("parameter_snapshot"), principal=str(context.get("user_id") or "owner"))# Resolve templates if resolver providednodes = context.get("nodes")@@ -249,6 +249,7 @@ class NodeExecutor:session_id: str,tool_args: Optional[Dict[str, Any]] = None,parameter_snapshot: Optional[Dict[str, Dict[str, Any]]] = None,+ principal: str = "owner",) -> Dict:"""Load from DB, validate, inject API keys."""# Merge with DB parameters (DB provides defaults, frontend can override)@@ -280,16 +281,19 @@ class NodeExecutor:logger.warning("Validation warning", node_type=node_type, errors=str(e))# Inject API keys- return await self._inject_api_keys(node_type, merged)+ return await self._inject_api_keys(node_type, merged, principal=principal)- async def _inject_api_keys(self, node_type: str, params: Dict) -> Dict:+ async def _inject_api_keys(self, node_type: str, params: Dict, *, principal: str = "owner") -> Dict:"""Auto-inject API keys for AI and Maps nodes."""result = params.copy()+ if getattr(self.settings, "distributed_mode", False) and result.get("api_key"):+ from services.plugin import NodeUserError+ raise NodeUserError("Distributed execution requires a saved 1Password credential.")if node_type in AI_MODEL_TYPES:provider = detect_ai_provider(node_type, params)if not result.get("api_key"):- key = await self.ai_service.auth.get_api_key(provider, "default")+ key = await self.ai_service.auth.resolve_api_key(provider, "default", principal=principal)if key:result["api_key"] = keyif not result.get("model"):@@ -300,10 +304,10 @@ class NodeExecutor:elif node_type in GOOGLE_MAPS_TYPES:if not result.get("api_key"):# Try database first, then fall back to environment variable- key = await self.ai_service.auth.get_api_key("google_maps", "default")+ key = await self.ai_service.auth.resolve_api_key("google_maps", "default", principal=principal)if key:result["api_key"] = key- elif self.settings.google_maps_api_key:+ elif not getattr(self.settings, "distributed_mode", False) and self.settings.google_maps_api_key:result["api_key"] = self.settings.google_maps_api_keyreturn resultdiff --git a/server/services/node_invocations.py b/server/services/node_invocations.pyindex af180cd0..79643590 100644--- a/server/services/node_invocations.py+++ b/server/services/node_invocations.py@@ -60,13 +60,17 @@ async def _controller_update(workflow_id: str, update, argument, *, update_id: sexcept WorkflowUpdateFailedError as exc:cause = exc.causemessages = {- "WorkspaceResetInProgress": "Phone tasks are resetting. Wait for Reset to finish.",+ "WorkspaceResetInProgress": "Workspace tasks are resetting. Wait for Reset to finish.","WorkspaceAdmissionChanged": "This submission crossed a Reset. Submit a new task.","WorkspaceSubmissionConflict": "Submission ID was already used for a different task","WorkspaceTaskQueueFull": "The Workspace task queue is full",}- if getattr(cause, "type", None) in messages:- raise NodeUserError(messages[cause.type]) from None+ for _ in range(8):+ if getattr(cause, "type", None) in messages:+ raise NodeUserError(messages[cause.type]) from None+ if getattr(cause, "cause", None) is None:+ break+ cause = cause.causeraise@@ -167,7 +171,7 @@ async def submit(principal: str, workflow_id: str, node_id: str, prompt: str, sudatabase = get_database()control = await database.get_latest_workflow_control(workflow_id)if (admission or {}).get("resetting") or (control and control.status == "resetting"):- raise NodeUserError("Phone tasks are resetting. Wait for Reset to finish.")+ raise NodeUserError("Workspace tasks are resetting. Wait for Reset to finish.")run_id = invocation_id(principal, workflow_id, node_id, submission_id)fingerprint = hashlib.sha256(prompt.encode()).hexdigest()params = {**(await get_database().get_node_parameters(node_id) or {}), "prompt": prompt}@@ -198,6 +202,28 @@ async def submit(principal: str, workflow_id: str, node_id: str, prompt: str, su"context": context,"admission_epoch": (admission or {}).get("epoch", 0),}+ if node["type"] == "browser_agent":+ if getattr(settings, "distributed_mode", False) is True:+ from services.credentials.preflight import assert_cluster_credentials+ await assert_cluster_credentials(database, graph, context)+ from services.browser_tasks import browser_tool_for_agent+ from services.browser_owners import routing_for_node+ browser_node = browser_tool_for_agent(graph, node_id)+ binding = await routing_for_node(database, workflow_id, browser_node["id"], principal)+ snapshot = {saved_node["id"]: await database.get_node_parameters(saved_node["id"]) or {}+ for saved_node in graph.get("nodes", []) if saved_node.get("id")}+ from services.temporal.agent_activities import _strip_credentials+ snapshot = _strip_credentials(snapshot)+ context["node_data"] = _strip_credentials(context["node_data"])+ context["nodes"] = _strip_credentials(context["nodes"])+ context.update(native_workspace_version=1, workspace_task_prompt=prompt,+ parameter_snapshot=snapshot, temporal_worker_pool_enabled=settings.temporal_worker_pool_enabled,+ browser_bindings={browser_node["id"]: binding}, _browser_task_id=run_id)+ payload.update(dispatch_version=1, dispatch_kind="native_agent", history_version=1,+ history_record={"invocation_id": run_id, "submission_id": str(UUID(submission_id)),+ "principal": principal, "workflow_id": workflow_id, "node_id": node_id,+ "fingerprint": fingerprint, "prompt": prompt,+ "browser_owner_ids": [binding["owner_id"]] if binding.get("task_queue") else []})client = temporal_client()# The controller owns submission idempotence. A new Update ID permits a# retry after queue-full/reset rejection; a completed failed Update would@@ -207,8 +233,19 @@ async def submit(principal: str, workflow_id: str, node_id: str, prompt: str, suupdate_id=f"submit:{run_id}:{uuid4().hex}",)if admitted.get("status") == "duplicate":- existing = await client.get_workflow_handle(run_id).query(NodeInvocationWorkflow.describe)- if existing["fingerprint"] != fingerprint:+ from temporalio.service import RPCError, RPCStatusCode+ try:+ existing = await client.get_workflow_handle(run_id).query(NodeInvocationWorkflow.describe)+ existing_fingerprint = existing["fingerprint"]+ except RPCError as exc:+ if exc.status != RPCStatusCode.NOT_FOUND or node["type"] != "browser_agent":+ raise+ from services.workspace_task_history import get_task, TERMINAL+ record = await get_task(database, principal, workflow_id, run_id)+ if record is None or record.status not in TERMINAL:+ raise NodeUserError("This Workspace task was not found") from None+ existing_fingerprint = record.fingerprint+ if existing_fingerprint != fingerprint:raise NodeUserError("Submission ID was already used for a different task") from Nonefrom services.deployment.handlers import _with_runtime_countsfrom services.deployment.control import serialize_control@@ -232,7 +269,13 @@ async def status(principal: str, workflow_id: str, node_id: str, submission_id:from services.plugin import NodeUserErrorfrom temporalio.service import RPCError, RPCStatusCode- await resolve_workflow_node(principal, workflow_id, node_id)+ from services.plugin.deps import get_database+ from services.workspace_task_history import get_task+ database = get_database()+ record = await get_task(database, principal, workflow_id, invocation_id(principal, workflow_id, node_id, submission_id))+ if record is None:+ # Legacy device tasks have no history projection and retain saved-node authorization.+ await resolve_workflow_node(principal, workflow_id, node_id)handle = temporal_client().get_workflow_handle(invocation_id(principal, workflow_id, node_id, submission_id))try:if cancel:@@ -240,6 +283,9 @@ async def status(principal: str, workflow_id: str, node_id: str, submission_id:result = await handle.query(NodeInvocationWorkflow.describe)except RPCError as exc:if exc.status == RPCStatusCode.NOT_FOUND:+ if record is not None and record.status in ("completed", "failed", "cancelled"):+ from services.workspace_task_history import serialize+ return serialize(record)raise NodeUserError("This Workspace task was not found") from Noneraise NodeUserError("Workflow engine is temporarily unavailable") from Noneif result.get("status") in ("completed", "failed"):@@ -247,4 +293,9 @@ async def status(principal: str, workflow_id: str, node_id: str, submission_id:result["result"] = await handle.result()except Exception:result["status"] = "failed"+ if record is not None:+ from services.workspace_task_history import task_availability, safe_result+ result.update(await task_availability(database, record.browser_owner_ids))+ if "result" in result:+ result["result"] = safe_result(result["result"])return resultdiff --git a/server/services/plugin/connection.py b/server/services/plugin/connection.pyindex d684825a..840b3b4c 100644--- a/server/services/plugin/connection.py+++ b/server/services/plugin/connection.py@@ -68,6 +68,7 @@ class Connection:return self._clientasync def aclose(self) -> None:+ self._secrets = Noneif self._client is not None:await self._client.aclose()self._client = Nonediff --git a/server/services/plugin/credential.py b/server/services/plugin/credential.pyindex 60ffea63..7d5e94aa 100644--- a/server/services/plugin/credential.py+++ b/server/services/plugin/credential.py@@ -28,7 +28,10 @@ from __future__ import annotationsimport loggingimport timefrom dataclasses import dataclass, field-from typing import Any, ClassVar, Dict, List, Literal, Optional, Sequence+from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Literal, Optional, Sequence++if TYPE_CHECKING:+ from pathlib import Pathimport httpx@@ -110,7 +113,7 @@ def classify_credential_error(exc: BaseException, *, display_name: str) -> Probe# is still useful, but don't dump a stacktrace into the user's toast.return ProbeResult(valid=False,- message=f"Could not validate {display_name}: {type(exc).__name__}: {exc}",+ message=f"Could not validate {display_name}: {type(exc).__name__}.",)@@ -277,7 +280,22 @@ class Credential:from core.container import containerfrom services.status_broadcaster import get_status_broadcaster- api_key = (data.get("api_key") or "").strip()+ source = data.get("credential_source")+ auth_service = container.auth_service()+ reference = None+ if source == "onepassword":+ from services.credentials.onepassword import CredentialSourceError, read_secret, validate_reference+ try:+ if cls.auth != "api_key" or getattr(cls, "extra_fields", ()):+ raise CredentialSourceError("unsupported_source", "This connection does not support static 1Password credentials.")+ await auth_service.get_credential_source(cls.id, data.get("session_id", "default"), principal=data.get("_principal"))+ reference = validate_reference(data.get("reference"))+ api_key = await read_secret(reference, auth_service.settings)+ except CredentialSourceError as exc:+ return {"success": False, "valid": False, "error": str(exc), "code": exc.code}+ else:+ auth_service.require_local_credentials()+ api_key = (data.get("api_key") or "").strip()session_id = data.get("session_id", "default")if not api_key:return {@@ -297,17 +315,30 @@ class Credential:result.message,)- broadcaster = get_status_broadcaster()- auth_service = container.auth_service()+ if reference is not None:+ # Upstream validators may echo request fields in successful+ # metadata. Never persist or broadcast an echoed secret.+ def contains_secret(value):+ if isinstance(value, str):+ return api_key in value+ if isinstance(value, dict):+ return any(contains_secret(key) or contains_secret(item) for key, item in value.items())+ if isinstance(value, (list, tuple)):+ return any(contains_secret(item) for item in value)+ return False+ if contains_secret({"models": result.models, "params": result.model_params, "extra": result.extra}):+ result = ProbeResult(valid=False, message="The provider returned unsafe credential metadata.")+ result.message = result.message.replace(api_key, "[credential]")+ broadcaster = get_status_broadcaster()if result.valid:- await auth_service.store_api_key(- provider=cls.id,- api_key=api_key,- models=result.models,- session_id=session_id,- model_params=result.model_params,- )+ if reference is not None:+ await auth_service.store_credential_source(cls.id, reference, principal=data["_principal"], models=result.models, session_id=session_id, model_params=result.model_params)+ else:+ await auth_service.store_api_key(+ provider=cls.id, api_key=api_key, models=result.models,+ session_id=session_id, model_params=result.model_params,+ )await broadcaster.update_api_key_status(provider=cls.id,@@ -341,7 +372,7 @@ class Credential:raise NotImplementedError(f"Credential subclass {cls.__name__} must override _probe()")@classmethod- async def catalogue_extras(cls) -> Optional[Dict[str, Any]]:+ async def catalogue_extras(cls, *, principal: Optional[str] = None) -> Optional[Dict[str, Any]]:"""Extra catalogue fields computed from stored state, or ``None``.``handle_get_credential_catalogue`` merges the result into this@@ -465,7 +496,7 @@ class ApiKeyCredential(Credential):from core.container import containerauth_service = container.auth_service()- api_key = await auth_service.get_api_key(cls.id)+ api_key = await auth_service.resolve_api_key(cls.id, principal=user_id)if not api_key:err = PermissionError(f"No API key for '{cls.id}'. Add via Credentials modal.")err.provider = cls.id@@ -473,10 +504,10 @@ class ApiKeyCredential(Credential):err.auth = cls.auth # "api_key"raise errsecrets: Dict[str, Any] = {"api_key": api_key}- for field in cls.extra_fields:- value = await auth_service.get_api_key(field)+ for field_name in cls.extra_fields:+ value = await auth_service.resolve_api_key(field_name, principal=user_id)if value:- secrets[field] = value+ secrets[field_name] = valuereturn secrets@classmethoddiff --git a/server/services/process_environment.py b/server/services/process_environment.pynew file mode 100644index 00000000..24c902e9--- /dev/null+++ b/server/services/process_environment.py@@ -0,0 +1,17 @@+"""Environment containment for ordinary application child processes."""++from __future__ import annotations++import os+from collections.abc import Mapping+++def without_onepassword_environment(env: Mapping[str, str] | None = None) -> dict[str, str]:+ """Copy the final environment without 1Password bootstrap/auth variables.++ Call after overrides and additions, at the spawn boundary. A missing+ environment keeps ordinary ambient inheritance. The private credential+ resolver supplies its own separately restricted environment.+ """+ source = os.environ if env is None else env+ return {key: value for key, value in source.items() if not key.upper().startswith("OP_")}diff --git a/server/services/process_service.py b/server/services/process_service.pyindex 1bc0d35d..3c27d277 100644--- a/server/services/process_service.py+++ b/server/services/process_service.py@@ -22,6 +22,7 @@ from typing import Any, Awaitable, Callable, Dict, List, Optionalfrom core.ansi import strip_ansifrom core.logging import get_loggerfrom services._supervisor.util import kill_tree+from services.process_environment import without_onepassword_environmentlogger = get_logger(__name__)@@ -146,8 +147,9 @@ class ProcessService:"error": (f"Command not found: '{argv[0] if argv else ''}'. " "Check spelling or ensure the binary is on PATH."),}argv[0] = resolved- env = {**os.environ, **(extra_env or {}), "PYTHONUNBUFFERED": "1"}- requested_ports = self._requested_ports(argv, ports or [], extra_env or {})+ safe_extra_env = without_onepassword_environment(extra_env or {})+ env = without_onepassword_environment({**os.environ, **safe_extra_env, "PYTHONUNBUFFERED": "1"})+ requested_ports = self._requested_ports(argv, ports or [], safe_extra_env)from core.config import Settingsfrom core.paths import daemons_dir@@ -249,7 +251,7 @@ class ProcessService:log_dir=log_dir,line_handler=line_handler,ports=tuple(requested_ports),- extra_env=dict(extra_env or {}),+ extra_env=safe_extra_env,)managed.stdout_task = asyncio.create_task(self._read_stream(managed, proc.stdout, "stdout"), name=f"proc-stdout-{name}",diff --git a/server/services/proxy/service.py b/server/services/proxy/service.pyindex 0cdf76fa..bf9e4603 100644--- a/server/services/proxy/service.py+++ b/server/services/proxy/service.py@@ -404,8 +404,8 @@ class ProxyService:# Load credentials from AuthServicecred_key = f"proxy_{config.name}"- username = await self._auth_service.get_api_key(f"{cred_key}_username")- password = await self._auth_service.get_api_key(f"{cred_key}_password")+ username = await self._auth_service.resolve_api_key(f"{cred_key}_username")+ password = await self._auth_service.resolve_api_key(f"{cred_key}_password")if username and password:runtime.username = usernameruntime.password = passworddiff --git a/server/services/rlm/adapters.py b/server/services/rlm/adapters.pyindex 8f16d661..e4d67ff9 100644--- a/server/services/rlm/adapters.py+++ b/server/services/rlm/adapters.py@@ -74,7 +74,7 @@ class ChatModelExtractor:api_key = params.get("api_key")if not api_key and auth:- api_key = await auth.get_api_key(provider)+ api_key = await auth.resolve_api_key(provider)if not api_key:logger.warning(f"[RLM] Skipping chat model node {node_type}: no API key")continuediff --git a/server/services/rlm/service.py b/server/services/rlm/service.pyindex 3dd54a4c..d22501a5 100644--- a/server/services/rlm/service.py+++ b/server/services/rlm/service.py@@ -108,7 +108,7 @@ class RLMService:model = await get_default_model_async(provider, database)if not api_key and self.auth:- api_key = await self.auth.get_api_key(provider)+ api_key = await self.auth.resolve_api_key(provider)if not api_key:raise ValueError(f"API key required for RLM Agent (provider: {provider})")diff --git a/server/services/settings/handlers.py b/server/services/settings/handlers.pyindex 5a7887c7..7d4c91aa 100644--- a/server/services/settings/handlers.py+++ b/server/services/settings/handlers.py@@ -137,6 +137,8 @@ async def handle_get_validated_ai_providers(auth_service = container.auth_service()database = container.database()+ from services.authz.ws_surface import execution_principal+ principal = execution_principal({}, websocket)from services.llm.config import PROVIDER_CONFIGS@@ -151,11 +153,10 @@ async def handle_get_validated_ai_providers(providers = []for provider in AI_PROVIDERS:- api_key = await auth_service.get_api_key(provider, data.get("session_id", "default"))- if not api_key:+ if not await auth_service.has_valid_key(provider, data.get("session_id", "default"), principal=principal):continue- stored_models = await auth_service.get_stored_models(provider, data.get("session_id", "default"))+ stored_models = await auth_service.get_stored_models(provider, data.get("session_id", "default"), principal=principal)provider_config = llm_defaults.get("providers", {}).get(provider, {})default_model = provider_config.get("default_model", "")@@ -187,7 +188,7 @@ async def handle_get_validated_ai_providers(# key, so the loop above already skipped it.from services.llm.endpoints import list_endpoints- for endpoint in await list_endpoints(auth_service):+ for endpoint in await list_endpoints(auth_service, principal=principal):endpoint_defaults = await database.get_provider_defaults(endpoint.ref)providers.append({diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.pyindex 2a4de622..0e5d8a6b 100644--- a/server/services/status_broadcaster.py+++ b/server/services/status_broadcaster.py@@ -225,13 +225,16 @@ class StatusBroadcaster:for exc in eg.exceptions:logger.warning("[StatusBroadcaster] Service refresh task failed: %s", exc)- async def broadcast(self, message: Dict[str, Any]):+ async def broadcast(self, message: Dict[str, Any], *, shared: bool = True):"""Broadcast a message to all connected clients using TaskGroup.Uses asyncio.TaskGroup (Python 3.11+) for structured concurrency:- All tasks complete or cancel together- Proper exception handling via ExceptionGroup"""+ if shared and message.get("type") in {"browser_updated", "browser_profiles_updated"}:+ from services.distributed_notifications import publish+ await publish(message)if not self._connections:returndiff --git a/server/services/temporal/_retry_policies.py b/server/services/temporal/_retry_policies.pyindex 882799d4..7748c047 100644--- a/server/services/temporal/_retry_policies.py+++ b/server/services/temporal/_retry_policies.py@@ -40,6 +40,7 @@ Refsfrom __future__ import annotationsfrom datetime import timedelta+from typing import Any, Mappingfrom temporalio.common import RetryPolicy@@ -131,6 +132,24 @@ PERMIT_WAIT_RETRY: RetryPolicy = RetryPolicy()+def frozen_retry_policy(retry: Mapping[str, Any]) -> RetryPolicy:+ """Rebuild a tool plugin's retry policy from the values frozen into history.++ ``agent_activities._tool_activity_policy`` records the plugin's declared+ policy as plain numbers when the payload is prepared, so a replay never+ consults plugin code that may have changed since. Workflow code turns+ those numbers back into a ``RetryPolicy`` here instead of constructing+ one inline, which keeps every policy a workflow schedules in this module.+ """+ return RetryPolicy(+ initial_interval=timedelta(seconds=retry["initial_interval_seconds"]),+ backoff_coefficient=retry["backoff_coefficient"],+ maximum_interval=timedelta(seconds=retry["maximum_interval_seconds"]),+ maximum_attempts=retry["maximum_attempts"],+ non_retryable_error_types=retry["non_retryable_error_types"],+ )++__all__ = ["NON_RETRYABLE_ERROR_TYPES","DEFAULT_ACTIVITY_RETRY",@@ -138,4 +157,5 @@ __all__ = ["LLM_STEP_RETRY","DELEGATION_CLEANUP_RETRY","PERMIT_WAIT_RETRY",+ "frozen_retry_policy",]diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex ae53b69a..7c32e2a0 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -84,6 +84,30 @@ def _tool_activity_policy(cls: Any) -> Dict[str, Any]:},}++async def _freeze_browser_tools(database, tools: list[dict], context: dict, *, browser_agent: bool = False) -> tuple[dict, int]:+ """Record owner destinations and plugin policies at an Activity boundary."""+ from core.config import Settings+ from services.node_registry import get_node_class+ bindings = dict(context.get("browser_bindings") or {})+ enabled = browser_agent or context.get("browser_routing_version") == 1 or context.get("browser_runtime_version") == 1 or getattr(Settings(), "distributed_mode", False) is True+ version = 0+ if enabled:+ from services.browser_owners import routing_for_node+ for tool in tools:+ if tool.get("node_type") != "browser":+ continue+ node_id = tool["tool_node_id"]+ binding = bindings.get(node_id)+ if binding is None:+ binding = await routing_for_node(database, str(context.get("workflow_id") or ""), node_id, str(context.get("user_id") or "owner"))+ bindings[node_id] = binding+ policy = tool.setdefault("activity_policy", _tool_activity_policy(get_node_class("browser")))+ if binding.get("task_queue"):+ policy.update(task_queue=binding["task_queue"], owner_routing=True)+ version = 1+ return bindings, version+# Activity result shapes — keep these in sync with AgentWorkflow's# expectations. Pydantic was considered but plain dicts keep the# payload-serialisation cost flat (Temporal serialises via JSON anyway)@@ -153,17 +177,37 @@ async def _resolve_activity_api_key(payload: Dict[str, Any]) -> str:keep a key in their own configuration instead of the credential service."""- recorded = payload.get("api_key")- if isinstance(recorded, str) and recorded:- return recorded-from core.container import container+ recorded = payload.get("api_key")provider = str(payload.get("provider") or "")auth = container.auth_service()- api_key = await auth.get_api_key(provider)+ if isinstance(recorded, str) and recorded:+ if getattr(auth, "distributed_credentials", False) is True:+ raise ApplicationError("Distributed execution requires a saved 1Password credential", type="NodeUserError", non_retryable=True)+ return recorded+ scope = {"principal": str(payload["user_id"])} if payload.get("user_id") else {}+ if not scope and payload.get("workflow_id"):+ # Histories predating principal fields can still resolve a newly+ # configured binding under their saved workflow owner's authority.+ saved = await container.database().get_workflow(str(payload["workflow_id"]))+ graph = getattr(saved, "data", None) if saved is not None else None+ if graph is None and isinstance(saved, dict):+ graph = saved.get("data", saved)+ scope = {"principal": str((graph or {}).get("owner_id") or "owner")}+ if getattr(auth, "distributed_credentials", False) is True:+ if recorded:+ raise ApplicationError("Distributed execution requires a saved 1Password credential", type="NodeUserError", non_retryable=True)+ api_key = await auth.resolve_api_key(provider, **scope)+ if not api_key:+ api_key = await auth.resolve_api_key(f"{provider}_api_key", **scope)+ if not api_key:+ raise _unsaved_endpoint_error(provider) or ApplicationError("Configure the provider's 1Password credential", type="MissingAgentProviderCredential", non_retryable=True)+ return str(api_key)+ resolve = getattr(auth, "resolve_api_key", auth.get_api_key)+ api_key = await resolve(provider, **scope)if not api_key:- api_key = await auth.get_api_key(f"{provider}_api_key")+ api_key = await resolve(f"{provider}_api_key", **scope)if not api_key and payload.get("node_id"):database = container.database()@@ -1086,6 +1130,18 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:connection_database = ParameterSnapshotDatabase(database, snapshot)db_params = snapshot.get(node_id) if node_id in snapshot else await database.get_node_parameters(node_id) or {}parameters = {**(context.get("node_data") or {}), **db_params}+ if node_type == "browser_agent":+ from services.browser_agent_recipe import BROWSER_AGENT_ROLE+ # Delegation's compatibility remap puts its mission in node_data's+ # system field. Only saved Browser configuration defines this role.+ if context.get("invocation"):+ parameters["system_message"] = db_params.get("system_message") or BROWSER_AGENT_ROLE+ else:+ parameters["system_message"] = parameters.get("system_message") or BROWSER_AGENT_ROLE+ from core.config import Settings as _PreflightSettings+ if getattr(_PreflightSettings(), "distributed_mode", False) is True:+ from services.credentials.preflight import assert_cluster_credentials+ await assert_cluster_credentials(database, {"nodes": context.get("nodes") or [], "edges": context.get("edges") or []}, context)from services.employees.team_runtime import employee_runtime_planemployee_plan = await employee_runtime_plan(database, context)if employee_plan:@@ -1129,8 +1185,14 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:# ``prompt`` can never clobber the delegated task.invocation = context.get("invocation") or {}if invocation.get("task") or invocation.get("context"):- system_message = invocation.get("task") or "You are a helpful assistant"- prompt = invocation.get("context") or invocation.get("task") or ""+ if node_type == "browser_agent":+ # A Browser Agent keeps its saved role and safety instructions.+ prompt = "\n\n".join(str(invocation[key]) for key in ("task", "context") if invocation.get(key))+ else:+ system_message = invocation.get("task") or "You are a helpful assistant"+ prompt = invocation.get("context") or invocation.get("task") or ""+ if context.get("native_workspace_version") == 1 and "workspace_task_prompt" in context:+ prompt = context["workspace_task_prompt"]api_key = flattened.get("api_key")provider = parameters.get("provider", "openai")@@ -1144,7 +1206,14 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:if not api_key:# Try auth_service one more time (covers chatAgent flow where# node params don't carry the api_key directly).- api_key = await auth.get_api_key(provider) or await auth.get_api_key(f"{provider}_api_key")+ if node_type == "browser_agent" or context.get("native_workspace_version") == 1 or context.get("browser_routing_version") == 1:+ principal = str(context.get("user_id") or "owner")+ source = await auth.get_credential_source(provider, principal=principal)+ if not source:+ source = await auth.get_credential_source(f"{provider}_api_key", principal=principal)+ api_key = bool(source) or await auth.has_valid_key(provider) or await auth.has_valid_key(f"{provider}_api_key")+ else:+ api_key = await auth.has_valid_key(provider) or await auth.has_valid_key(f"{provider}_api_key")if not api_key:endpoint_error = _unsaved_endpoint_error(provider)if endpoint_error:@@ -1210,6 +1279,10 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:connection_database,log_prefix=f"[AgentWorkflow:{node_type}]",)+ if context.get("native_workspace_version") == 1:+ # Direct tasks have their own transcript. A connected trigger or legacy+ # memory from employee chat must not steer this independent invocation.+ input_data, task_data, memory_data = {}, None, None# taskTrigger may be wired to input-task (task_data) or input-main# (input_data). In both cases preserve the CloudEvent payload as invokable@@ -1455,7 +1528,9 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:# through the workflow verbatim so ``execute_llm_step`` can# rebuild the real StructuredTool inside the activity."tool_info": tool_info,- **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))} if context.get("execution_control_version") == 1 else {}),+ **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))}+ if context.get("execution_control_version") == 1 or context.get("native_workspace_version") == 1+ or context.get("browser_routing_version") == 1 or node_type == "browser_agent" else {}),# Team leads create and dispatch durable work through Task# Manager. Delegate descriptors stay in workflow state for# trusted assignee resolution, but are not callable directly@@ -1609,7 +1684,14 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:else:user_images = []- return {+ if context.get("native_workspace_version") == 1 and "workspace_task_prompt" in context:+ prompt = context["workspace_task_prompt"]++ browser_bindings, browser_runtime_version = await _freeze_browser_tools(database, tools_payload, context, browser_agent=node_type == "browser_agent")+ if node_type == "browser_agent" and len([tool for tool in tools_payload if tool.get("node_type") == "browser"]) != 1:+ raise ApplicationError("Connect one enabled Browser tool", type="NodeUserError", non_retryable=True)++ prepared = {# The chat run this agent works for (stops when the owner presses# Stop), and, for the agent that answers it, where its text streams."chat_run_id": chat_run_id_of(context),@@ -1619,6 +1701,8 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:"workflow_id": workflow_id,"session_id": session_id,"parameter_snapshot": snapshot,+ "browser_bindings": browser_bindings,+ "browser_runtime_version": browser_runtime_version,"employee_job_id": context.get("employee_job_id"),"employee_team_plan": employee_plan,"employee_runtime_delivery": bool(employee_plan and node_id == employee_plan.get("lead_node_id")),@@ -1659,6 +1743,9 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:or ""),}+ if browser_runtime_version == 1 or context.get("native_workspace_version") == 1:+ return _strip_credentials(prepared)+ return prepared@activity.defn(name="agent.refresh_tools")@@ -1758,7 +1845,9 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:"tool_node_id": tool_info["node_id"],"parameters": tool_info["parameters"],"tool_info": tool_info,- **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))} if payload.get("execution_control_version") == 1 else {}),+ **({"activity_policy": _tool_activity_policy(cls), "needs_canvas": bool(getattr(cls, "needs_canvas", False))}+ if payload.get("execution_control_version") == 1 or payload.get("native_workspace_version") == 1+ or payload.get("browser_runtime_version") == 1 or payload.get("browser_routing_version") == 1 else {}),"llm_hidden": bool(team_lead_refresh and is_agent_delegate),})@@ -1776,7 +1865,12 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:parameter_updates[str(identifier)] = await database.get_node_parameters(str(identifier)) or {}old_snapshot = payload.get("graph_snapshot") or {}runtime_graph = extend_runtime_graph(old_snapshot, graph, operations) if old_snapshot else graph- return {"tools": new_tools_payload, "graph_snapshot": runtime_graph, "parameter_updates": parameter_updates}+ result = {"tools": new_tools_payload, "graph_snapshot": runtime_graph, "parameter_updates": parameter_updates}+ if payload.get("browser_runtime_version") == 1 or payload.get("browser_routing_version") == 1:+ bindings, version = await _freeze_browser_tools(database, new_tools_payload, payload)+ result.update(browser_bindings=bindings, browser_runtime_version=version)+ return _strip_credentials(result)+ return result@activity.defn(name="agent.skill.invoke")diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex b1cd746e..093d71b5 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -64,6 +64,7 @@ from ._retry_policies import (DELEGATION_CLEANUP_RETRY,LLM_STEP_RETRY,PERMIT_WAIT_RETRY,+ frozen_retry_policy,)from .agent_context_pressure import (clear_old_tool_results,@@ -112,7 +113,8 @@ async def _execute_plugin_tool_activity("heartbeat_timeout": TOOL_HEARTBEAT_TIMEOUT,}policy = (tool_info or {}).get("activity_policy")- if context.get("execution_control_version") == 1 and policy:+ if (context.get("execution_control_version") == 1 or context.get("native_workspace_version") == 1+ or context.get("browser_runtime_version") == 1 or context.get("browser_routing_version") == 1) and policy:options = _frozen_tool_activity_options(policy, context)tool_payload = {**tool_payload, **_inherited_scope(context), "user_id": str(context.get("user_id") or "owner")}else:@@ -141,16 +143,10 @@ def _frozen_tool_activity_options(policy: Dict[str, Any], context: Dict[str, Anyoptions: Dict[str, Any] = {"start_to_close_timeout": timedelta(seconds=policy["start_to_close_seconds"]),"heartbeat_timeout": (timedelta(seconds=policy["heartbeat_seconds"]) if policy.get("heartbeat_seconds") else None),- "retry_policy": RetryPolicy(- initial_interval=timedelta(seconds=retry["initial_interval_seconds"]),- backoff_coefficient=retry["backoff_coefficient"],- maximum_interval=timedelta(seconds=retry["maximum_interval_seconds"]),- maximum_attempts=retry["maximum_attempts"],- non_retryable_error_types=retry["non_retryable_error_types"],- ),+ "retry_policy": frozen_retry_policy(retry),"cancellation_type": ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,}- if context.get("temporal_worker_pool_enabled") is True:+ if context.get("temporal_worker_pool_enabled") is True or policy.get("owner_routing") is True:options["task_queue"] = policy["task_queue"]return options@@ -309,6 +305,11 @@ _INHERITED_SCOPE_KEYS = ("controller_workflow_id","execution_control_state","execution_control_revision",+ "native_workspace_version",+ "browser_routing_version",+ "browser_runtime_version",+ "browser_bindings",+ "_browser_task_id",)@@ -331,9 +332,14 @@ _CAN_TRANSCRIPT_MAX_BYTES = 1_000_000_CAN_INPUT_MAX_BYTES = 1_900_000-def _inherited_scope(context: Dict[str, Any]) -> Dict[str, Any]:+def _inherited_scope(context: Dict[str, Any], *, delegation: bool = False) -> Dict[str, Any]:"""Return the scope keys a delegated child must inherit from its parent."""- return {key: context[key] for key in _INHERITED_SCOPE_KEYS if key in context}+ inherited = {key: context[key] for key in _INHERITED_SCOPE_KEYS if key in context}+ if delegation:+ # A child owns its own task lifetime. Siblings must not accidentally+ # share a parent's claim token or release its still-active profile.+ inherited.pop("_browser_task_id", None)+ return inheriteddef _child_control_scope(control: ExecutionControl) -> Dict[str, Any]:@@ -669,6 +675,8 @@ class AgentWorkflow:def __init__(self, context: Dict[str, Any] = None) -> None:self._control_paused = Falseself._execution_control = ExecutionControl()+ self._browser_claims = []+ self._continuing = Falseif context is not None:self._execution_control.bind(context)@@ -707,6 +715,28 @@ class AgentWorkflow:if self._control_paused:await workflow.wait_condition(lambda: not self._control_paused)+ async def _claim_browser_tools(self, context: dict, tools: list[dict]) -> None:+ context.setdefault("_browser_task_id", workflow.info().workflow_id)+ seen_profiles = {binding["profile_id"] for binding in self._browser_claims}+ for tool in tools:+ if tool.get("node_type") != "browser":+ continue+ binding = context["browser_bindings"][tool["tool_node_id"]]+ if binding["profile_id"] in seen_profiles:+ continue+ seen_profiles.add(binding["profile_id"])+ self._browser_claims.append(binding)+ claim = await workflow.execute_activity(+ "browser_tasks.claim",+ {"binding": binding, "principal": str(context.get("user_id") or "owner"), "task_id": context["_browser_task_id"]},+ task_queue=binding.get("task_queue") or workflow.info().task_queue,+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=1),+ cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,+ )+ if isinstance(claim, dict) and isinstance(claim.get("binding"), dict):+ binding.update(claim["binding"])+@workflow.runasync def run(self, context: Dict[str, Any] = None) -> Dict[str, Any]:self._execution_control.bind(context)@@ -730,6 +760,21 @@ class AgentWorkflow:await fail_job(cancelled=is_cancelled_exception(exc))raisefinally:+ if not self._continuing:+ for binding in reversed(self._browser_claims):+ async def release(binding=binding):+ await workflow.execute_activity(+ "browser_tasks.release",+ {"binding": binding, "task_id": context["_browser_task_id"]},+ task_queue=binding.get("task_queue") or workflow.info().task_queue,+ start_to_close_timeout=timedelta(seconds=120),+ heartbeat_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=0),+ cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,+ )+ # Owner absence leaves cleanup queued. Cancel/Reset wait for+ # its receipt instead of releasing another task's claim.+ await asyncio.shield(asyncio.create_task(release()))if self._execution_control.enabled:await workflow.wait_condition(workflow.all_handlers_finished)@@ -814,7 +859,8 @@ class AgentWorkflow:# DB lookups + edge walking + tool schema build happen here, NOT# in the workflow body (workflows must be deterministic).resume = dict(context.get(_RESUME_MARKER) or {})- if self._execution_control.enabled and resume.get("prepared_payload"):+ durable_runtime = self._execution_control.enabled or context.get("native_workspace_version") == 1 or context.get("browser_runtime_version") == 1 or context.get("browser_routing_version") == 1+ if durable_runtime and resume.get("prepared_payload"):payload = dict(resume["prepared_payload"])else:async with self._execution_control.action():@@ -825,6 +871,11 @@ class AgentWorkflow:start_to_close_timeout=PERSIST_TURN_TIMEOUT * 2,retry_policy=AGENT_ACTIVITY_RETRY,)+ if payload.get("browser_runtime_version") == 1:+ context["browser_runtime_version"] = 1+ context["browser_bindings"] = payload.get("browser_bindings") or {}+ durable_runtime = True+ await self._claim_browser_tools(context, payload.get("tools") or [])# Stable per-run execution id, forwarded into every tool-call# activity so session-keyed nodes (browser) reuse one instance# across iterations instead of minting a fresh uuid per call@@ -972,7 +1023,8 @@ class AgentWorkflow:info = tool_index.get(name)return tool_output_is_capped(info.get("node_type") if info else None)- thinking_accumulated = str(resume.get("thinking") or "") if self._execution_control.enabled else ""+ thinking_accumulated = str(resume.get("thinking") or "") if durable_runtime else ""+ browser_artifacts = list(resume.get("browser_artifacts") or []) if durable_runtime else []final_content: Optional[str] = None# Billing/observability is cumulative for the entire execution and# survives continue_as_new via the resume marker — the final result@@ -1072,6 +1124,8 @@ class AgentWorkflow:else {}),}+ if context.get("native_workspace_version") == 1 or context.get("browser_runtime_version") == 1 or context.get("browser_routing_version") == 1:+ llm_payload["user_id"] = str(context.get("user_id") or "owner")async with self._execution_control.action():# Transient provider failures (429 rate limit, 5xx, network)@@ -1091,7 +1145,8 @@ class AgentWorkflow:)except Exception as e:from temporalio.exceptions import is_cancelled_exception- if getattr(self, "_employee_runtime_v2", False) and is_cancelled_exception(e):+ if (getattr(self, "_employee_runtime_v2", False) or context.get("native_workspace_version") == 1+ or context.get("browser_runtime_version") == 1) and is_cancelled_exception(e):raise asyncio.CancelledError() from ecause = getattr(e, "cause", None)raw_detail = str(cause) if cause is not None else str(e)@@ -1411,7 +1466,7 @@ class AgentWorkflow:)child_context = {# Inherited scope first: explicit keys below win.- **_inherited_scope(context),+ **_inherited_scope(context, delegation=True),**_child_control_scope(self._execution_control),"node_id": candidate_tool["tool_node_id"],"node_type": candidate_tool["node_type"],@@ -1663,7 +1718,7 @@ class AgentWorkflow:context_text = request_context if isinstance(request_context, str) else _serialise_tool_result(request_context)child_context = {# Inherited scope first: explicit keys below win.- **_inherited_scope(context),+ **_inherited_scope(context, delegation=True),**_child_control_scope(self._execution_control),"node_id": assignee_id, "node_type": delegate["node_type"],"node_data": {**(delegate.get("parameters") or {}),@@ -2012,6 +2067,9 @@ class AgentWorkflow:else {}),}+ binding = (context.get("browser_bindings") or {}).get(tool_info["tool_node_id"])+ if tool_info["node_type"] == "browser" and binding:+ tool_payload.update(_browser_owner=binding, _browser_task_id=context["_browser_task_id"])if workflow.patched("employee-task-manager-tool-scope-v2"):tool_payload = {**_trusted_tool_scope(context), **tool_payload}@@ -2190,6 +2248,15 @@ class AgentWorkflow:"requires_user_action": True,"retryable": False,}+ if durable_runtime and tool_info.get("node_type") == "browser" and isinstance(tool_result, dict):+ from services.workspace_task_history import safe_result+ browser_output = tool_result.get("result") if isinstance(tool_result.get("result"), dict) else tool_result+ screenshot = browser_output.get("screenshot")+ if isinstance(screenshot, dict):+ refs = safe_result({"artifacts": [screenshot]}).get("artifacts") or []+ for ref in refs:+ if not any(existing.get("path") == ref.get("path") for existing in browser_artifacts) and len(browser_artifacts) < 32:+ browser_artifacts.append(ref)tool_content = _serialise_tool_result(tool_result)if (tool_output_limit@@ -2250,6 +2317,9 @@ class AgentWorkflow:**call_metadata,**({"execution_control_version": 1} if self._execution_control.enabled else {}),}+ if context.get("browser_runtime_version") == 1 or context.get("browser_routing_version") == 1:+ refresh_payload.update({key: context[key] for key in ("browser_runtime_version", "browser_routing_version", "browser_bindings", "user_id") if key in context})+ refresh_payload["workflow_id"] = payload.get("workflow_id")if binding_refresh_v2:refresh_payload["bound_node_ids"] = [tool.get("tool_node_id") for tool in tools if tool.get("tool_node_id")]refresh_payload["graph_snapshot"] = {"nodes": context.get("nodes") or [], "edges": context.get("edges") or []}@@ -2308,6 +2378,12 @@ class AgentWorkflow:},)added_tools = []+ if added_tools and refresh_result.get("browser_bindings"):+ context["browser_bindings"] = {**(context.get("browser_bindings") or {}), **refresh_result["browser_bindings"]}+ if refresh_result.get("browser_runtime_version") == 1:+ context["browser_runtime_version"] = 1+ durable_runtime = True+ await self._claim_browser_tools(context, added_tools)for new_tool in added_tools:tools.append(new_tool)tool_index[new_tool["name"]] = new_tool@@ -2331,6 +2407,10 @@ class AgentWorkflow:await _cleanup_cancelled_delegations()raiseexcept Exception as e: # noqa: BLE001 — Temporal handles retries+ from temporalio.exceptions import is_cancelled_exception+ if (context.get("native_workspace_version") == 1 or context.get("browser_runtime_version") == 1) and is_cancelled_exception(e):+ await _cleanup_cancelled_delegations()+ raise asyncio.CancelledError() from e# After all retries exhausted, surface the error to# the LLM (per user decision: LLM sees error and# continues — matches the in-process agent loop).@@ -2567,6 +2647,8 @@ class AgentWorkflow:"provider": payload["provider"],"model": payload["model"],}+ if context.get("native_workspace_version") == 1 or context.get("browser_runtime_version") == 1 or context.get("browser_routing_version") == 1:+ compact_payload["user_id"] = str(context.get("user_id") or "owner")await self._wait_until_resumed()async with self._execution_control.action():try:@@ -2738,7 +2820,7 @@ class AgentWorkflow:delegation_handles or task_manager_delegation_tasks)if not delegations_live:- if self._execution_control.enabled:+ if durable_runtime:# A stopped workflow remains in this run. No live child# handle or unfinished Update crosses the boundary.await self._wait_until_resumed()@@ -2755,6 +2837,7 @@ class AgentWorkflow:"prepared_payload": payload,"tools": tools,"thinking": thinking_accumulated,+ "browser_artifacts": browser_artifacts,},}# Measure the converter's complete argument, including@@ -2767,6 +2850,7 @@ class AgentWorkflow:f"Agent continuation requires {input_bytes} bytes; limit is {_CAN_INPUT_MAX_BYTES}. Reduce tool output or enable context compaction.",type="AgentContinuationTooLarge", non_retryable=True,)+ self._continuing = Trueworkflow.continue_as_new(args=[next_context])# The live transcript crosses the boundary directly.# Compaction keeps it token-bounded; the byte guard@@ -2823,6 +2907,8 @@ class AgentWorkflow:"execution_id": context.get("execution_id"),"root_execution_id": root_execution_id,}+ if browser_artifacts:+ result_payload["artifacts"] = browser_artifacts# Persist the result to the OutputStore via the workflow_service# so ParameterResolver can resolve {{aiAgent.response}} indiff --git a/server/services/temporal/browser_task_activities.py b/server/services/temporal/browser_task_activities.pynew file mode 100644index 00000000..79885adc--- /dev/null+++ b/server/services/temporal/browser_task_activities.py@@ -0,0 +1,40 @@+"""Private owner operations and safe Workspace lifecycle projections."""++from temporalio import activity++[email protected](name="workspace_tasks.admit_record")+async def admit_task_record(payload: dict) -> dict:+ from services.plugin.deps import get_database+ from services.workspace_task_history import admit+ from temporalio.exceptions import ApplicationError+ try:+ return await admit(get_database(), payload)+ except ValueError:+ raise ApplicationError("Submission ID was already used for a different task",+ type="WorkspaceSubmissionConflict", non_retryable=True) from None++[email protected](name="workspace_tasks.update_record")+async def update_task_record(payload: dict) -> None:+ from services.plugin.deps import get_database+ from services.workspace_task_history import transition+ await transition(get_database(), payload)++[email protected](name="browser_tasks.claim")+async def claim_browser_task_activity(payload: dict) -> dict:+ from services.browser_owners import claim_browser_task+ from services.plugin.deps import get_database+ return await claim_browser_task(get_database(), payload["binding"], payload["principal"], payload["task_id"])++[email protected](name="browser_tasks.release")+async def release_browser_task_activity(payload: dict) -> dict:+ from services.browser_owners import cleanup_browser_task+ from services.plugin.deps import get_database+ return await cleanup_browser_task(get_database(), payload["binding"], payload["task_id"])+++HISTORY_ACTIVITIES = [admit_task_record, update_task_record]+BROWSER_OWNER_ACTIVITIES = [claim_browser_task_activity, release_browser_task_activity]diff --git a/server/services/temporal/executor.py b/server/services/temporal/executor.pyindex d632666a..49a3fbe7 100644--- a/server/services/temporal/executor.py+++ b/server/services/temporal/executor.py@@ -47,6 +47,20 @@ def capture_temporal_routing_input() -> Dict[str, Any]:}+async def capture_browser_routing_input(workflow_id: str, nodes: list[dict], user_id: str) -> dict:+ """Resolve distributed Browser destinations before recording workflow input."""+ from core.config import Settings+ if not getattr(Settings(), "distributed_mode", False):+ return {}+ from core.container import container+ from services.browser_owners import routing_for_node+ bindings = {}+ for node in nodes:+ if node.get("type") == "browser" and not (node.get("data") or {}).get("disabled"):+ bindings[node["id"]] = await routing_for_node(container.database(), workflow_id, node["id"], user_id)+ return {"browser_routing_version": 1, "browser_bindings": bindings}++class TemporalExecutor:"""Workflow executor that uses Temporal for durable execution.@@ -131,6 +145,7 @@ class TemporalExecutor:"execution_id": execution_id,"user_id": str(user_id or "owner"),**capture_temporal_routing_input(),+ **await capture_browser_routing_input(workflow_id, nodes, str(user_id or "owner")),}if parameter_snapshot:workflow_payload["parameter_snapshot"] = parameter_snapshotdiff --git a/server/services/temporal/lifecycle.py b/server/services/temporal/lifecycle.pyindex be1a382a..c53fbc59 100644--- a/server/services/temporal/lifecycle.py+++ b/server/services/temporal/lifecycle.py@@ -70,7 +70,10 @@ async def run_temporal_lifecycle(from core.container import containerwrapper = container.temporal_client()- owned = owns_dev_server(settings.temporal_server_address)+ distributed = getattr(settings, "distributed_mode", False)+ if distributed and owns_dev_server(settings.temporal_server_address):+ raise ValueError("Distributed deployment requires an external shared Temporal service")+ owned = owns_dev_server(settings.temporal_server_address) and not distributedif owned:# Same BaseSupervisor singleton pattern as the WhatsApp and# JS-executor runtimes; registering makes lifespan teardown@@ -207,19 +210,33 @@ async def _start_execution_engine(client=client,task_queue=settings.temporal_task_queue,)- await manager.start()+ if getattr(settings, "distributed_mode", False):+ from services.browser_owners import register_browser_owner, replica_id+ from services.temporal.worker import BrowserOwnerWorkerPool+ await register_browser_owner(container.database())+ pool = None+ try:+ await manager.start()+ if getattr(settings, "distributed_mode", False):+ manager._browser_pool = BrowserOwnerWorkerPool(client, replica_id())+ await manager._browser_pool.start()++ # Start specialized queues after framework workflow registration.+ # The Browser owner above is mandatory regardless of this flag.+ if settings.temporal_worker_pool_enabled:+ from services.temporal.worker import TemporalWorkerPool+ pool = TemporalWorkerPool(client=client)+ await pool.start()+ except BaseException:+ # The outer lifecycle retries startup. Do not leave workers polling+ # an abandoned client if one of the later pool constructions fails.+ if pool is not None:+ await pool.stop()+ await manager.stop()+ raiseapp_state.temporal_worker_manager = managercontainer.temporal_client().worker_manager = manager-- # Wave 16: per-queue activity worker pool (default-on since 16.4;- # TEMPORAL_WORKER_POOL_ENABLED=false is the rollback channel).- # Starts AFTER the manager so workflow registration is in place- # before specialised activity workers poll.- if settings.temporal_worker_pool_enabled:- from services.temporal.worker import TemporalWorkerPool-- pool = TemporalWorkerPool(client=client)- await pool.start()+ if pool is not None:app_state.temporal_pool = poollog(f"[Temporal] Worker pool started ({len(pool.queues)} queues)")diff --git a/server/services/temporal/node_invocation.py b/server/services/temporal/node_invocation.pyindex 3388d938..9ca4aa5b 100644--- a/server/services/temporal/node_invocation.py+++ b/server/services/temporal/node_invocation.py@@ -27,25 +27,58 @@ class NodeInvocationWorkflow:self.status = "running"result: dict = {}try:- result = await workflow.execute_activity(- payload["activity"],- payload["context"],- task_queue=payload["task_queue"],- start_to_close_timeout=timedelta(seconds=payload["timeout_s"]),- heartbeat_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=1),- cancellation_type=workflow.ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,- )+ if payload.get("history_version") == 1:+ await self._record_status(payload)+ if payload.get("dispatch_version") == 1 and payload.get("dispatch_kind") == "native_agent":+ result = await workflow.execute_child_workflow(+ "AgentWorkflow", payload["context"],+ id=f"{workflow.info().workflow_id}:agent",+ cancellation_type=workflow.ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED,+ parent_close_policy=workflow.ParentClosePolicy.REQUEST_CANCEL,+ )+ else:+ result = await workflow.execute_activity(+ payload["activity"],+ payload["context"],+ task_queue=payload["task_queue"],+ start_to_close_timeout=timedelta(seconds=payload["timeout_s"]),+ heartbeat_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=1),+ cancellation_type=workflow.ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,+ )self.status = "completed" if result.get("success") else "failed"return resultexcept asyncio.CancelledError:self.status = "cancelled"raise- except Exception:+ except Exception as exc:+ if payload.get("dispatch_version") == 1:+ from temporalio.exceptions import is_cancelled_exception+ if is_cancelled_exception(exc):+ self.status = "cancelled"+ raise asyncio.CancelledError() from exc+ cause = exc+ for _ in range(8):+ if getattr(cause, "cause", None) is None:+ break+ cause = cause.cause+ error_type = "BrowserBusy" if str(getattr(cause, "message", "")).startswith("BrowserBusy") else "BrowserTaskFailed"+ self.metadata["error_type"] = error_type+ self.metadata["detail"] = ("This browser is assigned to another task. Wait for that task to finish."+ if error_type == "BrowserBusy" else "The browser task failed. Check browser status and credentials.")+ result = {"error_type": error_type}self.status = "failed"raisefinally:+ if payload.get("history_version") == 1:+ # Cancellation waits for the attached child and its owner cleanup+ # before this terminal projection is persisted.+ try:+ await asyncio.shield(asyncio.create_task(self._record_status(payload, result)))+ except Exception as exc:+ workflow.logger.warning("Workspace task projection failed: %s", type(exc).__name__)+async def record() -> None:await workflow.execute_activity("workflow_runs.record_completion",@@ -65,3 +98,14 @@ class NodeInvocationWorkflow:# A summary outage must not convert a completed device task into# a failure that a user may replay. Temporal remains authoritative.workflow.logger.warning("Workspace run summary failed: %s", type(exc).__name__)++ async def _record_status(self, payload: dict, result: dict | None = None) -> None:+ await workflow.execute_activity(+ "workspace_tasks.update_record",+ {"invocation_id": workflow.info().workflow_id, "status": self.status, "result": result},+ start_to_close_timeout=timedelta(seconds=30),+ # The UI reads this projection. Keep an idempotent write pending+ # through a database outage rather than leave a task permanently+ # running after its authoritative Temporal execution has ended.+ retry_policy=RetryPolicy(maximum_attempts=0),+ )diff --git a/server/services/temporal/polling_trigger_workflow.py b/server/services/temporal/polling_trigger_workflow.pyindex c8e7872b..8a358c8d 100644--- a/server/services/temporal/polling_trigger_workflow.py+++ b/server/services/temporal/polling_trigger_workflow.py@@ -368,6 +368,8 @@ class PollingTriggerWorkflow:"tenant_id": tenant_id,}frozen_routing = listener_data.get(TEMPORAL_ROUTING_INPUT_KEY)+ if listener_data.get("browser_routing_version") == 1:+ child_payload.update(browser_routing_version=1, browser_bindings=listener_data.get("browser_bindings") or {})if isinstance(frozen_routing, dict):child_payload[TEMPORAL_ROUTING_INPUT_KEY] = dict(frozen_routingdiff --git a/server/services/temporal/trigger_listener_workflow.py b/server/services/temporal/trigger_listener_workflow.pyindex 1b586978..dc04729a 100644--- a/server/services/temporal/trigger_listener_workflow.py+++ b/server/services/temporal/trigger_listener_workflow.py@@ -453,6 +453,8 @@ class TriggerListenerWorkflow:"execution_control_revision", "execution_control_producers_held",) if key in listener_data})frozen_routing = listener_data.get(TEMPORAL_ROUTING_INPUT_KEY)+ if listener_data.get("browser_routing_version") == 1:+ child_payload.update(browser_routing_version=1, browser_bindings=listener_data.get("browser_bindings") or {})if isinstance(frozen_routing, dict):child_payload[TEMPORAL_ROUTING_INPUT_KEY] = dict(frozen_routingdiff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.pyindex 8c2a4d0f..ed373537 100644--- a/server/services/temporal/worker.py+++ b/server/services/temporal/worker.py@@ -159,6 +159,7 @@ class TemporalWorkerManager:self._worker_task: Optional[asyncio.Task] = Noneself._session: Optional[aiohttp.ClientSession] = Noneself._activities: Optional[NodeExecutionActivities] = None+ self._browser_pool = None@propertydef is_running(self) -> bool:@@ -243,7 +244,10 @@ class TemporalWorkerManager:store_node_output_activity,)- per_type = collect_plugin_activities() # no queue filter; all plugins+ per_type = _generic_plugin_activities()+ from services.temporal.browser_task_activities import HISTORY_ACTIVITIES, BROWSER_OWNER_ACTIVITIES+ from core.config import Settings+ local_browser_activities = [] if getattr(Settings(), "distributed_mode", False) is True else BROWSER_OWNER_ACTIVITIESagent_activities = collect_agent_activities()polling_activities = collect_polling_activities()# Plugin-owned workflow classes (e.g. cron's@@ -291,6 +295,8 @@ class TemporalWorkerManager:pause_workflow_on_failure_activity,record_run_completion_activity,reset_workspace_task_runtime,+ *HISTORY_ACTIVITIES,+ *local_browser_activities,*CHAT_RUN_ACTIVITIES,*APPROVAL_ACTIVITIES,store_node_output_activity,@@ -375,9 +381,9 @@ class TemporalWorkerManager:async def stop(self) -> None:"""Stop the Temporal worker and cleanup resources."""- if not self.is_running:- return-+ if self._browser_pool is not None:+ await self._browser_pool.stop()+ self._browser_pool = Nonelogger.info("Stopping Temporal worker")if self._worker_task:@@ -386,6 +392,8 @@ class TemporalWorkerManager:await self._worker_taskexcept asyncio.CancelledError:pass+ except Exception as exc:+ logger.warning("Worker task already failed during shutdown: %s", type(exc).__name__)self._worker_task = None# Close shared session@@ -561,6 +569,9 @@ class TemporalWorkerPool:)activities = collect_plugin_activities(task_queue=queue)+ from core.config import Settings+ if getattr(Settings(), "distributed_mode", False) is True and queue == "browser":+ return Noneif not activities:return Noneconcurrency = self._concurrency_for(queue)@@ -669,6 +680,38 @@ class TemporalWorkerPool:logger.info("[Pool] All workers stopped")+def _generic_plugin_activities() -> list:+ """Generic workers cannot operate process-local browsers in a cluster."""+ from core.config import Settings+ from services.node_registry import registered_node_classes+ from services.temporal.plugin_activities import collect_plugin_activities+ if getattr(Settings(), "distributed_mode", False) is not True:+ return collect_plugin_activities()+ return collect_plugin_activities(include_types=[kind for kind in registered_node_classes() if kind != "browser"])+++class BrowserOwnerWorkerPool(TemporalWorkerPool):+ """The backend alone polls its physical owner queue, independently of pool flags."""++ def __init__(self, client: Client, owner_id: str):+ from services.browser_owners import owner_queue+ super().__init__(client, queues=[owner_queue(owner_id)], default_pool_size=4)++ def _build_queue_worker(self, queue: str) -> Worker:+ from services.temporal.plugin_activities import collect_plugin_activities+ from services.temporal.browser_task_activities import BROWSER_OWNER_ACTIVITIES+ # Filtering by this physical queue would discard the Browser class:+ # its declared logical queue remains "browser".+ return Worker(+ self.client, task_queue=queue,+ activities=[*collect_plugin_activities(include_types=["browser"]), *BROWSER_OWNER_ACTIVITIES],+ max_concurrent_activities=4,+ graceful_shutdown_timeout=_graceful_shutdown_timeout(),+ identity=_worker_identity(queue),+ interceptors=[ObservabilityWorkerInterceptor()],+ )++async def run_standalone_worker(server_address: str | None = None,namespace: str = "default",@@ -738,6 +781,14 @@ async def run_standalone_worker(logger.error(f"Could not connect to Temporal server at {server_address} after 5 attempts")return+ from core.config import Settings+ if getattr(Settings(), "distributed_mode", False) is True:+ # Native provider/preparation Activities use DI directly. The legacy+ # backend bridge alone never initialized their shared database here.+ from core.container import container+ import nodes # noqa: F401 -- populate the native plugin registry+ await container.database().startup()+# Create shared session and activitiessession = await create_shared_session(pool_size)activities = NodeExecutionActivities(session)@@ -765,7 +816,10 @@ async def run_standalone_worker(registered_agent_activities = [*collect_agent_activities(),]- registered_plugin_activities = collect_plugin_activities()+ registered_plugin_activities = _generic_plugin_activities()+ from services.temporal.browser_task_activities import HISTORY_ACTIVITIES, BROWSER_OWNER_ACTIVITIES+ from core.config import Settings+ local_browser_activities = [] if getattr(Settings(), "distributed_mode", False) is True else BROWSER_OWNER_ACTIVITIES# No socket follows a chat here: its events go to the backend's hub.from services.chat.relay import start_relay, stop_relay@@ -786,6 +840,8 @@ async def run_standalone_worker(pause_workflow_on_failure_activity,record_run_completion_activity,reset_workspace_task_runtime,+ *HISTORY_ACTIVITIES,+ *local_browser_activities,*CHAT_RUN_ACTIVITIES,*APPROVAL_ACTIVITIES,store_node_output_activity,@@ -859,7 +915,10 @@ async def create_worker(registered_agent_activities = [*collect_agent_activities(),]- registered_plugin_activities = collect_plugin_activities()+ registered_plugin_activities = _generic_plugin_activities()+ from services.temporal.browser_task_activities import HISTORY_ACTIVITIES, BROWSER_OWNER_ACTIVITIES+ from core.config import Settings+ local_browser_activities = [] if getattr(Settings(), "distributed_mode", False) is True else BROWSER_OWNER_ACTIVITIESreturn Worker(client,@@ -874,6 +933,8 @@ async def create_worker(pause_workflow_on_failure_activity,record_run_completion_activity,reset_workspace_task_runtime,+ *HISTORY_ACTIVITIES,+ *local_browser_activities,*CHAT_RUN_ACTIVITIES,*APPROVAL_ACTIVITIES,store_node_output_activity,diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex 364a009d..1dc25e89 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -113,6 +113,7 @@ AGENT_WORKFLOW_TYPES = frozenset("chatAgent",# Specialized agents (11)"android_agent",+ "browser_agent","coding_agent","web_agent","task_agent",@@ -754,6 +755,11 @@ class MachinaWorkflow:context["temporal_worker_pool_enabled"] = bool(frozen_routing.get("worker_pool_enabled"))+ if workflow_data.get("browser_routing_version") == 1:+ context.update(browser_routing_version=1, browser_bindings=workflow_data.get("browser_bindings") or {})+ binding = context["browser_bindings"].get(node_id)+ if node_type == "browser" and binding:+ context.update(_browser_owner=binding, _browser_task_id=str(workflow.info().workflow_id))# F4.B: agent-as-child-workflow takes precedence over the# activity path for the 15 migrating agent types when its@@ -769,6 +775,11 @@ class MachinaWorkflow:),routing_snapshot=frozen_routing,)+ if node_type == "browser" and context.get("_browser_owner"):+ from services.node_registry import get_node_class+ cls = get_node_class("browser")+ dispatch = {"kind": "activity", "name": f"node.browser.v{cls.version}",+ "queue": context["_browser_owner"].get("task_queue")}# A preceding child start yields to the workflow event loop,# so a pause signal may have landed since ``ready`` was# computed. Re-admit every command in the batch.@@ -975,7 +986,9 @@ class MachinaWorkflow:worker_pool_enabled = (routing_snapshot.get("worker_pool_enabled") is True)- if agent_workflow_enabled and node_type in AGENT_WORKFLOW_TYPES:+ # This new capability has no historical single-Activity implementation+ # to replay. Its task-lifetime Browser ownership requires native dispatch.+ if node_type == "browser_agent" or (agent_workflow_enabled and node_type in AGENT_WORKFLOW_TYPES):return {"kind": "child_workflow", "name": "AgentWorkflow"}name, queue = self._resolve_activity(diff --git a/server/services/temporal/workspace_task_activities.py b/server/services/temporal/workspace_task_activities.pyindex 41b90696..ff9f3fe6 100644--- a/server/services/temporal/workspace_task_activities.py+++ b/server/services/temporal/workspace_task_activities.py@@ -28,6 +28,12 @@ async def reset_workspace_task_runtime(payload: dict) -> dict:generation = int(control.generation) if control and control.status == "resetting" else 0reset_nodes = []for node in nodes:+ if node["type"] == "browser_agent":+ # Every native Browser Agent child has already acknowledged its+ # matching-token owner cleanup before the controller reaches us.+ # Re-resolving editable bindings would target a different profile+ # or fail after a deliberate graph deletion.+ continueresult = await get_node_class(node["type"]).reset_execution_state(node_id=node["id"], workflow_id=workflow_id,execution_id=control.execution_id if control else "",diff --git a/server/services/temporal/workspace_tasks_workflow.py b/server/services/temporal/workspace_tasks_workflow.pyindex a6f97221..bb91f805 100644--- a/server/services/temporal/workspace_tasks_workflow.py+++ b/server/services/temporal/workspace_tasks_workflow.py@@ -97,6 +97,20 @@ class WorkspaceTaskControllerWorkflow:self._starting = run_idtry:+ # Only new server-versioned submissions produce this command;+ # histories recorded before the projection retain their commands.+ if payload.get("history_version") == 1:+ admitted_record = await workflow.execute_activity(+ "workspace_tasks.admit_record", payload,+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if isinstance(admitted_record, dict) and admitted_record.get("status") in ("completed", "failed", "cancelled"):+ # The projection can outlive Temporal retention and+ # this controller's bounded dedup window. A terminal+ # stable submission must never produce new effects.+ _bounded_remember(self._submissions, run_id, fingerprint, MAX_REMEMBERED_SUBMISSIONS)+ return {"run_id": run_id, "status": "duplicate"}child = await workflow.start_child_workflow(NodeInvocationWorkflow.run,payload,diff --git a/server/services/user_auth.py b/server/services/user_auth.pyindex 6c1a7dd0..6271fde5 100644--- a/server/services/user_auth.py+++ b/server/services/user_auth.py@@ -117,6 +117,9 @@ class UserAuthService:# Inline the lookups rather than calling get_user_by_email /# get_user_count: those open their own sessions, which would# reintroduce the very race this block exists to close.+ if session.bind.dialect.name == "postgresql":+ from sqlalchemy import text+ await session.execute(text("SELECT pg_advisory_xact_lock(763746821)"))existing = (await session.execute(select(User).where(User.email == normalized_email))).scalars().first()diff --git a/server/services/workspace_task_history.py b/server/services/workspace_task_history.pynew file mode 100644index 00000000..fb22a759--- /dev/null+++ b/server/services/workspace_task_history.py@@ -0,0 +1,153 @@+"""Idempotent history projection. Temporal remains the execution authority."""++from __future__ import annotations++from datetime import datetime, timedelta, timezone+from typing import Any++from sqlalchemy import delete, or_, and_, select, update+from sqlalchemy.exc import IntegrityError++from models.workspace_tasks import WorkspaceTaskRecord++TERMINAL = ("completed", "failed", "cancelled")+RETENTION_DAYS = 35+++def safe_result(result: Any) -> dict:+ """Persist the public answer only, never a tool transcript/configuration."""+ if not isinstance(result, dict):+ return {}+ answer = result.get("result") if isinstance(result.get("result"), dict) else result+ response = answer.get("response")+ safe = {"response": response[:16000]} if isinstance(response, str) else {}+ error_type = answer.get("error_type")+ if error_type in {"BrowserBusy", "BrowserTaskFailed"}:+ safe.update(error_type=error_type, error=("This browser is assigned to another task. Wait for that task to finish."+ if error_type == "BrowserBusy" else "The browser task failed. Check browser status and credentials."))+ # Only typed relative artifact references, not arbitrary result dictionaries.+ artifacts = answer.get("artifacts")+ if isinstance(artifacts, list):+ from pathlib import PurePosixPath, PureWindowsPath+ safe["artifacts"] = [+ {key: ref[key] for key in ("path", "mime_type", "name", "filename", "workflow_id") if key in ref}+ for ref in artifacts[:32]+ if isinstance(ref, dict) and isinstance(ref.get("path"), str)+ and not PureWindowsPath(ref["path"]).drive+ and not PurePosixPath(ref["path"]).is_absolute()+ and ".." not in PurePosixPath(ref["path"].replace("\\", "/")).parts+ ]+ from urllib.parse import quote+ for ref in safe["artifacts"]:+ if isinstance(ref.get("workflow_id"), str) and ref["workflow_id"]:+ ref["url"] = f"/api/workspace/{quote(ref['workflow_id'], safe='')}/files/{quote(ref['path'], safe='/')}"+ return safe+++async def admit(database, payload: dict) -> dict:+ """A unique invocation key makes Activity retries and transport retries safe."""+ values = payload["history_record"]+ async with database.get_session() as session:+ existing = await session.get(WorkspaceTaskRecord, values["invocation_id"])+ if existing:+ if existing.fingerprint != values["fingerprint"] or existing.principal != values["principal"]:+ raise ValueError("Workspace submission identity conflict")+ return {"status": existing.status}+ session.add(WorkspaceTaskRecord(**values))+ try:+ await session.commit()+ except IntegrityError:+ await session.rollback()+ existing = await session.get(WorkspaceTaskRecord, values["invocation_id"])+ if not existing or existing.fingerprint != values["fingerprint"] or existing.principal != values["principal"]:+ raise+ return {"status": existing.status}+ return {"status": "queued"}+++async def transition(database, payload: dict) -> None:+ status = payload["status"]+ if status not in ("running", *TERMINAL):+ raise ValueError("Invalid Workspace lifecycle status")+ now = datetime.now(timezone.utc)+ values: dict[str, Any] = {"status": status, "updated_at": now}+ if status in TERMINAL:+ values.update(completed_at=now, result=safe_result(payload.get("result")))+ async with database.get_session() as session:+ # Compare-and-set: retries or delayed running updates never regress terminal rows.+ await session.execute(update(WorkspaceTaskRecord).where(+ WorkspaceTaskRecord.invocation_id == payload["invocation_id"],+ WorkspaceTaskRecord.status.not_in(TERMINAL),+ ).values(**values))+ await session.commit()+++async def authorize_workflow(database, principal: str, workflow_id: str) -> dict:+ from services.plugin import NodeUserError+ saved = await database.get_workflow(workflow_id)+ if saved is None:+ raise NodeUserError("Workflow not found")+ graph = saved.data if hasattr(saved, "data") else saved.get("data", saved)+ if graph.get("owner_id") and graph["owner_id"] != principal:+ raise NodeUserError("Workflow access denied")+ return graph+++def serialize(record: WorkspaceTaskRecord) -> dict:+ return {key: getattr(record, key) for key in (+ "invocation_id", "submission_id", "workflow_id", "node_id", "prompt", "status",+ "result", "created_at", "updated_at", "completed_at",+ )}+++async def task_availability(database, owner_ids: list[str]) -> dict:+ import time+ if not owner_ids:+ return {"owner_available": True}+ from services.browser_owners import BrowserOwner+ async with database.get_session() as session:+ rows = list((await session.execute(select(BrowserOwner).where(BrowserOwner.owner_id.in_(owner_ids)))).scalars())+ available = len(rows) == len(set(owner_ids)) and all(row.heartbeat_at > time.time() - 35 for row in rows)+ return {"owner_available": available,+ **({"detail": "Browser unavailable — waiting for its owner."} if not available else {})}+++async def list_tasks(database, principal: str, workflow_id: str, *, node_id: str | None = None,+ cursor: str | None = None, limit: int = 20) -> dict:+ await authorize_workflow(database, principal, workflow_id)+ limit = max(1, min(100, limit))+ async with database.get_session() as session:+ cutoff = datetime.now(timezone.utc) - timedelta(days=RETENTION_DAYS)+ await session.execute(delete(WorkspaceTaskRecord).where(+ WorkspaceTaskRecord.workflow_id == workflow_id,+ WorkspaceTaskRecord.principal == principal,+ WorkspaceTaskRecord.completed_at < cutoff,+ ))+ await session.commit()+ conditions = [WorkspaceTaskRecord.workflow_id == workflow_id, WorkspaceTaskRecord.principal == principal]+ if node_id:+ conditions.append(WorkspaceTaskRecord.node_id == node_id)+ if cursor:+ marker = await session.get(WorkspaceTaskRecord, cursor)+ if not marker or marker.principal != principal or marker.workflow_id != workflow_id or (node_id and marker.node_id != node_id):+ from services.plugin import NodeUserError+ raise NodeUserError("Invalid task history cursor")+ conditions.append(or_(WorkspaceTaskRecord.created_at < marker.created_at,+ and_(WorkspaceTaskRecord.created_at == marker.created_at,+ WorkspaceTaskRecord.invocation_id < marker.invocation_id)))+ rows = list((await session.execute(select(WorkspaceTaskRecord).where(*conditions)+ .order_by(WorkspaceTaskRecord.created_at.desc(), WorkspaceTaskRecord.invocation_id.desc())+ .limit(limit + 1))).scalars())+ items = []+ for row in rows[:limit]:+ item = serialize(row)+ item.update(await task_availability(database, row.browser_owner_ids))+ items.append(item)+ return {"items": items, "next_cursor": rows[limit - 1].invocation_id if len(rows) > limit else None}+++async def get_task(database, principal: str, workflow_id: str, invocation_id: str) -> WorkspaceTaskRecord | None:+ await authorize_workflow(database, principal, workflow_id)+ async with database.get_session() as session:+ record = await session.get(WorkspaceTaskRecord, invocation_id)+ return record if record and record.principal == principal and record.workflow_id == workflow_id else Nonediff --git a/server/skills/web_agent/browser-skill/SKILL.md b/server/skills/web_agent/browser-skill/SKILL.mdindex 3e93e17f..b865b711 100644--- a/server/skills/web_agent/browser-skill/SKILL.md+++ b/server/skills/web_agent/browser-skill/SKILL.md@@ -51,6 +51,20 @@ If the snapshot says the page offers WebMCP tools, call `webmcp_list` and prefer## When a person must act+For a configured single-form login, use `credential_bindings` to discover+approved opaque binding IDs for this browser. Observe current username,+password and submit refs first, then call `credential_fill` with+`credential_binding_id`, `username_ref`, `password_ref` and `submit_ref`.+Never supply or request credential values, 1Password references or vault IDs.+The runtime privately fills the approved fields and submits once while+observations and capture are gated. It returns only safe status.++Under Ask first/read-only policy, or for multi-step login, MFA, passkeys,+missing bindings or protected-login failure, use `request_user`. A gated+browser requires the owner's close/reopen manual-login recovery action;+never evade the gate through screenshots, vision, page text or WebMCP, and+never replay an uncertain login submission.+Call `request_user` with a short, specific `message` and a `reason` (`login`, `captcha`, `two_factor`, `confirm`, `other`) when:- a site needs a login, a CAPTCHA or a two-factor code;@@ -87,4 +101,6 @@ It waits until the owner hands the browser back; the result says `handed_back`,| `wait` | `wait_for`, `wait_value` || `webmcp_list` / `webmcp_call` | the site's own tools || `request_user` | hand the page to the owner |+| `credential_bindings` | approved opaque IDs for configured website login |+| `credential_fill` | approved binding ID and current username/password/submit refs || `diagnose` | when the browser itself seems broken |diff --git a/server/tests/credentials/test_onepassword.py b/server/tests/credentials/test_onepassword.pynew file mode 100644index 00000000..61105fbf--- /dev/null+++ b/server/tests/credentials/test_onepassword.py@@ -0,0 +1,395 @@+"""Canaries for private resolution, saved metadata and scoped website bindings."""++import asyncio+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+import pytest_asyncio+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlmodel import SQLModel++from models.credential_sources import BrowserCredentialBinding, CredentialSource+from services.auth import AuthService+from services.credentials import onepassword+from services.credentials.onepassword import CredentialSourceError+from services.credentials.sources import CredentialSources, exact_origin, public_base_url++REF = "op://" + "a" * 26 + "/" + "b" * 26 + "/password"+USER_REF = REF.replace("password", "username")+CANARY = " 密碼-secret-CANARY\n "+++class Process:+ def __init__(self, output: bytes, error: bytes = b"", code: int = 0):+ self.stdout, self.stderr = asyncio.StreamReader(), asyncio.StreamReader()+ self.stdout.feed_data(output)+ self.stdout.feed_eof()+ self.stderr.feed_data(error)+ self.stderr.feed_eof()+ self.returncode = code++ async def wait(self):+ return self.returncode+++@pytest_asyncio.fixture+async def source_auth():+ engine = create_async_engine("sqlite+aiosqlite://")+ async with engine.begin() as connection:+ await connection.run_sync(lambda conn: SQLModel.metadata.create_all(conn, tables=[CredentialSource.__table__, BrowserCredentialBinding.__table__]))+ factory = async_sessionmaker(engine, expire_on_commit=False)++ @asynccontextmanager+ async def get_session():+ async with factory() as session:+ yield session++ database = SimpleNamespace(get_session=get_session, engine=engine)+ local = SimpleNamespace(get_api_key=AsyncMock(return_value="old-local-key"), delete_api_key=AsyncMock(), get_api_key_models=AsyncMock(return_value=["old-model"]), get_api_key_model_params=AsyncMock(return_value={}), list_api_keys=AsyncMock(return_value=[]), list_key_scopes=AsyncMock(return_value=[]))+ auth = AuthService(local, None, database, SimpleNamespace(distributed_mode=False))+ try:+ yield auth+ finally:+ await engine.dispose()+++def test_references_are_unambiguous_and_cannot_add_cli_options():+ assert onepassword.validate_reference(REF) == REF+ for bad in ("op://named-vault/item/password", REF + "?attribute=otp", REF + "\n--out-file /tmp/leak", REF.replace("op://", "--")):+ with pytest.raises(CredentialSourceError):+ onepassword.validate_reference(bad)+++def test_origin_and_public_endpoint_reject_credentials():+ assert exact_origin("https://EXAMPLE.com:443/") == "https://example.com"+ assert exact_origin("http://[::1]:8000") == "http://[::1]:8000"+ assert public_base_url("https://api.example.com/v1/") == "https://api.example.com/v1"+ for bad in ("https://user:[email protected]", "https://example.com/?secret=123", "https://example.com/path", "https://example.com/#token"):+ with pytest.raises(CredentialSourceError):+ exact_origin(bad)+++def test_auth_modes_exclude_connect_and_ambient_secrets(monkeypatch):+ for name, value in {"OP_CONNECT_HOST": "https://connect", "OP_CONNECT_TOKEN": "connect-canary", "OP_SERVICE_ACCOUNT_TOKEN": "bootstrap-canary", "OP_SESSION_bad": "session-canary", "OPENAI_API_KEY": "api-canary"}.items():+ monkeypatch.setenv(name, value)+ desktop = onepassword.resolver_environment(SimpleNamespace(onepassword_auth_mode="desktop", onepassword_account="work", distributed_mode=False))+ assert desktop["OP_ACCOUNT"] == "work"+ assert desktop["OP_BIOMETRIC_UNLOCK_ENABLED"] == "true"+ assert not any(name in desktop for name in ("OP_SERVICE_ACCOUNT_TOKEN", "OP_CONNECT_HOST", "OP_CONNECT_TOKEN", "OP_SESSION_bad", "OPENAI_API_KEY"))+ service = onepassword.resolver_environment(SimpleNamespace(onepassword_auth_mode="service_account", distributed_mode=True))+ assert service["OP_SERVICE_ACCOUNT_TOKEN"] == "bootstrap-canary"+ assert "OP_CONNECT_HOST" not in service and "OP_CONNECT_TOKEN" not in service+++async def test_reader_preserves_exact_value_and_fixed_argument_vector(monkeypatch):+ called = []+ async def spawn(executable, *args, **kwargs):+ called.append((executable, args, kwargs))+ return Process(CANARY.encode())+ monkeypatch.setattr(onepassword, "cli_path", lambda settings: "/approved/op")+ monkeypatch.setattr(onepassword, "doctor", AsyncMock(return_value={}))+ monkeypatch.setattr(onepassword.asyncio, "create_subprocess_exec", spawn)+ result = await onepassword.read_secret(REF, SimpleNamespace(onepassword_auth_mode="desktop"))+ assert result == CANARY+ assert called[0][1] == ("read", "--no-newline", REF)+ assert called[0][2]["stdin"] == asyncio.subprocess.DEVNULL+ assert CANARY not in str(called)+++async def test_raw_cli_error_and_secret_output_are_not_exposed(monkeypatch, caplog):+ monkeypatch.setattr(onepassword.asyncio, "create_subprocess_exec", AsyncMock(return_value=Process(CANARY.encode(), ("429 rate limit " + CANARY).encode(), 1)))+ with pytest.raises(CredentialSourceError) as failure:+ await onepassword._private_command("/approved/op", ("read", "--no-newline", REF), {}, 1)+ assert failure.value.code == "rate_limited"+ assert CANARY not in str(failure.value) and CANARY not in caplog.text+++async def test_pipe_size_limit_terminates_process(monkeypatch):+ process = Process(b"x" * 65537)+ process.returncode = None+ def terminate():+ process.returncode = -1+ process.terminate = terminate+ monkeypatch.setattr(onepassword.asyncio, "create_subprocess_exec", AsyncMock(return_value=process))+ with pytest.raises(CredentialSourceError) as failure:+ await onepassword._private_command("/approved/op", ("read", "--no-newline", REF), {}, 1)+ assert failure.value.code == "invalid_value"+ assert process.returncode == -1++[email protected]("cancel", [False, True])+async def test_timeout_and_cancellation_terminate_and_wait(monkeypatch, cancel):+ process = Process(b"")+ process.stdout = asyncio.StreamReader() # deliberately never reaches EOF+ process.returncode = None+ waited = []+ def terminate():+ process.returncode = -1+ async def wait():+ waited.append(True)+ return process.returncode+ process.terminate, process.wait = terminate, wait+ monkeypatch.setattr(onepassword.asyncio, "create_subprocess_exec", AsyncMock(return_value=process))+ task = asyncio.create_task(onepassword._private_command("/approved/op", ("read",), {}, .01))+ if cancel:+ await asyncio.sleep(0)+ task.cancel()+ with pytest.raises(asyncio.CancelledError if cancel else CredentialSourceError):+ await task+ assert process.returncode == -1 and waited+++async def test_sources_never_resolve_in_forms_models_or_existence_checks(source_auth, monkeypatch):+ await source_auth.store_credential_source("openai", REF, principal="owner", models=["gpt-test"], model_params={"gpt-test": {"context_length": 1000}})+ reader = AsyncMock(return_value=CANARY)+ monkeypatch.setattr(onepassword, "read_secret", reader)+ assert await source_auth.get_api_key("openai") is None+ assert await source_auth.has_valid_key("openai")+ assert await source_auth.get_stored_models("openai") == ["gpt-test"]+ assert (await source_auth.get_model_params("openai"))["gpt-test"]["context_length"] == 1000+ assert (await source_auth.get_credential_source("openai"))["reference"] == REF+ reader.assert_not_awaited()+ assert await source_auth.resolve_api_key("openai") == CANARY+ assert await source_auth.resolve_api_key("openai") == CANARY+ assert reader.await_count == 2 # no decrypted value cache+ assert not source_auth._api_key_cache+ source_auth.credentials_db.get_api_key.assert_not_awaited()+++async def test_cluster_rejects_fallback_and_handles_default_endpoint_metadata(source_auth):+ source_auth.settings.distributed_mode = True+ with pytest.raises(CredentialSourceError):+ await source_auth.resolve_api_key("openai")+ with pytest.raises(CredentialSourceError):+ await source_auth.store_api_key("openai", "inline", [])+ with pytest.raises(CredentialSourceError):+ await source_auth.get_oauth_tokens("google")+ source_auth.credentials_db.get_api_key.assert_not_awaited()+ await source_auth.store_credential_source("openai", REF, principal="owner")+ assert await source_auth.resolve_api_key("openai_proxy") is None+ await source_auth.store_credential_source("openai_compatible:lab", REF, principal="owner", base_url="https://models.example.com/v1")+ assert await source_auth.resolve_api_key("openai_compatible:lab_proxy") == "https://models.example.com/v1"+++async def test_source_permissions_precede_resolution(source_auth, monkeypatch):+ await source_auth.store_credential_source("openai", REF, principal="alice")+ reader = AsyncMock(return_value=CANARY)+ monkeypatch.setattr(onepassword, "read_secret", reader)+ with pytest.raises(CredentialSourceError):+ await source_auth.resolve_api_key("openai", principal="bob")+ with pytest.raises(CredentialSourceError):+ await source_auth.resolve_api_key("openai")+ with pytest.raises(CredentialSourceError):+ await source_auth.remove_api_key("openai", principal="bob")+ reader.assert_not_awaited()+++async def test_shared_catalogue_metadata_is_scoped_without_resolving(source_auth, monkeypatch):+ from services.llm.endpoints import list_endpoints+ await source_auth.store_credential_source("openai_compatible:alice", REF, principal="alice", models=["alice-model"], model_params={"_endpoint": {"label": "Alice", "base_url": "https://alice.example/v1"}}, base_url="https://alice.example/v1")+ reader = AsyncMock(return_value=CANARY)+ monkeypatch.setattr(onepassword, "read_secret", reader)+ assert await source_auth.has_valid_key("openai_compatible:alice", principal="bob") is False+ assert await source_auth.get_stored_models("openai_compatible:alice", principal="bob") == []+ assert await source_auth.get_model_params("openai_compatible:alice", principal="bob") == {}+ assert await source_auth.list_api_key_providers(principal="bob") == []+ assert await list_endpoints(source_auth, principal="bob") == []+ endpoints = await list_endpoints(source_auth, principal="alice")+ assert len(endpoints) == 1 and endpoints[0].label == "Alice" and endpoints[0].models == ["alice-model"]+ reader.assert_not_awaited()+++async def test_api_revocation_while_authorizing_does_not_return_old_value(source_auth, monkeypatch):+ await source_auth.store_credential_source("openai", REF, principal="owner")+ async def read(reference, settings):+ await source_auth._sources().delete("openai", principal="owner")+ return CANARY+ monkeypatch.setattr(onepassword, "read_secret", read)+ with pytest.raises(CredentialSourceError) as failure:+ await source_auth.resolve_api_key("openai")+ assert failure.value.code == "binding_changed"+ assert CANARY not in str(failure.value)+++async def test_explicit_disconnect_does_not_uncover_a_shadowed_local_key(source_auth):+ await source_auth.store_credential_source("openai", REF, principal="owner")+ await source_auth.remove_api_key("openai", principal="owner")+ source_auth.credentials_db.delete_api_key.assert_awaited_once_with("openai", "default")+ assert await source_auth.get_credential_source("openai") is None+++async def test_website_binding_scopes_and_opaque_metadata(source_auth, monkeypatch):+ store = CredentialSources(source_auth.database)+ metadata = await store.save_browser("alice", {"label": "Test", "origin": "https://example.com", "success_path": "/account", "username_reference": USER_REF, "password_reference": REF, "profile_id": "profile", "workflow_id": "workflow", "employee_id": "employee"})+ assert "reference" not in str(metadata)+ assert (await store.list_browser("alice")) == [metadata]+ reader = AsyncMock(side_effect=["user", CANARY])+ monkeypatch.setattr(onepassword, "read_secret", reader)+ for scope in ({"principal": "bob"}, {"principal": "alice", "profile_id": "other"}, {"principal": "alice", "profile_id": "profile", "workflow_id": "workflow", "employee_id": "other"}):+ with pytest.raises(CredentialSourceError):+ await source_auth.resolve_browser_credentials(metadata["id"], **scope)+ reader.assert_not_awaited()+ resolved = await source_auth.resolve_browser_credentials(metadata["id"], "alice", profile_id="profile", workflow_id="workflow", employee_id="employee")+ assert resolved["username"] == "user" and resolved["password"] == CANARY+ assert CANARY not in str(await store.list_browser("alice"))+++async def test_revocation_during_desktop_authorization_prevents_fill(source_auth, monkeypatch):+ store = CredentialSources(source_auth.database)+ saved = await store.save_browser("owner", {"label": "Test", "origin": "https://example.com", "success_path": "/account", "username_reference": USER_REF, "password_reference": REF})+ async def read(reference, settings):+ if reference == REF:+ await store.delete_browser("owner", saved["id"])+ return CANARY+ monkeypatch.setattr(onepassword, "read_secret", read)+ with pytest.raises(CredentialSourceError):+ await source_auth.resolve_browser_credentials(saved["id"], "owner")+++async def test_api_validation_persists_only_reference_and_never_echoed_secrets(source_auth, monkeypatch, caplog):+ from core.container import container+ from services.credentials import handlers+ from services.plugin.credential import ApiKeyCredential, ProbeResult++ class CanaryCredential(ApiKeyCredential):+ id = "onepassword_canary_test"+ @classmethod+ async def _probe(cls, key):+ assert key == CANARY+ return ProbeResult(valid=True, models=["safe-model"])++ broadcaster = SimpleNamespace(update_api_key_status=AsyncMock())+ monkeypatch.setattr(container, "auth_service", lambda: source_auth)+ monkeypatch.setattr("services.status_broadcaster.get_status_broadcaster", lambda: broadcaster)+ monkeypatch.setattr(onepassword, "read_secret", AsyncMock(return_value=CANARY))+ socket = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))+ result = await handlers.handle_validate_api_key({"provider": CanaryCredential.id, "credential_source": "onepassword", "reference": REF, "_principal": "attacker"}, socket)+ assert result["valid"]+ assert (await source_auth.get_credential_source(CanaryCredential.id, principal="owner"))["reference"] == REF+ assert CANARY not in str(result) and CANARY not in str(broadcaster.update_api_key_status.await_args)+ assert CANARY not in caplog.text++ async def echo(cls, key):+ return ProbeResult(valid=True, models=[key])+ monkeypatch.setattr(CanaryCredential, "_probe", classmethod(echo))+ result = await handlers.handle_validate_api_key({"provider": CanaryCredential.id, "credential_source": "onepassword", "reference": REF}, socket)+ assert not result["valid"]+ assert CANARY not in str(result)+ assert await source_auth.get_stored_models(CanaryCredential.id) == ["safe-model"]+++async def test_api_form_reads_reference_metadata_without_secret_resolution(source_auth, monkeypatch):+ from core.container import container+ from services.credentials import handlers+ await source_auth.store_credential_source("openai", REF, principal="owner", models=["model"])+ monkeypatch.setattr(container, "auth_service", lambda: source_auth)+ reader = AsyncMock(return_value=CANARY)+ monkeypatch.setattr(onepassword, "read_secret", reader)+ socket = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))+ result = await handlers.handle_get_stored_api_key({"provider": "openai"}, socket)+ assert result["hasKey"] is True and "apiKey" not in result+ assert result["credentialSource"]["reference"] == REF+ reader.assert_not_awaited()+++def test_signature_verification_uses_fixed_windows_script_and_private_path(monkeypatch):+ from pathlib import Path+ from services.credentials import provision+ calls = []+ monkeypatch.setattr(provision.platform, "system", lambda: "Windows")+ monkeypatch.setattr(provision.shutil, "which", lambda name: "powershell")+ monkeypatch.setattr(provision, "_run", lambda args, env=None: calls.append((args, env)))+ path = Path("C:/Program Files/op ' $(unsafe).exe")+ provision.verify_publisher(path)+ arguments, environment = calls[0]+ assert str(path) not in arguments[-1]+ assert environment == {"OPENCOMPANY_SIGNATURE_TARGET": str(path)}+ assert "Get-AuthenticodeSignature" in arguments[-1] and "Valid" in arguments[-1]++[email protected]("subject,approved", [+ ("CN=Agilebits, O=Agilebits, L=Toronto, S=Ontario, C=CA", True),+ ("CN=1Password, O=1Password Inc., C=CA", True),+ ("CN=AgileBits, O=AgileBits Inc, C=CA", True),+ ("CN=Agilebits, O=Someone Else, C=CA", False),+ ("CN=Unknown, O=Agilebits Malware Inc, C=CA", False),+ ("CN=Unknown, O=Fake 1Password Inc., C=CA", False),+])+def test_windows_signature_organization_is_exact(monkeypatch, subject, approved):+ import re+ from pathlib import Path+ from services.credentials import provision+ calls = []+ monkeypatch.setattr(provision.platform, "system", lambda: "Windows")+ monkeypatch.setattr(provision.shutil, "which", lambda name: "powershell")+ monkeypatch.setattr(provision, "_run", lambda args, env=None: calls.append(args))+ provision.verify_publisher(Path("op.exe"))+ pattern = calls[0][-1].split("-notmatch '")[1].split("'")[0]+ assert bool(re.search(pattern, subject, re.IGNORECASE)) is approved+++async def test_doctor_verifies_integrity_before_version_without_bootstrap(monkeypatch):+ from services.credentials import provision+ events = []+ monkeypatch.setattr(onepassword, "cli_path", lambda settings: "/approved/op")+ monkeypatch.setattr(provision, "verify_install", lambda path: events.append("verified"))+ monkeypatch.setenv("OP_SERVICE_ACCOUNT_TOKEN", "bootstrap-canary")+ async def private(executable, args, env, timeout):+ events.append("version")+ assert args == ("--version",)+ assert "OP_SERVICE_ACCOUNT_TOKEN" not in env+ return b"2.40.0\n"+ monkeypatch.setattr(onepassword, "_private_command", private)+ assert (await onepassword.doctor(SimpleNamespace(onepassword_auth_mode="desktop")))["available"]+ assert events == ["verified", "version"]+++def test_signature_subprocess_has_native_module_path_without_bootstrap(monkeypatch):+ from services.credentials import provision+ calls = []+ monkeypatch.setenv("PSModulePath", "incompatible-shell-modules")+ monkeypatch.setenv("OP_SERVICE_ACCOUNT_TOKEN", "bootstrap-canary")+ monkeypatch.setattr(provision.subprocess, "run", lambda args, **kwargs: calls.append(kwargs) or SimpleNamespace(returncode=0))+ provision._run(["powershell", "-NoProfile", "-Command", "verified"], {"op_connect_token": "override-canary", "OPENCOMPANY_SIGNATURE_TARGET": "op.exe"})+ env = calls[0]["env"]+ assert "PSModulePath" not in env+ assert not any(key.upper().startswith("OP_") for key in env)+ assert env["OPENCOMPANY_SIGNATURE_TARGET"] == "op.exe"+++async def test_catalogue_since_changes_with_shared_binding_and_keeps_principal_scope(source_auth, monkeypatch):+ from services import credential_registry+ import routers.websocket as websocket+ await source_auth.store_credential_source("openai", REF, principal="alice", models=["model-a"])+ registry = SimpleNamespace(+ get_live_version=lambda: "fixed-replica-local-version",+ get_catalogue=lambda: {"providers": [{"id": "openai", "kind": "apiKey"}], "categories": []},+ )+ monkeypatch.setattr(credential_registry, "get_credential_registry", lambda: registry)+ monkeypatch.setattr(websocket.container, "auth_service", lambda: source_auth)+ state = AsyncMock(wraps=credential_registry.provider_connection_state)+ monkeypatch.setattr(credential_registry, "provider_connection_state", state)+ reader = AsyncMock(side_effect=AssertionError("Catalogue reads must never resolve secrets"))+ monkeypatch.setattr(onepassword, "read_secret", reader)+ alice = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="alice"))+ first = await websocket.handle_get_credential_catalogue({}, alice)+ assert first["providers"][0]["stored"] is True+ assert await websocket.handle_get_credential_catalogue({"since": first["version"]}, alice) == {"success": True, "unchanged": True, "version": first["version"]}+ assert state.await_count == 1++ # Another replica writes the shared row without bumping this process's+ # registry version or broadcasting a local cache invalidation.+ await source_auth._sources().save("openai", USER_REF, owner_id="alice", models=["model-b"])+ refreshed = await websocket.handle_get_credential_catalogue({"since": first["version"]}, alice)+ assert "unchanged" not in refreshed and refreshed["version"] != first["version"]+ assert refreshed["providers"][0]["stored"] is True+ assert all(call.kwargs["principal"] == "alice" for call in state.await_args_list)++ bob = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="bob"))+ foreign = await websocket.handle_get_credential_catalogue({"since": refreshed["version"]}, bob)+ assert foreign["version"] != refreshed["version"]+ assert foreign["providers"][0]["stored"] is False+ assert state.await_args.kwargs["principal"] == "bob"+ reader.assert_not_awaited()diff --git a/server/tests/credentials/test_onepassword_process_boundaries.py b/server/tests/credentials/test_onepassword_process_boundaries.pynew file mode 100644index 00000000..8d4acafb--- /dev/null+++ b/server/tests/credentials/test_onepassword_process_boundaries.py@@ -0,0 +1,79 @@+"""Resolver bootstrap credentials must not reach ordinary CLI runtimes."""++import asyncio+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+++def bootstrap(monkeypatch):+ monkeypatch.setenv("OP_SERVICE_ACCOUNT_TOKEN", "bootstrap-canary")+ monkeypatch.setenv("OP_CONNECT_TOKEN", "connect-canary")+ monkeypatch.setenv("op_session_personal", "session-canary")+ monkeypatch.setenv("ORDINARY_RUNTIME_VAR", "keep-me")++[email protected]("module_name,function,args", [+ ("nodes.github._service", "gh_env", ()),+ ("nodes.github._service", "login_env", ()),+ ("nodes.gcloud._service", "gcloud_env", ()),+ ("nodes.gcloud._service", "login_env", ()),+ ("nodes.cloudflare._service", "cf_env", ("approved-api-token", "account")),+ ("nodes.cloudflare._service", "login_env", ()),+ ("nodes.vercel._service", "vercel_env", ("approved-api-token",)),+ ("nodes.agent.claude_code_agent._oauth", "_claude_env", ()),+])+def test_cli_auth_and_operation_environments_exclude_bootstrap(bootstrap, monkeypatch, module_name, function, args):+ from importlib import import_module+ module = import_module(module_name)+ if module_name == "nodes.gcloud._service":+ monkeypatch.setattr(module, "_config_dir", lambda: "isolated-gcloud-config")+ if module_name.endswith("._oauth"):+ monkeypatch.setattr(Path, "mkdir", lambda *args, **kwargs: None)+ env = getattr(module, function)(*args)+ assert env["ORDINARY_RUNTIME_VAR"] == "keep-me"+ assert not any(key.upper().startswith("OP_") for key in env)+ if function == "cf_env":+ assert env["CLOUDFLARE_API_TOKEN"] == "approved-api-token"+ if function == "vercel_env":+ assert env["VERCEL_TOKEN"] == "approved-api-token"+++async def test_mobile_final_spawn_filters_overrides(bootstrap, monkeypatch):+ from nodes.mobile import _process+ output = asyncio.StreamReader()+ output.feed_data(b"completed")+ output.feed_eof()+ process = SimpleNamespace(stdout=output, returncode=0, wait=AsyncMock(return_value=0))+ spawn = AsyncMock(return_value=process)+ monkeypatch.setattr(_process.asyncio, "create_subprocess_exec", spawn)+ assert await _process.command(["installer"], env={"OP_SERVICE_ACCOUNT_TOKEN": "override-canary", "op_session_other": "override", "PATH": "private-bin"}) == "completed"+ assert spawn.await_args.kwargs["env"] == {"PATH": "private-bin"}+++async def test_worktree_final_git_spawn_filters_ambient_bootstrap(bootstrap, monkeypatch):+ from services.cli_agent import worktree+ run = AsyncMock(return_value=SimpleNamespace(returncode=0))+ monkeypatch.setattr(worktree.anyio, "run_process", run)+ monkeypatch.setattr(Path, "exists", lambda self: False)+ monkeypatch.setattr(Path, "mkdir", lambda *args, **kwargs: None)+ await worktree.add_worktree(Path("repo"), Path("workspace/worktree"), "branch")+ await worktree.remove_worktree(Path("repo"), Path("workspace/worktree"))+ for call in run.await_args_list:+ env = call.kwargs["env"]+ assert env["ORDINARY_RUNTIME_VAR"] == "keep-me"+ assert not any(key.upper().startswith("OP_") for key in env)+++def test_dependency_install_final_spawn_filters_bootstrap(bootstrap, monkeypatch):+ from core import js_runtime+ monkeypatch.setattr(js_runtime, "require_bun", lambda purpose: "bun")+ monkeypatch.setattr(js_runtime, "ensure_shared_tree", lambda root: Path("shared-tree"))+ calls = []+ monkeypatch.setattr(js_runtime.subprocess, "run", lambda *args, **kwargs: calls.append(kwargs))+ js_runtime.add_package("@approved/[email protected]")+ assert calls[0]["env"]["ORDINARY_RUNTIME_VAR"] == "keep-me"+ assert not any(key.upper().startswith("OP_") for key in calls[0]["env"])diff --git a/server/tests/credentials/test_onepassword_runtime_adapters.py b/server/tests/credentials/test_onepassword_runtime_adapters.pynew file mode 100644index 00000000..2dfda216--- /dev/null+++ b/server/tests/credentials/test_onepassword_runtime_adapters.py@@ -0,0 +1,136 @@+"""Static providers resolve privately in their calling runtime, with identity."""++import sys+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from services.credentials.onepassword import CredentialSourceError+from services.plugin import NodeContext+++def runtime_auth(monkeypatch, key="runtime-key"):+ from services.plugin import deps+ auth = SimpleNamespace(+ resolve_api_key=AsyncMock(return_value=key),+ get_api_key=AsyncMock(side_effect=AssertionError("Legacy form getter is not a runtime resolver")),+ require_local_credentials=MagicMock(),+ )+ monkeypatch.setattr(deps, "get_auth_service", lambda: auth)+ monkeypatch.setattr(deps, "get_ai_service", lambda: SimpleNamespace(auth=auth))+ return auth+++async def test_apify_activity_passes_trusted_principal_to_private_resolution(monkeypatch):+ from nodes.scraper.apify_actor import ApifyActorNode, ApifyActorParams+ auth = runtime_auth(monkeypatch)+ actor = SimpleNamespace(call=AsyncMock(return_value={"id": "run", "status": "SUCCEEDED"}))+ sdk = MagicMock(return_value=SimpleNamespace(actor=lambda name: actor))+ monkeypatch.setitem(sys.modules, "apify_client", SimpleNamespace(ApifyClientAsync=sdk))+ ctx = NodeContext(node_id="scraper", node_type="apifyActor", raw={"user_id": "alice"})+ result = await ApifyActorNode().run(ctx, ApifyActorParams(actor_id="apify/instagram-scraper"))+ assert result.status == "SUCCEEDED"+ auth.resolve_api_key.assert_awaited_once_with("apify", "default", principal="alice")+ sdk.assert_called_once_with("runtime-key")+ auth.get_api_key.assert_not_awaited()+++async def test_vertex_admin_resolves_gemini_and_does_not_hide_revocation(monkeypatch):+ from nodes.agent import vertex_agent_admin as admin+ auth = runtime_auth(monkeypatch, key="AIza-runtime-key")+ build = MagicMock(return_value="private-client")+ monkeypatch.setattr(admin, "build_genai_client", build)+ ctx = NodeContext(node_id="admin", node_type="vertex_agent_admin", raw={"user_id": "alice"})+ params = admin.VertexAgentAdminParams(operation="list")+ assert await admin.VertexAgentAdminNode()._client(params, ctx) == "private-client"+ auth.resolve_api_key.assert_awaited_once_with("gemini", "default", principal="alice")+ auth.resolve_api_key.side_effect = CredentialSourceError("resolution_failed", "Approved reference unavailable.")+ with pytest.raises(CredentialSourceError, match="unavailable"):+ await admin.VertexAgentAdminNode()._client(params, ctx)+ assert build.call_count == 1+ auth.get_api_key.assert_not_awaited()+++def test_vertex_adc_is_a_local_only_connection(monkeypatch):+ from nodes.agent import _vertex+ auth = runtime_auth(monkeypatch)+ auth.require_local_credentials.side_effect = CredentialSourceError("unsupported_source", "ADC requires local execution.")+ with pytest.raises(CredentialSourceError, match="local execution"):+ _vertex.build_genai_client("", "gcp-project")+++async def test_live_voice_resolution_is_scoped_and_revocation_does_not_use_static_fallback(monkeypatch):+ from nodes.speech import _option_loaders, _unifier+ from services import ws_handler_registry+ auth = runtime_auth(monkeypatch)+ monkeypatch.setattr(ws_handler_registry, "current_load_options_principal", lambda: "alice")+ voice = SimpleNamespace(as_option=lambda: {"value": "voice", "label": "Approved voice"})+ voices = AsyncMock(return_value=[voice])+ monkeypatch.setattr(_unifier, "list_voices", voices)+ assert await _option_loaders.load_speech_voices({"provider": "elevenlabs"}) == [voice.as_option()]+ auth.resolve_api_key.assert_awaited_once_with("elevenlabs", principal="alice")+ auth.resolve_api_key.side_effect = CredentialSourceError("resolution_failed", "Approved reference unavailable.")+ with pytest.raises(CredentialSourceError):+ await _option_loaders.load_speech_voices({"provider": "elevenlabs"})+ assert voices.await_count == 1+++async def test_dictation_status_reads_metadata_and_never_resolves(monkeypatch):+ from core.container import container+ from nodes.speech import _handlers+ auth = runtime_auth(monkeypatch)+ auth.has_valid_key = AsyncMock(side_effect=lambda provider, **kwargs: provider == "groq")+ monkeypatch.setattr(container, "auth_service", lambda: auth)+ assert await _handlers.dictation_provider(principal="alice") == "groq"+ assert all(call.kwargs["principal"] == "alice" for call in auth.has_valid_key.await_args_list)+ auth.resolve_api_key.assert_not_awaited()+ auth.get_api_key.assert_not_awaited()+++async def test_employee_connections_scope_provider_and_endpoint_metadata(monkeypatch):+ from services.employees import connections+ from services.llm import endpoints+ auth = object()+ state = AsyncMock(return_value={"stored": True, "connected": True})+ listing = AsyncMock(return_value=[])+ registry = SimpleNamespace(get_provider=lambda provider: {"id": provider})+ monkeypatch.setattr(connections, "get_credential_registry", lambda: registry)+ monkeypatch.setattr(connections, "provider_connection_state", state)+ monkeypatch.setattr(endpoints, "list_endpoints", listing)+ current = connections.Connections(auth, principal="alice")+ await current.ai_providers()+ await current.state("openai")+ assert all(call.kwargs["principal"] == "alice" for call in state.await_args_list)+ assert sum(call.args[0]["id"] == "openai" for call in state.await_args_list) == 1+ listing.assert_awaited_once_with(auth, principal="alice")+++async def test_employee_setup_resolves_with_its_owner_without_legacy_fallback(monkeypatch):+ from services.employees.llm import LLMChoice, employees_chat+ auth = runtime_auth(monkeypatch)+ chat = AsyncMock(return_value="safe-result")+ assert await employees_chat(SimpleNamespace(chat=chat), auth, LLMChoice(provider="openai", model="gpt-test", local=False), [], principal="alice") == "safe-result"+ auth.resolve_api_key.assert_awaited_once_with("openai", principal="alice")+ assert chat.await_args.kwargs["api_key"] == "runtime-key"+ auth.get_api_key.assert_not_awaited()+++async def test_additional_credential_fields_require_an_explicit_adapter(monkeypatch):+ from core.container import container+ from services import credential_registry+ from services.credentials import onepassword+ from services.plugin.credential import ApiKeyCredential++ class AdditionalSecretCredential(ApiKeyCredential):+ id = "additional_secret_canary"+ extra_fields = ("additional-secret",)++ reader = AsyncMock(side_effect=AssertionError("Unsupported enrollment must not read secrets"))+ monkeypatch.setattr(onepassword, "read_secret", reader)+ monkeypatch.setattr(container, "auth_service", lambda: SimpleNamespace(distributed_credentials=True))+ state = await credential_registry.provider_connection_state({"id": AdditionalSecretCredential.id, "kind": "apiKey"}, container.auth_service(), principal="alice")+ assert not state["sourceSupported"] and not state["connected"]+ result = await AdditionalSecretCredential.validate({"credential_source": "onepassword", "reference": "unused", "_principal": "alice"})+ assert result["code"] == "unsupported_source" and not result["valid"]+ reader.assert_not_awaited()diff --git a/server/tests/llm/test_protocol_guard.py b/server/tests/llm/test_protocol_guard.pyindex 4002dd3e..d52a780a 100644--- a/server/tests/llm/test_protocol_guard.py+++ b/server/tests/llm/test_protocol_guard.py@@ -73,7 +73,7 @@ class TestTwoHundredWithoutChoices:client.chat = AsyncMock(side_effect=error)spec = ProviderSpec(name="lmstudio", factory=MagicMock(return_value=client), sdk_exception_refs=("openai:OpenAIError",))auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}}, auth_service=auth)with patch("services.llm.unifier.get_provider", return_value=spec):@@ -97,7 +97,7 @@ class TestTwoHundredWithoutChoices:name="openai_compatible", factory=MagicMock(return_value=client), sdk_exception_refs=("openai:OpenAIError",))auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=LEAKY_URL)+ auth.resolve_api_key = AsyncMock(return_value=LEAKY_URL)unifier = ChatUnifier(defaults={"providers": {}}, auth_service=auth)with patch("services.llm.unifier.get_provider", return_value=spec), patch("services.llm.unifier.logger") as log:diff --git a/server/tests/llm/test_provider_refs.py b/server/tests/llm/test_provider_refs.pyindex 7abf1708..b7cfac5b 100644--- a/server/tests/llm/test_provider_refs.py+++ b/server/tests/llm/test_provider_refs.py@@ -37,7 +37,7 @@ SERVER_DIR = Path(__file__).resolve().parents[2]def _unifier(get_api_key) -> ChatUnifier:auth = MagicMock()- auth.get_api_key = get_api_key+ auth.resolve_api_key = get_api_keyreturn ChatUnifier(defaults={"providers": {}}, auth_service=auth)diff --git a/server/tests/llm/test_rfc0003_source_contract.py b/server/tests/llm/test_rfc0003_source_contract.pyindex eb8974bd..319df9a0 100644--- a/server/tests/llm/test_rfc0003_source_contract.py+++ b/server/tests/llm/test_rfc0003_source_contract.py@@ -17,6 +17,7 @@ LLM_DIR = SERVER_DIR / "services" / "llm"MODEL_NODES_DIR = SERVER_DIR / "nodes" / "model"ENDPOINTS_PY = LLM_DIR / "endpoints.py"LOCAL_VALIDATOR_PY = MODEL_NODES_DIR / "_local_validator.py"+ONEPASSWORD_ENROLLMENT_PY = SERVER_DIR / "services" / "credentials" / "enrollment.py"# The two places allowed to touch a "/v1" path segment (AG2): the save-time# resolver, and the native-host derivation used only by native probes.@@ -99,7 +100,7 @@ def test_client_construction_does_no_io():assert not any(isinstance(n, ast.Await) for n in ast.walk(init)), f"{path.name}:{class_name}.__init__ awaits"for path in _python_files(SERVER_DIR / "services", SERVER_DIR / "nodes"):- if path in (ENDPOINTS_PY, LOCAL_VALIDATOR_PY):+ if path in (ENDPOINTS_PY, LOCAL_VALIDATOR_PY, ONEPASSWORD_ENROLLMENT_PY):continueassert "resolve_base_url" not in path.read_text(encoding="utf-8"), (f"{path.relative_to(SERVER_DIR)} probes a base URL; only the save path may"diff --git a/server/tests/llm/test_streaming.py b/server/tests/llm/test_streaming.pyindex bc57e009..7cf97c21 100644--- a/server/tests/llm/test_streaming.py+++ b/server/tests/llm/test_streaming.py@@ -267,7 +267,7 @@ def _unifier_with(name: str, client, *, streaming: bool):registry._REGISTRY[name] = ProviderSpec(name=name, factory=lambda **kwargs: client, sdk_exception_refs=("openai:OpenAIError",))auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)providers = {name: {"streaming": True}} if streaming else {}return ChatUnifier(defaults={"providers": providers}, auth_service=auth, client_cache_size=0)diff --git a/server/tests/llm/test_unifier_client_policy.py b/server/tests/llm/test_unifier_client_policy.pyindex 3735e18d..b60e286c 100644--- a/server/tests/llm/test_unifier_client_policy.py+++ b/server/tests/llm/test_unifier_client_policy.py@@ -30,7 +30,7 @@ async def test_unifier_caches_by_credential_and_retry_policy_and_closes_clients(sdk_exception_refs=("openai:OpenAIError",),)auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}},auth_service=auth,@@ -78,7 +78,7 @@ async def test_unifier_can_surface_structured_error_for_agent_retry_policy():)registry._REGISTRY[name] = specauth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}},auth_service=auth,@@ -130,7 +130,7 @@ async def test_unifier_public_error_does_not_expose_raw_sdk_message():sdk_exception_refs=("openai:OpenAIError",),)auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}},auth_service=auth,@@ -171,7 +171,7 @@ async def test_client_constructor_failure_is_structured_and_safe():sdk_exception_refs=("openai:OpenAIError",),)auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}},auth_service=auth,@@ -219,7 +219,7 @@ async def test_unifier_closes_ephemeral_client_when_cache_is_disabled():sdk_exception_refs=("openai:OpenAIError",),)auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}},auth_service=auth,@@ -269,7 +269,7 @@ async def test_lru_eviction_defers_close_until_in_flight_chat_releases_lease():sdk_exception_refs=("openai:OpenAIError",),)auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)unifier = ChatUnifier(defaults={"providers": {}},auth_service=auth,diff --git a/server/tests/llm/test_unifier_incompatible_models_filter.py b/server/tests/llm/test_unifier_incompatible_models_filter.pyindex cb0fc925..66e4a813 100644--- a/server/tests/llm/test_unifier_incompatible_models_filter.py+++ b/server/tests/llm/test_unifier_incompatible_models_filter.py@@ -22,7 +22,7 @@ from services.llm.providers.openai import OpenAIProvider@pytest.fixturedef auth_service_stub():stub = MagicMock()- stub.get_api_key = AsyncMock(return_value=None)+ stub.resolve_api_key = AsyncMock(return_value=None)return stubdiff --git a/server/tests/llm/test_unifier_transport_errors.py b/server/tests/llm/test_unifier_transport_errors.pyindex c50d463b..23972d0e 100644--- a/server/tests/llm/test_unifier_transport_errors.py+++ b/server/tests/llm/test_unifier_transport_errors.py@@ -23,7 +23,7 @@ def dispatch(monkeypatch):sdk_exception_refs=("google.genai.errors:APIError",),))auth = MagicMock()- auth.get_api_key = AsyncMock(return_value=None)+ auth.resolve_api_key = AsyncMock(return_value=None)return ChatUnifier(defaults={"providers": {}}, auth_service=auth, client_cache_size=0), clientdiff --git a/server/tests/llm/test_unifier_typed_errors.py b/server/tests/llm/test_unifier_typed_errors.pyindex 960e4526..a64a112d 100644--- a/server/tests/llm/test_unifier_typed_errors.py+++ b/server/tests/llm/test_unifier_typed_errors.py@@ -23,7 +23,7 @@ from services.plugin import NodeUserErrordef auth_service_stub():"""Stub auth_service whose get_api_key returns None for ``{provider}_proxy`` lookups."""stub = MagicMock()- stub.get_api_key = AsyncMock(return_value=None)+ stub.resolve_api_key = AsyncMock(return_value=None)return stubdiff --git a/server/tests/llm/test_wiring.py b/server/tests/llm/test_wiring.pyindex 8aba1702..a2f3b9d9 100644--- a/server/tests/llm/test_wiring.py+++ b/server/tests/llm/test_wiring.py@@ -44,7 +44,7 @@ def ai_service():settings = MagicMock()settings.ai_timeout = 30auth = AsyncMock()- auth.get_api_key = AsyncMock(return_value=None) # no proxy+ auth.resolve_api_key = AsyncMock(return_value=None) # no proxychat_unifier = MagicMock()chat_unifier.is_registered = MagicMock(return_value=True)diff --git a/server/tests/nodes/_harness.py b/server/tests/nodes/_harness.pyindex 1e4aa42c..548de6c4 100644--- a/server/tests/nodes/_harness.py+++ b/server/tests/nodes/_harness.py@@ -221,6 +221,7 @@ def _build_mock_ai_service() -> MagicMock:svc = MagicMock(name="AIService")svc.auth = MagicMock(name="AuthService")svc.auth.get_api_key = AsyncMock(return_value="test-api-key")+ svc.auth.resolve_api_key = AsyncMock(return_value="test-api-key")svc.auth.get_stored_models = AsyncMock(return_value=["test-model"])svc.auth.get_oauth_tokens = AsyncMock(return_value=None)svc.execute_chat = AsyncMock(diff --git a/server/tests/nodes/_mocks.py b/server/tests/nodes/_mocks.pyindex 3a40ba1c..bd7ed4cf 100644--- a/server/tests/nodes/_mocks.py+++ b/server/tests/nodes/_mocks.py@@ -76,6 +76,8 @@ def patched_container(auth_service = MagicMock(name="AuthService")auth_service.get_api_key = AsyncMock(side_effect=lambda provider, *a, **kw: api_keys.get(provider))+ auth_service.resolve_api_key = AsyncMock(side_effect=lambda provider, *a, **kw: api_keys.get(provider))+ auth_service.has_valid_key = AsyncMock(side_effect=lambda provider, *a, **kw: bool(api_keys.get(provider)))auth_service.get_oauth_tokens = AsyncMock(side_effect=lambda provider, *a, **kw: oauth_tokens.get(provider))auth_service.get_stored_models = AsyncMock(return_value=[])# Awaitable async writes (handlers like Twitter call these in refresh paths)diff --git a/server/tests/nodes/browser/test_browser_credentials.py b/server/tests/nodes/browser/test_browser_credentials.pynew file mode 100644index 00000000..8b232dbe--- /dev/null+++ b/server/tests/nodes/browser/test_browser_credentials.py@@ -0,0 +1,145 @@+"""Canary tests for configured login; no browser or real credential retrieval."""+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++from nodes.browser._credentials import fill_credentials+from nodes.browser._session import ProfileController++ORIGIN = "https://example.com"+CANARY = " secret-Σ-canary\n "+++def fixture(*, suspension=True, changed_origin=False, capture_error=False):+ controller = ProfileController("profile", "Work")+ controller.active_target_id = "T"+ controller.refs["T"] = {"e1": 1, "e2": 2, "e3": 3}+ calls = []+ async def send(method, args=None, **kwargs):+ calls.append((method, args))+ if method == "Page.getFrameTree":+ return {"frameTree": {"frame": {"url": "https://evil.test" if changed_origin else ORIGIN + "/login"}}}+ if method == "DOM.resolveNode":+ return {"object": {"objectId": str(args["backendNodeId"])}}+ if method == "Runtime.evaluate":+ if args.get("expression") == "document.documentElement":+ return {"result": {"objectId": "document"}}+ return {"result": {"value": {"origin": ORIGIN, "path": "/account", "password": False}}}+ return {"result": {"value": True}}+ page = SimpleNamespace(send=send, detach=AsyncMock())+ runtime = SimpleNamespace(profile=SimpleNamespace(id="profile"), controller=controller, chrome=SimpleNamespace(),+ cli=SimpleNamespace(suspend_for_credentials=AsyncMock(return_value=suspension)),+ page_session=AsyncMock(return_value=page),+ hub=SimpleNamespace(sensitive_barrier=AsyncMock(side_effect=RuntimeError("capture uncertain") if capture_error else None)))+ metadata = {"origin": ORIGIN, "success_path": "/account"}+ auth = SimpleNamespace(get_browser_credential_binding=AsyncMock(return_value=metadata),+ resolve_browser_credentials=AsyncMock(return_value={**metadata, "username": " user ", "password": CANARY}))+ ctx = SimpleNamespace(user_id="owner", execution_id="task", workflow_id="wf", raw={})+ call = SimpleNamespace(credential_binding_id="opaque", username_ref="e1", password_ref="e2", submit_ref="e3")+ return runtime, auth, ctx, call, calls+++async def run_fixture(runtime, auth, ctx, call):+ with patch("core.container.container.auth_service", return_value=auth), patch("services.browser_owners.set_sensitive", AsyncMock()):+ return await fill_credentials(ctx, runtime, call, timeout=5)+++async def test_secret_values_only_enter_private_cdp_with_exact_whitespace():+ runtime, auth, ctx, call, calls = fixture()+ result = await run_fixture(runtime, auth, ctx, call)+ assert result == {"success": True}+ assert CANARY not in str(result)+ fills = [args for method, args in calls if method == "Runtime.callFunctionOn" and "setter.call" in args["functionDeclaration"]]+ assert [args["arguments"][0]["value"] for args in fills] == [" user ", CANARY]+ assert runtime.cli.suspend_for_credentials.await_count == 1+ assert runtime.controller.sensitive_login is False+ assert runtime.controller.needs_observation is True+++async def test_wrong_origin_does_not_resolve_credentials():+ runtime, auth, ctx, call, _ = fixture(changed_origin=True)+ result = await run_fixture(runtime, auth, ctx, call)+ assert result["success"] is False+ auth.resolve_browser_credentials.assert_not_awaited()+ assert runtime.controller.sensitive_login is False+++async def test_uncertain_daemon_suspension_keeps_gate_and_does_not_resolve():+ runtime, auth, ctx, call, _ = fixture(suspension=False)+ result = await run_fixture(runtime, auth, ctx, call)+ assert result["success"] is False+ auth.resolve_browser_credentials.assert_not_awaited()+ assert runtime.controller.sensitive_login is True+++async def test_capture_barrier_failure_does_not_resolve_credentials():+ runtime, auth, ctx, call, _ = fixture(capture_error=True)+ result = await run_fixture(runtime, auth, ctx, call)+ assert result["success"] is False+ auth.resolve_browser_credentials.assert_not_awaited()+++async def test_changed_origin_after_authorization_never_fills():+ runtime, auth, ctx, call, calls = fixture()+ original = runtime.page_session.return_value.send+ async def send(method, args=None, **kwargs):+ if method == "Page.getFrameTree" and auth.resolve_browser_credentials.await_count:+ return {"frameTree": {"frame": {"url": "https://evil.test/"}}}+ return await original(method, args, **kwargs)+ runtime.page_session.return_value.send = send+ result = await run_fixture(runtime, auth, ctx, call)+ assert result["success"] is False and CANARY not in str(result)+ assert not any(method == "Runtime.callFunctionOn" and "setter.call" in args["functionDeclaration"] for method, args in calls)+++async def test_spa_success_cue_cannot_unhide_a_still_filled_username():+ runtime, auth, ctx, call, _ = fixture()+ original = runtime.page_session.return_value.send+ async def send(method, args=None, **kwargs):+ if method == "Runtime.callFunctionOn" and "return !this.isConnected" in args.get("functionDeclaration", ""):+ return {"result": {"value": False}}+ return await original(method, args, **kwargs)+ runtime.page_session.return_value.send = send+ with patch("core.container.container.auth_service", return_value=auth), patch("services.browser_owners.set_sensitive", AsyncMock()):+ result = await fill_credentials(ctx, runtime, call, timeout=1)+ assert result["success"] is False and CANARY not in str(result)+ assert runtime.controller.sensitive_login+++async def test_success_page_password_reflection_keeps_observation_gate():+ runtime, auth, ctx, call, _ = fixture()+ original = runtime.page_session.return_value.send+ async def send(method, args=None, **kwargs):+ if method == "Runtime.callFunctionOn" and "text.includes(password)" in args.get("functionDeclaration", ""):+ return {"result": {"value": False}}+ return await original(method, args, **kwargs)+ runtime.page_session.return_value.send = send+ with patch("core.container.container.auth_service", return_value=auth), patch("services.browser_owners.set_sensitive", AsyncMock()):+ result = await fill_credentials(ctx, runtime, call, timeout=1)+ assert result["success"] is False and CANARY not in str(result)+ assert runtime.controller.sensitive_login+++async def test_late_cleanup_cannot_release_replacement_task():+ controller = ProfileController("profile", "Work")+ controller.claim_task("replacement")+ assert await controller.release_task("old") is False+ assert controller.task_id == "replacement"+++async def test_webmcp_gate_drains_and_rejects_page_metadata_until_restored():+ from nodes.browser._webmcp import WebMcpTracker+ tracker = WebMcpTracker()+ session = SimpleNamespace(on=lambda *_: None, send=AsyncMock())+ await tracker.attach("T", session)+ tracker._added("T", {"tools": [{"name": "safe", "frameId": "F"}]})+ assert tracker.count("T") == 1+ await tracker.sensitive_barrier(True)+ tracker._added("T", {"tools": [{"name": CANARY, "frameId": "F"}]})+ tracker._responded({"invocationId": "late", "output": CANARY})+ assert tracker.tools("T") == [] and tracker._early == {}+ session.send.assert_awaited_with("WebMCP.disable", timeout=5)+ await tracker.sensitive_barrier(False)+ session.send.assert_awaited_with("WebMCP.enable", timeout=5)+ assert CANARY not in str(tracker._tools)diff --git a/server/tests/nodes/browser/test_browser_live_control.py b/server/tests/nodes/browser/test_browser_live_control.pyindex 2c6bb931..bd1f9158 100644--- a/server/tests/nodes/browser/test_browser_live_control.py+++ b/server/tests/nodes/browser/test_browser_live_control.py@@ -32,6 +32,17 @@ async def drain(queue):await asyncio.wait_for(queue._worker, 1)+async def test_protected_login_rejects_takeover_and_queued_input_before_dispatch():+ queue, hub, viewer, session, _ = setup_queue()+ assert queue.enqueue(viewer, {"type": "navigate", "action": "goto", "url": "https://example.test"}, session)+ hub.controller.sensitive_login = True+ assert not queue.enqueue(viewer, {"type": "control_request"}, session)+ assert not queue.enqueue(viewer, {"type": "insert_text", "text": "secret"}, session)+ assert await hub.controller.take_over(viewer.id) == (False, "protected_login")+ await drain(queue)+ hub.navigate.assert_not_awaited()++async def test_only_adjacent_moves_and_wheels_coalesce_without_reordering_keys():queue, hub, viewer, session, _ = setup_queue()for message in [diff --git a/server/tests/nodes/browser/test_browser_login_acceptance.py b/server/tests/nodes/browser/test_browser_login_acceptance.pynew file mode 100644index 00000000..36018aa4--- /dev/null+++ b/server/tests/nodes/browser/test_browser_login_acceptance.py@@ -0,0 +1,125 @@+"""Opt-in controlled local-browser acceptance; never uses external accounts.++BROWSER_ACCEPTANCE_LIVE=1 runs installed Chrome and the already provisioned+browser-use CLI. It does not install software or read real 1Password values.+"""+from __future__ import annotations++import asyncio+import os+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from types import SimpleNamespace+from urllib.parse import parse_qs+from unittest.mock import AsyncMock, patch++import pytest++from nodes.browser._chrome import ChromeProcess+from nodes.browser._cli import BrowserUseCli+from nodes.browser._credentials import fill_credentials+from nodes.browser._egress import EgressProxy+from nodes.browser._netpolicy import NetPolicy+from nodes.browser._runtime import ProfileRuntime+from nodes.browser._session import ProfileController+from nodes.browser._stream import ScreencastHub, Viewer+from nodes.browser._system_browser import discover_browser, browser_version, version_major+from nodes.browser._webmcp import WebMcpTracker++[email protected](os.environ.get("BROWSER_ACCEPTANCE_LIVE") != "1", reason="Opt-in installed-browser acceptance")[email protected]("newline", [False, True], ids=["exact-whitespace", "reject-browser-normalization"])+async def test_controlled_login_preserves_secret_and_drains_live_capture(tmp_path, newline):+ repository = Path(__file__).resolve().parents[4]+ package = repository / ".opencompany" / "packages" / "browser-use"+ exe = "browser-use.exe" if os.name == "nt" else "browser-use"+ cli_path = Path(os.environ.get("BROWSER_ACCEPTANCE_CLI", str(package / "bin" / exe)))+ python_path = package / "tools" / "browser-use" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ if not cli_path.is_file() or not python_path.is_file():+ pytest.skip("Provision the pinned browser-use CLI before live acceptance")+ executable, _ = discover_browser(os.environ.get("BROWSER_CHROME_PATH", ""))+ major = version_major(await browser_version(executable))+ canary = " secret-Σ-private-login" + ("\n" if newline else "") + " "+ accepted = []+ class Fixture(BaseHTTPRequestHandler):+ def log_message(self, *_):+ pass+ def do_GET(self):+ document = b'<form action="/account" method="POST"><label for="u">Username</label><input id="u" name="u" autocomplete="off"><label for="p">Password</label><input id="p" name="p" type="password" autocomplete="off"><button id="s" type="submit">Sign in</button></form>'+ self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8"); self.end_headers(); self.wfile.write(document)+ def do_POST(self):+ values = parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode(), keep_blank_values=True)+ accepted.append(values.get("p") == [canary] and values.get("u") == [" user "])+ self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8"); self.end_headers(); self.wfile.write(b'<h1 id="account">Account</h1>')+ server = ThreadingHTTPServer(("127.0.0.1", 0), Fixture)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ origin = f"http://127.0.0.1:{server.server_port}"+ profile_id = "acceptance-newline" if newline else "acceptance-whitespace"+ proxy = EgressProxy(lambda: NetPolicy(), name=f"browser-acceptance-proxy-{profile_id}")+ proxy_port = await asyncio.to_thread(proxy.start)+ root = tmp_path / "profile"; root.mkdir()+ user_data = root / "user-data"; user_data.mkdir()+ chrome = ChromeProcess(profile_id=profile_id, exe=executable, profile_root=root, user_data_dir=user_data,+ proxy_port=proxy_port, major=major, no_sandbox=False, small_shm=False)+ homes = {key: tmp_path / key for key in ("home", "runtime", "tmp", "workspace", "config")}+ for home in homes.values(): home.mkdir()+ cli = BrowserUseCli(cli_path=cli_path, python_path=python_path, profile_id=profile_id, cdp_http_url="")+ cli.dirs = lambda: homes+ hub = None+ try:+ cdp = await chrome.launch()+ cli.cdp_http_url = f"http://127.0.0.1:{chrome.port}"+ target = (await cdp.page_targets())[0]["targetId"]+ await cli.run("navigate", {"url": origin + "/login", "_target_id": target, "timeout": 25}, timeout=30)+ snapshot = await cli.run("snapshot", {"_target_id": target, "max_chars": 20000, "interactive_only": True, "timeout": 25}, timeout=30)+ assert snapshot.ok+ controller = ProfileController(profile_id, "Controlled fixture")+ controller.active_target_id = target+ controller.tabs[target] = {"target_id": target, "url": origin + "/login", "title": "Fixture"}+ controller.refs[target] = snapshot.value["refs"]+ runtime = ProfileRuntime(profile=SimpleNamespace(id=profile_id), controller=controller, chrome=chrome,+ proxy=proxy, cdp=cdp, cli=cli, webmcp=WebMcpTracker())+ page = await runtime.page_session(target)+ await runtime.webmcp.attach(target, page)+ document = await page.send("DOM.getDocument")+ chosen = []+ for selector in ("#u", "#p", "#s"):+ node = await page.send("DOM.querySelector", {"nodeId": document["root"]["nodeId"], "selector": selector})+ detail = await page.send("DOM.describeNode", {"nodeId": node["nodeId"]})+ backend = detail["node"]["backendNodeId"]+ chosen.append(next(ref for ref, value in snapshot.value["refs"].items() if value == backend))+ hub = ScreencastHub(runtime); runtime.hub = hub+ viewer = Viewer(SimpleNamespace(send_text=AsyncMock(), send_bytes=AsyncMock()), "owner")+ await hub.add(viewer)+ assert hub._active+ metadata = {"origin": origin, "success_origin": origin, "success_path": "/account", "success_selector": "#account"}+ async def resolve(*_args, **_kwargs):+ assert controller.sensitive_login and viewer.privacy_blocked and not hub._active+ assert not (homes["runtime"] / "bu.pid").exists()+ return {**metadata, "username": " user ", "password": canary}+ auth = SimpleNamespace(get_browser_credential_binding=AsyncMock(return_value=metadata), resolve_browser_credentials=resolve)+ ctx = SimpleNamespace(user_id="owner", execution_id="task", workflow_id="wf", raw={})+ call = SimpleNamespace(credential_binding_id="fixture", username_ref=chosen[0], password_ref=chosen[1], submit_ref=chosen[2])+ with patch("core.container.container.auth_service", return_value=auth), patch("services.browser_owners.set_sensitive", AsyncMock()):+ result = await fill_credentials(ctx, runtime, call, timeout=15)+ if newline:+ assert result["success"] is False+ assert accepted == []+ assert controller.sensitive_login and viewer.privacy_blocked+ else:+ assert result == {"success": True}+ assert accepted == [True]+ assert canary not in str(result)+ for home in homes.values():+ for file in home.rglob("*"):+ if file.is_file(): assert canary.encode() not in file.read_bytes()+ finally:+ if hub is not None:+ for viewer in list(hub.viewers.values()): await hub.remove(viewer)+ cli.stop_daemon()+ await chrome.shutdown()+ await asyncio.to_thread(proxy.stop)+ await asyncio.to_thread(server.shutdown)+ server.server_close()diff --git a/server/tests/nodes/browser/test_browser_node.py b/server/tests/nodes/browser/test_browser_node.pyindex 13e1a931..179b292b 100644--- a/server/tests/nodes/browser/test_browser_node.py+++ b/server/tests/nodes/browser/test_browser_node.py@@ -187,6 +187,34 @@ async def test_a_tool_call_cannot_change_the_operator_settings(runtime):assert runtime.cli.calls == [][email protected]("adapter", ["in_process", "temporal"])+async def test_trusted_ask_first_restriction_survives_saved_full_settings(runtime, adapter):+ saved = {"interaction": "full"}+ database = SimpleNamespace(get_node_parameters=AsyncMock(return_value=saved))+ raw = {"tool_args": {"operation": "click", "interaction": "full"}} if adapter == "temporal" else {}+ with patch("services.plugin.deps.get_database", return_value=database):+ result = await BrowserNode().execute_as_tool({"operation": "click", "x": 5, "y": 5, "interaction": "full"},+ {"interaction": "read_only"}, _ctx(**raw))+ assert "read-only" in result["error"]+ assert runtime.cli.calls == []+++async def test_task_lifetime_prevents_same_node_interleaving(runtime):+ runtime.controller.claim_task("another-task")+ result = await _run({"operation": "snapshot"})+ assert result.get("success") is False and result["error_type"] == "BrowserBusy"+ assert runtime.cli.calls == []+++async def test_sensitive_login_blocks_browser_observations(runtime):+ runtime.controller.sensitive_login = True+ for operation in ("snapshot", "screenshot", "page_text", "page_info", "tabs", "webmcp_list"):+ result = await _run({"operation": operation})+ assert result["error_type"] == "sensitive_login"+ assert result.get("url") is None and result.get("title") is None+ assert runtime.cli.calls == []++def test_the_model_schema_has_no_operator_settings_or_host_code():schema = BrowserToolInput.model_json_schema()props = set(schema["properties"])diff --git a/server/tests/nodes/browser/test_browser_owners.py b/server/tests/nodes/browser/test_browser_owners.pynew file mode 100644index 00000000..2fb43c00--- /dev/null+++ b/server/tests/nodes/browser/test_browser_owners.py@@ -0,0 +1,298 @@+"""Shared owner/task claims against SQLAlchemy; no browser processes."""+from __future__ import annotations++import asyncio+import time+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock, patch++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from models.browser_owners import BrowserOwner, BrowserProfileOwner+from models.browser_profiles import BrowserProfileRow+from services import browser_owners as owners+from services.plugin.base import NodeUserError+from nodes.browser._session import ProfileController+++async def database():+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as connection:+ for table in (BrowserOwner.__table__, BrowserProfileOwner.__table__, BrowserProfileRow.__table__):+ await connection.run_sync(table.create)+ db = SimpleNamespace(engine=engine, get_session=async_sessionmaker(engine, expire_on_commit=False))+ async with db.get_session() as session:+ session.add(BrowserOwner(owner_id="alpha", runtime_epoch=owners.RUNTIME_EPOCH, base_url="http://alpha:8000", heartbeat_at=time.time()))+ session.add(BrowserProfileOwner(profile_id="profile", principal_id="owner", owner_id="alpha"))+ session.add(BrowserProfileRow(id="profile", owner_id="owner", name="Work"))+ await session.commit()+ config = SimpleNamespace(distributed_mode=True, browser_replica_id="alpha", browser_replica_url="http://alpha:8000", browser_router_secret="test-forward-secret", secret_key="test-shared-secret")+ controller = ProfileController("profile", "Work")+ runtime = SimpleNamespace(controller_for=lambda _: controller, controller=lambda _: controller)+ with patch.object(owners, "settings", return_value=config), patch("nodes.browser._runtime.get_browser_runtime", return_value=runtime):+ yield db, controller+ await engine.dispose()+++async def test_task_claim_blocks_other_tasks_and_cleanup_is_token_matched(database):+ db, controller = database+ binding = await owners.bind_profile(db, "profile", "owner")+ claimed = await owners.claim_browser_task(db, binding, "owner", "first")+ assert claimed["binding"]["owner_id"] == "alpha"+ with pytest.raises(NodeUserError, match="BrowserBusy"):+ await owners.claim_browser_task(db, binding, "owner", "second")+ assert (await owners.release_browser_task(db, binding, "second"))["released"] is False+ assert controller.task_id == "first"+ assert (await owners.release_browser_task(db, binding, "first"))["released"] is True+ await owners.claim_browser_task(db, binding, "owner", "second")+ assert controller.task_id == "second"+++async def test_unavailable_owner_is_never_reassigned(database):+ db, _ = database+ async with db.get_session() as session:+ row = await session.get(BrowserOwner, "alpha")+ row.heartbeat_at = 0+ await session.commit()+ with patch.object(owners, "replica_id", return_value="beta"):+ binding = await owners.bind_profile(db, "profile", "owner")+ assert binding["owner_id"] == "alpha" and binding["available"] is False++[email protected]("available", [False, True])+async def test_new_profile_preparation_uses_backend_registration_without_registering_worker(database, available):+ db, _ = database+ async with db.get_session() as session:+ backend = await session.get(BrowserOwner, "alpha")+ backend.runtime_epoch = "backend-runtime"+ backend.heartbeat_at = time.time() if available else 0+ session.add(BrowserProfileRow(id="new-profile", owner_id="owner", name="New"))+ await session.commit()+ register = AsyncMock(side_effect=AssertionError("Orchestration workers must not register browser runtimes"))+ with patch.object(owners, "RUNTIME_EPOCH", "generic-worker-runtime"), patch.object(owners, "register_browser_owner", register):+ binding = await owners.bind_profile(db, "new-profile", "owner")+ assert binding["owner_id"] == "alpha"+ assert binding["runtime_epoch"] == "backend-runtime"+ assert binding["available"] is available+ with patch.object(owners, "replica_id", return_value="beta"):+ assert (await owners.bind_profile(db, "new-profile", "owner"))["owner_id"] == "alpha"+ register.assert_not_awaited()+ async with db.get_session() as session:+ assert (await session.get(BrowserOwner, "alpha")).runtime_epoch == "backend-runtime"+ assert (await session.get(BrowserProfileOwner, "new-profile")).owner_id == "alpha"+++async def test_new_profile_requires_preexisting_backend_registration(database):+ db, _ = database+ register = AsyncMock()+ with patch.object(owners, "replica_id", return_value="unregistered"), \+ patch.object(owners, "register_browser_owner", register), \+ pytest.raises(NodeUserError, match="owner is not registered"):+ await owners.bind_profile(db, "new-profile", "owner")+ register.assert_not_awaited()+ async with db.get_session() as session:+ assert await session.get(BrowserProfileOwner, "new-profile") is None+++async def test_fenced_owner_cannot_claim(database):+ db, _ = database+ binding = await owners.bind_profile(db, "profile", "owner")+ async with db.get_session() as session:+ row = await session.get(BrowserOwner, "alpha")+ row.runtime_epoch = "replacement-runtime"+ await session.commit()+ with pytest.raises(NodeUserError, match="fenced"):+ await owners.claim_browser_task(db, binding, "owner", "task")+++async def test_claim_restores_current_gate_instead_of_stale_frozen_binding(database):+ db, controller = database+ binding = await owners.bind_profile(db, "profile", "owner")+ await owners.set_sensitive(db, "profile", None, True)+ claimed = await owners.claim_browser_task(db, binding, "owner", "task")+ assert claimed["binding"]["sensitive_login"] is True+ assert controller.sensitive_login is True+++async def test_busy_live_operation_rolls_back_durable_task_claim(database):+ db, controller = database+ binding = await owners.bind_profile(db, "profile", "owner")+ await controller._op_lock.acquire()+ try:+ with pytest.raises(NodeUserError, match="BrowserBusy"):+ await owners.claim_browser_task(db, binding, "owner", "task")+ finally:+ controller._op_lock.release()+ async with db.get_session() as session:+ assert (await session.get(BrowserProfileOwner, "profile")).task_id is None+++async def test_viewer_routing_keeps_active_frozen_profile_after_parameter_edit(database):+ db, _ = database+ db.get_node_parameters = AsyncMock(return_value={"profile_id": "changed"})+ async with db.get_session() as session:+ session.add(BrowserProfileRow(id="changed", owner_id="owner", name="Changed"))+ session.add(BrowserProfileOwner(profile_id="changed", principal_id="owner", owner_id="alpha"))+ await session.commit()+ binding = {**await owners.bind_profile(db, "profile", "owner"), "workflow_id": "wf", "node_id": "browser"}+ await owners.claim_browser_task(db, binding, "owner", "task")+ with patch("nodes.browser._handlers.resolve_browser_node", AsyncMock()):+ assert (await owners.routing_for_node(db, "wf", "browser", "owner"))["profile_id"] == "profile"+ await owners.release_browser_task(db, binding, "stale")+ assert (await owners.routing_for_node(db, "wf", "browser", "owner"))["profile_id"] == "profile"+ await owners.release_browser_task(db, binding, "task")+ assert (await owners.routing_for_node(db, "wf", "browser", "owner"))["profile_id"] == "changed"++[email protected]("distributed", [False, True])+async def test_recovered_viewer_session_uses_active_profile_in_local_and_distributed_mode(database, distributed):+ from nodes.browser import _handlers+ from nodes.browser._runtime import BrowserRuntime++ db, _ = database+ db.get_node_parameters = AsyncMock(return_value={"profile_id": "changed"})+ async with db.get_session() as session:+ row = await session.get(BrowserProfileOwner, "profile")+ row.task_id, row.workflow_id, row.browser_node_id = "recovered-task", "wf", "browser"+ session.add(BrowserProfileRow(id="changed", owner_id="owner", name="Changed"))+ await session.commit()+ runtime = BrowserRuntime() # Recovered owner has no in-memory node sessions.+ config = SimpleNamespace(distributed_mode=distributed, browser_replica_id="alpha")+ authorized_node = ({}, {"id": "browser", "data": {"label": "Browser"}})+ with patch.object(owners, "settings", return_value=config), \+ patch.object(_handlers, "get_database", return_value=db), \+ patch.object(_handlers, "resolve_browser_node", AsyncMock(return_value=authorized_node)) as authorize, \+ patch("nodes.browser._runtime.get_browser_runtime", return_value=runtime):+ _, recovered_session = await _handlers._session_for_node("owner", "wf", "browser", create=True)+ assert recovered_session.profile_id == "profile"+ authorize.assert_awaited_with("owner", "wf", "browser")+ assert runtime.find_session("wf", "browser") is recovered_session+++async def test_inprocess_delegated_claim_survives_stale_reset_and_cleans_up_with_its_own_token(database):+ from nodes.agent.browser_agent import BrowserAgentNode, BrowserAgentParams+ from nodes.agent._specialized import SpecializedAgentBase+ from nodes.browser._runtime import BrowserRuntime+ from services.plugin.context import NodeContext++ db, _ = database+ db.get_node_parameters = AsyncMock(return_value={"profile_id": "profile"})+ graph = {"owner_id": "owner", "nodes": [{"id": "agent", "type": "browser_agent"},+ {"id": "browser", "type": "browser"}], "edges": [+ {"source": "browser", "target": "agent", "targetHandle": "input-tools"}]}+ context = NodeContext.from_legacy("agent", "browser_agent", {**graph, "workflow_id": "wf",+ "user_id": "owner", "execution_id": "old-execution", "parent_task_id": "delegated-child"})+ started, finish = asyncio.Event(), asyncio.Event()+ async def reason(*_):+ started.set()+ await finish.wait()+ return {"response": "Complete"}+ runtime = BrowserRuntime()+ with patch("services.plugin.deps.get_database", return_value=db), \+ patch("nodes.browser._handlers.resolve_browser_node", AsyncMock()), \+ patch("nodes.browser._runtime.get_browser_runtime", return_value=runtime), \+ patch.object(SpecializedAgentBase, "execute_op", reason):+ child = asyncio.create_task(BrowserAgentNode().execute_op(context, BrowserAgentParams()))+ try:+ await asyncio.wait_for(started.wait(), 2)+ assert runtime.controller("profile").task_id == "delegated-child:agent"+ reset = dict(node_id="agent", workflow_id="wf", execution_id="old-execution",+ generation=1, graph=graph, database=db)+ assert await BrowserAgentNode.reset_execution_state(**reset) == {"released": False}+ async with db.get_session() as session:+ assert (await session.get(BrowserProfileOwner, "profile")).task_id == "delegated-child:agent"+ finish.set()+ await child+ assert runtime.controller("profile").task_id is None+ binding = await owners.routing_for_node(db, "wf", "browser", "owner")+ await owners.claim_browser_task(db, binding, "owner", "new-execution:agent")+ assert await BrowserAgentNode.reset_execution_state(**reset) == {"released": False}+ assert runtime.controller("profile").task_id == "new-execution:agent"+ await owners.cleanup_browser_task(db, binding, "new-execution:agent")+ finally:+ finish.set()+ await child+++async def test_ambiguous_active_browser_bindings_fail_closed(database):+ db, _ = database+ db.get_node_parameters = AsyncMock(return_value={})+ async with db.get_session() as session:+ first = await session.get(BrowserProfileOwner, "profile")+ first.task_id, first.workflow_id, first.browser_node_id = "task", "wf", "browser"+ session.add(BrowserProfileOwner(profile_id="other", principal_id="owner", owner_id="alpha",+ task_id="other-task", workflow_id="wf", browser_node_id="browser"))+ await session.commit()+ with patch("nodes.browser._handlers.resolve_browser_node", AsyncMock()), pytest.raises(NodeUserError, match="ambiguous"):+ await owners.routing_for_node(db, "wf", "browser", "owner")+++async def test_runtime_open_restores_recovered_durable_task_and_capture_gate(database):+ from nodes.browser._runtime import BrowserRuntime+ from nodes.browser._profiles import ProfileStore+ db, _ = database+ async with db.get_session() as session:+ row = await session.get(BrowserProfileOwner, "profile")+ row.task_id, row.sensitive_login, row.needs_observation = "recovered-task", True, True+ await session.commit()+ runtime = BrowserRuntime()+ runtime._profiles["profile"] = SimpleNamespace(running=True)+ profile = await ProfileStore(db).get("owner", "profile")+ with patch("services.plugin.deps.get_database", return_value=db), patch.object(runtime, "_settings", return_value=SimpleNamespace(distributed_mode=True)):+ await runtime.open(profile)+ controller = runtime.controller("profile")+ assert controller.task_id == "recovered-task"+ assert controller.sensitive_login and controller.needs_observation+++async def test_claim_applies_frozen_network_policy_before_first_model_turn(database):+ from nodes.browser._netpolicy import NetPolicy+ db, controller = database+ binding = {**await owners.bind_profile(db, "profile", "owner"), "workflow_id": "wf", "node_id": "browser",+ "browser_policy": {"allowed_domains": "example.test", "allow_private_network": False}}+ runtime = SimpleNamespace(controller_for=lambda _: controller,+ register_session=lambda session: session, base_policy=lambda **args: NetPolicy(**args))+ with patch("nodes.browser._runtime.get_browser_runtime", return_value=runtime):+ await owners.claim_browser_task(db, binding, "owner", "task")+ assert controller.lease_session.node_id == "browser"+ assert controller.current_policy().allowed_domains == ("example.test",)+++async def test_workflow_profile_cleanup_never_deletes_under_unavailable_owner(database):+ from nodes.browser import _cleanup_deleted_workflow_profile+ db, _ = database+ db.get_workflow = AsyncMock(return_value=None)+ async with db.get_session() as session:+ profile = await session.get(BrowserProfileRow, "profile")+ profile.kind, profile.workflow_id = "employee", "wf"+ owner = await session.get(BrowserOwner, "alpha")+ owner.heartbeat_at = 0+ await session.commit()+ remove = Mock()+ with patch.object(owners, "replica_id", return_value="beta"), patch("nodes.browser._profiles.remove_profile_files", remove):+ assert await _cleanup_deleted_workflow_profile(db, "owner", "profile", "wf") == {"success": False, "deferred": True}+ remove.assert_not_called()+ async with db.get_session() as session:+ assert await session.get(BrowserProfileRow, "profile") is not None+++async def test_workflow_profile_cleanup_refuses_association_while_workflow_exists(database):+ from nodes.browser import _cleanup_deleted_workflow_profile+ db, _ = database+ db.get_workflow = AsyncMock(return_value={"id": "wf"})+ with pytest.raises(NodeUserError, match="not associated"):+ await _cleanup_deleted_workflow_profile(db, "owner", "profile", "wf")+++async def test_forward_authorization_binds_principal_method_path_body_and_expiry(database):+ body = b'{"command":"browser_session"}'+ token = owners.sign_forward("owner", "POST", "/api/browser/owner/command", body)+ assert owners.verify_forward(token, "POST", "/api/browser/owner/command", body) == "owner"+ for method, path, supplied in (("GET", "/api/browser/owner/command", body), ("POST", "/different", body), ("POST", "/api/browser/owner/command", body + b" ")):+ with pytest.raises(NodeUserError, match="authorization"):+ owners.verify_forward(token, method, path, supplied)+ with patch.object(owners.time, "time", return_value=time.time() + 60):+ with pytest.raises(NodeUserError, match="authorization"):+ owners.verify_forward(token, "POST", "/api/browser/owner/command", body)diff --git a/server/tests/nodes/browser/test_browser_runtime_units.py b/server/tests/nodes/browser/test_browser_runtime_units.pyindex bca4e626..fc3dc216 100644--- a/server/tests/nodes/browser/test_browser_runtime_units.py+++ b/server/tests/nodes/browser/test_browser_runtime_units.py@@ -82,6 +82,59 @@ def test_testing_browser_flags_are_explicit(tmp_path):assert any(a.startswith("--user-agent=") for a in argv)+async def test_live_profile_lock_prevents_orphan_sweep(tmp_path, monkeypatch):+ from unittest.mock import Mock+ from nodes.browser import _chrome+ chrome = _chrome.ChromeProcess(profile_id="locked", exe=Path("chrome"), profile_root=tmp_path,+ user_data_dir=tmp_path / "user-data", proxy_port=1, major=154, no_sandbox=False, small_shm=False)+ monkeypatch.setattr(chrome._profile_lock, "acquire", lambda: False)+ sweep = Mock()+ monkeypatch.setattr(_chrome, "sweep_orphan", sweep)+ with pytest.raises(_chrome.NodeUserError, match="open in another"):+ await chrome._pre_spawn()+ sweep.assert_not_called()+++async def test_secret_phase_refuses_pid_for_another_daemon_home(tmp_path, monkeypatch):+ from types import SimpleNamespace+ from unittest.mock import Mock+ import psutil+ cli = BrowserUseCli(cli_path=Path("cli"), python_path=Path("py"), profile_id="profile", cdp_http_url="")+ homes = {name: tmp_path / name for name in ("home", "runtime", "tmp", "workspace", "config")}+ for home in homes.values(): home.mkdir()+ (homes["runtime"] / "bu.pid").write_text("9")+ monkeypatch.setattr(cli, "dirs", lambda: homes)+ process = SimpleNamespace(cmdline=lambda: ["python", "browser_harness"], environ=lambda: {"BH_HOME": str(tmp_path / "other-profile")})+ monkeypatch.setattr(psutil, "Process", lambda _: process)+ stop = Mock()+ monkeypatch.setattr(cli, "stop_daemon", stop)+ assert await cli.suspend_for_credentials() is False+ stop.assert_not_called()+++async def test_prior_epoch_retirement_only_visits_matching_profile(tmp_path, monkeypatch):+ from types import SimpleNamespace+ from services import browser_owners+ current = tmp_path / browser_owners.RUNTIME_EPOCH / "profile"+ current.mkdir(parents=True)+ previous = tmp_path / ("0" * 32) / "profile"+ (previous / "runtime").mkdir(parents=True)+ (previous / "runtime" / "bu.pid").write_text("9")+ other = tmp_path / ("1" * 32) / "other-profile" / "runtime"+ other.mkdir(parents=True)+ (other / "bu.pid").write_text("10")+ cli = BrowserUseCli(cli_path=Path("cli"), python_path=Path("py"), profile_id="profile", cdp_http_url="")+ monkeypatch.setattr(cli, "dirs", lambda: {"home": current / "home"})+ monkeypatch.setattr(browser_owners, "settings", lambda: SimpleNamespace(distributed_mode=True))+ visited = []+ async def suspended(self):+ visited.append(self.dirs()["runtime"])+ return True+ monkeypatch.setattr(BrowserUseCli, "suspend_for_credentials", suspended)+ assert await cli.suspend_prior_epochs()+ assert visited == [previous / "runtime"]++async def test_cli_timeout_stops_the_daemon_and_reports_uncertain_outcome(monkeypatch, tmp_path):import asynciofrom types import SimpleNamespacediff --git a/server/tests/nodes/browser/test_browser_stream.py b/server/tests/nodes/browser/test_browser_stream.pyindex 4719c232..ffe7833c 100644--- a/server/tests/nodes/browser/test_browser_stream.py+++ b/server/tests/nodes/browser/test_browser_stream.py@@ -81,3 +81,28 @@ async def test_pending_retry_stops_when_no_visible_viewer_or_browser_closes(monkawait hub._on_controller("closed", {"reason": "stopped"})await asyncio.gather(retry, return_exceptions=True)assert retry.cancelled() and runtime.page_session.await_count == 1+++async def test_sensitive_barrier_drains_frames_and_redacts_metadata():+ hub, viewer, runtime, session = make_hub()+ controller = ProfileController("profile", "Work")+ controller.active_target_id = "page"+ controller.tabs = {"page": {"target_id": "page", "url": "https://example.com/?secret=canary", "title": "canary"}}+ hub.controller = controller+ await hub.add(viewer)+ viewer.pending = b"canary-frame"+ viewer.send_json({"type": "page", "url": "canary"})+ controller.sensitive_login = True+ await hub.sensitive_barrier(True)+ assert viewer.pending is None and viewer.privacy_blocked is True+ assert hub.tabs_message() == {"type": "tabs", "tabs": []}+ messages = []+ while not viewer.control.empty():+ messages.append(viewer.control.get_nowait())+ assert "canary" not in str(messages)+ calls = runtime.page_session.await_count+ await hub._refresh()+ assert runtime.page_session.await_count == calls+ hub._on_dialog({"message": "canary"})+ assert viewer.control.empty()+ await hub.remove(viewer)diff --git a/server/tests/nodes/browser/test_system_browser.py b/server/tests/nodes/browser/test_system_browser.pyindex 6201855c..3f199883 100644--- a/server/tests/nodes/browser/test_system_browser.py+++ b/server/tests/nodes/browser/test_system_browser.py@@ -321,7 +321,8 @@ async def test_start_records_connected_version_and_passes_actual_major(monkeypatchrome = SimpleNamespace(launch=AsyncMock(return_value=cdp), port=9000)constructor = Mock(return_value=chrome)monkeypatch.setattr(module, "ChromeProcess", constructor)- monkeypatch.setattr(module, "BrowserUseCli", Mock(return_value=SimpleNamespace(stop_daemon=Mock())))+ monkeypatch.setattr(module, "BrowserUseCli", Mock(return_value=SimpleNamespace(stop_daemon=Mock(),+ suspend_prior_epochs=AsyncMock(return_value=True), suspend_for_credentials=AsyncMock(return_value=True))))record = AsyncMock()monkeypatch.setattr(_profiles, "ProfileStore", lambda db: SimpleNamespace(record_chrome_major=record))monkeypatch.setattr(deps, "get_database", lambda: object())diff --git a/server/tests/nodes/test_browser_agent_creation.py b/server/tests/nodes/test_browser_agent_creation.pynew file mode 100644index 00000000..35c2f0d3--- /dev/null+++ b/server/tests/nodes/test_browser_agent_creation.py@@ -0,0 +1,23 @@+"""Agent Builder shares the atomic Browser capability recipe."""+from tests.nodes._agent_builder_harness import (+ builder_fixture, database_fixture, call, ctx, node, save_graph, saved,+)+from services.graph_build import tool_edge+++async def test_builder_creates_one_complete_browser_bundle_with_inherited_model(builder, database):+ lead = "7:orchestrator_agent:1"+ await save_graph(database, {"nodes": [node(lead, "orchestrator_agent", "Lead"), node("7:agentBuilder:1", "agentBuilder", "Builder")],+ "edges": [tool_edge("7:agentBuilder:1", lead).to_dict()]}, {lead: {"provider": "openai", "model": "saved-model"}})+ result = await call("add_subagent", ctx(lead), agent_type="browser_agent", purpose="Read fixture account")+ assert result.operations, result.summary+ graph = await saved(database)+ agent = next(node for node in graph["nodes"] if node["type"] == "browser_agent")+ assert (await database.get_node_parameters(agent["id"]))["model"] == "saved-model"+ assert "Read fixture account" in (await database.get_node_parameters(agent["id"]))["system_message"]+ assert {node["type"] for node in graph["nodes"]} >= {"browser", "visionAnalyze", "context", "masterSkill"}+ browser = next(node for node in graph["nodes"] if node["type"] == "browser")+ assert any(edge["source"] == browser["id"] and edge["target"] == agent["id"] and edge["targetHandle"] == "input-tools" for edge in graph["edges"])+ await call("add_subagent", ctx(lead), agent_type="browser_agent", purpose="Read fixture account")+ assert len((await saved(database))["nodes"]) == len(graph["nodes"])+ assert result.operationsdiff --git a/server/tests/services/employees/test_apply_changes.py b/server/tests/services/employees/test_apply_changes.pyindex 9a85764b..877003a2 100644--- a/server/tests/services/employees/test_apply_changes.py+++ b/server/tests/services/employees/test_apply_changes.py@@ -17,13 +17,13 @@ SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(useclass Auth:- async def has_valid_key(self, key):+ async def has_valid_key(self, key, *, principal=None):return Falseasync def get_oauth_tokens(self, provider):return None- async def list_api_key_providers(self):+ async def list_api_key_providers(self, *, principal=None):return []diff --git a/server/tests/services/employees/test_enable_talk.py b/server/tests/services/employees/test_enable_talk.pyindex 2fab9c64..c98a23f5 100644--- a/server/tests/services/employees/test_enable_talk.py+++ b/server/tests/services/employees/test_enable_talk.py@@ -26,13 +26,13 @@ SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(useclass Auth:- async def has_valid_key(self, key):+ async def has_valid_key(self, key, *, principal=None):return key == "openai"async def get_oauth_tokens(self, provider):return None- async def list_api_key_providers(self):+ async def list_api_key_providers(self, *, principal=None):return ["openai"]diff --git a/server/tests/services/employees/test_generate_setup.py b/server/tests/services/employees/test_generate_setup.pyindex 4c27dc2a..3f82f153 100644--- a/server/tests/services/employees/test_generate_setup.py+++ b/server/tests/services/employees/test_generate_setup.py@@ -47,7 +47,7 @@ class FakeDatabase:class FakeConnections:- def __init__(self, auth_service=None):+ def __init__(self, auth_service=None, *, principal=None):passasync def is_connected(self, provider_id):@@ -83,7 +83,7 @@ class FakeUnifier:class Auth:- async def get_api_key(self, provider, session_id="default"):+ async def resolve_api_key(self, provider, session_id="default", *, principal=None):return "sk-test"diff --git a/server/tests/services/employees/test_handlers.py b/server/tests/services/employees/test_handlers.pyindex f0b875f7..e02925e4 100644--- a/server/tests/services/employees/test_handlers.py+++ b/server/tests/services/employees/test_handlers.py@@ -16,13 +16,13 @@ from services.ws_handler_registry import get_ws_handlers@pytest.fixture()def container(monkeypatch, real_database):class Auth:- async def has_valid_key(self, key):+ async def has_valid_key(self, key, *, principal=None):return Falseasync def get_oauth_tokens(self, provider):return None- async def list_api_key_providers(self):+ async def list_api_key_providers(self, *, principal=None):return []import core.container as container_modulediff --git a/server/tests/services/employees/test_hire_handler.py b/server/tests/services/employees/test_hire_handler.pyindex bcab8470..c87f6681 100644--- a/server/tests/services/employees/test_hire_handler.py+++ b/server/tests/services/employees/test_hire_handler.py@@ -43,7 +43,7 @@ def payload(**patch):class FakeConnections:ai = True- def __init__(self, _auth=None):+ def __init__(self, _auth=None, *, principal=None):passasync def connected_app_ids(self):diff --git a/server/tests/services/employees/test_identity.py b/server/tests/services/employees/test_identity.pyindex 8dce66fc..d34a35f5 100644--- a/server/tests/services/employees/test_identity.py+++ b/server/tests/services/employees/test_identity.py@@ -18,13 +18,13 @@ AGENT = "1:aiAgent:1"@pytest.fixturedef setup(monkeypatch, real_database, tmp_path):class Auth:- async def has_valid_key(self, key):+ async def has_valid_key(self, key, *, principal=None):return Falseasync def get_oauth_tokens(self, provider):return None- async def list_api_key_providers(self):+ async def list_api_key_providers(self, *, principal=None):return []import core.container as container_modulediff --git a/server/tests/services/employees/test_list_employees.py b/server/tests/services/employees/test_list_employees.pyindex 97228249..c8635f5e 100644--- a/server/tests/services/employees/test_list_employees.py+++ b/server/tests/services/employees/test_list_employees.py@@ -25,13 +25,13 @@ class FakeAuth:self.keys = set(keys)self.oauth = dict(oauth or {})- async def has_valid_key(self, key):+ async def has_valid_key(self, key, *, principal=None):return key in self.keysasync def get_oauth_tokens(self, provider):return self.oauth.get(provider)- async def list_api_key_providers(self):+ async def list_api_key_providers(self, *, principal=None):return sorted(self.keys)diff --git a/server/tests/services/employees/test_start_employee.py b/server/tests/services/employees/test_start_employee.pyindex be423a78..ad245992 100644--- a/server/tests/services/employees/test_start_employee.py+++ b/server/tests/services/employees/test_start_employee.py@@ -68,7 +68,7 @@ def harness(monkeypatch):monkeypatch.setattr(deployment_handlers, "start_saved_workflow", start_saved)class Connections:- def __init__(self, _auth):+ def __init__(self, _auth, *, principal=None):passasync def ai_providers(self):diff --git a/server/tests/services/employees/test_team_recipe.py b/server/tests/services/employees/test_team_recipe.pyindex 2ceb8480..b39251f9 100644--- a/server/tests/services/employees/test_team_recipe.py+++ b/server/tests/services/employees/test_team_recipe.py@@ -58,6 +58,24 @@ def test_selection_is_bounded_and_job_specific():assert len(select_responsibilities("Research software and social posts and email appointments")) == 3+def test_new_browser_employee_gets_complete_private_capability():+ built = build(job="Use the browser to read website accounts")+ member = next(member for member in built.team_plan["members"] if member["node_type"] == "browser_agent")+ tools = [node for node in built.nodes if node["id"] in member["tools"]]+ assert {node["type"] for node in tools} >= {"browser", "visionAnalyze"}+ browser = next(node for node in tools if node["type"] == "browser")+ assert [edge["target"] for edge in built.edges if edge.get("source") == browser["id"] and edge.get("targetHandle") == "input-tools"] == [member["node_id"]]+ skills = next(edge["source"] for edge in built.edges if edge["target"] == member["node_id"] and edge.get("targetHandle") == "input-skill")+ assert built.parameters[skills]["skills_config"]["browser-skill"]["enabled"]+ assert sum(edge["target"] == member["node_id"] and edge.get("targetHandle") == "input-context" for edge in built.edges) == 1+ assert built.parameters[member["node_id"]]["model"] == "configured-model"+++def test_browser_employee_respects_companion_node_policy():+ with pytest.raises(BuildError, match="Browser tools"):+ build(job="Use the browser to read website accounts", allowed=lambda kind: kind != "visionAnalyze")++def test_hire_refuses_a_recipe_that_reintroduces_shared_tools(monkeypatch):from services.employees import team_recipefrom services.graph_build import tool_edgediff --git a/server/tests/services/employees/test_work_progress.py b/server/tests/services/employees/test_work_progress.pyindex 707c9ec4..42e0e611 100644--- a/server/tests/services/employees/test_work_progress.py+++ b/server/tests/services/employees/test_work_progress.py@@ -217,7 +217,7 @@ async def test_employee_detail_preserves_job_progress_and_adds_work_progress(reaawait real_database.save_workflow(workflow_id=wf.id, name="Maya", slug="progress-maya", data=wf.data)await add(real_database, Employee(id="employee-row", workflow_id=wf.id, owner_id="owner", team_plan={"version": 1}), job(team_id=None, state="queued"))monkeypatch.setattr(summaries, "_summary", AsyncMock(return_value={"workflow_id": wf.id, "pending_approvals": 0, "browser_request": None}))- monkeypatch.setattr(summaries, "Connections", lambda _: SimpleNamespace(has_ai=AsyncMock(return_value=True)))+ monkeypatch.setattr(summaries, "Connections", lambda _, **kwargs: SimpleNamespace(has_ai=AsyncMock(return_value=True)))result = await summaries.get_employee_summary(real_database, wf.id, auth_service=None)assert result["job_progress"] == await job_progress(real_database, wf.id)assert result["work_progress"]["state"] == "queued"diff --git a/server/tests/services/memory/test_vector_store.py b/server/tests/services/memory/test_vector_store.pyindex 2f5924d3..b31e168b 100644--- a/server/tests/services/memory/test_vector_store.py+++ b/server/tests/services/memory/test_vector_store.py@@ -61,7 +61,7 @@ async def test_store_cache_separates_credentials_without_exposing_them(def __init__(self, key):self.key = key- async def get_api_key(self, provider, session_id):+ async def resolve_api_key(self, provider, session_id):assert (provider, session_id) == ("openai", "default")return self.keydiff --git a/server/tests/services/test_process_environment.py b/server/tests/services/test_process_environment.pynew file mode 100644index 00000000..f6fa4929--- /dev/null+++ b/server/tests/services/test_process_environment.py@@ -0,0 +1,286 @@+"""Bootstrap credentials never enter ordinary child processes or restarts."""++from __future__ import annotations++import asyncio+import json+import os+import sys+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from nodes.filesystem._backend import WorkspaceBackend+from services._supervisor.process import BaseProcessSupervisor+from services.cli_agent.service import AICliService+from services.cli_agent.session import AICliSession+from services.cli_agent.transports.posix import PosixPtyTransport+from services.cli_agent.transports.windows import WindowsPtyTransport+from services.cli_agent.types import ClaudeTaskSpec+from services.events.cli import run_cli_command+from services.process_environment import without_onepassword_environment+from services.process_service import ProcessService+++def bootstrap_environment(monkeypatch):+ monkeypatch.setenv("OP_SERVICE_ACCOUNT_TOKEN", "canary-bootstrap-token")+ monkeypatch.setenv("OP_CONNECT_TOKEN", "canary-connect-token")+ monkeypatch.setenv("OP_CONNECT_HOST", "https://canary.invalid")+ monkeypatch.setenv("OP_SESSION_example", "canary-desktop-session")+ monkeypatch.setenv("OPENCOMPANY_ENV_CANARY", "ordinary\tΩ ")+++def _assert_contained(env):+ assert not any(key.upper().startswith("OP_") for key in env)+ assert env["OPENCOMPANY_ENV_CANARY"] == "ordinary\tΩ "+++def test_explicit_environment_retains_values_and_does_not_mutate_input():+ source = {+ "op_service_account_token": "canary-token",+ "OP_SESSION_ACCOUNT": "canary-session",+ "OPERATION_MODE": "unchanged",+ "OPENCOMPANY_ENV_CANARY": "ordinary\tΩ ",+ "EMPTY_VALUE": "",+ }+ original = dict(source)+ child = without_onepassword_environment(source)+ _assert_contained(child)+ assert child["OPERATION_MODE"] == "unchanged"+ assert child["EMPTY_VALUE"] == ""+ assert source == original+ # Explicit isolation must not silently turn into ambient inheritance.+ assert without_onepassword_environment({}) == {}+++async def test_supervisor_real_child_cannot_read_bootstrap_after_subclass_override(+ bootstrap_environment,+):+ class EnvironmentProbe(BaseProcessSupervisor):+ pipe_streams = True++ def __init__(self):+ super().__init__()+ self.lines = []++ def binary_path(self):+ return Path(sys.executable)++ def argv(self):+ probe = (+ "import os,json; print(json.dumps({'op_keys':"+ "[k for k in os.environ if k.upper().startswith('OP_')],"+ "'ordinary':os.environ['OPENCOMPANY_ENV_CANARY'],"+ "'override':os.environ['CHILD_OVERRIDE']}))"+ )+ return [sys.executable, "-c", probe]++ def env(self):+ # A subclass may merge ambient variables or add overrides.+ return {**os.environ, "op_override": "canary-override", "CHILD_OVERRIDE": "kept"}++ def stdout_log(self, line):+ self.lines.append(line)++ def stderr_log(self, line):+ raise AssertionError(line)++ supervisor = EnvironmentProbe()+ await supervisor._do_start()+ assert await supervisor._proc.wait() == 0+ await asyncio.gather(*supervisor._drain_tasks)+ observation = json.loads(supervisor.lines[0].partition("] ")[2])+ assert observation == {"op_keys": [], "ordinary": "ordinary\tΩ ", "override": "kept"}+ assert os.environ["OP_SERVICE_ACCOUNT_TOKEN"] == "canary-bootstrap-token"+ await supervisor._do_stop()+++async def test_process_manager_contains_ambient_and_extra_env_across_restart(+ bootstrap_environment, monkeypatch, tmp_path,+):+ calls = []++ async def spawn(*argv, **kwargs):+ calls.append(kwargs["env"])+ return SimpleNamespace(pid=42, stdout=object(), stderr=object())++ service = ProcessService()+ monkeypatch.setattr("asyncio.create_subprocess_exec", spawn)+ monkeypatch.setattr("services.process_service.shutil.which", lambda _: sys.executable)+ monkeypatch.setattr("core.config.Settings", lambda: SimpleNamespace(workspace_base_resolved=str(tmp_path)))+ monkeypatch.setattr("core.paths.daemons_dir", lambda: tmp_path / "daemons")+ monkeypatch.setattr(service, "_read_stream", AsyncMock())++ async def stop(name, workflow_id="default"):+ service._processes[service._key(workflow_id, name)].status = "stopped"+ return {"success": True}++ monkeypatch.setattr(service, "stop", stop)+ extra = {"OP_SERVICE_ACCOUNT_TOKEN": "canary-user-override", "op_session_other": "canary", "APP_MODE": "same"}+ accepted = await service.start("env-probe", "python", working_directory=str(tmp_path), extra_env=extra)+ assert accepted["success"]+ managed = service._processes[("default", "env-probe")]+ assert managed.extra_env == {"APP_MODE": "same"}+ assert (await service.restart("env-probe"))["success"]+ await asyncio.sleep(0)+ assert len(calls) == 2+ for env in calls:+ _assert_contained(env)+ assert env["APP_MODE"] == "same"+ assert env["PYTHONUNBUFFERED"] == "1"+ assert extra["OP_SERVICE_ACCOUNT_TOKEN"] == "canary-user-override"++[email protected]("transport_class", [PosixPtyTransport, WindowsPtyTransport])+async def test_pty_boundary_filters_environment_after_any_caller_override(+ transport_class, bootstrap_environment, tmp_path,+):+ observed = []++ class PtyStub:+ @staticmethod+ def spawn(argv, **kwargs):+ observed.append(kwargs)+ return SimpleNamespace(pid=42)++ transport = transport_class()+ transport._pty_process_cls = PtyStub+ caller_env = {**os.environ, "op_override": "canary-override", "TERM": "xterm-256color"}+ original = dict(caller_env)+ handle = await transport.spawn([sys.executable, "-c", "pass"], cwd=tmp_path, env=caller_env)+ assert handle.pid == 42+ _assert_contained(observed[0]["env"])+ assert observed[0]["env"]["TERM"] == "xterm-256color"+ assert observed[0]["cwd"] == str(tmp_path)+ assert observed[0]["dimensions"] == (24, 80)+ assert caller_env == original++[email protected]("inherit_env", [False, True])+def test_filesystem_shell_filters_final_env_without_changing_inheritance(+ bootstrap_environment, monkeypatch, tmp_path, inherit_env,+):+ observed = []++ def run(argv, **kwargs):+ observed.append(kwargs)+ return SimpleNamespace(returncode=0, stdout="safe-output", stderr="")++ monkeypatch.setattr("nodes.filesystem._backend._find_nu", lambda: None)+ monkeypatch.setattr("nodes.filesystem._backend.subprocess.run", run)+ backend = WorkspaceBackend(+ tmp_path,+ inherit_env=inherit_env,+ env={"OP_SERVICE_ACCOUNT_TOKEN": "canary-explicit", "CHILD_VALUE": "kept"},+ )+ # Even late additions must be contained at the execution boundary.+ backend._env["op_late_addition"] = "canary-late"+ result = backend.execute("echo safe-output")+ assert result.exit_code == 0+ env = observed[0]["env"]+ assert not any(key.upper().startswith("OP_") for key in env)+ assert env["CHILD_VALUE"] == "kept"+ assert ("OPENCOMPANY_ENV_CANARY" in env) == inherit_env+ if inherit_env:+ _assert_contained(env)+ assert observed[0]["cwd"] == str(tmp_path)+++def test_cli_session_env_filters_provider_additions_and_keeps_existing_contract(+ bootstrap_environment,+):+ session = AICliSession.__new__(AICliSession)+ session._provider = SimpleNamespace(name="codex", ide_lock_env_var="OP_PROVIDER_OVERRIDE")+ session._lockfile_path = Path("provider-lock")+ session._workflow_id = "workflow"+ session._node_id = "node"+ session._batch_token = "1234567890abcdef"+ env = session.env()+ _assert_contained(env)+ assert env["PYTHONUNBUFFERED"] == "1"+ assert env["OPENCOMPANY_PARENT_RUN_ID"] == "workflow:node:12345678"+ assert env["MACHINA_PARENT_RUN_ID"] == env["OPENCOMPANY_PARENT_RUN_ID"]+++async def test_cli_repo_discovery_contains_ambient_bootstrap(+ bootstrap_environment, monkeypatch, tmp_path,+):+ observed = []++ async def run(argv, **kwargs):+ observed.append(kwargs["env"])+ return SimpleNamespace(returncode=0, stdout=str(tmp_path).encode())++ monkeypatch.setattr("services.cli_agent.service.anyio.run_process", run)+ root = await AICliService._resolve_repo_root(workspace_dir=tmp_path, override=tmp_path)+ assert root == tmp_path+ _assert_contained(observed[0])+++async def test_cli_pooled_turn_supplies_filtered_env_and_keeps_parent_ids(+ bootstrap_environment, monkeypatch, tmp_path,+):+ pool = SimpleNamespace(+ start_reaper=AsyncMock(), acquire=AsyncMock(return_value="pooled"),+ send_turn=AsyncMock(return_value="result"), release=AsyncMock(),+ )+ monkeypatch.setattr("services.cli_agent.service.get_session_pool", lambda _: pool)+ result = await AICliService()._run_pooled_turn(+ task=ClaudeTaskSpec(prompt="safe task"), session_key="session", cwd=tmp_path,+ workspace_dir=tmp_path, defaults={}, mcp_port=8000, mcp_bearer_token="abcdefgh-token",+ connected_tools=[], connected_skill_names=[], workflow_id="workflow",+ )+ assert result == "result"+ env = pool.acquire.call_args.kwargs["env"]+ _assert_contained(env)+ assert env["CLAUDE_CONFIG_DIR"]+ assert env["OPENCOMPANY_PARENT_RUN_ID"] == "workflow:session:abcdefgh"+ assert env["MACHINA_PARENT_RUN_ID"] == env["OPENCOMPANY_PARENT_RUN_ID"]+ pool.release.assert_awaited_once_with("pooled")++[email protected]("env_mode", ["ambient", "override", "isolated"])+async def test_shared_cli_spawn_contains_bootstrap_and_preserves_env_modes(+ bootstrap_environment, monkeypatch, env_mode,+):+ observed = []+ process = SimpleNamespace(+ returncode=0,+ communicate=AsyncMock(return_value=(b'{"safe":true}', b"")),+ )++ async def spawn(*argv, **kwargs):+ observed.append((argv, kwargs))+ return process++ monkeypatch.setattr("services.events.cli.asyncio.create_subprocess_exec", spawn)+ monkeypatch.setattr("services.events.cli.shutil.which", lambda _: sys.executable)+ env = None+ if env_mode == "override":+ env = {"op_reintroduced": "canary-override", "CUSTOM_VALUE": "whitespace\tΩ "}+ elif env_mode == "isolated":+ env = {}+ original = dict(env) if env is not None else None+ result = await run_cli_command(binary="probe", argv=["--unchanged"], env=env, cwd="same-cwd")+ assert result == {"success": True, "result": {"safe": True}, "stdout": '{"safe":true}', "stderr": "", "error": None}+ argv, kwargs = observed[0]+ assert argv == (sys.executable, "--unchanged")+ assert kwargs["cwd"] == "same-cwd"+ assert not any(key.upper().startswith("OP_") for key in kwargs["env"])+ if env_mode == "ambient":+ _assert_contained(kwargs["env"])+ elif env_mode == "override":+ assert kwargs["env"] == {"CUSTOM_VALUE": "whitespace\tΩ "}+ else:+ assert kwargs["env"] == {}+ assert env == original+ process.communicate.assert_awaited_once_with(input=None)diff --git a/server/tests/services/test_proxy_reload.py b/server/tests/services/test_proxy_reload.pyindex 1022bef3..502b97ce 100644--- a/server/tests/services/test_proxy_reload.py+++ b/server/tests/services/test_proxy_reload.py@@ -35,7 +35,7 @@ async def test_provider_reload_serializes_fetch_build_and_swap():allow_old = asyncio.Event()class Auth:- async def get_api_key(self, key: str):+ async def resolve_api_key(self, key: str):if "proxy_old_username" in key:old_started.set()await allow_old.wait()diff --git a/server/tests/services/test_rlm_context_v2.py b/server/tests/services/test_rlm_context_v2.pyindex b59f870b..c1ccb7ab 100644--- a/server/tests/services/test_rlm_context_v2.py+++ b/server/tests/services/test_rlm_context_v2.py@@ -22,7 +22,7 @@ async def test_rlm_loads_context_into_prompt_and_records_the_turn():side_effect=lambda prompt: f"portable-history\n{prompt}")auth = MagicMock()- auth.get_api_key = AsyncMock(return_value="secret")+ auth.resolve_api_key = AsyncMock(return_value="secret")prompts = []fake_rlm = ModuleType("rlm")diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.pyindex 8d2d4eb7..b050a530 100644--- a/server/tests/temporal/test_agent_workflow.py+++ b/server/tests/temporal/test_agent_workflow.py@@ -1234,7 +1234,7 @@ class TestDelegatedChildrenInheritScope:from services.temporal.agent_workflow import AgentWorkflowsource = inspect.getsource(AgentWorkflow._run_impl)- assert source.count("**_inherited_scope(context)") == 2+ assert source.count("**_inherited_scope(context, delegation=True)") == 2def test_inherited_scope_never_overrides_explicit_child_keys(self):import inspect@@ -1243,7 +1243,7 @@ class TestDelegatedChildrenInheritScope:source = inspect.getsource(AgentWorkflow._run_impl)for block in source.split("child_context = {")[1:]:- spread = block.index("**_inherited_scope(context)")+ spread = block.index("**_inherited_scope(context, delegation=True)")node_id = block.index('"node_id"')assert spread < node_id, "spread must come first so explicit keys win"diff --git a/server/tests/temporal/test_browser_owner_worker.py b/server/tests/temporal/test_browser_owner_worker.pynew file mode 100644index 00000000..6c28dd0e--- /dev/null+++ b/server/tests/temporal/test_browser_owner_worker.py@@ -0,0 +1,81 @@+"""Owner worker startup, routing separation and partial-start cleanup."""++from datetime import timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++[email protected]("owner_fails", [False, True])+async def test_owner_worker_is_required_without_general_pool_and_startup_failure_is_cleaned(monkeypatch, owner_fails):+ from core import container as container_module+ from services import browser_owners+ from services.temporal import lifecycle, worker+ events = []+ async def register(database):+ events.append("registered")+ async def start_main():+ events.append("main")+ async def start_owner():+ events.append("owner")+ if owner_fails:+ raise RuntimeError("owner construction failed")+ manager = SimpleNamespace(start=start_main, stop=AsyncMock(), _browser_pool=None)+ owner = SimpleNamespace(start=start_owner)+ wrapper = SimpleNamespace(worker_manager=None)+ fake_container = SimpleNamespace(database=lambda: object(),+ workflow_service=lambda: SimpleNamespace(set_temporal_executor=MagicMock()), temporal_client=lambda: wrapper)+ monkeypatch.setattr(container_module, "container", fake_container)+ monkeypatch.setattr(browser_owners, "register_browser_owner", register)+ monkeypatch.setattr(browser_owners, "replica_id", lambda: "replica")+ monkeypatch.setattr(worker, "TemporalWorkerManager", lambda **kwargs: manager)+ monkeypatch.setattr(worker, "BrowserOwnerWorkerPool", lambda *args: owner)+ settings = SimpleNamespace(temporal_task_queue="main", distributed_mode=True, temporal_worker_pool_enabled=False)+ state = SimpleNamespace()+ if owner_fails:+ with pytest.raises(RuntimeError, match="owner construction failed"):+ await lifecycle._start_execution_engine(object(), state, settings, lambda line: None)+ manager.stop.assert_awaited_once()+ assert wrapper.worker_manager is None+ assert not hasattr(state, "temporal_worker_manager")+ else:+ await lifecycle._start_execution_engine(object(), state, settings, lambda line: None)+ assert wrapper.worker_manager is manager+ assert manager._browser_pool is owner+ manager.stop.assert_not_awaited()+ assert events == ["registered", "main", "owner"]+++async def test_stop_closes_partial_manager_session_before_worker_started():+ from services.temporal.worker import TemporalWorkerManager+ manager = TemporalWorkerManager(client=MagicMock())+ session = SimpleNamespace(closed=False, close=AsyncMock())+ manager._session = session+ await manager.stop()+ session.close.assert_awaited_once()+ assert manager._session is None+++def test_owner_registration_uses_plugin_types_and_generic_workers_exclude_browser(monkeypatch):+ from services.temporal import worker, plugin_activities+ from services import node_registry, browser_owners+ from services.temporal.browser_task_activities import BROWSER_OWNER_ACTIVITIES+ settings = SimpleNamespace(distributed_mode=True)+ monkeypatch.setattr("core.config.Settings", lambda: settings)+ monkeypatch.setattr(node_registry, "registered_node_classes", lambda: {"browser": object(), "rest": object()})+ collect = MagicMock(return_value=["plugin"])+ monkeypatch.setattr(plugin_activities, "collect_plugin_activities", collect)+ assert worker._generic_plugin_activities() == ["plugin"]+ collect.assert_called_once_with(include_types=["rest"])+ collect.reset_mock()+ monkeypatch.setattr(browser_owners, "owner_queue", lambda identity: "physical-owner")+ monkeypatch.setattr(worker, "_graceful_shutdown_timeout", lambda: timedelta(seconds=1))+ monkeypatch.setattr(worker, "_worker_identity", lambda queue: "fixture")+ factory = MagicMock()+ monkeypatch.setattr(worker, "Worker", factory)+ pool = worker.BrowserOwnerWorkerPool(MagicMock(), "replica")+ pool._build_queue_worker("physical-owner")+ collect.assert_called_once_with(include_types=["browser"])+ assert factory.call_args.kwargs["task_queue"] == "physical-owner"+ assert factory.call_args.kwargs["activities"] == ["plugin", *BROWSER_OWNER_ACTIVITIES]diff --git a/server/tests/temporal/test_browser_provider_credentials.py b/server/tests/temporal/test_browser_provider_credentials.pynew file mode 100644index 00000000..fbae8060--- /dev/null+++ b/server/tests/temporal/test_browser_provider_credentials.py@@ -0,0 +1,35 @@+"""Provider secrets resolve under the calling principal at the Activity boundary."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from services.temporal.agent_activities import _resolve_activity_api_key++[email protected]("distributed", [False, True])+async def test_runtime_resolution_uses_calling_principal_and_never_legacy_key_reader(monkeypatch, distributed):+ auth = SimpleNamespace(distributed_credentials=distributed,+ resolve_api_key=AsyncMock(return_value="PRIVATE-CANARY"),+ get_api_key=AsyncMock(side_effect=AssertionError("Cannot read a cached credential")))+ database = SimpleNamespace(get_node_parameters=AsyncMock(side_effect=AssertionError("Cannot use inline fallback")))+ monkeypatch.setattr("core.container.container", SimpleNamespace(auth_service=lambda: auth, database=lambda: database))+ payload = {"provider": "openai", "user_id": "tenant-a", "node_id": "browser-agent", "workflow_id": "wf"}+ assert await _resolve_activity_api_key(payload) == "PRIVATE-CANARY"+ auth.resolve_api_key.assert_awaited_once_with("openai", principal="tenant-a")+ auth.get_api_key.assert_not_awaited()+ database.get_node_parameters.assert_not_awaited()+ assert "PRIVATE-CANARY" not in repr(payload)+++async def test_revoked_binding_does_not_fall_back_to_a_local_inline_key(monkeypatch):+ from services.credentials.onepassword import CredentialSourceError+ auth = SimpleNamespace(distributed_credentials=False,+ resolve_api_key=AsyncMock(side_effect=CredentialSourceError("revoked", "The credential is unavailable.")),+ get_api_key=AsyncMock())+ database = SimpleNamespace(get_node_parameters=AsyncMock(return_value={"api_key": "INLINE-CANARY"}))+ monkeypatch.setattr("core.container.container", SimpleNamespace(auth_service=lambda: auth, database=lambda: database))+ with pytest.raises(CredentialSourceError, match="unavailable"):+ await _resolve_activity_api_key({"provider": "openai", "user_id": "tenant-a", "node_id": "agent"})+ database.get_node_parameters.assert_not_awaited()diff --git a/server/tests/temporal/test_browser_task_dispatch.py b/server/tests/temporal/test_browser_task_dispatch.pynew file mode 100644index 00000000..03e534e2--- /dev/null+++ b/server/tests/temporal/test_browser_task_dispatch.py@@ -0,0 +1,87 @@+"""Versioned native dispatch, owner cleanup, and admission commands."""++import asyncio+from datetime import timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock++from services.temporal import node_invocation as module+from services.temporal.agent_workflow import _frozen_tool_activity_options+++async def test_native_invocation_attaches_child_and_counts_completion_once(monkeypatch):+ payload = {"principal": "owner", "workflow_id": "wf", "node_id": "agent", "fingerprint": "hash",+ "context": {"generation": 0, "native_workspace_version": 1},+ "dispatch_version": 1, "dispatch_kind": "native_agent", "history_version": 1}+ result = {"success": True, "result": {"response": "done"}}+ execute = AsyncMock()+ child = AsyncMock(return_value=result)+ monkeypatch.setattr(module.workflow, "execute_activity", execute)+ monkeypatch.setattr(module.workflow, "execute_child_workflow", child)+ monkeypatch.setattr(module.workflow, "info", lambda: SimpleNamespace(workflow_id="stable", run_id="attempt"))+ run = module.NodeInvocationWorkflow()+ assert await run.run(payload) == result+ child.assert_awaited_once()+ assert child.await_args.args == ("AgentWorkflow", payload["context"])+ assert child.await_args.kwargs["id"] == "stable:agent"+ assert child.await_args.kwargs["cancellation_type"] == module.workflow.ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED+ assert child.await_args.kwargs["parent_close_policy"] == module.workflow.ParentClosePolicy.REQUEST_CANCEL+ assert [call.args[0] for call in execute.await_args_list] == ["workspace_tasks.update_record", "workspace_tasks.update_record", "workflow_runs.record_completion"]+ assert execute.await_args_list[1].args[1]["status"] == "completed"+++def test_owner_queue_is_required_even_when_worker_pool_is_disabled():+ policy = {"start_to_close_seconds": 60, "heartbeat_seconds": 10,+ "task_queue": "browser-owner-test", "owner_routing": True,+ "retry_policy": {"initial_interval_seconds": 1, "backoff_coefficient": 2,+ "maximum_interval_seconds": 10, "maximum_attempts": 3, "non_retryable_error_types": []}}+ options = _frozen_tool_activity_options(policy, {"native_workspace_version": 1, "temporal_worker_pool_enabled": False})+ assert options["task_queue"] == "browser-owner-test"+ assert "schedule_to_close_timeout" not in options+ assert options["retry_policy"].maximum_attempts == 3+ policy.pop("owner_routing")+ assert "task_queue" not in _frozen_tool_activity_options(policy, {"temporal_worker_pool_enabled": False})+++def test_child_task_owns_its_claim_while_tool_calls_keep_the_parent_token():+ from services.temporal.agent_workflow import _inherited_scope, _trusted_tool_scope+ context = {"native_workspace_version": 1, "browser_bindings": {"browser": {"profile_id": "profile"}},+ "_browser_task_id": "parent"}+ assert "_browser_task_id" not in _inherited_scope(context, delegation=True)+ assert _trusted_tool_scope(context)["_browser_task_id"] == "parent"+ assert _inherited_scope(context, delegation=True)["browser_bindings"] == context["browser_bindings"]+++async def test_controller_records_admission_before_child_start(monkeypatch):+ from services.temporal import workspace_tasks_workflow as controller_module+ commands = []+ async def execute(*args, **kwargs):+ commands.append(args[0])+ child = asyncio.Future()+ async def start(*args, **kwargs):+ commands.append("child")+ return child+ monkeypatch.setattr(controller_module.workflow, "execute_activity", execute)+ monkeypatch.setattr(controller_module.workflow, "start_child_workflow", start)+ controller = controller_module.WorkspaceTaskControllerWorkflow({"workflow_id": "wf"})+ payload = {"workflow_id": "wf", "fingerprint": "hash", "context": {"workflow_id": "wf", "execution_id": "task"}, "history_version": 1}+ assert (await controller.submit(payload))["status"] == "accepted"+ assert commands == ["workspace_tasks.admit_record", "child"]+ await controller.submit(payload)+ assert commands == ["workspace_tasks.admit_record", "child"]+ child.set_result({"success": True})+ await asyncio.sleep(0)+++async def test_terminal_projection_prevents_duplicate_effects_after_controller_eviction(monkeypatch):+ from services.temporal import workspace_tasks_workflow as controller_module+ execute = AsyncMock(return_value={"status": "completed"})+ start = AsyncMock()+ monkeypatch.setattr(controller_module.workflow, "execute_activity", execute)+ monkeypatch.setattr(controller_module.workflow, "start_child_workflow", start)+ controller = controller_module.WorkspaceTaskControllerWorkflow({"workflow_id": "wf"})+ payload = {"workflow_id": "wf", "fingerprint": "hash", "context": {"workflow_id": "wf", "execution_id": "task"}, "history_version": 1}+ assert (await controller.submit(payload))["status"] == "duplicate"+ start.assert_not_awaited()+ assert controller._submissions == {"task": "hash"}+ assert controller._starting is Nonediff --git a/server/tests/temporal/test_browser_workspace_replay.py b/server/tests/temporal/test_browser_workspace_replay.pynew file mode 100644index 00000000..258cbcb7--- /dev/null+++ b/server/tests/temporal/test_browser_workspace_replay.py@@ -0,0 +1,204 @@+"""Native Browser tasks on separate owner queues, with SDK replay and cleanup.++Uses an explicitly supplied native Temporal binary. Browser/model Activities+are controlled fixtures: no external website, provider or credential access.+"""++from __future__ import annotations++import asyncio+import os+from contextlib import AsyncExitStack, suppress+from datetime import timedelta+from pathlib import Path+import subprocess+import sys+from uuid import uuid4++import pytest+++async def run_gate(cli: str):+ from temporalio import activity+ from temporalio.client import WithStartWorkflowOperation+ from temporalio.common import WorkflowIDConflictPolicy+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker, Replayer+ from services.llm.protocol import Message, ToolCall, message_to_wire+ from services.temporal import agent_workflow as agent_module+ from services.temporal.agent_workflow import AgentWorkflow+ from services.temporal.node_invocation import NodeInvocationWorkflow+ from services.temporal.workspace_tasks_workflow import WorkspaceTaskControllerWorkflow++ # Roll over after the first completed tool turn, proving generation-zero+ # tasks retain their payload, task token, tools and transcript.+ agent_module._AGENT_HISTORY_SOFT_CAP = 1+ token = uuid4().hex+ main_queue = f"browser-main-{token}"+ queues = {owner: f"browser-{owner}-{token}" for owner in ("a", "b")}+ prepared_calls, llm_calls, records, completions = [], [], [], []+ cancel_entered, cancel_release, cleanup_entered, cleanup_release = (asyncio.Event() for _ in range(4))++ def context(identity, owner, *, cancelling=False):+ binding = {"owner_id": owner, "profile_id": owner, "runtime_epoch": "epoch", "task_queue": queues[owner]}+ return {"node_id": "agent", "node_type": "browser_agent", "workflow_id": "saved",+ "execution_id": identity, "session_id": identity, "user_id": "owner", "generation": 0,+ "native_workspace_version": 1, "temporal_worker_pool_enabled": False,+ "workspace_task_prompt": "read issues", "nodes": [], "edges": [],+ "browser_bindings": {"browser": binding}, "_browser_task_id": identity, "cancelling": cancelling}++ @activity.defn(name="agent.prepare_payload")+ async def prepare(ctx: dict):+ prepared_calls.append(ctx["execution_id"])+ binding = ctx["browser_bindings"]["browser"]+ return {"node_id": "agent", "node_type": "browser_agent", "workflow_id": "saved", "session_id": ctx["session_id"],+ "provider": "openai", "model": "fixture", "system_message": "Browser role stays intact", "user_prompt": ctx["workspace_task_prompt"],+ "max_iterations": 3, "memory_node_id": "", "memory_content": "", "compaction_threshold": None,+ "browser_runtime_version": 1, "browser_bindings": ctx["browser_bindings"],+ "tools": [{"name": "browser", "node_type": "browser", "tool_node_id": "browser", "version": 1,+ "parameters": {}, "definition": {"name": "browser", "description": "browser fixture", "parameters": {"type": "object"}},+ "activity_policy": {"start_to_close_seconds": 60, "heartbeat_seconds": 10,+ "task_queue": binding["task_queue"], "owner_routing": True,+ "retry_policy": {"initial_interval_seconds": 1, "backoff_coefficient": 2, "maximum_interval_seconds": 5,+ "maximum_attempts": 3, "non_retryable_error_types": []}}}]}++ @activity.defn(name="agent.execute_llm_step")+ async def llm(payload: dict):+ llm_calls.append(payload)+ if payload["iteration"] == 0:+ call = ToolCall(id="call-1", name="browser", args={"operation": "snapshot"})+ return {"kind": "tool_calls", "calls": [{"id": "call-1", "name": "browser", "args": {"operation": "snapshot"}}],+ "assistant_message": message_to_wire(Message(role="assistant", content="", tool_calls=[call])), "usage": {"input_tokens": 3}}+ assert any(message.get("role") == "tool" and "observed" in str(message) for message in payload["messages"])+ return {"kind": "final", "content": "done", "usage": {"input_tokens": 2}}++ @activity.defn(name="agent.broadcast_progress")+ async def progress(payload: dict):+ return {}+ @activity.defn(name="agent.skill.clear")+ async def clear(payload: dict):+ return {}+ @activity.defn(name="agent.store_output")+ async def output(payload: dict):+ return {}+ @activity.defn(name="workspace_tasks.admit_record")+ async def admit(payload: dict):+ records.append((payload["context"]["execution_id"], "admitted"))+ @activity.defn(name="workspace_tasks.update_record")+ async def update(payload: dict):+ records.append((payload["invocation_id"], payload["status"]))+ @activity.defn(name="workflow_runs.record_completion")+ async def completion(payload: dict):+ completions.append(payload)++ class Owner:+ def __init__(self, identity):+ self.identity = identity+ self.claims, self.releases, self.operations = [], [], []+ @activity.defn(name="browser_tasks.claim")+ async def claim(self, payload: dict):+ assert payload["binding"]["owner_id"] == self.identity+ self.claims.append(payload["task_id"])+ return {"claimed": True, "binding": payload["binding"]}+ @activity.defn(name="browser_tasks.release")+ async def release(self, payload: dict):+ assert payload["binding"]["owner_id"] == self.identity+ if payload["task_id"].endswith("cancel"):+ cleanup_entered.set()+ while not cleanup_release.is_set():+ activity.heartbeat("cleanup fixture")+ await asyncio.sleep(.02)+ self.releases.append(payload["task_id"])+ return {"released": True}+ @activity.defn(name="node.browser.v1")+ async def browser(self, payload: dict):+ assert payload["_browser_owner"]["owner_id"] == self.identity+ self.operations.append(payload["_browser_task_id"])+ if payload["_browser_task_id"].endswith("cancel"):+ cancel_entered.set()+ try:+ while not cancel_release.is_set():+ activity.heartbeat("browser fixture")+ await asyncio.sleep(.02)+ except asyncio.CancelledError:+ raise+ return {"success": True, "result": {"observed": True,+ "screenshot": {"path": "screenshots/fixture.png", "workflow_id": "saved",+ "filename": "fixture.png", "mime_type": "image/png"}}}++ owners = {name: Owner(name) for name in queues}+ async with await WorkflowEnvironment.start_local(dev_server_existing_path=cli) as environment:+ client = environment.client+ async with AsyncExitStack() as stack:+ await stack.enter_async_context(Worker(client, task_queue=main_queue,+ workflows=[WorkspaceTaskControllerWorkflow, NodeInvocationWorkflow, AgentWorkflow],+ activities=[prepare, llm, progress, clear, output, admit, update, completion]))+ async def start_owner(name):+ owner = owners[name]+ await stack.enter_async_context(Worker(client, task_queue=queues[name],+ activities=[owner.claim, owner.release, owner.browser],+ max_heartbeat_throttle_interval=timedelta(milliseconds=50),+ default_heartbeat_throttle_interval=timedelta(milliseconds=50)))+ await start_owner("b")+ controller_id = f"browser-controller-{token}"+ async def submit(identity, owner, cancelling=False):+ ctx = context(identity, owner, cancelling=cancelling)+ return await client.execute_update_with_start_workflow(WorkspaceTaskControllerWorkflow.submit,+ {"principal": "owner", "workflow_id": "saved", "node_id": "agent", "fingerprint": identity,+ "dispatch_version": 1, "dispatch_kind": "native_agent", "history_version": 1,+ "admission_epoch": 0, "context": ctx}, id=uuid4().hex,+ start_workflow_operation=WithStartWorkflowOperation(WorkspaceTaskControllerWorkflow.run,+ {"workflow_id": "saved"}, id=controller_id, task_queue=main_queue,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING))+ first, second = f"browser-{token}-a", f"browser-{token}-b"+ await submit(first, "a")+ await submit(second, "b")+ # Owner B cannot consume A's call, even with pool routing disabled.+ assert (await asyncio.wait_for(client.get_workflow_handle(second).result(), 20))["success"]+ assert first in prepared_calls and not owners["a"].claims+ assert owners["b"].operations == [second]+ await start_owner("a")+ first_result = await asyncio.wait_for(client.get_workflow_handle(first).result(), 20)+ assert first_result["success"]+ assert first_result["result"]["artifacts"][0]["url"] == "/api/workspace/saved/files/screenshots/fixture.png"+ assert prepared_calls.count(first) == prepared_calls.count(second) == 1+ assert owners["a"].claims == [first, first] # idempotent reacquire after CAN+ assert owners["a"].releases == [first]+ assert len(completions) == 2 # parent boundary only, regardless of CAN++ cancelled = f"browser-{token}-cancel"+ await submit(cancelled, "a", cancelling=True)+ await asyncio.wait_for(cancel_entered.wait(), 10)+ handle = client.get_workflow_handle(cancelled)+ await handle.cancel()+ await asyncio.wait_for(cleanup_entered.wait(), 10)+ assert (cancelled, "cancelled") not in records+ cleanup_release.set()+ with suppress(Exception):+ await asyncio.wait_for(handle.result(), 10)+ assert owners["a"].releases[-1] == cancelled+ assert (cancelled, "cancelled") in records++ replayer = Replayer(workflows=[WorkspaceTaskControllerWorkflow, NodeInvocationWorkflow, AgentWorkflow])+ for identity in (first, second, cancelled, controller_id):+ history = await client.get_workflow_handle(identity).fetch_history()+ assert (await replayer.replay_workflow(history)).replay_failure is None+ for identity in (first, second, cancelled):+ history = await client.get_workflow_handle(f"{identity}:agent").fetch_history()+ assert (await replayer.replay_workflow(history)).replay_failure is None+ assert "CANARY" not in history.to_json()+ await client.get_workflow_handle(controller_id).terminate("isolated fixture finished")+++def test_native_browser_owner_routing_continuation_and_cleanup_replay():+ cli = os.environ.get("TEMPORAL_TEST_CLI")+ if not cli or not Path(cli).is_file():+ pytest.skip("Set TEMPORAL_TEST_CLI to a native Temporal binary")+ completed = subprocess.run([sys.executable, "-X", "utf8", "-m", "tests.temporal.test_browser_workspace_replay", cli],+ cwd=Path(__file__).parents[2], stdin=subprocess.DEVNULL, capture_output=True,+ encoding="utf-8", timeout=90, env={**os.environ, "DEBUG": "false"})+ assert completed.returncode == 0, (completed.stdout + completed.stderr)[-9000:]+++if __name__ == "__main__":+ asyncio.run(run_gate(sys.argv[1]))diff --git a/server/tests/temporal/test_prepare_payload_context.py b/server/tests/temporal/test_prepare_payload_context.pyindex 6fd7e82a..f075a336 100644--- a/server/tests/temporal/test_prepare_payload_context.py+++ b/server/tests/temporal/test_prepare_payload_context.py@@ -96,3 +96,57 @@ async def test_parameter_snapshot_keeps_original_mission_and_model(descriptor):result = await prepare_agent_payload({**_CONTEXT, "parameter_snapshot": snapshot})assert result["user_prompt"] == "Original admitted mission"assert result["parameter_snapshot"] == snapshot+++async def test_direct_workspace_prompt_wins_and_never_loads_deployed_conversation(descriptor, monkeypatch):+ import core.container as container_module+ database = container_module.container.database()+ database.get_node_parameters.return_value.update(prompt="Saved chat template", system_message="Keep Browser instructions")+ descriptor.value = {"kind": "context", "node_id": "context", "workflow_id": "7", "generation": 3}+ load = AsyncMock(side_effect=AssertionError("Direct tasks cannot load deployed conversation"))+ monkeypatch.setattr("services.agent_context.load_conversation", load)+ result = await prepare_agent_payload({**_CONTEXT, "generation": 0,+ "native_workspace_version": 1, "workspace_task_prompt": "Direct task", "node_data": {"prompt": "ignored"}})+ assert result["user_prompt"] == "Direct task"+ assert result["system_message"] == "Keep Browser instructions"+ assert result["conversation_key"] is None and result["memory_node_id"] == ""+ assert "sk-test" not in repr(result)+ load.assert_not_awaited()++[email protected]("native_workspace", [False, True])+async def test_browser_delegation_preserves_role_and_records_owner_policy(descriptor, monkeypatch, native_workspace):+ import core.container as container_module+ container = container_module.container+ database = container.database()+ database.get_node_parameters.return_value.update(system_message="Keep Browser instructions")+ tool = SimpleNamespace(name="browser", description="browser", args_schema={"type": "object"})+ monkeypatch.setattr(container, "ai_service", lambda: SimpleNamespace(_build_tool_from_node=AsyncMock(return_value=(tool, {}))))+ async def connections(*args, **kwargs):+ return None, [], [{"node_id": "browser", "node_type": "browser", "parameters": {"password": "CANARY"}}], {}, None+ monkeypatch.setattr("services.plugin.edge_walker.collect_agent_connections", connections)+ binding = {"profile_id": "profile", "owner_id": "owner-a", "task_queue": "owner-a-queue"}+ result = await prepare_agent_payload({**_CONTEXT, "node_type": "browser_agent", "user_id": "owner",+ **({"native_workspace_version": 1, "generation": 0} if native_workspace else {}),+ "browser_bindings": {"browser": binding}, "invocation": {"task": "Read issues", "context": "Repository A"}})+ assert result["system_message"] == "Keep Browser instructions"+ assert result["user_prompt"] == "Read issues\n\nRepository A"+ assert result["tools"][0]["activity_policy"]["task_queue"] == "owner-a-queue"+ assert result["tools"][0]["activity_policy"]["owner_routing"] is True+ assert "CANARY" not in repr(result) and "sk-test" not in repr(result)+++async def test_browser_delegation_without_saved_role_uses_browser_default(descriptor, monkeypatch):+ import core.container as container_module+ from services.browser_agent_recipe import BROWSER_AGENT_ROLE+ monkeypatch.setattr("services.temporal.agent_activities._freeze_browser_tools", AsyncMock(return_value=({}, 0)))+ async def connections(*args, **kwargs):+ return None, [], [{"node_id": "browser", "node_type": "browser", "parameters": {}}], {}, None+ monkeypatch.setattr("services.plugin.edge_walker.collect_agent_connections", connections)+ tool = SimpleNamespace(name="browser", description="browser", args_schema={"type": "object"})+ monkeypatch.setattr(container_module.container, "ai_service", lambda: SimpleNamespace(_build_tool_from_node=AsyncMock(return_value=(tool, {}))))+ result = await prepare_agent_payload({**_CONTEXT, "node_type": "browser_agent",+ "node_data": {"system_message": "Delegated mission is input"},+ "invocation": {"task": "Read issues"}})+ assert result["system_message"] == BROWSER_AGENT_ROLE+ assert result["user_prompt"] == "Read issues"diff --git a/server/tests/test_browser_workspace_tasks.py b/server/tests/test_browser_workspace_tasks.pynew file mode 100644index 00000000..a5c94910--- /dev/null+++ b/server/tests/test_browser_workspace_tasks.py@@ -0,0 +1,133 @@+"""Browser direct-task contracts and durable history, without external accounts."""++from contextlib import asynccontextmanager+from datetime import datetime, timedelta, timezone+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from models.workspace_tasks import WorkspaceTaskRecord+from services.browser_tasks import browser_tool_for_agent+from services.workspace_task_history import admit, transition, list_tasks, safe_result+++async def history_db():+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as connection:+ await connection.run_sync(lambda sync: WorkspaceTaskRecord.__table__.create(sync))+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ @asynccontextmanager+ async def get_session():+ async with sessions() as session:+ yield session+ database = SimpleNamespace(get_session=get_session,+ get_workflow=AsyncMock(return_value={"data": {"owner_id": "owner", "nodes": []}}))+ yield database+ await engine.dispose()+++def record(identity="one", **overrides):+ return {"history_record": {"invocation_id": identity, "submission_id": "submission",+ "principal": "owner", "workflow_id": "wf", "node_id": "deleted-agent", "fingerprint": "hash",+ "prompt": "Read issues", **overrides}}+++async def test_retry_admission_and_late_running_cannot_regress_terminal(history_db):+ assert await admit(history_db, record()) == {"status": "queued"}+ assert await admit(history_db, record()) == {"status": "queued"}+ await transition(history_db, {"invocation_id": "one", "status": "completed",+ "result": {"success": True, "result": {"response": "done", "thinking": "private", "api_key": "CANARY"}}})+ await transition(history_db, {"invocation_id": "one", "status": "running"})+ await transition(history_db, {"invocation_id": "one", "status": "failed"})+ rows = (await list_tasks(history_db, "owner", "wf"))["items"]+ assert len(rows) == 1 and rows[0]["status"] == "completed"+ assert rows[0]["result"] == {"response": "done"}+ assert await admit(history_db, record()) == {"status": "completed"}+ with pytest.raises(ValueError, match="conflict"):+ await admit(history_db, record(fingerprint="different"))+++async def test_history_survives_node_deletion_and_reset_is_not_a_retention_action(history_db):+ await admit(history_db, record())+ from services.plugin import NodeUserError+ assert (await list_tasks(history_db, "owner", "wf", node_id="deleted-agent"))["items"][0]["prompt"] == "Read issues"+ with pytest.raises(NodeUserError, match="denied"):+ await list_tasks(history_db, "intruder", "wf")+++async def test_pagination_ties_and_retention_preserve_active_tasks(history_db):+ now = datetime.now(timezone.utc)+ for identity in ("a", "b", "c"):+ await admit(history_db, record(identity, created_at=now))+ first = await list_tasks(history_db, "owner", "wf", limit=2)+ assert [item["invocation_id"] for item in first["items"]] == ["c", "b"]+ assert first["next_cursor"] == "b"+ assert [item["invocation_id"] for item in (await list_tasks(history_db, "owner", "wf", cursor="b", limit=2))["items"]] == ["a"]+ await admit(history_db, record("old-completed", status="completed", completed_at=now - timedelta(days=36)))+ await admit(history_db, record("old-running", status="running", created_at=now - timedelta(days=40)))+ rows = (await list_tasks(history_db, "owner", "wf"))["items"]+ assert "old-completed" not in {row["invocation_id"] for row in rows}+ assert "old-running" in {row["invocation_id"] for row in rows}+++def test_safe_result_rejects_absolute_traversal_and_private_transcripts():+ result = safe_result({"response": "x" * 20000, "thinking": "CANARY", "messages": ["CANARY"],+ "artifacts": [{"path": "screenshots/safe.png", "mime_type": "image/png", "raw": "CANARY"},+ {"path": "C:\\private.txt"}, {"path": "../private"}, {"path": "/private"}]})+ assert len(result["response"]) == 16000+ assert result["artifacts"] == [{"path": "screenshots/safe.png", "mime_type": "image/png"}]+ assert "CANARY" not in repr(result)+++def test_agent_binding_requires_one_enabled_saved_browser():+ from services.plugin import NodeUserError+ graph = {"nodes": [{"id": "a", "type": "browser_agent"}, {"id": "b", "type": "browser"}],+ "edges": [{"source": "b", "target": "a", "targetHandle": "input-tools"}]}+ assert browser_tool_for_agent(graph, "a")["id"] == "b"+ graph["nodes"][1]["data"] = {"disabled": True}+ with pytest.raises(NodeUserError, match="enabled"):+ browser_tool_for_agent(graph, "a")++[email protected]("extra", ["graph", "owner_url", "cdp_address", "credential_source"])+def test_task_schema_rejects_client_execution_bindings(extra):+ from pydantic import ValidationError+ from routers.browser_tasks import TaskSubmission+ body = {"workflow_id": "wf", "agent_node_id": "agent", "prompt": "Read issues",+ "submission_id": "ddc00a18-4e6e-41ca-b6ec-bca6be408bd5", extra: "untrusted"}+ with pytest.raises(ValidationError):+ TaskSubmission.model_validate(body)+++def test_task_schema_requires_a_uuid_submission_identity():+ from pydantic import ValidationError+ from routers.browser_tasks import TaskSubmission+ with pytest.raises(ValidationError):+ TaskSubmission.model_validate({"workflow_id": "wf", "agent_node_id": "agent",+ "prompt": "Read issues", "submission_id": "invalid"})+++async def test_task_endpoint_passes_only_saved_identity_prompt_and_normalized_uuid(monkeypatch):+ from routers.browser_tasks import TaskSubmission, submit_task+ submit = AsyncMock(return_value={"status": "accepted"})+ monkeypatch.setattr("services.node_invocations.submit", submit)+ monkeypatch.setattr("services.authz.workflow_node.resolve_workflow_node", AsyncMock(return_value=(None, {}, {"type": "browser_agent"})))+ request = SimpleNamespace(state=SimpleNamespace(user_id="tenant"))+ body = TaskSubmission.model_validate({"workflow_id": "wf", "agent_node_id": "agent", "prompt": "Read issues",+ "submission_id": "DDC00A18-4E6E-41CA-B6EC-BCA6BE408BD5"})+ assert await submit_task(request, body) == {"status": "accepted"}+ submit.assert_awaited_once_with("tenant", "wf", "agent", "Read issues", "ddc00a18-4e6e-41ca-b6ec-bca6be408bd5")+++async def test_invalid_status_submission_identity_returns_safe_400(monkeypatch):+ from fastapi import HTTPException+ from routers.browser_tasks import task_status+ monkeypatch.setattr("services.node_invocations.status", AsyncMock(side_effect=ValueError("private invalid value")))+ request = SimpleNamespace(state=SimpleNamespace(user_id="tenant"))+ with pytest.raises(HTTPException) as raised:+ await task_status(request, "invalid", "wf", "agent")+ assert raised.value.status_code == 400 and raised.value.detail == "Invalid submission identity"diff --git a/server/tests/test_credential_catalogue_consumer_fields.py b/server/tests/test_credential_catalogue_consumer_fields.pyindex 3ab86220..3afe3322 100644--- a/server/tests/test_credential_catalogue_consumer_fields.py+++ b/server/tests/test_credential_catalogue_consumer_fields.py@@ -189,7 +189,7 @@ class TestProviderConnectionState:async def test_email_account_is_stored_and_connected_only_with_both_keys(self, registry):provider = registry.get_provider("email_himalaya")state = await provider_connection_state(provider, FakeAuth(keys={"email_address"}))- assert state == {"stored": False, "connected": False, "account_label": None}+ assert state == {"stored": False, "connected": False, "account_label": None, "sourceSupported": False, "sourceRequired": False}state = await provider_connection_state(provider, FakeAuth(keys={"email_address", "email_password"}))assert state["stored"] is True and state["connected"] is Truediff --git a/server/tests/test_event_framework_phase_a.py b/server/tests/test_event_framework_phase_a.pyindex 34b7df95..640a6c3f 100644--- a/server/tests/test_event_framework_phase_a.py+++ b/server/tests/test_event_framework_phase_a.py@@ -467,8 +467,9 @@ class TestTriggerOutputPersistenceForTemplateResolution:The legacy ``DeploymentManager._execute_from_trigger`` path called``_store_output(trigger_node_id, "output_0", trigger_output)``before executing downstream. The fix adds a- ``store_node_output_activity`` call inside MachinaWorkflow.run's- pre-executed loop that mirrors that persist.+ ``store_node_output_activity`` call inside MachinaWorkflow's+ pre-executed loop (now in ``_run_graph``, which ``run`` drives) that+ mirrors that persist."""def test_activity_exists_and_is_async(self):@@ -481,14 +482,14 @@ class TestTriggerOutputPersistenceForTemplateResolution:)def test_opencompany_workflow_calls_persist_activity_for_pre_executed(self):- """Source-introspection regression: MachinaWorkflow.run's+ """Source-introspection regression: MachinaWorkflow'spre-executed handler must call store_node_output_activity soParameterResolver can read the trigger output back."""import inspectfrom services.temporal.workflow import MachinaWorkflow- src = inspect.getsource(MachinaWorkflow.run)+ src = inspect.getsource(MachinaWorkflow.run) + inspect.getsource(MachinaWorkflow._run_graph)assert "store_node_output_activity" in src, ("MachinaWorkflow.run no longer schedules the "diff --git a/server/tests/test_mobile_models.py b/server/tests/test_mobile_models.pyindex 3455cbee..59571ace 100644--- a/server/tests/test_mobile_models.py+++ b/server/tests/test_mobile_models.py@@ -17,8 +17,8 @@ def models(monkeypatch):get_user_settings=AsyncMock(return_value={"default_llm_provider": "gemini", "default_llm_model": "global-vision"}),get_provider_defaults=AsyncMock(return_value={"default_model": "provider-default"}),)- auth = SimpleNamespace(get_api_key=AsyncMock(return_value="selected-key"))- auth.get_api_key.side_effect = lambda provider, *_: None if provider.endswith("_proxy") else auth.get_api_key.return_value+ auth = SimpleNamespace(resolve_api_key=AsyncMock(return_value="selected-key"))+ auth.resolve_api_key.side_effect = lambda provider, *_, **kw: None if provider.endswith("_proxy") else auth.resolve_api_key.return_valuemonkeypatch.setattr(deps, "get_database", lambda: database)monkeypatch.setattr(deps, "get_ai_service", lambda: SimpleNamespace(auth=auth))monkeypatch.setattr(registry, "get_node_class", lambda _: SimpleNamespace(component_kind="model"))@@ -36,7 +36,7 @@ async def test_global_selection_is_read_fresh_and_ignores_drag_defaults(models):result = await resolve_model(context(), params)assert result == {"provider": "google", "model": "global-vision", "model_env": {"GOOGLE_API_KEY": "selected-key", "GOOGLE_GENAI_USE_VERTEXAI": "false"}}db.get_user_settings.assert_awaited_once_with("default")- auth.get_api_key.assert_awaited_once_with("gemini", "default")+ auth.resolve_api_key.assert_awaited_once_with("gemini", "default", principal=None)db.get_user_settings.return_value = {"default_llm_provider": "openai", "default_llm_model": "new-global"}assert (await resolve_model(context(), params))["model"] == "new-global"@@ -74,12 +74,12 @@ async def test_missing_or_unsupported_global_is_actionable(models, settings, matdb.get_user_settings.return_value = settingswith pytest.raises(NodeUserError, match=match):await resolve_model(context(), MobileParams())- auth.get_api_key.assert_not_awaited()+ auth.resolve_api_key.assert_not_awaited()async def test_missing_key_is_actionable(models):_, auth = models- auth.get_api_key.return_value = None+ auth.resolve_api_key.return_value = Nonewith pytest.raises(NodeUserError, match="Settings"):await resolve_model(context(), MobileParams())@@ -89,12 +89,21 @@ async def test_blank_custom_model_uses_provider_default(models):assert result["model"] == "provider-default"+async def test_private_runtime_resolution_uses_trusted_execution_principal(models):+ _, auth = models+ ctx = context()+ ctx.raw = {"user_id": "alice"}+ await resolve_model(ctx, MobileParams(model_source="custom", provider="openai", model="vision"))+ assert [call.args[0] for call in auth.resolve_api_key.await_args_list] == ["openai", "openai_proxy"]+ assert all(call.kwargs["principal"] == "alice" for call in auth.resolve_api_key.await_args_list)++@pytest.mark.parametrize("key,mode", [("AQ.synthetic-express-key", "true"), ("AIza-synthetic-developer-key", "false")])@pytest.mark.parametrize("source", ["global", "custom", "connected"])async def test_gemini_backend_matches_saved_key_type(models, monkeypatch, key, mode, source):import constantsdb, auth = models- auth.get_api_key.return_value = key+ auth.resolve_api_key.return_value = keyctx = context()params = MobileParams()if source == "custom":@@ -118,7 +127,7 @@ async def test_openai_and_claude_use_selected_model_credentials_and_endpoint(modimport constantsdb, auth = modelsdb.get_user_settings.return_value = {"default_llm_provider": provider, "default_llm_model": "selected-vision-model"}- auth.get_api_key.side_effect = lambda name, *_: endpoint if name == provider + "_proxy" else "selected-key"+ auth.resolve_api_key.side_effect = lambda name, *_, **kw: endpoint if name == provider + "_proxy" else "selected-key"ctx = context()params = MobileParams()if source == "custom":diff --git a/server/tools/database_transfer.py b/server/tools/database_transfer.pynew file mode 100644index 00000000..36be2161--- /dev/null+++ b/server/tools/database_transfer.py@@ -0,0 +1,177 @@+"""Offline application metadata transfer; encrypted local stores stay local.++Run with ``python -m tools.database_transfer``. Both applications must be+stopped and deployments/tasks reset before export; this is not live replication.+"""+from __future__ import annotations++import argparse+import asyncio+import json+import socket+from datetime import datetime+from pathlib import Path++from sqlalchemy import DateTime, Integer, func, inspect, select, text+from sqlmodel import SQLModel++from core.config import Settings+from core.database import Database++EXCLUDED_TABLES = frozenset({+ "api_keys", "api_key_validations", "google_connections", "gmail_connections",+ "credentials_metadata", "encrypted_api_keys", "oauth_tokens",+ "cache_entries", "browser_owners", "browser_transient_routes",+ "subagent_concurrency_counters", "subagent_concurrency_permits",+})+SECRET_FIELDS = frozenset({"api_key", "apiKey", "access_token", "refresh_token", "password", "client_secret"})+++def _assert_no_inline_secrets(value):+ if isinstance(value, dict):+ for key, child in value.items():+ if key in SECRET_FIELDS and child:+ raise ValueError("Remove inline credentials and enroll 1Password bindings before exporting application metadata")+ _assert_no_inline_secrets(child)+ elif isinstance(value, list):+ for child in value:+ _assert_no_inline_secrets(child)+++def validate_manifest(manifest):+ if not isinstance(manifest, dict) or manifest.get("version") != 1 or not isinstance(manifest.get("tables"), dict):+ raise ValueError("Unsupported database transfer format")+ for name, rows in manifest["tables"].items():+ if name in EXCLUDED_TABLES or name not in SQLModel.metadata.tables or not isinstance(rows, list):+ raise ValueError("Unknown or excluded table in database transfer")+ table = SQLModel.metadata.tables[name]+ for row in rows:+ if not isinstance(row, dict) or set(row) != set(table.columns.keys()):+ raise ValueError("Database transfer schema differs from the current application schema")+ if name in {"workflows", "node_parameters", "workflow_control_executions"}:+ _assert_no_inline_secrets(row)+ if name == "workspace_task_records" and row.get("completed_at") is None:+ raise ValueError("Cancel or finish every Workspace task before offline transfer")+ if name == "browser_profile_owners":+ if row.get("task_id"):+ raise ValueError("Finish Browser cleanup before offline transfer")+ if row.get("owner_id") != "local":+ raise ValueError("This command transfers local metadata; distributed ownership needs an operator migration")+ if not isinstance(manifest.get("local_owner_machine_id"), str) or not 0 < len(manifest["local_owner_machine_id"]) <= 255:+ raise ValueError("Offline browser ownership requires its original machine identity")+ if name == "workflow_control_executions" and row.get("status") not in {"reset", "completed", "failed", "cancelled", "terminated"}:+ raise ValueError("Reset every deployed workflow before offline transfer")+++async def export_manifest(database: Database) -> dict:+ if database.engine.dialect.name != "sqlite":+ raise ValueError("Export requires a local SQLite application database")+ tables = {}+ async with database.engine.connect() as connection:+ await connection.exec_driver_sql("BEGIN EXCLUSIVE")+ try:+ present = set(await connection.run_sync(lambda sync: inspect(sync).get_table_names()))+ for table in SQLModel.metadata.sorted_tables:+ if table.name in EXCLUDED_TABLES or table.name not in present:+ continue+ tables[table.name] = [dict(row) for row in (await connection.execute(select(table))).mappings()]+ finally:+ await connection.rollback()+ manifest = {"version": 1, "tables": tables,+ "local_owner_machine_id": database.settings.browser_machine_id or socket.gethostname()}+ # Profiles created by the old SQLite app predate owner metadata. Preserve+ # their original machine instead of letting the first cluster caller adopt+ # them after import. Existing ownership and recovery latches stay intact.+ from models.browser_owners import BrowserProfileOwner+ ownership = tables.setdefault("browser_profile_owners", [])+ owned = {row["profile_id"] for row in ownership}+ for profile in tables.get("browser_profiles", []):+ if profile["id"] not in owned:+ ownership.append(BrowserProfileOwner(profile_id=profile["id"],+ principal_id=profile["owner_id"], owner_id="local").model_dump())+ validate_manifest(manifest)+ return manifest+++async def import_manifest(database: Database, manifest: dict) -> None:+ validate_manifest(manifest)+ async with database.engine.begin() as connection:+ if database.engine.dialect.name == "postgresql":+ await connection.execute(text("SELECT pg_advisory_xact_lock(763746822)"))+ # No destructive overwrite or partial merge: import into a fresh schema.+ for table in SQLModel.metadata.sorted_tables:+ if table.name in EXCLUDED_TABLES:+ continue+ if (await connection.execute(select(func.count()).select_from(table))).scalar_one():+ raise ValueError("Database transfer requires an empty target application database")+ for table in SQLModel.metadata.sorted_tables:+ rows = manifest["tables"].get(table.name, [])+ decoded = []+ for row in rows:+ row = dict(row)+ for column in table.columns:+ typ = getattr(column.type, "original", column.type)+ if isinstance(typ, DateTime) and isinstance(row.get(column.name), str):+ row[column.name] = datetime.fromisoformat(row[column.name])+ decoded.append(row)+ if decoded:+ await connection.execute(table.insert(), decoded)+ if database.engine.dialect.name == "postgresql":+ for column in table.primary_key.columns:+ if column.autoincrement is False or not isinstance(column.type, Integer):+ continue+ sequence = (await connection.execute(text("SELECT pg_get_serial_sequence(:table, :column)"),+ {"table": table.name, "column": column.name})).scalar_one()+ if sequence:+ maximum = (await connection.execute(select(func.max(column)))).scalar_one() or 0+ await connection.execute(text("SELECT setval(CAST(:sequence AS regclass), :next_id, false)"),+ {"sequence": sequence, "next_id": maximum + 1})+ if manifest["tables"].get("browser_profile_owners"):+ from models.browser_owners import BrowserOwner+ # Keep the imported profile owner unavailable until the original+ # machine explicitly boots its first cluster replica as `local`.+ await connection.execute(BrowserOwner.__table__.insert().values(owner_id="local",+ machine_id=manifest["local_owner_machine_id"], runtime_epoch="offline-import",+ base_url="", heartbeat_at=0))+++async def _run(args):+ if not args.offline:+ raise ValueError("Stop local writers and Reset deployed workflows, then acknowledge with --offline")+ if args.operation == "export":+ source = Path(args.sqlite).resolve(strict=True)+ output = Path(args.output)+ if output.exists():+ raise ValueError("Export output already exists")+ database = Database(Settings(distributed_mode=False, database_url_override=f"sqlite+aiosqlite:///{source.as_posix()}"))+ else:+ database = Database(Settings(distributed_mode=False))+ if not database.settings.database_url.startswith("postgresql+asyncpg://"):+ raise ValueError("Import requires DATABASE_URL configured for the new shared PostgreSQL database")+ await database.startup()+ try:+ if args.operation == "export":+ manifest = await export_manifest(database)+ with output.open("x", encoding="utf-8") as handle:+ json.dump(manifest, handle, ensure_ascii=False, default=lambda value: value.isoformat() if isinstance(value, datetime) else value)+ else:+ await import_manifest(database, json.loads(Path(args.input).read_text(encoding="utf-8")))+ finally:+ await database.shutdown()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ commands = parser.add_subparsers(dest="operation", required=True)+ export = commands.add_parser("export")+ export.add_argument("--sqlite", required=True)+ export.add_argument("--output", required=True)+ export.add_argument("--offline", action="store_true")+ target = commands.add_parser("import")+ target.add_argument("--input", required=True)+ target.add_argument("--offline", action="store_true")+ asyncio.run(_run(parser.parse_args()))+++if __name__ == "__main__":+ main()diff --git a/server/uv.lock b/server/uv.lockindex cf3c1080..b9e3c2fc 100644--- a/server/uv.lock+++ b/server/uv.lock@@ -165,6 +165,32 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/fe/ba/e2081de779ca30d473f21f5b30e0e737c438205440784c7dfc81efc2b029/async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c", size = 6233, upload-time = "2024-11-06T16:41:37.9Z" },]+[[package]]+name = "asyncpg"+version = "0.32.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/80/4e/59dc964f962f09e3ed472e5d2d3ba670a41a2be25080dc62ab3db507ff5e/asyncpg-0.32.0.tar.gz", hash = "sha256:45e64e56714d888330b884aad1dfb363d0bf43fb343e3d1a8968525f3bade478", size = 1075156, upload-time = "2026-10-06T20:32:40.251Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a3/27/1a7970f1ece6c205b03c79f45b89420dee9655ffb66bd2c11be8f40c248a/asyncpg-0.32.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5789340b9bcdab94a19eb8ff119322a09991e3626d131b55828535b373e285d4", size = 686071, upload-time = "2026-10-06T20:30:39.115Z" },+ { url = "https://files.pythonhosted.org/packages/2b/47/085934d0290806a92789eee860109c44bea71ff8bc7850a9d3a30da7a819/asyncpg-0.32.0-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:057ed2455e4e14ad9949f1ac1829112c7d0454c9810b124f36de1486febe6824", size = 692193, upload-time = "2026-10-06T20:30:40.563Z" },+ { url = "https://files.pythonhosted.org/packages/b4/2c/d92524b9e860aecd119c0ebe43f3b9eca26dc2b75c4dfe1be3e999e3f6b1/asyncpg-0.32.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c938c4da9166ac1ef330475e314e2b94c68bde2795be0f4e8a1e00ccd806cadd", size = 3196713, upload-time = "2026-10-06T20:30:42.123Z" },+ { url = "https://files.pythonhosted.org/packages/85/b5/3ac7cb86aa287e5bbceaeb783ee6e4f51cd2a001f1747ef4f1236a20bde6/asyncpg-0.32.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:968c570c5913b7ce0995953d7239bd2367142d1af4359f87699f7a6ca75c4382", size = 3260618, upload-time = "2026-10-06T20:30:43.552Z" },+ { url = "https://files.pythonhosted.org/packages/e3/08/618ac36b2970b437d45523f50b5580dba0c34756bbf2153306f82a2697e5/asyncpg-0.32.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:96c8226d2026e025852facb5a05035ea5e11b14bebb6b42e4e43948ef8f0d075", size = 3132973, upload-time = "2026-10-06T20:30:45.147Z" },+ { url = "https://files.pythonhosted.org/packages/f6/e6/54db41b3d5fe26b0401a49327ffce439195c5f6073d8afbbdc9758cb35c3/asyncpg-0.32.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d3f745f4947df9004e2637753ff81d52f305f790f49d67f72e1677db12b07a7b", size = 3251612, upload-time = "2026-10-06T20:30:46.923Z" },+ { url = "https://files.pythonhosted.org/packages/a7/e0/ed1e7536ce949896de29ee955b473659b3daa7887e7081030dba2b15ea5d/asyncpg-0.32.0-cp311-cp311-win32.whl", hash = "sha256:469e6520a839957304582eb8a708d874985914500b64517155f80e6fec00e742", size = 538739, upload-time = "2026-10-06T20:30:48.355Z" },+ { url = "https://files.pythonhosted.org/packages/df/eb/52c4bddad17ff1bee485ae83e08c752a998ef04ac5df76f03fef6430d0ed/asyncpg-0.32.0-cp311-cp311-win_amd64.whl", hash = "sha256:6a1e671e67f4b0bef3c03f37a896d61706f769a83922c119070f1f04e415dc17", size = 610534, upload-time = "2026-10-06T20:30:50.003Z" },+ { url = "https://files.pythonhosted.org/packages/85/c7/9af12f2b3300c425a151ef8f85f47c0db76135827c549031858954805ff7/asyncpg-0.32.0-cp311-cp311-win_arm64.whl", hash = "sha256:901bc87b94539f32853bd73a9b02fa78f7feed4cf628824caad3093ec6662f58", size = 574363, upload-time = "2026-10-06T20:30:51.489Z" },+ { url = "https://files.pythonhosted.org/packages/73/06/d5f956db9c936c90cd3289cf948a86c3efc9849e26354356c23da29f6a2d/asyncpg-0.32.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7cb31f7a8472ddc6b6f5c9da1290e901d5c77c8441c7213bd13b13ef6fe6359c", size = 681566, upload-time = "2026-10-06T20:30:52.779Z" },+ { url = "https://files.pythonhosted.org/packages/09/93/ea55f3b26fd40ec90e5b6d6c53b9ff52633cf6b87a468d9c033a727832f4/asyncpg-0.32.0-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:643d8d6e955a355045dddfe827d74f4f0d1dc4a18e06963a08260af838fbf093", size = 704359, upload-time = "2026-10-06T20:30:54.608Z" },+ { url = "https://files.pythonhosted.org/packages/46/2c/a3704e8675d37b168f3584661fc9f64f3021659c9b94e51cf9ab957b2bc5/asyncpg-0.32.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:14ff79ca2574182ce258159c48978a086f9026fc121d935017b5d10c64fa3c72", size = 3707008, upload-time = "2026-10-06T20:30:56.326Z" },+ { url = "https://files.pythonhosted.org/packages/30/30/4fd8d1155b3d7a32a2c241dcb9c5d9e9bd74a59ae71ed25ef8ddb8e038e1/asyncpg-0.32.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:54851411bee2aa51a30d0911524201fbb05f82cc0f7c248b140203db637c723d", size = 3810163, upload-time = "2026-10-06T20:30:58.114Z" },+ { url = "https://files.pythonhosted.org/packages/c1/25/5b0992d45661e1488aba775cf17a2e6c82c7d1d7e10acc71efd394760a00/asyncpg-0.32.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8592f0ed9c315b2117dbdc707cf3292f09a89d5b07661016a84dd881326965cf", size = 3600446, upload-time = "2026-10-06T20:30:59.946Z" },+ { url = "https://files.pythonhosted.org/packages/ea/88/1c82c6feacec813423401b5aef1a43baea951694157f4d405b2d14e80e6d/asyncpg-0.32.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4dbe0982cb3ded878de0867dfaeae3116faf471d484ea28b3e3da942f01fb778", size = 3764563, upload-time = "2026-10-06T20:31:01.462Z" },+ { url = "https://files.pythonhosted.org/packages/84/f5/5a3796088f0c3f7d22aaf7c48536f40b27e44b7c9603d4d7abfeca2ed97e/asyncpg-0.32.0-cp312-cp312-win32.whl", hash = "sha256:fbe1f8c788fb5df18ea8a5432dfa2473fd8f7f088025fb83d089a7c7b37e37b0", size = 551810, upload-time = "2026-10-06T20:31:03.248Z" },+ { url = "https://files.pythonhosted.org/packages/af/42/f4d333a3f67b0e7cf58ea855f9d5d9104ce38c21f2a2f22bf7dce524428c/asyncpg-0.32.0-cp312-cp312-win_amd64.whl", hash = "sha256:cd7157a86817730c3239bc687abf8186a471525d695e225c187b9a523a808a98", size = 626763, upload-time = "2026-10-06T20:31:04.927Z" },+ { url = "https://files.pythonhosted.org/packages/a8/82/9d82e16e1d0b4e2a639a2db649d4b444b8a479cd52553a9c36ba0d6320a8/asyncpg-0.32.0-cp312-cp312-win_arm64.whl", hash = "sha256:9509e21fc526f1fc27cf80ad9f9b8dde3f3e21935d46be66d649635321d3407c", size = 577288, upload-time = "2026-10-06T20:31:06.776Z" },+]+[[package]]name = "attrs"version = "26.1.0"@@ -1892,6 +1918,7 @@ dependencies = [{ name = "aiosqlite" },{ name = "anthropic" },{ name = "apify-client" },+ { name = "asyncpg" },{ name = "bcrypt" },{ name = "crawlee", extra = ["beautifulsoup"] },{ name = "cryptography" },@@ -1978,6 +2005,7 @@ requires-dist = [{ name = "aiosqlite", specifier = ">=0.20.0" },{ name = "anthropic", specifier = "==0.96.0" },{ name = "apify-client", specifier = ">=1.8.0" },+ { name = "asyncpg", specifier = ">=0.30.0,<1" },{ name = "bcrypt", specifier = ">=4.2.0" },{ name = "beautifulsoup4", marker = "extra == 'docs'", specifier = ">=4.12.0" },{ name = "boto3", marker = "extra == 'aws'", specifier = ">=1.34.0" },