@yahyahammad/venastine 0.1.0

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 (143) hide show
  1. package/.env.example +14 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +14 -0
  4. package/PRIVACY.md +66 -0
  5. package/README.md +878 -0
  6. package/SECURITY.md +88 -0
  7. package/THIRD_PARTY_NOTICES.md +100 -0
  8. package/agents/builtin/compactor.md +75 -0
  9. package/agents/builtin/explore.md +77 -0
  10. package/agents/builtin/grill-me.md +27 -0
  11. package/agents/builtin/initializer.md +94 -0
  12. package/agents/builtin/pipeline-reviewer.md +100 -0
  13. package/agents/builtin/plan.md +88 -0
  14. package/agents/builtin/review.md +74 -0
  15. package/agents/manager.py +195 -0
  16. package/agents/subagent_tool.py +215 -0
  17. package/agents/tui_commands.py +136 -0
  18. package/bin/venastine.mjs +382 -0
  19. package/config.py +1198 -0
  20. package/core/__init__.py +0 -0
  21. package/core/approval.py +115 -0
  22. package/core/client.py +1548 -0
  23. package/core/compaction.py +959 -0
  24. package/core/config_loader.py +1563 -0
  25. package/core/events.py +61 -0
  26. package/core/interaction.py +328 -0
  27. package/core/loop.py +1353 -0
  28. package/core/memory.py +370 -0
  29. package/core/model_windows.py +175 -0
  30. package/core/pipeline_models.py +176 -0
  31. package/core/reasoning/__init__.py +0 -0
  32. package/core/reasoning/authorization.py +130 -0
  33. package/core/reasoning/base.py +219 -0
  34. package/core/reasoning/confidence_scoring.py +468 -0
  35. package/core/reasoning/events.py +149 -0
  36. package/core/reasoning/json_retry.py +219 -0
  37. package/core/reasoning/orchestrator.py +1382 -0
  38. package/core/reasoning/output_writer.py +286 -0
  39. package/core/reasoning/payload_validation.py +398 -0
  40. package/core/reasoning/pipeline_storage.py +361 -0
  41. package/core/reasoning/review.py +615 -0
  42. package/core/reasoning/scholar.py +434 -0
  43. package/core/reasoning/source_corpus.py +327 -0
  44. package/core/reasoning/source_scoring.py +855 -0
  45. package/core/replay.py +167 -0
  46. package/core/session.py +153 -0
  47. package/core/workspace_trust.py +207 -0
  48. package/credentials.py +180 -0
  49. package/database.py +252 -0
  50. package/env_secrets.py +77 -0
  51. package/json_store.py +123 -0
  52. package/logging_setup.py +185 -0
  53. package/main.py +1959 -0
  54. package/mcp_client/__init__.py +15 -0
  55. package/mcp_client/client.py +499 -0
  56. package/mcp_client/config.py +379 -0
  57. package/mcp_client/registration.py +182 -0
  58. package/memories/manager.py +132 -0
  59. package/memories/tui_commands.py +232 -0
  60. package/package.json +73 -0
  61. package/project_init/config_files.py +278 -0
  62. package/project_init/doc_sets.py +330 -0
  63. package/project_init/generator.py +564 -0
  64. package/project_init/manifest.py +406 -0
  65. package/project_init/tui_commands.py +144 -0
  66. package/prompts/__init__.py +0 -0
  67. package/prompts/annotate.md +14 -0
  68. package/prompts/assumption_audit.md +27 -0
  69. package/prompts/claim_extraction.md +34 -0
  70. package/prompts/completeness.md +18 -0
  71. package/prompts/confidence_tiers.md +23 -0
  72. package/prompts/critic_pass.md +24 -0
  73. package/prompts/final_synthesis.md +13 -0
  74. package/prompts/initial_generation.md +14 -0
  75. package/prompts/preliminary_plan.md +23 -0
  76. package/prompts/revalidate.md +25 -0
  77. package/prompts/revise.md +15 -0
  78. package/prompts/source_grounding.md +66 -0
  79. package/prompts/system_prompts.py +262 -0
  80. package/prompts/universal_system_prompt +7 -0
  81. package/prompts/untrusted_content +1 -0
  82. package/providers.json.example +92 -0
  83. package/pyproject.toml +100 -0
  84. package/requirements.txt +72 -0
  85. package/safety/__init__.py +0 -0
  86. package/safety/policy_enforcement.py +682 -0
  87. package/security/__init__.py +0 -0
  88. package/security/capability.py +177 -0
  89. package/security/permissions.py +190 -0
  90. package/security/posture.py +302 -0
  91. package/security/protected_paths.py +309 -0
  92. package/security/sandbox.py +985 -0
  93. package/skills/builtin/crypto/cryptography-verification.md +66 -0
  94. package/skills/builtin/math/formal-specification.md +67 -0
  95. package/skills/builtin/math/numerical-methods.md +66 -0
  96. package/skills/builtin/math/proof-writing.md +61 -0
  97. package/skills/builtin/research/experiment-design.md +62 -0
  98. package/skills/builtin/research/literature-review.md +65 -0
  99. package/skills/builtin/research/reproducibility.md +55 -0
  100. package/skills/builtin/research/source-evaluation.md +70 -0
  101. package/skills/builtin/research/statistical-inference.md +63 -0
  102. package/skills/builtin/research/technical-writing.md +59 -0
  103. package/skills/builtin/security/cybersecurity-research.md +63 -0
  104. package/skills/builtin/software/code-review.md +61 -0
  105. package/skills/builtin/software/debugging.md +61 -0
  106. package/skills/builtin/software/test-design.md +67 -0
  107. package/skills/manager.py +138 -0
  108. package/skills/tui_commands.py +111 -0
  109. package/storage.py +1005 -0
  110. package/tools/base.py +305 -0
  111. package/tools/builtin/__init__.py +0 -0
  112. package/tools/builtin/_math_common.py +377 -0
  113. package/tools/builtin/_net_common.py +61 -0
  114. package/tools/builtin/arxiv.py +223 -0
  115. package/tools/builtin/ask_user.py +213 -0
  116. package/tools/builtin/discrete_math.py +134 -0
  117. package/tools/builtin/fetch_url.py +153 -0
  118. package/tools/builtin/file_ops.py +412 -0
  119. package/tools/builtin/geometry.py +148 -0
  120. package/tools/builtin/get_time.py +20 -0
  121. package/tools/builtin/linear_algebra.py +155 -0
  122. package/tools/builtin/load_skill.py +66 -0
  123. package/tools/builtin/logic.py +96 -0
  124. package/tools/builtin/pin.py +193 -0
  125. package/tools/builtin/probability_stats.py +228 -0
  126. package/tools/builtin/project_docs.py +405 -0
  127. package/tools/builtin/remember.py +158 -0
  128. package/tools/builtin/shell.py +461 -0
  129. package/tools/builtin/symbolic_math.py +119 -0
  130. package/tools/builtin/todo.py +147 -0
  131. package/tools/builtin/web_search.py +151 -0
  132. package/tools/context.py +136 -0
  133. package/tools/isolation.py +314 -0
  134. package/tools/registry.py +897 -0
  135. package/tui/app.py +3423 -0
  136. package/tui/app.tcss +458 -0
  137. package/tui/commands.py +61 -0
  138. package/tui/diffs.py +265 -0
  139. package/tui/preferences.py +182 -0
  140. package/tui/ravens.py +146 -0
  141. package/tui/screens.py +943 -0
  142. package/tui/themes.py +366 -0
  143. package/tui/widgets.py +1239 -0
@@ -0,0 +1,897 @@
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
+
25
+ import config
26
+ from typing import Optional, TYPE_CHECKING
27
+
28
+ from tools.base import (
29
+ BUDGET_COMPUTE, BUDGET_HUMAN, BUDGET_IO,
30
+ GRANT_ANYWHERE, GRANT_NEVER, GRANT_SIGNOFF_ONLY, ToolSpec,
31
+ assert_budget_declared, assert_grant_policy_declared,
32
+ )
33
+ from tools import isolation
34
+ from tools.builtin import (
35
+ web_search, fetch_url, get_time, arxiv,
36
+ symbolic_math, linear_algebra, probability_stats, discrete_math, logic, geometry,
37
+ file_ops, shell, load_skill, pin, remember, project_docs,
38
+ ask_user, todo,
39
+ )
40
+ from security.permissions import (
41
+ assert_permissions_declared, is_tool_allowed, requires_approval,
42
+ )
43
+ from safety.policy_enforcement import (check_input_policy,
44
+ check_output_policy,
45
+ param_digest)
46
+ from agents import subagent_tool
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ if TYPE_CHECKING: # pragma: no cover - typing only
51
+ from tools.context import ToolContext, RunInfo
52
+
53
+ # Handler parameter names dispatch() will inject, by signature inspection
54
+ # (ROADMAP_v2 §18). A tool handler that declares one of these receives the
55
+ # live value; handlers that don't are called with params only. Generalised
56
+ # so §23's response-channel tools can add a third name later without
57
+ # touching dispatch() again.
58
+ _INJECTABLE_PARAMS = (
59
+ # §23 renamed permission_channel -> response_channel: it is no longer
60
+ # permission-specific, and a tool that needs to ask a human anything
61
+ # receives the same object the loop asks through.
62
+ "parent_context", "parent_run", "response_channel",
63
+ # §23 AC1b: the approved SUBSET from a subagent sign-off. The comment
64
+ # above anticipated §23's tools adding a name here without reopening
65
+ # dispatch(); this is that name.
66
+ "signoff",
67
+ # ROADMAP_v2 §21: the live ConversationMemory, for `pin`. The
68
+ # comment above anticipated a third name arriving without touching
69
+ # dispatch() again; this is it.
70
+ "memory",
71
+ )
72
+
73
+
74
+ class ToolCallDenied(Exception):
75
+ """Raised when policy blocks a tool call outright, or an approval was
76
+ required and not given."""
77
+
78
+
79
+ class ToolRegistry:
80
+ def __init__(self) -> None:
81
+ self._tools: dict[str, ToolSpec] = {}
82
+ # name -> the subset of _INJECTABLE_PARAMS the handler declares.
83
+ # Cached at register() so dispatch() never re-inspects per call.
84
+ self._injectable: dict[str, tuple] = {}
85
+
86
+ def register(self, spec: ToolSpec) -> None:
87
+ self._tools[spec.name] = spec
88
+ self._injectable[spec.name] = self._declared_injections(spec.handler)
89
+
90
+ @staticmethod
91
+ def _declared_injections(handler) -> tuple:
92
+ """Which injectable run-scoped values this handler wants. A
93
+ handler opts in simply by naming a parameter (e.g.
94
+ `def run(params, parent_context)`); everything else stays a
95
+ params-only call so the existing twelve tools are untouched."""
96
+ try:
97
+ names = set(inspect.signature(handler).parameters)
98
+ except (TypeError, ValueError): # builtins / un-introspectable
99
+ return ()
100
+ return tuple(p for p in _INJECTABLE_PARAMS if p in names)
101
+
102
+ def unregister(self, tool_name: str) -> None:
103
+ """Runtime removal (D15). An MCP server disconnecting drops its
104
+ tools mid-session, so a name that was valid a moment ago becomes
105
+ a reachable state rather than a programmer error -- which is why
106
+ dispatch() keeps its unknown-tool guard.
107
+
108
+ Idempotent: removing an absent name is not an error, because
109
+ disconnect handling can run more than once for the same server.
110
+ """
111
+ self._tools.pop(tool_name, None)
112
+ self._injectable.pop(tool_name, None)
113
+
114
+ def _advertised(self, name: str, spec, context) -> bool:
115
+ """The two §15 filters, shared by schemas() and
116
+ headless_hidden(): policy allowability plus the tool's own
117
+ "nothing to act on" signal."""
118
+ if not is_tool_allowed(name, context):
119
+ return False
120
+ if spec.available_check is not None and not spec.available_check():
121
+ return False
122
+ return True
123
+
124
+ def _answered_by_grant(self, tool_name: str, granted) -> bool:
125
+ """Whether a pre-flight grant has ALREADY answered this tool's
126
+ approval question (§25 R15).
127
+
128
+ `callable_only` below asks "can anything ask?". Since §25 that is
129
+ the wrong question by itself: a grant is an answer given early, so
130
+ the question is "can anything answer FOR THIS TOOL?" -- and a
131
+ granted tool is answerable with no channel at all. #156 is the gap
132
+ between those two sentences: `--grant-tools X` with no `--attended`
133
+ built a grant the enforcement path honoured and the advertisement
134
+ path never saw, so the model was never told the tool existed and
135
+ never emitted the call.
136
+
137
+ TWO checks, and both are RE-derived here rather than trusted from
138
+ the set -- the same discipline core/loop.py applies before honouring
139
+ a grant, because a stale or hand-built `RunInfo` must not widen what
140
+ is advertised any more than it can widen what is dispatched:
141
+
142
+ grantable() R2. A tool deciding approval from its PARAMS was
143
+ never consented to by name, so a grant naming one
144
+ answers nothing.
145
+ grant_policy R13, and it must be `== GRANT_ANYWHERE` rather than
146
+ `!= GRANT_NEVER`. Both callers of this reach it only
147
+ when the run is HEADLESS, and headless is precisely
148
+ the unattended case GRANT_SIGNOFF_ONLY exists to
149
+ exclude: R13 admits `write_project_doc` to the §18
150
+ sign-off because a human is answering in the moment
151
+ about one named agent, and refuses it to ten
152
+ unattended passes on one launch-time tick. A
153
+ headless run has no human answering in the moment,
154
+ so the looser test would readmit it exactly where
155
+ the argument was written against.
156
+
157
+ THIS IS THE SAME PREDICATE `candidates()` USES, and deliberately so.
158
+ That function decides what may be OFFERED to an unattended run and
159
+ this one decides what a grant then makes VISIBLE to it -- one
160
+ question, so one answer. Written `!= GRANT_NEVER` first, which let
161
+ `write_project_doc` through here while `candidates()` refused it:
162
+ #67/#133's own shape, reappearing inside the batch that generalised
163
+ it. Neither the CLI nor the TUI nor a subagent sign-off can put a
164
+ SIGNOFF_ONLY name into a headless grant today, so nothing was
165
+ reachable -- but "unreachable" is a fact about the callers, and this
166
+ is a claim about the policy.
167
+
168
+ Shared by schemas() and headless_hidden() rather than written out
169
+ twice -- those two must agree about what is hidden, and #67/#133
170
+ are what a shared mechanism with a duplicated policy costs.
171
+ """
172
+ return (bool(granted)
173
+ and tool_name in granted
174
+ and self.grantable(tool_name)
175
+ and self.grant_policy(tool_name) == GRANT_ANYWHERE)
176
+
177
+ def is_advertised(
178
+ self, tool_name: str, context: Optional["ToolContext"] = None,
179
+ callable_only: bool = False,
180
+ granted: Optional[set] = None,
181
+ ) -> bool:
182
+ """Whether schemas() would advertise this tool right now.
183
+
184
+ THE WHOLE ADVERTISEMENT QUESTION IN ONE PLACE, and the reason
185
+ is one method up: _answered_by_grant is shared by schemas()
186
+ and headless_hidden() because "those two must agree about
187
+ what is hidden, and #67/#133 are what a shared mechanism with
188
+ a duplicated policy costs". #68 is the same sentence with a
189
+ third party to the agreement -- prompts.system_prompts's
190
+ catalogs, whose prose INSTRUCTS the model to call a tool.
191
+
192
+ That third caller asked `is_allowed(name, context)` instead,
193
+ which is POLICY: it answers "is this tool permitted", not
194
+ "can this run call it". A research pass is headless, so
195
+ spawn_subagent is permitted, hidden from the schema list, and
196
+ named in the run's own headless_hidden() warning -- while the
197
+ prompt told the model to spawn one. The harness stated the
198
+ contradiction to its log and to the model in the same breath.
199
+
200
+ A PREDICATE RATHER THAN `name in [s["name"] for s in
201
+ schemas()]`: the schema list is built where the run is, and
202
+ the prompt is built before the run exists. Both need the
203
+ answer; only one is in a position to enumerate.
204
+ """
205
+ spec = self._tools.get(tool_name)
206
+ if spec is None:
207
+ return False
208
+ if not self._advertised(tool_name, spec, context):
209
+ return False
210
+ return not (callable_only
211
+ and self.approval_needed(tool_name, {}, context)
212
+ and not self._answered_by_grant(tool_name, granted))
213
+
214
+ def schemas(
215
+ self, context: Optional["ToolContext"] = None,
216
+ callable_only: bool = False,
217
+ granted: Optional[set] = None,
218
+ ) -> list[dict]:
219
+ """What gets sent to the LLM's `tools` parameter each call.
220
+
221
+ Only tools that are actually callable are advertised. Advertising
222
+ an uncallable tool is not harmless: the model keeps choosing it,
223
+ burns a turn per attempt, and the only signal is a denial string
224
+ inside a tool result. That is precisely the damage the `fetch_url`
225
+ defect did for its whole life (D24), so §15 fixes the shape as
226
+ well as the instance.
227
+
228
+ Filters, deliberately distinct:
229
+ * is_tool_allowed(name, context) -- policy. Global config AND
230
+ every active layer's restriction.
231
+ * spec.available_check() -- the tool's own "I have nothing to
232
+ act on yet" signal (load_skill with an empty skill catalog).
233
+ * callable_only (§18, user-widened headless callability rule) --
234
+ when the run has no response_channel, a tool whose
235
+ approval_needed() is True for empty params is UNCALLABLE in
236
+ this configuration (nothing can grant the approval), so it is
237
+ not advertised. autoApproved MCP servers and approval-free
238
+ tools pass; approval-gated ones drop. The loop pairs this with
239
+ a once-per-process WARNING naming what was hidden -- no quiet
240
+ invisibility (the fetch_url lesson).
241
+ * granted (§25 R15) -- names a pre-flight grant already answered
242
+ for. Those stay advertised even with no channel, because the
243
+ approval question HAS an answer; see _answered_by_grant.
244
+
245
+ WHAT callable_only GUARANTEES, stated because the converse does not
246
+ hold and #158 is what assuming it costs: it means SOME call shape
247
+ is callable, not that every one is. The probe is
248
+ approval_needed(name, {}), and for a tool whose approval_check
249
+ reads the params -- read/write/edit on a path, shell on a command --
250
+ the empty dict is a call the model will never make. `write` resolves
251
+ an empty path inside the workspace, so it survives this filter and
252
+ is then denied per out-of-workspace call. That is deliberate (an
253
+ in-workspace write IS callable headless), but it means a survivor
254
+ of this filter is not a promise about any particular call.
255
+ """
256
+ return [spec.schema for name, spec in self._tools.items()
257
+ if self.is_advertised(name, context, callable_only,
258
+ granted)]
259
+
260
+ def headless_hidden(
261
+ self, context: Optional["ToolContext"] = None,
262
+ granted: Optional[set] = None,
263
+ ) -> list[str]:
264
+ """Names that would be advertised with a response_channel but
265
+ are dropped by schemas(callable_only=True) -- i.e. advertised yet
266
+ uncallable headless. The loop logs exactly this list once, so a
267
+ tool hidden by the headless filter is named and explained rather
268
+ than silently absent (the trade this project keeps deciding
269
+ against).
270
+
271
+ Takes `granted` for the same reason schemas() does, and it is not
272
+ cosmetic: this list is what the WARNING names. A granted tool that
273
+ is genuinely callable must not be reported as hidden, or the notice
274
+ whose whole purpose is to stop invisibility starts producing a
275
+ second kind of wrong answer.
276
+ """
277
+ # ADVERTISED ATTENDED AND NOT HEADLESS -- written as the two
278
+ # calls it means rather than as the filter's negation, so the
279
+ # list and the schemas can only disagree if is_advertised
280
+ # disagrees with itself.
281
+ return [
282
+ name for name in self._tools
283
+ if self.is_advertised(name, context, False, granted)
284
+ and not self.is_advertised(name, context, True, granted)
285
+ ]
286
+
287
+ def approval_needed(
288
+ self, tool_name: str, params: dict,
289
+ context: Optional["ToolContext"] = None,
290
+ ) -> bool:
291
+ """SINGLE SOURCE OF TRUTH for whether a call needs human approval.
292
+
293
+ Both dispatch() and core/loop.py's permission bridge call this, so
294
+ they can never disagree -- a path-dependent tool must surface a
295
+ permission_request event the user can approve, not be silently
296
+ denied by one check while the other reports no approval needed.
297
+
298
+ §15 makes this an OR rather than an either/or. Previously a tool
299
+ with an approval_check bypassed requires_approval() entirely,
300
+ which would have made agent-level approval_overrides do nothing
301
+ for read/write/edit/shell. Now:
302
+
303
+ tool's own approval_check OR config/context requirement
304
+
305
+ so a context can tighten a lenient default (an agent may demand
306
+ approval for symbolic_math) but can never suppress a check the
307
+ tool itself imposes (an agent declaring `shell: false` does NOT
308
+ skip shell's non-inert-command gate).
309
+ """
310
+ spec = self._tools.get(tool_name)
311
+ tool_level = (
312
+ spec.approval_check(tool_name, params)
313
+ if spec is not None and spec.approval_check is not None
314
+ else False
315
+ )
316
+ return tool_level or requires_approval(tool_name, params, context)
317
+
318
+ def refusal_reason(
319
+ self, tool_name: str, params: dict,
320
+ context: Optional["ToolContext"] = None,
321
+ ) -> Optional[str]:
322
+ """Why this call would be refused before it is asked about,
323
+ or None (§32 A7).
324
+
325
+ The loop asks the registry, the same way it asks whether
326
+ approval is needed at all -- which tools have pre-flight
327
+ conditions is not the loop's knowledge.
328
+
329
+ NOT AN ENFORCEMENT PATH. dispatch() still runs the handler and
330
+ the handler still refuses; this only decides whether a human
331
+ is put to a question whose answer cannot change the outcome.
332
+ A refusal_check that wrongly returned a reason would therefore
333
+ skip a prompt, never widen anything.
334
+ """
335
+ spec = self._tools.get(tool_name)
336
+ if spec is None or spec.refusal_check is None:
337
+ return None
338
+ return spec.refusal_check(params, context)
339
+
340
+ def is_allowed(
341
+ self, tool_name: str, context: Optional["ToolContext"] = None,
342
+ ) -> bool:
343
+ """Whether policy permits this tool at all, in this context.
344
+
345
+ The loop needs this to avoid prompting for a call it will refuse
346
+ regardless. Exposed here rather than importing is_tool_allowed
347
+ into core/loop.py: this file is the only one that talks to
348
+ security.permissions, and that boundary is the point.
349
+ """
350
+ return is_tool_allowed(tool_name, context)
351
+
352
+ def is_registered(self, tool_name: str) -> bool:
353
+ """Whether a tool with this name is currently registered.
354
+
355
+ Policy and registration are different questions (review §19-20
356
+ f12): is_allowed answers "would policy refuse this call", and for
357
+ unknown mcp__ names it says no-refuse by design -- the server may
358
+ connect later. A caller that needs to know whether the tool
359
+ EXISTS (e.g. §19's activation notice, which should flag a
360
+ declared tool that is not callable right now) asks this.
361
+ """
362
+ return tool_name in self._tools
363
+
364
+ def grantable(self, tool_name: str) -> bool:
365
+ """Whether approving this tool BY NAME, before any call exists, is
366
+ meaningful consent (ROADMAP_v2 §25, R2).
367
+
368
+ False for any tool declaring its own approval_check. Those decide
369
+ per call, from the params -- read/write/edit on a path outside the
370
+ workspace, shell on a non-inert command -- so a name-level grant
371
+ would authorise a call the user never saw. `shell` is the sharp
372
+ case: granting the NAME would wave through every command for the
373
+ rest of the run, which is not what anyone ticking a checkbox
374
+ labelled "shell" is agreeing to.
375
+
376
+ A registration-time property, not an inference about params, and
377
+ the same rule for §18's subagent sign-off as for §25's pipeline
378
+ grants -- one mechanism, so the two cannot drift into different
379
+ ideas of what a grant covers. A non-grantable tool is not blocked:
380
+ it falls back to being asked, exactly as it is today.
381
+ """
382
+ spec = self._tools.get(tool_name)
383
+ return spec is not None and spec.approval_check is None
384
+
385
+ def grant_scope(self, tool_name: str) -> Optional[str]:
386
+ """"run" if approving this tool once covers the rest of the run.
387
+
388
+ Mechanism, not policy: the loop asks rather than knowing which
389
+ tools work this way, so the tool name stays out of core/loop.py.
390
+ """
391
+ spec = self._tools.get(tool_name)
392
+ return spec.grant_scope if spec is not None else None
393
+
394
+ def rationale_param(self, tool_name: str) -> Optional[str]:
395
+ """Which param carries the agent's own stated reason,
396
+ or None (§42, RA2).
397
+
398
+ Mechanism, not policy, exactly like grant_scope above: the
399
+ consumer asks rather than testing for the literal name
400
+ `shell`. Two of them need this -- the approval prompt, which
401
+ shows the reason, and the transcript digest, which skips it --
402
+ and neither is a place for a tool name to live.
403
+ """
404
+ spec = self._tools.get(tool_name)
405
+ return spec.rationale_param if spec is not None else None
406
+
407
+ def rationale_for(self, tool_name: str, params: dict):
408
+ """The agent's stated reason for THIS call, or None.
409
+
410
+ The VALUE, so no caller has to know the key. core/loop.py puts
411
+ the result on the approval request and the shells render it;
412
+ `tui/screens.py` imports nothing from this package and that
413
+ stays true because what travels is a string.
414
+
415
+ Empty and whitespace-only collapse to None, so a model that
416
+ supplies the key with nothing in it is treated as the omission
417
+ it is -- the prompt says so rather than showing a blank space
418
+ where a reason should be.
419
+ """
420
+ key = self.rationale_param(tool_name)
421
+ if not key or not isinstance(params, dict):
422
+ return None
423
+ value = params.get(key)
424
+ if not isinstance(value, str) or not value.strip():
425
+ return None
426
+ return value.strip()
427
+
428
+ def headline_param(self, tool_name: str) -> Optional[str]:
429
+ """Which param is the SUBJECT of this tool's approval question,
430
+ or None (§46, EP2).
431
+
432
+ Mechanism, not policy, exactly like rationale_param above: the
433
+ consumer asks rather than testing for the literal name `shell`.
434
+ """
435
+ spec = self._tools.get(tool_name)
436
+ return spec.headline_param if spec is not None else None
437
+
438
+ def headline_for(self, tool_name: str, params: dict):
439
+ """The thing THIS call is asking permission to do, or None.
440
+
441
+ The VALUE, so no caller has to know the key -- `tui/screens.py`
442
+ imports nothing from this package and that stays true because
443
+ what travels is a string.
444
+
445
+ NOT `str()`-coerced, and that is the point rather than an
446
+ oversight. `classify_command` is total precisely because the
447
+ model's tool input reaches the approval gate unvalidated
448
+ (`ShellParams` does not run until `run()`), so `command` can be
449
+ a list, a dict or None here. A non-string coerced to
450
+ `"['cat', '/etc/passwd']"` would put a fabricated command in
451
+ the one place on the screen that must be verbatim; returning
452
+ None instead drops the pinned block and leaves the payload --
453
+ rendered whole, showing the real shape -- as the only account
454
+ of the call. The prompt still says what it is, because the
455
+ notice reports UNKNOWN for exactly this input.
456
+
457
+ Empty and whitespace-only collapse to None for
458
+ `rationale_for`'s reason: a key supplied with nothing in it is
459
+ the omission it looks like.
460
+ """
461
+ key = self.headline_param(tool_name)
462
+ if not key or not isinstance(params, dict):
463
+ return None
464
+ value = params.get(key)
465
+ if not isinstance(value, str) or not value.strip():
466
+ return None
467
+ return value.strip()
468
+
469
+ def call_digest(self, tool_name: str, params) -> str:
470
+ """The transcript's one-line summary of a tool call.
471
+
472
+ THE ONE PRODUCER (§42, RA3). `param_digest` is pure and knows
473
+ nothing about tools; this knows which param a tool declared as
474
+ its rationale and drops it, because that field is prose for a
475
+ person and would take sixty of the digest's hundred and forty
476
+ characters -- leading the line about half the time, since the
477
+ key order is the model's.
478
+
479
+ Three consumers went through `param_digest` directly before
480
+ this: the TUI's `▸ name` line, the research pipeline's tool
481
+ rows, and §27's replay of the archive. Teaching each of them
482
+ the lookup would be three copies of one rule, which is the
483
+ producer/consumer shape `param_digest`'s own docstring calls
484
+ this project's canonical bug.
485
+ """
486
+ key = self.rationale_param(tool_name)
487
+ return param_digest(params, omit=(key,) if key else ())
488
+
489
+ def request_kind(self, tool_name: str) -> str:
490
+ """Which kind of question approving this tool asks (§23).
491
+
492
+ Mechanism, not policy, exactly like grant_scope above: the loop
493
+ asks rather than knowing that spawn_subagent is special.
494
+ """
495
+ spec = self._tools.get(tool_name)
496
+ return spec.request_kind if spec is not None else "approval"
497
+
498
+ def grant_policy(self, tool_name: str) -> str:
499
+ """How far approving this tool BY NAME goes (§25 R13).
500
+
501
+ Mechanism, not policy, in the same shape as grant_scope and
502
+ request_kind above: the two callers ask rather than each keeping
503
+ their own idea of which names are special. That is the whole
504
+ substance of #67 -- `grantable()` was genuinely shared while the
505
+ exclusion list lived in one caller's module, so the §18 sign-off
506
+ and the §25 pipeline held different ideas of what a grant covers.
507
+
508
+ An undeclared `mcp__*` tool is GRANT_ANYWHERE. Those names exist
509
+ only at connection time, they are the picker's real population,
510
+ and R1's argument -- the tool's own description is the whole of
511
+ informed consent, because MCP exposes no read-only/write metadata
512
+ -- was written about exactly them.
513
+
514
+ Anything else undeclared is GRANT_NEVER, failing closed.
515
+ assert_grant_policy_declared() makes that branch unreachable for
516
+ statically registered tools, exactly as D24's import check makes
517
+ _default_for_unknown_tool's unreachable for them.
518
+ """
519
+ spec = self._tools.get(tool_name)
520
+ declared = getattr(spec, "grant_policy", None)
521
+ if declared is not None:
522
+ return declared
523
+ return GRANT_ANYWHERE if tool_name.startswith("mcp__") else GRANT_NEVER
524
+
525
+ def request_payload(
526
+ self, tool_name: str, params: dict,
527
+ context: Optional["ToolContext"] = None,
528
+ ) -> dict:
529
+ """Extra payload fields for that question, or {}.
530
+
531
+ Never raises, for approval_notice's reason: a tool whose payload
532
+ callable blows up must still be answerable. It degrades to an
533
+ empty dict, which for a sign-off means no candidates -- and
534
+ interaction.decode intersects the answer with the candidates, so
535
+ the safe consequence follows automatically rather than needing a
536
+ second rule here.
537
+ """
538
+ spec = self._tools.get(tool_name)
539
+ if spec is None or spec.request_payload is None:
540
+ return {}
541
+ try:
542
+ return dict(spec.request_payload(params, context) or {})
543
+ except Exception: # noqa: BLE001 - a broken payload must not block
544
+ logger.warning("request_payload for %r failed", tool_name,
545
+ exc_info=True)
546
+ return {}
547
+
548
+ def approval_notice(
549
+ self, tool_name: str, params: dict,
550
+ context: Optional["ToolContext"] = None,
551
+ ) -> Optional[str]:
552
+ """Extra text for the approval prompt, or None.
553
+
554
+ Never raises: a tool whose notice callable blows up must still be
555
+ approvable, because the alternative is a prompt that cannot be
556
+ rendered and therefore a call that can never be allowed.
557
+ """
558
+ spec = self._tools.get(tool_name)
559
+ if spec is None or spec.approval_notice is None:
560
+ return None
561
+ try:
562
+ return spec.approval_notice(params, context)
563
+ except Exception: # noqa: BLE001 - a broken notice must not block
564
+ logger.warning("approval_notice for %r failed", tool_name,
565
+ exc_info=True)
566
+ return None
567
+
568
+ def dispatch(
569
+ self, tool_name: str, params: dict,
570
+ context: Optional["ToolContext"] = None,
571
+ approval_callback=None,
572
+ parent_run: Optional["RunInfo"] = None,
573
+ response_channel=None,
574
+ signoff=None,
575
+ memory=None,
576
+ ) -> dict:
577
+ # Unknown-tool guard: ValueError, deliberately NOT ToolCallDenied.
578
+ # The two exception types separate "you misnamed it" from "policy
579
+ # blocks you". This matters MORE since §15, not less -- runtime
580
+ # unregister() makes a stale tool name a reachable state.
581
+ if tool_name not in self._tools:
582
+ raise ValueError(f"Unknown tool: {tool_name}")
583
+
584
+ if not is_tool_allowed(tool_name, context):
585
+ # Distinguish the two causes: the model can do something about
586
+ # "not available in this context" (pick another tool for this
587
+ # task) that it cannot about a global policy denial.
588
+ if is_tool_allowed(tool_name, None):
589
+ raise ToolCallDenied(
590
+ f"{tool_name} is not available in this context")
591
+ raise ToolCallDenied(f"{tool_name} is disabled by policy")
592
+
593
+ # §32 A7 (#70). BEFORE the approval gate, and that order is the
594
+ # whole fix. A call the tool will refuse must report the REAL
595
+ # reason, and the approval check would otherwise get there
596
+ # first: with the loop no longer asking (because it consulted
597
+ # this same predicate), there is no approval_callback here, so
598
+ # an unknown agent name came back as "spawn_subagent requires
599
+ # approval and was not given" -- a cause that is not the cause,
600
+ # and worse than the empty modal it replaced.
601
+ #
602
+ # RETURNED, not raised. This is the tool's own answer about its
603
+ # own call -- the same dict its handler would have returned --
604
+ # and ToolCallDenied means policy blocked you, which is a
605
+ # different fact the model should be able to tell apart.
606
+ #
607
+ # Nothing executes past here, so the argument policy below has
608
+ # nothing left to protect on this path.
609
+ refused = self.refusal_reason(tool_name, params, context)
610
+ if refused is not None:
611
+ logger.info("%s refused before approval: %s",
612
+ tool_name, refused)
613
+ return {"error": refused}
614
+
615
+ spec = self._tools[tool_name]
616
+
617
+ if self.approval_needed(tool_name, params, context):
618
+ approved = approval_callback(tool_name, params) if approval_callback else False
619
+ if not approved:
620
+ raise ToolCallDenied(f"{tool_name} requires approval and was not given")
621
+
622
+ # §25 (R5): content policy on the ARGUMENTS, the mirror of the
623
+ # check_output_policy call below. Runs AFTER the approval check,
624
+ # deliberately -- approving a call does not authorise smuggling a
625
+ # credential out inside it, and a user who just clicked Allow is
626
+ # the last person positioned to notice that the parameters were
627
+ # chosen by a model reading an attacker's web page.
628
+ refusal = check_input_policy(tool_name, params)
629
+ if refusal is not None:
630
+ logger.warning("%s", refusal)
631
+ raise ToolCallDenied(refusal)
632
+
633
+ # §18: hand the live run-scoped values to handlers that declared
634
+ # them (spawn_subagent wants both). Handlers that didn't are
635
+ # called with params only -- the twelve pre-§18 tools are
636
+ # byte-for-byte untouched by this.
637
+ # An explicit map, not a ternary. The two-value version silently
638
+ # mis-injected any THIRD name: _declared_injections would advertise
639
+ # it and dispatch would hand it parent_run, a wrong-typed value
640
+ # with no error at register or dispatch time. A name added to
641
+ # _INJECTABLE_PARAMS and forgotten here now raises immediately.
642
+ available = {
643
+ "parent_context": context,
644
+ "parent_run": parent_run,
645
+ "response_channel": response_channel,
646
+ "signoff": signoff,
647
+ "memory": memory,
648
+ }
649
+ injected = {p: available[p] for p in self._injectable.get(tool_name, ())}
650
+ try:
651
+ # §31 (H2). A BUDGET_COMPUTE tool is a pure function of its
652
+ # params with nothing bounding it from the inside, so it runs
653
+ # in a child this call can actually kill. Everything else is
654
+ # called exactly as before -- an io tool carries its own
655
+ # bound and a human one blocks on a person, and an outer
656
+ # clock over either would stop WAITING without stopping the
657
+ # work, which is the mechanism H7 rejects.
658
+ #
659
+ # The branch is HERE, inside the containment try and at the
660
+ # one place a handler is ever invoked, rather than inside the
661
+ # six tools. A tool that isolated itself could not be called
662
+ # plainly by a test, and the 123 tests in test_math_tools.py
663
+ # would then be measuring the transport instead of the maths.
664
+ #
665
+ # `injected` is not passed: nothing in _INJECTABLE_PARAMS
666
+ # survives a process boundary, and assert_budget_declared
667
+ # rejects the pairing at import so this cannot silently drop
668
+ # a value a handler wanted.
669
+ if spec.budget == BUDGET_COMPUTE:
670
+ result = isolation.run_isolated(
671
+ spec.handler, params, config.TOOL_COMPUTE_TIMEOUT_S,
672
+ tool_name=tool_name)
673
+ else:
674
+ result = spec.handler(params, **injected)
675
+ except Exception as e: # noqa: BLE001 -- contained on purpose
676
+ # A raising tool used to take the whole run down with it. In
677
+ # chat that is a lost turn; in the research pipeline it is a
678
+ # ten-pass run flipped to status='failed' by one transient
679
+ # network error inside one pass, which is how arxiv_search's
680
+ # http:// redirect presented.
681
+ #
682
+ # Contained HERE, at the boundary that turns a handler into a
683
+ # tool result, rather than in each tool: this covers the
684
+ # twelve built-ins, every future one, and every MCP server,
685
+ # which is third-party code that can raise anything at all.
686
+ # The two tools that had their own raise-after-retries path
687
+ # were also changed to return, so the model gets a specific
688
+ # message rather than this generic wrapper -- this is the
689
+ # backstop, not the primary route.
690
+ #
691
+ # ToolCallDenied does NOT reach here: every raise of it is
692
+ # above, before the handler runs. That is deliberate -- a
693
+ # policy denial is the caller's to handle (core/loop.py turns
694
+ # it into an error result with its own wording), not something
695
+ # to flatten into a tool failure.
696
+ #
697
+ # logger.exception, not warning: the traceback is how a real
698
+ # bug in a handler stays findable now that it no longer
699
+ # crashes the process. The MODEL sees only the message.
700
+ #
701
+ # This line fires BEFORE check_output_policy below, and for a
702
+ # long time that meant the unredacted message and traceback
703
+ # were on disk while the result the model saw was clean --
704
+ # the exact threat the comment below describes, bypassed for
705
+ # the one sink it did not name (#132). The log is redacted at
706
+ # the FORMATTER now (logging_setup._RedactingFormatter), so
707
+ # this ordering is no longer load-bearing and no call site
708
+ # has to remember.
709
+ logger.exception("Tool %s raised; returning it as an error "
710
+ "result.", tool_name)
711
+ result = {"error": f"{tool_name} failed: {e}"}
712
+ # ROADMAP §8 secret redaction -- a post-call filter, not a pre-call
713
+ # gate. Load-bearing: §15's own Rev. 2 sketch dropped this line,
714
+ # which would have deleted the redaction layer outright in the
715
+ # section whose subject is tightening permissions.
716
+ #
717
+ # The error path above goes through it TOO, and must: an exception
718
+ # message routinely carries the request that produced it, and for
719
+ # an HTTP client that means a URL with an API key in the query
720
+ # string. Redacting only the success path would make a failing
721
+ # tool the way secrets escape.
722
+ #
723
+ # Scans EVERY value now, not an allowlist of keys (#47): the two
724
+ # search tools return `results` and were never covered by the set
725
+ # that held `result`.
726
+ result = check_output_policy(tool_name, result)
727
+ return result
728
+
729
+
730
+ registry = ToolRegistry()
731
+
732
+ # R13: EVERY static registration declares a grant policy, including the
733
+ # tools that are not approval-gated today and so never reach either grant
734
+ # path. That is deliberate and is the reason the field is required rather
735
+ # than inferred: whether a tool is gated is CONFIG-dependent (a user may
736
+ # gate web_search in config.ToolApprovals), so a policy derived from
737
+ # today's gating would be answered by whoever edited settings, not by
738
+ # whoever registered the tool. Declaring it here keeps the answer
739
+ # config-independent and next to the tool it is about.
740
+ registry.register(ToolSpec("web_search", web_search.TOOL_SCHEMA, web_search.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
741
+ registry.register(ToolSpec("fetch_url", fetch_url.TOOL_SCHEMA, fetch_url.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
742
+ registry.register(ToolSpec("get_time", get_time.TOOL_SCHEMA, get_time.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
743
+ registry.register(ToolSpec("arxiv_search", arxiv.TOOL_SCHEMA, arxiv.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
744
+ registry.register(ToolSpec("symbolic_math", symbolic_math.TOOL_SCHEMA, symbolic_math.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
745
+ registry.register(ToolSpec("linear_algebra", linear_algebra.TOOL_SCHEMA, linear_algebra.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
746
+ registry.register(ToolSpec("probability_stats", probability_stats.TOOL_SCHEMA, probability_stats.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
747
+ registry.register(ToolSpec("discrete_math", discrete_math.TOOL_SCHEMA, discrete_math.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
748
+ registry.register(ToolSpec("logic", logic.TOOL_SCHEMA, logic.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
749
+ registry.register(ToolSpec("geometry", geometry.TOOL_SCHEMA, geometry.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_COMPUTE))
750
+ # The four param-dependent tools. grantable() already returns False for
751
+ # them -- an approval_check means the answer depends on the path or the
752
+ # command, so a name-level grant would authorise a call nobody saw -- and
753
+ # the policy field says the same thing from the other side. Both are
754
+ # checked at both call sites; neither is load-bearing alone.
755
+ #
756
+ # read/write/edit also carry a refusal_check (§32 A7): any path resolving
757
+ # into a PROTECTED_SEGMENTS directory (`.venastine/`) is denied outright,
758
+ # pre-approval, so no human is asked a question the tool would refuse
759
+ # anyway. The handlers re-test -- the refusal_check is the
760
+ # prompt-suppression half, not the enforcement.
761
+ registry.register(ToolSpec("read", file_ops.READ_TOOL_SCHEMA, file_ops.read_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._protected_refusal, grant_policy=GRANT_NEVER, budget=BUDGET_IO))
762
+ registry.register(ToolSpec("write", file_ops.WRITE_TOOL_SCHEMA, file_ops.write_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._protected_refusal, grant_policy=GRANT_NEVER, budget=BUDGET_IO))
763
+ registry.register(ToolSpec("edit", file_ops.EDIT_TOOL_SCHEMA, file_ops.edit_run, approval_check=file_ops._file_approval_check, refusal_check=file_ops._protected_refusal, grant_policy=GRANT_NEVER, budget=BUDGET_IO))
764
+ # §28: approval_notice carries the capability profile into the prompt.
765
+ # The command text is already in the params; what it does not show is
766
+ # WHERE it runs, and "cat /etc/shadow" does not look like a host read.
767
+ 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"))
768
+ 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))
769
+ registry.register(ToolSpec("pin", pin.TOOL_SCHEMA, pin.run, available_check=pin.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
770
+ # §21/D26 restored (#89): the mirror of pin. Same gating posture (ungated,
771
+ # thread-scoped, visible), same availability, and it is what makes D26's
772
+ # "reversible" premise true rather than aspirational.
773
+ registry.register(ToolSpec("unpin", pin.UNPIN_TOOL_SCHEMA, pin.unpin_run, available_check=pin.available, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
774
+ # §23 slice 2. No request_kind: this tool does NOT ask through the approval
775
+ # bridge -- it is ungated (J12), so the bridge never fires for it. It names
776
+ # `response_channel` in its handler signature and asks with it directly,
777
+ # which is what _INJECTABLE_PARAMS was generalised for.
778
+ registry.register(ToolSpec("ask_user", ask_user.TOOL_SCHEMA, ask_user.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_HUMAN))
779
+ # §23 slice 2. Ungated and needs no channel (J9): it asks nobody, so a
780
+ # headless research pass can keep a checklist. `memory` is injected by
781
+ # signature inspection, as it is for `pin`.
782
+ registry.register(ToolSpec("todo_write", todo.TOOL_SCHEMA, todo.run, grant_policy=GRANT_ANYWHERE, budget=BUDGET_IO))
783
+ registry.register(ToolSpec(
784
+ "remember", remember.TOOL_SCHEMA, remember.run,
785
+ available_check=remember.available,
786
+ # D26 gates this in config.ToolApprovals; the notice is what makes
787
+ # the gate worth having, since "remember wants to run" tells the
788
+ # user nothing they can act on.
789
+ approval_notice=remember.approval_notice,
790
+ # ROADMAP_v2 §21b (M17), moved here from the pipeline's own module by
791
+ # R13 because the argument was never pipeline-specific. `remember`
792
+ # has no approval_check, so it is grantable by R2's mechanical rule
793
+ # and would appear in both grant paths -- and one --grant remember at
794
+ # launch would let ten unattended passes, reading attacker-controlled
795
+ # web pages, write durable cross-session memories. §21's D26
796
+ # consequence 1 says research passes must not be able to do that.
797
+ #
798
+ # NEVER rather than SIGNOFF_ONLY: D26 consequence 1 is about what a
799
+ # SUBAGENT can do, not only a pass, and the §18 sign-off hands the
800
+ # child its set for the rest of the turn. A durable cross-session
801
+ # write is exactly the authority that outlives the turn somebody was
802
+ # watching.
803
+ grant_policy=GRANT_NEVER,
804
+ budget=BUDGET_IO))
805
+ registry.register(ToolSpec(
806
+ "read_project_doc", project_docs.READ_TOOL_SCHEMA, project_docs.read_run,
807
+ grant_policy=GRANT_ANYWHERE,
808
+ budget=BUDGET_IO))
809
+ registry.register(ToolSpec(
810
+ "write_project_doc", project_docs.WRITE_TOOL_SCHEMA, project_docs.write_run,
811
+ # Gated in config.ToolApprovals; the notice names the destination and
812
+ # the size, because "write_project_doc wants to run" is not a decision
813
+ # anyone can make. The content itself is not repeated here -- /init has
814
+ # already shown it as a diff, and several kilobytes of markdown inside
815
+ # a modal buries the one line that says which file changes.
816
+ approval_notice=project_docs.approval_notice,
817
+ # #133. SIGNOFF_ONLY is the one place the two paths differ, and the
818
+ # difference is argued from ATTENDEDNESS rather than from the tool.
819
+ #
820
+ # Against an unattended run: one --grant-tools write_project_doc
821
+ # authorises 15 document names, resolved to paths by the tool and
822
+ # overwritten in place, for the rest of a ten-pass run that is reading
823
+ # attacker-controlled web pages -- with no diff and no second
824
+ # question. One of them is the root AGENTS.md, which config_loader
825
+ # injects into every agent that opts in, so it reaches M17's own
826
+ # justification for excluding `remember` ("outlives the conversation
827
+ # and silently shapes ones you have not started yet") through a
828
+ # different tool.
829
+ #
830
+ # For the §18 sign-off it stays offered: a human is answering in the
831
+ # moment, about one named agent, for one turn, and the notice above
832
+ # names the destination and the size. That is the per-call consent a
833
+ # gate is for, which is also why --attended was never the mode at
834
+ # issue in #133.
835
+ grant_policy=GRANT_SIGNOFF_ONLY,
836
+ budget=BUDGET_IO))
837
+ registry.register(ToolSpec(
838
+ "spawn_subagent", subagent_tool.TOOL_SCHEMA, subagent_tool.run,
839
+ # §23 AC1b. Approving a spawn is not a yes/no any more: the request
840
+ # carries the candidate tools and the answer carries the subset.
841
+ request_kind="subagent_signoff",
842
+ request_payload=subagent_tool.request_payload,
843
+ # §32 A7 (#70). The loop consults this before deciding to ask, so
844
+ # a spawn that will be refused anyway does not first produce a
845
+ # sign-off modal -- which for an unknown agent name was a question
846
+ # with an empty notice and nothing to tick.
847
+ refusal_check=subagent_tool.refusal_reason,
848
+ # Approving a spawn IS the subagent sign-off (§18 S1): it authorises
849
+ # the child's whole approval-gated tool set for the rest of the turn,
850
+ # which is why grant_scope is "run" -- a second spawn in the same turn
851
+ # reuses the answer rather than re-asking.
852
+ grant_scope="run",
853
+ approval_notice=subagent_tool.approval_notice,
854
+ # ROADMAP_v2 §25 (R4), moved here from the pipeline's own module by
855
+ # R13. spawn_subagent is grantable in the ordinary sense -- it has no
856
+ # approval_check, so approving the NAME is meaningful consent. It is
857
+ # excluded for what that consent then authorises: approving a spawn IS
858
+ # the §18 subagent sign-off, handing the child its whole gated set.
859
+ #
860
+ # NEVER, not SIGNOFF_ONLY, and #67 is why. R4's argument is ABOUT the
861
+ # sign-off -- it names it as the thing pre-granting would duplicate --
862
+ # so a policy that excluded it from the pipeline while leaving it in
863
+ # the sign-off would exempt the one path the argument was written
864
+ # against. A ticked spawn_subagent lets the child spawn ANY agent with
865
+ # any task, unprompted, because the grant carries no subject; see
866
+ # R14's condition in tools/context.py recall_signoff.
867
+ #
868
+ # Nothing is lost: research passes have never been able to delegate,
869
+ # and in chat a spawn is still asked about per subject through the
870
+ # J8-keyed memo, which is the mechanism that actually shows the user
871
+ # which agent they are authorising.
872
+ grant_policy=GRANT_NEVER,
873
+ budget=BUDGET_HUMAN,
874
+ ))
875
+
876
+ # D24: fail loudly at import if any statically registered tool has no
877
+ # declared permission/approval field. Runs here rather than in
878
+ # security/permissions.py because that file must not import the registry
879
+ # (the dependency runs tools -> security, not both ways). Runs AFTER the
880
+ # registrations above and before any dynamic mcp__* registration, which
881
+ # is exactly the set the check is meant to cover.
882
+ assert_permissions_declared(registry._tools)
883
+ # R13, the same trade one question over: fail loudly at import if any
884
+ # statically registered tool has no usable grant policy. Same placement
885
+ # and same reason -- after the static registrations, before any dynamic
886
+ # mcp__* one, which is exactly the set that can carry a declaration.
887
+ assert_grant_policy_declared(registry._tools, registry._tools)
888
+ # H1, the same trade one question further over: fail loudly at import if
889
+ # any statically registered tool has not said what a call to it is
890
+ # allowed to cost. Same placement and the same reason as the two above.
891
+ #
892
+ # `_injectable` is passed because BUDGET_COMPUTE is not only a policy --
893
+ # it routes the call through a process boundary that no injected value
894
+ # survives -- so the two declarations have to be checked against each
895
+ # other rather than each on its own.
896
+ assert_budget_declared(registry._tools, registry._tools,
897
+ registry._injectable)