@yahyahammad/venastine 0.3.8 → 0.3.10

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 (130) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2139 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1043 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +584 -528
  14. package/bin/venastine.py +73 -71
  15. package/cli_commands.py +848 -835
  16. package/config.yaml +64 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +987 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2756 -2715
  28. package/core/commands.py +464 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +274 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +467 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +114 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +780 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +314 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +1145 -267
  102. package/tools/builtin/_page_text.py +490 -0
  103. package/tools/builtin/_pdf_text.py +113 -0
  104. package/tools/builtin/arxiv.py +685 -681
  105. package/tools/builtin/fetch_url.py +639 -371
  106. package/tools/builtin/file_ops.py +720 -720
  107. package/tools/builtin/geometry.py +184 -184
  108. package/tools/builtin/load_skill.py +76 -76
  109. package/tools/builtin/pin.py +227 -227
  110. package/tools/builtin/probability_stats.py +224 -224
  111. package/tools/builtin/project_docs.py +464 -464
  112. package/tools/builtin/remember.py +175 -175
  113. package/tools/builtin/shell.py +980 -980
  114. package/tools/builtin/todo.py +149 -149
  115. package/tools/builtin/web_search.py +402 -328
  116. package/tools/context.py +159 -159
  117. package/tools/isolation.py +387 -387
  118. package/tools/registry.py +1252 -1242
  119. package/tui/app.py +8372 -8307
  120. package/tui/app.tcss +754 -739
  121. package/tui/commands.py +26 -26
  122. package/tui/diffs.py +286 -286
  123. package/tui/history.py +128 -128
  124. package/tui/hosted_driver.py +102 -102
  125. package/tui/markdown.py +1329 -1329
  126. package/tui/meters.py +364 -364
  127. package/tui/ravens.py +146 -146
  128. package/tui/screens.py +1255 -1197
  129. package/tui/themes.py +599 -599
  130. package/tui/widgets.py +3861 -3796
package/tools/registry.py CHANGED
@@ -1,1242 +1,1252 @@
1
- """
2
- tools/registry.py
3
-
4
- MECHANISM, not policy: the single choke point every tool call passes
5
- through. This is the only file that imports both security.permissions and
6
- the individual tool modules; tool modules never import permissions
7
- themselves.
8
-
9
- ROADMAP_v2 §15:
10
- * every entry point takes an optional ToolContext, threaded from
11
- core/loop.py, and hands it to the policy functions ("stricter wins",
12
- D14 -- see security/permissions.py for the composition rule);
13
- * approval_needed() is where the tool's own dynamic approval_check is
14
- OR'd with the config/context lookup, so dispatch() and the loop's
15
- permission bridge cannot diverge (see its docstring);
16
- * schemas() advertises only what is actually callable;
17
- * register()/unregister() work at runtime (D15) for MCP (§17);
18
- * assert_permissions_declared() runs at import, after static
19
- registration (D24).
20
- """
21
-
22
- import inspect
23
- import logging
24
- from typing import TYPE_CHECKING, Optional
25
-
26
- import config
27
- from agents import subagent_tool
28
- from safety.policy_enforcement import (
29
- check_input_policy,
30
- check_output_policy,
31
- param_digest,
32
- redacted_values,
33
- )
34
- from security.permissions import (
35
- APPROVAL_BY_SHELL_MODE,
36
- assert_permissions_declared,
37
- is_tool_allowed,
38
- requires_approval,
39
- )
40
- from tools import isolation
41
- from tools.base import (
42
- BUDGET_COMPUTE,
43
- BUDGET_HUMAN,
44
- BUDGET_IO,
45
- GRANT_ANYWHERE,
46
- GRANT_NEVER,
47
- GRANT_SIGNOFF_ONLY,
48
- OPENS_CALL,
49
- OPENS_SESSION,
50
- OPENS_THREAD,
51
- ToolSpec,
52
- assert_budget_declared,
53
- assert_grant_policy_declared,
54
- )
55
- from tools.builtin import (
56
- arxiv,
57
- ask_user,
58
- discrete_math,
59
- fetch_url,
60
- file_ops,
61
- geometry,
62
- get_time,
63
- linear_algebra,
64
- load_skill,
65
- logic,
66
- pin,
67
- probability_stats,
68
- project_docs,
69
- remember,
70
- shell,
71
- shell_sessions,
72
- symbolic_math,
73
- todo,
74
- web_search,
75
- )
76
-
77
- logger = logging.getLogger(__name__)
78
-
79
- if TYPE_CHECKING: # pragma: no cover - typing only
80
- from tools.context import RunInfo, ToolContext
81
-
82
- # Handler parameter names dispatch() will inject, by signature inspection
83
- # (ROADMAP_v2 §18). A tool handler that declares one of these receives the
84
- # live value; handlers that don't are called with params only. Generalised
85
- # so §23's response-channel tools can add a third name later without
86
- # touching dispatch() again.
87
- _INJECTABLE_PARAMS = (
88
- # §23 renamed permission_channel -> response_channel: it is no longer
89
- # permission-specific, and a tool that needs to ask a human anything
90
- # receives the same object the loop asks through.
91
- "parent_context", "parent_run", "response_channel",
92
- # §23 AC1b: the approved SUBSET from a subagent sign-off. The comment
93
- # above anticipated §23's tools adding a name here without reopening
94
- # dispatch(); this is that name.
95
- "signoff",
96
- # ROADMAP_v2 §21: the live ConversationMemory, for `pin`. The
97
- # comment above anticipated a third name arriving without touching
98
- # dispatch() again; this is it.
99
- "memory",
100
- # Batch 59: the core/agent_activity.py sink, for spawn_subagent. A
101
- # shell watching the agent stack has to learn about a run that
102
- # happens INSIDE a tool call, which is the one place a LoopEvent
103
- # cannot reach -- see that module for why. Injected rather than
104
- # threaded through params because it is a run-scoped value, exactly
105
- # like response_channel beside it.
106
- "activity",
107
- # ROADMAP_v3 §61 (CN7): the turn's CancelToken, for spawn_subagent. A
108
- # child run is the parent's turn continuing, so stopping the parent
109
- # stops it -- and the only way a value reaches a run that happens
110
- # INSIDE a tool call is this list, which is `activity`'s own argument
111
- # one line up.
112
- "cancel",
113
- # ROADMAP_v2 §47: the model's own id for THIS call. A tool that
114
- # creates something durable can then record which call created it,
115
- # which is what lets one line in a transcript find one row in the
116
- # database when a turn made three of them. Injected rather than put
117
- # in params, twice over: params are the MODEL'S, parsed from its
118
- # tool call, and a model that could write its own call id could
119
- # claim a line it did not make.
120
- "call_id",
121
- )
122
-
123
-
124
- class ToolCallDenied(Exception):
125
- """Raised when policy blocks a tool call outright, or an approval was
126
- required and not given."""
127
-
128
-
129
- class ToolRegistry:
130
- def __init__(self) -> None:
131
- self._tools: dict[str, ToolSpec] = {}
132
- # name -> the subset of _INJECTABLE_PARAMS the handler declares.
133
- # Cached at register() so dispatch() never re-inspects per call.
134
- self._injectable: dict[str, tuple] = {}
135
-
136
- def register(self, spec: ToolSpec) -> None:
137
- self._tools[spec.name] = spec
138
- self._injectable[spec.name] = self._declared_injections(spec.handler)
139
-
140
- @staticmethod
141
- def _declared_injections(handler) -> tuple:
142
- """Which injectable run-scoped values this handler wants. A
143
- handler opts in simply by naming a parameter (e.g.
144
- `def run(params, parent_context)`); everything else stays a
145
- params-only call so the existing twelve tools are untouched."""
146
- try:
147
- names = set(inspect.signature(handler).parameters)
148
- except (TypeError, ValueError): # builtins / un-introspectable
149
- return ()
150
- return tuple(p for p in _INJECTABLE_PARAMS if p in names)
151
-
152
- def unregister(self, tool_name: str) -> None:
153
- """Runtime removal (D15). An MCP server disconnecting drops its
154
- tools mid-session, so a name that was valid a moment ago becomes
155
- a reachable state rather than a programmer error -- which is why
156
- dispatch() keeps its unknown-tool guard.
157
-
158
- Idempotent: removing an absent name is not an error, because
159
- disconnect handling can run more than once for the same server.
160
- """
161
- self._tools.pop(tool_name, None)
162
- self._injectable.pop(tool_name, None)
163
-
164
- def _advertised(self, name: str, spec, context,
165
- images: bool = False) -> bool:
166
- """The two §15 filters, shared by schemas() and
167
- headless_hidden(): policy allowability plus the tool's own
168
- "nothing to act on" signal -- and, since ROADMAP_v3 §81 (IM6), a
169
- third: a tool whose result carries an image is offered only where
170
- the caller says images can be delivered.
171
-
172
- `images` DEFAULTS FALSE, so a caller that never heard of images
173
- hides such a tool rather than offering one whose result the model
174
- could not see. The loop is the one caller that knows the answer,
175
- and it passes it."""
176
- if not is_tool_allowed(name, context):
177
- return False
178
- if spec.available_check is not None and not spec.available_check():
179
- return False
180
- if spec.returns_images and not images:
181
- return False
182
- return True
183
-
184
- def _answered_by_grant(self, tool_name: str, granted) -> bool:
185
- """Whether a pre-flight grant has ALREADY answered this tool's
186
- approval question (§25 R15).
187
-
188
- `callable_only` below asks "can anything ask?". Since §25 that is
189
- the wrong question by itself: a grant is an answer given early, so
190
- the question is "can anything answer FOR THIS TOOL?" -- and a
191
- granted tool is answerable with no channel at all. #156 is the gap
192
- between those two sentences: `--grant-tools X` with no `--attended`
193
- built a grant the enforcement path honoured and the advertisement
194
- path never saw, so the model was never told the tool existed and
195
- never emitted the call.
196
-
197
- TWO checks, and both are RE-derived here rather than trusted from
198
- the set -- the same discipline core/loop.py applies before honouring
199
- a grant, because a stale or hand-built `RunInfo` must not widen what
200
- is advertised any more than it can widen what is dispatched:
201
-
202
- grantable() R2. A tool deciding approval from its PARAMS was
203
- never consented to by name, so a grant naming one
204
- answers nothing.
205
- grant_policy R13, and it must be `== GRANT_ANYWHERE` rather than
206
- `!= GRANT_NEVER`. Both callers of this reach it only
207
- when the run is HEADLESS, and headless is precisely
208
- the unattended case GRANT_SIGNOFF_ONLY exists to
209
- exclude: R13 admits `write_project_doc` to the §18
210
- sign-off because a human is answering in the moment
211
- about one named agent, and refuses it to ten
212
- unattended passes on one launch-time tick. A
213
- headless run has no human answering in the moment,
214
- so the looser test would readmit it exactly where
215
- the argument was written against.
216
-
217
- THIS IS THE SAME PREDICATE `candidates()` USES, and deliberately so.
218
- That function decides what may be OFFERED to an unattended run and
219
- this one decides what a grant then makes VISIBLE to it -- one
220
- question, so one answer. Written `!= GRANT_NEVER` first, which let
221
- `write_project_doc` through here while `candidates()` refused it:
222
- #67/#133's own shape, reappearing inside the batch that generalised
223
- it. Neither the CLI nor the TUI nor a subagent sign-off can put a
224
- SIGNOFF_ONLY name into a headless grant today, so nothing was
225
- reachable -- but "unreachable" is a fact about the callers, and this
226
- is a claim about the policy.
227
-
228
- Shared by schemas() and headless_hidden() rather than written out
229
- twice -- those two must agree about what is hidden, and #67/#133
230
- are what a shared mechanism with a duplicated policy costs.
231
- """
232
- return (bool(granted)
233
- and tool_name in granted
234
- and self.grantable(tool_name)
235
- and self.grant_policy(tool_name) == GRANT_ANYWHERE)
236
-
237
- def is_advertised(
238
- self, tool_name: str, context: Optional["ToolContext"] = None,
239
- callable_only: bool = False,
240
- granted: Optional[set] = None,
241
- images: bool = False,
242
- ) -> bool:
243
- """Whether schemas() would advertise this tool right now.
244
-
245
- THE WHOLE ADVERTISEMENT QUESTION IN ONE PLACE, and the reason
246
- is one method up: _answered_by_grant is shared by schemas()
247
- and headless_hidden() because "those two must agree about
248
- what is hidden, and #67/#133 are what a shared mechanism with
249
- a duplicated policy costs". #68 is the same sentence with a
250
- third party to the agreement -- prompts.system_prompts's
251
- catalogs, whose prose INSTRUCTS the model to call a tool.
252
-
253
- That third caller asked `is_allowed(name, context)` instead,
254
- which is POLICY: it answers "is this tool permitted", not
255
- "can this run call it". A research pass is headless, so
256
- spawn_subagent is permitted, hidden from the schema list, and
257
- named in the run's own headless_hidden() warning -- while the
258
- prompt told the model to spawn one. The harness stated the
259
- contradiction to its log and to the model in the same breath.
260
-
261
- A PREDICATE RATHER THAN `name in [s["name"] for s in
262
- schemas()]`: the schema list is built where the run is, and
263
- the prompt is built before the run exists. Both need the
264
- answer; only one is in a position to enumerate.
265
- """
266
- spec = self._tools.get(tool_name)
267
- if spec is None:
268
- return False
269
- if not self._advertised(tool_name, spec, context, images):
270
- return False
271
- return not (callable_only
272
- and self.approval_needed(tool_name, {}, context)
273
- and not self._answered_by_grant(tool_name, granted))
274
-
275
- def schemas(
276
- self, context: Optional["ToolContext"] = None,
277
- callable_only: bool = False,
278
- granted: Optional[set] = None,
279
- images: bool = False,
280
- ) -> list[dict]:
281
- """What gets sent to the LLM's `tools` parameter each call.
282
-
283
- Only tools that are actually callable are advertised. Advertising
284
- an uncallable tool is not harmless: the model keeps choosing it,
285
- burns a turn per attempt, and the only signal is a denial string
286
- inside a tool result. That is precisely the damage the `fetch_url`
287
- defect did for its whole life (D24), so §15 fixes the shape as
288
- well as the instance.
289
-
290
- Filters, deliberately distinct:
291
- * is_tool_allowed(name, context) -- policy. Global config AND
292
- every active layer's restriction.
293
- * spec.available_check() -- the tool's own "I have nothing to
294
- act on yet" signal (load_skill with an empty skill catalog).
295
- * callable_only (§18, user-widened headless callability rule) --
296
- when the run has no response_channel, a tool whose
297
- approval_needed() is True for empty params is UNCALLABLE in
298
- this configuration (nothing can grant the approval), so it is
299
- not advertised. autoApproved MCP servers and approval-free
300
- tools pass; approval-gated ones drop. The loop pairs this with
301
- a once-per-process WARNING naming what was hidden -- no quiet
302
- invisibility (the fetch_url lesson).
303
- * granted (§25 R15) -- names a pre-flight grant already answered
304
- for. Those stay advertised even with no channel, because the
305
- approval question HAS an answer; see _answered_by_grant.
306
- * images (ROADMAP_v3 §81, IM6) -- whether an image in a tool
307
- result can reach the model in this run. A tool that declares
308
- `returns_images` is dropped when it cannot; see _advertised.
309
-
310
- WHAT callable_only GUARANTEES, stated because the converse does not
311
- hold and #158 is what assuming it costs: it means SOME call shape
312
- is callable, not that every one is. The probe is
313
- approval_needed(name, {}), and for a tool whose approval_check
314
- reads the params -- read/write/edit on a path, shell on a command --
315
- the empty dict is a call the model will never make. `write` resolves
316
- an empty path inside the workspace, so it survives this filter and
317
- is then denied per out-of-workspace call. That is deliberate (an
318
- in-workspace write IS callable headless), but it means a survivor
319
- of this filter is not a promise about any particular call.
320
- """
321
- return [spec.schema for name, spec in self._tools.items()
322
- if self.is_advertised(name, context, callable_only,
323
- granted, images)]
324
-
325
- def headless_hidden(
326
- self, context: Optional["ToolContext"] = None,
327
- granted: Optional[set] = None,
328
- images: bool = False,
329
- ) -> list[str]:
330
- """Names that would be advertised with a response_channel but
331
- are dropped by schemas(callable_only=True) -- i.e. advertised yet
332
- uncallable headless. The loop logs exactly this list once, so a
333
- tool hidden by the headless filter is named and explained rather
334
- than silently absent (the trade this project keeps deciding
335
- against).
336
-
337
- Takes `granted` for the same reason schemas() does, and it is not
338
- cosmetic: this list is what the WARNING names. A granted tool that
339
- is genuinely callable must not be reported as hidden, or the notice
340
- whose whole purpose is to stop invisibility starts producing a
341
- second kind of wrong answer.
342
- """
343
- # ADVERTISED ATTENDED AND NOT HEADLESS -- written as the two
344
- # calls it means rather than as the filter's negation, so the
345
- # list and the schemas can only disagree if is_advertised
346
- # disagrees with itself.
347
- return [
348
- name for name in self._tools
349
- if self.is_advertised(name, context, False, granted, images)
350
- and not self.is_advertised(name, context, True, granted, images)
351
- ]
352
-
353
- def image_hidden(
354
- self, context: Optional["ToolContext"] = None,
355
- granted: Optional[set] = None,
356
- ) -> list[str]:
357
- """ROADMAP_v3 §81 (IM6). Names that would be advertised if images
358
- could be delivered, and are dropped because they cannot. The loop
359
- logs exactly this list, once, for headless_hidden()'s reason: a
360
- tool the user enabled and the model never sees is named and
361
- explained, not silently absent.
362
-
363
- Written as the two calls it means, like headless_hidden() above,
364
- so the list and the schemas can only disagree if is_advertised
365
- disagrees with itself.
366
- """
367
- return [
368
- name for name in self._tools
369
- if self.is_advertised(name, context, False, granted, True)
370
- and not self.is_advertised(name, context, False, granted, False)
371
- ]
372
-
373
- def approval_needed(
374
- self, tool_name: str, params: dict,
375
- context: Optional["ToolContext"] = None,
376
- ) -> bool:
377
- """SINGLE SOURCE OF TRUTH for whether a call needs human approval.
378
-
379
- Both dispatch() and core/loop.py's permission bridge call this, so
380
- they can never disagree -- a path-dependent tool must surface a
381
- permission_request event the user can approve, not be silently
382
- denied by one check while the other reports no approval needed.
383
-
384
- §15 makes this an OR rather than an either/or. Previously a tool
385
- with an approval_check bypassed requires_approval() entirely,
386
- which would have made agent-level approval_overrides do nothing
387
- for read/write/edit/shell. Now:
388
-
389
- tool's own approval_check OR config/context requirement
390
-
391
- so a context can tighten a lenient default (an agent may demand
392
- approval for symbolic_math) but can never suppress a check the
393
- tool itself imposes (an agent declaring `shell: false` does NOT
394
- skip shell's non-inert-command gate).
395
- """
396
- spec = self._tools.get(tool_name)
397
- tool_level = (
398
- spec.approval_check(tool_name, params)
399
- if spec is not None and spec.approval_check is not None
400
- else False
401
- )
402
- return tool_level or requires_approval(tool_name, params, context)
403
-
404
- def refusal_reason(
405
- self, tool_name: str, params: dict,
406
- context: Optional["ToolContext"] = None,
407
- ) -> Optional[str]:
408
- """Why this call would be refused before it is asked about,
409
- or None (§32 A7).
410
-
411
- The loop asks the registry, the same way it asks whether
412
- approval is needed at all -- which tools have pre-flight
413
- conditions is not the loop's knowledge.
414
-
415
- NOT AN ENFORCEMENT PATH. dispatch() still runs the handler and
416
- the handler still refuses; this only decides whether a human
417
- is put to a question whose answer cannot change the outcome.
418
- A refusal_check that wrongly returned a reason would therefore
419
- skip a prompt, never widen anything.
420
- """
421
- spec = self._tools.get(tool_name)
422
- if spec is None or spec.refusal_check is None:
423
- return None
424
- return spec.refusal_check(params, context)
425
-
426
- def is_allowed(
427
- self, tool_name: str, context: Optional["ToolContext"] = None,
428
- ) -> bool:
429
- """Whether policy permits this tool at all, in this context.
430
-
431
- The loop needs this to avoid prompting for a call it will refuse
432
- regardless. Exposed here rather than importing is_tool_allowed
433
- into core/loop.py: this file is the only one that talks to
434
- security.permissions, and that boundary is the point.
435
- """
436
- return is_tool_allowed(tool_name, context)
437
-
438
- def is_registered(self, tool_name: str) -> bool:
439
- """Whether a tool with this name is currently registered.
440
-
441
- Policy and registration are different questions (review §19-20
442
- f12): is_allowed answers "would policy refuse this call", and for
443
- unknown mcp__ names it says no-refuse by design -- the server may
444
- connect later. A caller that needs to know whether the tool
445
- EXISTS (e.g. §19's activation notice, which should flag a
446
- declared tool that is not callable right now) asks this.
447
- """
448
- return tool_name in self._tools
449
-
450
- def grantable(self, tool_name: str) -> bool:
451
- """Whether approving this tool BY NAME, before any call exists, is
452
- meaningful consent (ROADMAP_v2 §25, R2).
453
-
454
- False for any tool declaring its own approval_check. Those decide
455
- per call, from the params -- read/write/edit on a path outside the
456
- workspace, shell on a non-inert command -- so a name-level grant
457
- would authorise a call the user never saw. `shell` is the sharp
458
- case: granting the NAME would wave through every command for the
459
- rest of the run, which is not what anyone ticking a checkbox
460
- labelled "shell" is agreeing to.
461
-
462
- A registration-time property, not an inference about params, and
463
- the same rule for §18's subagent sign-off as for §25's pipeline
464
- grants -- one mechanism, so the two cannot drift into different
465
- ideas of what a grant covers. A non-grantable tool is not blocked:
466
- it falls back to being asked, exactly as it is today.
467
- """
468
- spec = self._tools.get(tool_name)
469
- return spec is not None and spec.approval_check is None
470
-
471
- def grant_scope(self, tool_name: str) -> Optional[str]:
472
- """"run" if approving this tool once covers the rest of the run.
473
-
474
- Mechanism, not policy: the loop asks rather than knowing which
475
- tools work this way, so the tool name stays out of core/loop.py.
476
- """
477
- spec = self._tools.get(tool_name)
478
- return spec.grant_scope if spec is not None else None
479
-
480
- def rationale_param(self, tool_name: str) -> Optional[str]:
481
- """Which param carries the agent's own stated reason,
482
- or None (§42, RA2).
483
-
484
- Mechanism, not policy, exactly like grant_scope above: the
485
- consumer asks rather than testing for the literal name
486
- `shell`. Two of them need this -- the approval prompt, which
487
- shows the reason, and the transcript digest, which skips it --
488
- and neither is a place for a tool name to live.
489
- """
490
- spec = self._tools.get(tool_name)
491
- return spec.rationale_param if spec is not None else None
492
-
493
- def rationale_for(self, tool_name: str, params: dict):
494
- """The agent's stated reason for THIS call, or None.
495
-
496
- The VALUE, so no caller has to know the key. core/loop.py puts
497
- the result on the approval request and the shells render it;
498
- `tui/screens.py` imports nothing from this package and that
499
- stays true because what travels is a string.
500
-
501
- Empty and whitespace-only collapse to None, so a model that
502
- supplies the key with nothing in it is treated as the omission
503
- it is -- the prompt says so rather than showing a blank space
504
- where a reason should be.
505
- """
506
- key = self.rationale_param(tool_name)
507
- if not key or not isinstance(params, dict):
508
- return None
509
- value = params.get(key)
510
- if not isinstance(value, str) or not value.strip():
511
- return None
512
- return value.strip()
513
-
514
- def headline_param(self, tool_name: str) -> Optional[str]:
515
- """Which param is the SUBJECT of this tool's approval question,
516
- or None (§46, EP2).
517
-
518
- Mechanism, not policy, exactly like rationale_param above: the
519
- consumer asks rather than testing for the literal name `shell`.
520
- """
521
- spec = self._tools.get(tool_name)
522
- return spec.headline_param if spec is not None else None
523
-
524
- def headline_for(self, tool_name: str, params: dict):
525
- """The thing THIS call is asking permission to do, or None.
526
-
527
- The VALUE, so no caller has to know the key -- `tui/screens.py`
528
- imports nothing from this package and that stays true because
529
- what travels is a string.
530
-
531
- NOT `str()`-coerced, and that is the point rather than an
532
- oversight. `classify_command` is total precisely because the
533
- model's tool input reaches the approval gate unvalidated
534
- (`ShellParams` does not run until `run()`), so `command` can be
535
- a list, a dict or None here. A non-string coerced to
536
- `"['cat', '/etc/passwd']"` would put a fabricated command in
537
- the one place on the screen that must be verbatim; returning
538
- None instead drops the pinned block and leaves the payload --
539
- rendered whole, showing the real shape -- as the only account
540
- of the call. The prompt still says what it is, because the
541
- notice reports UNKNOWN for exactly this input.
542
-
543
- Empty and whitespace-only collapse to None for
544
- `rationale_for`'s reason: a key supplied with nothing in it is
545
- the omission it looks like.
546
- """
547
- key = self.headline_param(tool_name)
548
- if not key or not isinstance(params, dict):
549
- return None
550
- value = params.get(key)
551
- if not isinstance(value, str) or not value.strip():
552
- return None
553
- return value.strip()
554
-
555
- def call_digest(self, tool_name: str, params) -> str:
556
- """The transcript's one-line summary of a tool call.
557
-
558
- THE ONE PRODUCER (§42, RA3). `param_digest` is pure and knows
559
- nothing about tools; this knows which param a tool declared as
560
- its rationale and drops it, because that field is prose for a
561
- person and would take sixty of the digest's hundred and forty
562
- characters -- leading the line about half the time, since the
563
- key order is the model's.
564
-
565
- Three consumers went through `param_digest` directly before
566
- this: the TUI's `▸ name` line, the research pipeline's tool
567
- rows, and §27's replay of the archive. Teaching each of them
568
- the lookup would be three copies of one rule, which is the
569
- producer/consumer shape `param_digest`'s own docstring calls
570
- this project's canonical bug.
571
- """
572
- key = self.rationale_param(tool_name)
573
- return param_digest(params, omit=(key,) if key else ())
574
-
575
- def call_links(self, tool_name: str, params) -> tuple:
576
- """The untruncated values behind that summary (batch 65).
577
-
578
- `call_digest` caps a value at 60 characters, which is shorter
579
- than most real URLs, so the transcript resolves a truncated
580
- span against these to arm a ctrl+click. Redacted, and with any
581
- value the redactor rewrote dropped -- `redacted_values` says
582
- why a target may never come from the raw params.
583
-
584
- THE SAME `omit`, which is the whole reason this sits here
585
- rather than being called direct (Section 42, RA3): the two
586
- halves describe one call, and a candidate drawn from a
587
- parameter the line does not show is a target no span could
588
- resolve to.
589
- """
590
- key = self.rationale_param(tool_name)
591
- return redacted_values(params, omit=(key,) if key else ())
592
-
593
- def opens_thread(self, tool_name: str) -> bool:
594
- """Whether a call to this tool creates a thread of its own (§47).
595
-
596
- Mechanism, not policy, exactly like request_kind below: a reader
597
- asks rather than knowing that spawn_subagent is special. Two
598
- consumers -- core/replay.py, deciding what a stored tool line
599
- carries, and the TUI, deciding which live line to arm -- and one
600
- declaration between them.
601
-
602
- False for an unknown tool, which is what an MCP tool registered
603
- at runtime is until it says otherwise.
604
- """
605
- spec = self._tools.get(tool_name)
606
- return bool(spec is not None and spec.opens_thread)
607
-
608
- def opens_session(self, tool_name: str) -> bool:
609
- """Whether a call to this tool starts a background session (§49,
610
- SS14). `opens_thread`'s sibling, and False for an unknown tool for
611
- the same reason."""
612
- spec = self._tools.get(tool_name)
613
- return bool(spec is not None and spec.opens_session)
614
-
615
- def opens(self, tool_name: str) -> tuple:
616
- """What a call to this tool OPENS: `("thread",)`, `("session",)` or
617
- `("call",)` (§47, extended by §49 SS14, widened by §55 TR7).
618
-
619
- THE ONE QUESTION A CONSUMER ASKS, and the reason the two flags above
620
- are not read directly outside this class. core/replay.py and the TUI
621
- each decide what a tool line carries; before this they asked
622
- `opens_thread` and would each have had to grow the same second
623
- branch, which is how the live line and the replayed one come to
624
- disagree about what is clickable -- the exact divergence
625
- `opens_thread`'s own docstring exists to prevent, one kind over.
626
-
627
- THERE IS NO LONGER AN EMPTY ANSWER, and the contract that replaced
628
- it is the one thing to read here before changing a caller. Until
629
- §55 this returned `()` for a line that opened nothing, and the two
630
- consumers paired that falsy tuple with a call id as their gate:
631
- `opens and call_id`. TR7 makes every call openable -- its own
632
- params and its own result, which is the half of a tool call nothing
633
- rendered -- so the kind is always present and THE CALL ID IS THE
634
- ONLY GATE. A call the model made without an id cannot be looked up
635
- in the archive and is the one unarmed line.
636
-
637
- OPENS_CALL IS ANSWERED WITHOUT A REGISTRY LOOKUP, deliberately.
638
- `opens_thread` and `opens_session` are False for a tool this
639
- registry has never seen -- which is what an MCP tool registered at
640
- runtime is until it says otherwise, and what a tool removed between
641
- a thread being written and being replayed is for ever. Neither of
642
- those is a reason to hide a stored result: the archive holds the
643
- call and its result whatever this process knows about the tool, so
644
- the fallback is a property of the ARCHIVE rather than of the
645
- registry, and asking would only teach it to lie about old threads.
646
-
647
- A tuple rather than a string because the two consumers carry
648
- `(kind, call id)` into style metadata as one unit, and because the
649
- shape outlived the falsy contract that first chose it.
650
- """
651
- if self.opens_thread(tool_name):
652
- return (OPENS_THREAD,)
653
- if self.opens_session(tool_name):
654
- return (OPENS_SESSION,)
655
- return (OPENS_CALL,)
656
-
657
- def parallel(self, tool_name: str) -> bool:
658
- """Whether several calls to this tool in one response may run at
659
- the same time (§47 slice 8, NA9).
660
-
661
- Mechanism, not policy, in `opens_thread`'s exact shape and for its
662
- reason: core/loop.py partitions a response by asking, so the file
663
- that decides what runs concurrently names no tool.
664
-
665
- False for an unknown tool, which is what an MCP tool registered at
666
- runtime is until it says otherwise -- and the answer that keeps a
667
- stranger's tool sequential, which is the safe one here.
668
- """
669
- spec = self._tools.get(tool_name)
670
- return bool(spec is not None and spec.parallel)
671
-
672
- def request_kind(self, tool_name: str) -> str:
673
- """Which kind of question approving this tool asks (§23).
674
-
675
- Mechanism, not policy, exactly like grant_scope above: the loop
676
- asks rather than knowing that spawn_subagent is special.
677
- """
678
- spec = self._tools.get(tool_name)
679
- return spec.request_kind if spec is not None else "approval"
680
-
681
- def grant_policy(self, tool_name: str) -> str:
682
- """How far approving this tool BY NAME goes (§25 R13).
683
-
684
- Mechanism, not policy, in the same shape as grant_scope and
685
- request_kind above: the two callers ask rather than each keeping
686
- their own idea of which names are special. That is the whole
687
- substance of #67 -- `grantable()` was genuinely shared while the
688
- exclusion list lived in one caller's module, so the §18 sign-off
689
- and the §25 pipeline held different ideas of what a grant covers.
690
-
691
- An undeclared `mcp__*` tool is GRANT_ANYWHERE. Those names exist
692
- only at connection time, they are the picker's real population,
693
- and R1's argument -- the tool's own description is the whole of
694
- informed consent, because MCP exposes no read-only/write metadata
695
- -- was written about exactly them.
696
-
697
- Anything else undeclared is GRANT_NEVER, failing closed.
698
- assert_grant_policy_declared() makes that branch unreachable for
699
- statically registered tools, exactly as D24's import check makes
700
- _default_for_unknown_tool's unreachable for them.
701
- """
702
- spec = self._tools.get(tool_name)
703
- declared = getattr(spec, "grant_policy", None)
704
- if declared is not None:
705
- return declared
706
- return GRANT_ANYWHERE if tool_name.startswith("mcp__") else GRANT_NEVER
707
-
708
- def request_payload(
709
- self, tool_name: str, params: dict,
710
- context: Optional["ToolContext"] = None,
711
- ) -> dict:
712
- """Extra payload fields for that question, or {}.
713
-
714
- Never raises, for approval_notice's reason: a tool whose payload
715
- callable blows up must still be answerable. It degrades to an
716
- empty dict, which for a sign-off means no candidates -- and
717
- interaction.decode intersects the answer with the candidates, so
718
- the safe consequence follows automatically rather than needing a
719
- second rule here.
720
- """
721
- spec = self._tools.get(tool_name)
722
- if spec is None or spec.request_payload is None:
723
- return {}
724
- try:
725
- return dict(spec.request_payload(params, context) or {})
726
- except Exception: # noqa: BLE001 - a broken payload must not block
727
- logger.warning("request_payload for %r failed", tool_name,
728
- exc_info=True)
729
- return {}
730
-
731
- def approval_notice(
732
- self, tool_name: str, params: dict,
733
- context: Optional["ToolContext"] = None,
734
- ) -> Optional[str]:
735
- """Extra text for the approval prompt, or None.
736
-
737
- Never raises: a tool whose notice callable blows up must still be
738
- approvable, because the alternative is a prompt that cannot be
739
- rendered and therefore a call that can never be allowed.
740
- """
741
- spec = self._tools.get(tool_name)
742
- if spec is None or spec.approval_notice is None:
743
- return None
744
- try:
745
- return spec.approval_notice(params, context)
746
- except Exception: # noqa: BLE001 - a broken notice must not block
747
- logger.warning("approval_notice for %r failed", tool_name,
748
- exc_info=True)
749
- return None
750
-
751
- def dispatch(
752
- self, tool_name: str, params: dict,
753
- context: Optional["ToolContext"] = None,
754
- approval_callback=None,
755
- parent_run: Optional["RunInfo"] = None,
756
- response_channel=None,
757
- signoff=None,
758
- memory=None,
759
- activity=None,
760
- call_id=None,
761
- cancel=None,
762
- ) -> dict:
763
- # Unknown-tool guard: ValueError, deliberately NOT ToolCallDenied.
764
- # The two exception types separate "you misnamed it" from "policy
765
- # blocks you". This matters MORE since §15, not less -- runtime
766
- # unregister() makes a stale tool name a reachable state.
767
- if tool_name not in self._tools:
768
- raise ValueError(f"Unknown tool: {tool_name}")
769
-
770
- if not is_tool_allowed(tool_name, context):
771
- # Distinguish the two causes: the model can do something about
772
- # "not available in this context" (pick another tool for this
773
- # task) that it cannot about a global policy denial.
774
- if is_tool_allowed(tool_name, None):
775
- raise ToolCallDenied(
776
- f"{tool_name} is not available in this context")
777
- raise ToolCallDenied(f"{tool_name} is disabled by policy")
778
-
779
- # §32 A7 (#70). BEFORE the approval gate, and that order is the
780
- # whole fix. A call the tool will refuse must report the REAL
781
- # reason, and the approval check would otherwise get there
782
- # first: with the loop no longer asking (because it consulted
783
- # this same predicate), there is no approval_callback here, so
784
- # an unknown agent name came back as "spawn_subagent requires
785
- # approval and was not given" -- a cause that is not the cause,
786
- # and worse than the empty modal it replaced.
787
- #
788
- # RETURNED, not raised. This is the tool's own answer about its
789
- # own call -- the same dict its handler would have returned --
790
- # and ToolCallDenied means policy blocked you, which is a
791
- # different fact the model should be able to tell apart.
792
- #
793
- # Nothing executes past here, so the argument policy below has
794
- # nothing left to protect on this path.
795
- refused = self.refusal_reason(tool_name, params, context)
796
- if refused is not None:
797
- logger.info("%s refused before approval: %s",
798
- tool_name, refused)
799
- # THROUGH THE REDACTOR, like every other result (batch 156,
800
- # A60). This was the one `return` in this function that did
801
- # not, and it is a result path: the success path, the
802
- # handler-exception path and the depth cap all pass the call
803
- # below, and this one went straight out.
804
- #
805
- # IT WAS NOT A THEORETICAL HOLE. Measured (batch 156) through
806
- # this very function: `spawn_subagent` with an `agent_name` of
807
- # `ghp_` plus 36 characters came back as "Unknown agent:
808
- # '<the whole token>' is not one of this harness's agents" --
809
- # the full credential, to the model and to the transcript,
810
- # from a value the model chose. And the harness has a scanner
811
- # for exactly that input: `check_input_policy` BELOW refuses
812
- # the same params with "an argument contains what looks like
813
- # a credential". The refusal returned above it, so both
814
- # scanners were skipped on one path -- §25 (R5) exists
815
- # because "the parameters were chosen by a model reading an
816
- # attacker's web page", and this is where that argument was
817
- # not being applied.
818
- #
819
- # THE SINK AND NOT THE PRODUCER, which is the same split the
820
- # handler containment two inches below uses: a refusal string
821
- # is written by whichever tool owns the gate, and this is the
822
- # one place that covers the next one. `tools/base.py` still
823
- # asks producers not to echo a value, for a reason that
824
- # survives this change and is stated there.
825
- return check_output_policy(tool_name, {"error": refused})
826
-
827
- spec = self._tools[tool_name]
828
-
829
- if self.approval_needed(tool_name, params, context):
830
- approved = approval_callback(tool_name, params) if approval_callback else False
831
- if not approved:
832
- raise ToolCallDenied(f"{tool_name} requires approval and was not given")
833
-
834
- # §25 (R5): content policy on the ARGUMENTS, the mirror of the
835
- # check_output_policy call below. Runs AFTER the approval check,
836
- # deliberately -- approving a call does not authorise smuggling a
837
- # credential out inside it, and a user who just clicked Allow is
838
- # the last person positioned to notice that the parameters were
839
- # chosen by a model reading an attacker's web page.
840
- refusal = check_input_policy(tool_name, params)
841
- if refusal is not None:
842
- logger.warning("%s", refusal)
843
- raise ToolCallDenied(refusal)
844
-
845
- # §18: hand the live run-scoped values to handlers that declared
846
- # them (spawn_subagent wants both). Handlers that didn't are
847
- # called with params only -- the twelve pre-§18 tools are
848
- # byte-for-byte untouched by this.
849
- # An explicit map, not a ternary. The two-value version silently
850
- # mis-injected any THIRD name: _declared_injections would advertise
851
- # it and dispatch would hand it parent_run, a wrong-typed value
852
- # with no error at register or dispatch time. A name added to
853
- # _INJECTABLE_PARAMS and forgotten here now raises immediately.
854
- available = {
855
- "parent_context": context,
856
- "parent_run": parent_run,
857
- "response_channel": response_channel,
858
- "signoff": signoff,
859
- "memory": memory,
860
- "activity": activity,
861
- "call_id": call_id,
862
- "cancel": cancel,
863
- }
864
- injected = {p: available[p] for p in self._injectable.get(tool_name, ())}
865
- try:
866
- # §31 (H2). A BUDGET_COMPUTE tool is a pure function of its
867
- # params with nothing bounding it from the inside, so it runs
868
- # in a child this call can actually kill. Everything else is
869
- # called exactly as before -- an io tool carries its own
870
- # bound and a human one blocks on a person, and an outer
871
- # clock over either would stop WAITING without stopping the
872
- # work, which is the mechanism H7 rejects.
873
- #
874
- # The branch is HERE, inside the containment try and at the
875
- # one place a handler is ever invoked, rather than inside the
876
- # six tools. A tool that isolated itself could not be called
877
- # plainly by a test, and every test in test_math_tools.py
878
- # would then be measuring the transport instead of the maths.
879
- # (The count that used to stand here said 123 and was 131 by
880
- # the time anyone checked, and 141 after batch 131 -- the
881
- # ARGUMENT never needed the number, which is why it is gone
882
- # rather than corrected.)
883
- #
884
- # `injected` is not passed: nothing in _INJECTABLE_PARAMS
885
- # survives a process boundary, and assert_budget_declared
886
- # rejects the pairing at import so this cannot silently drop
887
- # a value a handler wanted.
888
- if spec.budget == BUDGET_COMPUTE:
889
- result = isolation.run_isolated(
890
- spec.handler, params, config.TOOL_COMPUTE_TIMEOUT_S,
891
- tool_name=tool_name)
892
- else:
893
- result = spec.handler(params, **injected)
894
- except Exception as e: # noqa: BLE001 -- contained on purpose
895
- # A raising tool used to take the whole run down with it. In
896
- # chat that is a lost turn; in the research pipeline it is a
897
- # ten-pass run flipped to status='failed' by one transient
898
- # network error inside one pass, which is how arxiv_search's
899
- # http:// redirect presented.
900
- #
901
- # Contained HERE, at the boundary that turns a handler into a
902
- # tool result, rather than in each tool: this covers the
903
- # twelve built-ins, every future one, and every MCP server,
904
- # which is third-party code that can raise anything at all.
905
- # The two tools that had their own raise-after-retries path
906
- # were also changed to return, so the model gets a specific
907
- # message rather than this generic wrapper -- this is the
908
- # backstop, not the primary route.
909
- #
910
- # ToolCallDenied does NOT reach here: every raise of it is
911
- # above, before the handler runs. That is deliberate -- a
912
- # policy denial is the caller's to handle (core/loop.py turns
913
- # it into an error result with its own wording), not something
914
- # to flatten into a tool failure.
915
- #
916
- # logger.exception, not warning: the traceback is how a real
917
- # bug in a handler stays findable now that it no longer
918
- # crashes the process. The MODEL sees only the message.
919
- #
920
- # This line fires BEFORE check_output_policy below, and for a
921
- # long time that meant the unredacted message and traceback
922
- # were on disk while the result the model saw was clean --
923
- # the exact threat the comment below describes, bypassed for
924
- # the one sink it did not name (#132). The log is redacted at
925
- # the FORMATTER now (logging_setup._RedactingFormatter), so
926
- # this ordering is no longer load-bearing and no call site
927
- # has to remember.
928
- logger.exception("Tool %s raised; returning it as an error "
929
- "result.", tool_name)
930
- result = {"error": f"{tool_name} failed: {e}"}
931
- # ROADMAP §8 secret redaction -- a post-call filter, not a pre-call
932
- # gate. Load-bearing: §15's own Rev. 2 sketch dropped this line,
933
- # which would have deleted the redaction layer outright in the
934
- # section whose subject is tightening permissions.
935
- #
936
- # The error path above goes through it TOO, and must: an exception
937
- # message routinely carries the request that produced it, and for
938
- # an HTTP client that means a URL with an API key in the query
939
- # string. Redacting only the success path would make a failing
940
- # tool the way secrets escape.
941
- #
942
- # Scans EVERY value now, not an allowlist of keys (#47): the two
943
- # search tools return `results` and were never covered by the set
944
- # that held `result`.
945
- result = check_output_policy(tool_name, result)
946
- return result
947
-
948
-
949
- registry = ToolRegistry()
950
-
951
- # R13: EVERY static registration declares a grant policy, including the
952
- # tools that are not approval-gated today and so never reach either grant
953
- # path. That is deliberate and is the reason the field is required rather
954
- # than inferred: whether a tool is gated is CONFIG-dependent (a user may
955
- # gate web_search in config.ToolApprovals), so a policy derived from
956
- # today's gating would be answered by whoever edited settings, not by
957
- # whoever registered the tool. Declaring it here keeps the answer
958
- # config-independent and next to the tool it is about.
959
- registry.register(ToolSpec("web_search", web_search.TOOL_SCHEMA, web_search.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
960
- registry.register(ToolSpec("fetch_url", fetch_url.TOOL_SCHEMA, fetch_url.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
961
- registry.register(ToolSpec("get_time", get_time.TOOL_SCHEMA, get_time.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
962
- registry.register(ToolSpec("arxiv_search", arxiv.TOOL_SCHEMA, arxiv.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
963
- registry.register(ToolSpec("symbolic_math", symbolic_math.TOOL_SCHEMA, symbolic_math.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
964
- registry.register(ToolSpec("linear_algebra", linear_algebra.TOOL_SCHEMA, linear_algebra.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
965
- registry.register(ToolSpec("probability_stats", probability_stats.TOOL_SCHEMA, probability_stats.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
966
- registry.register(ToolSpec("discrete_math", discrete_math.TOOL_SCHEMA, discrete_math.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
967
- registry.register(ToolSpec("logic", logic.TOOL_SCHEMA, logic.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
968
- registry.register(ToolSpec("geometry", geometry.TOOL_SCHEMA, geometry.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
969
- # The four param-dependent tools. grantable() already returns False for
970
- # them -- an approval_check means the answer depends on the path or the
971
- # command, so a name-level grant would authorise a call nobody saw -- and
972
- # the policy field says the same thing from the other side. Both are
973
- # checked at both call sites; neither is load-bearing alone.
974
- #
975
- # read/write/edit also carry a refusal_check (§32 A7): any path resolving
976
- # into a PROTECTED_SEGMENTS directory (`.venastine/`) is denied outright,
977
- # pre-approval, so no human is asked a question the tool would refuse
978
- # anyway. The handlers re-test -- the refusal_check is the
979
- # prompt-suppression half, not the enforcement.
980
- registry.register(ToolSpec("read", file_ops.READ_TOOL_SCHEMA, file_ops.read_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("read"), grant_policy=GRANT_NEVER, budget=BUDGET_IO))
981
- # ROADMAP_v3 §81 (IM1, IM6). `read`'s path rules exactly -- the same approval
982
- # check and the same refusal shape -- plus `returns_images`, which keeps it
983
- # off the schema list wherever the image could not reach the model.
984
- registry.register(ToolSpec("view_image", file_ops.VIEW_IMAGE_TOOL_SCHEMA, file_ops.view_image_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("view_image"), grant_policy=GRANT_NEVER, budget=BUDGET_IO, returns_images=True))
985
- registry.register(ToolSpec("write", file_ops.WRITE_TOOL_SCHEMA, file_ops.write_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("write"), grant_policy=GRANT_NEVER, budget=BUDGET_IO))
986
- registry.register(ToolSpec("edit", file_ops.EDIT_TOOL_SCHEMA, file_ops.edit_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("edit"), grant_policy=GRANT_NEVER, budget=BUDGET_IO))
987
- # §28: approval_notice carries the capability profile into the prompt.
988
- # The command text is already in the params; what it does not show is
989
- # WHERE it runs, and "cat /etc/shadow" does not look like a host read.
990
- registry.register(ToolSpec("shell", shell.TOOL_SCHEMA, shell.run, approval_check=shell._shell_approval_check, approval_notice=shell._shell_approval_notice, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command"))
991
- # ROADMAP_v3 §49 (SS11, SS16, SS17). Five tools over background and monitor
992
- # sessions, and the two that START one are `shell` with a lifetime: the same
993
- # approval_check OBJECT, because a session runs a command and a second gate
994
- # over it would be the ratchet G3 removed -- _assert_shell_mode_exemption
995
- # below requires that identity, which is what ties the missing
996
- # `tool_approvals` field to the gate that replaces it.
997
- #
998
- # available_check rather than a permission: all seven are hidden wherever
999
- # nothing will wake the run when a session reports (a research pass, any run
1000
- # outside a chat turn or a subagent). A start is refused there too, by
1001
- # refusal_check before any approval prompt and again in the handler -- but
1002
- # advertising a tool that can only be refused is the D24 defect, and under
1003
- # `shell_approval_mode: never` nothing else would stop a pass calling it.
1004
- # SS14: the three START tools open a session, so their lines are the ones a
1005
- # reader can click. `shell_output`, `shell_kill` and `shell_input` name a
1006
- # session they did not create -- arming those would put the same target on
1007
- # four lines, and on twenty for an interactive session that is typed into
1008
- # twenty times, which makes "the line that started it" stop meaning
1009
- # anything.
1010
- registry.register(ToolSpec("shell_background", shell_sessions.BACKGROUND_TOOL_SCHEMA, shell_sessions.background_run, approval_check=shell._shell_approval_check, approval_notice=shell_sessions.background_notice, refusal_check=shell_sessions.background_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command", opens_session=True))
1011
- registry.register(ToolSpec("shell_monitor", shell_sessions.MONITOR_TOOL_SCHEMA, shell_sessions.monitor_run, approval_check=shell._shell_approval_check, approval_notice=shell_sessions.monitor_notice, refusal_check=shell_sessions.monitor_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command", opens_session=True))
1012
- # Slice 2. Its gate is NOT shell's: `_interactive_approval_check` asks
1013
- # about the session being opened rather than about its first line, because
1014
- # the yes covers every line that follows (SS29, SS32). The assert below
1015
- # holds it to that function by identity, exactly as it holds the three
1016
- # above to theirs.
1017
- registry.register(ToolSpec("shell_interactive", shell_sessions.INTERACTIVE_TOOL_SCHEMA, shell_sessions.interactive_run, approval_check=shell._interactive_approval_check, approval_notice=shell_sessions.interactive_notice, refusal_check=shell_sessions.interactive_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command", opens_session=True))
1018
- # Typing into a session is NOT a start, so `opens_session` is False: one
1019
- # session would otherwise be the target of every line sent to it, which is
1020
- # the same reason `shell_output` and `shell_kill` are not armed. It keeps
1021
- # an approval_check because SS29's exception -- a line naming a protected
1022
- # segment -- still asks, and a control key never does (SS30).
1023
- registry.register(ToolSpec("shell_input", shell_sessions.INPUT_TOOL_SCHEMA, shell_sessions.input_run, approval_check=shell_sessions.input_approval_check, approval_notice=shell_sessions.input_notice, refusal_check=shell_sessions.input_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, headline_param="text"))
1024
- # Reading and stopping need no approval (SS11): they act only on sessions
1025
- # this conversation started, which someone already approved.
1026
- registry.register(ToolSpec("shell_sessions", shell_sessions.SESSIONS_TOOL_SCHEMA, shell_sessions.sessions_run, available_check=shell_sessions.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1027
- registry.register(ToolSpec("shell_output", shell_sessions.OUTPUT_TOOL_SCHEMA, shell_sessions.output_run, available_check=shell_sessions.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1028
- registry.register(ToolSpec("shell_kill", shell_sessions.KILL_TOOL_SCHEMA, shell_sessions.kill_run, available_check=shell_sessions.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1029
- registry.register(ToolSpec("load_skill", load_skill.TOOL_SCHEMA, load_skill.run, available_check=load_skill.has_skills, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1030
- registry.register(ToolSpec("pin", pin.TOOL_SCHEMA, pin.run, available_check=pin.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1031
- # §21/D26 restored (#89): the mirror of pin. Same gating posture (ungated,
1032
- # thread-scoped, visible), same availability, and it is what makes D26's
1033
- # "reversible" premise true rather than aspirational.
1034
- registry.register(ToolSpec("unpin", pin.UNPIN_TOOL_SCHEMA, pin.unpin_run, available_check=pin.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1035
- # §23 slice 2. No request_kind: this tool does NOT ask through the approval
1036
- # bridge -- it is ungated (J12), so the bridge never fires for it. It names
1037
- # `response_channel` in its handler signature and asks with it directly,
1038
- # which is what _INJECTABLE_PARAMS was generalised for.
1039
- registry.register(ToolSpec("ask_user", ask_user.TOOL_SCHEMA, ask_user.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_HUMAN))
1040
- # §23 slice 2. Ungated and needs no channel (J9): it asks nobody, so a
1041
- # headless research pass can keep a checklist. `memory` is injected by
1042
- # signature inspection, as it is for `pin`.
1043
- registry.register(ToolSpec("todo_write", todo.TOOL_SCHEMA, todo.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1044
- registry.register(ToolSpec(
1045
- "remember", remember.TOOL_SCHEMA, remember.run,
1046
- available_check=remember.available,
1047
- # D26 gates this in config.ToolApprovals; the notice is what makes
1048
- # the gate worth having, since "remember wants to run" tells the
1049
- # user nothing they can act on.
1050
- approval_notice=remember.approval_notice,
1051
- # ROADMAP_v2 §21b (M17), moved here from the pipeline's own module by
1052
- # R13 because the argument was never pipeline-specific. `remember`
1053
- # has no approval_check, so it is grantable by R2's mechanical rule
1054
- # and would appear in both grant paths -- and one --grant remember at
1055
- # launch would let ten unattended passes, reading attacker-controlled
1056
- # web pages, write durable cross-session memories. §21's D26
1057
- # consequence 1 says research passes must not be able to do that.
1058
- #
1059
- # NEVER rather than SIGNOFF_ONLY: D26 consequence 1 is about what a
1060
- # SUBAGENT can do, not only a pass, and the §18 sign-off hands the
1061
- # child its set for the rest of the turn. A durable cross-session
1062
- # write is exactly the authority that outlives the turn somebody was
1063
- # watching.
1064
- grant_policy=GRANT_NEVER,
1065
- budget=BUDGET_IO))
1066
- registry.register(ToolSpec(
1067
- "read_project_doc", project_docs.READ_TOOL_SCHEMA, project_docs.read_run,
1068
- grant_policy=GRANT_ANYWHERE,
1069
- budget=BUDGET_IO))
1070
- registry.register(ToolSpec(
1071
- "write_project_doc", project_docs.WRITE_TOOL_SCHEMA, project_docs.write_run,
1072
- # Gated in config.ToolApprovals; the notice names the destination and
1073
- # the size, because "write_project_doc wants to run" is not a decision
1074
- # anyone can make. The content itself is not repeated here -- /init has
1075
- # already shown it as a diff, and several kilobytes of markdown inside
1076
- # a modal buries the one line that says which file changes.
1077
- approval_notice=project_docs.approval_notice,
1078
- # #133. SIGNOFF_ONLY is the one place the two paths differ, and the
1079
- # difference is argued from ATTENDEDNESS rather than from the tool.
1080
- #
1081
- # Against an unattended run: one --grant-tools write_project_doc
1082
- # authorises 15 document names, resolved to paths by the tool and
1083
- # overwritten in place, for the rest of a ten-pass run that is reading
1084
- # attacker-controlled web pages -- with no diff and no second
1085
- # question. One of them is the root AGENTS.md, which config_loader
1086
- # injects into every agent that opts in, so it reaches M17's own
1087
- # justification for excluding `remember` ("outlives the conversation
1088
- # and silently shapes ones you have not started yet") through a
1089
- # different tool.
1090
- #
1091
- # For the §18 sign-off it stays offered: a human is answering in the
1092
- # moment, about one named agent, for one turn, and the notice above
1093
- # names the destination and the size. That is the per-call consent a
1094
- # gate is for, which is also why --attended was never the mode at
1095
- # issue in #133.
1096
- #
1097
- # OFFERED TO NOTHING THAT SHIPS, measured in batch 139 and ruled
1098
- # deliberate (TECHNICAL_DEBT 83). This is the only
1099
- # GRANT_SIGNOFF_ONLY registration in the registry, and no agent in
1100
- # agents/builtin/ declares `write_project_doc` -- so the policy
1101
- # value above is correct and has no shipped instance. The sign-off
1102
- # picker is for operator-configured installs: an agent that
1103
- # declines to narrow `allowed_tools`, or one naming a gated tool
1104
- # outright. Do not "fix" this by adding the tool to a shipped
1105
- # agent -- `writer` is the only plausible candidate and its own
1106
- # file refuses write capability in two places, so that is a
1107
- # decision reversal and wants its own batch.
1108
- grant_policy=GRANT_SIGNOFF_ONLY,
1109
- budget=BUDGET_IO))
1110
- registry.register(ToolSpec(
1111
- "spawn_subagent", subagent_tool.TOOL_SCHEMA, subagent_tool.run,
1112
- # §23 AC1b. Approving a spawn is not a yes/no any more: the request
1113
- # carries the candidate tools and the answer carries the subset.
1114
- request_kind="subagent_signoff",
1115
- request_payload=subagent_tool.request_payload,
1116
- # §32 A7 (#70). The loop consults this before deciding to ask, so
1117
- # a spawn that will be refused anyway does not first produce a
1118
- # sign-off modal -- which for an unknown agent name was a question
1119
- # with an empty notice and nothing to tick.
1120
- refusal_check=subagent_tool.refusal_reason,
1121
- # Approving a spawn IS the subagent sign-off (§18 S1): it authorises
1122
- # the child's whole approval-gated tool set for the rest of the turn,
1123
- # which is why grant_scope is "run" -- a second spawn in the same turn
1124
- # reuses the answer rather than re-asking.
1125
- grant_scope="run",
1126
- approval_notice=subagent_tool.approval_notice,
1127
- # ROADMAP_v2 §25 (R4), moved here from the pipeline's own module by
1128
- # R13. spawn_subagent is grantable in the ordinary sense -- it has no
1129
- # approval_check, so approving the NAME is meaningful consent. It is
1130
- # excluded for what that consent then authorises: approving a spawn IS
1131
- # the §18 subagent sign-off, handing the child its whole gated set.
1132
- #
1133
- # NEVER, not SIGNOFF_ONLY, and #67 is why. R4's argument is ABOUT the
1134
- # sign-off -- it names it as the thing pre-granting would duplicate --
1135
- # so a policy that excluded it from the pipeline while leaving it in
1136
- # the sign-off would exempt the one path the argument was written
1137
- # against. A ticked spawn_subagent lets the child spawn ANY agent with
1138
- # any task, unprompted, because the grant carries no subject; see
1139
- # R14's condition in tools/context.py recall_signoff.
1140
- #
1141
- # Nothing is lost: research passes have never been able to delegate,
1142
- # and in chat a spawn is still asked about per subject through the
1143
- # J8-keyed memo, which is the mechanism that actually shows the user
1144
- # which agent they are authorising.
1145
- grant_policy=GRANT_NEVER,
1146
- budget=BUDGET_HUMAN,
1147
- # TECHNICAL_DEBT 13, batch 110. The asymmetry `load_skill` did not
1148
- # have: with no spawnable agent discovered, this tool's only possible
1149
- # answer is `Unknown agent`, and until batch 51 shipped two of them
1150
- # that was every default install. See has_agents for why it reads the
1151
- # catalog function rather than the roster.
1152
- available_check=subagent_tool.has_agents,
1153
- # §47. The only tool that does, so far: the child runs in a thread
1154
- # of its own, which is what makes `▸ spawn_subagent` a line a
1155
- # reader can open.
1156
- opens_thread=True,
1157
- # §47 slice 8 (NA9). The only tool that declares it, and the reason
1158
- # the slice exists: a model emitting three spawns in one response
1159
- # meant three runs one after another, so the parallelism a subagent
1160
- # swarm is FOR was spent. Safe to declare because everything the
1161
- # child's run touches was made concurrency-safe first -- the budget's
1162
- # lock, the serialised question, the per-future authorization -- which
1163
- # is why this one field is the last line of the section rather than
1164
- # the first.
1165
- parallel=True,
1166
- ))
1167
-
1168
- # WHICH gate each shell-mode-exempt tool must carry, by identity. A mapping
1169
- # rather than the single name this started as, because slice 2 added a tool
1170
- # whose gate is deliberately a different function: `shell_interactive` is
1171
- # governed by `shell_approval_mode` like the rest, but asks its question
1172
- # about the SESSION rather than about one command (SS29, SS32). Naming the
1173
- # expected gate per tool keeps the check as strict as identity ever was and
1174
- # makes it stricter in one way -- a name added to APPROVAL_BY_SHELL_MODE
1175
- # with no entry here now fails, where before any shell gate would have done.
1176
- _SHELL_MODE_GATES = {
1177
- "shell": shell._shell_approval_check,
1178
- "shell_background": shell._shell_approval_check,
1179
- "shell_monitor": shell._shell_approval_check,
1180
- "shell_interactive": shell._interactive_approval_check,
1181
- }
1182
-
1183
-
1184
- def _assert_shell_mode_exemption(tools: dict) -> None:
1185
- """SS16: every tool exempt from `tool_approvals` carries the shell gate.
1186
-
1187
- `security.permissions.APPROVAL_BY_SHELL_MODE` is a HOLE in D24's
1188
- import-time check -- the names in it may omit an approvals field -- and
1189
- the whole argument for the hole is that `shell_approval_mode` decides
1190
- their approval instead. That argument is true only while they actually
1191
- go through that gate, so the exemption is tied to it by IDENTITY here
1192
- rather than by trusting the registration to have done it: a tool that
1193
- lost its approval_check, or was given one of its own, would otherwise
1194
- be a command-running tool with no approval question anywhere and
1195
- nothing to say so. Raises for D24's reason -- the failure it guards
1196
- against is invisible at runtime.
1197
- """
1198
- broken = []
1199
- for name in sorted(APPROVAL_BY_SHELL_MODE):
1200
- spec = tools.get(name)
1201
- expected = _SHELL_MODE_GATES.get(name)
1202
- if spec is None:
1203
- broken.append(f"{name} is not registered")
1204
- elif expected is None:
1205
- broken.append(f"{name} has no declared gate in "
1206
- f"_SHELL_MODE_GATES")
1207
- elif spec.approval_check is not expected:
1208
- broken.append(f"{name} does not use {expected.__name__}")
1209
- if broken:
1210
- raise RuntimeError(
1211
- "These tools are exempt from tool_approvals because "
1212
- "shell_approval_mode is supposed to gate them, and it does not: "
1213
- f"{broken}. Either register them with the gate "
1214
- "_SHELL_MODE_GATES names, or take them out of "
1215
- "security.permissions.APPROVAL_BY_SHELL_MODE and give them a "
1216
- "tool_approvals field (ROADMAP_v3 §49, SS16)."
1217
- )
1218
-
1219
-
1220
- _assert_shell_mode_exemption(registry._tools)
1221
- # D24: fail loudly at import if any statically registered tool has no
1222
- # declared permission/approval field. Runs here rather than in
1223
- # security/permissions.py because that file must not import the registry
1224
- # (the dependency runs tools -> security, not both ways). Runs AFTER the
1225
- # registrations above and before any dynamic mcp__* registration, which
1226
- # is exactly the set the check is meant to cover.
1227
- assert_permissions_declared(registry._tools)
1228
- # R13, the same trade one question over: fail loudly at import if any
1229
- # statically registered tool has no usable grant policy. Same placement
1230
- # and same reason -- after the static registrations, before any dynamic
1231
- # mcp__* one, which is exactly the set that can carry a declaration.
1232
- assert_grant_policy_declared(registry._tools, registry._tools)
1233
- # H1, the same trade one question further over: fail loudly at import if
1234
- # any statically registered tool has not said what a call to it is
1235
- # allowed to cost. Same placement and the same reason as the two above.
1236
- #
1237
- # `_injectable` is passed because BUDGET_COMPUTE is not only a policy --
1238
- # it routes the call through a process boundary that no injected value
1239
- # survives -- so the two declarations have to be checked against each
1240
- # other rather than each on its own.
1241
- assert_budget_declared(registry._tools, registry._tools,
1242
- registry._injectable)
1
+ """
2
+ tools/registry.py
3
+
4
+ MECHANISM, not policy: the single choke point every tool call passes
5
+ through. This is the only file that imports both security.permissions and
6
+ the individual tool modules; tool modules never import permissions
7
+ themselves.
8
+
9
+ ROADMAP_v2 §15:
10
+ * every entry point takes an optional ToolContext, threaded from
11
+ core/loop.py, and hands it to the policy functions ("stricter wins",
12
+ D14 -- see security/permissions.py for the composition rule);
13
+ * approval_needed() is where the tool's own dynamic approval_check is
14
+ OR'd with the config/context lookup, so dispatch() and the loop's
15
+ permission bridge cannot diverge (see its docstring);
16
+ * schemas() advertises only what is actually callable;
17
+ * register()/unregister() work at runtime (D15) for MCP (§17);
18
+ * assert_permissions_declared() runs at import, after static
19
+ registration (D24).
20
+ """
21
+
22
+ import inspect
23
+ import logging
24
+ from typing import TYPE_CHECKING, Optional
25
+
26
+ import config
27
+ from agents import subagent_tool
28
+ from safety.policy_enforcement import (
29
+ check_input_policy,
30
+ check_output_policy,
31
+ param_digest,
32
+ redacted_values,
33
+ )
34
+ from security.permissions import (
35
+ APPROVAL_BY_SHELL_MODE,
36
+ assert_permissions_declared,
37
+ is_tool_allowed,
38
+ requires_approval,
39
+ )
40
+ from tools import isolation
41
+ from tools.base import (
42
+ BUDGET_COMPUTE,
43
+ BUDGET_HUMAN,
44
+ BUDGET_IO,
45
+ GRANT_ANYWHERE,
46
+ GRANT_NEVER,
47
+ GRANT_SIGNOFF_ONLY,
48
+ OPENS_CALL,
49
+ OPENS_SESSION,
50
+ OPENS_THREAD,
51
+ ToolSpec,
52
+ assert_budget_declared,
53
+ assert_grant_policy_declared,
54
+ )
55
+ from tools.builtin import (
56
+ arxiv,
57
+ ask_user,
58
+ discrete_math,
59
+ fetch_url,
60
+ file_ops,
61
+ geometry,
62
+ get_time,
63
+ linear_algebra,
64
+ load_skill,
65
+ logic,
66
+ pin,
67
+ probability_stats,
68
+ project_docs,
69
+ remember,
70
+ shell,
71
+ shell_sessions,
72
+ symbolic_math,
73
+ todo,
74
+ web_search,
75
+ )
76
+ from tools.builtin._net_common import NetworkLimitReached
77
+
78
+ logger = logging.getLogger(__name__)
79
+
80
+ if TYPE_CHECKING: # pragma: no cover - typing only
81
+ from tools.context import RunInfo, ToolContext
82
+
83
+ # Handler parameter names dispatch() will inject, by signature inspection
84
+ # (ROADMAP_v2 §18). A tool handler that declares one of these receives the
85
+ # live value; handlers that don't are called with params only. Generalised
86
+ # so §23's response-channel tools can add a third name later without
87
+ # touching dispatch() again.
88
+ _INJECTABLE_PARAMS = (
89
+ # §23 renamed permission_channel -> response_channel: it is no longer
90
+ # permission-specific, and a tool that needs to ask a human anything
91
+ # receives the same object the loop asks through.
92
+ "parent_context", "parent_run", "response_channel",
93
+ # §23 AC1b: the approved SUBSET from a subagent sign-off. The comment
94
+ # above anticipated §23's tools adding a name here without reopening
95
+ # dispatch(); this is that name.
96
+ "signoff",
97
+ # ROADMAP_v2 §21: the live ConversationMemory, for `pin`. The
98
+ # comment above anticipated a third name arriving without touching
99
+ # dispatch() again; this is it.
100
+ "memory",
101
+ # Batch 59: the core/agent_activity.py sink, for spawn_subagent. A
102
+ # shell watching the agent stack has to learn about a run that
103
+ # happens INSIDE a tool call, which is the one place a LoopEvent
104
+ # cannot reach -- see that module for why. Injected rather than
105
+ # threaded through params because it is a run-scoped value, exactly
106
+ # like response_channel beside it.
107
+ "activity",
108
+ # ROADMAP_v3 §61 (CN7): the turn's CancelToken, for spawn_subagent. A
109
+ # child run is the parent's turn continuing, so stopping the parent
110
+ # stops it -- and the only way a value reaches a run that happens
111
+ # INSIDE a tool call is this list, which is `activity`'s own argument
112
+ # one line up.
113
+ "cancel",
114
+ # ROADMAP_v2 §47: the model's own id for THIS call. A tool that
115
+ # creates something durable can then record which call created it,
116
+ # which is what lets one line in a transcript find one row in the
117
+ # database when a turn made three of them. Injected rather than put
118
+ # in params, twice over: params are the MODEL'S, parsed from its
119
+ # tool call, and a model that could write its own call id could
120
+ # claim a line it did not make.
121
+ "call_id",
122
+ )
123
+
124
+
125
+ class ToolCallDenied(Exception):
126
+ """Raised when policy blocks a tool call outright, or an approval was
127
+ required and not given."""
128
+
129
+
130
+ class ToolRegistry:
131
+ def __init__(self) -> None:
132
+ self._tools: dict[str, ToolSpec] = {}
133
+ # name -> the subset of _INJECTABLE_PARAMS the handler declares.
134
+ # Cached at register() so dispatch() never re-inspects per call.
135
+ self._injectable: dict[str, tuple] = {}
136
+
137
+ def register(self, spec: ToolSpec) -> None:
138
+ self._tools[spec.name] = spec
139
+ self._injectable[spec.name] = self._declared_injections(spec.handler)
140
+
141
+ @staticmethod
142
+ def _declared_injections(handler) -> tuple:
143
+ """Which injectable run-scoped values this handler wants. A
144
+ handler opts in simply by naming a parameter (e.g.
145
+ `def run(params, parent_context)`); everything else stays a
146
+ params-only call so the existing twelve tools are untouched."""
147
+ try:
148
+ names = set(inspect.signature(handler).parameters)
149
+ except (TypeError, ValueError): # builtins / un-introspectable
150
+ return ()
151
+ return tuple(p for p in _INJECTABLE_PARAMS if p in names)
152
+
153
+ def unregister(self, tool_name: str) -> None:
154
+ """Runtime removal (D15). An MCP server disconnecting drops its
155
+ tools mid-session, so a name that was valid a moment ago becomes
156
+ a reachable state rather than a programmer error -- which is why
157
+ dispatch() keeps its unknown-tool guard.
158
+
159
+ Idempotent: removing an absent name is not an error, because
160
+ disconnect handling can run more than once for the same server.
161
+ """
162
+ self._tools.pop(tool_name, None)
163
+ self._injectable.pop(tool_name, None)
164
+
165
+ def _advertised(self, name: str, spec, context,
166
+ images: bool = False) -> bool:
167
+ """The two §15 filters, shared by schemas() and
168
+ headless_hidden(): policy allowability plus the tool's own
169
+ "nothing to act on" signal -- and, since ROADMAP_v3 §81 (IM6), a
170
+ third: a tool whose result carries an image is offered only where
171
+ the caller says images can be delivered.
172
+
173
+ `images` DEFAULTS FALSE, so a caller that never heard of images
174
+ hides such a tool rather than offering one whose result the model
175
+ could not see. The loop is the one caller that knows the answer,
176
+ and it passes it."""
177
+ if not is_tool_allowed(name, context):
178
+ return False
179
+ if spec.available_check is not None and not spec.available_check():
180
+ return False
181
+ if spec.returns_images and not images:
182
+ return False
183
+ return True
184
+
185
+ def _answered_by_grant(self, tool_name: str, granted) -> bool:
186
+ """Whether a pre-flight grant has ALREADY answered this tool's
187
+ approval question (§25 R15).
188
+
189
+ `callable_only` below asks "can anything ask?". Since §25 that is
190
+ the wrong question by itself: a grant is an answer given early, so
191
+ the question is "can anything answer FOR THIS TOOL?" -- and a
192
+ granted tool is answerable with no channel at all. #156 is the gap
193
+ between those two sentences: `--grant-tools X` with no `--attended`
194
+ built a grant the enforcement path honoured and the advertisement
195
+ path never saw, so the model was never told the tool existed and
196
+ never emitted the call.
197
+
198
+ TWO checks, and both are RE-derived here rather than trusted from
199
+ the set -- the same discipline core/loop.py applies before honouring
200
+ a grant, because a stale or hand-built `RunInfo` must not widen what
201
+ is advertised any more than it can widen what is dispatched:
202
+
203
+ grantable() R2. A tool deciding approval from its PARAMS was
204
+ never consented to by name, so a grant naming one
205
+ answers nothing.
206
+ grant_policy R13, and it must be `== GRANT_ANYWHERE` rather than
207
+ `!= GRANT_NEVER`. Both callers of this reach it only
208
+ when the run is HEADLESS, and headless is precisely
209
+ the unattended case GRANT_SIGNOFF_ONLY exists to
210
+ exclude: R13 admits `write_project_doc` to the §18
211
+ sign-off because a human is answering in the moment
212
+ about one named agent, and refuses it to ten
213
+ unattended passes on one launch-time tick. A
214
+ headless run has no human answering in the moment,
215
+ so the looser test would readmit it exactly where
216
+ the argument was written against.
217
+
218
+ THIS IS THE SAME PREDICATE `candidates()` USES, and deliberately so.
219
+ That function decides what may be OFFERED to an unattended run and
220
+ this one decides what a grant then makes VISIBLE to it -- one
221
+ question, so one answer. Written `!= GRANT_NEVER` first, which let
222
+ `write_project_doc` through here while `candidates()` refused it:
223
+ #67/#133's own shape, reappearing inside the batch that generalised
224
+ it. Neither the CLI nor the TUI nor a subagent sign-off can put a
225
+ SIGNOFF_ONLY name into a headless grant today, so nothing was
226
+ reachable -- but "unreachable" is a fact about the callers, and this
227
+ is a claim about the policy.
228
+
229
+ Shared by schemas() and headless_hidden() rather than written out
230
+ twice -- those two must agree about what is hidden, and #67/#133
231
+ are what a shared mechanism with a duplicated policy costs.
232
+ """
233
+ return (bool(granted)
234
+ and tool_name in granted
235
+ and self.grantable(tool_name)
236
+ and self.grant_policy(tool_name) == GRANT_ANYWHERE)
237
+
238
+ def is_advertised(
239
+ self, tool_name: str, context: Optional["ToolContext"] = None,
240
+ callable_only: bool = False,
241
+ granted: Optional[set] = None,
242
+ images: bool = False,
243
+ ) -> bool:
244
+ """Whether schemas() would advertise this tool right now.
245
+
246
+ THE WHOLE ADVERTISEMENT QUESTION IN ONE PLACE, and the reason
247
+ is one method up: _answered_by_grant is shared by schemas()
248
+ and headless_hidden() because "those two must agree about
249
+ what is hidden, and #67/#133 are what a shared mechanism with
250
+ a duplicated policy costs". #68 is the same sentence with a
251
+ third party to the agreement -- prompts.system_prompts's
252
+ catalogs, whose prose INSTRUCTS the model to call a tool.
253
+
254
+ That third caller asked `is_allowed(name, context)` instead,
255
+ which is POLICY: it answers "is this tool permitted", not
256
+ "can this run call it". A research pass is headless, so
257
+ spawn_subagent is permitted, hidden from the schema list, and
258
+ named in the run's own headless_hidden() warning -- while the
259
+ prompt told the model to spawn one. The harness stated the
260
+ contradiction to its log and to the model in the same breath.
261
+
262
+ A PREDICATE RATHER THAN `name in [s["name"] for s in
263
+ schemas()]`: the schema list is built where the run is, and
264
+ the prompt is built before the run exists. Both need the
265
+ answer; only one is in a position to enumerate.
266
+ """
267
+ spec = self._tools.get(tool_name)
268
+ if spec is None:
269
+ return False
270
+ if not self._advertised(tool_name, spec, context, images):
271
+ return False
272
+ return not (callable_only
273
+ and self.approval_needed(tool_name, {}, context)
274
+ and not self._answered_by_grant(tool_name, granted))
275
+
276
+ def schemas(
277
+ self, context: Optional["ToolContext"] = None,
278
+ callable_only: bool = False,
279
+ granted: Optional[set] = None,
280
+ images: bool = False,
281
+ ) -> list[dict]:
282
+ """What gets sent to the LLM's `tools` parameter each call.
283
+
284
+ Only tools that are actually callable are advertised. Advertising
285
+ an uncallable tool is not harmless: the model keeps choosing it,
286
+ burns a turn per attempt, and the only signal is a denial string
287
+ inside a tool result. That is precisely the damage the `fetch_url`
288
+ defect did for its whole life (D24), so §15 fixes the shape as
289
+ well as the instance.
290
+
291
+ Filters, deliberately distinct:
292
+ * is_tool_allowed(name, context) -- policy. Global config AND
293
+ every active layer's restriction.
294
+ * spec.available_check() -- the tool's own "I have nothing to
295
+ act on yet" signal (load_skill with an empty skill catalog).
296
+ * callable_only (§18, user-widened headless callability rule) --
297
+ when the run has no response_channel, a tool whose
298
+ approval_needed() is True for empty params is UNCALLABLE in
299
+ this configuration (nothing can grant the approval), so it is
300
+ not advertised. autoApproved MCP servers and approval-free
301
+ tools pass; approval-gated ones drop. The loop pairs this with
302
+ a once-per-process WARNING naming what was hidden -- no quiet
303
+ invisibility (the fetch_url lesson).
304
+ * granted (§25 R15) -- names a pre-flight grant already answered
305
+ for. Those stay advertised even with no channel, because the
306
+ approval question HAS an answer; see _answered_by_grant.
307
+ * images (ROADMAP_v3 §81, IM6) -- whether an image in a tool
308
+ result can reach the model in this run. A tool that declares
309
+ `returns_images` is dropped when it cannot; see _advertised.
310
+
311
+ WHAT callable_only GUARANTEES, stated because the converse does not
312
+ hold and #158 is what assuming it costs: it means SOME call shape
313
+ is callable, not that every one is. The probe is
314
+ approval_needed(name, {}), and for a tool whose approval_check
315
+ reads the params -- read/write/edit on a path, shell on a command --
316
+ the empty dict is a call the model will never make. `write` resolves
317
+ an empty path inside the workspace, so it survives this filter and
318
+ is then denied per out-of-workspace call. That is deliberate (an
319
+ in-workspace write IS callable headless), but it means a survivor
320
+ of this filter is not a promise about any particular call.
321
+ """
322
+ return [spec.schema for name, spec in self._tools.items()
323
+ if self.is_advertised(name, context, callable_only,
324
+ granted, images)]
325
+
326
+ def headless_hidden(
327
+ self, context: Optional["ToolContext"] = None,
328
+ granted: Optional[set] = None,
329
+ images: bool = False,
330
+ ) -> list[str]:
331
+ """Names that would be advertised with a response_channel but
332
+ are dropped by schemas(callable_only=True) -- i.e. advertised yet
333
+ uncallable headless. The loop logs exactly this list once, so a
334
+ tool hidden by the headless filter is named and explained rather
335
+ than silently absent (the trade this project keeps deciding
336
+ against).
337
+
338
+ Takes `granted` for the same reason schemas() does, and it is not
339
+ cosmetic: this list is what the WARNING names. A granted tool that
340
+ is genuinely callable must not be reported as hidden, or the notice
341
+ whose whole purpose is to stop invisibility starts producing a
342
+ second kind of wrong answer.
343
+ """
344
+ # ADVERTISED ATTENDED AND NOT HEADLESS -- written as the two
345
+ # calls it means rather than as the filter's negation, so the
346
+ # list and the schemas can only disagree if is_advertised
347
+ # disagrees with itself.
348
+ return [
349
+ name for name in self._tools
350
+ if self.is_advertised(name, context, False, granted, images)
351
+ and not self.is_advertised(name, context, True, granted, images)
352
+ ]
353
+
354
+ def image_hidden(
355
+ self, context: Optional["ToolContext"] = None,
356
+ granted: Optional[set] = None,
357
+ ) -> list[str]:
358
+ """ROADMAP_v3 §81 (IM6). Names that would be advertised if images
359
+ could be delivered, and are dropped because they cannot. The loop
360
+ logs exactly this list, once, for headless_hidden()'s reason: a
361
+ tool the user enabled and the model never sees is named and
362
+ explained, not silently absent.
363
+
364
+ Written as the two calls it means, like headless_hidden() above,
365
+ so the list and the schemas can only disagree if is_advertised
366
+ disagrees with itself.
367
+ """
368
+ return [
369
+ name for name in self._tools
370
+ if self.is_advertised(name, context, False, granted, True)
371
+ and not self.is_advertised(name, context, False, granted, False)
372
+ ]
373
+
374
+ def approval_needed(
375
+ self, tool_name: str, params: dict,
376
+ context: Optional["ToolContext"] = None,
377
+ ) -> bool:
378
+ """SINGLE SOURCE OF TRUTH for whether a call needs human approval.
379
+
380
+ Both dispatch() and core/loop.py's permission bridge call this, so
381
+ they can never disagree -- a path-dependent tool must surface a
382
+ permission_request event the user can approve, not be silently
383
+ denied by one check while the other reports no approval needed.
384
+
385
+ §15 makes this an OR rather than an either/or. Previously a tool
386
+ with an approval_check bypassed requires_approval() entirely,
387
+ which would have made agent-level approval_overrides do nothing
388
+ for read/write/edit/shell. Now:
389
+
390
+ tool's own approval_check OR config/context requirement
391
+
392
+ so a context can tighten a lenient default (an agent may demand
393
+ approval for symbolic_math) but can never suppress a check the
394
+ tool itself imposes (an agent declaring `shell: false` does NOT
395
+ skip shell's non-inert-command gate).
396
+ """
397
+ spec = self._tools.get(tool_name)
398
+ tool_level = (
399
+ spec.approval_check(tool_name, params)
400
+ if spec is not None and spec.approval_check is not None
401
+ else False
402
+ )
403
+ return tool_level or requires_approval(tool_name, params, context)
404
+
405
+ def refusal_reason(
406
+ self, tool_name: str, params: dict,
407
+ context: Optional["ToolContext"] = None,
408
+ ) -> Optional[str]:
409
+ """Why this call would be refused before it is asked about,
410
+ or None (§32 A7).
411
+
412
+ The loop asks the registry, the same way it asks whether
413
+ approval is needed at all -- which tools have pre-flight
414
+ conditions is not the loop's knowledge.
415
+
416
+ NOT AN ENFORCEMENT PATH. dispatch() still runs the handler and
417
+ the handler still refuses; this only decides whether a human
418
+ is put to a question whose answer cannot change the outcome.
419
+ A refusal_check that wrongly returned a reason would therefore
420
+ skip a prompt, never widen anything.
421
+ """
422
+ spec = self._tools.get(tool_name)
423
+ if spec is None or spec.refusal_check is None:
424
+ return None
425
+ return spec.refusal_check(params, context)
426
+
427
+ def is_allowed(
428
+ self, tool_name: str, context: Optional["ToolContext"] = None,
429
+ ) -> bool:
430
+ """Whether policy permits this tool at all, in this context.
431
+
432
+ The loop needs this to avoid prompting for a call it will refuse
433
+ regardless. Exposed here rather than importing is_tool_allowed
434
+ into core/loop.py: this file is the only one that talks to
435
+ security.permissions, and that boundary is the point.
436
+ """
437
+ return is_tool_allowed(tool_name, context)
438
+
439
+ def is_registered(self, tool_name: str) -> bool:
440
+ """Whether a tool with this name is currently registered.
441
+
442
+ Policy and registration are different questions (review §19-20
443
+ f12): is_allowed answers "would policy refuse this call", and for
444
+ unknown mcp__ names it says no-refuse by design -- the server may
445
+ connect later. A caller that needs to know whether the tool
446
+ EXISTS (e.g. §19's activation notice, which should flag a
447
+ declared tool that is not callable right now) asks this.
448
+ """
449
+ return tool_name in self._tools
450
+
451
+ def grantable(self, tool_name: str) -> bool:
452
+ """Whether approving this tool BY NAME, before any call exists, is
453
+ meaningful consent (ROADMAP_v2 §25, R2).
454
+
455
+ False for any tool declaring its own approval_check. Those decide
456
+ per call, from the params -- read/write/edit on a path outside the
457
+ workspace, shell on a non-inert command -- so a name-level grant
458
+ would authorise a call the user never saw. `shell` is the sharp
459
+ case: granting the NAME would wave through every command for the
460
+ rest of the run, which is not what anyone ticking a checkbox
461
+ labelled "shell" is agreeing to.
462
+
463
+ A registration-time property, not an inference about params, and
464
+ the same rule for §18's subagent sign-off as for §25's pipeline
465
+ grants -- one mechanism, so the two cannot drift into different
466
+ ideas of what a grant covers. A non-grantable tool is not blocked:
467
+ it falls back to being asked, exactly as it is today.
468
+ """
469
+ spec = self._tools.get(tool_name)
470
+ return spec is not None and spec.approval_check is None
471
+
472
+ def grant_scope(self, tool_name: str) -> Optional[str]:
473
+ """"run" if approving this tool once covers the rest of the run.
474
+
475
+ Mechanism, not policy: the loop asks rather than knowing which
476
+ tools work this way, so the tool name stays out of core/loop.py.
477
+ """
478
+ spec = self._tools.get(tool_name)
479
+ return spec.grant_scope if spec is not None else None
480
+
481
+ def rationale_param(self, tool_name: str) -> Optional[str]:
482
+ """Which param carries the agent's own stated reason,
483
+ or None (§42, RA2).
484
+
485
+ Mechanism, not policy, exactly like grant_scope above: the
486
+ consumer asks rather than testing for the literal name
487
+ `shell`. Two of them need this -- the approval prompt, which
488
+ shows the reason, and the transcript digest, which skips it --
489
+ and neither is a place for a tool name to live.
490
+ """
491
+ spec = self._tools.get(tool_name)
492
+ return spec.rationale_param if spec is not None else None
493
+
494
+ def rationale_for(self, tool_name: str, params: dict):
495
+ """The agent's stated reason for THIS call, or None.
496
+
497
+ The VALUE, so no caller has to know the key. core/loop.py puts
498
+ the result on the approval request and the shells render it;
499
+ `tui/screens.py` imports nothing from this package and that
500
+ stays true because what travels is a string.
501
+
502
+ Empty and whitespace-only collapse to None, so a model that
503
+ supplies the key with nothing in it is treated as the omission
504
+ it is -- the prompt says so rather than showing a blank space
505
+ where a reason should be.
506
+ """
507
+ key = self.rationale_param(tool_name)
508
+ if not key or not isinstance(params, dict):
509
+ return None
510
+ value = params.get(key)
511
+ if not isinstance(value, str) or not value.strip():
512
+ return None
513
+ return value.strip()
514
+
515
+ def headline_param(self, tool_name: str) -> Optional[str]:
516
+ """Which param is the SUBJECT of this tool's approval question,
517
+ or None (§46, EP2).
518
+
519
+ Mechanism, not policy, exactly like rationale_param above: the
520
+ consumer asks rather than testing for the literal name `shell`.
521
+ """
522
+ spec = self._tools.get(tool_name)
523
+ return spec.headline_param if spec is not None else None
524
+
525
+ def headline_for(self, tool_name: str, params: dict):
526
+ """The thing THIS call is asking permission to do, or None.
527
+
528
+ The VALUE, so no caller has to know the key -- `tui/screens.py`
529
+ imports nothing from this package and that stays true because
530
+ what travels is a string.
531
+
532
+ NOT `str()`-coerced, and that is the point rather than an
533
+ oversight. `classify_command` is total precisely because the
534
+ model's tool input reaches the approval gate unvalidated
535
+ (`ShellParams` does not run until `run()`), so `command` can be
536
+ a list, a dict or None here. A non-string coerced to
537
+ `"['cat', '/etc/passwd']"` would put a fabricated command in
538
+ the one place on the screen that must be verbatim; returning
539
+ None instead drops the pinned block and leaves the payload --
540
+ rendered whole, showing the real shape -- as the only account
541
+ of the call. The prompt still says what it is, because the
542
+ notice reports UNKNOWN for exactly this input.
543
+
544
+ Empty and whitespace-only collapse to None for
545
+ `rationale_for`'s reason: a key supplied with nothing in it is
546
+ the omission it looks like.
547
+ """
548
+ key = self.headline_param(tool_name)
549
+ if not key or not isinstance(params, dict):
550
+ return None
551
+ value = params.get(key)
552
+ if not isinstance(value, str) or not value.strip():
553
+ return None
554
+ return value.strip()
555
+
556
+ def call_digest(self, tool_name: str, params) -> str:
557
+ """The transcript's one-line summary of a tool call.
558
+
559
+ THE ONE PRODUCER (§42, RA3). `param_digest` is pure and knows
560
+ nothing about tools; this knows which param a tool declared as
561
+ its rationale and drops it, because that field is prose for a
562
+ person and would take sixty of the digest's hundred and forty
563
+ characters -- leading the line about half the time, since the
564
+ key order is the model's.
565
+
566
+ Three consumers went through `param_digest` directly before
567
+ this: the TUI's `▸ name` line, the research pipeline's tool
568
+ rows, and §27's replay of the archive. Teaching each of them
569
+ the lookup would be three copies of one rule, which is the
570
+ producer/consumer shape `param_digest`'s own docstring calls
571
+ this project's canonical bug.
572
+ """
573
+ key = self.rationale_param(tool_name)
574
+ return param_digest(params, omit=(key,) if key else ())
575
+
576
+ def call_links(self, tool_name: str, params) -> tuple:
577
+ """The untruncated values behind that summary (batch 65).
578
+
579
+ `call_digest` caps a value at 60 characters, which is shorter
580
+ than most real URLs, so the transcript resolves a truncated
581
+ span against these to arm a ctrl+click. Redacted, and with any
582
+ value the redactor rewrote dropped -- `redacted_values` says
583
+ why a target may never come from the raw params.
584
+
585
+ THE SAME `omit`, which is the whole reason this sits here
586
+ rather than being called direct (Section 42, RA3): the two
587
+ halves describe one call, and a candidate drawn from a
588
+ parameter the line does not show is a target no span could
589
+ resolve to.
590
+ """
591
+ key = self.rationale_param(tool_name)
592
+ return redacted_values(params, omit=(key,) if key else ())
593
+
594
+ def opens_thread(self, tool_name: str) -> bool:
595
+ """Whether a call to this tool creates a thread of its own (§47).
596
+
597
+ Mechanism, not policy, exactly like request_kind below: a reader
598
+ asks rather than knowing that spawn_subagent is special. Two
599
+ consumers -- core/replay.py, deciding what a stored tool line
600
+ carries, and the TUI, deciding which live line to arm -- and one
601
+ declaration between them.
602
+
603
+ False for an unknown tool, which is what an MCP tool registered
604
+ at runtime is until it says otherwise.
605
+ """
606
+ spec = self._tools.get(tool_name)
607
+ return bool(spec is not None and spec.opens_thread)
608
+
609
+ def opens_session(self, tool_name: str) -> bool:
610
+ """Whether a call to this tool starts a background session (§49,
611
+ SS14). `opens_thread`'s sibling, and False for an unknown tool for
612
+ the same reason."""
613
+ spec = self._tools.get(tool_name)
614
+ return bool(spec is not None and spec.opens_session)
615
+
616
+ def opens(self, tool_name: str) -> tuple:
617
+ """What a call to this tool OPENS: `("thread",)`, `("session",)` or
618
+ `("call",)` (§47, extended by §49 SS14, widened by §55 TR7).
619
+
620
+ THE ONE QUESTION A CONSUMER ASKS, and the reason the two flags above
621
+ are not read directly outside this class. core/replay.py and the TUI
622
+ each decide what a tool line carries; before this they asked
623
+ `opens_thread` and would each have had to grow the same second
624
+ branch, which is how the live line and the replayed one come to
625
+ disagree about what is clickable -- the exact divergence
626
+ `opens_thread`'s own docstring exists to prevent, one kind over.
627
+
628
+ THERE IS NO LONGER AN EMPTY ANSWER, and the contract that replaced
629
+ it is the one thing to read here before changing a caller. Until
630
+ §55 this returned `()` for a line that opened nothing, and the two
631
+ consumers paired that falsy tuple with a call id as their gate:
632
+ `opens and call_id`. TR7 makes every call openable -- its own
633
+ params and its own result, which is the half of a tool call nothing
634
+ rendered -- so the kind is always present and THE CALL ID IS THE
635
+ ONLY GATE. A call the model made without an id cannot be looked up
636
+ in the archive and is the one unarmed line.
637
+
638
+ OPENS_CALL IS ANSWERED WITHOUT A REGISTRY LOOKUP, deliberately.
639
+ `opens_thread` and `opens_session` are False for a tool this
640
+ registry has never seen -- which is what an MCP tool registered at
641
+ runtime is until it says otherwise, and what a tool removed between
642
+ a thread being written and being replayed is for ever. Neither of
643
+ those is a reason to hide a stored result: the archive holds the
644
+ call and its result whatever this process knows about the tool, so
645
+ the fallback is a property of the ARCHIVE rather than of the
646
+ registry, and asking would only teach it to lie about old threads.
647
+
648
+ A tuple rather than a string because the two consumers carry
649
+ `(kind, call id)` into style metadata as one unit, and because the
650
+ shape outlived the falsy contract that first chose it.
651
+ """
652
+ if self.opens_thread(tool_name):
653
+ return (OPENS_THREAD,)
654
+ if self.opens_session(tool_name):
655
+ return (OPENS_SESSION,)
656
+ return (OPENS_CALL,)
657
+
658
+ def parallel(self, tool_name: str) -> bool:
659
+ """Whether several calls to this tool in one response may run at
660
+ the same time (§47 slice 8, NA9).
661
+
662
+ Mechanism, not policy, in `opens_thread`'s exact shape and for its
663
+ reason: core/loop.py partitions a response by asking, so the file
664
+ that decides what runs concurrently names no tool.
665
+
666
+ False for an unknown tool, which is what an MCP tool registered at
667
+ runtime is until it says otherwise -- and the answer that keeps a
668
+ stranger's tool sequential, which is the safe one here.
669
+ """
670
+ spec = self._tools.get(tool_name)
671
+ return bool(spec is not None and spec.parallel)
672
+
673
+ def request_kind(self, tool_name: str) -> str:
674
+ """Which kind of question approving this tool asks (§23).
675
+
676
+ Mechanism, not policy, exactly like grant_scope above: the loop
677
+ asks rather than knowing that spawn_subagent is special.
678
+ """
679
+ spec = self._tools.get(tool_name)
680
+ return spec.request_kind if spec is not None else "approval"
681
+
682
+ def grant_policy(self, tool_name: str) -> str:
683
+ """How far approving this tool BY NAME goes (§25 R13).
684
+
685
+ Mechanism, not policy, in the same shape as grant_scope and
686
+ request_kind above: the two callers ask rather than each keeping
687
+ their own idea of which names are special. That is the whole
688
+ substance of #67 -- `grantable()` was genuinely shared while the
689
+ exclusion list lived in one caller's module, so the §18 sign-off
690
+ and the §25 pipeline held different ideas of what a grant covers.
691
+
692
+ An undeclared `mcp__*` tool is GRANT_ANYWHERE. Those names exist
693
+ only at connection time, they are the picker's real population,
694
+ and R1's argument -- the tool's own description is the whole of
695
+ informed consent, because MCP exposes no read-only/write metadata
696
+ -- was written about exactly them.
697
+
698
+ Anything else undeclared is GRANT_NEVER, failing closed.
699
+ assert_grant_policy_declared() makes that branch unreachable for
700
+ statically registered tools, exactly as D24's import check makes
701
+ _default_for_unknown_tool's unreachable for them.
702
+ """
703
+ spec = self._tools.get(tool_name)
704
+ declared = getattr(spec, "grant_policy", None)
705
+ if declared is not None:
706
+ return declared
707
+ return GRANT_ANYWHERE if tool_name.startswith("mcp__") else GRANT_NEVER
708
+
709
+ def request_payload(
710
+ self, tool_name: str, params: dict,
711
+ context: Optional["ToolContext"] = None,
712
+ ) -> dict:
713
+ """Extra payload fields for that question, or {}.
714
+
715
+ Never raises, for approval_notice's reason: a tool whose payload
716
+ callable blows up must still be answerable. It degrades to an
717
+ empty dict, which for a sign-off means no candidates -- and
718
+ interaction.decode intersects the answer with the candidates, so
719
+ the safe consequence follows automatically rather than needing a
720
+ second rule here.
721
+ """
722
+ spec = self._tools.get(tool_name)
723
+ if spec is None or spec.request_payload is None:
724
+ return {}
725
+ try:
726
+ return dict(spec.request_payload(params, context) or {})
727
+ except Exception: # noqa: BLE001 - a broken payload must not block
728
+ logger.warning("request_payload for %r failed", tool_name,
729
+ exc_info=True)
730
+ return {}
731
+
732
+ def approval_notice(
733
+ self, tool_name: str, params: dict,
734
+ context: Optional["ToolContext"] = None,
735
+ ) -> Optional[str]:
736
+ """Extra text for the approval prompt, or None.
737
+
738
+ Never raises: a tool whose notice callable blows up must still be
739
+ approvable, because the alternative is a prompt that cannot be
740
+ rendered and therefore a call that can never be allowed.
741
+ """
742
+ spec = self._tools.get(tool_name)
743
+ if spec is None or spec.approval_notice is None:
744
+ return None
745
+ try:
746
+ return spec.approval_notice(params, context)
747
+ except Exception: # noqa: BLE001 - a broken notice must not block
748
+ logger.warning("approval_notice for %r failed", tool_name,
749
+ exc_info=True)
750
+ return None
751
+
752
+ def dispatch(
753
+ self, tool_name: str, params: dict,
754
+ context: Optional["ToolContext"] = None,
755
+ approval_callback=None,
756
+ parent_run: Optional["RunInfo"] = None,
757
+ response_channel=None,
758
+ signoff=None,
759
+ memory=None,
760
+ activity=None,
761
+ call_id=None,
762
+ cancel=None,
763
+ ) -> dict:
764
+ # Unknown-tool guard: ValueError, deliberately NOT ToolCallDenied.
765
+ # The two exception types separate "you misnamed it" from "policy
766
+ # blocks you". This matters MORE since §15, not less -- runtime
767
+ # unregister() makes a stale tool name a reachable state.
768
+ if tool_name not in self._tools:
769
+ raise ValueError(f"Unknown tool: {tool_name}")
770
+
771
+ if not is_tool_allowed(tool_name, context):
772
+ # Distinguish the two causes: the model can do something about
773
+ # "not available in this context" (pick another tool for this
774
+ # task) that it cannot about a global policy denial.
775
+ if is_tool_allowed(tool_name, None):
776
+ raise ToolCallDenied(
777
+ f"{tool_name} is not available in this context")
778
+ raise ToolCallDenied(f"{tool_name} is disabled by policy")
779
+
780
+ # §32 A7 (#70). BEFORE the approval gate, and that order is the
781
+ # whole fix. A call the tool will refuse must report the REAL
782
+ # reason, and the approval check would otherwise get there
783
+ # first: with the loop no longer asking (because it consulted
784
+ # this same predicate), there is no approval_callback here, so
785
+ # an unknown agent name came back as "spawn_subagent requires
786
+ # approval and was not given" -- a cause that is not the cause,
787
+ # and worse than the empty modal it replaced.
788
+ #
789
+ # RETURNED, not raised. This is the tool's own answer about its
790
+ # own call -- the same dict its handler would have returned --
791
+ # and ToolCallDenied means policy blocked you, which is a
792
+ # different fact the model should be able to tell apart.
793
+ #
794
+ # Nothing executes past here, so the argument policy below has
795
+ # nothing left to protect on this path.
796
+ refused = self.refusal_reason(tool_name, params, context)
797
+ if refused is not None:
798
+ logger.info("%s refused before approval: %s",
799
+ tool_name, refused)
800
+ # THROUGH THE REDACTOR, like every other result (batch 156,
801
+ # A60). This was the one `return` in this function that did
802
+ # not, and it is a result path: the success path, the
803
+ # handler-exception path and the depth cap all pass the call
804
+ # below, and this one went straight out.
805
+ #
806
+ # IT WAS NOT A THEORETICAL HOLE. Measured (batch 156) through
807
+ # this very function: `spawn_subagent` with an `agent_name` of
808
+ # `ghp_` plus 36 characters came back as "Unknown agent:
809
+ # '<the whole token>' is not one of this harness's agents" --
810
+ # the full credential, to the model and to the transcript,
811
+ # from a value the model chose. And the harness has a scanner
812
+ # for exactly that input: `check_input_policy` BELOW refuses
813
+ # the same params with "an argument contains what looks like
814
+ # a credential". The refusal returned above it, so both
815
+ # scanners were skipped on one path -- §25 (R5) exists
816
+ # because "the parameters were chosen by a model reading an
817
+ # attacker's web page", and this is where that argument was
818
+ # not being applied.
819
+ #
820
+ # THE SINK AND NOT THE PRODUCER, which is the same split the
821
+ # handler containment two inches below uses: a refusal string
822
+ # is written by whichever tool owns the gate, and this is the
823
+ # one place that covers the next one. `tools/base.py` still
824
+ # asks producers not to echo a value, for a reason that
825
+ # survives this change and is stated there.
826
+ return check_output_policy(tool_name, {"error": refused})
827
+
828
+ spec = self._tools[tool_name]
829
+
830
+ if self.approval_needed(tool_name, params, context):
831
+ approved = approval_callback(tool_name, params) if approval_callback else False
832
+ if not approved:
833
+ raise ToolCallDenied(f"{tool_name} requires approval and was not given")
834
+
835
+ # §25 (R5): content policy on the ARGUMENTS, the mirror of the
836
+ # check_output_policy call below. Runs AFTER the approval check,
837
+ # deliberately -- approving a call does not authorise smuggling a
838
+ # credential out inside it, and a user who just clicked Allow is
839
+ # the last person positioned to notice that the parameters were
840
+ # chosen by a model reading an attacker's web page.
841
+ refusal = check_input_policy(tool_name, params)
842
+ if refusal is not None:
843
+ logger.warning("%s", refusal)
844
+ raise ToolCallDenied(refusal)
845
+
846
+ # §18: hand the live run-scoped values to handlers that declared
847
+ # them (spawn_subagent wants both). Handlers that didn't are
848
+ # called with params only -- the twelve pre-§18 tools are
849
+ # byte-for-byte untouched by this.
850
+ # An explicit map, not a ternary. The two-value version silently
851
+ # mis-injected any THIRD name: _declared_injections would advertise
852
+ # it and dispatch would hand it parent_run, a wrong-typed value
853
+ # with no error at register or dispatch time. A name added to
854
+ # _INJECTABLE_PARAMS and forgotten here now raises immediately.
855
+ available = {
856
+ "parent_context": context,
857
+ "parent_run": parent_run,
858
+ "response_channel": response_channel,
859
+ "signoff": signoff,
860
+ "memory": memory,
861
+ "activity": activity,
862
+ "call_id": call_id,
863
+ "cancel": cancel,
864
+ }
865
+ injected = {p: available[p] for p in self._injectable.get(tool_name, ())}
866
+ try:
867
+ # §31 (H2). A BUDGET_COMPUTE tool is a pure function of its
868
+ # params with nothing bounding it from the inside, so it runs
869
+ # in a child this call can actually kill. Everything else is
870
+ # called exactly as before -- an io tool carries its own
871
+ # bound and a human one blocks on a person, and an outer
872
+ # clock over either would stop WAITING without stopping the
873
+ # work, which is the mechanism H7 rejects.
874
+ #
875
+ # The branch is HERE, inside the containment try and at the
876
+ # one place a handler is ever invoked, rather than inside the
877
+ # six tools. A tool that isolated itself could not be called
878
+ # plainly by a test, and every test in test_math_tools.py
879
+ # would then be measuring the transport instead of the maths.
880
+ # (The count that used to stand here said 123 and was 131 by
881
+ # the time anyone checked, and 141 after batch 131 -- the
882
+ # ARGUMENT never needed the number, which is why it is gone
883
+ # rather than corrected.)
884
+ #
885
+ # `injected` is not passed: nothing in _INJECTABLE_PARAMS
886
+ # survives a process boundary, and assert_budget_declared
887
+ # rejects the pairing at import so this cannot silently drop
888
+ # a value a handler wanted.
889
+ if spec.budget == BUDGET_COMPUTE:
890
+ result = isolation.run_isolated(
891
+ spec.handler, params, config.TOOL_COMPUTE_TIMEOUT_S,
892
+ tool_name=tool_name)
893
+ else:
894
+ result = spec.handler(params, **injected)
895
+ except NetworkLimitReached as e:
896
+ # ROADMAP_v3 §53 (IO6). A refusal, not a failure: the model
897
+ # reads the meter's own sentence, which says what is full and
898
+ # when room returns, rather than "<tool> failed: ...". No
899
+ # traceback -- nothing is broken -- and no warning here, because
900
+ # the meter has already said it once for the whole run of
901
+ # refusals. ABOVE the containment below, which would otherwise
902
+ # log it as a crash.
903
+ result = {"error": e.reason}
904
+ except Exception as e: # noqa: BLE001 -- contained on purpose
905
+ # A raising tool used to take the whole run down with it. In
906
+ # chat that is a lost turn; in the research pipeline it is a
907
+ # ten-pass run flipped to status='failed' by one transient
908
+ # network error inside one pass, which is how arxiv_search's
909
+ # http:// redirect presented.
910
+ #
911
+ # Contained HERE, at the boundary that turns a handler into a
912
+ # tool result, rather than in each tool: this covers the
913
+ # twelve built-ins, every future one, and every MCP server,
914
+ # which is third-party code that can raise anything at all.
915
+ # The two tools that had their own raise-after-retries path
916
+ # were also changed to return, so the model gets a specific
917
+ # message rather than this generic wrapper -- this is the
918
+ # backstop, not the primary route.
919
+ #
920
+ # ToolCallDenied does NOT reach here: every raise of it is
921
+ # above, before the handler runs. That is deliberate -- a
922
+ # policy denial is the caller's to handle (core/loop.py turns
923
+ # it into an error result with its own wording), not something
924
+ # to flatten into a tool failure.
925
+ #
926
+ # logger.exception, not warning: the traceback is how a real
927
+ # bug in a handler stays findable now that it no longer
928
+ # crashes the process. The MODEL sees only the message.
929
+ #
930
+ # This line fires BEFORE check_output_policy below, and for a
931
+ # long time that meant the unredacted message and traceback
932
+ # were on disk while the result the model saw was clean --
933
+ # the exact threat the comment below describes, bypassed for
934
+ # the one sink it did not name (#132). The log is redacted at
935
+ # the FORMATTER now (logging_setup._RedactingFormatter), so
936
+ # this ordering is no longer load-bearing and no call site
937
+ # has to remember.
938
+ logger.exception("Tool %s raised; returning it as an error "
939
+ "result.", tool_name)
940
+ result = {"error": f"{tool_name} failed: {e}"}
941
+ # ROADMAP §8 secret redaction -- a post-call filter, not a pre-call
942
+ # gate. Load-bearing: §15's own Rev. 2 sketch dropped this line,
943
+ # which would have deleted the redaction layer outright in the
944
+ # section whose subject is tightening permissions.
945
+ #
946
+ # The error path above goes through it TOO, and must: an exception
947
+ # message routinely carries the request that produced it, and for
948
+ # an HTTP client that means a URL with an API key in the query
949
+ # string. Redacting only the success path would make a failing
950
+ # tool the way secrets escape.
951
+ #
952
+ # Scans EVERY value now, not an allowlist of keys (#47): the two
953
+ # search tools return `results` and were never covered by the set
954
+ # that held `result`.
955
+ result = check_output_policy(tool_name, result)
956
+ return result
957
+
958
+
959
+ registry = ToolRegistry()
960
+
961
+ # R13: EVERY static registration declares a grant policy, including the
962
+ # tools that are not approval-gated today and so never reach either grant
963
+ # path. That is deliberate and is the reason the field is required rather
964
+ # than inferred: whether a tool is gated is CONFIG-dependent (a user may
965
+ # gate web_search in config.ToolApprovals), so a policy derived from
966
+ # today's gating would be answered by whoever edited settings, not by
967
+ # whoever registered the tool. Declaring it here keeps the answer
968
+ # config-independent and next to the tool it is about.
969
+ registry.register(ToolSpec("web_search", web_search.TOOL_SCHEMA, web_search.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
970
+ registry.register(ToolSpec("fetch_url", fetch_url.TOOL_SCHEMA, fetch_url.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
971
+ registry.register(ToolSpec("get_time", get_time.TOOL_SCHEMA, get_time.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
972
+ registry.register(ToolSpec("arxiv_search", arxiv.TOOL_SCHEMA, arxiv.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
973
+ registry.register(ToolSpec("symbolic_math", symbolic_math.TOOL_SCHEMA, symbolic_math.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
974
+ registry.register(ToolSpec("linear_algebra", linear_algebra.TOOL_SCHEMA, linear_algebra.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
975
+ registry.register(ToolSpec("probability_stats", probability_stats.TOOL_SCHEMA, probability_stats.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
976
+ registry.register(ToolSpec("discrete_math", discrete_math.TOOL_SCHEMA, discrete_math.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
977
+ registry.register(ToolSpec("logic", logic.TOOL_SCHEMA, logic.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
978
+ registry.register(ToolSpec("geometry", geometry.TOOL_SCHEMA, geometry.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
979
+ # The four param-dependent tools. grantable() already returns False for
980
+ # them -- an approval_check means the answer depends on the path or the
981
+ # command, so a name-level grant would authorise a call nobody saw -- and
982
+ # the policy field says the same thing from the other side. Both are
983
+ # checked at both call sites; neither is load-bearing alone.
984
+ #
985
+ # read/write/edit also carry a refusal_check (§32 A7): any path resolving
986
+ # into a PROTECTED_SEGMENTS directory (`.venastine/`) is denied outright,
987
+ # pre-approval, so no human is asked a question the tool would refuse
988
+ # anyway. The handlers re-test -- the refusal_check is the
989
+ # prompt-suppression half, not the enforcement.
990
+ registry.register(ToolSpec("read", file_ops.READ_TOOL_SCHEMA, file_ops.read_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("read"), grant_policy=GRANT_NEVER, budget=BUDGET_IO))
991
+ # ROADMAP_v3 §81 (IM1, IM6). `read`'s path rules exactly -- the same approval
992
+ # check and the same refusal shape -- plus `returns_images`, which keeps it
993
+ # off the schema list wherever the image could not reach the model.
994
+ registry.register(ToolSpec("view_image", file_ops.VIEW_IMAGE_TOOL_SCHEMA, file_ops.view_image_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("view_image"), grant_policy=GRANT_NEVER, budget=BUDGET_IO, returns_images=True))
995
+ registry.register(ToolSpec("write", file_ops.WRITE_TOOL_SCHEMA, file_ops.write_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("write"), grant_policy=GRANT_NEVER, budget=BUDGET_IO))
996
+ registry.register(ToolSpec("edit", file_ops.EDIT_TOOL_SCHEMA, file_ops.edit_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._refusal_for("edit"), grant_policy=GRANT_NEVER, budget=BUDGET_IO))
997
+ # §28: approval_notice carries the capability profile into the prompt.
998
+ # The command text is already in the params; what it does not show is
999
+ # WHERE it runs, and "cat /etc/shadow" does not look like a host read.
1000
+ registry.register(ToolSpec("shell", shell.TOOL_SCHEMA, shell.run, approval_check=shell._shell_approval_check, approval_notice=shell._shell_approval_notice, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command"))
1001
+ # ROADMAP_v3 §49 (SS11, SS16, SS17). Five tools over background and monitor
1002
+ # sessions, and the two that START one are `shell` with a lifetime: the same
1003
+ # approval_check OBJECT, because a session runs a command and a second gate
1004
+ # over it would be the ratchet G3 removed -- _assert_shell_mode_exemption
1005
+ # below requires that identity, which is what ties the missing
1006
+ # `tool_approvals` field to the gate that replaces it.
1007
+ #
1008
+ # available_check rather than a permission: all seven are hidden wherever
1009
+ # nothing will wake the run when a session reports (a research pass, any run
1010
+ # outside a chat turn or a subagent). A start is refused there too, by
1011
+ # refusal_check before any approval prompt and again in the handler -- but
1012
+ # advertising a tool that can only be refused is the D24 defect, and under
1013
+ # `shell_approval_mode: never` nothing else would stop a pass calling it.
1014
+ # SS14: the three START tools open a session, so their lines are the ones a
1015
+ # reader can click. `shell_output`, `shell_kill` and `shell_input` name a
1016
+ # session they did not create -- arming those would put the same target on
1017
+ # four lines, and on twenty for an interactive session that is typed into
1018
+ # twenty times, which makes "the line that started it" stop meaning
1019
+ # anything.
1020
+ registry.register(ToolSpec("shell_background", shell_sessions.BACKGROUND_TOOL_SCHEMA, shell_sessions.background_run, approval_check=shell._shell_approval_check, approval_notice=shell_sessions.background_notice, refusal_check=shell_sessions.background_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command", opens_session=True))
1021
+ registry.register(ToolSpec("shell_monitor", shell_sessions.MONITOR_TOOL_SCHEMA, shell_sessions.monitor_run, approval_check=shell._shell_approval_check, approval_notice=shell_sessions.monitor_notice, refusal_check=shell_sessions.monitor_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command", opens_session=True))
1022
+ # Slice 2. Its gate is NOT shell's: `_interactive_approval_check` asks
1023
+ # about the session being opened rather than about its first line, because
1024
+ # the yes covers every line that follows (SS29, SS32). The assert below
1025
+ # holds it to that function by identity, exactly as it holds the three
1026
+ # above to theirs.
1027
+ registry.register(ToolSpec("shell_interactive", shell_sessions.INTERACTIVE_TOOL_SCHEMA, shell_sessions.interactive_run, approval_check=shell._interactive_approval_check, approval_notice=shell_sessions.interactive_notice, refusal_check=shell_sessions.interactive_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, rationale_param="rationale", headline_param="command", opens_session=True))
1028
+ # Typing into a session is NOT a start, so `opens_session` is False: one
1029
+ # session would otherwise be the target of every line sent to it, which is
1030
+ # the same reason `shell_output` and `shell_kill` are not armed. It keeps
1031
+ # an approval_check because SS29's exception -- a line naming a protected
1032
+ # segment -- still asks, and a control key never does (SS30).
1033
+ registry.register(ToolSpec("shell_input", shell_sessions.INPUT_TOOL_SCHEMA, shell_sessions.input_run, approval_check=shell_sessions.input_approval_check, approval_notice=shell_sessions.input_notice, refusal_check=shell_sessions.input_refusal, available_check=shell_sessions.available, grant_policy=GRANT_NEVER, budget=BUDGET_IO, headline_param="text"))
1034
+ # Reading and stopping need no approval (SS11): they act only on sessions
1035
+ # this conversation started, which someone already approved.
1036
+ registry.register(ToolSpec("shell_sessions", shell_sessions.SESSIONS_TOOL_SCHEMA, shell_sessions.sessions_run, available_check=shell_sessions.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1037
+ registry.register(ToolSpec("shell_output", shell_sessions.OUTPUT_TOOL_SCHEMA, shell_sessions.output_run, available_check=shell_sessions.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1038
+ registry.register(ToolSpec("shell_kill", shell_sessions.KILL_TOOL_SCHEMA, shell_sessions.kill_run, available_check=shell_sessions.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1039
+ registry.register(ToolSpec("load_skill", load_skill.TOOL_SCHEMA, load_skill.run, available_check=load_skill.has_skills, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1040
+ registry.register(ToolSpec("pin", pin.TOOL_SCHEMA, pin.run, available_check=pin.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1041
+ # §21/D26 restored (#89): the mirror of pin. Same gating posture (ungated,
1042
+ # thread-scoped, visible), same availability, and it is what makes D26's
1043
+ # "reversible" premise true rather than aspirational.
1044
+ registry.register(ToolSpec("unpin", pin.UNPIN_TOOL_SCHEMA, pin.unpin_run, available_check=pin.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1045
+ # §23 slice 2. No request_kind: this tool does NOT ask through the approval
1046
+ # bridge -- it is ungated (J12), so the bridge never fires for it. It names
1047
+ # `response_channel` in its handler signature and asks with it directly,
1048
+ # which is what _INJECTABLE_PARAMS was generalised for.
1049
+ registry.register(ToolSpec("ask_user", ask_user.TOOL_SCHEMA, ask_user.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_HUMAN))
1050
+ # §23 slice 2. Ungated and needs no channel (J9): it asks nobody, so a
1051
+ # headless research pass can keep a checklist. `memory` is injected by
1052
+ # signature inspection, as it is for `pin`.
1053
+ registry.register(ToolSpec("todo_write", todo.TOOL_SCHEMA, todo.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
1054
+ registry.register(ToolSpec(
1055
+ "remember", remember.TOOL_SCHEMA, remember.run,
1056
+ available_check=remember.available,
1057
+ # D26 gates this in config.ToolApprovals; the notice is what makes
1058
+ # the gate worth having, since "remember wants to run" tells the
1059
+ # user nothing they can act on.
1060
+ approval_notice=remember.approval_notice,
1061
+ # ROADMAP_v2 §21b (M17), moved here from the pipeline's own module by
1062
+ # R13 because the argument was never pipeline-specific. `remember`
1063
+ # has no approval_check, so it is grantable by R2's mechanical rule
1064
+ # and would appear in both grant paths -- and one --grant remember at
1065
+ # launch would let ten unattended passes, reading attacker-controlled
1066
+ # web pages, write durable cross-session memories. §21's D26
1067
+ # consequence 1 says research passes must not be able to do that.
1068
+ #
1069
+ # NEVER rather than SIGNOFF_ONLY: D26 consequence 1 is about what a
1070
+ # SUBAGENT can do, not only a pass, and the §18 sign-off hands the
1071
+ # child its set for the rest of the turn. A durable cross-session
1072
+ # write is exactly the authority that outlives the turn somebody was
1073
+ # watching.
1074
+ grant_policy=GRANT_NEVER,
1075
+ budget=BUDGET_IO))
1076
+ registry.register(ToolSpec(
1077
+ "read_project_doc", project_docs.READ_TOOL_SCHEMA, project_docs.read_run,
1078
+ grant_policy=GRANT_ANYWHERE,
1079
+ budget=BUDGET_IO))
1080
+ registry.register(ToolSpec(
1081
+ "write_project_doc", project_docs.WRITE_TOOL_SCHEMA, project_docs.write_run,
1082
+ # Gated in config.ToolApprovals; the notice names the destination and
1083
+ # the size, because "write_project_doc wants to run" is not a decision
1084
+ # anyone can make. The content itself is not repeated here -- /init has
1085
+ # already shown it as a diff, and several kilobytes of markdown inside
1086
+ # a modal buries the one line that says which file changes.
1087
+ approval_notice=project_docs.approval_notice,
1088
+ # #133. SIGNOFF_ONLY is the one place the two paths differ, and the
1089
+ # difference is argued from ATTENDEDNESS rather than from the tool.
1090
+ #
1091
+ # Against an unattended run: one --grant-tools write_project_doc
1092
+ # authorises 15 document names, resolved to paths by the tool and
1093
+ # overwritten in place, for the rest of a ten-pass run that is reading
1094
+ # attacker-controlled web pages -- with no diff and no second
1095
+ # question. One of them is the root AGENTS.md, which config_loader
1096
+ # injects into every agent that opts in, so it reaches M17's own
1097
+ # justification for excluding `remember` ("outlives the conversation
1098
+ # and silently shapes ones you have not started yet") through a
1099
+ # different tool.
1100
+ #
1101
+ # For the §18 sign-off it stays offered: a human is answering in the
1102
+ # moment, about one named agent, for one turn, and the notice above
1103
+ # names the destination and the size. That is the per-call consent a
1104
+ # gate is for, which is also why --attended was never the mode at
1105
+ # issue in #133.
1106
+ #
1107
+ # OFFERED TO NOTHING THAT SHIPS, measured in batch 139 and ruled
1108
+ # deliberate (TECHNICAL_DEBT 83). This is the only
1109
+ # GRANT_SIGNOFF_ONLY registration in the registry, and no agent in
1110
+ # agents/builtin/ declares `write_project_doc` -- so the policy
1111
+ # value above is correct and has no shipped instance. The sign-off
1112
+ # picker is for operator-configured installs: an agent that
1113
+ # declines to narrow `allowed_tools`, or one naming a gated tool
1114
+ # outright. Do not "fix" this by adding the tool to a shipped
1115
+ # agent -- `writer` is the only plausible candidate and its own
1116
+ # file refuses write capability in two places, so that is a
1117
+ # decision reversal and wants its own batch.
1118
+ grant_policy=GRANT_SIGNOFF_ONLY,
1119
+ budget=BUDGET_IO))
1120
+ registry.register(ToolSpec(
1121
+ "spawn_subagent", subagent_tool.TOOL_SCHEMA, subagent_tool.run,
1122
+ # §23 AC1b. Approving a spawn is not a yes/no any more: the request
1123
+ # carries the candidate tools and the answer carries the subset.
1124
+ request_kind="subagent_signoff",
1125
+ request_payload=subagent_tool.request_payload,
1126
+ # §32 A7 (#70). The loop consults this before deciding to ask, so
1127
+ # a spawn that will be refused anyway does not first produce a
1128
+ # sign-off modal -- which for an unknown agent name was a question
1129
+ # with an empty notice and nothing to tick.
1130
+ refusal_check=subagent_tool.refusal_reason,
1131
+ # Approving a spawn IS the subagent sign-off (§18 S1): it authorises
1132
+ # the child's whole approval-gated tool set for the rest of the turn,
1133
+ # which is why grant_scope is "run" -- a second spawn in the same turn
1134
+ # reuses the answer rather than re-asking.
1135
+ grant_scope="run",
1136
+ approval_notice=subagent_tool.approval_notice,
1137
+ # ROADMAP_v2 §25 (R4), moved here from the pipeline's own module by
1138
+ # R13. spawn_subagent is grantable in the ordinary sense -- it has no
1139
+ # approval_check, so approving the NAME is meaningful consent. It is
1140
+ # excluded for what that consent then authorises: approving a spawn IS
1141
+ # the §18 subagent sign-off, handing the child its whole gated set.
1142
+ #
1143
+ # NEVER, not SIGNOFF_ONLY, and #67 is why. R4's argument is ABOUT the
1144
+ # sign-off -- it names it as the thing pre-granting would duplicate --
1145
+ # so a policy that excluded it from the pipeline while leaving it in
1146
+ # the sign-off would exempt the one path the argument was written
1147
+ # against. A ticked spawn_subagent lets the child spawn ANY agent with
1148
+ # any task, unprompted, because the grant carries no subject; see
1149
+ # R14's condition in tools/context.py recall_signoff.
1150
+ #
1151
+ # Nothing is lost: research passes have never been able to delegate,
1152
+ # and in chat a spawn is still asked about per subject through the
1153
+ # J8-keyed memo, which is the mechanism that actually shows the user
1154
+ # which agent they are authorising.
1155
+ grant_policy=GRANT_NEVER,
1156
+ budget=BUDGET_HUMAN,
1157
+ # TECHNICAL_DEBT 13, batch 110. The asymmetry `load_skill` did not
1158
+ # have: with no spawnable agent discovered, this tool's only possible
1159
+ # answer is `Unknown agent`, and until batch 51 shipped two of them
1160
+ # that was every default install. See has_agents for why it reads the
1161
+ # catalog function rather than the roster.
1162
+ available_check=subagent_tool.has_agents,
1163
+ # §47. The only tool that does, so far: the child runs in a thread
1164
+ # of its own, which is what makes `▸ spawn_subagent` a line a
1165
+ # reader can open.
1166
+ opens_thread=True,
1167
+ # §47 slice 8 (NA9). The only tool that declares it, and the reason
1168
+ # the slice exists: a model emitting three spawns in one response
1169
+ # meant three runs one after another, so the parallelism a subagent
1170
+ # swarm is FOR was spent. Safe to declare because everything the
1171
+ # child's run touches was made concurrency-safe first -- the budget's
1172
+ # lock, the serialised question, the per-future authorization -- which
1173
+ # is why this one field is the last line of the section rather than
1174
+ # the first.
1175
+ parallel=True,
1176
+ ))
1177
+
1178
+ # WHICH gate each shell-mode-exempt tool must carry, by identity. A mapping
1179
+ # rather than the single name this started as, because slice 2 added a tool
1180
+ # whose gate is deliberately a different function: `shell_interactive` is
1181
+ # governed by `shell_approval_mode` like the rest, but asks its question
1182
+ # about the SESSION rather than about one command (SS29, SS32). Naming the
1183
+ # expected gate per tool keeps the check as strict as identity ever was and
1184
+ # makes it stricter in one way -- a name added to APPROVAL_BY_SHELL_MODE
1185
+ # with no entry here now fails, where before any shell gate would have done.
1186
+ _SHELL_MODE_GATES = {
1187
+ "shell": shell._shell_approval_check,
1188
+ "shell_background": shell._shell_approval_check,
1189
+ "shell_monitor": shell._shell_approval_check,
1190
+ "shell_interactive": shell._interactive_approval_check,
1191
+ }
1192
+
1193
+
1194
+ def _assert_shell_mode_exemption(tools: dict) -> None:
1195
+ """SS16: every tool exempt from `tool_approvals` carries the shell gate.
1196
+
1197
+ `security.permissions.APPROVAL_BY_SHELL_MODE` is a HOLE in D24's
1198
+ import-time check -- the names in it may omit an approvals field -- and
1199
+ the whole argument for the hole is that `shell_approval_mode` decides
1200
+ their approval instead. That argument is true only while they actually
1201
+ go through that gate, so the exemption is tied to it by IDENTITY here
1202
+ rather than by trusting the registration to have done it: a tool that
1203
+ lost its approval_check, or was given one of its own, would otherwise
1204
+ be a command-running tool with no approval question anywhere and
1205
+ nothing to say so. Raises for D24's reason -- the failure it guards
1206
+ against is invisible at runtime.
1207
+ """
1208
+ broken = []
1209
+ for name in sorted(APPROVAL_BY_SHELL_MODE):
1210
+ spec = tools.get(name)
1211
+ expected = _SHELL_MODE_GATES.get(name)
1212
+ if spec is None:
1213
+ broken.append(f"{name} is not registered")
1214
+ elif expected is None:
1215
+ broken.append(f"{name} has no declared gate in "
1216
+ f"_SHELL_MODE_GATES")
1217
+ elif spec.approval_check is not expected:
1218
+ broken.append(f"{name} does not use {expected.__name__}")
1219
+ if broken:
1220
+ raise RuntimeError(
1221
+ "These tools are exempt from tool_approvals because "
1222
+ "shell_approval_mode is supposed to gate them, and it does not: "
1223
+ f"{broken}. Either register them with the gate "
1224
+ "_SHELL_MODE_GATES names, or take them out of "
1225
+ "security.permissions.APPROVAL_BY_SHELL_MODE and give them a "
1226
+ "tool_approvals field (ROADMAP_v3 §49, SS16)."
1227
+ )
1228
+
1229
+
1230
+ _assert_shell_mode_exemption(registry._tools)
1231
+ # D24: fail loudly at import if any statically registered tool has no
1232
+ # declared permission/approval field. Runs here rather than in
1233
+ # security/permissions.py because that file must not import the registry
1234
+ # (the dependency runs tools -> security, not both ways). Runs AFTER the
1235
+ # registrations above and before any dynamic mcp__* registration, which
1236
+ # is exactly the set the check is meant to cover.
1237
+ assert_permissions_declared(registry._tools)
1238
+ # R13, the same trade one question over: fail loudly at import if any
1239
+ # statically registered tool has no usable grant policy. Same placement
1240
+ # and same reason -- after the static registrations, before any dynamic
1241
+ # mcp__* one, which is exactly the set that can carry a declaration.
1242
+ assert_grant_policy_declared(registry._tools, registry._tools)
1243
+ # H1, the same trade one question further over: fail loudly at import if
1244
+ # any statically registered tool has not said what a call to it is
1245
+ # allowed to cost. Same placement and the same reason as the two above.
1246
+ #
1247
+ # `_injectable` is passed because BUDGET_COMPUTE is not only a policy --
1248
+ # it routes the call through a process boundary that no injected value
1249
+ # survives -- so the two declarations have to be checked against each
1250
+ # other rather than each on its own.
1251
+ assert_budget_declared(registry._tools, registry._tools,
1252
+ registry._injectable)