session_shell.py 4.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one captured shell command for a local session.
  2. The legacy sidecar ran ``subprocess.run(cwd=os.getcwd())`` in its own process: on the owner that is
  3. the daemon's directory (the install root for an auto-started one), not the session's launch cwd or
  4. ``-w`` worktree, and the sidecar's contract refused the ``session_id`` Ink sends (dokterdok N22).
  5. Here the command runs for exactly one local session, in its frozen launch cwd, behind the same
  6. hardline/dangerous-command refusal, with Hermes-managed secrets scrubbed from the child and the
  7. output redacted before it crosses the wire. Nothing enters the transcript or the admission FIFO.
  8. """
  9. import asyncio
  10. from functools import partial
  11. import json
  12. import os
  13. import subprocess
  14. from hermes_state_runtime import RuntimeStoreError
  15. TIMEOUT_SECONDS = 30
  16. _LOCAL_BACKENDS = frozenset({'', 'local'})
  17. def handlers(connection):
  18. return {'shell.exec': partial(shell_exec, connection)}
  19. async def shell_exec(connection, ref, params):
  20. command = params.get('command')
  21. if (set(params) - {'session_id', 'profile', 'command'} or not isinstance(ref.session_id, str)
  22. or not ref.session_id or not isinstance(command, str) or not command.strip()):
  23. raise RuntimeStoreError('invalid_params')
  24. from gateway.session_busy_controls import authorize
  25. authorize(connection, ref, params, 'session:control')
  26. authority = connection.authority
  27. authority._require_admission_open()
  28. from gateway.session_local import authorize_local_source
  29. from gateway.session_policy import policy_for_source
  30. live = authority.sessions[ref.session_id]
  31. # Local terminal sessions only: an API, messaging or A2A session has no composer, and running
  32. # commands for it would be a remote-execution surface with no human at the keyboard.
  33. if authorize_local_source(authority.runner, live.source) is not True:
  34. raise RuntimeStoreError('permission_denied')
  35. policy = policy_for_source(authority.runner, live.source)
  36. if policy is None:
  37. raise RuntimeStoreError('permission_denied')
  38. # The frozen terminal policy chose a sandbox (docker, ssh, ...): the owner's host shell is not
  39. # that backend, so refuse rather than run on the host behind the session's back.
  40. # The refusal names the backend so the client can say where the command would have run.
  41. backend = str(json.loads(policy.terminal_json).get('TERMINAL_ENV') or '').strip().lower()
  42. if backend not in _LOCAL_BACKENDS:
  43. raise RuntimeStoreError('unsupported_terminal_backend', field='terminal.backend', detail=backend)
  44. from tools.approval_detection import detect_dangerous_command, detect_hardline_command
  45. if detect_hardline_command(command)[0] or detect_dangerous_command(command)[0]:
  46. raise RuntimeStoreError('dangerous_command')
  47. return await asyncio.to_thread(_run, command, policy.cwd)
  48. def _run(command, cwd):
  49. from agent.redact import redact_sensitive_text
  50. from hermes_cli._subprocess_compat import windows_hide_flags
  51. from tools.environments.local import build_subprocess_env
  52. # shell=True keeps the user-facing !cmd grammar (pipes, redirects); the child never inherits
  53. # credentials the long-lived owner holds, nor a launch profile's .env residue in a routed one.
  54. if not os.path.isdir(cwd): # a deleted checkout / worktree: never fall back to the owner's cwd
  55. raise RuntimeStoreError('cwd_unavailable')
  56. env = build_subprocess_env(strip_launch_profile=True)
  57. try:
  58. result = subprocess.run(command, cwd=cwd, shell=True, env=env, capture_output=True,
  59. text=True, encoding='utf-8', errors='replace', timeout=TIMEOUT_SECONDS,
  60. stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(), check=False)
  61. except subprocess.TimeoutExpired:
  62. raise RuntimeStoreError('command_timeout') from None
  63. except OSError:
  64. raise RuntimeStoreError('command_failed') from None
  65. # Redact before tailing so a credential crossing the slice boundary cannot survive as fragments.
  66. stdout = redact_sensitive_text(result.stdout or '', force=True, redact_url_credentials=True)[-4000:]
  67. stderr = redact_sensitive_text(result.stderr or '', force=True, redact_url_credentials=True)[-2000:]
  68. return {'stdout': stdout, 'stderr': stderr, 'code': result.returncode}