Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: require operator authority for Runs and host voice tools (#8834)
[._.]/ Adam Eivy913407a8a2d5
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex bfc84f5837..f1065bb503 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -80,6 +80,9 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// and rotation must already hold operator authority (#8771).'POST /api/auth/password',+ // Generic runs accept arbitrary prompts/workspaces, including API-to-CLI fallback.+ 'POST /api/runs',+// Apps: create/edit choose the repo path and the start/build commands; the// lifecycle and launch routes run them under PM2 or the native launcher.'POST /api/apps',diff --git a/server/routes/hostControlRunsVoice.test.js b/server/routes/hostControlRunsVoice.test.jsnew file mode 100644index 0000000000..271b7007db--- /dev/null+++ b/server/routes/hostControlRunsVoice.test.js@@ -0,0 +1,219 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { asyncHandler, errorMiddleware, ServerError } from '../lib/errorHandler.js';++const auth = vi.hoisted(() => ({ enabled: false, session: false }));+vi.mock('../services/auth.js', () => ({+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyRequestSession: vi.fn(async () => auth.session),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: new EventEmitter(),+ getSettings: vi.fn(async () => ({ security: { passwordRiskAcknowledged: true } })),+}));+vi.mock('../services/voice/config.js', () => ({+ getVoiceConfig: vi.fn(async () => ({+ enabled: true,+ llm: { model: 'test-model', usePersonality: false, systemPrompt: 'sys',+ tools: { enabled: true, maxIterations: 1 }, codeAgent: { enabled: true } },+ })),+}));+vi.mock('../services/appProcessStatus.js', () => ({ annotateExpectedExit: async (processes) => processes }));+vi.mock('../services/pm2.js', () => ({+ listProcesses: vi.fn(async () => [{ name: 'example-api', status: 'online' }]),+ restartApp: vi.fn(async () => {}),+}));+vi.mock('../services/cos.js', () => ({+ addTask: vi.fn(async () => ({ id: 'example-task' })),+ isRunning: () => true,+ reviveBlockedTask: vi.fn(),+}));+vi.mock('../services/providers.js', () => ({+ getActiveProvider: vi.fn(async () => ({ id: 'example-cli', type: 'cli', enabled: true })),+ getProviderById: vi.fn(), getAllProviders: vi.fn(),+}));+vi.mock('../services/voice/stt.js', () => ({+ transcribe: vi.fn(async () => ({ text: 'restart the example service', latencyMs: 1 })),+}));+vi.mock('../services/voice/tts.js', () => ({ synthesize: vi.fn(async () => ({ wav: Buffer.alloc(8), latencyMs: 1 })) }));+vi.mock('../services/voice/llm.js', () => ({ streamChat: vi.fn() }));+// Only replace the call transport/endpoint detector; real socket handlers,+// pipeline, tool dispatcher, auth predicates, and tool bodies run end to end.+const callHost = vi.hoisted(() => ({ socket: null }));+vi.mock('../services/voice/callSession.js', () => ({+ attachHost: (socket) => { callHost.socket = socket; return { ok: true, state: {} }; },+ getCallHost: () => callHost.socket, isCallActive: () => true,+ getCallState: () => ({}), getCallContext: () => null,+ peekCallOpeningLine: () => null, clearCallOpeningLine: vi.fn(),+ detachHost: vi.fn(), endCall: vi.fn(), markListening: vi.fn(), markSpeaking: vi.fn(),+ noteCallerSpeech: vi.fn(), recordTurn: vi.fn(), setCallStateListener: vi.fn(),+}));+vi.mock('../services/voice/callEndpointing.js', async (importOriginal) => ({+ ...await importOriginal(),+ createCallEndpointer: () => ({ speaking: false, push: () => ({ pcm: new Int16Array(16) }), reset() {} }),+}));+vi.mock('../services/voice/captureSession.js', () => ({+ isCaptureActive: () => false, getCaptureHost: () => null,+ attachCaptureHost: vi.fn(), detachCaptureHost: vi.fn(), endCapture: vi.fn(),+ recordUtterance: vi.fn(), setCaptureStateListener: vi.fn(), startCapture: vi.fn(),+}));++import { authGate, hostControlRouteGate, socketAuthGate } from '../services/authGate.js';+import { createRunsRoutes } from '../lib/aiToolkit/routes/runs.js';+import paletteRoutes from './palette.js';+import { registerVoiceHandlers } from '../sockets/voice.js';+import { dispatchTool } from '../services/voice/tools.js';+import { streamChat } from '../services/voice/llm.js';+import { restartApp } from '../services/pm2.js';+import { addTask } from '../services/cos.js';++const runner = {+ createRun: vi.fn(), executeCliRun: vi.fn(), executeTuiRun: vi.fn(), executeApiRun: vi.fn(),+};+const appFor = (address) => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json());+ app.use('/api/runs', createRunsRoutes(runner, { asyncHandler, ServerError }));+ app.use('/api/palette', paletteRoutes);+ app.use(errorMiddleware);+ return app;+};+const runBody = { providerId: 'example-provider', prompt: 'Fix the example test', workspacePath: '/example/repo' };+const hostTools = [+ ['pm2_restart', { name: 'example-api' }],+ ['dispatch_code_agent', { task: 'Fix the example test' }],+];+const responseFor = (name, args) => ({ text: '', model: 'test-model', toolCalls: [+ { id: 'call-1', type: 'function', function: { name, arguments: JSON.stringify(args) } },+] });+const socketFor = async (address) => {+ const handlers = new Map();+ const socket = {+ id: 'example-socket', data: {}, handshake: { address, headers: {} },+ on: (event, fn) => handlers.set(event, fn), emit: vi.fn(),+ fire: (event, payload) => handlers.get(event)?.(payload),+ };+ await socketAuthGate(socket, (err) => { if (err) throw err; });+ registerVoiceHandlers(socket);+ return socket;+};+const fireTurn = async (socket, event) => {+ const forged = { hasHostControl: true, portosLocalConnection: true, authenticated: true };+ if (event === 'voice:call:audio') await socket.fire('voice:call:attach');+ await socket.fire(event, { text: 'restart the example service', audio: Buffer.alloc(8), pcm: Buffer.alloc(32), ...forged });+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+ auth.session = false;+ callHost.socket = null;+});++describe('Runs and palette host authority (#8834)', () => {+ it('refuses remote password-free Runs before creating metadata or resolving any runner/fallback', async () => {+ const response = await request(appFor('192.0.2.10')).post('/api/runs').send(runBody);+ expect(response.status).toBe(403);+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ for (const sink of Object.values(runner)) expect(sink).not.toHaveBeenCalled();+ });++ it('refuses a Basic peer credential for Runs before creating metadata', async () => {+ auth.enabled = true;+ const response = await request(appFor('192.0.2.10')).post('/api/runs')+ .set('Authorization', `Basic ${Buffer.from(':example-password').toString('base64')}`)+ .send(runBody);+ expect(response.status).toBe(403);+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ expect(runner.createRun).not.toHaveBeenCalled();+ });++ it.each(['cli', 'tui', 'api'])('allows local and session Runs with %s fallback', async (type) => {+ runner.createRun.mockResolvedValue({ runId: 'example-run', provider: { type }, metadata: {}, usedFallback: true, fallbackModel: 'fallback-model' });+ for (const address of ['127.0.0.1', '192.0.2.10']) {+ auth.enabled = address !== '127.0.0.1';+ auth.session = auth.enabled;+ expect((await request(appFor(address)).post('/api/runs').send(runBody)).status).toBe(202);+ }+ const sink = { cli: runner.executeCliRun, tui: runner.executeTuiRun, api: runner.executeApiRun }[type];+ expect(sink).toHaveBeenCalledTimes(2);+ expect(sink.mock.calls[0][0]).toMatchObject(type === 'api'+ ? { model: 'fallback-model' } : { provider: { defaultModel: 'fallback-model' } });+ });++ it.each(hostTools)('protects palette %s from remote anonymous and Basic callers, allowing local/session', async (name, args) => {+ for (const enabled of [false, true]) {+ auth.enabled = enabled;+ const response = await request(appFor('192.0.2.10')).post(`/api/palette/action/${name}`)+ .set('Authorization', `Basic ${Buffer.from(':example-password').toString('base64')}`)+ .send({ args: { ...args, hasHostControl: true }, hasHostControl: true });+ expect(response.status).toBe(403);+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ }+ expect(restartApp).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ for (const address of ['127.0.0.1', '192.0.2.10']) {+ auth.enabled = address !== '127.0.0.1';+ auth.session = auth.enabled;+ expect((await request(appFor(address)).post(`/api/palette/action/${name}`).send({ args })).status).toBe(200);+ }+ expect(name === 'pm2_restart' ? restartApp : addTask).toHaveBeenCalledTimes(2);+ });++ it('does not grant host tools authority from missing or JSON-shaped contexts, while read tools stay usable', async () => {+ for (const [name, args] of hostTools) {+ for (const ctx of [undefined, { hasHostControl: true }, { hasHostControl: () => false }]) {+ await expect(dispatchTool(name, { ...args, hasHostControl: true }, ctx)).rejects.toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN' });+ }+ }+ expect((await request(appFor('192.0.2.10')).post('/api/palette/action/pm2_status').send({})).status).toBe(200);+ expect(restartApp).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ });+});++describe.each(['voice:text', 'voice:turn', 'voice:call:audio'])('%s tool authority', (event) => {+ it.each(hostTools)('rejects forged remote authority for %s through the real pipeline', async (name, args) => {+ streamChat.mockResolvedValue(responseFor(name, { ...args, hasHostControl: true }));+ const socket = await socketFor('192.0.2.10');+ await fireTurn(socket, event);+ expect(streamChat).toHaveBeenCalled();+ expect(socket.emit).toHaveBeenCalledWith('voice:error', expect.objectContaining({ code: 'HOST_CONTROL_FORBIDDEN', message: expect.stringContaining('operator session') }));+ expect(restartApp).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ });++ it('allows local/operator tools but rechecks a revoked session after the model responds', async () => {+ const [name, args] = hostTools[0];+ streamChat.mockResolvedValue(responseFor(name, args));+ await fireTurn(await socketFor('127.0.0.1'), event);+ auth.enabled = true;+ auth.session = true;+ const operator = await socketFor('192.0.2.10');+ await fireTurn(operator, event);+ expect(restartApp).toHaveBeenCalledTimes(2);+ streamChat.mockImplementationOnce(async () => {+ auth.session = false;+ return responseFor(name, args);+ });+ await fireTurn(operator, event);+ expect(restartApp).toHaveBeenCalledTimes(2);+ expect(operator.emit).toHaveBeenCalledWith('voice:error', expect.objectContaining({ code: 'HOST_CONTROL_FORBIDDEN' }));+ });++ it('keeps non-host tools usable for remote password-free callers', async () => {+ streamChat.mockResolvedValue(responseFor('pm2_status', {}));+ const socket = await socketFor('192.0.2.10');+ await fireTurn(socket, event);+ expect(streamChat).toHaveBeenCalled();+ expect(socket.emit).not.toHaveBeenCalledWith('voice:error', expect.objectContaining({ code: 'HOST_CONTROL_FORBIDDEN' }));+ expect(socket.emit).toHaveBeenCalledWith('voice:tool', expect.objectContaining({ name: 'pm2_status' }));+ });+});diff --git a/server/routes/palette.js b/server/routes/palette.jsindex f6b996234b..4b8b4498b5 100644--- a/server/routes/palette.js+++ b/server/routes/palette.js@@ -16,6 +16,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { NAV_COMMANDS } from '../lib/navManifest.js';import { dispatchTool, getToolMetadata } from '../services/voice/tools.js';+import { requireHostControl, requestHasHostControl } from '../services/authGate.js';const router = Router();@@ -82,13 +83,15 @@ const actionBodySchema = z.object({args: z.record(z.any()).optional().default({}),});-router.post('/action/:id', asyncHandler(async (req, res) => {+router.post('/action/:id', (req, res, next) => (+ getToolMetadata(req.params.id)?.hostControl ? requireHostControl(req, res, next) : next()+), asyncHandler(async (req, res) => {const id = String(req.params.id || '');if (!PALETTE_ACTION_IDS.has(id)) {throw new ServerError(`Unknown palette action "${id}"`, { status: 404 });}const { args } = validateRequest(actionBodySchema, req.body ?? {});- const result = await dispatchTool(id, args, { sideEffects: [] });+ const result = await dispatchTool(id, args, { sideEffects: [], hasHostControl: () => requestHasHostControl(req) });res.json({ ok: result?.ok !== false, result });}));diff --git a/server/services/authGate.js b/server/services/authGate.jsindex e68d9fa57e..4bd678ae2d 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -251,9 +251,24 @@ const hasHostControl = (auth, localConnection) =>export const HOST_CONTROL_FORBIDDEN_MESSAGE = 'Host control requires an operator session, or a local connection when no password is set. Set an instance password to use it remotely.';+// Server-derived HTTP authority; never read caller-provided body fields.+export const requestHasHostControl = (req) => hasHostControl(+ req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers),+);++// Re-check at tool dispatch, after any STT/LLM wait. A handshake/session that+// was valid when a turn started is not a durable grant to execute later.+export const socketHasCurrentHostControl = async (socket) => {+ if (socket.disconnected === true) return false;+ if (await isAuthEnabled()) {+ return await verifyRequestSession({ headers: socket.handshake?.headers || {} }) === true;+ }+ return socketHasHostControl(socket);+};+// Mount after authGate: missing context fails closed.export const requireHostControl = (req, res, next) => {- if (hasHostControl(req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers))) return next();+ if (requestHasHostControl(req)) return next();sendErrorResponse(res, new ServerError(HOST_CONTROL_FORBIDDEN_MESSAGE, {status: 403, code: 'HOST_CONTROL_FORBIDDEN',}));diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 92c76a7bf0..80c6a29321 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -984,7 +984,13 @@ const executeAdapter = async (tool, args, context, authority) => {: adjustPersistentMindLocalContext(args, context);}if (tool.adapter.kind === 'voice-tool') {- return dispatchTool(tool.adapter.legacyName, args, { sideEffects: [], signal: context.signal });+ return dispatchTool(tool.adapter.legacyName, args, {+ sideEffects: [], signal: context.signal,+ // executeCosToolCall already validated this server-owned principal and+ // the tool's capability. Never promote arguments or voice scope to host authority.+ hasHostControl: () => ['agent', 'mind'].includes(authority?.scope)+ || (authority?.scope === 'ui' && authority.authenticated === true),+ });}if (tool.adapter.kind.startsWith('persistent-mind-issue-')) {const { filePersistentMindIssue, listPersistentMindIssues } = await import('./persistentMindIssueCapability.js');diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex cf6f9587f0..5dbede6271 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -493,7 +493,22 @@ describe('cosToolRegistry', () => {context: { signal },});expect(result.state).toBe('completed');- expect(mocks.dispatch).toHaveBeenCalledWith('brain_search', { query: 'example' }, { sideEffects: [], signal });+ expect(mocks.dispatch).toHaveBeenCalledWith('brain_search', { query: 'example' }, { sideEffects: [], signal, hasHostControl: expect.any(Function) });+ expect(mocks.dispatch.mock.calls[0][2].hasHostControl()).toBe(false);+ });++ it('derives the voice adapter grant from a validated principal, never the arguments', async () => {+ await executeCosToolCall({+ call: { requestId: 'authorized-write', name: 'brain.capture', arguments: { text: 'example' } },+ authority: { scope: 'mind', capabilities: { writePortos: true } },+ });+ expect(mocks.dispatch.mock.calls[0][2].hasHostControl()).toBe(true);+ await executeCosToolCall({+ call: { requestId: 'voice-read', name: 'brain.search', arguments: { query: 'example' } },+ authority: { scope: 'voice', authenticated: true },+ context: { hasHostControl: () => true },+ });+ expect(mocks.dispatch.mock.calls[1][2].hasHostControl()).toBe(false);});it('blocks untrusted HTTP mutations and ungranted mind tools', async () => {diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex 59c272e26b..9a3701b2ee 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -388,7 +388,7 @@ const shortId = () => Math.random().toString(36).slice(2, 7);// of that conversation and a runaway caller would blow the model's window.const MAX_SYSTEM_CONTEXT_CHARS = 4000;-export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state, systemContext = null }) => {+export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state, systemContext = null, hasHostControl }) => {const cfg = await getVoiceConfig();if (signal?.aborted) return { transcript: '', reply: '' };@@ -737,6 +737,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi// so the tool just calls ctx.requestUiText() with no plumbing.const ctx = {sideEffects: [],+ hasHostControl,state,signal,// ui_describe_visually: capture the active tab (client round-trip) and@@ -757,6 +758,9 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi} catch (err) {const ms = Date.now() - t0;result = { ok: false, error: err.message };+ if (err.code === 'HOST_CONTROL_FORBIDDEN') {+ emit('voice:error', { stage: 'tool', code: err.code, message: err.message });+ }toolRuns.push({ name: tc.function.name, ok: false, ms, error: err.message });tlog(`tool.fail ${tc.function.name} ${ms}ms err="${err.message}"`);}diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex d7442e7f1a..e381428724 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -181,7 +181,7 @@ export const getAllToolNames = () => TOOLS.map((t) => t.name);export const getToolMetadata = (id) => {const tool = TOOLS.find((t) => t.name === id);if (!tool) return null;- return { id: tool.name, description: tool.description, parameters: tool.parameters };+ return { id: tool.name, description: tool.description, parameters: tool.parameters, hostControl: tool.hostControl === true };};// Intent-filtered spec list. Pass the user's current utterance; returns the@@ -228,5 +228,13 @@ export const getToolSpecsForIntent = (userText) => {export const dispatchTool = async (name, args, ctx) => {const tool = TOOLS.find((t) => t.name === name);if (!tool) throw new Error(`Unknown tool: ${name}`);+ // A function supplied by our HTTP/socket/internal adapter cannot be forged+ // in JSON tool arguments. Missing context fails closed, even when enabled.+ if (tool.hostControl && (typeof ctx?.hasHostControl !== 'function' || await ctx.hasHostControl() !== true)) {+ const [{ HOST_CONTROL_FORBIDDEN_MESSAGE }, { ServerError }] = await Promise.all([+ import('../authGate.js'), import('../../lib/errorHandler.js'),+ ]);+ throw new ServerError(HOST_CONTROL_FORBIDDEN_MESSAGE, { status: 403, code: 'HOST_CONTROL_FORBIDDEN' });+ }return tool.execute(args || {}, ctx || { sideEffects: [] });};diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex 6c683da09b..cc7cf379fd 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -266,21 +266,21 @@ describe('dispatch_code_agent', () => {});it('rejects an empty task without creating a CoS task', async () => {- const r = await dispatchTool('dispatch_code_agent', { task: ' ' });+ const r = await dispatchTool('dispatch_code_agent', { task: ' ' }, { hasHostControl: () => true });expect(r.ok).toBe(false);expect(mockedAddTask).not.toHaveBeenCalled();});it('refuses when codeAgent is disabled', async () => {mockedGetVoiceConfig.mockResolvedValue({ llm: { codeAgent: { enabled: false } } });- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' }, { hasHostControl: () => true });expect(r.ok).toBe(false);expect(r.error).toMatch(/disabled/);expect(mockedAddTask).not.toHaveBeenCalled();});it('creates a voice-dispatched user task without pinning provider/model by default', async () => {- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the failing backup test' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the failing backup test' }, { hasHostControl: () => true });expect(r.ok).toBe(true);expect(r.taskId).toBe('task-test');expect(mockedAddTask).toHaveBeenCalledTimes(1);@@ -295,7 +295,7 @@ describe('dispatch_code_agent', () => {it('pins provider/model when configured', async () => {mockedGetVoiceConfig.mockResolvedValue({ llm: { codeAgent: { enabled: true, provider: 'codex-cli', model: 'gpt-5' } } });- await dispatchTool('dispatch_code_agent', { task: 'add a flag' });+ await dispatchTool('dispatch_code_agent', { task: 'add a flag' }, { hasHostControl: () => true });expect(mockedAddTask.mock.calls[0][0]).toMatchObject({ provider: 'codex-cli', model: 'gpt-5' });});@@ -307,7 +307,7 @@ describe('dispatch_code_agent', () => {{ id: 'lmstudio', type: 'api', enabled: true },{ id: 'codex', type: 'cli', enabled: true },] });- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' }, { hasHostControl: () => true });expect(r.ok).toBe(true);const [data] = mockedAddTask.mock.calls[0];expect(data.provider).toBe('codex');@@ -318,7 +318,7 @@ describe('dispatch_code_agent', () => {it('errors when the system default is an API backend and no CLI/TUI provider is enabled', async () => {mockedGetActiveProvider.mockResolvedValue({ id: 'lmstudio', type: 'api', enabled: true });mockedGetAllProviders.mockResolvedValue({ providers: [{ id: 'lmstudio', type: 'api', enabled: true }] });- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' }, { hasHostControl: () => true });expect(r.ok).toBe(false);expect(r.error).toMatch(/code-capable/);expect(mockedAddTask).not.toHaveBeenCalled();@@ -333,7 +333,7 @@ describe('dispatch_code_agent', () => {{ id: 'lmstudio', type: 'api', enabled: true },{ id: 'claude-code', type: 'tui', enabled: true },] });- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' }, { hasHostControl: () => true });expect(r.ok).toBe(true);const [data] = mockedAddTask.mock.calls[0];expect(data.provider).toBe('claude-code');@@ -345,20 +345,20 @@ describe('dispatch_code_agent', () => {// the spawner rather than swapping a provider we know nothing about.mockedGetVoiceConfig.mockResolvedValue({ llm: { codeAgent: { enabled: true, provider: 'my-custom-cli', model: 'x' } } });mockedGetProviderById.mockResolvedValue(null);- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the build' }, { hasHostControl: () => true });expect(r.ok).toBe(true);expect(mockedAddTask.mock.calls[0][0]).toMatchObject({ provider: 'my-custom-cli', model: 'x' });});it('warns in the summary when the CoS runner is stopped', async () => {mockedIsRunning.mockReturnValue(false);- const r = await dispatchTool('dispatch_code_agent', { task: 'refactor X' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'refactor X' }, { hasHostControl: () => true });expect(r.ok).toBe(true);expect(r.summary).toMatch(/stopped/i);});it('resolves a spoken `app` to a managed-app id and threads it through addTask', async () => {- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: 'book loom' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: 'book loom' }, { hasHostControl: () => true });expect(r.ok).toBe(true);expect(r.app).toBe('bookloom-abc');expect(r.summary).toMatch(/in BookLoom/);@@ -366,12 +366,12 @@ describe('dispatch_code_agent', () => {});it('omits the `app` field on addTask when no target is spoken (PortOS-self)', async () => {- await dispatchTool('dispatch_code_agent', { task: 'fix the test' });+ await dispatchTool('dispatch_code_agent', { task: 'fix the test' }, { hasHostControl: () => true });expect(mockedAddTask.mock.calls[0][0]).not.toHaveProperty('app');});it('errors when the spoken app is unknown — does NOT silently fall through to PortOS', async () => {- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: 'GhostApp' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: 'GhostApp' }, { hasHostControl: () => true });expect(r.ok).toBe(false);expect(r.error).toMatch(/GhostApp/);expect(r.summary).toMatch(/BookLoom/); // suggestion list pulled from active apps@@ -379,7 +379,7 @@ describe('dispatch_code_agent', () => {});it('ignores an empty/whitespace `app` string (treats as omitted)', async () => {- const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: ' ' });+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: ' ' }, { hasHostControl: () => true });expect(r.ok).toBe(true);expect(mockedAddTask.mock.calls[0][0]).not.toHaveProperty('app');});@@ -569,10 +569,10 @@ describe('goal_log_note type guard', () => {describe('pm2_restart type guard', () => {it('rejects non-string name', async () => {- await expect(dispatchTool('pm2_restart', { name: 12345 })).rejects.toThrow(/name is required/);+ await expect(dispatchTool('pm2_restart', { name: 12345 }, { hasHostControl: () => true })).rejects.toThrow(/name is required/);});it('rejects empty string name', async () => {- await expect(dispatchTool('pm2_restart', { name: ' ' })).rejects.toThrow(/name is required/);+ await expect(dispatchTool('pm2_restart', { name: ' ' }, { hasHostControl: () => true })).rejects.toThrow(/name is required/);});});diff --git a/server/services/voice/tools/code.js b/server/services/voice/tools/code.jsindex ec433e3e2b..ac79b57240 100644--- a/server/services/voice/tools/code.js+++ b/server/services/voice/tools/code.js@@ -19,6 +19,7 @@ export const CODE_INTENT_RE = /\b(?:have (?:claude|codex|antigravity|gemini|theexport const CODE_TOOLS = [{name: 'dispatch_code_agent',+ hostControl: true,description:'Hand a software-engineering task to an autonomous coding agent that works in an isolated git worktree and opens a pull request for review. Use when the user asks you to write, fix, refactor, debug, or test CODE — e.g. "fix the failing test in X", "add a --dry-run flag to the backup script", "refactor the widget registry". Do NOT use for capturing notes/ideas (that is brain_capture) or for clicking/navigating the UI. The work runs in the background and the user is told when it finishes — do not wait for it. State the task in the user\'s own words with enough detail to act on it. When the user names a managed app to work in ("…in BookLoom", "fix the bug in the finance tracker"), pass that name as `app`; omit `app` for tasks on PortOS itself. The coding agent and model come from the user\'s configured default; never put a provider or model in this call.',parameters: {diff --git a/server/services/voice/tools/system.js b/server/services/voice/tools/system.jsindex c8aec18567..096c188b4c 100644--- a/server/services/voice/tools/system.js+++ b/server/services/voice/tools/system.js@@ -50,6 +50,7 @@ export const SYSTEM_TOOLS = [{name: 'pm2_restart',+ hostControl: true,description:'Restart a PortOS PM2 process by name. Use when the user says "restart the whisper server", "restart portos-api", "bounce the cos runner". Only restart — never kill or delete.',parameters: {diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex 1517779670..8045465084 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -16,6 +16,7 @@// Inbound: voice:capture:start | voice:call:audio | voice:capture:stop// Outbound: voice:capture:state+import { socketHasCurrentHostControl } from '../services/authGate.js';import { runTurn } from '../services/voice/pipeline.js';import { getVoiceConfig } from '../services/voice/config.js';import { registerEchoBuffer, unregisterEchoBuffer } from '../services/voice/echo.js';@@ -179,6 +180,7 @@ export const registerVoiceHandlers = (socket) => {try {const { transcript, reply } = await runTurn({audio, mimeType, text, source, history: state.history, emit, signal, state,+ hasHostControl: () => socketHasCurrentHostControl(socket),});// Don't persist transcript/reply when the turn was aborted or superseded// by a newer turn — the user interrupted, and that output shouldn't@@ -494,6 +496,7 @@ export const registerVoiceHandlers = (socket) => {// A mind-placed call carries the mind's own briefing, so the voice on// the phone continues that conversation instead of answering cold.systemContext: getCallContext(),+ hasHostControl: () => socketHasCurrentHostControl(socket),// The pipeline speaks the widget's event vocabulary; only the audio is// re-addressed, so persona, tools, and the confirm gate are unchanged.emit: (event, data) => {