@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,74 @@
1
+ ---
2
+ name: review
3
+ description: Reviews a change or a document against what it claims to do and reports defects with the evidence for each — it never rewrites the work itself
4
+ allowed_tools:
5
+ - read
6
+ - read_project_doc
7
+ - shell
8
+ - load_skill
9
+ use_project_context: true
10
+ use_memory: true
11
+ max_steps: 15
12
+ # §32 A3/A4 (#69). "Review the diff on this branch against what the
13
+ # commit message says it does" is a complete task string, and the
14
+ # review reads the work itself rather than the conversation that
15
+ # produced it -- which is what makes this one spawnable where
16
+ # pipeline-reviewer (a finished PipelineRun) and grill-me (a live
17
+ # thread) are not.
18
+ spawnable: true
19
+ # §32 A15. Read-only by OMISSION: no write, edit, write_project_doc or
20
+ # remember, so a reviewer cannot start fixing what it found. `shell` is
21
+ # here for `git diff` and `git log`, and every non-inert command still
22
+ # reaches the human who signed off the spawn.
23
+ ---
24
+
25
+ You are reviewing work someone else has finished. Your output is a list of
26
+ defects with evidence. You do not rewrite the work, and you do not rewrite
27
+ it in prose either by describing at length what you would have done.
28
+
29
+ ## Find the claim before you judge the work
30
+
31
+ A review needs a standard to review against. Establish it first: the
32
+ commit message, the issue, the docstring, the spec, the function's own
33
+ name. Then read the work as an answer to that claim. Most real defects are
34
+ disagreements between what something says it does and what it does, and
35
+ they are invisible if you only read the code as itself.
36
+
37
+ ## Every finding carries its evidence
38
+
39
+ For each item:
40
+
41
+ - **Where** — file and line, or section.
42
+ - **What is wrong** — one sentence, stated as a defect and not as a
43
+ preference.
44
+ - **How it fails** — the concrete input, state or sequence that produces
45
+ the wrong result. If you cannot name one, say so, and mark the finding
46
+ as a smell rather than a defect.
47
+
48
+ A finding with no failure path is a hypothesis. It can still be worth
49
+ reporting; it must not be reported in the same voice as one you can
50
+ demonstrate.
51
+
52
+ ## Rank by consequence, not by how easy it was to spot
53
+
54
+ Correctness first, then anything that silently produces a wrong answer
55
+ rather than an error, then security and data loss, then maintainability.
56
+ Naming conventions come last if they come at all. A review that opens with
57
+ three style notes teaches the reader to skim the rest.
58
+
59
+ ## Check what is NOT there
60
+
61
+ The defect that survives review is usually an omission: the error path
62
+ nobody wrote, the case the tests do not distinguish, the caller that was
63
+ not updated, the invariant that used to hold. Ask what would have to be
64
+ added for the change to be complete, not only whether what is present is
65
+ correct.
66
+
67
+ For tests specifically: ask whether each one could fail. A test that
68
+ passes against the unfixed code is not testing the fix.
69
+
70
+ ## Say when it is fine
71
+
72
+ If the work is sound, say so plainly and stop. Manufacturing findings to
73
+ justify the review is worse than a short review, because it costs the
74
+ reader the ability to tell your serious findings from your filler.
@@ -0,0 +1,195 @@
1
+ """
2
+ agents/manager.py
3
+
4
+ ROADMAP_v2 §18. AgentManager discovers agent `.md` files across the three
5
+ tiers and exposes lookup by name plus the §18 scope-composition rules.
6
+
7
+ Thin by design: discovery, frontmatter parsing, and tier precedence
8
+ (D29: harness > user > project) all live in core/config_loader.py, which
9
+ runs at initialize() time. This file adds only the agent-specific policy
10
+ composition that §18 owns and that §20 (subagent review) will call:
11
+
12
+ * active_context() -- the ToolContext for a session-scoped active
13
+ agent (/agent switch): the agent's own restrictions at depth 0.
14
+ * child_context() -- the ToolContext for a spawned subagent: C6's
15
+ intersection-with-parent (never union) plus a depth increment (C3).
16
+ * system_prompt_for() -- base + catalogs + the agent's body + opt-in
17
+ project context, assembled in one place so the TUI worker and
18
+ spawn_subagent cannot drift apart.
19
+ """
20
+
21
+ from typing import Optional
22
+
23
+ from core import config_loader
24
+ from core.config_loader import AgentDef
25
+ from memories.manager import manager as memory_manager
26
+ from tools.context import ToolContext
27
+
28
+
29
+ class AgentManager:
30
+ """Lookup + scope composition over the loader's discovered agents."""
31
+
32
+ def get(self, name: str) -> Optional[AgentDef]:
33
+ return config_loader.get_agent(name)
34
+
35
+ def names(self) -> list:
36
+ return sorted(config_loader.get_agents())
37
+
38
+ def all(self) -> dict:
39
+ return config_loader.get_agents()
40
+
41
+ @staticmethod
42
+ def active_context(agent: AgentDef) -> ToolContext:
43
+ """ToolContext for running AS this agent (session-scoped /agent
44
+ switch). The agent's own restrictions at depth 0 -- no parent to
45
+ intersect with, no nesting."""
46
+ allowed = (
47
+ set(agent.allowed_tools)
48
+ if agent.allowed_tools is not None else None
49
+ )
50
+ return ToolContext(
51
+ allowed_tools=allowed,
52
+ approval_overrides=dict(agent.approval_overrides),
53
+ subagent_depth=0,
54
+ )
55
+
56
+ @staticmethod
57
+ def child_context(
58
+ agent: AgentDef, parent_context: Optional[ToolContext],
59
+ ) -> ToolContext:
60
+ """ToolContext for a subagent spawned WHILE running under
61
+ parent_context. C6: intersection, never union -- a restricted
62
+ parent must not escape its restriction by spawning a permissive
63
+ child. C3: depth increments so the nesting limit is enforceable.
64
+
65
+ An agent that declares no allowed_tools inherits the parent's
66
+ restriction unchanged (it may not widen it either).
67
+
68
+ APPROVAL COMPOSES THE SAME WAY (§14-§18 review f12, decision S2).
69
+ §18's spec sketch built the child's overrides from the agent
70
+ definition alone, which drops the parent's. C6 reasoned about
71
+ allowed_tools and never considered the approval axis, so the same
72
+ escalation it exists to prevent was open one field over: a parent
73
+ declaring `approval_overrides: {web_search: true}` prompts on
74
+ every search, then spawns a child that computes
75
+ approval_needed(web_search) == False and runs it ungated.
76
+
77
+ Union rather than replace. Only True entries carry -- a False is
78
+ indistinguishable from absent under D14's OR, so unioning can
79
+ only ever tighten, which is what makes it safe to do silently."""
80
+ parent = parent_context or ToolContext()
81
+ if agent.allowed_tools is not None:
82
+ own = set(agent.allowed_tools)
83
+ child_allowed = own & (
84
+ parent.allowed_tools if parent.allowed_tools is not None
85
+ else own
86
+ )
87
+ else:
88
+ child_allowed = (
89
+ set(parent.allowed_tools)
90
+ if parent.allowed_tools is not None else None
91
+ )
92
+ overrides = {k: v for k, v in parent.approval_overrides.items() if v}
93
+ overrides.update(agent.approval_overrides)
94
+ return ToolContext(
95
+ allowed_tools=child_allowed,
96
+ approval_overrides=overrides,
97
+ subagent_depth=parent.subagent_depth + 1,
98
+ )
99
+
100
+ @staticmethod
101
+ def candidate_approvals(child_context: ToolContext) -> list:
102
+ """Tools the subagent could reach that would each need approval.
103
+
104
+ ONE helper, TWO callers -- the sign-off prompt's notice text and
105
+ the grant the child actually receives. Computing the list twice
106
+ would let what the user approved drift from what the child got,
107
+ which is the whole substance of the sign-off.
108
+
109
+ Params are empty because there are none yet: a path-dependent
110
+ approval_check (file_ops outside the workspace, shell on a
111
+ non-inert command) cannot be resolved before the call exists, so
112
+ those still prompt at call time through the inherited channel.
113
+
114
+ §25 (R2) filters those tools OUT of the list rather than merely
115
+ letting them re-prompt. They were never grantable by name, and the
116
+ loop now enforces that -- so leaving them here would make the
117
+ sign-off notice promise authority the grant does not carry, which
118
+ is worse than not offering it. What the user reads and what the
119
+ child receives have to be the same list; that is the whole
120
+ substance of a sign-off, and this helper exists to keep them one.
121
+
122
+ §25 (R13) adds the second filter, and #67 is why it is here rather
123
+ than only in core/reasoning/authorization.py. Both functions
124
+ answer "what may be pre-granted", both were built from
125
+ headless_hidden + grantable, and only the pipeline's one then
126
+ subtracted an exclusion list -- which lived in the pipeline's
127
+ module where this one could not see it. So this list offered
128
+ `spawn_subagent` and `remember`, the two tools R4 and M17 exist to
129
+ keep out of a grant, and R4's argument is ABOUT this sign-off.
130
+ Now both read one per-tool declaration.
131
+
132
+ The LOOSE half of the pair: GRANT_SIGNOFF_ONLY passes here and is
133
+ refused by the pipeline. A human answering in the moment, about
134
+ one named agent, for one turn, is the consent write_project_doc's
135
+ notice was written for; ten unattended passes on one launch-time
136
+ tick is not.
137
+ """
138
+ from tools.base import GRANT_NEVER
139
+ from tools.registry import registry
140
+
141
+ return sorted(
142
+ name for name in registry.headless_hidden(child_context)
143
+ if registry.grantable(name)
144
+ and registry.grant_policy(name) != GRANT_NEVER
145
+ )
146
+
147
+ @staticmethod
148
+ def system_prompt_for(agent: AgentDef, base_prompt: str,
149
+ active_skills=None, context=None,
150
+ callable_only: bool = False,
151
+ granted=None) -> str:
152
+ """The full system prompt for a run AS this agent: base + skill /
153
+ agent catalogs, then the agent's own body, then the project's
154
+ AGENTS.md iff the agent opts in (use_project_context). One
155
+ assembly point so every caller produces the same prompt.
156
+
157
+ active_skills (§19) reaches only the catalog, where it MARKS the
158
+ skills whose bodies the shell pins separately. Bodies are not
159
+ added here -- see with_catalogs' K6 note.
160
+
161
+ context (§20 review f19, generalised): the ToolContext this run
162
+ will actually use. It reaches with_catalogs, which suppresses a
163
+ catalog whose tool the context excludes -- otherwise a restricted
164
+ agent is told to "call the load_skill tool" it does not have.
165
+ Pass the SAME context the run gets: child_context() for a spawned
166
+ subagent, so a parent's restriction suppresses the invitation too;
167
+ active_context() for a /agent switch. None means the run is under
168
+ global policy only, and both catalogs apply."""
169
+ import prompts.system_prompts as system_prompts
170
+
171
+ # callable_only / granted (#68): forwarded, not decided here.
172
+ # This function knows which agent is running; whether anything
173
+ # can answer an approval question is the RUN's fact, and the
174
+ # caller is the one holding it. Defaulting to the attended
175
+ # answer keeps both TUI call sites correct with no argument.
176
+ prompt = system_prompts.with_catalogs(
177
+ base_prompt, active_skills, context,
178
+ callable_only=callable_only, granted=granted)
179
+ prompt = f"{prompt}\n\n## Agent: {agent.name}\n\n{agent.body}"
180
+ context = config_loader.context_for_agent(agent)
181
+ if context:
182
+ prompt = f"{prompt}\n\n## Project context\n\n{context}"
183
+ # ROADMAP_v2 §21b: durable memories, the third context tier beside
184
+ # the project's AGENTS.md and gated the same way (use_memory).
185
+ # Appended HERE and not inside with_catalogs, which feeds
186
+ # pass_prompt() -- injecting there would put every memory into all
187
+ # ten research passes, which is §19's K6 trap in its second
188
+ # instance.
189
+ memories = memory_manager.prompt_fragment(agent)
190
+ if memories:
191
+ prompt = f"{prompt}\n\n{memories}"
192
+ return prompt
193
+
194
+
195
+ manager = AgentManager()
@@ -0,0 +1,215 @@
1
+ """
2
+ agents/subagent_tool.py
3
+
4
+ ROADMAP_v2 §18, D6: the model-initiated half of agent invocation. The
5
+ model spawns a named agent to handle a task; the run is scope-capped by
6
+ the parent's ToolContext (C6), depth-limited (C3), and returns only the
7
+ subagent's final text -- distilled, matching the pipeline's own "don't
8
+ share raw history" principle.
9
+
10
+ The handler declares `parent_context` and `parent_run`, which
11
+ tools/registry.dispatch() injects by signature inspection (§18). The
12
+ Rev. 1 sketch's `depth: int` parameter and `allowed_tools=` kwarg are
13
+ both gone: depth lives on ToolContext.subagent_depth, and §15 replaced
14
+ allowed_tools with context= everywhere.
15
+
16
+ core.loop is imported INSIDE run(), not at module top: tools/registry.py
17
+ imports this module to register it, and core.loop imports tools.registry
18
+ -- a top-level import here would close that cycle at import time.
19
+ """
20
+
21
+ import config
22
+ from storage import THREAD_KIND_SUBAGENT
23
+ from tools.context import ToolContext
24
+
25
+ TOOL_SCHEMA = {
26
+ "name": "spawn_subagent",
27
+ "description": "Spawn a named agent to handle a self-contained task "
28
+ "and return its final answer. The subagent runs in its "
29
+ "own thread with its own methodology and a tool set "
30
+ "capped by your current restrictions. Use it when a "
31
+ "task matches a listed agent's specialty; do the work "
32
+ "yourself otherwise.",
33
+ "input_schema": {
34
+ "type": "object",
35
+ "properties": {
36
+ "agent_name": {
37
+ "type": "string",
38
+ "description": "Agent name exactly as listed in the "
39
+ "Available agents catalog.",
40
+ },
41
+ "task": {
42
+ "type": "string",
43
+ "description": "The self-contained task description the "
44
+ "subagent receives as its first message.",
45
+ },
46
+ },
47
+ "required": ["agent_name", "task"],
48
+ },
49
+ }
50
+
51
+
52
+ def refusal_reason(params: dict, context=None):
53
+ """Why this spawn would be refused, or None (§32 A7, #70).
54
+
55
+ ONE function, TWO callers: the loop consults it before deciding to
56
+ ask, and run() below calls it before doing anything. That is the
57
+ point rather than a tidiness -- the sign-off shown and the error
58
+ returned have to be about the same refusal, and the way to
59
+ guarantee it is to have one place that decides.
60
+
61
+ THE ORDER MATCHES run()'s ORIGINAL ORDER, depth before params
62
+ before name, because these strings are what the model already
63
+ sees and reordering them would change a live contract for no
64
+ reason.
65
+
66
+ Returns None for anything it cannot settle in advance -- an agent
67
+ that exists and a depth that is fine can still fail once it runs,
68
+ and this function is deliberately not in the business of
69
+ predicting that.
70
+ """
71
+ parent = context or ToolContext()
72
+ if parent.subagent_depth >= config.SUBAGENT_MAX_DEPTH:
73
+ return (f"Maximum subagent nesting depth "
74
+ f"({config.SUBAGENT_MAX_DEPTH}) reached")
75
+ name = params.get("agent_name")
76
+ task = params.get("task")
77
+ if not name or not task:
78
+ return ("spawn_subagent requires both 'agent_name' and "
79
+ "'task'.")
80
+ from agents.manager import manager
81
+
82
+ if manager.get(name) is None:
83
+ return (f"Unknown agent: {name!r} is not "
84
+ f"in the available agents catalog.")
85
+ return None
86
+
87
+
88
+ def approval_notice(params: dict, context=None) -> str:
89
+ """What approving this spawn actually authorises (§18 S1).
90
+
91
+ The params alone say only which agent and which task. What the user
92
+ is really being asked is whether that agent may run a set of tools
93
+ without asking again -- so the prompt has to name them. Computed
94
+ through manager.candidate_approvals(), the SAME helper that builds
95
+ the grant, so the list shown and the list granted cannot drift.
96
+ """
97
+ from agents.manager import manager
98
+
99
+ agent = manager.get(params.get("agent_name", ""))
100
+ if agent is None:
101
+ return ""
102
+ child = manager.child_context(agent, context or ToolContext())
103
+ candidates = manager.candidate_approvals(child)
104
+ if not candidates:
105
+ return f"{agent.name} needs no approval-gated tools."
106
+ listed = "\n".join(f" - {name}" for name in candidates)
107
+ return (f"{agent.name} may use these without asking again, for the "
108
+ f"rest of this turn:\n{listed}")
109
+
110
+
111
+ def request_payload(params: dict, context=None) -> dict:
112
+ """What the sign-off question is ABOUT (§23 AC1b).
113
+
114
+ Carries the agent's name as the memo `subject` and the candidate tool
115
+ list as the options the user picks from. Computed through
116
+ manager.candidate_approvals(), the SAME helper approval_notice uses
117
+ and the same one that used to build the grant wholesale -- so the list
118
+ shown, the list offered and the list granted cannot drift apart.
119
+
120
+ Lives on the TOOL rather than in core/loop.py because which tools a
121
+ child could reach is agents/manager.py's knowledge. The loop asks the
122
+ registry for this the same way it asks for the notice.
123
+ """
124
+ from agents.manager import manager
125
+
126
+ agent = manager.get(params.get("agent_name", ""))
127
+ if agent is None:
128
+ return {}
129
+ child = manager.child_context(agent, context or ToolContext())
130
+ return {"subject": agent.name, "agent": agent.name,
131
+ "candidates": manager.candidate_approvals(child)}
132
+
133
+
134
+ def run(params: dict, parent_context=None, parent_run=None,
135
+ response_channel=None, signoff=None) -> dict:
136
+ from core.loop import (
137
+ RunAgentLoop, DEFAULT_PROVIDER, DEFAULT_SYSTEM_PROMPT,
138
+ )
139
+ from agents.manager import manager
140
+
141
+ parent = parent_context or ToolContext()
142
+ # §32 A7. The SAME function the loop consulted before deciding
143
+ # whether to ask and dispatch() applied before its approval gate,
144
+ # so all three agree about what is being refused. It covers the
145
+ # depth limit, the missing-params case (.get not [], because no
146
+ # provider validates tool inputs against the schema and a bare
147
+ # KeyError escapes _run and takes down the turn) and the
148
+ # unknown-agent case.
149
+ #
150
+ # Kept here even though dispatch now short-circuits first: this is
151
+ # the backstop for a caller that reaches run() directly, which is
152
+ # every test in the suite and anything future that composes agents
153
+ # without going through the registry. Two layers, one predicate.
154
+ refusal = refusal_reason(params, parent)
155
+ if refusal:
156
+ return {"error": refusal}
157
+
158
+ name = params.get("agent_name")
159
+ task = params.get("task")
160
+ agent = manager.get(name)
161
+
162
+ child = manager.child_context(agent, parent)
163
+ # The channel is inherited, and it is NOT redundant with the grant.
164
+ # The grant covers what approval_needed(name, {}) can enumerate; a
165
+ # path-dependent approval_check (file_ops outside the workspace, shell
166
+ # on a non-inert command) only resolves once the call exists, so those
167
+ # still have to reach a human mid-run. Without the channel the child
168
+ # ran headless and lost every approval-gated tool silently.
169
+ #
170
+ # §23 AC1b: the grant is the SUBSET the user ticked, not every
171
+ # candidate. §18 shipped this all-or-nothing (S1) because a boolean
172
+ # channel could not carry a list out and a subset back; approving a
173
+ # spawn therefore authorised the child's entire approval-gated set.
174
+ # `signoff` is injected by dispatch() and is None only when nothing
175
+ # asked -- a headless run, where the child gets no grant anyway.
176
+ granted = set(signoff) if signoff else set()
177
+
178
+ # Inherit the parent run's identity only where the agent definition
179
+ # is silent -- an agent's declared model/provider is its identity.
180
+ model = agent.model or (parent_run.model if parent_run else None) \
181
+ or config.MODEL_NAME
182
+ provider = agent.provider \
183
+ or (parent_run.provider_name if parent_run else None) \
184
+ or DEFAULT_PROVIDER
185
+ effort = parent_run.effort if parent_run else None
186
+
187
+ response = RunAgentLoop.run_agent_conversation(
188
+ user_goal=task,
189
+ model=model,
190
+ provider_name=provider,
191
+ max_steps=agent.max_steps or config.MAX_ITERATIONS,
192
+ context=child,
193
+ effort=effort,
194
+ # `child`, not the agent's own context: C6 intersects with the
195
+ # parent, so a parent that excluded spawn_subagent must not have
196
+ # the catalog re-invite its child to spawn one (review f19).
197
+ # #68: the child's own facts, not the parent's. A subagent
198
+ # spawned from a headless run inherits no channel, so its
199
+ # catalogs must be decided by what IT can call -- the same
200
+ # values handed to run_agent_conversation two lines below.
201
+ system_prompt=manager.system_prompt_for(
202
+ agent, DEFAULT_SYSTEM_PROMPT, context=child,
203
+ callable_only=response_channel is None,
204
+ granted=granted),
205
+ response_channel=response_channel,
206
+ granted_tools=granted if (response_channel is not None
207
+ and granted) else None,
208
+ # §27 AC1. A spawned agent's thread is not a conversation anyone
209
+ # will resume, and one goal-mode turn can spawn several.
210
+ thread_kind=THREAD_KIND_SUBAGENT,
211
+ )
212
+ return {
213
+ "result": response.text,
214
+ "subagent_thread_id": str(response.thread_id),
215
+ }
@@ -0,0 +1,136 @@
1
+ """
2
+ agents/tui_commands.py
3
+
4
+ ROADMAP_v2 §18, D6 user-initiated half: /agent, /goal and /grill-me
5
+ register into §16's slash registry. The shell hosts the commands; this
6
+ section owns them -- the same mechanism-vs-policy split tools/registry.py
7
+ uses for tools. TUI-only for now (CLI stays unchanged per the §18 scope
8
+ decision); the model-initiated half lives in subagent_tool.py and works
9
+ in every shell.
10
+
11
+ Handlers receive the app object from tui.commands.dispatch(); this module
12
+ deliberately does NOT import tui.app, so app.py can import it without a
13
+ cycle.
14
+ """
15
+
16
+ from tui.commands import SlashCommand, registry as commands
17
+ from agents.manager import manager
18
+
19
+
20
+ def _cmd_agent(app, args: str) -> None:
21
+ """Session-scoped active agent: subsequent turns run under the
22
+ agent's body, model/provider/max_steps overrides, and ToolContext,
23
+ until /agent default or another switch."""
24
+ if not args:
25
+ current = app.active_agent.name if app.active_agent else "default"
26
+ app._transcript.write_system(
27
+ f"Active agent: {current}. "
28
+ f"Available: {', '.join(manager.names()) or 'none'}. "
29
+ "/agent <name> to switch, /agent default to clear."
30
+ )
31
+ return
32
+ if args == "default":
33
+ app.active_agent = None
34
+ app._transcript.write_system("Active agent cleared — default harness.")
35
+ _note_skills_under_new_context(app)
36
+ return
37
+ agent = manager.get(args)
38
+ if agent is None:
39
+ app._transcript.write_error(
40
+ f"Unknown agent {args!r}. "
41
+ f"Available: {', '.join(manager.names()) or 'none'}."
42
+ )
43
+ return
44
+ app.active_agent = agent
45
+ app._transcript.write_system(
46
+ f"Active agent: {agent.name} — {agent.description}")
47
+ _note_skills_under_new_context(app)
48
+
49
+
50
+ def _note_skills_under_new_context(app) -> None:
51
+ """K2's activation note is computed against the context active at
52
+ activation time; an /agent switch changes the context for every
53
+ subsequent turn, so re-check active skills and say what is now
54
+ denied (review §19-20 f21). Advisory only -- enforcement still
55
+ happens per call via is_tool_allowed."""
56
+ from skills.manager import manager as skill_manager
57
+
58
+ context = (manager.active_context(app.active_agent)
59
+ if app.active_agent is not None else None)
60
+ label = app.active_agent.name if app.active_agent is not None else "default"
61
+ for name in app.active_skills:
62
+ skill = skill_manager.get(name)
63
+ if skill is None:
64
+ continue
65
+ missing = skill_manager.missing_tools(skill, context)
66
+ if missing:
67
+ app._transcript.write_system(
68
+ f"Note: {name} expects {', '.join(missing)}, which are "
69
+ f"not available under agent {label}.")
70
+
71
+
72
+ def _cmd_goal(app, args: str) -> None:
73
+ """Persistent per-thread objective (extra_data). Injected into every
74
+ turn's system prompt in ANY shell; the banner mirrors it here.
75
+
76
+ #113: the read and clear paths go through `app._memory`, NOT
77
+ `app.memory` -- same rule refresh_goal_banner's comment states.
78
+ Constructing a ConversationMemory persists a thread row, so answering
79
+ "there is no goal" (or clearing one on a session that has none) must
80
+ not be what creates the thread. Only SETTING a goal touches
81
+ app.memory: the user is putting state on a thread, so a thread is
82
+ warranted."""
83
+ if args == "clear":
84
+ if app._memory is None:
85
+ app._transcript.write_system("No goal set.")
86
+ else:
87
+ app.memory.set_extra("goal", None)
88
+ app._transcript.write_system("Goal cleared.")
89
+ elif args:
90
+ app.memory.set_extra("goal", args)
91
+ app._transcript.write_system(f"Goal set: {args}")
92
+ else:
93
+ goal = app._memory.extra.get("goal") if app._memory else None
94
+ if goal:
95
+ app._transcript.write_system(f"Current goal: {goal}")
96
+ else:
97
+ app._transcript.write_system(
98
+ "No goal set. /goal <text> to set one, /goal clear to remove.")
99
+ app.refresh_goal_banner()
100
+
101
+
102
+ def _cmd_grill(app, args: str) -> None:
103
+ """One turn in the CURRENT thread under the grill-me agent's system
104
+ prompt -- it reads the live history directly (no digest loss)."""
105
+ if app._busy:
106
+ app._transcript.write_error(
107
+ "Still working — wait for this turn to finish.")
108
+ return
109
+ agent = manager.get("grill-me")
110
+ if agent is None:
111
+ app._transcript.write_error("grill-me agent not found.")
112
+ return
113
+ app._transcript.write_user("/grill-me")
114
+ # run_one_shot owns the WHOLE assembly (#170): the channel, the
115
+ # catalog facts and the run must come from one answer, so nothing is
116
+ # decided here. (Review f19's "no context, deliberately" answered a
117
+ # question §25 R15 replaced -- what matters now is not which policy
118
+ # governs but whether anything can answer, and only the run knows.)
119
+ app.run_one_shot(
120
+ agent,
121
+ "Grill this thread: surface what still needs a decision.",
122
+ )
123
+
124
+
125
+ def register_agent_commands() -> None:
126
+ """Idempotent — registering by name overwrites, matching §16's
127
+ register_builtin_commands()."""
128
+ for command in (
129
+ SlashCommand("agent", "switch the active agent", _cmd_agent,
130
+ "[name|default]"),
131
+ SlashCommand("goal", "set the thread's persistent objective",
132
+ _cmd_goal, "[text|clear]"),
133
+ SlashCommand("grill-me", "surface what still needs a decision",
134
+ _cmd_grill),
135
+ ):
136
+ commands.register(command)