Coverage for app / services / chat_commands.py: 97%
180 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Chat commands: ``/<action> <kind> <target> [request]`` in an agent's chat.
4A command runs a named workflow instead of leaving the turn to the agent's
5dynamic graph. ``/execute skill research-brief UK AI regulation news`` runs the
6built-in Research brief on that request: the skill's whole graph, in order,
7answered in the agent's persona and on its model, governed, ledgered and
8stored like any other turn. Without a command the agent decides how to answer
9(and, with the chat's skill graph on, routes through its first skill).
11**The grammar is one shape for every command**: an *action* (a verb), the
12*kind* of resource it acts on, the *target* — that resource's slug — and the
13request, which is everything after. So a new workflow is a new
14``(action, kind)`` pair, never a new syntax: ``/execute agent …`` or
15``/search knowledge …`` would read the way ``/execute skill …`` does.
17**Commands are a registry**: one class per ``(action, kind)``, registered with
18``@register``. Each says what it can target in this chat (``targets``) and how
19the turn then runs (``dispatch``). The registry is served as a catalogue
20(``GET /app/agents/{id}/commands``), from which fe-core's command palette
21completes a typed ``/``, so no command, target or slug is spelled out in the
22client. Adding a command is adding one class here; a command that needs a new
23way of running a turn adds one dispatch type too, and the chat route learns
24it once.
26**A command can take a form.** A target may declare the fields it needs
27(``ChatCommand.form``): a skill's are its run schema — the same fields, types
28and required flags as its standalone Run form (``skill_runs/schema.py``) — and
29the chat draws them under the command. A form's values arrive beside the text
30(``command_inputs``), are validated by the same ``validate_inputs`` a run uses,
31and the free text becomes optional additional instructions, required only for
32a target with no fields. The turn then runs on the task a standalone run would
33(``compose_task``): the instructions, or a line naming the workflow, then the
34inputs listed — so rules read the form's values, and the skill reads them both
35there and as graph state.
37**The server parses every command** (``parse``) and resolves its target from
38the same ``targets`` the catalogue served — in the chat's workspace, with the
39caller's access — so a command typed by hand, or sent by a client that skipped
40the palette, is checked exactly like one picked from it. Text whose first word
41is not a known action (``/usr/bin is a folder``) is not a command and goes to
42the agent unchanged; a known action with a wrong kind, an unknown target, a
43missing request or a form that is not filled in is refused with the reason,
44the nearest matches and an error per field.
45"""
47from __future__ import annotations
49import difflib
50import re
51from abc import ABC, abstractmethod
52from dataclasses import dataclass, field
53from typing import Any, ClassVar
54from uuid import UUID
56from sqlalchemy.orm import Session
58from app.db.postgres.models import Skill
59from app.services.skill_runs.schema import RunSchema, compose_task, validate_inputs
61#: What opens a command.
62PREFIX = "/"
64#: ``/action kind target request`` — the request keeps its line breaks.
65_COMMAND_RE = re.compile(
66 r"^/(?P<action>\S+)(?:[ \t]+(?P<kind>\S+))?(?:[ \t]+(?P<target>\S+))?"
67 r"(?:\s+(?P<request>[\s\S]*))?$"
68)
69_SLUG_UNSAFE = re.compile(r"[^a-z0-9]+")
71#: Close matches offered when a kind or target is not recognised.
72MAX_SUGGESTIONS = 5
75class CommandError(ValueError):
76 """A command this chat cannot run. The message is for the person,
77 ``suggestions`` are command lines they may have meant, and ``fields`` an
78 error per form field."""
80 def __init__(
81 self,
82 message: str,
83 suggestions: list[str] | None = None,
84 fields: dict[str, str] | None = None,
85 ) -> None:
86 super().__init__(message)
87 self.message = message
88 self.suggestions = list(suggestions or [])
89 self.fields = dict(fields or {})
92@dataclass(frozen=True)
93class CommandTarget:
94 """Something a command can act on in this chat, as the palette lists it."""
96 id: str
97 slug: str
98 name: str
99 description: str = ""
100 built_in: bool = False
101 #: The row it was listed from, so running it needs no second lookup and
102 #: runs exactly what was listed. Never served.
103 resource: Any = field(default=None, compare=False, repr=False)
105 def as_json(self) -> dict[str, Any]:
106 return {
107 "id": self.id,
108 "slug": self.slug,
109 "name": self.name,
110 "description": self.description,
111 "built_in": self.built_in,
112 }
115@dataclass(frozen=True)
116class CommandContext:
117 """The chat a command runs in: who asks, which agent, which workspace."""
119 db: Session
120 user: Any
121 agent: Any
122 #: The chat's resolved workspace (``app/services/workspace.py``).
123 workspace: Any
124 #: What a command looked up once for this request (svc-ai's worker
125 #: interfaces, for many skills' forms).
126 cache: dict[str, Any] = field(default_factory=dict, compare=False, repr=False)
129@dataclass(frozen=True)
130class CommandForm:
131 """The fields a target takes, as a skill's run schema describes them."""
133 schema: RunSchema
135 @property
136 def request_required(self) -> bool:
137 """With no fields the free text is the only input; with some it is
138 optional instructions."""
139 return self.schema.requires_prompt
141 def as_json(self) -> dict[str, Any]:
142 return {
143 "fields": [f.as_dict() for f in self.schema.fields],
144 "request": "required" if self.request_required else "optional",
145 "complete": self.schema.complete,
146 }
149@dataclass(frozen=True)
150class SkillDispatch:
151 """Run this skill as the turn — its graph pinned, every node in order —
152 in place of the agent's own dispatch."""
154 skill: Any
157#: How a commanded turn runs. One type today; a command that needs another
158#: way of running a turn adds its dispatch here and the chat route once.
159TurnDispatch = SkillDispatch
162@dataclass(frozen=True)
163class ParsedCommand:
164 """A command the chat will run."""
166 command: ChatCommand
167 target: CommandTarget
168 #: The free text after the command: the request, or for a target with a
169 #: form, optional additional instructions.
170 request: str
171 dispatch: TurnDispatch
172 #: The form's values, validated and typed (empty without a form).
173 inputs: dict[str, Any] = field(default_factory=dict)
174 #: What the turn runs on — what rules read, the model is given and the
175 #: user's message stores (``ChatCommand.task``).
176 task: str = ""
178 @property
179 def line(self) -> str:
180 """The command as typed, without the request: what the chat shows."""
181 return self.command.line(self.target.slug)
183 def meta(self) -> dict[str, Any]:
184 """What the user's message keeps about the command it ran — the
185 record of which workflow the person chose, beside what they asked."""
186 return {
187 "line": self.line,
188 "action": self.command.action,
189 "kind": self.command.kind,
190 "target_id": self.target.id,
191 "target_name": self.target.name,
192 "inputs": dict(self.inputs),
193 "request": self.request,
194 }
197class ChatCommand(ABC):
198 """One ``/action kind`` command. Subclasses set the class attributes and
199 implement ``targets`` and ``dispatch``."""
201 action: ClassVar[str]
202 kind: ClassVar[str]
203 #: Short, for the palette's group heading ("Run a skill").
204 label: ClassVar[str]
205 description: ClassVar[str]
206 #: What the request after the target is for, as a prompt to the person.
207 request_hint: ClassVar[str]
208 #: Whether a target with no form needs the free text.
209 request_required: ClassVar[bool] = True
211 @abstractmethod
212 def targets(self, ctx: CommandContext) -> list[CommandTarget]:
213 """What this command can act on in this chat, slugged."""
215 @abstractmethod
216 def dispatch(self, ctx: CommandContext, target: CommandTarget) -> TurnDispatch:
217 """How the turn runs for ``target``, which came from ``targets``."""
219 def form(self, ctx: CommandContext, target: CommandTarget) -> CommandForm | None:
220 """The fields ``target`` takes, or None for free text only."""
221 return None
223 def task(
224 self,
225 ctx: CommandContext,
226 target: CommandTarget,
227 request: str,
228 inputs: dict[str, Any],
229 ) -> str:
230 """The text the turn runs on."""
231 return request
233 def line(self, slug: str = "") -> str:
234 return f"{PREFIX}{self.action} {self.kind}" + (f" {slug}" if slug else "")
236 @property
237 def usage(self) -> str:
238 return f"{self.line()} <{self.kind}> <request>"
240 def catalogue(self, ctx: CommandContext) -> dict[str, Any]:
241 targets = []
242 for target in self.targets(ctx):
243 form = self.form(ctx, target)
244 targets.append(
245 {**target.as_json(), "form": form.as_json() if form else None}
246 )
247 return {
248 "action": self.action,
249 "kind": self.kind,
250 "label": self.label,
251 "description": self.description,
252 "request_hint": self.request_hint,
253 "request_required": self.request_required,
254 "usage": self.usage,
255 "targets": targets,
256 }
259_REGISTRY: dict[tuple[str, str], ChatCommand] = {}
262def register(cls: type[ChatCommand]) -> type[ChatCommand]:
263 key = (cls.action, cls.kind)
264 if key in _REGISTRY:
265 raise ValueError(
266 f"Chat command {PREFIX}{cls.action} {cls.kind} is registered twice"
267 )
268 _REGISTRY[key] = cls()
269 return cls
272def registered() -> list[ChatCommand]:
273 return list(_REGISTRY.values())
276def actions() -> set[str]:
277 return {action for action, _ in _REGISTRY}
280def slugify(name: str) -> str:
281 return _SLUG_UNSAFE.sub("-", (name or "").lower()).strip("-")
284@dataclass
285class _Slugger:
286 """Unique slugs within one command's targets. The first claimant of a
287 slug keeps it — built-ins first, then oldest — and a later one takes its
288 id's first characters, so a slug never moves once given out."""
290 taken: set[str] = field(default_factory=set)
292 def __call__(self, name: str, row_id: Any, fallback: str) -> str:
293 base = slugify(name) or fallback
294 slug = base if base not in self.taken else f"{base}-{str(row_id)[:4]}"
295 self.taken.add(slug)
296 return slug
299# ── Commands ────────────────────────────────────────────────────────────────
302@register
303class ExecuteSkill(ChatCommand):
304 """``/execute skill <skill> <request>`` — run one skill on the request.
306 Any skill the chat's workspace shows (its own, what a project inherits,
307 and the built-ins) whose graph has nodes, whether or not the agent holds
308 it: running a skill is using it, which the workspace already allows. The
309 skill answers as the agent — its persona, its model for the nodes that
310 name none (``agent_transformers.skill_default_model``) — and a
311 skill-scoped rule governs the turn.
312 """
314 action = "execute"
315 kind = "skill"
316 label = "Run a skill"
317 description = (
318 "Run one skill on your request — its whole workflow, in order — "
319 "instead of letting the agent decide how to answer."
320 )
321 request_hint = "What should the skill work on?"
323 def _rows(self, ctx: CommandContext) -> list[Any]:
324 from app.services import workspace as workspace_service
326 rows = (
327 ctx.db.query(Skill)
328 .filter(workspace_service.in_scope(Skill, ctx.workspace, system=True))
329 .all()
330 )
331 runnable = [s for s in rows if (s.graph_definition or {}).get("nodes")]
332 # Built-ins first, then oldest: the order slugs are claimed in.
333 return sorted(
334 runnable,
335 key=lambda s: (
336 s.is_system is not True,
337 str(getattr(s, "created_at", "") or ""),
338 str(s.id),
339 ),
340 )
342 def targets(self, ctx: CommandContext) -> list[CommandTarget]:
343 slug = _Slugger()
344 return [
345 CommandTarget(
346 id=str(s.id),
347 slug=slug(s.name, s.id, self.kind),
348 name=s.name,
349 description=s.description or "",
350 built_in=s.is_system is True,
351 resource=s,
352 )
353 for s in self._rows(ctx)
354 ]
356 def _skill(self, ctx: CommandContext, target: CommandTarget) -> Any:
357 skill = target.resource or ctx.db.get(Skill, UUID(target.id))
358 if skill is None: # a target not from this listing, since deleted
359 raise CommandError(f"{target.name} is no longer available here.")
360 return skill
362 def dispatch(self, ctx: CommandContext, target: CommandTarget) -> SkillDispatch:
363 return SkillDispatch(skill=self._skill(ctx, target))
365 def form(self, ctx: CommandContext, target: CommandTarget) -> CommandForm:
366 """The skill's run schema: the standalone Run form's fields."""
367 from app.services.skill_runs import runner
369 lookup = ctx.cache.setdefault(
370 "definitions", runner.shared_definition_lookup(ctx.db)
371 )
372 return CommandForm(runner.run_schema(ctx.db, self._skill(ctx, target), lookup))
374 def task(
375 self,
376 ctx: CommandContext,
377 target: CommandTarget,
378 request: str,
379 inputs: dict[str, Any],
380 ) -> str:
381 """What a standalone run of the skill would be given."""
382 skill = self._skill(ctx, target)
383 return compose_task(skill.name, skill.description, request, inputs)
386# ── The chat's entry points ─────────────────────────────────────────────────
389def catalogue(ctx: CommandContext) -> list[dict[str, Any]]:
390 """Every command this chat offers, with what each can target."""
391 return [command.catalogue(ctx) for command in registered()]
394def _closest(word: str, options: list[str]) -> list[str]:
395 return difflib.get_close_matches(word, options, n=MAX_SUGGESTIONS, cutoff=0.4)
398def parse(
399 text: str, ctx: CommandContext, inputs: dict[str, Any] | None = None
400) -> ParsedCommand | None:
401 """The command ``text`` runs, or None when it is not one. ``inputs`` are
402 the values of its target's form (``command_inputs``).
404 Raises ``CommandError`` for a known action that cannot run as written.
405 """
406 stripped = (text or "").strip()
407 match = _COMMAND_RE.match(stripped) if stripped.startswith(PREFIX) else None
408 if match is None or match["action"].lower() not in actions():
409 return None
410 action = match["action"].lower()
411 kinds = {kind: cmd for (act, kind), cmd in _REGISTRY.items() if act == action}
413 kind = (match["kind"] or "").lower()
414 if kind not in kinds:
415 lines = [cmd.line() for cmd in kinds.values()]
416 said = (
417 f"“{match['kind']}” is not something {PREFIX}{action} works on. "
418 if kind
419 else ""
420 )
421 raise CommandError(
422 f"{said}Try {' or '.join(lines)}.",
423 [cmd.line() for k, cmd in kinds.items() if k in _closest(kind, list(kinds))]
424 or lines,
425 )
426 command = kinds[kind]
428 targets = command.targets(ctx)
429 by_slug = {t.slug: t for t in targets}
430 wanted = (match["target"] or "").lower()
431 if wanted not in by_slug:
432 suggestions = [command.line(s) for s in _closest(wanted, list(by_slug))] or [
433 command.line(t.slug) for t in targets[:MAX_SUGGESTIONS]
434 ]
435 if not wanted:
436 raise CommandError(f"Name the {kind} to run: {command.usage}.", suggestions)
437 raise CommandError(f"There is no {kind} called “{wanted}” here.", suggestions)
438 target = by_slug[wanted]
440 request = (match["request"] or "").strip()
441 form = command.form(ctx, target)
442 coerced: dict[str, Any] = {}
443 if form is not None:
444 coerced, errors = validate_inputs(form.schema, inputs or {})
445 if errors:
446 missing = [name for name, error in errors.items() if error == "required"]
447 message = (
448 f"Fill in {', '.join(missing)} to run {target.name}."
449 if len(missing) == len(errors)
450 else f"Some of {target.name}'s inputs are missing or invalid."
451 )
452 raise CommandError(message, fields=errors)
453 request_required = form.request_required
454 else:
455 if inputs:
456 raise CommandError(f"{command.line(target.slug)} takes no form.")
457 request_required = command.request_required
458 if request_required and not request:
459 raise CommandError(
460 f"Add what {target.name} should work on after {command.line(target.slug)}."
461 )
462 return ParsedCommand(
463 command=command,
464 target=target,
465 request=request,
466 dispatch=command.dispatch(ctx, target),
467 inputs=coerced,
468 task=command.task(ctx, target, request, coerced),
469 )