Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Expose literal-argv terminal launches through a shell service (#893)

Deeb6b4772ddd1f
diff --git a/cli/e2e/shell.e2e.ts b/cli/e2e/shell.e2e.ts
new file mode 100644
index 000000000..51c8cc517
--- /dev/null
+++ b/cli/e2e/shell.e2e.ts
@@ -0,0 +1,108 @@
+/** A connected shell opens through the service, with literal arguments and the terminal's existing access rules. */
+import { randomUUID } from 'node:crypto'
+import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'
+import { SHELL_REQUESTS } from '../src/lib/shellProtocol.js'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+import { startPhoneMachine, type PhoneMachine } from './harness/fleet.js'
+import { RelayPhone } from './harness/relayPhone.js'
+
+function shell(d: IsolatedDaemon) {
+ const cwd = join(d.projectsDir, 'folder with spaces')
+ mkdirSync(cwd, { recursive: true })
+ const marker = join(cwd, 'argv.txt')
+ const script = join(cwd, 'start shell.sh')
+ // The caller sends only a path and literal arguments. This fixture writes what the shell received,
+ // then becomes an interactive shell so the client can attach and type through the real stream.
+ writeFileSync(script, 'marker="$1"\nshift\nprintf "%s\\n" "$PWD" "$@" > "$marker"\nexec /bin/sh -i\n')
+ const args = ['a b', '$(touch injected)', '; touch injected', "quote'and\"quote", '']
+ return { cwd, marker, args, payload: { creationId: randomUUID(), cwd, argv: ['/bin/sh', script, marker, ...args] } }
+}
+async function written(fixture: ReturnType<typeof shell>) {
+ await until('the shell to record its literal arguments', () => existsSync(fixture.marker) || null, 15_000, 50)
+ const [cwd, ...args] = readFileSync(fixture.marker, 'utf8').split('\n')
+ expect(realpathSync(cwd)).toBe(realpathSync(fixture.cwd))
+ expect(args).toEqual([...fixture.args, ''])
+ expect(existsSync(join(fixture.cwd, 'injected'))).toBe(false)
+}
+
+describe('opening connected shells', () => {
+ let daemon: IsolatedDaemon | undefined
+ let world: PhoneMachine | undefined
+ const clients: Array<{ close(): void }> = []
+ afterEach(async () => {
+ for (const client of clients.splice(0)) client.close()
+ await daemon?.close(); daemon = undefined
+ await world?.close(); world = undefined
+ })
+
+ it('opens a local shell while a client is connected, accepts terminal input and recovers the same launch after reconnect', async () => {
+ daemon = await IsolatedDaemon.create()
+ const d = daemon
+ onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))
+ await d.start()
+ const client = await LocalClient.connect(d); clients.push(client)
+ const fixture = shell(d)
+ expect(await client.request('shell_capabilities')).toMatchObject({ protocol: 1 })
+ const created = await client.request('shell_open', fixture.payload)
+ expect(created).toMatchObject({ state: 'created', agent: { engine: 'terminal', terminal: { available: true } } })
+ await written(fixture)
+ const requestId = randomUUID()
+ const attached = client.next(f => ['terminal_ready', 'terminal_error'].includes(f.type) && f.payload?.requestId === requestId)
+ client.send('terminal_open', { requestId, protocolVersion: 3, agentId: created.agent.id, cols: 100, rows: 30 })
+ const ready = await attached
+ expect(ready.type, JSON.stringify(ready)).toBe('terminal_ready')
+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId: ready.payload!.streamId, seq: 0, compressed: false,
+ bytes: Buffer.from('printf shell-input-ok > input.txt\r') })
+ await until('the shell to receive input from its attached view', () => existsSync(join(fixture.cwd, 'input.txt')) || null, 20_000, 100)
+ expect(readFileSync(join(fixture.cwd, 'input.txt'), 'utf8')).toBe('shell-input-ok')
+ client.close()
+ const again = await LocalClient.connect(d); clients.push(again)
+ expect(await again.request('shell_open_status', fixture.payload)).toMatchObject({ state: 'created', agent: { id: created.agent.id } })
+ expect(await again.request('shell_open', fixture.payload)).toMatchObject({ state: 'created', agent: { id: created.agent.id } })
+ expect((await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}')).split('\n')).toHaveLength(1)
+ })
+
+ it('opens remotely through a sealed owner connection, answers only its requester and refuses every unsealed shell request', async () => {
+ world = await startPhoneMachine()
+ const w = world
+ const d = w.machine.daemon
+ onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))
+ const options = { backend: w.backend, machineId: w.machine.machineId, machinePub: w.machine.identity.pub, ...w.phone }
+ const phone = new RelayPhone(options); clients.push(phone); await phone.open()
+ const witness = new RelayPhone(options); clients.push(witness); await witness.open()
+ const fixture = shell(d)
+ expect(await phone.request('shell_capabilities')).toMatchObject({ protocol: 1 })
+ const created = await phone.request('shell_open', fixture.payload)
+ expect(created).toMatchObject({ state: 'created', agent: { engine: 'terminal', terminal: { available: true } } })
+ await written(fixture)
+ expect(await phone.request('shell_open_status', fixture.payload)).toMatchObject({ state: 'created', agent: { id: created.agent.id } })
+ expect(await phone.request('shell_open', { ...fixture.payload, creationId: randomUUID(), command: 'echo unsafe' })).toMatchObject({ error: 'INVALID_ARGV' })
+ for (const type of SHELL_REQUESTS) {
+ const requestId = randomUUID()
+ w.backend.injectDown(w.machine.machineId, phone.connId!, { type, payload: { ...fixture.payload, creationId: randomUUID(), requestId } })
+ const refused = await phone.waitFor(f => f.type === `${type}_result` && f.payload?.requestId === requestId)
+ expect(refused.payload).toMatchObject({ error: 'E2EE_REQUIRED' })
+ }
+ // A subsequent answer is a barrier on the same connection, so the witness assertion needs no sleep.
+ await witness.request('agents_list')
+ const results = w.backend.webReceived.get(phone.connId!)!.filter(f => SHELL_REQUESTS.some(type => f.type === `${type}_result`))
+ expect(results.length).toBeGreaterThan(4)
+ expect(results.every(f => f.payload?.__e2e?.k === 'p')).toBe(true)
+ expect(witness.frames.some(f => SHELL_REQUESTS.some(type => f.type === `${type}_result`))).toBe(false)
+ expect(JSON.stringify(w.backend.webSent.get(phone.connId!))).not.toContain(fixture.cwd)
+ expect((await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}')).split('\n')).toHaveLength(1)
+ })
+
+ it('answers unavailable when the service cannot start, while the core continues serving agents', async () => {
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'shell' } })
+ await daemon.start()
+ const client = await LocalClient.connect(daemon); clients.push(client)
+ for (const type of SHELL_REQUESTS) expect(await client.request(type)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'shell' })
+ expect(await client.request('agents_list')).toHaveProperty('agents')
+ expect(daemon.coresStarted()).toBe(1)
+ })
+})
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 89716b253..ca4c2dd76 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -162,7 +162,10 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
* Grew by 97 for the Jev catalog (#888, lib/localModels.ts and appModels.ts): the models service's own
* code, in the core's process only until step 7 runs models in a process of its own and takes it out.
*/
-const CORE_CLOSURE_BUDGET = 106_034
+// Connected TUI shells add a literal-argv launch port and shell service (160 loaded lines).
+// Moving the search filename out of its CLI command removes 188 loaded lines, so this lowers
+// the measured closure by 28. Shell policy stays in the service; the core only launches argv.
+const CORE_CLOSURE_BUDGET = 106_006
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
@@ -262,13 +265,11 @@ const CORE_MAY_REACH: Record<string, string> = {
'lib/gridTarget.ts': 'step 7: models, in its own process',
'lib/gridWake.ts': 'step 7: models, in its own process',
'lib/localModels.ts': 'step 7: models, in its own process',
- 'lib/sessionSearch/command.ts': 'step 5: search\'s in-process start, into services/inline.ts',
'lib/sessionSearch/indexer.ts': 'step 5: search\'s in-process start, into services/inline.ts',
'lib/sessionSearch/sessionTurns.ts': 'step 5: the handoff (lib/agentHandoff.ts), in the edge host',
'lib/sessionSearch/store.ts': 'step 5: search\'s in-process start, into services/inline.ts',
'lib/sessionSearch/transcript.ts': 'step 5: search\'s in-process start, into services/inline.ts; the readers keep this helper, beside them',
'lib/sessionSearch/turns.ts': 'step 5: the handoff (lib/agentHandoff.ts), in the edge host',
- 'lib/sessionSearch/when.ts': 'step 5: the handoff (lib/agentHandoff.ts), in the edge host',
'orchestrator/artifacts.ts': 'step 8: the experimental host',
'orchestrator/model.ts': 'step 8: the experimental host',
'orchestrator/prompts.ts': 'step 8: the experimental host',
@@ -278,6 +279,7 @@ const CORE_MAY_REACH: Record<string, string> = {
'services/fleetRouter.ts': 'step 9: the fleet, beside the dial',
'services/models.ts': 'step 7: models, in its own process',
'services/monitor.ts': 'step 5: the machine monitor, in the edge host',
+ 'services/shell.ts': 'step 5: shell setup and launch receipts, in the edge host; only the argv launch stays in the core',
'services/projects.ts': 'step 5: the project and folder readers, in the edge host',
'services/requestErrors.ts': 'step 7: with the last service that uses it, models, out of the core\'s process',
'services/search.ts': 'step 5: search\'s in-process start, into services/inline.ts',
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index f27a528fb..a43f5c701 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -13,6 +13,7 @@ import { bindAgentList, bindAgentUpdate, bindCancelRequest, bindLaunchRequests,
import { emptyPorts, MODELS_FALLBACKS, MONITOR_FALLBACKS } from './core/api.js'
import { createServiceHost, ServiceUnavailableError } from './core/serviceHost.js'
import { MODELS_REQUESTS, startModels } from './services/models.js'
+import { SHELL_REQUESTS, startShell } from './services/shell.js'
import { USAGE_REQUESTS, startUsage } from './services/usage.js'
import { MONITOR_REQUESTS, startMonitor, type MonitorDeps } from './services/monitor.js'
import { PROJECTS_REQUESTS, startProjects } from './services/projects.js'
@@ -3686,6 +3687,28 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()
expect(replies).toEqual([{ connId: 'web-1', type, payload: { error: 'E2EE_REQUIRED' } }])
})
+ it.each([...SHELL_REQUESTS])('requires sealing for %s and its requester-only result', async type => {
+ const { socket, replies, dispatch } = harness()
+ const serviceRouter = vi.fn(() => true)
+ socket.serviceRouter = serviceRouter
+ expect(encryptDownFrame(type)).toBe(true)
+ expect(encryptDownFrameFor(type, { strictDown: false })).toBe(true)
+ expect(encryptRpcResult(`${type}_result`)).toBe(true)
+ await dispatch({ type, payload: { requestId: 'r', argv: ['/bin/sh'], cwd: '/tmp', owner: true } }, 'web-1')
+ expect(serviceRouter).not.toHaveBeenCalled()
+ expect(replies).toEqual([{ connId: 'web-1', type, payload: { error: 'E2EE_REQUIRED' } }])
+ })
+
+ it.each([...SHELL_REQUESTS])('refuses a sealed %s from a device even when its payload claims ownership', async type => {
+ const { socket, replies, dispatch } = harness()
+ const core = fakeCore()
+ serveOn(socket, host => host.serve('shell', startShell, core, SHELL_REQUESTS))
+ vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue('device')
+ await dispatch(sealedDown(socket, 'device-1', type, { requestId: 'r', owner: true }).frame, 'device-1')
+ await vi.waitFor(() => expect(replies).toEqual([{ connId: 'device-1', type, payload: { error: 'OWNER_REQUIRED' } }]))
+ expect(core.terminals.open).not.toHaveBeenCalled()
+ })
+
it('hands a sealed dsh_install from a paired client to the service that answers it', async () => {
const { socket, dispatch } = harness()
const serviceRouter = vi.fn(() => true)
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 10a902822..ae09505c7 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -14,7 +14,7 @@ describe('the core API services stand on', () => {
expect(resolveAgent(agents, 'nobody')).toBeUndefined()
})
- it('lists every agent, live then stopped, and names them as the apps do', () => {
+ it('lists every agent, live then stopped, and names them as the apps do', async () => {
const deps: CoreApiDeps = {
dataDir: '/data',
registry: {
@@ -46,6 +46,9 @@ describe('the core API services stand on', () => {
}
const core = createCoreApi(deps)
expect(core.dataDir).toBe('/data')
+ expect(await core.terminals.open({ argv: ['/bin/zsh'], cwd: '/work' })).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
+ const terminals = { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })) }
+ expect(createCoreApi({ ...deps, terminals }).terminals).toBe(terminals)
expect(core.agents.all().map((s) => s.agentId)).toEqual(['live', 'stopped'])
expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])
expect(core.agents.displayName).toBe(projectDisplayName)
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 264d4bf5d..d61d76ca9 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -32,9 +32,22 @@ import { FAIL, later, ServiceUnavailableError, type PortFallbacks } from './serv
export type { RouteAnswer }
+/** A service may open a terminal with a literal argv, never shell source. */
+export interface TerminalOpen {
+ argv: string[]
+ cwd: string
+}
+export type TerminalOpenResult = { ok: true; agentId: string } | { ok: false; error: string; detail?: string }
+export interface TerminalsPort { open(request: TerminalOpen): Promise<TerminalOpenResult> }
+/** A service without the core's launch call must refuse, never launch outside the core. */
+export const TERMINALS_OFF: TerminalsPort = {
+ open: async () => ({ ok: false, error: 'SERVICE_UNAVAILABLE' }),
+}
+
export interface CoreApi {
/** The daemon's data folder; a service keeps its own files in it. */
dataDir: string
+ terminals: TerminalsPort
agents: {
/** Every agent on this machine: the live ones, then the stopped ones. */
all(): RegisteredSession[]
@@ -337,6 +350,7 @@ export function emptyPorts(): CorePorts {
}
export interface CoreApiDeps {
+ terminals?: TerminalsPort
dataDir: string
registry: Pick<typeof registry, 'list' | 'byAgent' | 'resolve' | 'advertised' | 'terminalAvailable'>
stoppedAgents: Pick<StoppedAgentStore, 'list'>
@@ -363,10 +377,11 @@ export interface CoreApiDeps {
export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,
gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, privateGridName, machineName,
- runtimeProfile, setRuntime, fork, turns, questions,
+ runtimeProfile, setRuntime, fork, turns, questions, terminals = TERMINALS_OFF,
}: CoreApiDeps): CoreApi {
return {
dataDir,
+ terminals,
agents: {
all: () => [...registry.list(), ...stoppedAgents.list()],
live: () => registry.list(),
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index fa826e54c..823a1c847 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -90,6 +90,8 @@ import { RECONCILE_PASS_DEADLINE_MS, TerminalAgentReconciler } from '../lib/term
import { Watcher } from '../watcher/watcher.js'
import { startHookServer } from '../hookServer.js'
import { connectToMaster } from '../harnessd/coreLink.js'
+import { createTerminalOpener } from './terminals/open.js'
+import { SHELL_REQUESTS, startShell } from '../services/shell.js'
import { createTerminalControl } from './terminals/control.js'
import { createTerminalRequests } from './terminals/requests.js'
import { createAgentEvents } from './agents/events.js'
@@ -684,6 +686,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const openSessions = new OpenSessions({ providers: externalEngines, log: (line) => console.warn(line) })
// The core's side of the boundary its services stand on, and the ports it reaches them through (core/api.ts).
const coreApi = createCoreApi({
+ terminals: createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }),
dataDir: env.ADAPTER_DATA_DIR,
registry,
stoppedAgents,
@@ -1174,6 +1177,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// An agent's branch and pull request, a project's repository and preview, a folder's subfolders and a
// media file from an agent's project (services/projects.ts).
serviceHost.serve('projects', startProjects, coreApi, PROJECTS_REQUESTS)
+ serviceHost.serve('shell', startShell, coreApi, SHELL_REQUESTS)
const runtimeController = new RuntimeProfileController({
manager: runtimeProfiles,
diff --git a/cli/src/core/terminals/open.spec.ts b/cli/src/core/terminals/open.spec.ts
new file mode 100644
index 000000000..7ef138529
--- /dev/null
+++ b/cli/src/core/terminals/open.spec.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createAndRegisterPane } from '../../lib/createAgentPane.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+import { createTerminalOpener, type TerminalOpenerDeps } from './open.js'
+
+vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
+vi.mock('../../lib/tmux.js', () => ({ clearPaneRemainOnExit: vi.fn(async () => {}) }))
+
+const row = { agentId: 'shell', engine: 'terminal', launch: { state: 'ready' } } as RegisteredSession
+function setup(over: Partial<TerminalOpenerDeps> = {}) {
+ const deps: TerminalOpenerDeps = {
+ tmuxBackend: { create: vi.fn(), kill: vi.fn() },
+ registry: { openPendingAgent: vi.fn(), setLaunch: vi.fn(() => row) },
+ announceSession: vi.fn(), blocksFolder: vi.fn(() => false), ...over,
+ }
+ vi.mocked(createAndRegisterPane).mockResolvedValue({ ok: true, pending: row,
+ spawned: { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%42' } },
+ })
+ return { deps, open: createTerminalOpener(deps).open }
+}
+
+describe('the core terminal launch call', () => {
+ afterEach(() => vi.clearAllMocks())
+ it('registers literal argv in its folder, marks it ready and announces it', async () => {
+ const { deps, open } = setup()
+ const argv = ['/bin/zsh', '/work/a script', '$(touch injected)', 'a; b', '']
+ expect(await open({ argv, cwd: '/work/project' })).toEqual({ ok: true, agentId: 'shell' })
+ expect(createAndRegisterPane).toHaveBeenCalledWith({
+ tmuxBackend: deps.tmuxBackend, registry: deps.registry, engine: 'terminal', cwd: '/work/project',
+ spawnCwd: '/work/project', argv, sessionLabel: expect.stringMatching(/^harness-shell-[\da-f-]+$/), bypassPermission: false,
+ })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0].argv).not.toBe(argv)
+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%42')
+ expect(deps.registry.setLaunch).toHaveBeenCalledWith('shell', { state: 'ready' })
+ expect(deps.announceSession).toHaveBeenCalledWith(row)
+ })
+ it('refuses when tmux is unavailable or the folder is being removed', async () => {
+ expect(await setup({ tmuxBackend: null }).open({ argv: ['/bin/sh'], cwd: '/work' })).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })
+ expect(await setup({ blocksFolder: () => true }).open({ argv: ['/bin/sh'], cwd: '/work' })).toEqual({ ok: false, error: 'WORKTREE_BUSY' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+ it('preserves a failed launch and never announces it', async () => {
+ const { deps, open } = setup()
+ vi.mocked(createAndRegisterPane).mockResolvedValueOnce({ ok: false, error: 'SPAWN_FAILED', detail: 'gone' })
+ expect(await open({ argv: ['/bin/sh'], cwd: '/work' })).toEqual({ ok: false, error: 'SPAWN_FAILED', detail: 'gone' })
+ expect(clearPaneRemainOnExit).not.toHaveBeenCalled()
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ })
+ it('does not announce a terminal that closed before it became ready', async () => {
+ const { deps, open } = setup()
+ vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
+ expect(await open({ argv: ['/bin/sh'], cwd: '/work' })).toEqual({ ok: false, error: 'TERMINAL_CLOSED' })
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/core/terminals/open.ts b/cli/src/core/terminals/open.ts
new file mode 100644
index 000000000..0d15ba53f
--- /dev/null
+++ b/cli/src/core/terminals/open.ts
@@ -0,0 +1,30 @@
+/** The core's narrow launch call. Shell setup and request policy belong to the shell service. */
+import { randomUUID } from 'node:crypto'
+import type { TerminalsPort } from '../api.js'
+import { createAndRegisterPane, type CreateAgentPaneDeps } from '../../lib/createAgentPane.js'
+import type { RegisteredSession, registry } from '../../lib/registry.js'
+import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+
+export interface TerminalOpenerDeps {
+ tmuxBackend: CreateAgentPaneDeps['tmuxBackend'] | null
+ registry: CreateAgentPaneDeps['registry'] & Pick<typeof registry, 'setLaunch'>
+ announceSession(session: RegisteredSession): void
+ blocksFolder(cwd: string): boolean
+}
+
+export function createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder }: TerminalOpenerDeps): TerminalsPort {
+ return { open: async ({ argv, cwd }) => {
+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'terminal', cwd, spawnCwd: cwd,
+ argv: [...argv], sessionLabel: `harness-shell-${randomUUID()}`, bypassPermission: false,
+ })
+ if (!result.ok) return result
+ await clearPaneRemainOnExit(result.spawned.runtime.paneId)
+ const ready = registry.setLaunch(result.pending.agentId, { state: 'ready' })
+ if (!ready) return { ok: false, error: 'TERMINAL_CLOSED' }
+ announceSession(ready)
+ return { ok: true, agentId: ready.agentId }
+ } }
+}
diff --git a/cli/src/lib/createAgentPane.spec.ts b/cli/src/lib/createAgentPane.spec.ts
index 27b44900c..5819da232 100644
--- a/cli/src/lib/createAgentPane.spec.ts
+++ b/cli/src/lib/createAgentPane.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'fs'
-import { tmpdir } from 'os'
+import { homedir, tmpdir } from 'os'
import { join } from 'path'
import type { TerminalCreateResult, TmuxRuntimeRef } from './terminalTypes.js'
import { createAndRegisterPane } from './createAgentPane.js'
@@ -54,10 +54,23 @@ describe('createAndRegisterPane', () => {
expect(result.ok).toBe(true)
expect(tmuxBackend.create).toHaveBeenCalledTimes(1)
- expect(tmuxBackend.create).toHaveBeenCalledWith(expect.objectContaining({ label: 'harness-claude-1' }))
+ expect(tmuxBackend.create).toHaveBeenCalledWith(expect.objectContaining({ label: 'harness-claude-1', cwd: homedir() }))
expect(tmuxBackend.kill).not.toHaveBeenCalled()
})
+ it('starts an explicit-argv terminal in its folder without evaluating its arguments', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const tmuxBackend = fakeTmux([succeeded('%1')])
+ const argv = ['/bin/zsh', '/work/a script', '$(touch injected)', 'a; echo b', '']
+ const result = await createAndRegisterPane({
+ tmuxBackend, registry, engine: 'terminal', cwd: '/work/project with spaces',
+ spawnCwd: '/work/project with spaces', sessionLabel: 'harness-shell-1', argv,
+ })
+ expect(result.ok).toBe(true)
+ expect(tmuxBackend.create).toHaveBeenCalledWith({ label: 'harness-shell-1', cwd: '/work/project with spaces', command: argv })
+ })
+
it('retries past a stale registration collision and succeeds on the next pane', async () => {
const { registry } = await loadRegistryModule()
registry.load()
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index 3235e7b07..10761f824 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -52,6 +52,8 @@ export interface CreateAgentPaneDeps {
/** Base tmux session name (`-s`). Retries append `-r<attempt>` — see module doc. */
sessionLabel: string
argv: string[]
+ /** Explicit-argv terminals start here; engine wrappers still enter cwd after rc files. */
+ spawnCwd?: string
env?: Record<string, string>
grid?: { baseUrl: string; model: string | null } | null
/** The grid launch behind `grid` (credential included — what restore/restart relaunch the pane with)
@@ -82,7 +84,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
// The login shell starts somewhere stable; its argv enters the requested workspace after rc
// files. `deps.cwd` still travels below, into the registry entry — this is only about where
// the pane's OWN shell starts, not the workspace the agent ends up in.
- cwd: homedir(),
+ cwd: deps.spawnCwd ?? homedir(),
label,
command: deps.argv,
...(deps.env ? { env: deps.env } : {}),
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index 22072f97c..6be131cf3 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -8,6 +8,7 @@
* the two callers (relayClient's wrap, backendSocket's unwrap and reply) must agree — they used to
* spell the union inline, in three places, and merging two of these features meant merging the spelling.
*/
+import { SHELL_REQUESTS } from '../shellProtocol.js'
import { ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType } from './core.js'
import { SHARE_REQUEST_TYPES, SHARE_RESULT_TYPES } from '../../sharing/protocol.js'
import { VIEWER_DOWN_TYPES } from '../viewerWire.js'
@@ -18,7 +19,7 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr
'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.
-const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare', ...OWNER_COMMAND_TYPES])
+const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare', ...OWNER_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the
* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floor
diff --git a/cli/src/lib/sessionSearch/command.ts b/cli/src/lib/sessionSearch/command.ts
index c5980231a..0e9fd1234 100644
--- a/cli/src/lib/sessionSearch/command.ts
+++ b/cli/src/lib/sessionSearch/command.ts
@@ -5,10 +5,10 @@
import { join } from 'node:path'
-import { MARK_CLOSE, MARK_OPEN, SessionSearchStore } from './store.js'
+import { MARK_CLOSE, MARK_OPEN, SessionSearchStore, SESSION_SEARCH_FILE } from './store.js'
import { parseSearchWhen } from './when.js'
-export const SESSION_SEARCH_FILE = 'session-search.db'
+export { SESSION_SEARCH_FILE } from './store.js'
export interface SearchCommandOptions {
argv: string[]
diff --git a/cli/src/lib/sessionSearch/store.ts b/cli/src/lib/sessionSearch/store.ts
index abc804dbe..1d87f20e4 100644
--- a/cli/src/lib/sessionSearch/store.ts
+++ b/cli/src/lib/sessionSearch/store.ts
@@ -20,6 +20,8 @@ import type { IndexedTurn } from './turns.js'
const SCHEMA_VERSION = '11'
/** The row that holds a session's name, title and folder: searchable beside its turns. */
+export const SESSION_SEARCH_FILE = 'session-search.db'
+
export const HEADER_TURN = -1
interface Statement {
diff --git a/cli/src/lib/shellContextReply.spec.ts b/cli/src/lib/shellContextReply.spec.ts
new file mode 100644
index 000000000..6dfadf8d0
--- /dev/null
+++ b/cli/src/lib/shellContextReply.spec.ts
@@ -0,0 +1,71 @@
+import { afterEach, expect, it } from 'vitest'
+import { closeSync, constants, mkdirSync, mkdtempSync, openSync, readSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { shellContextReply } from './shellContextReply.js'
+
+const homes: string[] = []
+const context = '8c73ea55-683a-4207-a9aa-ab8a9e813bea'
+const payload = {context, id:'12-34-56', code:0, text:'a model with spaces'}
+function fixture() {
+ const home = mkdtempSync(join(tmpdir(),'hn-shell-fifo-')); homes.push(home)
+ const dir = join(home,'.harness','shell-requests',context)
+ mkdirSync(dir,{recursive:true,mode:0o700})
+ return {home, file:join(dir,payload.id)}
+}
+afterEach(() => { for (const h of homes.splice(0)) rmSync(h,{recursive:true,force:true}) })
+it('writes data only to the waiting private FIFO and never needs terminal input', () => {
+ const {home,file} = fixture()
+ execFileSync('/usr/bin/mkfifo',['-m','600',file])
+ const fd = openSync(file,constants.O_RDWR | constants.O_NONBLOCK)
+ try {
+ expect(shellContextReply(payload,home)).toBe(true)
+ const data = Buffer.alloc(512), count = readSync(fd,data)
+ expect(data.subarray(0,count).toString()).toBe(`HN:${payload.id}:0:${Buffer.from(payload.text).toString('base64')}\n`)
+ } finally { closeSync(fd) }
+})
+it('rejects traversal, oversized responses, regular files and symlinks without modifying them', () => {
+ const {home,file} = fixture()
+ writeFileSync(file,'untouched',{mode:0o600})
+ for (const p of [payload,{...payload,id:'../escape'},{...payload,context:'../escape'},{...payload,text:'x'.repeat(2049)},{...payload,code:2}]) {
+ expect(shellContextReply(p,home)).toBe(false)
+ }
+ expect(readFileSync(file,'utf8')).toBe('untouched')
+ const other = join(home,'other'); writeFileSync(other,'other')
+ rmSync(file); symlinkSync(other,file)
+ expect(shellContextReply(payload,home)).toBe(false)
+ expect(readFileSync(other,'utf8')).toBe('other')
+})
+it('does not block on a cancelled or missing request', () => {
+ const {home,file} = fixture()
+ expect(shellContextReply(payload,home)).toBe(false)
+ execFileSync('/usr/bin/mkfifo',['-m','600',file])
+ expect(shellContextReply(payload,home)).toBe(false)
+})
+it('delivers a large catalog atomically with a short FIFO acknowledgement', () => {
+ const {home,file} = fixture()
+ execFileSync('/usr/bin/mkfifo',['-m','600',file])
+ const fd = openSync(file,constants.O_RDWR | constants.O_NONBLOCK)
+ const data = {rows: Array.from({length:1000},(_,i)=>({id:String(i),label:`Saved conversation ${i}`}))}
+ try {
+ expect(shellContextReply({...payload,data},home)).toBe(true)
+ expect(JSON.parse(readFileSync(file+'.json','utf8'))).toEqual(data)
+ expect(statSync(file+'.json').mode & 0o777).toBe(0o600)
+ const buffer = Buffer.alloc(512)
+ expect(readSync(fd,buffer)).toBeGreaterThan(0)
+ expect(shellContextReply({...payload,data:'x'.repeat(8*1024*1024)},home)).toBe(false)
+ } finally { closeSync(fd) }
+})
+it('does not follow a catalog symlink or write a catalog for an absent reader', () => {
+ const {home,file} = fixture()
+ const other = join(home,'other'); writeFileSync(other,'untouched')
+ symlinkSync(other,file+'.json')
+ execFileSync('/usr/bin/mkfifo',['-m','600',file])
+ const fd = openSync(file,constants.O_RDWR | constants.O_NONBLOCK)
+ try { expect(shellContextReply({...payload,data:{rows:[]}},home)).toBe(false) }
+ finally { closeSync(fd) }
+ expect(readFileSync(other,'utf8')).toBe('untouched')
+ rmSync(file+'.json')
+ expect(shellContextReply({...payload,data:{rows:[]}},home)).toBe(false)
+})
diff --git a/cli/src/lib/shellContextReply.ts b/cli/src/lib/shellContextReply.ts
new file mode 100644
index 000000000..42502b23c
--- /dev/null
+++ b/cli/src/lib/shellContextReply.ts
@@ -0,0 +1,42 @@
+/** Private, bounded replies to a shell helper. Never type protocol data into stdin. */
+import { constants, closeSync, fstatSync, lstatSync, openSync, renameSync, rmSync, writeFileSync, writeSync } from 'node:fs'
+import { randomUUID } from 'node:crypto'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+export function shellContextReply(payload: Record<string, unknown>, home = homedir()): boolean {
+ const { context, id, code, text } = payload
+ if (typeof context !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(context)
+ || typeof id !== 'string' || !/^[a-zA-Z0-9-]{1,80}$/.test(id)
+ || (code !== 0 && code !== 1) || typeof text !== 'string' || Buffer.byteLength(text) > 2048) return false
+ const uid = process.getuid?.()
+ let fd: number | undefined
+ try {
+ const base = join(home, '.harness', 'shell-requests')
+ for (const path of [base, join(base, context)]) {
+ const stat = lstatSync(path)
+ if (!stat.isDirectory() || stat.uid !== uid || (stat.mode & 0o077) !== 0) return false
+ }
+ fd = openSync(join(base, context, id), constants.O_WRONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW)
+ const stat = fstatSync(fd)
+ if (!stat.isFIFO() || stat.uid !== uid || (stat.mode & 0o077) !== 0) return false
+ // Large picker catalogs travel through a private file, not through terminal
+ // stdin or a single nonblocking FIFO write that could be only partly written.
+ if (payload.data !== undefined) {
+ const data = JSON.stringify(payload.data)
+ if (Buffer.byteLength(data) > 8 * 1024 * 1024) return false
+ const target = join(base, context, `${id}.json`)
+ try {
+ const old = lstatSync(target)
+ if (!old.isFile() || old.uid !== uid || (old.mode & 0o077) !== 0 || old.nlink !== 1) return false
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return false }
+ const staged = `${target}.${randomUUID()}`
+ try {
+ writeFileSync(staged, data, { flag: 'wx', mode: 0o600 })
+ renameSync(staged, target)
+ } finally { rmSync(staged, { force: true }) }
+ }
+ const line = `HN:${id}:${code}:${Buffer.from(text).toString('base64')}\n`
+ return writeSync(fd, line) === Buffer.byteLength(line)
+ } catch { return false } finally { if (fd !== undefined) closeSync(fd) }
+}
diff --git a/cli/src/lib/shellProtocol.ts b/cli/src/lib/shellProtocol.ts
new file mode 100644
index 000000000..57e3459ad
--- /dev/null
+++ b/cli/src/lib/shellProtocol.ts
@@ -0,0 +1,2 @@
+/** Always sealed over the relay; replies go only to the requester. */
+export const SHELL_REQUESTS = ['shell_capabilities', 'shell_open', 'shell_open_status', 'shell_context_reply'] as const
diff --git a/cli/src/services/search.spec.ts b/cli/src/services/search.spec.ts
index 25721561c..c3d95f11d 100644
--- a/cli/src/services/search.spec.ts
+++ b/cli/src/services/search.spec.ts
@@ -4,11 +4,10 @@ import { emptyPorts, type CoreApi } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { SessionSearchIndexOptions } from '../lib/sessionSearch/indexer.js'
import { fakeCore } from '../testing/fakeCore.js'
-import { SESSION_SEARCH_FILE } from '../lib/sessionSearch/command.js'
-import { SessionSearchStore } from '../lib/sessionSearch/store.js'
+import { SessionSearchStore, SESSION_SEARCH_FILE } from '../lib/sessionSearch/store.js'
import { SEARCH_REQUESTS, searchRequests, startSearch } from './search.js'
-vi.mock('../lib/sessionSearch/store.js', () => ({ SessionSearchStore: { open: vi.fn() } }))
+vi.mock('../lib/sessionSearch/store.js', () => ({ SESSION_SEARCH_FILE: 'session-search.db', SessionSearchStore: { open: vi.fn() } }))
// The index, recording what it was built with so its callbacks can be driven directly.
vi.mock('../lib/sessionSearch/indexer.js', async (real) => {
const actual = await real<typeof import('../lib/sessionSearch/indexer.js')>()
diff --git a/cli/src/services/search.ts b/cli/src/services/search.ts
index f57571801..a00b4fb2a 100644
--- a/cli/src/services/search.ts
+++ b/cli/src/services/search.ts
@@ -9,9 +9,8 @@
*/
import { join } from 'node:path'
import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
-import { SESSION_SEARCH_FILE } from '../lib/sessionSearch/command.js'
import { SessionSearchIndex, folderWords, type SearchSource } from '../lib/sessionSearch/indexer.js'
-import { SessionSearchStore } from '../lib/sessionSearch/store.js'
+import { SessionSearchStore, SESSION_SEARCH_FILE } from '../lib/sessionSearch/store.js'
/** The requests search answers for the apps. */
export const SEARCH_REQUESTS = ['session_search', 'session_tail'] as const
diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.ts
index eed622283..f10d3c0f8 100644
--- a/cli/src/services/searchProcess.ts
+++ b/cli/src/services/searchProcess.ts
@@ -8,7 +8,7 @@
* process's alone: a crash or a leak in search costs search, and the master starts it again.
*/
import type { CoreApi } from '../core/api.js'
-import { emptyPorts, resolveAgent } from '../core/api.js'
+import { emptyPorts, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import { databaseHistory } from '../core/transcripts/databaseHistory.js'
import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'
import { externalProviders } from '../lib/sessionSearch/externals/index.js'
@@ -40,6 +40,7 @@ export function searchCoreApi(
): CoreApi {
return {
dataDir,
+ terminals: TERMINALS_OFF,
agents: {
all: agents,
live: () => agents().filter((agent) => agent.active),
diff --git a/cli/src/services/shell.spec.ts b/cli/src/services/shell.spec.ts
new file mode 100644
index 000000000..ccd75a042
--- /dev/null
+++ b/cli/src/services/shell.spec.ts
@@ -0,0 +1,109 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { stat } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'
+import { shellContextReply } from '../lib/shellContextReply.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { SHELL_REQUESTS, startShell } from './shell.js'
+
+vi.mock('node:fs/promises', async importOriginal => ({
+ ...await importOriginal<typeof import('node:fs/promises')>(), stat: vi.fn(async () => ({ isDirectory: () => true })),
+}))
+vi.mock('../lib/shellContextReply.js', () => ({ shellContextReply: vi.fn(() => true) }))
+const OWNER = { local: false, owner: true }
+let dataDir: string
+function setup() {
+ const row = { agentId: 'shell', sessionId: '', engine: 'terminal', cwd: '/work/project', projectDir: 'project', launch: { state: 'ready' } } as RegisteredSession
+ const core = fakeCore({ dataDir, terminals: { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })) }, agents: {
+ byAgent: vi.fn(() => row), displayName: () => 'project', terminalAvailable: () => true,
+ } })
+ const requests = startShell(core)
+ const ask = (type: string, payload: Record<string, unknown> = {}, asker = OWNER) => requests[type]!(payload, asker)
+ const payload = { creationId: randomUUID(), cwd: '/work/project', argv: ['/bin/zsh', '/work/a script', '$(touch nope)', 'a; b', ''] }
+ return { core, requests, ask, payload }
+}
+
+describe('shells through a service', () => {
+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'shell-service-')) })
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); vi.clearAllMocks(); rmSync(dataDir, { recursive: true, force: true }) })
+ it('declares every request and refuses every non-owner, regardless of the payload', async () => {
+ const { requests, core, ask, payload } = setup()
+ expect(Object.keys(requests).sort()).toEqual([...SHELL_REQUESTS].sort())
+ for (const type of SHELL_REQUESTS) {
+ expect(await ask(type, { ...payload, owner: true }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ expect(core.terminals.open).not.toHaveBeenCalled()
+ expect(shellContextReply).not.toHaveBeenCalled()
+ expect(await ask('shell_capabilities')).toEqual({ protocol: 1 })
+ expect(await ask('shell_context_reply', { id: 'reply' })).toEqual({ ok: true })
+ expect(shellContextReply).toHaveBeenCalledWith({ id: 'reply' })
+ vi.mocked(shellContextReply).mockReturnValueOnce(false)
+ expect(await ask('shell_context_reply')).toEqual({ ok: false })
+ })
+ it('opens exact argv once, recovers a lost reply and keeps the receipt across service restarts', async () => {
+ const { core, ask, payload } = setup()
+ const reply = await ask('shell_open', payload)
+ expect(reply).toEqual({ creationId: payload.creationId, state: 'created', agent: {
+ id: 'shell', sessionId: '', engine: 'terminal', name: 'project', status: 'active', launch: { state: 'ready' },
+ terminal: { available: true }, project: { cwd: payload.cwd, root: payload.cwd, name: 'project' },
+ } })
+ expect(core.terminals.open).toHaveBeenCalledWith({ argv: payload.argv, cwd: payload.cwd })
+ expect(vi.mocked(core.terminals.open).mock.calls[0]![0].argv).not.toBe(payload.argv)
+ expect(await ask('shell_open', payload)).toEqual(reply)
+ expect(await ask('shell_open_status', payload)).toEqual(reply)
+ expect(await startShell(core).shell_open!(payload, OWNER)).toEqual(reply)
+ expect(core.terminals.open).toHaveBeenCalledTimes(1)
+ expect(await ask('shell_open', { ...payload, argv: ['/bin/bash'] })).toEqual({ error: 'CREATION_CONFLICT' })
+ vi.mocked(core.agents.byAgent).mockReturnValue(undefined)
+ expect(await ask('shell_open_status', payload)).toEqual({ creationId: payload.creationId, state: 'unavailable' })
+ })
+ it('requires a durable creation id, an absolute folder, and bounded literal argv', async () => {
+ const { core, ask, payload } = setup()
+ for (const type of ['shell_open', 'shell_open_status']) expect(await ask(type, { creationId: 'bad' })).toEqual({ error: 'INVALID_CREATION_ID' })
+ for (const argv of [undefined, 'echo hello', [], new Array(257).fill('x'), [null], [1], ['x\0y'], [''], ['x'.repeat(32 * 1024)]]) {
+ expect(await ask('shell_open', { ...payload, argv })).toEqual({ error: 'INVALID_ARGV' })
+ }
+ expect(await ask('shell_open', { ...payload, command: 'echo unsafe' })).toEqual({ error: 'INVALID_ARGV' })
+ for (const cwd of [undefined, 'relative', '/x\0y', '/' + 'x'.repeat(4096)]) {
+ expect(await ask('shell_open', { ...payload, cwd })).toEqual({ error: 'INVALID_CWD' })
+ }
+ expect(core.terminals.open).not.toHaveBeenCalled()
+ expect(await ask('shell_open_status', payload)).toEqual({ creationId: payload.creationId, state: 'missing' })
+ })
+ it('records launch failures, and never retries an unconfirmed launch', async () => {
+ const { core, ask, payload } = setup()
+ vi.mocked(core.terminals.open).mockResolvedValueOnce({ ok: false, error: 'TMUX_UNAVAILABLE', detail: 'gone' })
+ expect(await ask('shell_open', payload)).toEqual({ creationId: payload.creationId, state: 'failed', error: 'TMUX_UNAVAILABLE', detail: 'gone' })
+ const next = { ...payload, creationId: randomUUID() }
+ vi.mocked(core.terminals.open).mockRejectedValueOnce(new Error('the reply was lost'))
+ expect(await ask('shell_open', next)).toEqual({ creationId: next.creationId, state: 'unconfirmed' })
+ expect(await ask('shell_open', next)).toEqual({ creationId: next.creationId, state: 'unconfirmed' })
+ expect(core.terminals.open).toHaveBeenCalledTimes(2)
+ })
+ it('refuses unreadable folders and files without opening a terminal', async () => {
+ const { core, ask, payload } = setup()
+ vi.mocked(stat).mockRejectedValueOnce(new Error('ENOENT'))
+ expect(await ask('shell_open', payload)).toMatchObject({ state: 'failed', error: 'CWD_NOT_FOUND' })
+ vi.mocked(stat).mockResolvedValueOnce({ isDirectory: () => false } as Awaited<ReturnType<typeof stat>>)
+ expect(await ask('shell_open', { ...payload, creationId: randomUUID() })).toMatchObject({ state: 'failed', error: 'CWD_NOT_FOUND' })
+ expect(core.terminals.open).not.toHaveBeenCalled()
+ })
+ it('bounds a filesystem provider that never answers', async () => {
+ vi.useFakeTimers()
+ const { core, ask, payload } = setup()
+ vi.mocked(stat).mockImplementationOnce(() => new Promise(() => {}))
+ const opening = ask('shell_open', payload)
+ await vi.advanceTimersByTimeAsync(4001)
+ expect(await opening).toMatchObject({ state: 'failed', error: 'CWD_NOT_FOUND' })
+ expect(core.terminals.open).not.toHaveBeenCalled()
+ })
+ it('leaves unexpected failures to the service host instead of reporting a successful launch', async () => {
+ const { ask, payload } = setup()
+ vi.spyOn(AgentCreationReceipts.prototype, 'status').mockImplementationOnce(() => { throw new Error('unexpected') })
+ await expect(ask('shell_open_status', payload)).rejects.toThrow('unexpected')
+ })
+})
diff --git a/cli/src/services/shell.ts b/cli/src/services/shell.ts
new file mode 100644
index 000000000..25d19e095
--- /dev/null
+++ b/cli/src/services/shell.ts
@@ -0,0 +1,60 @@
+/** Shell requests stay outside the core: authorization, literal argv, and durable launch receipts. */
+import { stat } from 'node:fs/promises'
+import { isAbsolute, join } from 'node:path'
+import type { CoreApi, ServiceRequests } from '../core/api.js'
+import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from '../lib/agentCreationReceipt.js'
+import { shellContextReply } from '../lib/shellContextReply.js'
+export { SHELL_REQUESTS } from '../lib/shellProtocol.js'
+
+export function startShell(core: CoreApi): ServiceRequests {
+ const receipts = new AgentCreationReceipts(join(core.dataDir, 'shell-creations'))
+ const describe = (status: AgentCreationStatus): Record<string, unknown> => {
+ if (status.state !== 'created') return { ...status }
+ const row = core.agents.byAgent(status.agentId)
+ if (!row) return { state: 'unavailable' }
+ return { state: 'created', agent: {
+ id: row.agentId, sessionId: row.sessionId, engine: row.engine, name: core.agents.displayName(row),
+ status: 'active', launch: row.launch, terminal: { available: core.agents.terminalAvailable(row.agentId) },
+ project: { cwd: row.cwd, root: row.cwd, name: row.projectDir },
+ } }
+ }
+ const guarded = (run: () => Record<string, unknown> | Promise<Record<string, unknown>>) =>
+ Promise.resolve().then(run).catch((error: unknown) => {
+ if (error instanceof AgentCreationReceiptError) return { error: error.code }
+ throw error // The service host isolates unexpected failures from the core.
+ })
+ return {
+ shell_capabilities: (_, asker) => asker.owner ? { protocol: 1 } : { error: 'OWNER_REQUIRED' },
+ shell_context_reply: (payload, asker) => asker.owner ? { ok: shellContextReply(payload) } : { error: 'OWNER_REQUIRED' },
+ shell_open_status: (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ if (!validCreationId(payload.creationId)) return { error: 'INVALID_CREATION_ID' }
+ return guarded(() => ({ creationId: payload.creationId, ...describe(receipts.status(payload.creationId as string)) }))
+ },
+ shell_open: (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ const { argv, cwd, creationId } = payload
+ if (!validCreationId(creationId)) return { error: 'INVALID_CREATION_ID' }
+ // Do not turn a string into a program. All arguments, including punctuation and spaces, stay literal.
+ if (payload.command !== undefined || !Array.isArray(argv) || argv.length === 0 || argv.length > 256
+ || argv.some(arg => typeof arg !== 'string' || arg.includes('\0')) || !argv[0]
+ || Buffer.byteLength(JSON.stringify(argv)) > 32 * 1024) return { error: 'INVALID_ARGV' }
+ if (typeof cwd !== 'string' || !isAbsolute(cwd) || cwd.includes('\0') || Buffer.byteLength(cwd) > 4096) return { error: 'INVALID_CWD' }
+ const request = { argv: [...argv] as string[], cwd }
+ return guarded(async () => {
+ const status = await receipts.run(creationId, creationFingerprint(request), async () => {
+ // Filesystem providers can stall; a stalled path must not hold a launch indefinitely.
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const directory = await Promise.race([
+ stat(cwd).then(s => s.isDirectory(), () => false),
+ new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), 4000) }),
+ ]).finally(() => clearTimeout(timer))
+ if (!directory) return { state: 'failed', error: 'CWD_NOT_FOUND' }
+ const opened = await core.terminals.open(request)
+ return opened.ok ? { state: 'created', agentId: opened.agentId } : { state: 'failed', error: opened.error, detail: opened.detail }
+ })
+ return { creationId, ...describe(status) }
+ })
+ },
+ }
+}
diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.ts
index 52633b975..9f2c4da41 100644
--- a/cli/src/services/viewersProcess.ts
+++ b/cli/src/services/viewersProcess.ts
@@ -18,7 +18,7 @@
* no longer restarts every viewer: they stay up here, and the new core hears their URLs at once.
*/
import type { CoreApi } from '../core/api.js'
-import { emptyPorts, resolveAgent } from '../core/api.js'
+import { emptyPorts, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { startViewers } from './viewers.js'
@@ -50,6 +50,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re
const attached = (): RegisteredSession[] => [...sessions.values()]
return {
dataDir,
+ terminals: TERMINALS_OFF,
agents: {
all: attached,
live: attached,
diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.ts
index d8b03d231..e989e4e74 100644
--- a/cli/src/services/workspacesProcess.ts
+++ b/cli/src/services/workspacesProcess.ts
@@ -13,7 +13,7 @@
* alone: a hang or a crash in it costs workspaces, and the master starts them again.
*/
import type { CoreApi } from '../core/api.js'
-import { emptyPorts, resolveAgent } from '../core/api.js'
+import { emptyPorts, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { startWorkspaces } from './workspaces.js'
@@ -45,6 +45,7 @@ export function workspacesCoreApi(
): CoreApi {
return {
dataDir,
+ terminals: TERMINALS_OFF,
agents: {
all: () => {
const agents = view.inUse()
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index f4d273f23..a89ad34f1 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -4,13 +4,14 @@
* one (docs/design/2026-10-03-harnessd.md, the core boundary).
*/
import { vi } from 'vitest'
-import type { CoreApi } from '../core/api.js'
+import { TERMINALS_OFF, type CoreApi } from '../core/api.js'
type Overrides = { [K in keyof CoreApi]?: CoreApi[K] extends object ? Partial<CoreApi[K]> : CoreApi[K] }
export function fakeCore(over: Overrides = {}): CoreApi {
return {
dataDir: over.dataDir ?? '/data',
+ terminals: { open: vi.fn(TERMINALS_OFF.open), ...over.terminals },
agents: {
all: vi.fn(() => []),
live: vi.fn(() => []),