@yahyahammad/venastine 0.2.0 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/.env.example +9 -4
  2. package/CONFIG_ARCHITECTURE.md +2030 -0
  3. package/LICENSE +201 -201
  4. package/NOTICE +1 -1
  5. package/README.md +1034 -895
  6. package/agents/builtin/build.md +73 -0
  7. package/agents/builtin/compactor.md +75 -75
  8. package/agents/builtin/explore.md +77 -77
  9. package/agents/builtin/general.md +80 -0
  10. package/agents/builtin/pipeline-reviewer.md +100 -100
  11. package/agents/builtin/plan.md +106 -88
  12. package/agents/builtin/review.md +74 -74
  13. package/agents/builtin/test.md +65 -0
  14. package/agents/builtin/writer.md +67 -0
  15. package/agents/manager.py +68 -2
  16. package/agents/subagent_tool.py +472 -238
  17. package/agents/tui_commands.py +238 -151
  18. package/bin/venastine.mjs +150 -4
  19. package/bin/venastine.py +71 -0
  20. package/cli_commands.py +838 -0
  21. package/config.py +95 -1198
  22. package/config.yaml +1103 -0
  23. package/config_edit.py +1301 -0
  24. package/config_schema.py +971 -0
  25. package/config_update.py +749 -0
  26. package/core/agent_activity.py +256 -118
  27. package/core/ansi.py +452 -0
  28. package/core/approval.py +137 -115
  29. package/core/call_view.py +364 -0
  30. package/core/cancel.py +121 -0
  31. package/core/chatgpt_auth.py +747 -0
  32. package/core/claims_view.py +107 -0
  33. package/core/client.py +2715 -1559
  34. package/core/commands.py +460 -0
  35. package/core/compaction.py +1735 -971
  36. package/core/config_loader.py +1982 -1563
  37. package/core/connect.py +686 -0
  38. package/core/events.py +123 -61
  39. package/core/file_mentions.py +280 -0
  40. package/core/interaction.py +411 -328
  41. package/core/line_pattern.py +128 -0
  42. package/core/loop.py +2566 -1490
  43. package/core/memory.py +482 -370
  44. package/core/pipeline_models.py +190 -176
  45. package/core/provider_errors.py +234 -0
  46. package/core/reasoning/authorization.py +130 -130
  47. package/core/reasoning/base.py +219 -219
  48. package/core/reasoning/confidence_scoring.py +484 -468
  49. package/core/reasoning/events.py +149 -149
  50. package/core/reasoning/json_retry.py +19 -1
  51. package/core/reasoning/orchestrator.py +1561 -1382
  52. package/core/reasoning/output_writer.py +345 -286
  53. package/core/reasoning/payload_validation.py +524 -398
  54. package/core/reasoning/pipeline_storage.py +88 -22
  55. package/core/reasoning/review.py +659 -615
  56. package/core/reasoning/scholar.py +458 -434
  57. package/core/reasoning/source_corpus.py +433 -327
  58. package/core/reasoning/source_scoring.py +855 -855
  59. package/core/replay.py +315 -183
  60. package/core/session.py +36 -12
  61. package/core/session_view.py +259 -0
  62. package/core/session_wake.py +259 -0
  63. package/core/shell_sessions.py +1553 -0
  64. package/core/workspace_trust.py +1 -1
  65. package/credentials.py +148 -20
  66. package/database.py +333 -252
  67. package/{PRIVACY.md → docs/PRIVACY.md} +78 -66
  68. package/docs/SECURITY.md +108 -0
  69. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  70. package/env_secrets.py +50 -9
  71. package/json_store.py +343 -123
  72. package/logging_setup.py +295 -185
  73. package/main.py +3433 -1961
  74. package/mcp_client/client.py +733 -499
  75. package/mcp_client/config.py +126 -21
  76. package/mcp_client/registration.py +343 -182
  77. package/memories/manager.py +147 -132
  78. package/memories/tui_commands.py +319 -244
  79. package/package.json +303 -73
  80. package/project_init/config_files.py +282 -278
  81. package/project_init/generator.py +728 -564
  82. package/project_init/manifest.py +18 -6
  83. package/project_init/tui_commands.py +147 -144
  84. package/prompts/critic_pass.md +24 -24
  85. package/prompts/revalidate.md +25 -25
  86. package/prompts/revise.md +2 -0
  87. package/prompts/source_grounding.md +66 -66
  88. package/prompts/system_prompts.py +316 -262
  89. package/providers.json.example +4 -2
  90. package/pyproject.toml +149 -100
  91. package/requirements.txt +295 -72
  92. package/safety/policy_enforcement.py +1082 -746
  93. package/security/askpass.py +419 -0
  94. package/security/capability.py +207 -177
  95. package/security/confine.py +484 -0
  96. package/security/hosted.py +182 -0
  97. package/security/permissions.py +237 -190
  98. package/security/posture.py +124 -12
  99. package/security/protected_paths.py +501 -309
  100. package/security/sandbox.py +4108 -985
  101. package/security/secrets.py +855 -0
  102. package/skills/builtin/math/formal-specification.md +67 -67
  103. package/skills/builtin/math/numerical-methods.md +66 -66
  104. package/skills/builtin/research/experiment-design.md +62 -62
  105. package/skills/builtin/research/reproducibility.md +55 -55
  106. package/skills/builtin/research/source-evaluation.md +70 -70
  107. package/skills/builtin/research/statistical-inference.md +63 -63
  108. package/skills/builtin/research/technical-writing.md +59 -59
  109. package/skills/builtin/software/code-review.md +61 -61
  110. package/skills/builtin/software/debugging.md +61 -61
  111. package/skills/builtin/software/test-design.md +67 -67
  112. package/skills/tui_commands.py +110 -111
  113. package/storage.py +1338 -1005
  114. package/tools/base.py +161 -1
  115. package/tools/builtin/_math_common.py +667 -377
  116. package/tools/builtin/_net_common.py +225 -19
  117. package/tools/builtin/arxiv.py +497 -39
  118. package/tools/builtin/ask_user.py +231 -213
  119. package/tools/builtin/discrete_math.py +35 -4
  120. package/tools/builtin/fetch_url.py +371 -153
  121. package/tools/builtin/file_ops.py +720 -412
  122. package/tools/builtin/geometry.py +48 -12
  123. package/tools/builtin/get_time.py +2 -2
  124. package/tools/builtin/linear_algebra.py +66 -23
  125. package/tools/builtin/load_skill.py +76 -66
  126. package/tools/builtin/logic.py +171 -12
  127. package/tools/builtin/pin.py +227 -193
  128. package/tools/builtin/probability_stats.py +12 -16
  129. package/tools/builtin/project_docs.py +464 -405
  130. package/tools/builtin/remember.py +175 -158
  131. package/tools/builtin/shell.py +980 -461
  132. package/tools/builtin/shell_sessions.py +613 -0
  133. package/tools/builtin/symbolic_math.py +80 -10
  134. package/tools/builtin/todo.py +149 -147
  135. package/tools/builtin/web_search.py +191 -13
  136. package/tools/context.py +159 -136
  137. package/tools/isolation.py +107 -34
  138. package/tools/registry.py +1242 -925
  139. package/tui/app.py +8318 -4100
  140. package/tui/app.tcss +747 -556
  141. package/tui/commands.py +26 -170
  142. package/tui/diffs.py +34 -13
  143. package/tui/history.py +128 -128
  144. package/tui/hosted_driver.py +102 -0
  145. package/tui/markdown.py +1329 -1279
  146. package/tui/meters.py +364 -268
  147. package/tui/ravens.py +146 -146
  148. package/tui/screens.py +1255 -943
  149. package/tui/themes.py +599 -559
  150. package/tui/widgets.py +3813 -2332
  151. package/SECURITY.md +0 -88
  152. package/THIRD_PARTY_NOTICES.md +0 -100
@@ -1,461 +1,980 @@
1
- """
2
- tools/builtin/shell.py
3
-
4
- Shell execution tool (ROADMAP §7). Runs commands in the detected shell
5
- (bash on Linux/macOS, PowerShell on Windows) through the sandbox module
6
- (security/sandbox.py).
7
-
8
- SANDBOX MODEL (ROADMAP_v2 §46 moved one tier of this):
9
- Almost everything runs in Docker. The one exception is HOST_READ --
10
- a read-only command from config.INERT_COMMANDS whose argument
11
- resolves OUTSIDE the workspace -- which runs as a host subprocess
12
- because the file it names is one no container can see. It always
13
- requires approval, and the prompt names the resolved binary.
14
-
15
- INERT (every argument inside the workspace) used to take that same
16
- host path, on the argument that a read-only command needs no
17
- isolation. §46 (EP5) moved it into the container: it is the tier the
18
- gate AUTO-APPROVES, and on Windows `ls`/`cat`/`grep` have no native
19
- binary, so the host path was resolving them off the user's PATH and
20
- executing whichever POSIX toolchain some other product had installed.
21
- Inside the container they are the pinned image's coreutils. It falls
22
- back to the host when Docker is down, which changes nothing about the
23
- approval answer (see security/sandbox.containment_for) and is
24
- reported to the model as `ran_on: "host"`.
25
-
26
- Non-inert commands go through Docker (strong isolation) or the
27
- explicit subprocess fallback (weak isolation, requires
28
- ALLOW_INSECURE_SANDBOX_FALLBACK=True).
29
-
30
- EVERY result carries `ran_on` and `tier` (EP4). The human was always
31
- told where a command would run; the model never was, and it is the
32
- one that writes the user an answer about the output.
33
-
34
- APPROVAL MODEL (ROADMAP_v2 §28):
35
- config.SHELL_APPROVAL_MODE is the gate -- "always", "tiered" or
36
- "never" -- and ToolApprovals.shell is the RATCHET above it: True
37
- forces "always", and can never loosen (D14).
38
-
39
- Under "tiered", the command is classified ONCE
40
- (security/sandbox.classify_command) into a capability set, and the
41
- generic rule in security/capability.auto_approved decides. The same
42
- profile is then handed to run_sandboxed, so the thing that was
43
- approved is the thing that runs.
44
-
45
- What this replaced: a five-step ladder whose bottom four steps could
46
- only return False on the shipped config flags, making the whole check
47
- a pass-through for ToolApprovals.shell. Audit #157 is what that cost
48
- -- `cat ~/.aws/credentials` classified as "inert", ran on the HOST,
49
- and was never asked about.
50
-
51
- TOCTOU safety: run() probes Docker once and passes the result to
52
- run_sandboxed(). If Docker was available during approval but is now
53
- down, and the fallback would have required approval, run() returns
54
- an error instead of silently downgrading.
55
-
56
- FILE ACCESS:
57
- The sandbox restricts filesystem access to the workspace (Docker
58
- volume mount / fallback cwd). Output files generated by sandboxed
59
- commands appear in the workspace seamlessly.
60
- """
61
-
62
- from __future__ import annotations
63
-
64
- import logging
65
- import os
66
- import re
67
- import shutil
68
-
69
- from pydantic import BaseModel, Field
70
-
71
- import config
72
- from security import capability, posture
73
- from security.capability import UNAVAILABLE, UNCONTAINED, auto_approved
74
- from security.protected_paths import PROTECTED_SEGMENTS, protected_segment
75
- from security.sandbox import (
76
- HOST_READ,
77
- INERT,
78
- SandboxUnavailable,
79
- _is_inert,
80
- classify_command,
81
- containment_for,
82
- detect_shell,
83
- is_docker_available,
84
- run_sandboxed,
85
- )
86
-
87
- logger = logging.getLogger(__name__)
88
-
89
- # Validated at IMPORT, so a typo in a security setting is a startup
90
- # failure rather than a policy that quietly means something else. Same
91
- # posture as D24's assert_permissions_declared, applied to a value.
92
- #
93
- # It used to say "re-checked per call as well, because a test or a runtime
94
- # edit can change it after this line has run", and that sentence described
95
- # a test seam and an attack in the same breath: `config.SHELL_APPROVAL_MODE
96
- # = "never"` was one attribute assignment, from anywhere in the process,
97
- # and the gate followed it. §40 (UN1) binds the value once into
98
- # `security.posture`, and `_shell_approval_check` reads it from there.
99
- #
100
- # THIS line still reads `config` directly, and deliberately (UN2). It
101
- # validates the CONSTANT A HUMAN WROTE -- a typo check, not a decision --
102
- # and it runs at import, which is before `main()` has folded in the
103
- # command line. Reading the posture here would mark it bound and make
104
- # `apply_cli()` raise on every launch, because importing this module is
105
- # how the registry is built. The rule the guard enforces: **no module may
106
- # read the posture at import time**, pinned by
107
- # test_posture.py::test_no_module_reads_the_posture_at_import.
108
- capability.validate_mode(config.SHELL_APPROVAL_MODE,
109
- "config.SHELL_APPROVAL_MODE")
110
-
111
- # Compute the shell name once at import time to avoid blocking on
112
- # subprocess probes every time the schema is accessed. On Windows this
113
- # probes pwsh/powershell; a failure falls back to a static label.
114
- try:
115
- _SHELL_DISPLAY = detect_shell()
116
- except Exception:
117
- _SHELL_DISPLAY = "auto-detected"
118
-
119
-
120
- # ---------------------------------------------------------------------------
121
- # ---- Schema ---------------------------------------------------------------
122
- # ---------------------------------------------------------------------------
123
-
124
- class ShellParams(BaseModel):
125
- command: str = Field(
126
- ...,
127
- min_length=1,
128
- description=(
129
- "Shell command to execute. WHERE it runs depends on its "
130
- "arguments, and the result tells you which happened: read "
131
- "`ran_on` before drawing any conclusion about the machine "
132
- "you are on. A read-only command (ls, cat, grep, etc.) "
133
- "whose arguments all resolve INSIDE the workspace runs in "
134
- "the container. The same command with an argument OUTSIDE "
135
- "the workspace runs ON THE HOST, with the user's own file "
136
- "access and the host's own PATH -- it is not sandboxed, and "
137
- "what it reads is the real machine, not the container. "
138
- "Everything else runs in the container, with the workspace "
139
- f"mounted at /workspace. Interpreted by {_SHELL_DISPLAY}."
140
- ),
141
- )
142
- rationale: str = Field(
143
- default="",
144
- description=(
145
- "Why you are running this command, right now, in a sentence "
146
- "or two. Say what you are trying to learn or change and "
147
- "what it is for -- not what the command does, which the "
148
- "reader can see. This is shown to the user on the approval "
149
- "prompt and recorded with the call; it never affects whether "
150
- "the command is allowed or how it runs."
151
- ),
152
- )
153
-
154
-
155
- TOOL_SCHEMA = {
156
- "name": "shell",
157
- "description": (
158
- "Execute a shell command. Commands run inside a Docker "
159
- "container with the workspace mounted at /workspace -- EXCEPT "
160
- "a read-only command with an argument outside the workspace, "
161
- "which runs on the HOST with the user's own file access "
162
- "because the container cannot see those files. The result "
163
- "carries `ran_on` ('container' or 'host') and `tier`; a "
164
- "command that ran on the host tells you about the user's real "
165
- "machine, so do not describe its output as the sandbox's. "
166
- f"Shell: {_SHELL_DISPLAY}. Output is truncated at "
167
- f"{config.MAX_READ_CHARS} characters."
168
- ),
169
- "input_schema": ShellParams.model_json_schema(),
170
- }
171
-
172
- # §42 (RA4). ADVERTISED as required, TOLERATED when absent -- and the
173
- # asymmetry is deliberate rather than an oversight to tidy up.
174
- #
175
- # The schema is what the model reads, so `required` is where the ask
176
- # belongs: a rationale nobody asks for is supplied inconsistently, and
177
- # a drift signal with unknown coverage is not a signal. But
178
- # `ShellParams` keeps its default, because approval is obtained BEFORE
179
- # dispatch: a hard requirement would show the user a modal, take their
180
- # yes, and only then fail validation. That is the burn-a-turn class --
181
- # a human decision spent on an outcome already fixed -- and §32 A7
182
- # rejected it for a condition the tool could see, which this is.
183
- #
184
- # So an omission costs nothing and is VISIBLE: the prompt says
185
- # "(none given)", which is itself the observation. A silent gap would
186
- # not be.
187
- TOOL_SCHEMA["input_schema"]["required"] = ["command", "rationale"]
188
-
189
-
190
- # ---------------------------------------------------------------------------
191
- # ---- Approval check -------------------------------------------------------
192
- # ---------------------------------------------------------------------------
193
-
194
-
195
- def _profile_and_containment(command: str):
196
- """Classify *command* and work out what will contain it.
197
-
198
- One helper for both the gate and the prompt so they cannot describe
199
- the same call differently -- which is the failure #157 came from,
200
- with `_is_inert` consulted twice for two different questions.
201
- """
202
- profile = classify_command(command, config.WORKSPACE_DIR)
203
- # Docker is probed only when the answer depends on it. HOST_READ is
204
- # UNCONTAINED whatever Docker is doing -- it names a file outside
205
- # the workspace, which no container can show it -- so it still
206
- # returns without paying for a `docker info` that costs up to its
207
- # 10s timeout on an unresponsive daemon.
208
- #
209
- # INERT no longer qualifies (§46, EP5): it runs in the container
210
- # when there is one, so its containment now depends on the probe.
211
- # The cost is bounded rather than per-call -- `is_docker_available`
212
- # is lru_cached for the process, measured at 0.43s once.
213
- if profile.tier == HOST_READ:
214
- return profile, containment_for(profile, docker_available=False)
215
- return profile, containment_for(profile, is_docker_available())
216
-
217
-
218
- def _command_touches_protected(command: str) -> str | None:
219
- """The protected segment a command's tokens name, or None.
220
-
221
- Raw whitespace-split tokens, per Q1/Q5: for an INERT command
222
- ``command.split()`` IS the executed argument list, and EP5 runs that
223
- tier as argv with NO shell -- so there is no glob or variable
224
- expansion between this check and what executes, and a token check is
225
- sound exactly where it matters. A token counts when the segment
226
- appears as a component of its TEXT -- or of the tail after its first
227
- ``=``, the one split _escapes_workspace permits itself (hole 1:
228
- ``--path=.venastine/settings.json`` reads whole as one component
229
- glued to a flag) -- or of its realpath against WORKSPACE_DIR, which
230
- catches `..` travel, an absolute path from anywhere, and a
231
- case-spelling Windows realpath normalises.
232
-
233
- Totality is the approval gate's, and this runs inside it (Q3): a
234
- non-string command answers None, and a token whose realpath cannot
235
- RESOLVE answers None for that token -- the tier machinery fails
236
- closed on exactly those values, so an unresolvable reference is
237
- already on a path that asks. What this deliberately does NOT do is
238
- parse. A token like ``.ven*/settings.json`` carries no literal
239
- segment and reaches no answer here (G2 -- a classifier that learned
240
- shell syntax would be a parser whose bugs auto-approve). That is why
241
- the consumer is an always-ASK trigger and never a deny: what slips
242
- past a token check still lands in front of a human with the full
243
- command text.
244
- """
245
- if not isinstance(command, str):
246
- return None
247
- for token in command.split():
248
- candidates = [token]
249
- if "=" in token:
250
- candidates.append(token.split("=", 1)[1])
251
- for candidate in candidates:
252
- for part in re.split(r"[\\/]", candidate):
253
- if part in PROTECTED_SEGMENTS:
254
- return part
255
- try:
256
- resolved = os.path.realpath(
257
- os.path.join(config.WORKSPACE_DIR, candidate))
258
- except (OSError, ValueError):
259
- continue
260
- segment = protected_segment(resolved)
261
- if segment is not None:
262
- return segment
263
- return None
264
-
265
-
266
- def _shell_approval_check(tool_name: str, params: dict) -> bool:
267
- """Whether this shell call needs a human to say yes (ROADMAP_v2 §28).
268
-
269
- Reads top to bottom as the policy it is:
270
-
271
- 1. ToolApprovals.shell is the RATCHET. True forces "always",
272
- whatever the mode says, so a config or an agent override can
273
- still only tighten (D14).
274
- 2. The mode answers outright unless it is "tiered".
275
- 3. A command naming a protected path segment
276
- (security.protected_paths.PROTECTED_SEGMENTS) always asks --
277
- before the fallback opt-in and the capability rule can answer
278
- for it. The file tools DENY such a path outright; the shell
279
- only asks, because a command is free text and the token check
280
- refuses to parse it (G2), so what slips past the check still
281
- meets a human. Behind step 2 deliberately: mode "never" is a
282
- documented opt-out of ALL approval, and it already answers
283
- "auto-approve" for a host read of /etc/shadow.
284
- 4. AUTO_APPROVE_SANDBOX_FALLBACK is applied HERE, visibly, rather
285
- than passed into the generic rule to be honoured out of sight.
286
- It is the user's own opt-in to an isolation level the harness
287
- has already told them is weak -- and it sits BELOW the
288
- protected-segment check, so one opt-in cannot cover the
289
- directory the ro-mount exists to keep commands out of.
290
- 5. Otherwise the capability rule decides.
291
-
292
- The return is `not auto_approved(...)` -- this function answers "must
293
- someone be asked", the rule answers "is this covered". Two names for
294
- opposite polarities of one question, and inverting them by accident
295
- is a silent auto-approve, so the negation stays on one line where it
296
- can be read.
297
- """
298
- approvals = config.ToolApprovals()
299
- if getattr(approvals, tool_name, False):
300
- return True
301
-
302
- active = posture.current()
303
- mode = capability.validate_mode(active.shell_approval_mode,
304
- "config.SHELL_APPROVAL_MODE")
305
- if mode == capability.ALWAYS:
306
- return True
307
- if mode == capability.NEVER:
308
- return False
309
-
310
- command = params.get("command", "")
311
- profile, containment = _profile_and_containment(command)
312
-
313
- # No backend can run this, so there is nothing to approve. NOT the
314
- # same as auto_approved() answering False, which means ASK -- the two
315
- # polarities meet here and only here. run_sandboxed still raises
316
- # SandboxUnavailable with the instructions; asking first would spend
317
- # a human decision on an outcome that is already fixed, which is the
318
- # burn-a-turn class, and it is what the pre-§28 check did too.
319
- #
320
- # Read above the fallback branch, which it can never co-occur with --
321
- # UNCONTAINED and UNAVAILABLE are different answers -- so moving it
322
- # changes nothing there and lets the protected-segment check sit
323
- # before both.
324
- if containment == UNAVAILABLE:
325
- return False
326
-
327
- # Step 3: a protected segment always asks, whatever the sandbox says.
328
- segment = _command_touches_protected(command)
329
- if segment is not None:
330
- return True
331
-
332
- # The pre-§28 steps 4 and 5, preserved exactly. For a non-inert tier,
333
- # UNCONTAINED can only mean "Docker is down AND the insecure fallback
334
- # is enabled" -- that is what containment_for computed -- so this
335
- # reads the answer already in hand instead of re-deriving it from two
336
- # more config reads and a second Docker probe.
337
- if (profile.tier not in (INERT, HOST_READ)
338
- and containment == UNCONTAINED
339
- and active.auto_approve_fallback):
340
- return False
341
-
342
- return not auto_approved(profile, containment)
343
-
344
-
345
- def _shell_approval_notice(params: dict, _context=None) -> str:
346
- """What the person answering the prompt is being asked to allow.
347
-
348
- Wired through ToolSpec.approval_notice, which core/loop.py already
349
- renders above the params. The command is right there in the params,
350
- so what this adds is the part the command text does NOT show: where
351
- it will run. "cat /etc/shadow" does not look like a host read until
352
- someone tells you the inert path is a host subprocess.
353
- """
354
- command = params.get("command", "")
355
- profile, containment = _profile_and_containment(command)
356
- where = {
357
- "contained": "in a Docker container, workspace mounted at /workspace",
358
- "uncontained": "on the HOST, with your own file access",
359
- "unavailable": "nowhere -- no sandbox backend is available",
360
- }.get(containment, containment)
361
- notice = f"{profile.tier}: {profile.reason}. Runs {where}."
362
- binary = _resolved_binary(command) if containment == UNCONTAINED else ""
363
- if binary:
364
- notice += f" Binary resolves to {binary}."
365
- segment = _command_touches_protected(command)
366
- if segment is not None:
367
- # Why an INERT read is prompting at all: the tier alone would
368
- # look like a false positive to the person answering.
369
- notice += (f" It names {segment}/, a protected path that always "
370
- "requires approval.")
371
- return notice
372
-
373
-
374
- def _resolved_binary(command) -> str:
375
- """The absolute path the first word will actually execute as, on a
376
- run that is about to happen on the HOST (§46, EP8).
377
-
378
- Named on the prompt because "runs on the host" understates it on
379
- Windows. `ls`, `cat` and `grep` have no native Windows binary, so
380
- the inert path resolves them off the user's PATH -- and on the
381
- machine where this was found, `cat` was
382
- `...\\AppData\\Local\\hermes\\git\\usr\\bin\\cat.exe`, a POSIX
383
- toolchain shipped by unrelated software. `_is_inert` rejects a
384
- path-qualified binary (`./ls`) precisely so a planted one cannot be
385
- NAMED; PATH lookup reaches the same place from the other side, and
386
- the harness does not get to choose what is on it.
387
-
388
- Disclosure, not enforcement: the containment argument that lets
389
- this path run at all is unchanged, and HOST_READ always asks a
390
- human anyway. What changes is that the human is told which
391
- executable they are approving.
392
-
393
- Total, like everything else the gate calls: `command` arrives from
394
- `registry.approval_needed` as whatever the model emitted, and
395
- `shutil.which` on a non-string raises.
396
- """
397
- if not isinstance(command, str) or not command.strip():
398
- return ""
399
- try:
400
- return shutil.which(command.split()[0]) or ""
401
- except (OSError, ValueError):
402
- return ""
403
-
404
-
405
- # ---------------------------------------------------------------------------
406
- # ---- Tool handler ---------------------------------------------------------
407
- # ---------------------------------------------------------------------------
408
-
409
-
410
- def run(params: dict) -> dict:
411
- # `parsed.rationale` is deliberately never read below. It is shown
412
- # to a person and archived with the call; it has no part in what
413
- # runs or in whether it is allowed to (§42, RA2).
414
- parsed = ShellParams(**params)
415
-
416
- # Probe Docker once for this execution — the result is threaded
417
- # into run_sandboxed to eliminate the TOCTOU gap where Docker
418
- # status changes between the approval check and execution.
419
- docker_up = is_docker_available()
420
-
421
- # TOCTOU safety net: if the approval check auto-approved because
422
- # Docker was available at that time, but Docker is now down and
423
- # we'd use the fallback, check whether the fallback would have
424
- # required approval that was never given.
425
- if not docker_up and not _is_inert(parsed.command):
426
- approvals = config.ToolApprovals()
427
- base_needs_approval = getattr(approvals, "shell", False)
428
- # Read here rather than passed in from the approval check: §40
429
- # makes the two reads the SAME object for the life of the process,
430
- # so re-reading cannot reintroduce the TOCTOU gap this block
431
- # exists to close. Before §40 it could have.
432
- active = posture.current()
433
- if (
434
- not base_needs_approval
435
- and active.allow_insecure_fallback
436
- and not active.auto_approve_fallback
437
- ):
438
- return {
439
- "error": (
440
- "Docker became unavailable after the approval check. "
441
- "The insecure subprocess fallback requires explicit "
442
- "per-run approval (AUTO_APPROVE_SANDBOX_FALLBACK is "
443
- "False). Please retry — the approval prompt will "
444
- "appear this time."
445
- ),
446
- }
447
-
448
- try:
449
- return run_sandboxed(
450
- command=parsed.command,
451
- workspace_dir=config.WORKSPACE_DIR,
452
- docker_available=docker_up,
453
- # §28: the SAME classification the approval check made, so
454
- # routing cannot disagree with the decision to allow it.
455
- profile=classify_command(parsed.command, config.WORKSPACE_DIR),
456
- )
457
- except SandboxUnavailable as e:
458
- return {"error": str(e)}
459
- except Exception as e:
460
- logger.exception("shell tool failed")
461
- return {"error": f"Shell execution failed: {e}"}
1
+ """
2
+ tools/builtin/shell.py
3
+
4
+ Shell execution tool (ROADMAP §7). Runs commands in the detected shell
5
+ (bash on Linux/macOS, PowerShell on Windows) through the sandbox module
6
+ (security/sandbox.py).
7
+
8
+ SANDBOX MODEL (ROADMAP_v2 §46 moved one tier of this):
9
+ Almost everything runs in a container -- Docker's, or Podman's when
10
+ Docker cannot run one (ROADMAP_v3 §49, SS22; the approval notice names
11
+ which). The one exception is HOST_READ --
12
+ a read-only command from config.INERT_COMMANDS whose argument
13
+ resolves OUTSIDE the workspace -- which runs as a host subprocess
14
+ because the file it names is one no container can see. It always
15
+ requires approval, and the prompt names the resolved binary.
16
+
17
+ INERT (every argument inside the workspace) used to take that same
18
+ host path, on the argument that a read-only command needs no
19
+ isolation. §46 (EP5) moved it into the container: it is the tier the
20
+ gate AUTO-APPROVES, and on Windows `ls`/`cat`/`grep` have no native
21
+ binary, so the host path was resolving them off the user's PATH and
22
+ executing whichever POSIX toolchain some other product had installed.
23
+ Inside the container they are the pinned image's coreutils. It falls
24
+ back to the host when Docker is down, which changes nothing about the
25
+ approval answer (see security/sandbox.containment_for) and is
26
+ reported to the model as `ran_on: "host"`.
27
+
28
+ Non-inert commands go through the container (strong isolation) or the
29
+ explicit subprocess fallback (weak isolation, requires
30
+ ALLOW_INSECURE_SANDBOX_FALLBACK=True).
31
+
32
+ EVERY result carries `ran_on` and `tier` (EP4). The human was always
33
+ told where a command would run; the model never was, and it is the
34
+ one that writes the user an answer about the output.
35
+
36
+ APPROVAL MODEL (ROADMAP_v2 §28, amended by §48):
37
+ config.SHELL_APPROVAL_MODE is the gate -- "always", "tiered",
38
+ "contained" or "never" -- and it is the ONLY gate: there is no second
39
+ switch that can disagree with it (D14's one-way tightening for shell
40
+ lives in the agent's `approval_overrides`, which reach the same OR
41
+ below).
42
+
43
+ Under "tiered" and "contained", the command is classified ONCE
44
+ (security/sandbox.classify_command) into a capability set, and the
45
+ generic rule in security/capability.auto_approved decides. The same
46
+ profile is then handed to run_sandboxed, so the thing that was
47
+ approved is the thing that runs.
48
+
49
+ The two differ in one capability (§48, CE1/CE2). "tiered" asks about
50
+ anything that may run code, contained or not, so only INERT runs
51
+ unasked. "contained" is the rule "tiered" had before §48: a command
52
+ the container confines runs unasked unless it gets network. There is
53
+ no interpreter list behind either, and there must not be one -- see
54
+ classify_command's `runs_code`.
55
+
56
+ What this replaced: a five-step ladder whose bottom four steps could
57
+ only return False on the shipped config flags, making the whole check
58
+ a pass-through for ToolApprovals.shell. Audit #157 is what that cost
59
+ -- `cat ~/.aws/credentials` classified as "inert", ran on the HOST,
60
+ and was never asked about.
61
+
62
+ TOCTOU safety: run() probes Docker once and passes the result to
63
+ run_sandboxed(). If Docker was available during approval but is now
64
+ down, and the fallback would have required approval, run() returns
65
+ an error instead of silently downgrading.
66
+
67
+ FILE ACCESS:
68
+ The sandbox restricts filesystem access to the workspace (Docker
69
+ volume mount / fallback cwd). Output files generated by sandboxed
70
+ commands appear in the workspace seamlessly.
71
+ """
72
+
73
+ from __future__ import annotations
74
+
75
+ import logging
76
+ import os
77
+ import re
78
+ import shutil
79
+ from typing import Literal
80
+
81
+ from pydantic import BaseModel, Field, StrictBool
82
+
83
+ import config
84
+ from security import capability, posture
85
+ from security.capability import (
86
+ UNAVAILABLE,
87
+ UNCONTAINED,
88
+ CommandProfile,
89
+ auto_approved,
90
+ )
91
+ from security.protected_paths import (
92
+ PROTECTED_SEGMENTS_FOLDED,
93
+ protected_segment,
94
+ )
95
+ from security.sandbox import (
96
+ BACKEND_CONTAINER,
97
+ BACKEND_SSH,
98
+ BACKEND_WSL,
99
+ HOST_READ,
100
+ INERT,
101
+ SANDBOXED,
102
+ SANDBOXED_NET,
103
+ SandboxUnavailable,
104
+ _is_inert,
105
+ classify_command,
106
+ containment_for,
107
+ declared_backend,
108
+ declared_network,
109
+ declared_root,
110
+ detect_shell,
111
+ is_docker_available,
112
+ known_runtime,
113
+ run_sandboxed,
114
+ ssh_enabled,
115
+ ssh_target,
116
+ ssh_unavailable_reason,
117
+ sudo_refusal,
118
+ wsl_distro,
119
+ wsl_enabled,
120
+ wsl_unavailable_reason,
121
+ )
122
+
123
+ logger = logging.getLogger(__name__)
124
+
125
+ # Validated at IMPORT, so a typo in a security setting is a startup
126
+ # failure rather than a policy that quietly means something else. Same
127
+ # posture as D24's assert_permissions_declared, applied to a value.
128
+ #
129
+ # It used to say "re-checked per call as well, because a test or a runtime
130
+ # edit can change it after this line has run", and that sentence described
131
+ # a test seam and an attack in the same breath: `config.SHELL_APPROVAL_MODE
132
+ # = "never"` was one attribute assignment, from anywhere in the process,
133
+ # and the gate followed it. §40 (UN1) binds the value once into
134
+ # `security.posture`, and `_shell_approval_check` reads it from there.
135
+ #
136
+ # THIS line still reads `config` directly, and deliberately (UN2). It
137
+ # validates the CONSTANT A HUMAN WROTE -- a typo check, not a decision --
138
+ # and it runs at import, which is before `main()` has folded in the
139
+ # command line. Reading the posture here would mark it bound and make
140
+ # `apply_cli()` raise on every launch, because importing this module is
141
+ # how the registry is built. The rule the guard enforces: **no module may
142
+ # read the posture at import time**, pinned by
143
+ # test_posture.py::test_no_module_reads_the_posture_at_import.
144
+ capability.validate_mode(config.SHELL_APPROVAL_MODE,
145
+ "config.SHELL_APPROVAL_MODE")
146
+
147
+ # Compute the shell name once at import time to avoid blocking on
148
+ # subprocess probes every time the schema is accessed. On Windows this
149
+ # probes pwsh/powershell; a failure falls back to a static label.
150
+ try:
151
+ _SHELL_DISPLAY = detect_shell()
152
+ except Exception:
153
+ _SHELL_DISPLAY = "auto-detected"
154
+
155
+
156
+ # ---------------------------------------------------------------------------
157
+ # ---- Schema ---------------------------------------------------------------
158
+ # ---------------------------------------------------------------------------
159
+
160
+ class ShellParams(BaseModel):
161
+ command: str = Field(
162
+ ...,
163
+ min_length=1,
164
+ description=(
165
+ "Shell command to execute. WHERE it runs depends on its "
166
+ "arguments, and the result tells you which happened: read "
167
+ "`ran_on` before drawing any conclusion about the machine "
168
+ "you are on. A read-only command (ls, cat, grep, etc.) "
169
+ "whose arguments all resolve INSIDE the workspace runs in "
170
+ "the container. The same command with an argument OUTSIDE "
171
+ "the workspace runs ON THE HOST, with the user's own file "
172
+ "access and the host's own PATH -- it is not sandboxed, and "
173
+ "what it reads is the real machine, not the container. "
174
+ "Everything else runs in the container, with the workspace "
175
+ f"mounted at /workspace. Interpreted by {_SHELL_DISPLAY}."
176
+ ),
177
+ )
178
+ rationale: str = Field(
179
+ default="",
180
+ description=(
181
+ "Why you are running this command, right now, in a sentence "
182
+ "or two. Say what you are trying to learn or change and "
183
+ "what it is for -- not what the command does, which the "
184
+ "reader can see. This is shown to the user on the approval "
185
+ "prompt and recorded with the call; it never affects whether "
186
+ "the command is allowed or how it runs."
187
+ ),
188
+ )
189
+ requires_network: StrictBool = Field(
190
+ default=False,
191
+ description=(
192
+ "Whether this command needs to reach the network. Say true "
193
+ "for anything that downloads, installs, clones, publishes or "
194
+ "calls an API. WITHOUT IT THE COMMAND RUNS WITH NETWORKING "
195
+ "OFF and the connection simply fails -- the harness reads "
196
+ "your command as text and cannot tell that an inline script "
197
+ "or an interpreter you invoke wants egress, so it assumes "
198
+ "not. Saying true does not bypass approval; it tells the "
199
+ "user what they are being asked to allow."
200
+ ),
201
+ )
202
+ needs_root: StrictBool = Field(
203
+ default=False,
204
+ description=(
205
+ "Whether this command must run as root. The harness prefixes "
206
+ "sudo for you and supplies the password it holds for that "
207
+ "machine -- DO NOT write `sudo` in the command yourself, and "
208
+ "never put a password in it. The WHOLE command line runs as "
209
+ "root, redirects and pipes included. Only 'wsl' and 'ssh' can "
210
+ "do this: in the container you ALREADY are root, so drop the "
211
+ "flag there. A human is asked every single time, whatever the "
212
+ "approval mode, and the call is refused outright if no "
213
+ "password is stored for that machine -- the refusal says which "
214
+ "one to store. Leave it false unless the command genuinely "
215
+ "cannot work otherwise."
216
+ ),
217
+ )
218
+ backend: Literal["container", "wsl", "ssh"] = Field(
219
+ default="container",
220
+ description=(
221
+ "Where to run it. 'container' is the sandbox: a pinned Linux "
222
+ "image with only the workspace visible, no network unless you "
223
+ "ask, and memory, CPU and process limits. 'wsl' is the USER'S "
224
+ "OWN Windows machine with a Linux userland on it -- their real "
225
+ "home directory, their installed tools, the network always on, "
226
+ "no resource limits, and no isolation from this harness's own "
227
+ "files. Ask for it only when the work genuinely needs the "
228
+ "user's machine or a Linux toolchain the image does not have, "
229
+ "say so in the rationale, and expect to be asked: only a "
230
+ "read-only command whose arguments are all inside the "
231
+ "workspace runs there without a prompt. It may be turned off, "
232
+ "in which case the call is refused and says so. Use paths "
233
+ "RELATIVE to the workspace -- an absolute POSIX path is read "
234
+ "as leaving the workspace and always asks. "
235
+ "'ssh' is a DIFFERENT MACHINE -- the remote host the user "
236
+ "configured. Nothing runs there without asking, not even a "
237
+ "read-only command, because this harness cannot resolve a "
238
+ "path on a filesystem it cannot see. Its network is always "
239
+ "on and `requires_network` means nothing there. Note the "
240
+ "trap: `write` saves files LOCALLY, so a file you just wrote "
241
+ "does not exist on the remote -- send it through the command "
242
+ "itself, or do the work in the container."
243
+ ),
244
+ )
245
+
246
+
247
+ TOOL_SCHEMA = {
248
+ "name": "shell",
249
+ "description": (
250
+ "Execute a shell command. Commands run inside a container "
251
+ "(Docker, or Podman where Docker cannot run one) with the "
252
+ "workspace mounted at /workspace -- EXCEPT "
253
+ "a read-only command with an argument outside the workspace, "
254
+ "which runs on the HOST with the user's own file access "
255
+ "because the container cannot see those files. The result "
256
+ "carries `ran_on` ('container' or 'host') and `tier`; a "
257
+ "command that ran on the host tells you about the user's real "
258
+ "machine, so do not describe its output as the sandbox's. "
259
+ f"Shell: {_SHELL_DISPLAY}. Output is truncated at "
260
+ f"{config.MAX_READ_CHARS} characters."
261
+ ),
262
+ "input_schema": ShellParams.model_json_schema(),
263
+ }
264
+
265
+ # §42 (RA4). ADVERTISED as required, TOLERATED when absent -- and the
266
+ # asymmetry is deliberate rather than an oversight to tidy up.
267
+ #
268
+ # The schema is what the model reads, so `required` is where the ask
269
+ # belongs: a rationale nobody asks for is supplied inconsistently, and
270
+ # a drift signal with unknown coverage is not a signal. But
271
+ # `ShellParams` keeps its default, because approval is obtained BEFORE
272
+ # dispatch: a hard requirement would show the user a modal, take their
273
+ # yes, and only then fail validation. That is the burn-a-turn class --
274
+ # a human decision spent on an outcome already fixed -- and §32 A7
275
+ # rejected it for a condition the tool could see, which this is.
276
+ #
277
+ # So an omission costs nothing and is VISIBLE: the prompt says
278
+ # "(none given)", which is itself the observation. A silent gap would
279
+ # not be.
280
+ #
281
+ # `requires_network` (ROADMAP_v3 §50, NW1) is listed on the same terms
282
+ # and for the same reason: it is a thing the agent STATES, and a flag
283
+ # it is never asked for is one it will not set -- but it defaults to
284
+ # False, so a call that omits it runs with no network rather than
285
+ # failing validation after a human has already said yes.
286
+ #
287
+ # `backend` (ROADMAP_v3 §49, SS35) is NOT on the list, and the difference
288
+ # from `requires_network` is the direction its default fails in. An
289
+ # unstated `requires_network` runs a command that needed egress without
290
+ # it, so the command fails for a reason the model cannot see and the
291
+ # field has to be asked for. An unstated `backend` runs in the container,
292
+ # which is both the safe answer and the right one for almost every call --
293
+ # requiring it would make every command state the obvious in order to
294
+ # requiring it would make every command state the obvious in order to
295
+ # surface a field that matters for a handful.
296
+ #
297
+ # `needs_root` (slice 5b, SS67) is off the list for `backend`'s reason and
298
+ # not for `requires_network`'s. Unstated, the command runs unprivileged and
299
+ # fails with a permission error the model can READ and act on -- the
300
+ # visible direction. And unlike either of the others, forgetting it is not
301
+ # how root is reached by accident: a command that names `sudo` itself still
302
+ # meets a human, because the always-ask step reads the command text too.
303
+ TOOL_SCHEMA["input_schema"]["required"] = [
304
+ "command", "rationale", "requires_network"]
305
+
306
+
307
+ # ---------------------------------------------------------------------------
308
+ # ---- Approval check -------------------------------------------------------
309
+ # ---------------------------------------------------------------------------
310
+
311
+
312
+ def _profile_and_containment(command: str, requires_network: bool = False,
313
+ backend: str = BACKEND_CONTAINER):
314
+ """Classify *command* and work out what will contain it.
315
+
316
+ One helper for both the gate and the prompt so they cannot describe
317
+ the same call differently -- which is the failure #157 came from,
318
+ with `_is_inert` consulted twice for two different questions.
319
+
320
+ *requires_network* is the agent's declaration (§50), already coerced
321
+ by `declared_network`. It reaches the classifier rather than being
322
+ applied afterwards, so the gate and the prompt read the one network
323
+ fact instead of each OR-ing the flag in for itself.
324
+
325
+ *backend* is the agent's other declaration (§49, SS35), coerced by
326
+ `declared_backend`. It does NOT reach the classifier: what a command
327
+ is ABLE to do is a fact about the command, and the same text has the
328
+ same capabilities wherever it runs. It reaches `containment_for`,
329
+ which is the half of the question that is about the machine -- and
330
+ the answer there is UNCONTAINED for every tier (SS1).
331
+ """
332
+ profile = classify_command(command, config.WORKSPACE_DIR,
333
+ requires_network=requires_network)
334
+ # SS35. Asked first, because on this backend the runtime's answer is
335
+ # not part of the question: WSL is uncontained whether or not a
336
+ # container could have run the command, and probing Docker to decide
337
+ # that would be paying for an answer nobody reads.
338
+ if backend == BACKEND_WSL:
339
+ return profile, containment_for(profile, False, backend)
340
+ # SS46/SS48, for SS35's reason and one more: a remote host's
341
+ # containment does not depend on what this machine's Docker is doing
342
+ # either, and the classified tier is kept only so the NOTICE can still
343
+ # describe the command. Nothing downstream may act on it -- see the
344
+ # SSH step in `_shell_approval_check`.
345
+ if backend == BACKEND_SSH:
346
+ return profile, containment_for(profile, False, backend)
347
+ # Docker is probed only when the answer depends on it. HOST_READ is
348
+ # UNCONTAINED whatever Docker is doing -- it names a file outside
349
+ # the workspace, which no container can show it -- so it still
350
+ # returns without paying for a `docker info` that costs up to its
351
+ # 10s timeout on an unresponsive daemon.
352
+ #
353
+ # INERT no longer qualifies (§46, EP5): it runs in the container
354
+ # when there is one, so its containment now depends on the probe.
355
+ # The cost is bounded rather than per-call -- `is_docker_available`
356
+ # is lru_cached for the process, measured at 0.43s once.
357
+ if profile.tier == HOST_READ:
358
+ return profile, containment_for(profile, docker_available=False)
359
+ return profile, containment_for(profile, is_docker_available())
360
+
361
+
362
+ def _command_touches_protected(command: str) -> str | None:
363
+ """The protected segment a command's tokens name, or None.
364
+
365
+ Raw whitespace-split tokens, per Q1/Q5: for an INERT command
366
+ ``command.split()`` IS the executed argument list, and EP5 runs that
367
+ tier as argv with NO shell -- so there is no glob or variable
368
+ expansion between this check and what executes, and a token check is
369
+ sound exactly where it matters. A token counts when the segment
370
+ appears as a component of its TEXT -- or of the tail after its first
371
+ ``=``, the one split _escapes_workspace permits itself (hole 1:
372
+ ``--path=.venastine/settings.json`` reads whole as one component
373
+ glued to a flag) -- or of its realpath against WORKSPACE_DIR, which
374
+ catches `..` travel, an absolute path from anywhere, and a
375
+ case-spelling Windows realpath normalises.
376
+
377
+ Totality is the approval gate's, and this runs inside it (Q3): a
378
+ non-string command answers None, and a token whose realpath cannot
379
+ RESOLVE answers None for that token -- the tier machinery fails
380
+ closed on exactly those values, so an unresolvable reference is
381
+ already on a path that asks. What this deliberately does NOT do is
382
+ parse. A token like ``.ven*/settings.json`` carries no literal
383
+ segment and reaches no answer here (G2 -- a classifier that learned
384
+ shell syntax would be a parser whose bugs auto-approve). That is why
385
+ the consumer is an always-ASK trigger and never a deny: under
386
+ `tiered`, what slips past a token check still lands in front of a
387
+ human with the full command text, because a spelling that could
388
+ expand into the segment is not INERT and so asks anyway.
389
+
390
+ That last clause was FALSE until §48 (CE1). A contained command was
391
+ auto-approved, so `cat .ven*/settings.json; true` and a `python -c`
392
+ that opens the file read it unasked, while this docstring said they
393
+ met a human. Under `contained` and `never` they still do not: the
394
+ ro mount stops a write there, and the read is documented risk.
395
+ """
396
+ if not isinstance(command, str):
397
+ return None
398
+ for token in command.split():
399
+ candidates = [token]
400
+ if "=" in token:
401
+ candidates.append(token.split("=", 1)[1])
402
+ for candidate in candidates:
403
+ for part in re.split(r"[\\/]", candidate):
404
+ # Folded, like the resolved branch below it (batch 146).
405
+ # This is the branch for a token realpath cannot help with,
406
+ # so an exact-case compare here was the half of the fold
407
+ # that `protected_segment` could not reach.
408
+ if part.casefold() in PROTECTED_SEGMENTS_FOLDED:
409
+ return part
410
+ try:
411
+ resolved = os.path.realpath(
412
+ os.path.join(config.WORKSPACE_DIR, candidate))
413
+ except (OSError, ValueError):
414
+ continue
415
+ segment = protected_segment(resolved)
416
+ if segment is not None:
417
+ return segment
418
+ return None
419
+
420
+
421
+ # The binaries that make a command somebody else's. `sudo` is the one
422
+ # slice 5b supplies a password for; the other three are here because they
423
+ # answer the same question -- "does this line try to become another user"
424
+ # -- and a step that knew only about `sudo` would auto-approve `doas` on
425
+ # the one backend where the measurement showed nothing asks.
426
+ _ROOT_BINARIES = frozenset({"sudo", "doas", "pkexec", "su"})
427
+
428
+
429
+ def _command_names_root(command) -> bool:
430
+ """Whether the command TEXT names an escalation binary (SS67).
431
+
432
+ RAW `.split()` tokens and a basename compare -- a token check, never a
433
+ parser (G2), exactly like `_command_touches_protected` beside it and
434
+ for the same trade. `echo sudo` asks, and that costs one prompt; what
435
+ it buys is that `sudo apt-get install` cannot be auto-approved on WSL
436
+ because the call left `needs_root` unset. That was MEASURED to be the
437
+ live behaviour before this slice: under AUTO_APPROVE_SANDBOX_FALLBACK
438
+ the fallback opt-in answered for the whole WSL backend.
439
+
440
+ What it deliberately does NOT do is decide anything about HOW the
441
+ command runs. It only ever ADDS a prompt -- the harness supplies a
442
+ password for `needs_root` and for nothing else -- so a spelling that
443
+ slips past this check reaches a `sudo` with no password and fails,
444
+ rather than reaching one with a password nobody approved.
445
+
446
+ Total, like everything else the gate calls: `params["command"]` is
447
+ whatever the model emitted.
448
+ """
449
+ if not isinstance(command, str):
450
+ return False
451
+ for token in command.split():
452
+ if re.split(r"[\\/]", token)[-1] in _ROOT_BINARIES:
453
+ return True
454
+ return False
455
+
456
+
457
+ def _shell_approval_check(tool_name: str, params: dict) -> bool:
458
+ """Whether this shell call needs a human to say yes (ROADMAP_v2 §28).
459
+
460
+ Reads top to bottom as the policy it is:
461
+
462
+ 1. The mode answers outright unless it is "tiered".
463
+ 2. A command naming a protected path segment
464
+ (security.protected_paths.PROTECTED_SEGMENTS) always asks --
465
+ before the fallback opt-in and the capability rule can answer
466
+ for it. The file tools DENY such a path outright; the shell
467
+ only asks, because a command is free text and the token check
468
+ refuses to parse it (G2), so what slips past the check still
469
+ meets a human. Behind step 1 deliberately: mode "never" is a
470
+ documented opt-out of ALL approval, and it already answers
471
+ "auto-approve" for a host read of /etc/shadow.
472
+ 2b. A call that will be REFUSED answers "no" rather than
473
+ "ask" (ROADMAP_v3 §49, SS37/SS40) -- the WSL backend turned
474
+ off, or a WSL command naming a protected segment. It reads
475
+ beside the UNAVAILABLE branch above and means the same
476
+ thing: there is nothing to approve, and asking would spend
477
+ a human decision on an outcome already fixed. `run` and the
478
+ session start handler refuse the same call, through the one
479
+ `uncontained_refusal`.
480
+ 2c. An SSH call ALWAYS asks (ROADMAP_v3 §49, SS48), read
481
+ above every opt-in below so that neither of them can answer
482
+ for a machine this process cannot inspect.
483
+ 2d. A ROOT call ALWAYS asks (slice 5b, SS65/SS67), in the same
484
+ position and for a measured version of the same reason: the
485
+ fallback opt-in already answers for the ENTIRE WSL backend,
486
+ so a root step below it would be dead code on the one
487
+ backend where root is most reachable. It fires on the
488
+ DECLARATION or on the command text naming an escalation
489
+ binary, because a model that types `sudo` itself never sets
490
+ the flag.
491
+ 3. AUTO_APPROVE_SANDBOX_FALLBACK is applied HERE, visibly, rather
492
+ than passed into the generic rule to be honoured out of sight.
493
+ It is the user's own opt-in to an isolation level the harness
494
+ has already told them is weak -- and it sits BELOW the
495
+ protected-segment check, so one opt-in cannot cover the
496
+ directory the ro-mount exists to keep commands out of. Honoured
497
+ under `tiered` and `contained` alike (§48, CE5): it is written on
498
+ purpose and already flagged. Under `always` it is never reached,
499
+ because step 1 returned (CE6).
500
+ 4. The `contained` mode (§48, CE2) is the second visible opt-in, and
501
+ applied here for the same reason: a command the container
502
+ confines and that gets no network runs unasked. Below the
503
+ protected-segment check, so a literal `.venastine` token still
504
+ asks in that mode, and read off capabilities rather than the tier
505
+ label (G1), with `measured` first (G5).
506
+ 5. Otherwise the capability rule decides -- which, since §48 (CE1),
507
+ asks about anything that may run code, contained or not.
508
+
509
+ The return is `not auto_approved(...)` -- this function answers "must
510
+ someone be asked", the rule answers "is this covered". Two names for
511
+ opposite polarities of one question, and inverting them by accident
512
+ is a silent auto-approve, so the negation stays on one line where it
513
+ can be read.
514
+ """
515
+ active = posture.current()
516
+ mode = capability.validate_mode(active.shell_approval_mode,
517
+ "config.SHELL_APPROVAL_MODE")
518
+ if mode == capability.ALWAYS:
519
+ return True
520
+ if mode == capability.NEVER:
521
+ return False
522
+
523
+ # TOTAL from here down (batch 146). Below the mode branches on
524
+ # purpose: `never` is a documented opt-out of ALL approval and answers
525
+ # without reading the params at all, so a guard above it would have
526
+ # changed what that opt-out means. From here the function reads six
527
+ # fields, and `params` is whatever the model emitted -- which for this
528
+ # shape means "not an object". ASK, like every other answer this
529
+ # function cannot settle.
530
+ if not isinstance(params, dict):
531
+ return True
532
+ command = params.get("command", "")
533
+ backend = declared_backend(params)
534
+ profile, containment = _profile_and_containment(
535
+ command, declared_network(params), backend)
536
+
537
+ # No backend can run this, so there is nothing to approve. NOT the
538
+ # same as auto_approved() answering False, which means ASK -- the two
539
+ # polarities meet here and only here. run_sandboxed still raises
540
+ # SandboxUnavailable with the instructions; asking first would spend
541
+ # a human decision on an outcome that is already fixed, which is the
542
+ # burn-a-turn class, and it is what the pre-§28 check did too.
543
+ #
544
+ # Read above the fallback branch, which it can never co-occur with --
545
+ # UNCONTAINED and UNAVAILABLE are different answers -- so moving it
546
+ # changes nothing there and lets the protected-segment check sit
547
+ # before both.
548
+ if containment == UNAVAILABLE:
549
+ return False
550
+
551
+ # SS40, and read beside the UNAVAILABLE branch above rather than with
552
+ # the protected-segment step below, because it is the same KIND of
553
+ # answer: this call is refused before it runs, so there is nothing to
554
+ # approve, and asking would spend a human decision on an outcome that
555
+ # is already fixed. Below the mode switch for the same reason
556
+ # UNAVAILABLE is -- `always` asks about everything, including calls
557
+ # that will not run, and that wart is one the gate already has.
558
+ # `declared_root` and NOT `_command_names_root`, and the asymmetry is
559
+ # the decision: the refusal is about a password THIS HARNESS would
560
+ # have to supply, which it only ever does for a declared call. A
561
+ # command that merely names `sudo` supplies its own or fails, and
562
+ # refusing it for want of a stored secret would break a passwordless
563
+ # setup that works today.
564
+ if uncontained_refusal(command, backend,
565
+ declared_root(params)) is not None:
566
+ return False
567
+
568
+ # SS48. NOTHING on the SSH route is auto-approved, and this is the one
569
+ # place that is decided -- an explicit step rather than a synthesized
570
+ # profile that happens to fail `auto_approved`, because the opt-ins
571
+ # below (the fallback's and `contained`'s) each answer BEFORE that
572
+ # rule is reached, and a profile tuned to lose the last test would
573
+ # still have to be tuned to lose those two. One line that cannot be
574
+ # got wrong beats three that agree today.
575
+ #
576
+ # Two independent reasons, either sufficient. `_within` resolves
577
+ # against the LOCAL filesystem, so on a remote it answers a true
578
+ # question about the wrong machine -- and SS45, one slice old, is what
579
+ # a path check that cannot resolve costs: it does not fail open
580
+ # loudly, it approves confidently. And SS51: ssh has no `execve` path,
581
+ # so the "argv with no shell" property that EP5 makes the INERT tier
582
+ # out of does not exist on this route at all.
583
+ #
584
+ # Below the mode switch, so `never` still means never (SS1) and
585
+ # `always` still asks -- this widens neither.
586
+ if backend == BACKEND_SSH:
587
+ return True
588
+
589
+ # SS65/SS67. Above both opt-ins below, and the OR is the whole point:
590
+ # `declared_root` alone would be a step the model can step around by
591
+ # writing `sudo` and leaving the flag off, which is exactly what the
592
+ # measurement found already running unasked.
593
+ if declared_root(params) or _command_names_root(command):
594
+ return True
595
+
596
+ # Step 2: a protected segment always asks, whatever the sandbox says.
597
+ segment = _command_touches_protected(command)
598
+ if segment is not None:
599
+ return True
600
+
601
+ # The pre-§28 fallback steps, preserved exactly. For a non-inert tier,
602
+ # UNCONTAINED can only mean "Docker is down AND the insecure fallback
603
+ # is enabled" -- that is what containment_for computed -- so this
604
+ # reads the answer already in hand instead of re-deriving it from two
605
+ # more config reads and a second Docker probe.
606
+ if (profile.tier not in (INERT, HOST_READ)
607
+ and containment == UNCONTAINED
608
+ and active.auto_approve_fallback):
609
+ return False
610
+
611
+ # Step 4, §48 (CE2): the rule `tiered` had before §48, under the name
612
+ # that says what it trusts. `measured` first, for G5's reason -- the
613
+ # container must not argue an uncharacterised call through.
614
+ if (mode == capability.CONTAINED_MODE
615
+ and containment == capability.CONTAINED
616
+ and profile.measured
617
+ and not profile.network):
618
+ return False
619
+
620
+ return not auto_approved(profile, containment)
621
+
622
+
623
+ def _shell_approval_notice(params: dict, _context=None) -> str:
624
+ """What the person answering the prompt is being asked to allow.
625
+
626
+ Wired through ToolSpec.approval_notice, which core/loop.py already
627
+ renders above the params. The command is right there in the params,
628
+ so what this adds is the part the command text does NOT show: where
629
+ it will run. "cat /etc/shadow" does not look like a host read until
630
+ someone tells you the inert path is a host subprocess.
631
+ """
632
+ command = params.get("command", "")
633
+ backend = declared_backend(params)
634
+ profile, containment = _profile_and_containment(
635
+ command, declared_network(params), backend)
636
+ # The runtime is read from the probe `_profile_and_containment` just
637
+ # ran, never re-probed: the person answering should see WHICH runtime
638
+ # isolates the command, since Podman and Docker are not the same
639
+ # product (ROADMAP_v3 §49, SS22).
640
+ where = {
641
+ "contained": (f"in a {known_runtime().capitalize()} container, "
642
+ "workspace mounted at /workspace"),
643
+ "uncontained": "on the HOST, with your own file access",
644
+ "unavailable": "nowhere -- no sandbox backend is available",
645
+ }.get(containment, containment)
646
+ # SS41. "uncontained" is true of WSL and nowhere near enough: the
647
+ # person answering has to know it is not a weaker container but their
648
+ # own machine, and that the two protections they may be picturing --
649
+ # the read-only mount over this harness's own files, and the memory
650
+ # and process limits -- are simply not there. Said here rather than
651
+ # only in the docs, because this prompt is where the decision is made.
652
+ if backend == BACKEND_WSL:
653
+ where = (f"in WSL ({wsl_distro() or 'default distribution'}) -- "
654
+ f"YOUR machine, not a sandbox: your own files, the "
655
+ f"network on, no memory or process limit, no read-only "
656
+ f"mount over this harness's own config, and it can start "
657
+ f"Windows programs with your full authority")
658
+ # SS48/SS55. The person answering has to know this is not their
659
+ # machine at all, and that two things they may be picturing are
660
+ # absent: any isolation, and any way for this harness to check what
661
+ # the command will touch. The remote is NAMED, because "uncontained"
662
+ # is equally true of the host fallback and means something different
663
+ # here -- and because a prompt that does not say which machine is
664
+ # about to run something is not a prompt anyone can answer.
665
+ if backend == BACKEND_SSH:
666
+ where = (f"on {ssh_target() or 'the configured remote host'} over "
667
+ f"SSH -- ANOTHER MACHINE, not a sandbox and not this "
668
+ f"one: no isolation, no memory or process limit, the "
669
+ f"network on, and nothing here can see its filesystem, "
670
+ f"so no argument of this command has been checked "
671
+ f"against anything")
672
+ notice = f"{profile.tier}: {profile.reason}. Runs {where}."
673
+ # Slice 5b. The person is answering for a privilege level, not only a
674
+ # machine, and "uncontained" does not say which. Two sentences, because
675
+ # the two cases are genuinely different: one is the harness handing over
676
+ # a password it holds, the other is the command asking for root on its
677
+ # own with nothing behind it.
678
+ if declared_root(params):
679
+ notice += (" AS ROOT -- the whole command line runs under sudo, "
680
+ "with the password this harness holds for that machine. "
681
+ "Anything root can do there, this can do.")
682
+ elif _command_names_root(command):
683
+ notice += (" It names sudo (or su, doas, pkexec) itself, which is "
684
+ "why this is being asked about at all. The harness "
685
+ "supplies a password only for a call that declares "
686
+ "needs_root, so this one may simply fail.")
687
+ binary = _resolved_binary(command) if containment == UNCONTAINED else ""
688
+ if binary:
689
+ notice += f" Binary resolves to {binary}."
690
+ segment = _command_touches_protected(command)
691
+ if segment is not None:
692
+ # Why an INERT read is prompting at all: the tier alone would
693
+ # look like a false positive to the person answering.
694
+ notice += (f" It names {segment}/, a protected path that always "
695
+ "requires approval.")
696
+ return notice
697
+
698
+
699
+
700
+ def interactive_profile(requires_network: bool = False) -> CommandProfile:
701
+ """What an interactive shell can do -- STATED, not derived (SS32).
702
+
703
+ `classify_command` reads a command's text. An interactive session has no
704
+ text to read: `cd`, an alias and a REPL mean what arrives later is not
705
+ an argv, and the first line is only the first line. So the capabilities
706
+ are declared at their upper bound -- it runs code, it writes -- and
707
+ `measured` is True because that IS the measurement: the answer does not
708
+ depend on parsing anything, which is exactly when a profile is allowed
709
+ to claim it was characterised (G5).
710
+
711
+ `escapes_workspace` is False because the container's filesystem is not
712
+ the host's, and SS28 admits no other route for this kind.
713
+ """
714
+ network = bool(requires_network)
715
+ return CommandProfile(
716
+ tier=SANDBOXED_NET if network else SANDBOXED,
717
+ measured=True,
718
+ escapes_workspace=False,
719
+ writes=True,
720
+ runs_code=True,
721
+ network=network,
722
+ reason=("an interactive shell in the container -- anything may be "
723
+ "typed into it" + (", and it was opened with network access"
724
+ if network else "")))
725
+
726
+
727
+ def _interactive_approval_check(tool_name: str, params: dict) -> bool:
728
+ """Whether OPENING an interactive shell needs a human yes (SS29, SS32).
729
+
730
+ NOT `_shell_approval_check`, and the difference is the point. That one
731
+ answers about the text it is handed; here the text is only the first
732
+ line of a session whose LATER lines are covered by the same yes. Asking
733
+ about the first line would mean `shell_interactive` with `pwd` was
734
+ auto-approved as a read and handed back a shell that can run anything --
735
+ the approval and the authority describing different calls, which is
736
+ #157's shape.
737
+
738
+ So the question is asked about what is actually being granted:
739
+ `interactive_profile`, through the same mode ladder and the same
740
+ `auto_approved` rule as every other shell call. Under `tiered` and
741
+ `contained` that always asks, because it always runs code (§48, CE1) --
742
+ and it asks through the rule rather than by hardcoding "always", so if
743
+ the rule ever changes this follows it instead of contradicting it.
744
+ """
745
+ active = posture.current()
746
+ mode = capability.validate_mode(active.shell_approval_mode,
747
+ "config.SHELL_APPROVAL_MODE")
748
+ if mode == capability.ALWAYS:
749
+ return True
750
+ if mode == capability.NEVER:
751
+ return False
752
+ profile = interactive_profile(declared_network(params))
753
+ containment = containment_for(profile, is_docker_available())
754
+ if containment == UNAVAILABLE:
755
+ # Nothing can run it, so there is nothing to approve;
756
+ # `start_interactive` refuses with the instructions. Same polarity
757
+ # note as `_shell_approval_check`'s.
758
+ return False
759
+ return not auto_approved(profile, containment)
760
+
761
+
762
+ def _interactive_approval_notice(params: dict, _context=None) -> str:
763
+ """What the person answering is being asked to allow.
764
+
765
+ It says the quiet part out loud (SS29): this yes is not for one command,
766
+ it is for the session. A prompt that described only the first line would
767
+ be telling the truth about the wrong thing.
768
+ """
769
+ network = declared_network(params)
770
+ profile = interactive_profile(network)
771
+ containment = containment_for(profile, is_docker_available())
772
+ where = ("in a container" if containment == capability.CONTAINED
773
+ else "with no container available")
774
+ first = params.get("command", "") if isinstance(params, dict) else ""
775
+ text = (f"Opens an interactive shell {where} and keeps it open. "
776
+ f"APPROVING THIS APPROVES EVERYTHING THE AGENT LATER TYPES INTO "
777
+ f"IT, not just the first line.")
778
+ if isinstance(first, str) and first.strip():
779
+ text += f" It starts by running: {first.strip()[:200]}"
780
+ if network:
781
+ text += " The call declared it needs the network, so egress is on."
782
+ segment = _command_touches_protected(first)
783
+ if segment is not None:
784
+ text += f" That first line names {segment}, which is protected."
785
+ return text
786
+
787
+
788
+ def _resolved_binary(command) -> str:
789
+ """The absolute path the first word will actually execute as, on a
790
+ run that is about to happen on the HOST (§46, EP8).
791
+
792
+ Named on the prompt because "runs on the host" understates it on
793
+ Windows. `ls`, `cat` and `grep` have no native Windows binary, so
794
+ the inert path resolves them off the user's PATH -- and on the
795
+ machine where this was found, `cat` was
796
+ `...\\AppData\\Local\\hermes\\git\\usr\\bin\\cat.exe`, a POSIX
797
+ toolchain shipped by unrelated software. `_is_inert` rejects a
798
+ path-qualified binary (`./ls`) precisely so a planted one cannot be
799
+ NAMED; PATH lookup reaches the same place from the other side, and
800
+ the harness does not get to choose what is on it.
801
+
802
+ Disclosure, not enforcement: the containment argument that lets
803
+ this path run at all is unchanged, and HOST_READ always asks a
804
+ human anyway. What changes is that the human is told which
805
+ executable they are approving.
806
+
807
+ Total, like everything else the gate calls: `command` arrives from
808
+ `registry.approval_needed` as whatever the model emitted, and
809
+ `shutil.which` on a non-string raises.
810
+ """
811
+ if not isinstance(command, str) or not command.strip():
812
+ return ""
813
+ try:
814
+ return shutil.which(command.split()[0]) or ""
815
+ except (OSError, ValueError):
816
+ return ""
817
+
818
+
819
+ # ---------------------------------------------------------------------------
820
+ # ---- Tool handler ---------------------------------------------------------
821
+ # ---------------------------------------------------------------------------
822
+
823
+
824
+ def uncontained_refusal(command: str, backend: str,
825
+ needs_root: bool = False) -> str | None:
826
+ """Why this call must not run at all, or None (§49).
827
+
828
+ `fallback_changed_refusal`'s shape, and ONE copy for the same reason:
829
+ the gate reads it to answer "there is nothing to approve", and `run`
830
+ and the session start handler read it to stop the call. Three sites
831
+ deciding this separately is the drift #157 came from.
832
+
833
+ Two refusals, and they say different things on purpose.
834
+
835
+ THE BACKEND IS OFF (SS35). Not "unavailable" -- a machine that has WSL
836
+ and is not allowed to use it, which a model told "no distro found"
837
+ would try to fix by asking the user to install one.
838
+
839
+ A PROTECTED SEGMENT (SS40). In the container `.venastine/` is mounted
840
+ read-only, so a write there fails with EROFS and a read is documented
841
+ risk; on WSL there is no mount at all, a write SUCCEEDS, and D17's
842
+ hash notices only at the next launch. So the shell's usual answer for
843
+ a protected segment -- always ask -- is the wrong one here, and this
844
+ is the file tools' answer instead: deny.
845
+
846
+ The token check is exactly sound where it bites. An INERT command
847
+ carries no metacharacters by construction, so `command.split()` IS the
848
+ argv that will run and a literal segment cannot hide behind quoting or
849
+ expansion. A non-inert command can hide one, and still meets a human
850
+ on top of this -- `runs_code` is True for every non-inert profile
851
+ (CE1), so it asks under `tiered` and, being UNCONTAINED here, under
852
+ `contained` too.
853
+
854
+ A THIRD refusal arrives with slice 5b, and it is read FIRST because it
855
+ is true of every backend including the container: a call that asked for
856
+ root and cannot have it. `sudo_refusal` owns that decision -- see there
857
+ for why the container is refused for already being root, and why no
858
+ stored password is a refusal rather than a prompt (SS68).
859
+ """
860
+ if needs_root:
861
+ refusal = sudo_refusal(backend)
862
+ if refusal is not None:
863
+ return refusal
864
+ if backend == BACKEND_SSH:
865
+ if not ssh_enabled():
866
+ return ssh_unavailable_reason()
867
+ segment = _command_touches_protected(command)
868
+ if segment is not None:
869
+ # SS54. SS40's answer, reached by a different road: WSL is
870
+ # refused because it demonstrably CAN write this harness's own
871
+ # authority files, and SSH is refused because nothing here can
872
+ # demonstrate that it cannot. `ssh localhost` is this machine,
873
+ # and a remote that mounts this one is not visible from here
874
+ # either -- so the question "is that path this harness's own?"
875
+ # has no answer, and an unanswerable question is not a yes.
876
+ return (
877
+ f"This command names {segment}/, and a command over SSH is "
878
+ f"refused rather than asked about when it does. This "
879
+ f"harness cannot tell whether the remote host is a "
880
+ f"different machine -- `ssh localhost` is this one, and a "
881
+ f"remote that mounts this one looks the same from here -- "
882
+ f"so it cannot tell whether that path is its own authority "
883
+ f"files. Run it in the container, or do the work somewhere "
884
+ f"inside the workspace.")
885
+ return None
886
+ if backend != BACKEND_WSL:
887
+ return None
888
+ if not wsl_enabled():
889
+ return wsl_unavailable_reason()
890
+ segment = _command_touches_protected(command)
891
+ if segment is not None:
892
+ return (
893
+ f"This command names {segment}/, and a command in WSL is "
894
+ f"refused rather than asked about when it does. In the "
895
+ f"container that directory is mounted read-only, so a write "
896
+ f"fails and a read is a documented risk you can accept. WSL "
897
+ f"mounts nothing: a write there would succeed against this "
898
+ f"harness's own authority files and would only be noticed at "
899
+ f"the next launch. Run it in the container, or do the work "
900
+ f"somewhere inside the workspace.")
901
+ return None
902
+
903
+
904
+ def fallback_changed_refusal(command: str, docker_up: bool) -> str | None:
905
+ """The TOCTOU safety net, or None: why a command approved while a
906
+ container runtime answered must not now run on the fallback.
907
+
908
+ If the approval check auto-approved because the runtime was available
909
+ at that time, but it is now down and the command would take the
910
+ fallback, the fallback would have required approval that was never
911
+ given. One copy for `run` and for the background-session start tools
912
+ (ROADMAP_v3 §49), which pass the same gate and the same probe.
913
+ """
914
+ if docker_up or _is_inert(command):
915
+ return None
916
+ # Read here rather than passed in from the approval check: §40 makes the
917
+ # two reads the SAME object for the life of the process, so re-reading
918
+ # cannot reintroduce the TOCTOU gap this exists to close. Before §40 it
919
+ # could have.
920
+ active = posture.current()
921
+ if active.allow_insecure_fallback and not active.auto_approve_fallback:
922
+ return ("Docker became unavailable after the approval check. "
923
+ "The insecure subprocess fallback requires explicit "
924
+ "per-run approval (AUTO_APPROVE_SANDBOX_FALLBACK is "
925
+ "False). Please retry — the approval prompt will "
926
+ "appear this time.")
927
+ return None
928
+
929
+
930
+ def run(params: dict) -> dict:
931
+ # `parsed.rationale` is deliberately never read below. It is shown
932
+ # to a person and archived with the call; it has no part in what
933
+ # runs or in whether it is allowed to (§42, RA2).
934
+ parsed = ShellParams(**params)
935
+
936
+ # Probe Docker once for this execution — the result is threaded
937
+ # into run_sandboxed to eliminate the TOCTOU gap where Docker
938
+ # status changes between the approval check and execution.
939
+ # SS37/SS40/SS54, above the container probe: a call that asked for WSL
940
+ # or SSH and cannot have it is refused by name, and is never quietly
941
+ # served by a backend it did not ask for.
942
+ refusal = uncontained_refusal(parsed.command, parsed.backend,
943
+ parsed.needs_root)
944
+ if refusal is not None:
945
+ return {"error": refusal}
946
+
947
+ # Not probed for a WSL or SSH call, and not merely to save the 0.43s:
948
+ # the TOCTOU guard below is about a container runtime disappearing
949
+ # between the gate and the run and the command then taking the INSECURE
950
+ # FALLBACK. Neither can take it -- `_route` answers ROUTE_WSL/ROUTE_SSH
951
+ # or refuses (SS37) -- so running that guard here would refuse a call
952
+ # for a backend it was never going to touch.
953
+ docker_up = True if parsed.backend != BACKEND_CONTAINER \
954
+ else is_docker_available()
955
+
956
+ if parsed.backend == BACKEND_CONTAINER:
957
+ refusal = fallback_changed_refusal(parsed.command, docker_up)
958
+ if refusal is not None:
959
+ return {"error": refusal}
960
+
961
+ try:
962
+ return run_sandboxed(
963
+ command=parsed.command,
964
+ workspace_dir=config.WORKSPACE_DIR,
965
+ docker_available=docker_up,
966
+ backend=parsed.backend,
967
+ needs_root=parsed.needs_root,
968
+ # §28: the SAME classification the approval check made, so
969
+ # routing cannot disagree with the decision to allow it --
970
+ # the declaration included (§50), read off the validated
971
+ # params here and off the raw ones at the gate, which is why
972
+ # `declared_network` accepts only literal True.
973
+ profile=classify_command(parsed.command, config.WORKSPACE_DIR,
974
+ requires_network=parsed.requires_network),
975
+ )
976
+ except SandboxUnavailable as e:
977
+ return {"error": str(e)}
978
+ except Exception as e:
979
+ logger.exception("shell tool failed")
980
+ return {"error": f"Shell execution failed: {e}"}