@yahyahammad/venastine 0.2.0 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/.env.example +9 -4
  2. package/CONFIG_ARCHITECTURE.md +2030 -0
  3. package/LICENSE +201 -201
  4. package/NOTICE +1 -1
  5. package/README.md +1034 -895
  6. package/agents/builtin/build.md +73 -0
  7. package/agents/builtin/compactor.md +75 -75
  8. package/agents/builtin/explore.md +77 -77
  9. package/agents/builtin/general.md +80 -0
  10. package/agents/builtin/pipeline-reviewer.md +100 -100
  11. package/agents/builtin/plan.md +106 -88
  12. package/agents/builtin/review.md +74 -74
  13. package/agents/builtin/test.md +65 -0
  14. package/agents/builtin/writer.md +67 -0
  15. package/agents/manager.py +68 -2
  16. package/agents/subagent_tool.py +472 -238
  17. package/agents/tui_commands.py +238 -151
  18. package/bin/venastine.mjs +150 -4
  19. package/bin/venastine.py +71 -0
  20. package/cli_commands.py +838 -0
  21. package/config.py +95 -1198
  22. package/config.yaml +1103 -0
  23. package/config_edit.py +1301 -0
  24. package/config_schema.py +971 -0
  25. package/config_update.py +749 -0
  26. package/core/agent_activity.py +256 -118
  27. package/core/ansi.py +452 -0
  28. package/core/approval.py +137 -115
  29. package/core/call_view.py +364 -0
  30. package/core/cancel.py +121 -0
  31. package/core/chatgpt_auth.py +747 -0
  32. package/core/claims_view.py +107 -0
  33. package/core/client.py +2715 -1559
  34. package/core/commands.py +460 -0
  35. package/core/compaction.py +1735 -971
  36. package/core/config_loader.py +1982 -1563
  37. package/core/connect.py +686 -0
  38. package/core/events.py +123 -61
  39. package/core/file_mentions.py +280 -0
  40. package/core/interaction.py +411 -328
  41. package/core/line_pattern.py +128 -0
  42. package/core/loop.py +2566 -1490
  43. package/core/memory.py +482 -370
  44. package/core/pipeline_models.py +190 -176
  45. package/core/provider_errors.py +234 -0
  46. package/core/reasoning/authorization.py +130 -130
  47. package/core/reasoning/base.py +219 -219
  48. package/core/reasoning/confidence_scoring.py +484 -468
  49. package/core/reasoning/events.py +149 -149
  50. package/core/reasoning/json_retry.py +19 -1
  51. package/core/reasoning/orchestrator.py +1561 -1382
  52. package/core/reasoning/output_writer.py +345 -286
  53. package/core/reasoning/payload_validation.py +524 -398
  54. package/core/reasoning/pipeline_storage.py +88 -22
  55. package/core/reasoning/review.py +659 -615
  56. package/core/reasoning/scholar.py +458 -434
  57. package/core/reasoning/source_corpus.py +433 -327
  58. package/core/reasoning/source_scoring.py +855 -855
  59. package/core/replay.py +315 -183
  60. package/core/session.py +36 -12
  61. package/core/session_view.py +259 -0
  62. package/core/session_wake.py +259 -0
  63. package/core/shell_sessions.py +1553 -0
  64. package/core/workspace_trust.py +1 -1
  65. package/credentials.py +148 -20
  66. package/database.py +333 -252
  67. package/{PRIVACY.md → docs/PRIVACY.md} +78 -66
  68. package/docs/SECURITY.md +108 -0
  69. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  70. package/env_secrets.py +50 -9
  71. package/json_store.py +343 -123
  72. package/logging_setup.py +295 -185
  73. package/main.py +3433 -1961
  74. package/mcp_client/client.py +733 -499
  75. package/mcp_client/config.py +126 -21
  76. package/mcp_client/registration.py +343 -182
  77. package/memories/manager.py +147 -132
  78. package/memories/tui_commands.py +319 -244
  79. package/package.json +303 -73
  80. package/project_init/config_files.py +282 -278
  81. package/project_init/generator.py +728 -564
  82. package/project_init/manifest.py +18 -6
  83. package/project_init/tui_commands.py +147 -144
  84. package/prompts/critic_pass.md +24 -24
  85. package/prompts/revalidate.md +25 -25
  86. package/prompts/revise.md +2 -0
  87. package/prompts/source_grounding.md +66 -66
  88. package/prompts/system_prompts.py +316 -262
  89. package/providers.json.example +4 -2
  90. package/pyproject.toml +149 -100
  91. package/requirements.txt +295 -72
  92. package/safety/policy_enforcement.py +1082 -746
  93. package/security/askpass.py +419 -0
  94. package/security/capability.py +207 -177
  95. package/security/confine.py +484 -0
  96. package/security/hosted.py +182 -0
  97. package/security/permissions.py +237 -190
  98. package/security/posture.py +124 -12
  99. package/security/protected_paths.py +501 -309
  100. package/security/sandbox.py +4108 -985
  101. package/security/secrets.py +855 -0
  102. package/skills/builtin/math/formal-specification.md +67 -67
  103. package/skills/builtin/math/numerical-methods.md +66 -66
  104. package/skills/builtin/research/experiment-design.md +62 -62
  105. package/skills/builtin/research/reproducibility.md +55 -55
  106. package/skills/builtin/research/source-evaluation.md +70 -70
  107. package/skills/builtin/research/statistical-inference.md +63 -63
  108. package/skills/builtin/research/technical-writing.md +59 -59
  109. package/skills/builtin/software/code-review.md +61 -61
  110. package/skills/builtin/software/debugging.md +61 -61
  111. package/skills/builtin/software/test-design.md +67 -67
  112. package/skills/tui_commands.py +110 -111
  113. package/storage.py +1338 -1005
  114. package/tools/base.py +161 -1
  115. package/tools/builtin/_math_common.py +667 -377
  116. package/tools/builtin/_net_common.py +225 -19
  117. package/tools/builtin/arxiv.py +497 -39
  118. package/tools/builtin/ask_user.py +231 -213
  119. package/tools/builtin/discrete_math.py +35 -4
  120. package/tools/builtin/fetch_url.py +371 -153
  121. package/tools/builtin/file_ops.py +720 -412
  122. package/tools/builtin/geometry.py +48 -12
  123. package/tools/builtin/get_time.py +2 -2
  124. package/tools/builtin/linear_algebra.py +66 -23
  125. package/tools/builtin/load_skill.py +76 -66
  126. package/tools/builtin/logic.py +171 -12
  127. package/tools/builtin/pin.py +227 -193
  128. package/tools/builtin/probability_stats.py +12 -16
  129. package/tools/builtin/project_docs.py +464 -405
  130. package/tools/builtin/remember.py +175 -158
  131. package/tools/builtin/shell.py +980 -461
  132. package/tools/builtin/shell_sessions.py +613 -0
  133. package/tools/builtin/symbolic_math.py +80 -10
  134. package/tools/builtin/todo.py +149 -147
  135. package/tools/builtin/web_search.py +191 -13
  136. package/tools/context.py +159 -136
  137. package/tools/isolation.py +107 -34
  138. package/tools/registry.py +1242 -925
  139. package/tui/app.py +8318 -4100
  140. package/tui/app.tcss +747 -556
  141. package/tui/commands.py +26 -170
  142. package/tui/diffs.py +34 -13
  143. package/tui/history.py +128 -128
  144. package/tui/hosted_driver.py +102 -0
  145. package/tui/markdown.py +1329 -1279
  146. package/tui/meters.py +364 -268
  147. package/tui/ravens.py +146 -146
  148. package/tui/screens.py +1255 -943
  149. package/tui/themes.py +599 -559
  150. package/tui/widgets.py +3813 -2332
  151. package/SECURITY.md +0 -88
  152. package/THIRD_PARTY_NOTICES.md +0 -100
@@ -1,213 +1,231 @@
1
- """
2
- tools/builtin/ask_user.py
3
-
4
- ROADMAP_v2 §23 slice 2: the question tool. "Up to 4 options, multi-select, a
5
- write-your-own answer, and a 'chat about this' escape that returns control to
6
- the conversation instead of forcing a choice."
7
-
8
- IT ASKS THROUGH THE INJECTED CHANNEL, NOT THROUGH THE APPROVAL BRIDGE. The
9
- loop's `_obtain_approval` fires only under `if needs_approval:`, builds a
10
- payload of {"tool_name", "params"}, and coerces the answer to (bool, grant) --
11
- a free-text or multi-select answer has nowhere to go in it. It does not need
12
- one: `response_channel` is already an injectable parameter, handed to every
13
- handler that names it on BOTH dispatch branches, which is what
14
- tools/registry.py's `_INJECTABLE_PARAMS` comment anticipated -- "generalised
15
- so §23's response-channel tools add a third injectable name without reopening
16
- dispatch()". So core/loop.py is untouched by this tool.
17
-
18
- UNGATED, DELIBERATELY (J12). Requiring approval to ask a question would mean
19
- approving a prompt in order to be shown a prompt -- and worse, §13 does not
20
- merely deny a gated tool where nothing can ask, it stops ADVERTISING it. A
21
- gated question tool would be invisible in every headless run rather than
22
- denied with a reason, and §23 AC2 wants the opposite: the model must see the tool,
23
- call it, and receive "there is nobody to ask" as something it can work around.
24
- Same shape as `pin`'s ungating (D26), for the same reason.
25
-
26
- NO CHANNEL MEANS DENIED, AND THE DENIAL EXPLAINS ITSELF (§23 AC2). An unattended
27
- ten-pass pipeline is exactly where a blocking prompt nobody will answer turns
28
- into a hang, and where a question injected by fetched web content would be
29
- least noticed. An attended run carries a channel and can ask -- that is §25's
30
- amendment, and it is why the condition tested here is "is there a channel"
31
- rather than "is this the pipeline".
32
- """
33
-
34
- import logging
35
-
36
- from core import interaction
37
-
38
- logger = logging.getLogger(__name__)
39
-
40
- # The spec's cap, enforced rather than advisory. See run() for why a fifth
41
- # option is an error and not a truncation.
42
- MAX_OPTIONS = 4
43
-
44
- #: Longest option the modal can show whole (batch 49). QuestionScreen is a
45
- #: fixed 66 columns and an option button 58 of them, so 100 characters is
46
- #: two wrapped lines for every shape measured -- prose, twenty-character
47
- #: words, and an unbroken run -- and 105 is three for two of them. It is a
48
- #: BUDGET, not a guess: the options region scrolls, so exceeding it costs
49
- #: legibility rather than correctness, and the number is re-derivable by
50
- #: the test that measures the drawn rows rather than trusting this
51
- #: comment.
52
- MAX_OPTION_CHARS = 100
53
-
54
- TOOL_SCHEMA = {
55
- "name": "ask_user",
56
- "description": (
57
- "Ask the user a question and wait for their answer. Use this when a "
58
- "decision is genuinely theirs to make and getting it wrong would "
59
- "waste work -- an ambiguous requirement, a choice between "
60
- "approaches with different tradeoffs, a missing fact only they "
61
- "have. Do NOT use it for things you can determine yourself, or to "
62
- "confirm work you have already been asked to do. The user can pick "
63
- "one or more of your options, write their own answer, or ask to "
64
- "discuss it instead of choosing."
65
- ),
66
- "input_schema": {
67
- "type": "object",
68
- "properties": {
69
- "question": {
70
- "type": "string",
71
- "description": "The question, in one or two sentences. State "
72
- "what you need and why it changes what you "
73
- "will do.",
74
- },
75
- "options": {
76
- "type": "array",
77
- "items": {"type": "string"},
78
- "description": f"Up to {MAX_OPTIONS} concrete answers to "
79
- f"choose from. Optional -- omit it to ask an "
80
- f"open question. Each must be at most "
81
- f"{MAX_OPTION_CHARS} characters, so it can be "
82
- f"shown whole -- put the reasoning in the "
83
- f"question, not in the options.",
84
- },
85
- "multi_select": {
86
- "type": "boolean",
87
- "description": "True if several options can be chosen "
88
- "together. Defaults to false.",
89
- },
90
- "allow_text": {
91
- "type": "boolean",
92
- "description": "Whether the user may write their own answer "
93
- "instead of picking. Defaults to true.",
94
- },
95
- },
96
- "required": ["question"],
97
- },
98
- }
99
-
100
-
101
- def run(params: dict, response_channel=None) -> dict:
102
- # params.get throughout, never params[]: no provider validates tool
103
- # inputs against the schema, and a bare KeyError escapes the loop's
104
- # ToolCallDenied handler and takes down the whole turn. pin.py's rule.
105
- question = params.get("question")
106
- if not question or not isinstance(question, str):
107
- return {"error": "ask_user requires a 'question' string."}
108
-
109
- options = params.get("options") or []
110
- if not isinstance(options, (list, tuple)):
111
- return {"error": "ask_user requires 'options' to be a list of strings."}
112
- options = [str(o) for o in options]
113
-
114
- if len(options) > MAX_OPTIONS:
115
- # AN ERROR, NOT A TRUNCATION. Silently dropping the fifth option
116
- # would show the user a different question from the one the model
117
- # asked, and the model would then read the answer as a response to
118
- # the full list. M15's rule -- never silently drop something
119
- # somebody named -- with the model in the naming role. An error it
120
- # can correct costs one step; a mis-answered question costs the
121
- # decision.
122
- return {
123
- "error": f"ask_user allows at most {MAX_OPTIONS} options; "
124
- f"{len(options)} were given. Ask a narrower question, "
125
- f"or drop the options and ask it openly.",
126
- }
127
-
128
- too_long = [o for o in options if len(o) > MAX_OPTION_CHARS]
129
- if too_long:
130
- # AN ERROR, NOT A TRUNCATION, for the reason directly above: an
131
- # option shortened here is not the option the model offered, and
132
- # the answer would come back as though it were. The modal used to
133
- # truncate this way by accident -- an option wider than the dialog
134
- # was CUT at its edge, so a user chose between two options whose
135
- # visible halves were identical -- which is the failure this
136
- # refusal exists to make impossible rather than merely unlikely.
137
- longest = max(too_long, key=len)
138
- return {
139
- "error": f"ask_user allows at most {MAX_OPTION_CHARS} characters "
140
- f"per option so it can be read whole; one is "
141
- f"{len(longest)}. Shorten it to the choice itself and "
142
- f"put the reasoning in the question: "
143
- f"{longest[:60]!r}...",
144
- }
145
-
146
- if not options and params.get("allow_text", True) is False:
147
- # #114, same family as the two refusals above: a question with no
148
- # options and no text box renders as a modal whose only button is
149
- # "Discuss instead", so a defer means "that was my only button"
150
- # rather than "let's talk about it" -- collapsing exactly the
151
- # distinction QuestionScreen's escape/defer pair exists to keep.
152
- return {
153
- "error": "ask_user needs something to answer with: give "
154
- "options, or leave allow_text true so the user can "
155
- "write a reply.",
156
- }
157
-
158
- if response_channel is None:
159
- # §23 AC2. Not an exception: dispatch would convert one to an error dict
160
- # anyway, and this way the message is written for the reader who
161
- # needs it -- a model mid-run that must now decide something itself.
162
- return {
163
- "error": "ask_user cannot reach anyone in this run -- there is "
164
- "nobody to answer. Decide it yourself, state the "
165
- "assumption you are proceeding on, and carry on.",
166
- }
167
-
168
- answer = interaction.ask(response_channel, interaction.Request(
169
- kind=interaction.QUESTION,
170
- payload={
171
- "question": question,
172
- "options": options,
173
- "multi_select": bool(params.get("multi_select")),
174
- # Defaults TRUE: the spec lists a write-your-own answer as one of
175
- # the four affordances, so absence of the key is not absence of
176
- # the affordance.
177
- "allow_text": params.get("allow_text", True) is not False,
178
- },
179
- ))
180
-
181
- if answer is None:
182
- # Nobody answered -- dismissed, timed out, or a shell returning
183
- # something decode could not read. Distinct from a deferral below,
184
- # and reported as such: "they declined to answer" and "they want to
185
- # discuss it" call for different next moves.
186
- return {
187
- "error": "The user did not answer the question. Proceed on your "
188
- "best judgement and say which assumption you made.",
189
- }
190
-
191
- if answer.get("defer"):
192
- # The spec's escape, "returns control to the conversation instead of
193
- # forcing a choice". A result rather than any change of control
194
- # flow: the loop has one shape, and a tool that could abort a turn
195
- # would be a second one. The model simply talks next.
196
- return {
197
- "result": "The user would rather discuss this than pick an "
198
- "answer. Raise it in conversation -- do not call "
199
- "ask_user again for the same question.",
200
- }
201
-
202
- chosen, text = answer.get("options") or [], answer.get("text") or ""
203
- if not chosen and not text:
204
- # A blank submission. They were present and said nothing, which is
205
- # not the same as never being asked -- so this is not the no-channel
206
- # error, and the wording does not tell the model to assume anything.
207
- return {
208
- "result": "The user answered without choosing an option or "
209
- "writing anything. Ask again more specifically, or "
210
- "raise it in conversation.",
211
- }
212
-
213
- return {"result": {"chosen": chosen, "text": text}}
1
+ """
2
+ tools/builtin/ask_user.py
3
+
4
+ ROADMAP_v2 §23 slice 2: the question tool. "Up to 4 options, multi-select, a
5
+ write-your-own answer, and a 'chat about this' escape that returns control to
6
+ the conversation instead of forcing a choice."
7
+
8
+ IT ASKS THROUGH THE INJECTED CHANNEL, NOT THROUGH THE APPROVAL BRIDGE. The
9
+ loop's `_obtain_approval` fires only under `if needs_approval:`, builds a
10
+ payload of {"tool_name", "params"}, and coerces the answer to (bool, grant) --
11
+ a free-text or multi-select answer has nowhere to go in it. It does not need
12
+ one: `response_channel` is already an injectable parameter, handed to every
13
+ handler that names it on BOTH dispatch branches, which is what
14
+ tools/registry.py's `_INJECTABLE_PARAMS` comment anticipated -- "generalised
15
+ so §23's response-channel tools add a third injectable name without reopening
16
+ dispatch()". So core/loop.py is untouched by this tool.
17
+
18
+ UNGATED, DELIBERATELY (J12). Requiring approval to ask a question would mean
19
+ approving a prompt in order to be shown a prompt -- and worse, §13 does not
20
+ merely deny a gated tool where nothing can ask, it stops ADVERTISING it. A
21
+ gated question tool would be invisible in every headless run rather than
22
+ denied with a reason, and §23 AC2 wants the opposite: the model must see the tool,
23
+ call it, and receive "there is nobody to ask" as something it can work around.
24
+ Same shape as `pin`'s ungating (D26), for the same reason.
25
+
26
+ NO CHANNEL MEANS DENIED, AND THE DENIAL EXPLAINS ITSELF (§23 AC2). An unattended
27
+ ten-pass pipeline is exactly where a blocking prompt nobody will answer turns
28
+ into a hang, and where a question injected by fetched web content would be
29
+ least noticed. An attended run carries a channel and can ask -- that is §25's
30
+ amendment, and it is why the condition tested here is "is there a channel"
31
+ rather than "is this the pipeline".
32
+ """
33
+
34
+ import logging
35
+
36
+ from core import agent_activity, interaction
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ # The spec's cap, enforced rather than advisory. See run() for why a fifth
41
+ # option is an error and not a truncation.
42
+ MAX_OPTIONS = 4
43
+
44
+ #: Longest option the modal can show whole (batch 49). QuestionScreen is a
45
+ #: fixed 66 columns and an option button 58 of them, so 100 characters is
46
+ #: two wrapped lines for every shape measured -- prose, twenty-character
47
+ #: words, and an unbroken run -- and 105 is three for two of them. It is a
48
+ #: BUDGET, not a guess: the options region scrolls, so exceeding it costs
49
+ #: legibility rather than correctness, and the number is re-derivable by
50
+ #: the test that measures the drawn rows rather than trusting this
51
+ #: comment.
52
+ MAX_OPTION_CHARS = 100
53
+
54
+ TOOL_SCHEMA = {
55
+ "name": "ask_user",
56
+ "description": (
57
+ "Ask the user a question and wait for their answer. Use this when a "
58
+ "decision is genuinely theirs to make and getting it wrong would "
59
+ "waste work -- an ambiguous requirement, a choice between "
60
+ "approaches with different tradeoffs, a missing fact only they "
61
+ "have. Do NOT use it for things you can determine yourself, or to "
62
+ "confirm work you have already been asked to do. The user can pick "
63
+ "one or more of your options, write their own answer, or ask to "
64
+ "discuss it instead of choosing."
65
+ ),
66
+ "input_schema": {
67
+ "type": "object",
68
+ "properties": {
69
+ "question": {
70
+ "type": "string",
71
+ "description": "The question, in one or two sentences. State "
72
+ "what you need and why it changes what you "
73
+ "will do.",
74
+ },
75
+ "options": {
76
+ "type": "array",
77
+ "items": {"type": "string"},
78
+ "description": f"Up to {MAX_OPTIONS} concrete answers to "
79
+ f"choose from. Optional -- omit it to ask an "
80
+ f"open question. Each must be at most "
81
+ f"{MAX_OPTION_CHARS} characters, so it can be "
82
+ f"shown whole -- put the reasoning in the "
83
+ f"question, not in the options.",
84
+ },
85
+ "multi_select": {
86
+ "type": "boolean",
87
+ "description": "True if several options can be chosen "
88
+ "together. Defaults to false.",
89
+ },
90
+ "allow_text": {
91
+ "type": "boolean",
92
+ "description": "Whether the user may write their own answer "
93
+ "instead of picking. Defaults to true.",
94
+ },
95
+ },
96
+ "required": ["question"],
97
+ },
98
+ }
99
+
100
+
101
+ def run(params: dict, response_channel=None) -> dict:
102
+ # params.get throughout, never params[]: no provider validates tool
103
+ # inputs against the schema. tools/base.py carries the one copy of why, under
104
+ # "WHAT A CALLABLE REGISTERED BELOW MAY RAISE": a handler's exception IS
105
+ # contained, so what this buys is an error dict the model can READ rather
106
+ # than the generic wrapper dispatch() would return (batch 146).
107
+ question = params.get("question")
108
+ if not question or not isinstance(question, str):
109
+ return {"error": "ask_user requires a 'question' string."}
110
+
111
+ options = params.get("options") or []
112
+ if not isinstance(options, (list, tuple)):
113
+ return {"error": "ask_user requires 'options' to be a list of strings."}
114
+ options = [str(o) for o in options]
115
+
116
+ if len(options) > MAX_OPTIONS:
117
+ # AN ERROR, NOT A TRUNCATION. Silently dropping the fifth option
118
+ # would show the user a different question from the one the model
119
+ # asked, and the model would then read the answer as a response to
120
+ # the full list. M15's rule -- never silently drop something
121
+ # somebody named -- with the model in the naming role. An error it
122
+ # can correct costs one step; a mis-answered question costs the
123
+ # decision.
124
+ return {
125
+ "error": f"ask_user allows at most {MAX_OPTIONS} options; "
126
+ f"{len(options)} were given. Ask a narrower question, "
127
+ f"or drop the options and ask it openly.",
128
+ }
129
+
130
+ too_long = [o for o in options if len(o) > MAX_OPTION_CHARS]
131
+ if too_long:
132
+ # AN ERROR, NOT A TRUNCATION, for the reason directly above: an
133
+ # option shortened here is not the option the model offered, and
134
+ # the answer would come back as though it were. The modal used to
135
+ # truncate this way by accident -- an option wider than the dialog
136
+ # was CUT at its edge, so a user chose between two options whose
137
+ # visible halves were identical -- which is the failure this
138
+ # refusal exists to make impossible rather than merely unlikely.
139
+ longest = max(too_long, key=len)
140
+ return {
141
+ "error": f"ask_user allows at most {MAX_OPTION_CHARS} characters "
142
+ f"per option so it can be read whole; one is "
143
+ f"{len(longest)}. Shorten it to the choice itself and "
144
+ f"put the reasoning in the question: "
145
+ f"{longest[:60]!r}...",
146
+ }
147
+
148
+ if not options and params.get("allow_text", True) is False:
149
+ # #114, same family as the two refusals above: a question with no
150
+ # options and no text box renders as a modal whose only button is
151
+ # "Discuss instead", so a defer means "that was my only button"
152
+ # rather than "let's talk about it" -- collapsing exactly the
153
+ # distinction QuestionScreen's escape/defer pair exists to keep.
154
+ return {
155
+ "error": "ask_user needs something to answer with: give "
156
+ "options, or leave allow_text true so the user can "
157
+ "write a reply.",
158
+ }
159
+
160
+ if response_channel is None:
161
+ # §23 AC2. Not an exception: dispatch would convert one to an error dict
162
+ # anyway, and this way the message is written for the reader who
163
+ # needs it -- a model mid-run that must now decide something itself.
164
+ return {
165
+ "error": "ask_user cannot reach anyone in this run -- there is "
166
+ "nobody to answer. Decide it yourself, state the "
167
+ "assumption you are proceeding on, and carry on.",
168
+ }
169
+
170
+ # §47, added by batch 75's review of it. WHICH run is asking, read off
171
+ # the open span rather than threaded through the tool's parameters --
172
+ # the same source and the same reason as `_obtain_approval`'s: params
173
+ # are the MODEL'S, and a model that could name its own asker could
174
+ # claim to be a run it is not.
175
+ #
176
+ # THE PRODUCER, because `core/interaction.py` cannot be. That module is
177
+ # the one place every question goes through and would be the tidy home
178
+ # for this, but it is a stdlib-only leaf -- `tests/test_interaction.py`
179
+ # pins its import list -- so reaching `core.agent_activity` from there
180
+ # would break a boundary to save one line here.
181
+ #
182
+ # None at depth 0, where the asking run is the conversation on screen.
183
+ asking = agent_activity.current()
184
+ answer = interaction.ask(response_channel, interaction.Request(
185
+ kind=interaction.QUESTION,
186
+ payload={
187
+ "question": question,
188
+ "options": options,
189
+ "multi_select": bool(params.get("multi_select")),
190
+ # Defaults TRUE: the spec lists a write-your-own answer as one of
191
+ # the four affordances, so absence of the key is not absence of
192
+ # the affordance.
193
+ "allow_text": params.get("allow_text", True) is not False,
194
+ "asking_agent": asking.name if asking is not None else None,
195
+ "asking_depth": asking.depth if asking is not None else 0,
196
+ },
197
+ ))
198
+
199
+ if answer is None:
200
+ # Nobody answered -- dismissed, timed out, or a shell returning
201
+ # something decode could not read. Distinct from a deferral below,
202
+ # and reported as such: "they declined to answer" and "they want to
203
+ # discuss it" call for different next moves.
204
+ return {
205
+ "error": "The user did not answer the question. Proceed on your "
206
+ "best judgement and say which assumption you made.",
207
+ }
208
+
209
+ if answer.get("defer"):
210
+ # The spec's escape, "returns control to the conversation instead of
211
+ # forcing a choice". A result rather than any change of control
212
+ # flow: the loop has one shape, and a tool that could abort a turn
213
+ # would be a second one. The model simply talks next.
214
+ return {
215
+ "result": "The user would rather discuss this than pick an "
216
+ "answer. Raise it in conversation -- do not call "
217
+ "ask_user again for the same question.",
218
+ }
219
+
220
+ chosen, text = answer.get("options") or [], answer.get("text") or ""
221
+ if not chosen and not text:
222
+ # A blank submission. They were present and said nothing, which is
223
+ # not the same as never being asked -- so this is not the no-channel
224
+ # error, and the wording does not tell the model to assume anything.
225
+ return {
226
+ "result": "The user answered without choosing an option or "
227
+ "writing anything. Ask again more specifically, or "
228
+ "raise it in conversation.",
229
+ }
230
+
231
+ return {"result": {"chosen": chosen, "text": text}}
@@ -12,6 +12,8 @@ from typing import Literal, Optional
12
12
  import sympy
13
13
  from pydantic import BaseModel, Field
14
14
 
15
+ from tools.builtin._math_common import MathParseError, parse_params
16
+
15
17
  _OPERATIONS = Literal[
16
18
  "gcd", "lcm", "is_prime", "prime_factors", "next_prime",
17
19
  "factorial", "permutations", "combinations",
@@ -42,7 +44,10 @@ TOOL_SCHEMA = {
42
44
 
43
45
 
44
46
  def run(params: dict) -> dict:
45
- parsed = DiscreteMathParams(**params)
47
+ try:
48
+ parsed = parse_params(DiscreteMathParams, params)
49
+ except MathParseError as e:
50
+ return {"error": str(e)}
46
51
 
47
52
  try:
48
53
  op = parsed.operation
@@ -72,11 +77,37 @@ def run(params: dict) -> dict:
72
77
  return {"error": "factorial requires 'n' (integer)."}
73
78
  result = sympy.factorial(parsed.n)
74
79
  elif op == "permutations":
75
- # nPr = n! / (n-r)! -- computed directly rather than relying
76
- # on a less-common sympy function name.
80
+ # nPr AS THE FALLING FACTORIAL, which is O(r). It used to be
81
+ # `factorial(n) / factorial(n - r)`, so its cost was in `n`
82
+ # while the operation's cost is in `r` -- and `combinations`,
83
+ # four lines below in this same chain, was already O(r) via
84
+ # `binomial`. Measured, with `combinations` on identical
85
+ # inputs as the control in every row:
86
+ #
87
+ # permutations n=100000 r=1 0.14s
88
+ # permutations n=1000000 r=1 15.27s of a 20s budget
89
+ # permutations n=3000000 r=1 killed at the wall clock,
90
+ # 48.07s uncontained
91
+ # combinations n=3000000 r=1 0.0002s -> 3000000
92
+ #
93
+ # At r=1 the two operations return the same number, and the
94
+ # model was told "the inputs given are too large for this
95
+ # operation" about one multiplication. `ff` agrees with the
96
+ # factorial form everywhere both are defined, checked
97
+ # including the edges: ff(5,7)=0 (the old form divided by
98
+ # factorial(-2)=zoo) and ff(10,-1)=1/11.
99
+ #
100
+ # This is H5's trade -- paying a full budget to learn the
101
+ # answer is the wrong answer -- and it does NOT contradict H4,
102
+ # which refuses a per-parameter CEILING. The fix is an
103
+ # algorithm. H4's rationale ("cost is joint, so no
104
+ # per-parameter ceiling expresses it") was true of
105
+ # `combinations` and false of this line as it stood; the
106
+ # comment that stood here preferred a common sympy name to the
107
+ # right complexity class.
77
108
  if parsed.n is None or parsed.r is None:
78
109
  return {"error": "permutations requires 'n' and 'r' (integers)."}
79
- result = sympy.factorial(parsed.n) / sympy.factorial(parsed.n - parsed.r)
110
+ result = sympy.ff(parsed.n, parsed.r)
80
111
  elif op == "combinations":
81
112
  if parsed.n is None or parsed.r is None:
82
113
  return {"error": "combinations requires 'n' and 'r' (integers)."}