@yahyahammad/venastine 0.2.0 → 0.3.8

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 (129) hide show
  1. package/.env.example +19 -14
  2. package/CONFIG_ARCHITECTURE.md +2002 -0
  3. package/NOTICE +1 -1
  4. package/README.md +233 -94
  5. package/agents/builtin/build.md +73 -0
  6. package/agents/builtin/general.md +80 -0
  7. package/agents/builtin/plan.md +23 -5
  8. package/agents/builtin/test.md +65 -0
  9. package/agents/builtin/writer.md +67 -0
  10. package/agents/manager.py +261 -195
  11. package/agents/subagent_tool.py +277 -43
  12. package/agents/tui_commands.py +7 -12
  13. package/bin/venastine.mjs +528 -382
  14. package/bin/venastine.py +71 -0
  15. package/cli_commands.py +835 -0
  16. package/config.py +95 -1198
  17. package/config.yaml +1090 -0
  18. package/config_edit.py +1301 -0
  19. package/config_schema.py +966 -0
  20. package/config_update.py +749 -0
  21. package/core/agent_activity.py +158 -20
  22. package/core/ansi.py +452 -0
  23. package/core/approval.py +27 -5
  24. package/core/call_view.py +364 -0
  25. package/core/cancel.py +121 -0
  26. package/core/chatgpt_auth.py +747 -0
  27. package/core/claims_view.py +107 -0
  28. package/core/client.py +1238 -82
  29. package/core/commands.py +454 -0
  30. package/core/compaction.py +830 -66
  31. package/core/config_loader.py +516 -97
  32. package/core/connect.py +686 -0
  33. package/core/events.py +68 -6
  34. package/core/file_mentions.py +280 -0
  35. package/core/interaction.py +87 -4
  36. package/core/line_pattern.py +128 -0
  37. package/core/loop.py +1516 -440
  38. package/core/memory.py +120 -8
  39. package/core/pipeline_models.py +23 -9
  40. package/core/provider_errors.py +234 -0
  41. package/core/reasoning/confidence_scoring.py +70 -54
  42. package/core/reasoning/json_retry.py +19 -1
  43. package/core/reasoning/orchestrator.py +232 -53
  44. package/core/reasoning/output_writer.py +90 -31
  45. package/core/reasoning/payload_validation.py +133 -7
  46. package/core/reasoning/pipeline_storage.py +427 -361
  47. package/core/reasoning/review.py +659 -615
  48. package/core/reasoning/scholar.py +38 -14
  49. package/core/reasoning/source_corpus.py +110 -4
  50. package/core/replay.py +158 -26
  51. package/core/session.py +36 -12
  52. package/core/session_view.py +259 -0
  53. package/core/session_wake.py +259 -0
  54. package/core/shell_sessions.py +1553 -0
  55. package/core/workspace_trust.py +1 -1
  56. package/credentials.py +308 -180
  57. package/database.py +82 -1
  58. package/{PRIVACY.md → docs/PRIVACY.md} +19 -7
  59. package/docs/SECURITY.md +108 -0
  60. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  61. package/env_secrets.py +118 -77
  62. package/json_store.py +236 -16
  63. package/logging_setup.py +121 -11
  64. package/main.py +1671 -199
  65. package/mcp_client/client.py +257 -23
  66. package/mcp_client/config.py +484 -379
  67. package/mcp_client/registration.py +163 -2
  68. package/memories/manager.py +15 -0
  69. package/memories/tui_commands.py +7 -12
  70. package/package.json +234 -4
  71. package/project_init/config_files.py +4 -0
  72. package/project_init/generator.py +201 -37
  73. package/project_init/manifest.py +418 -406
  74. package/project_init/tui_commands.py +7 -4
  75. package/prompts/revalidate.md +1 -1
  76. package/prompts/revise.md +17 -15
  77. package/prompts/system_prompts.py +64 -10
  78. package/providers.json.example +94 -92
  79. package/pyproject.toml +51 -2
  80. package/requirements.txt +252 -29
  81. package/safety/policy_enforcement.py +353 -17
  82. package/security/askpass.py +419 -0
  83. package/security/capability.py +37 -7
  84. package/security/confine.py +484 -0
  85. package/security/hosted.py +182 -0
  86. package/security/permissions.py +54 -7
  87. package/security/posture.py +124 -12
  88. package/security/protected_paths.py +198 -6
  89. package/security/sandbox.py +3262 -139
  90. package/security/secrets.py +855 -0
  91. package/skills/tui_commands.py +3 -4
  92. package/storage.py +368 -35
  93. package/tools/base.py +465 -305
  94. package/tools/builtin/_math_common.py +306 -16
  95. package/tools/builtin/_net_common.py +267 -61
  96. package/tools/builtin/arxiv.py +681 -223
  97. package/tools/builtin/ask_user.py +231 -213
  98. package/tools/builtin/discrete_math.py +35 -4
  99. package/tools/builtin/fetch_url.py +239 -21
  100. package/tools/builtin/file_ops.py +341 -33
  101. package/tools/builtin/geometry.py +184 -148
  102. package/tools/builtin/get_time.py +2 -2
  103. package/tools/builtin/linear_algebra.py +66 -23
  104. package/tools/builtin/load_skill.py +10 -0
  105. package/tools/builtin/logic.py +171 -12
  106. package/tools/builtin/pin.py +46 -12
  107. package/tools/builtin/probability_stats.py +224 -228
  108. package/tools/builtin/project_docs.py +80 -21
  109. package/tools/builtin/remember.py +21 -4
  110. package/tools/builtin/shell.py +586 -67
  111. package/tools/builtin/shell_sessions.py +613 -0
  112. package/tools/builtin/symbolic_math.py +80 -10
  113. package/tools/builtin/todo.py +5 -3
  114. package/tools/builtin/web_search.py +329 -151
  115. package/tools/context.py +23 -0
  116. package/tools/isolation.py +387 -314
  117. package/tools/registry.py +347 -30
  118. package/tui/app.py +4645 -438
  119. package/tui/app.tcss +185 -2
  120. package/tui/commands.py +10 -154
  121. package/tui/diffs.py +286 -265
  122. package/tui/hosted_driver.py +102 -0
  123. package/tui/markdown.py +60 -10
  124. package/tui/meters.py +103 -7
  125. package/tui/screens.py +346 -92
  126. package/tui/themes.py +59 -19
  127. package/tui/widgets.py +1575 -111
  128. package/SECURITY.md +0 -88
  129. package/THIRD_PARTY_NOTICES.md +0 -100
@@ -0,0 +1,454 @@
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
+ CommandSpec("forget", "delete one durable memory", "<id>"),
104
+ CommandSpec("goal", "set the thread's persistent objective",
105
+ "[text|clear]"),
106
+ CommandSpec("grill-me", "surface what still needs a decision"),
107
+ CommandSpec("help", "list commands"),
108
+ CommandSpec("init", "generate this project's documentation set",
109
+ "[--software|--research] [--config]",
110
+ absent={CLI: "not yet; run venastine --init."}),
111
+ CommandSpec("kill", "stop a background session", "[session-id]",
112
+ absent={CLI: "the CLI's prompt waits until background "
113
+ "sessions finish, and Ctrl+C while it waits "
114
+ "stops them."}),
115
+ CommandSpec("memories", "list durable memories visible here"),
116
+ CommandSpec("mentions", "show file mention status or include ignored "
117
+ "paths", "[ignored on|off]",
118
+ absent={CLI: "it manages the TUI's @-file completion, which "
119
+ "the CLI does not have."}),
120
+ CommandSpec("model", "switch provider and/or model for this session",
121
+ "[[PROVIDER] name]"),
122
+ CommandSpec("new", "start a new thread"),
123
+ CommandSpec("quit", "exit the harness", aliases=("exit", "bye")),
124
+ CommandSpec("ref", "reference another conversation's summary",
125
+ "[--list|--clear]"),
126
+ CommandSpec("research", "run the deep-research pipeline",
127
+ "[--attended] [--review|--no-review] [--grant[=a,b]] <query>",
128
+ absent={CLI: 'not yet; run venastine --mode research '
129
+ '"<query>".'}),
130
+ CommandSpec("resume", "resume a thread by id, even an old one",
131
+ "<thread-id>"),
132
+ CommandSpec("secrets", "manage the harness-held secret store",
133
+ "[status|list|set <name>|delete <name>|lock]",
134
+ absent={CLI: "not yet; run venastine --secrets status."}),
135
+ CommandSpec("skill", "activate a skill for this session",
136
+ "[name|off <name>|clear]"),
137
+ # ROADMAP_v3 §57: both shells (SM11), since the pair it stores reaches
138
+ # either shell's spawns.
139
+ CommandSpec("submodel", "run spawned subagents on another model",
140
+ "[[PROVIDER] name|off]"),
141
+ CommandSpec("summary", "distil this conversation without folding it"),
142
+ CommandSpec("theme", "switch colour theme", "[name]",
143
+ absent={CLI: "a line-based terminal has no colour theme to "
144
+ "switch."}),
145
+ CommandSpec("thinking", "show or hide reasoning inline", "[on|off]",
146
+ absent={CLI: "not yet; the CLI prints reasoning whenever "
147
+ "the model returns it."}),
148
+ CommandSpec("threads", "resume a saved thread"),
149
+ CommandSpec("trigger", "override when this chat compacts, for the "
150
+ "session", "[tokens|off]",
151
+ absent={CLI: _IN_THE_TUI}),
152
+ CommandSpec("window", "override this model's context window for the "
153
+ "session", "[tokens|off]",
154
+ absent={CLI: _IN_THE_TUI}),
155
+ )
156
+
157
+
158
+ def _index(specs) -> tuple[dict, dict]:
159
+ """(name -> spec, alias -> name), refusing what would shadow.
160
+
161
+ At IMPORT, so a collision in the catalog fails the first test that
162
+ imports either shell rather than reaching a keystroke.
163
+ """
164
+ catalog: dict = {}
165
+ aliases: dict = {}
166
+ for spec in specs:
167
+ if spec.name in catalog or spec.name in aliases:
168
+ raise ValueError(f"/{spec.name} is declared twice")
169
+ unknown = set(spec.absent) - set(SHELLS)
170
+ if unknown:
171
+ raise ValueError(f"/{spec.name} names unknown shells {unknown}")
172
+ if not all(spec.absent.values()):
173
+ raise ValueError(f"/{spec.name} is absent without a reason")
174
+ catalog[spec.name] = spec
175
+ for alias in spec.aliases:
176
+ if alias in catalog or alias in aliases:
177
+ raise ValueError(f"/{alias} is declared twice")
178
+ aliases[alias] = spec.name
179
+ return catalog, aliases
180
+
181
+
182
+ #: name -> CommandSpec. A test that registers a command of its own declares
183
+ #: it here first (`mocker.patch.dict`), which is the rule it is testing.
184
+ CATALOG, ALIASES = _index(_SPECS)
185
+
186
+
187
+ def lookup(name: str) -> Optional[CommandSpec]:
188
+ """The spec called `name`, by its own name or an alias."""
189
+ name = name.lower()
190
+ spec = CATALOG.get(name)
191
+ if spec is not None:
192
+ return spec
193
+ canonical = ALIASES.get(name)
194
+ return CATALOG.get(canonical) if canonical else None
195
+
196
+
197
+ def absent_reason(name: str, shell: str) -> Optional[str]:
198
+ """Why `shell` has no /`name`, or None when it has one or nobody does.
199
+
200
+ What a shell says INSTEAD of "unknown command" for a command the other
201
+ shell has: `/theme` typed in the CLI is not a typo, and answering it as
202
+ one would send the reader to /help to find a command they already know.
203
+ """
204
+ spec = lookup(name)
205
+ if spec is None or spec.in_shell(shell):
206
+ return None
207
+ return f"/{spec.name} is not in this shell: {spec.absent[shell]}"
208
+
209
+
210
+ @dataclass
211
+ class SlashCommand:
212
+ name: str # without the leading slash
213
+ summary: str # one line, shown by /help
214
+ handler: Callable # (shell_state, args: str) -> None
215
+ usage: Optional[str] = None # shown by /help when the shape is not obvious
216
+ # Other names the same command answers to (batch 57). A FIELD rather
217
+ # than two more registrations, and the difference is what the LISTS
218
+ # say: `all()` and `names()` stay canonical, so `/help` prints one row
219
+ # per command and a bare slash still offers the menu it always did.
220
+ # Registering `/exit` and `/bye` outright would have sorted `bye`
221
+ # second in that menu, ahead of `/claims`, for a name nobody browses
222
+ # for -- and moved every window position batch 56 measured.
223
+ aliases: tuple[str, ...] = ()
224
+ # Batch 84. What to offer once this command's name has been typed and a
225
+ # space follows it: `(argument_text) -> [SlashCommand]`, where each row's
226
+ # `name` is the WHOLE line after the slash, because that is what the
227
+ # panel draws and what completion writes into the prompt.
228
+ #
229
+ # Opt-in per command, and that is what keeps `/copy last` offering
230
+ # nothing: a command without one behaves exactly as every command did
231
+ # before this field existed, which is the contract
232
+ # `test_a_space_ends_it_at_either_end` pins.
233
+ complete: Optional[Callable] = None
234
+
235
+
236
+ def bind(name: str, handler: Callable,
237
+ complete: Optional[Callable] = None) -> SlashCommand:
238
+ """A command built from its catalog entry -- the only way a shell
239
+ should construct one, since everything but the handler is the
240
+ catalog's to say."""
241
+ spec = CATALOG[name]
242
+ return SlashCommand(spec.name, spec.summary, handler, spec.usage,
243
+ spec.aliases, complete)
244
+
245
+
246
+ class CommandRegistry:
247
+ def __init__(self, shell: Optional[str] = None) -> None:
248
+ self._commands: dict[str, SlashCommand] = {}
249
+ # alias -> canonical name. A second index rather than a scan, and
250
+ # it is what makes an alias collision detectable at REGISTRATION
251
+ # instead of at the keystroke that silently reached the wrong
252
+ # handler.
253
+ self._aliases: dict[str, str] = {}
254
+ # §89. The shell this registry belongs to, which binds it to the
255
+ # catalog. None is the bare mechanism, for a test of the mechanism.
256
+ self.shell = shell
257
+
258
+ def _check_bound(self, command: SlashCommand) -> None:
259
+ """A shell's registry takes only what the catalog declares for it,
260
+ exactly as declared (§89).
261
+
262
+ AT REGISTRATION, the alias check's reason: a summary edited in one
263
+ shell's registration would otherwise be the first thing the two
264
+ disagree about, and nothing would say so until a reader compared
265
+ two /help outputs.
266
+ """
267
+ spec = CATALOG.get(command.name)
268
+ if spec is None:
269
+ raise ValueError(
270
+ f"/{command.name} is not in core/commands.py's catalog; "
271
+ f"declare it there, then bind a handler to it")
272
+ if not spec.in_shell(self.shell):
273
+ raise ValueError(
274
+ f"/{command.name} is declared absent from the {self.shell} "
275
+ f"({spec.absent[self.shell]}); change the catalog first")
276
+ declared = (spec.summary, spec.usage, tuple(spec.aliases))
277
+ given = (command.summary, command.usage, tuple(command.aliases))
278
+ if declared != given:
279
+ raise ValueError(
280
+ f"/{command.name} differs from its catalog entry "
281
+ f"({given} vs {declared}); build it with bind()")
282
+
283
+ def register(self, command: SlashCommand) -> None:
284
+ """Register by name; re-registering the same name overwrites.
285
+
286
+ Idempotent on purpose -- `register_builtin_commands()` runs on
287
+ import AND is called again by tests, so a second pass must not
288
+ duplicate or raise.
289
+
290
+ An alias that would shadow something REFUSES, both ways round: a
291
+ name already taken by a command, and a command name already taken
292
+ by somebody's alias. Both resolve silently otherwise -- `get()`
293
+ prefers real names, so the alias would simply stop working and
294
+ nothing would say why.
295
+
296
+ A shell's registry also refuses what the catalog does not declare
297
+ for that shell, or declares differently (§89, `_check_bound`).
298
+ """
299
+ if self.shell is not None:
300
+ self._check_bound(command)
301
+ for alias in command.aliases:
302
+ if alias in self._commands:
303
+ raise ValueError(
304
+ f"/{alias} is already a command; it cannot also be an "
305
+ f"alias of /{command.name}")
306
+ owner = self._aliases.get(alias)
307
+ if owner is not None and owner != command.name:
308
+ raise ValueError(
309
+ f"/{alias} is already an alias of /{owner}; it cannot "
310
+ f"also be an alias of /{command.name}")
311
+ owner = self._aliases.get(command.name)
312
+ if owner is not None and owner != command.name:
313
+ raise ValueError(
314
+ f"/{command.name} is already an alias of /{owner}")
315
+ old = self._commands.get(command.name)
316
+ if old is not None:
317
+ for alias in old.aliases:
318
+ if alias not in command.aliases \
319
+ and self._aliases.get(alias) == command.name:
320
+ del self._aliases[alias]
321
+ self._commands[command.name] = command
322
+ for alias in command.aliases:
323
+ self._aliases[alias] = command.name
324
+
325
+ def get(self, name: str) -> Optional[SlashCommand]:
326
+ """The command called `name`, by its own name or by an alias.
327
+
328
+ Names win over aliases, which is also the collision `register`
329
+ refuses -- so the precedence can never actually be exercised.
330
+ """
331
+ command = self._commands.get(name)
332
+ if command is not None:
333
+ return command
334
+ canonical = self._aliases.get(name)
335
+ return self._commands.get(canonical) if canonical else None
336
+
337
+ def names(self) -> list[str]:
338
+ return sorted(self._commands)
339
+
340
+ def all(self) -> list[SlashCommand]:
341
+ return [self._commands[n] for n in self.names()]
342
+
343
+ def matching(self, text: str) -> list[SlashCommand]:
344
+ """Commands whose name starts with the token in `text`.
345
+
346
+ The suggestion panel's source, and it reads `all()` so the panel and
347
+ `/help` cannot disagree about what exists -- register a command
348
+ anywhere and both change, which is the whole reason the matching
349
+ lives here rather than in the widget.
350
+
351
+ A BARE slash token offers commands: leading whitespace allowed
352
+ (`dispatch` tolerates it, so `" /help"` runs and had better
353
+ offer), a leading `/`, and no whitespace inside the name.
354
+
355
+ PAST THE FIRST SPACE, the command itself answers (batch 84). If it
356
+ declares a `complete` the rows come from there, and if it does not
357
+ the answer is nothing, exactly as it was for every command before
358
+ the field existed. `/config ` is the only one today.
359
+
360
+ The split is on a SPACE and nothing else, because `dispatch`
361
+ partitions on a space and nothing else: a line with a newline or a
362
+ tab in it is not a command line there, so it must not look like one
363
+ here. A panel that offered `/config` for a line `dispatch` would
364
+ send to the model as chat is the disagreement this whole method is
365
+ written to avoid.
366
+
367
+ `lstrip`, not `strip`, and the difference is a bug this had: a
368
+ TRAILING space survives `strip()`, so `"/copy "` read as `"/copy"`
369
+ and the panel stayed open over a line that had already moved on to
370
+ its arguments. Once a space is typed there is nothing left to
371
+ complete, whichever end of the token it is on.
372
+
373
+ Lowercased for the same reason `dispatch` lowercases: `/HELP` runs,
374
+ so `/HEL` had better offer it.
375
+
376
+ ALIASES join the list once a prefix is typed, and never on a bare
377
+ slash (batch 57). The bare slash is the MENU -- it is what someone
378
+ who does not know the commands presses, and a menu lists each
379
+ thing once, under its own name. `/ex` is not browsing: it is a
380
+ guess, and the answer to a guess is whether it works. So
381
+ `matching("/") == all()` still holds exactly, and typing toward an
382
+ alias surfaces it.
383
+ """
384
+ token = text.lstrip()
385
+ if not token.startswith("/"):
386
+ return []
387
+ head, space, rest = token.partition(" ")
388
+ if any(c.isspace() for c in head):
389
+ # A newline or a tab before any space. Not a command line.
390
+ return []
391
+ if space:
392
+ if any(c.isspace() and c != " " for c in rest):
393
+ return []
394
+ command = self.get(head[1:].lower())
395
+ if command is None or command.complete is None:
396
+ return []
397
+ # CONTAINED HERE, unlike dispatch(), and the asymmetry is the
398
+ # point rather than an inconsistency. `matching()` runs per
399
+ # KEYSTROKE on the UI thread, and the right answer to a
400
+ # completer that raises is "offer nothing" -- which is this
401
+ # function's own vocabulary, already returned on four other
402
+ # lines. There is no policy for the shell to decide, so there
403
+ # is nothing to hand upward.
404
+ #
405
+ # dispatch() is the other way round: what a broken COMMAND does
406
+ # to the session is the shell's call, so it is caught at the
407
+ # call site in tui/app.py instead (batch 135). Uncontained,
408
+ # this was the same exposure one layer over and on a hotter
409
+ # path: an exception here reaches Textual's `_handle_exception`
410
+ # and exits the application mid-keystroke, while the user is
411
+ # still typing the command.
412
+ try:
413
+ return command.complete(rest)
414
+ except Exception: # noqa: BLE001 -- see the comment above
415
+ logger.exception(
416
+ "The /%s completer raised; offering no rows.",
417
+ command.name)
418
+ return []
419
+ prefix = token[1:].lower()
420
+ matches = [c for c in self.all() if c.name.startswith(prefix)]
421
+ if not prefix:
422
+ return matches
423
+ matches.extend(self._alias_row(a) for a in self._aliases
424
+ if a.startswith(prefix))
425
+ return sorted(matches, key=lambda command: command.name)
426
+
427
+ def _alias_row(self, alias: str) -> SlashCommand:
428
+ """One offer for `alias`, carrying the canonical command's handler.
429
+
430
+ A real `SlashCommand` rather than a flag on the canonical one, so
431
+ the panel needs to know nothing about aliases: it draws the name
432
+ it is given and completes the name it drew, which has to be the
433
+ alias the user was typing rather than the name they were not.
434
+ """
435
+ command = self._commands[self._aliases[alias]]
436
+ return SlashCommand(
437
+ alias, f"{command.summary} (alias of /{command.name})",
438
+ command.handler, command.usage, complete=command.complete)
439
+
440
+ def dispatch(self, app, raw: str) -> bool:
441
+ """Run the command in `raw` (a line starting with '/').
442
+
443
+ Returns True if a command handled the line, False if the name is
444
+ unknown -- the caller decides what to do about it. Unknown names are
445
+ NOT sent to the model: a mistyped slash command should say so, not
446
+ silently become a chat turn that burns a request.
447
+ """
448
+ stripped = raw[1:].strip()
449
+ name, _, args = stripped.partition(" ")
450
+ command = self.get(name.lower())
451
+ if command is None:
452
+ return False
453
+ command.handler(app, args.strip())
454
+ return True