@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
@@ -0,0 +1,460 @@
1
+ """
2
+ core/commands.py
3
+
4
+ The slash-command CATALOG both shells bind to, and the registry mechanism
5
+ each of them binds with (ROADMAP_v3 §89, #8).
6
+
7
+ WHY ONE CATALOG. D12 makes the CLI a permanent fallback, and the failure
8
+ mode issue #8 names is the two shells disagreeing about what a command IS
9
+ -- what `/compact` is called, what it takes, what it says it does. So a
10
+ command's name, summary, usage and aliases are declared here once, and a
11
+ shell does not describe a command: it BINDS a handler to one by name.
12
+ `core/replay.py`'s reason (§26 L6), one subject over: one place decides
13
+ what exists, and each shell decides how to run it.
14
+
15
+ WHY NOT ONE HANDLER. A handler is where the shells genuinely differ -- the
16
+ TUI pushes a modal and runs a worker, the CLI prints and reads a line --
17
+ so each shell keeps its own, and what they share is the CORE FUNCTIONS
18
+ both handlers call (`attach_ref`, `summarize_thread`, `compact`,
19
+ `render_claims`, `agent_turn`). The handlers are thin on purpose; a
20
+ handler with policy inline is the copy that drifts.
21
+
22
+ A COMMAND ONE SHELL CANNOT HAVE SAYS WHY. `absent` maps a shell to the
23
+ sentence that explains it -- `/theme` has nothing to theme on a
24
+ line-based terminal, `/call` is the CLI's spelling of the TUI's
25
+ ctrl+click -- and both shells answer a name they lack with that sentence
26
+ rather than with "unknown command". A shell absent from the map binds a
27
+ handler, and `tests/test_command_catalog.py` holds every shell to that.
28
+
29
+ THE MECHANISM MOVED HERE FROM `tui/commands.py` UNCHANGED, apart from the
30
+ binding check: the CLI needs the same registry and must not import from
31
+ `tui/` to get it. `tui/commands.py` re-exports it.
32
+
33
+ A handler takes (shell_state, argument_string) and returns None. In the
34
+ TUI the state is the app and the handler runs on the UI thread, so
35
+ anything slow belongs in a worker; in the CLI it is `cli_commands.
36
+ ChatSession` and the handler runs on the chat loop's own thread.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import logging
42
+ from collections.abc import Callable
43
+ from dataclasses import dataclass, field
44
+ from typing import Optional
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ #: The two shells. Strings rather than an enum because they are keys in
49
+ #: each spec's `absent` map and appear in error text.
50
+ TUI = "tui"
51
+ CLI = "cli"
52
+ SHELLS = (TUI, CLI)
53
+
54
+ # The sentence most CLI absences share. Not "use the TUI" alone: the flag
55
+ # beside it, where one exists, is what a scripted run can actually type.
56
+ _IN_THE_TUI = "not yet; use it in the TUI (venastine --tui)."
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class CommandSpec:
61
+ """One command as both shells know it."""
62
+
63
+ name: str # without the leading slash
64
+ summary: str # one line, shown by /help
65
+ usage: Optional[str] = None # shown by /help when the shape is not obvious
66
+ aliases: tuple[str, ...] = () # see SlashCommand.aliases
67
+ # shell -> why that shell has no handler. A shell missing from the map
68
+ # binds one; the census test holds it to that.
69
+ absent: dict = field(default_factory=dict)
70
+
71
+ def in_shell(self, shell: str) -> bool:
72
+ return shell not in self.absent
73
+
74
+
75
+ #: Alphabetical, which is the order `/help` prints in either shell.
76
+ _SPECS = (
77
+ CommandSpec("agent", "switch the active agent", "[name|default]"),
78
+ CommandSpec("call", "list this thread's tool calls, or show one",
79
+ "[number]",
80
+ absent={TUI: "ctrl+click a ▸ line to open its call."}),
81
+ CommandSpec("claims", "show a research run's claims and their tiers",
82
+ "[run id]"),
83
+ CommandSpec("compact", "summarize this conversation's older turns now",
84
+ "[--strength 1-5]"),
85
+ CommandSpec("config", "browse and set the harness configuration",
86
+ "[key] [value]", absent={CLI: _IN_THE_TUI}),
87
+ CommandSpec("connect", "connect a model provider: sign in or paste a key",
88
+ "[name [--key]|custom <NAME> <url>|cancel]",
89
+ absent={CLI: _IN_THE_TUI}),
90
+ # tui/app.py's _COPY_TARGETS, spelled out; the census test pins the two.
91
+ CommandSpec("copy", "copy text out of the session",
92
+ "[last|report|claims|conversation|all] [--file <path>]",
93
+ absent={CLI: "the CLI prints plain text, so the terminal's "
94
+ "own selection copies it."}),
95
+ CommandSpec("critic", "route the grounding and critic passes to another "
96
+ "model", "[[PROVIDER] name|off]",
97
+ absent={CLI: _IN_THE_TUI}),
98
+ CommandSpec("disconnect", "remove a provider's key, or sign out of one",
99
+ "[name [--forget]]", absent={CLI: _IN_THE_TUI}),
100
+ CommandSpec("effort", "switch reasoning effort", "[level|auto]"),
101
+ CommandSpec("embedder", "choose the model that scores source similarity",
102
+ "[[PROVIDER] name|off]", absent={CLI: _IN_THE_TUI}),
103
+ # ROADMAP_v3 §59: the id is optional in the TUI, where /forget alone
104
+ # opens a picker. The CLI's handler still asks for it, and says so.
105
+ # 49 characters with its name and usage, inside the slash panel's 50 at
106
+ # 80x24 (54 less SUGGEST_CONT): past 50 the entry wraps to two rows,
107
+ # which moves the window test_the_window_can_drop_one_and_gain_two
108
+ # measures.
109
+ CommandSpec("forget", "pick memories to delete, or by id", "[id]"),
110
+ CommandSpec("goal", "set the thread's persistent objective",
111
+ "[text|clear]"),
112
+ CommandSpec("grill-me", "surface what still needs a decision"),
113
+ CommandSpec("help", "list commands"),
114
+ CommandSpec("init", "generate this project's documentation set",
115
+ "[--software|--research] [--config]",
116
+ absent={CLI: "not yet; run venastine --init."}),
117
+ CommandSpec("kill", "stop a background session", "[session-id]",
118
+ absent={CLI: "the CLI's prompt waits until background "
119
+ "sessions finish, and Ctrl+C while it waits "
120
+ "stops them."}),
121
+ CommandSpec("memories", "list durable memories visible here"),
122
+ CommandSpec("mentions", "show file mention status or include ignored "
123
+ "paths", "[ignored on|off]",
124
+ absent={CLI: "it manages the TUI's @-file completion, which "
125
+ "the CLI does not have."}),
126
+ CommandSpec("model", "switch provider and/or model for this session",
127
+ "[[PROVIDER] name]"),
128
+ CommandSpec("new", "start a new thread"),
129
+ CommandSpec("quit", "exit the harness", aliases=("exit", "bye")),
130
+ CommandSpec("ref", "reference another conversation's summary",
131
+ "[--list|--clear]"),
132
+ CommandSpec("research", "run the deep-research pipeline",
133
+ "[--attended] [--review|--no-review] [--grant[=a,b]] <query>",
134
+ absent={CLI: 'not yet; run venastine --mode research '
135
+ '"<query>".'}),
136
+ CommandSpec("resume", "resume a thread by id, even an old one",
137
+ "<thread-id>"),
138
+ CommandSpec("secrets", "manage the harness-held secret store",
139
+ "[status|list|set <name>|delete <name>|lock]",
140
+ absent={CLI: "not yet; run venastine --secrets status."}),
141
+ CommandSpec("skill", "activate a skill for this session",
142
+ "[name|off <name>|clear]"),
143
+ # ROADMAP_v3 §57: both shells (SM11), since the pair it stores reaches
144
+ # either shell's spawns.
145
+ CommandSpec("submodel", "run spawned subagents on another model",
146
+ "[[PROVIDER] name|off]"),
147
+ CommandSpec("summary", "distil this conversation without folding it"),
148
+ CommandSpec("theme", "switch colour theme", "[name]",
149
+ absent={CLI: "a line-based terminal has no colour theme to "
150
+ "switch."}),
151
+ CommandSpec("thinking", "show or hide reasoning inline", "[on|off]",
152
+ absent={CLI: "not yet; the CLI prints reasoning whenever "
153
+ "the model returns it."}),
154
+ CommandSpec("threads", "resume a saved thread"),
155
+ CommandSpec("trigger", "override when this chat compacts, for the "
156
+ "session", "[tokens|off]",
157
+ absent={CLI: _IN_THE_TUI}),
158
+ CommandSpec("window", "override this model's context window for the "
159
+ "session", "[tokens|off]",
160
+ absent={CLI: _IN_THE_TUI}),
161
+ )
162
+
163
+
164
+ def _index(specs) -> tuple[dict, dict]:
165
+ """(name -> spec, alias -> name), refusing what would shadow.
166
+
167
+ At IMPORT, so a collision in the catalog fails the first test that
168
+ imports either shell rather than reaching a keystroke.
169
+ """
170
+ catalog: dict = {}
171
+ aliases: dict = {}
172
+ for spec in specs:
173
+ if spec.name in catalog or spec.name in aliases:
174
+ raise ValueError(f"/{spec.name} is declared twice")
175
+ unknown = set(spec.absent) - set(SHELLS)
176
+ if unknown:
177
+ raise ValueError(f"/{spec.name} names unknown shells {unknown}")
178
+ if not all(spec.absent.values()):
179
+ raise ValueError(f"/{spec.name} is absent without a reason")
180
+ catalog[spec.name] = spec
181
+ for alias in spec.aliases:
182
+ if alias in catalog or alias in aliases:
183
+ raise ValueError(f"/{alias} is declared twice")
184
+ aliases[alias] = spec.name
185
+ return catalog, aliases
186
+
187
+
188
+ #: name -> CommandSpec. A test that registers a command of its own declares
189
+ #: it here first (`mocker.patch.dict`), which is the rule it is testing.
190
+ CATALOG, ALIASES = _index(_SPECS)
191
+
192
+
193
+ def lookup(name: str) -> Optional[CommandSpec]:
194
+ """The spec called `name`, by its own name or an alias."""
195
+ name = name.lower()
196
+ spec = CATALOG.get(name)
197
+ if spec is not None:
198
+ return spec
199
+ canonical = ALIASES.get(name)
200
+ return CATALOG.get(canonical) if canonical else None
201
+
202
+
203
+ def absent_reason(name: str, shell: str) -> Optional[str]:
204
+ """Why `shell` has no /`name`, or None when it has one or nobody does.
205
+
206
+ What a shell says INSTEAD of "unknown command" for a command the other
207
+ shell has: `/theme` typed in the CLI is not a typo, and answering it as
208
+ one would send the reader to /help to find a command they already know.
209
+ """
210
+ spec = lookup(name)
211
+ if spec is None or spec.in_shell(shell):
212
+ return None
213
+ return f"/{spec.name} is not in this shell: {spec.absent[shell]}"
214
+
215
+
216
+ @dataclass
217
+ class SlashCommand:
218
+ name: str # without the leading slash
219
+ summary: str # one line, shown by /help
220
+ handler: Callable # (shell_state, args: str) -> None
221
+ usage: Optional[str] = None # shown by /help when the shape is not obvious
222
+ # Other names the same command answers to (batch 57). A FIELD rather
223
+ # than two more registrations, and the difference is what the LISTS
224
+ # say: `all()` and `names()` stay canonical, so `/help` prints one row
225
+ # per command and a bare slash still offers the menu it always did.
226
+ # Registering `/exit` and `/bye` outright would have sorted `bye`
227
+ # second in that menu, ahead of `/claims`, for a name nobody browses
228
+ # for -- and moved every window position batch 56 measured.
229
+ aliases: tuple[str, ...] = ()
230
+ # Batch 84. What to offer once this command's name has been typed and a
231
+ # space follows it: `(argument_text) -> [SlashCommand]`, where each row's
232
+ # `name` is the WHOLE line after the slash, because that is what the
233
+ # panel draws and what completion writes into the prompt.
234
+ #
235
+ # Opt-in per command, and that is what keeps `/copy last` offering
236
+ # nothing: a command without one behaves exactly as every command did
237
+ # before this field existed, which is the contract
238
+ # `test_a_space_ends_it_at_either_end` pins.
239
+ complete: Optional[Callable] = None
240
+
241
+
242
+ def bind(name: str, handler: Callable,
243
+ complete: Optional[Callable] = None) -> SlashCommand:
244
+ """A command built from its catalog entry -- the only way a shell
245
+ should construct one, since everything but the handler is the
246
+ catalog's to say."""
247
+ spec = CATALOG[name]
248
+ return SlashCommand(spec.name, spec.summary, handler, spec.usage,
249
+ spec.aliases, complete)
250
+
251
+
252
+ class CommandRegistry:
253
+ def __init__(self, shell: Optional[str] = None) -> None:
254
+ self._commands: dict[str, SlashCommand] = {}
255
+ # alias -> canonical name. A second index rather than a scan, and
256
+ # it is what makes an alias collision detectable at REGISTRATION
257
+ # instead of at the keystroke that silently reached the wrong
258
+ # handler.
259
+ self._aliases: dict[str, str] = {}
260
+ # §89. The shell this registry belongs to, which binds it to the
261
+ # catalog. None is the bare mechanism, for a test of the mechanism.
262
+ self.shell = shell
263
+
264
+ def _check_bound(self, command: SlashCommand) -> None:
265
+ """A shell's registry takes only what the catalog declares for it,
266
+ exactly as declared (§89).
267
+
268
+ AT REGISTRATION, the alias check's reason: a summary edited in one
269
+ shell's registration would otherwise be the first thing the two
270
+ disagree about, and nothing would say so until a reader compared
271
+ two /help outputs.
272
+ """
273
+ spec = CATALOG.get(command.name)
274
+ if spec is None:
275
+ raise ValueError(
276
+ f"/{command.name} is not in core/commands.py's catalog; "
277
+ f"declare it there, then bind a handler to it")
278
+ if not spec.in_shell(self.shell):
279
+ raise ValueError(
280
+ f"/{command.name} is declared absent from the {self.shell} "
281
+ f"({spec.absent[self.shell]}); change the catalog first")
282
+ declared = (spec.summary, spec.usage, tuple(spec.aliases))
283
+ given = (command.summary, command.usage, tuple(command.aliases))
284
+ if declared != given:
285
+ raise ValueError(
286
+ f"/{command.name} differs from its catalog entry "
287
+ f"({given} vs {declared}); build it with bind()")
288
+
289
+ def register(self, command: SlashCommand) -> None:
290
+ """Register by name; re-registering the same name overwrites.
291
+
292
+ Idempotent on purpose -- `register_builtin_commands()` runs on
293
+ import AND is called again by tests, so a second pass must not
294
+ duplicate or raise.
295
+
296
+ An alias that would shadow something REFUSES, both ways round: a
297
+ name already taken by a command, and a command name already taken
298
+ by somebody's alias. Both resolve silently otherwise -- `get()`
299
+ prefers real names, so the alias would simply stop working and
300
+ nothing would say why.
301
+
302
+ A shell's registry also refuses what the catalog does not declare
303
+ for that shell, or declares differently (§89, `_check_bound`).
304
+ """
305
+ if self.shell is not None:
306
+ self._check_bound(command)
307
+ for alias in command.aliases:
308
+ if alias in self._commands:
309
+ raise ValueError(
310
+ f"/{alias} is already a command; it cannot also be an "
311
+ f"alias of /{command.name}")
312
+ owner = self._aliases.get(alias)
313
+ if owner is not None and owner != command.name:
314
+ raise ValueError(
315
+ f"/{alias} is already an alias of /{owner}; it cannot "
316
+ f"also be an alias of /{command.name}")
317
+ owner = self._aliases.get(command.name)
318
+ if owner is not None and owner != command.name:
319
+ raise ValueError(
320
+ f"/{command.name} is already an alias of /{owner}")
321
+ old = self._commands.get(command.name)
322
+ if old is not None:
323
+ for alias in old.aliases:
324
+ if alias not in command.aliases \
325
+ and self._aliases.get(alias) == command.name:
326
+ del self._aliases[alias]
327
+ self._commands[command.name] = command
328
+ for alias in command.aliases:
329
+ self._aliases[alias] = command.name
330
+
331
+ def get(self, name: str) -> Optional[SlashCommand]:
332
+ """The command called `name`, by its own name or by an alias.
333
+
334
+ Names win over aliases, which is also the collision `register`
335
+ refuses -- so the precedence can never actually be exercised.
336
+ """
337
+ command = self._commands.get(name)
338
+ if command is not None:
339
+ return command
340
+ canonical = self._aliases.get(name)
341
+ return self._commands.get(canonical) if canonical else None
342
+
343
+ def names(self) -> list[str]:
344
+ return sorted(self._commands)
345
+
346
+ def all(self) -> list[SlashCommand]:
347
+ return [self._commands[n] for n in self.names()]
348
+
349
+ def matching(self, text: str) -> list[SlashCommand]:
350
+ """Commands whose name starts with the token in `text`.
351
+
352
+ The suggestion panel's source, and it reads `all()` so the panel and
353
+ `/help` cannot disagree about what exists -- register a command
354
+ anywhere and both change, which is the whole reason the matching
355
+ lives here rather than in the widget.
356
+
357
+ A BARE slash token offers commands: leading whitespace allowed
358
+ (`dispatch` tolerates it, so `" /help"` runs and had better
359
+ offer), a leading `/`, and no whitespace inside the name.
360
+
361
+ PAST THE FIRST SPACE, the command itself answers (batch 84). If it
362
+ declares a `complete` the rows come from there, and if it does not
363
+ the answer is nothing, exactly as it was for every command before
364
+ the field existed. `/config ` is the only one today.
365
+
366
+ The split is on a SPACE and nothing else, because `dispatch`
367
+ partitions on a space and nothing else: a line with a newline or a
368
+ tab in it is not a command line there, so it must not look like one
369
+ here. A panel that offered `/config` for a line `dispatch` would
370
+ send to the model as chat is the disagreement this whole method is
371
+ written to avoid.
372
+
373
+ `lstrip`, not `strip`, and the difference is a bug this had: a
374
+ TRAILING space survives `strip()`, so `"/copy "` read as `"/copy"`
375
+ and the panel stayed open over a line that had already moved on to
376
+ its arguments. Once a space is typed there is nothing left to
377
+ complete, whichever end of the token it is on.
378
+
379
+ Lowercased for the same reason `dispatch` lowercases: `/HELP` runs,
380
+ so `/HEL` had better offer it.
381
+
382
+ ALIASES join the list once a prefix is typed, and never on a bare
383
+ slash (batch 57). The bare slash is the MENU -- it is what someone
384
+ who does not know the commands presses, and a menu lists each
385
+ thing once, under its own name. `/ex` is not browsing: it is a
386
+ guess, and the answer to a guess is whether it works. So
387
+ `matching("/") == all()` still holds exactly, and typing toward an
388
+ alias surfaces it.
389
+ """
390
+ token = text.lstrip()
391
+ if not token.startswith("/"):
392
+ return []
393
+ head, space, rest = token.partition(" ")
394
+ if any(c.isspace() for c in head):
395
+ # A newline or a tab before any space. Not a command line.
396
+ return []
397
+ if space:
398
+ if any(c.isspace() and c != " " for c in rest):
399
+ return []
400
+ command = self.get(head[1:].lower())
401
+ if command is None or command.complete is None:
402
+ return []
403
+ # CONTAINED HERE, unlike dispatch(), and the asymmetry is the
404
+ # point rather than an inconsistency. `matching()` runs per
405
+ # KEYSTROKE on the UI thread, and the right answer to a
406
+ # completer that raises is "offer nothing" -- which is this
407
+ # function's own vocabulary, already returned on four other
408
+ # lines. There is no policy for the shell to decide, so there
409
+ # is nothing to hand upward.
410
+ #
411
+ # dispatch() is the other way round: what a broken COMMAND does
412
+ # to the session is the shell's call, so it is caught at the
413
+ # call site in tui/app.py instead (batch 135). Uncontained,
414
+ # this was the same exposure one layer over and on a hotter
415
+ # path: an exception here reaches Textual's `_handle_exception`
416
+ # and exits the application mid-keystroke, while the user is
417
+ # still typing the command.
418
+ try:
419
+ return command.complete(rest)
420
+ except Exception: # noqa: BLE001 -- see the comment above
421
+ logger.exception(
422
+ "The /%s completer raised; offering no rows.",
423
+ command.name)
424
+ return []
425
+ prefix = token[1:].lower()
426
+ matches = [c for c in self.all() if c.name.startswith(prefix)]
427
+ if not prefix:
428
+ return matches
429
+ matches.extend(self._alias_row(a) for a in self._aliases
430
+ if a.startswith(prefix))
431
+ return sorted(matches, key=lambda command: command.name)
432
+
433
+ def _alias_row(self, alias: str) -> SlashCommand:
434
+ """One offer for `alias`, carrying the canonical command's handler.
435
+
436
+ A real `SlashCommand` rather than a flag on the canonical one, so
437
+ the panel needs to know nothing about aliases: it draws the name
438
+ it is given and completes the name it drew, which has to be the
439
+ alias the user was typing rather than the name they were not.
440
+ """
441
+ command = self._commands[self._aliases[alias]]
442
+ return SlashCommand(
443
+ alias, f"{command.summary} (alias of /{command.name})",
444
+ command.handler, command.usage, complete=command.complete)
445
+
446
+ def dispatch(self, app, raw: str) -> bool:
447
+ """Run the command in `raw` (a line starting with '/').
448
+
449
+ Returns True if a command handled the line, False if the name is
450
+ unknown -- the caller decides what to do about it. Unknown names are
451
+ NOT sent to the model: a mistyped slash command should say so, not
452
+ silently become a chat turn that burns a request.
453
+ """
454
+ stripped = raw[1:].strip()
455
+ name, _, args = stripped.partition(" ")
456
+ command = self.get(name.lower())
457
+ if command is None:
458
+ return False
459
+ command.handler(app, args.strip())
460
+ return True