Skip to content

The agent that grows with you

fix(tui): serve Ink !cmd on the shared owner in the session's cwd; a failed {!cmd} refuses the submit

Tekniumcc89333889bc
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index e75e928332a..ae982cf63fc 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4426,6 +4426,11 @@ export interface OnboardingCatalogPlugin {
app_state: CatalogAppState
sentence: string
}
+export interface CanonicalShellExecParams {
+ session_id: string
+ command: string
+ profile?: string | null
+}
export interface PromptReceiptParams {
session_id: string
admission_id: string
@@ -6387,6 +6392,8 @@ export interface CanonicalRpcMethods {
'session.redirect': { params: CanonicalCorrectionParams; result: CanonicalCorrectionResult }
'session.resume': { params: CanonicalResumeParams; result: CanonicalSnapshot }
'session.steer': { params: CanonicalCorrectionParams; result: CanonicalCorrectionResult }
+ /** Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one safe command for a local session, in its frozen launch cwd (``gateway/session_shell.py``). */
+ 'shell.exec': { params: CanonicalShellExecParams; result: ShellExecResult }
/** Adopt a registered execution after verifying the live producer claim. */
'worker.adopt': { params: WorkerScopeParams; result: WorkerExecution }
/** Sequence-fenced typed persistence write from an adopted worker. */
@@ -6431,6 +6438,7 @@ export const CANONICAL_RPC_METHODS = [
'session.redirect',
'session.resume',
'session.steer',
+ 'shell.exec',
'worker.adopt',
'worker.persist',
'worker.register'
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index d2f9298090a..9b462aa3f10 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -9815,6 +9815,37 @@
"title": "CanonicalSessionRef",
"type": "object"
},
+ "CanonicalShellExecParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "command": {
+ "title": "Command",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "required": [
+ "session_id",
+ "command"
+ ],
+ "title": "CanonicalShellExecParams",
+ "type": "object"
+ },
"CanonicalSnapshot": {
"additionalProperties": false,
"properties": {
@@ -44372,6 +44403,24 @@
}
}
},
+ {
+ "name": "shell.exec",
+ "summary": "Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one safe command for a local session, in its frozen launch cwd (``gateway/session_shell.py``).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalShellExecParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ShellExecResult"
+ }
+ }
+ },
{
"name": "worker.adopt",
"summary": "Adopt a registered execution after verifying the live producer claim.",
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 90723f9add0..1c0e372727c 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -93,6 +93,8 @@ class AuthorityConnection:
handlers.update(config_handlers(self))
from gateway.session_ancillary import handlers as ancillary_handlers
handlers.update(ancillary_handlers(self))
+ from gateway.session_shell import handlers as shell_handlers
+ handlers.update(shell_handlers(self))
from gateway.session_images import attach_bytes
from functools import partial
handlers['image.attach_bytes'] = partial(attach_bytes, self)
diff --git a/gateway/session_shell.py b/gateway/session_shell.py
new file mode 100644
index 00000000000..99e324defe1
--- /dev/null
+++ b/gateway/session_shell.py
@@ -0,0 +1,75 @@
+"""Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one captured shell command for a local session.
+
+The legacy sidecar ran ``subprocess.run(cwd=os.getcwd())`` in its own process: on the owner that is
+the daemon's directory (the install root for an auto-started one), not the session's launch cwd or
+``-w`` worktree, and the sidecar's contract refused the ``session_id`` Ink sends (dokterdok N22).
+Here the command runs for exactly one local session, in its frozen launch cwd, behind the same
+hardline/dangerous-command refusal, with Hermes-managed secrets scrubbed from the child and the
+output redacted before it crosses the wire. Nothing enters the transcript or the admission FIFO.
+"""
+import asyncio
+from functools import partial
+import json
+import os
+import subprocess
+
+from hermes_state_runtime import RuntimeStoreError
+
+TIMEOUT_SECONDS = 30
+_LOCAL_BACKENDS = frozenset({'', 'local'})
+
+
+def handlers(connection):
+ return {'shell.exec': partial(shell_exec, connection)}
+
+
+async def shell_exec(connection, ref, params):
+ command = params.get('command')
+ if (set(params) - {'session_id', 'profile', 'command'} or not isinstance(ref.session_id, str)
+ or not ref.session_id or not isinstance(command, str) or not command.strip()):
+ raise RuntimeStoreError('invalid_params')
+ from gateway.session_busy_controls import authorize
+ authorize(connection, ref, params, 'session:control')
+ authority = connection.authority
+ authority._require_admission_open()
+ from gateway.session_local import authorize_local_source
+ from gateway.session_policy import policy_for_source
+ live = authority.sessions[ref.session_id]
+ # Local terminal sessions only: an API, messaging or A2A session has no composer, and running
+ # commands for it would be a remote-execution surface with no human at the keyboard.
+ if authorize_local_source(authority.runner, live.source) is not True:
+ raise RuntimeStoreError('permission_denied')
+ policy = policy_for_source(authority.runner, live.source)
+ if policy is None:
+ raise RuntimeStoreError('permission_denied')
+ # The frozen terminal policy chose a sandbox (docker, ssh, ...): the owner's host shell is not
+ # that backend, so refuse rather than run on the host behind the session's back.
+ if str(json.loads(policy.terminal_json).get('TERMINAL_ENV') or '').strip().lower() not in _LOCAL_BACKENDS:
+ raise RuntimeStoreError('unsupported_terminal_backend')
+ from tools.approval_detection import detect_dangerous_command, detect_hardline_command
+ if detect_hardline_command(command)[0] or detect_dangerous_command(command)[0]:
+ raise RuntimeStoreError('dangerous_command')
+ return await asyncio.to_thread(_run, command, policy.cwd)
+
+
+def _run(command, cwd):
+ from agent.redact import redact_sensitive_text
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ from tools.environments.local import build_subprocess_env
+ # shell=True keeps the user-facing !cmd grammar (pipes, redirects); the child never inherits
+ # credentials the long-lived owner holds, nor a launch profile's .env residue in a routed one.
+ if not os.path.isdir(cwd): # a deleted checkout / worktree: never fall back to the owner's cwd
+ raise RuntimeStoreError('cwd_unavailable')
+ env = build_subprocess_env(strip_launch_profile=True)
+ try:
+ result = subprocess.run(command, cwd=cwd, shell=True, env=env, capture_output=True,
+ text=True, encoding='utf-8', errors='replace', timeout=TIMEOUT_SECONDS,
+ stdin=subprocess.DEVNULL, creationflags=windows_hide_flags())
+ except subprocess.TimeoutExpired:
+ raise RuntimeStoreError('command_timeout') from None
+ except OSError:
+ raise RuntimeStoreError('command_failed') from None
+ # Redact before tailing so a credential crossing the slice boundary cannot survive as fragments.
+ stdout = redact_sensitive_text(result.stdout or '', force=True, redact_url_credentials=True)[-4000:]
+ stderr = redact_sensitive_text(result.stderr or '', force=True, redact_url_credentials=True)[-2000:]
+ return {'stdout': stdout, 'stderr': stderr, 'code': result.returncode}
diff --git a/locales/_keys.tui.json b/locales/_keys.tui.json
index cb356e67c60..445c4c805ec 100644
--- a/locales/_keys.tui.json
+++ b/locales/_keys.tui.json
@@ -703,6 +703,7 @@
"secure.vault.unlockTitle",
"session.approval.approved",
"session.approval.denied",
+ "session.common.interpolationFailed",
"session.common.invalidResponse",
"session.handoff.exitedWithCode",
"session.handoff.launchError",
diff --git a/tests/gateway/fixtures/shell_exec_peer.py b/tests/gateway/fixtures/shell_exec_peer.py
new file mode 100644
index 00000000000..1452b209a12
--- /dev/null
+++ b/tests/gateway/fixtures/shell_exec_peer.py
@@ -0,0 +1,57 @@
+"""Authenticated WS fixture: Ink ``!cmd`` on the shared owner; no inference."""
+import asyncio
+import json
+import os
+from pathlib import Path
+import sys
+import traceback
+
+
+async def probe():
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.run_api import start_gateway_api, stop_gateway_api
+ from hermes_cli import web_server
+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+ from websockets.asyncio.client import connect
+
+ home = Path(os.environ['HERMES_HOME'])
+ work = home / 'session-checkout'
+ work.mkdir()
+ (home / 'config.yaml').write_text('gateway:\n multiplex_profiles: false\nmodel:\n provider: custom\n default: no-inference\n base_url: http://127.0.0.1:1/v1\nauxiliary:\n title_generation:\n enabled: false\n')
+ # A credential the long-lived owner holds must never reach a user-typed child.
+ os.environ['OPENROUTER_API_KEY'] = 'sk-or-v1-' + 'f' * 48
+ runner = GatewayRunner()
+ await initialize_session_authority(runner, profile_id=str(home), instance_id='shell')
+ api = await start_gateway_api(runner)
+ web_server.app.state.auth_required = True
+ receipt = {'owner_cwd': os.getcwd(), 'session_cwd': str(work)}
+ try:
+ def socket(actor):
+ return connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket='
+ + mint_ticket(user_id=actor, provider='fixture'))
+ async with socket('owner') as ws:
+ sid = (await rpc(ws, 'session.create', request_id='shell', source='tui', cwd=str(work),
+ toolsets=[]))['result']['session_id']
+ ran = await rpc(ws, 'shell.exec', session_id=sid,
+ command='pwd; printf "key=%s" "${OPENROUTER_API_KEY:-}" >&2; exit 3')
+ receipt['ran'] = ran.get('result', ran.get('error'))
+ dangerous = await rpc(ws, 'shell.exec', session_id=sid, command='rm -rf /')
+ receipt['dangerous'] = dangerous.get('error', dangerous.get('result'))
+ receipt['sessionless'] = (await rpc(ws, 'shell.exec', command='pwd')).get('error', {}).get('code')
+ finally:
+ await stop_gateway_api(api)
+ (home / 'receipt.json').write_text(json.dumps(receipt))
+
+
+if __name__ == '__main__':
+ status = 0
+ try:
+ asyncio.run(probe())
+ except BaseException:
+ traceback.print_exc()
+ status = 1
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(status)
diff --git a/tests/gateway/test_session_shell.py b/tests/gateway/test_session_shell.py
new file mode 100644
index 00000000000..bd29d5e727f
--- /dev/null
+++ b/tests/gateway/test_session_shell.py
@@ -0,0 +1,35 @@
+"""Ink ``!cmd`` runs for its own local session, in that session's directory (dokterdok N22)."""
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import child_env
+
+
+def test_shell_exec_runs_in_the_session_cwd_behind_the_safety_gates(tmp_path):
+ """The owner serves ``shell.exec`` with the ``session_id`` Ink sends: the command runs in the
+ session's frozen launch cwd (not the daemon's), its exit code and output come back, the
+ owner's credentials are scrubbed from the child, and a dangerous or sessionless command is
+ refused."""
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir()
+ user.mkdir()
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),
+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')
+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/shell_exec_peer.py')],
+ cwd=root, env=env, capture_output=True, text=True, timeout=90)
+ assert result.returncode == 0, result.stdout + result.stderr
+ receipt = json.loads((home / 'receipt.json').read_text())
+ assert receipt['owner_cwd'] != receipt['session_cwd']
+ ran = receipt['ran']
+ assert isinstance(ran, dict) and ran.get('code') == 3, receipt
+ assert Path(ran['stdout'].strip()).resolve() == Path(receipt['session_cwd']).resolve(), receipt
+ assert ran['stderr'] == 'key=', receipt
+ assert receipt['dangerous'].get('message') == 'dangerous_command', receipt
+ assert receipt['sessionless'] == 4001, receipt
diff --git a/tui_gateway/contracts/tools_commands.py b/tui_gateway/contracts/tools_commands.py
index 6cdd731de1d..cc88e8962be 100644
--- a/tui_gateway/contracts/tools_commands.py
+++ b/tui_gateway/contracts/tools_commands.py
@@ -11,7 +11,7 @@ from __future__ import annotations
from pydantic import Field
from .base import JsonValue, Params, Result, WireEnum
-from .registry import method
+from .registry import canonical_method, method
class _Open(Result):
@@ -168,6 +168,17 @@ method("shell.exec", params=ShellExecParams, result=ShellExecResult,
doc="Run a safe (non-dangerous) shell command captured for ``!cmd`` / inline substitution.")
+class CanonicalShellExecParams(Params):
+ session_id: str
+ command: str
+ profile: str | None = None
+
+
+canonical_method("shell.exec", params=CanonicalShellExecParams, result=ShellExecResult,
+ doc="Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one safe command for a local session, in "
+ "its frozen launch cwd (``gateway/session_shell.py``).")
+
+
class CliExecParams(Params):
argv: list[str]
timeout: int | None = None
diff --git a/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx b/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx
index 97a1deed9aa..85402ac2e94 100644
--- a/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx
+++ b/ui-tui/src/__tests__/submissionDestinationRenderer.test.tsx
@@ -97,3 +97,62 @@ it('submits interpolated queued input only to its captured owner and removes it
rmSync(home, { recursive: true, force: true })
}
})
+
+it('refuses the whole submit when a {!cmd} cannot run instead of sending a placeholder to the model', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-submit-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'owner', info: { model: 'test', stored_session_id: 'stored-owner', skills: {}, tools: {} } as any })
+
+ // dokterdok N22: the interpolation's failure used to become the literal text `(error)`.
+ const request = vi.fn((method: string) =>
+ method === 'shell.exec' ? Promise.reject(Object.assign(new Error('dangerous_command'), { code: 4001 })) : Promise.resolve({})
+ )
+
+ let queue!: ReturnType<typeof useQueue>
+ let submission!: ReturnType<typeof useSubmission>
+ const sys = vi.fn()
+
+ function Harness() {
+ queue = useQueue()
+ submission = useSubmission({
+ appendMessage: vi.fn(),
+ composerActions: { ...queue, prependQueue: queue.prependQ, takeQueue: queue.takeQ } as any,
+ composerRefs: { queueRef: queue.queueRef, queueEditRef: queue.queueEditRef, tokensRef: { current: [] } } as any,
+ composerState: { input: '', inputBuf: [], completions: [] } as any,
+ gw: { request } as any,
+ setLastUserMsg: vi.fn(),
+ slashRef: { current: () => true },
+ submitRef: { current: () => {} },
+ sys
+ })
+
+ return <Text>{queue.queuedDisplay.join('|')}</Text>
+ }
+
+ const stdout = Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false })
+
+ const instance = renderSync(<Harness />, {
+ stdin: new PassThrough() as any,
+ stdout: stdout as any,
+ stderr: new PassThrough() as any,
+ patchConsole: false
+ })
+
+ try {
+ queue.enqueue('summarize {!rm -rf /}')
+ const item = queue.dequeue()!
+ submission.sendQueued(item)
+ await expect.poll(() => sys.mock.calls.length).toBe(1)
+ expect(request.mock.calls.map(([method]) => method)).not.toContain('prompt.submit')
+ expect(String(sys.mock.calls[0]![0])).toContain('dangerous_command')
+ // Retained for Alt+K / an edit, never silently dropped.
+ expect(item.failed).toBe(true)
+ expect(queue.queueRef.current).toContain(item)
+ } finally {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+})
diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts
index 598adbddd40..e87ebd4d110 100644
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@ -8,7 +8,7 @@ import type { GatewayClient } from '../gatewayClient.js'
import type { ShellExecResponse } from '../gatewayTypes.js'
import { queueItem, type QueueItem } from '../hooks/useQueue.js'
import { t } from '../i18n/runtime.js'
-import { asRpcResult } from '../lib/rpc.js'
+import { asRpcResult, rpcErrorMessage } from '../lib/rpc.js'
import { hasInterpolation, INTERPOLATION_RE } from '../protocol/interpolation.js'
import type { Msg } from '../types.js'
@@ -199,8 +199,11 @@ export function useSubmission(opts: UseSubmissionOptions) {
[appendMessage, gw, sys]
)
+ // A `{!cmd}` that could not run refuses the whole submit: the model never receives a
+ // placeholder such as `(error)` standing in for output the user expected (dokterdok N22). The
+ // staged row settles as not accepted, so the input stays retained for Alt+K / an edit.
const interpolate = useCallback(
- (text: string, then: (result: string) => void, destination = captureDestination()) => {
+ (text: string, then: (result: string) => void, destination = captureDestination(), item?: QueueItem) => {
patchUiState({ status: 'interpolating…' })
const matches = [...text.matchAll(new RegExp(INTERPOLATION_RE.source, 'g'))]
@@ -211,13 +214,26 @@ export function useSubmission(opts: UseSubmissionOptions) {
.then(raw => {
const r = asRpcResult<ShellExecResponse>(raw)
- return [r?.stdout, r?.stderr].filter(Boolean).join('\n').trim()
+ if (!r) {
+ throw new Error(t('session.common.invalidResponse', 'shell.exec'))
+ }
+
+ return [r.stdout, r.stderr].filter(Boolean).join('\n').trim()
})
- .catch(() => '(error)')
)
- ).then(results => then(spliceMatches(text, matches, results)))
+ ).then(
+ results => then(spliceMatches(text, matches, results)),
+ (error: unknown) => {
+ item?.settle?.(false)
+
+ if (isCurrentDestination(destination)) {
+ sys(t('session.common.interpolationFailed', rpcErrorMessage(error)))
+ patchUiState({ busy: false, status: 'ready' })
+ }
+ }
+ )
},
- [gw]
+ [gw, sys]
)
const sendQueued = useCallback(
@@ -240,7 +256,8 @@ export function useSubmission(opts: UseSubmissionOptions) {
return interpolate(
text,
result => send(result, true, undefined, value => value, { destination, queueItem: item }),
- destination
+ destination,
+ item
)
}
@@ -455,7 +472,8 @@ export function useSubmission(opts: UseSubmissionOptions) {
destination,
queueItem: item, attachments: submission.attachments
}),
- destination
+ destination,
+ item
)
}
diff --git a/ui-tui/src/i18n/en/session.ts b/ui-tui/src/i18n/en/session.ts
index 51a55688860..8e269d13a05 100644
--- a/ui-tui/src/i18n/en/session.ts
+++ b/ui-tui/src/i18n/en/session.ts
@@ -31,7 +31,9 @@ export const sessionEn = {
},
// Shared by the rpc wrapper (useMainApp) and the lifecycle paths; `error: ` prefix stays literal.
common: {
- invalidResponse: (method: string) => `invalid response: ${method}`
+ invalidResponse: (method: string) => `invalid response: ${method}`,
+ // useSubmission.interpolate: a `{!cmd}` that could not run refuses the whole submit.
+ interpolationFailed: (message: string) => `not sent: {!…} could not run (${message}) — input retained`
},
lifecycle: {
newLiveSessionStarted: 'new live session started',