8000 feat(assistant): add tools, skills, hooks and plugins to the assistant by adeelahmad · Pull Request #81 · adeelahmad/lense · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions DEVLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,32 @@

Plans and progress for work in flight. Newest first.

## 2026-10-03 · Assistant extensions: tools, skills, hooks, plugins

Goal: the assistant can be extended to the same level by code, the canvas, voice or plain chat.

Model (fastapi_backend/app/domain/extensions.py, /api/v1/extensions):

- One registry, four kinds: tool (params, effect read/change, body prompt/http, later code and canvas graph), skill
(when + instructions, read with `use_skill`), hook (message, before_tool, after_tool, answer: add context, block a
tool, call a tool), plugin (a bundle of the three, shared and switched off as one).
- Versioned and shared like custom nodes (private / namespace / everyone); a version records how it was made (code,
canvas, chat). Change tools wait for approval like the built-in ones; `ai.extensions` turns them all off.
- Manifests as code: Markdown with frontmatter (body = skill instructions or a prompt tool's prompt) or YAML/JSON.

Todo:

- [x] Registry, versions, sharing, manifests in and out, check without saving, try a tool
- [x] Prompt and web tools, skills, hooks in the chat tool loop; approvals for change tools
- [ ] Code tools: Python in a sandboxed subprocess (admins create; time limit, no secrets, no network unless allowed)
- [ ] Canvas: a `tool` workflow scope whose arg nodes are the tool's parameters; save a graph as a tool
- [ ] Authoring from chat and voice: the assistant drafts, tries and saves extensions behind an approval card
- [ ] Extensions page in the web app: list, manifest editor, switch on/off, share, try
- [ ] `lens ext` CLI (push/pull manifests)

Refine later: hook-called tools don't show as steps; web tools reach ports 80/443 only and have no secret
references yet; extensions aren't offered over MCP yet; marketplace on top of plugins.

## 2026-10-02 · Routines

Goal: run syncs, pipelines and workflows on a schedule, including a daily LLM pass that organises the entity graph per
Expand Down
2 changes: 2 additions & 0 deletions fastapi_backend/app/api/v1/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
custom_nodes,
entities,
entity_setup,
extensions,
fields,
files,
hierarchy,
Expand Down Expand Up @@ -78,6 +79,7 @@
content_types,
workflows,
custom_nodes,
extensions,
chats,
collections,
batches,
Expand Down
3 changes: 2 additions & 1 deletion fastapi_backend/app/api/v1/routes/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ def answer(on: chat.Answering) -> Iterator[str]:
else:
answer = data
else:
box.after_answer(answer)
for appr in box.approvals:
yield _ev("approval", appr)
cited = box.cited(answer)
Expand Down Expand Up @@ -343,7 +344,7 @@ def decide_approval(aid: int, body: ApprovalDecision, user: Writer, acl: Acl, db
raise HTTPException(404, "not found")
try:
out = ai_tools.approve(
db, cfg, aid, user.as_audit(), set(acl.editable()), body.decision, request.app.state.archive.base, user.admin
db, cfg, aid, user.as_audit(), set(acl.editable()), body.decision, request.app.state.archive.base, user.admin, set(acl.roles)
)
except (ValueError, PermissionError, KeyError) as e:
raise HTTPException(400, str(e)) from None
Expand Down
119 changes: 119 additions & 0 deletions fastapi_backend/app/api/v1/routes/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Extensions: tools, skills, hooks and plugins for the assistant, kept private or shared like custom nodes."""

from __future__ import annotations

import contextlib
from collections.abc import Iterator
from typing import Any

from fastapi import APIRouter, HTTPException

from app.api.deps import Cfg, CurrentUser, Db, Principal, Writer, domain_errors
from app.domain import auth, extensions
from app.schemas.common import Created, Ok
from app.schemas.extensions import (
Extension,
ExtensionCreate,
ExtensionDetail,
ExtensionTest,
ExtensionTestResult,
ExtensionUpdate,
ExtensionVersionCreate,
Kind,
ManifestCheck,
ManifestChecked,
)
from app.schemas.templates import VersionSaved

router = APIRouter(prefix="/extensions", tags=["extensions"])


def me(user: Principal) -> dict[str, Any]:
return extensions.who(user.id, user.email, user.admin and user.via != "oauth", user.roles)


@contextlib.contextmanager
def _errors() -> Iterator[None]:
with domain_errors():
try:
yield
except PermissionError as e:
raise HTTPException(403, str(e)) from None


def _manifest(body: ExtensionCreate | ExtensionVersionCreate) -> dict[str, Any]:
if (body.manifest is None) == (body.text is None):
raise ValueError("send the manifest as an object or as text, one of the two")
return body.manifest if body.manifest is not None else extensions.parse_manifest(body.text)


@router.get("")
def list_extensions(user: CurrentUser, db: Db, kind: Kind | None = None) -> list[Extension]:
"""The extensions you can see: yours, the ones shared with your namespaces or with everyone (admins: all)."""
return extensions.visible(db, me(user), kind)


@router.post("/check")
def check_manifest(body: ManifestCheck, user: CurrentUser) -> ManifestChecked:
"""Read and check a manifest written as code, without saving it: 400 says what's wrong."""
with _errors():
return ManifestChecked(manifest=extensions.check_manifest(extensions.parse_manifest(body.text), me(user)))


@router.post("")
def create_extension(body: ExtensionCreate, user: Writer, db: Db) -> Created:
with _errors():
eid = extensions.create(db, me(user), _manifest(body), body.enabled, body.origin)
auth.audit(db, user.as_audit(), "extension.create", f"extension:{eid}", {"origin": body.origin})
return Created(id=eid)


@router.get("/{eid}")
def get_extension(eid: int, user: CurrentUser, db: Db, version: int | None = None) -> ExtensionDetail:
"""One version (default: the current one), as a manifest too, and the list of versions."""
with _errors():
return extensions.visible_one(db, me(user), eid, version)


@router.post("/{eid}/versions")
def create_extension_version(eid: int, body: ExtensionVersionCreate, user: Writer, db: Db) -> VersionSaved:
with _errors():
n = extensions.save_version(db, me(user), eid, _manifest(body), body.notes, body.origin)
auth.audit(db, user.as_audit(), "extension.save", f"extension:{eid}", {"version": n, "origin": body.origin})
return VersionSaved(version=n)


@router.patch("/{eid}")
def update_extension(eid: int, body: ExtensionUpdate, user: Writer, db: Db) -> Ok:
"""Its title, description, who sees it, and whether it's switched on."""
with _errors():
extensions.update(db, me(user), eid, **body.model_dump(exclude_unset=True))
auth.audit(db, user.as_audit(), "extension.update", f"extension:{eid}", body.model_dump(exclude_unset=True))
return Ok()


@router.delete("/{eid}")
def delete_extension(eid: int, user: Writer, db: Db) -> Ok:
"""Takes it out of the assistant at once."""
with _errors():
extensions.remove(db, me(user), eid)
auth.audit(db, user.as_audit(), "extension.delete", f"extension:{eid}")
return Ok()


@router.post("/{eid}/test")
def test_extension(eid: int, body: ExtensionTest, user: Writer, db: Db, cfg: Cfg) -> ExtensionTestResult:
"""Try one of its tools with these arguments, switched on or not. A tool that changes something really runs, so it
needs `confirm`."""
with _errors():
g = extensions.visible_one(db, me(user), eid)
items = g["spec"]["items"] if g["kind"] == "plugin" else [g]
name = body.tool or (g["name"] if g["kind"] == "tool" else None)
t = next((it for it in items if it.get("kind") == "tool" and it["name"] == name), None)
if not t:
raise ValueError("name one of its tools to try")
if t["spec"]["effect"] == "change" and not body.confirm:
raise ValueError("this tool changes something: confirm to really run it")
out = extensions.run_tool(db, cfg, t["spec"], extensions.tool_args(t["spec"], body.args))
auth.audit(db, user.as_audit(), "extension.test", f"extension:{eid}", {"tool": name})
return ExtensionTestResult(output=out)
111 changes: 108 additions & 3 deletions fastapi_backend/app/domain/ai_tools.py
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from . import (
batches,
entities,
extensions,
entity_map,
entity_setup,
ops_tools,
Expand Down Expand Up @@ -115,6 +116,11 @@
]


def builtin_names():
"""The assistant's own tool names, which extensions can't take."""
return {t[0] for t in TOOLS + ops_tools.ADMIN_TOOLS + ops_tools.FILE_TOOLS} | {"use_skill"}


class Toolbox(ops_tools.OpsTools):
"""`admin` adds the server tools (ops_tools.py), with `base` (archive.yaml's config) to save settings over; `act`
makes their changes at once instead of asking for approval."""
Expand All @@ -129,6 +135,38 @@ def __init__(self, db, cfg, user, readable, editable, scope, chat_id, base=None,
self.readable = {s for s in self.readable if names.get(s) in self.scope["namespaces"]}
self.allowed = recsets.within(db, self.readable, self.scope.get("recordings"), self.scope.get("collections"))
self.refs, self.reads, self.approvals = [], 0, []
# the extensions this person switched on or was given (extensions.py); hooks don't run inside hooks
me = extensions.who(user["id"], user.get("email"), admin, {s: "viewer" for s in self.readable})
self.ext = extensions.Active(db, me) if cfg["ai"].get("extensions", True) else None
self.hooking = False

def system_note(self):
"""What the model is told besides its usual instructions: the skills it can follow, and context that hooks add
for this question."""
if not self.ext:
return ""
out = self.ext.system_note()
for h in self.ext.matching("message", text=self.said):
out += self._hook(h, {"said": self.said})
return out

def after_answer(self, text):
"""Run the hooks for an answer that was written."""
for h in self.ext.matching("answer", text=text) if self.ext else ():
self._hook(h, {"said": self.said, "answer": text})

def _hook(self, h, values):
"""Carry out one hook: context it adds (returned), a tool it calls (run like any other, approvals and all)."""
a = h["spec"]["action"]
if a["type"] == "context":
return "\n\n" + extensions.fill(a["text"], values)
if a["type"] == "tool" and not self.hooking:
self.hooking = True
try:
self.call(a["tool"], extensions.fill_json(a["args"], values))
finally:
self.hooking = False
return ""

def specs(self):
off = set(self.cfg["ai"].get("disabled_tools") or [])
Expand All @@ -138,6 +176,8 @@ def specs(self):
tools += ops_tools.ADMIN_TOOLS
if can_act or self.admin:
tools += ops_tools.FILE_TOOLS
if self.ext:
tools += self.ext.tool_specs(can_act or self.admin)
return [
{
"type": "function",
Expand Down Expand Up @@ -176,9 +216,58 @@ def call(self, name, args):
try:
if name not in offered:
raise AttributeError(name)
fn = getattr(self, "t_" + name)
fn = getattr(self, "t_" + name, None) or self._ext_tool(name)
except AttributeError:
return json.dumps({"error": f"no tool {name}"}), f"unknown tool {name}"
hooks, extra = self.ext and not self.hooking, ""
if hooks:
for h in self.ext.matching("before_tool", name, json.dumps(args or {}, default=str)):
if h["spec"]["action"]["type"] == "block":
why = extensions.fill(h["spec"]["action"]["reason"], {"said": self.said, "tool": name})
return json.dumps({"error": f"blocked: {why}"}), f"{name}: blocked ({why})"
extra += self._hook(h, {"said": self.said, "tool": name})
result, summary = self._run(name, fn, args)
if hooks:
for h in self.ext.matching("after_tool", name, result):
extra += self._hook(h, {"said": self.said, "tool": name, "result": result[:4000]})
if extra: # what hooks add, next to what the tool gave back
try:
got = json.loads(result)
except ValueError:
got = result
result = json.dumps({"result": got, "note": extra.strip()}, ensure_ascii=False, default=str)
return result, summary

def _ext_tool(self, name):
"""An extension's tool (or use_skill), called like the built-in ones."""
if name == "use_skill":
return self.t_use_skill
t = (self.ext.tools if self.ext else {}).get(name)
if not t:
raise AttributeError(name)

def run(**args):
args = extensions.tool_args(t["spec"], args)
what = f"{t['name']}(" + ", ".join(f"{k}={json.dumps(v, ensure_ascii=False)[:60]}" for k, v in args.items()) + ")"
if t["spec"]["effect"] == "change" and not self.act:
return self._approval(
"extension", {"tool": t["name"], "extension": t["ext"], "version": t["version"], "args": args}, f"Run {what}"
)
out = extensions.run_tool(self.db, self.cfg, t["spec"], args)
return out, f"Ran {what}"

return run

def t_use_skill(self, name):
s = (self.ext.skills if self.ext else {}).get(name)
if not s:
raise ValueError(f"no skill {name}")
out = {"skill": name, "instructions": s["spec"]["instructions"]}
if s["spec"].get("tools"):
out["tools"] = s["spec"]["tools"]
return out, f"Read the skill {name}"

def _run(self, name, fn, args):
try:
out, summary = fn(**{k: v for k, v in (args or {}).items() if v is not None})
except KeyError as e: # an id or name that doesn't exist
Expand Down Expand Up @@ -461,7 +550,7 @@ def cited(self, text):
return [{**r, "used": r["n"] in used} for r in self.refs if r["n"] in used]


def approve(db, cfg, aid, user, editable, decision="approve", base=None, admin=False):
def approve(db, cfg, aid, user, editable, decision="approve", base=None, admin=False, readable=None):
"""Carry out an approved action: a batch run (or a sample of it), an entity change, or a change to the server
(ops_tools.py: settings, a namespace, importing attached files)."""
a = db.one("SELECT record::id(id) AS id, chat, account, tool, args, status FROM $r", r=R("approval", int(aid)))
Expand All @@ -473,7 +562,9 @@ def approve(db, cfg, aid, user, editable, decision="approve", base=None, admin=F
)
return {"status": "declined"}
args = a["args"]
if a["tool"] in ("change_settings", "create_namespace", "import_files"):
if a["tool"] == "extension":
result = run_extension(db, cfg, args, user, admin, readable if readable is not None else editable)
elif a["tool"] in ("change_settings", "create_namespace", "import_files"):
result = ops_tools.apply(db, cfg, base or cfg, a["tool"], args, user, editable, admin)
elif a["tool"] == "run_template":
steps, label = batches.steps_for(db, {"template": args["template_id"]})
Expand Down Expand Up @@ -526,3 +617,17 @@ def approve(db, cfg, aid, user, editable, decision="approve", base=None, admin=F
res=result,
)
return {"status": "done", **result}


def run_extension(db, cfg, args, user, admin, readable):
"""An approved extension tool: the version that was proposed, if it's still on and still the person's to use."""
g = extensions.get(db, int(args["extension"]), args.get("version"))
me = extensions.who(user["id"], user.get("email"), admin, {s: "viewer" for s in readable})
if g.get("deleted_at") or not g.get("enabled") or not extensions.can_use(g, me):
raise ValueError("that extension was switched off or removed")
items = g["spec"]["items"] if g["kind"] == "plugin" else [g]
t = next((it for it in items if it.get("kind") == "tool" and it["name"] == args["tool"]), None)
if not t:
raise ValueError(f"the extension has no tool {args['tool']} any more")
out = extensions.run_tool(db, cfg, t["spec"], extensions.tool_args(t["spec"], args.get("args") or {}))
return {"output": out}
2 changes: 2 additions & 0 deletions fastapi_backend/app/domain/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,8 @@ def tool_answer(cfg, toolbox, question, history=(), max_steps=6, model=None, set
answered without looking anything up (it never saw the archive, so the caller can answer from a search instead).
Raises llm.ToolsUnsupported."""
system = TOOL_SYSTEM + ("\n\n" + SETUP_SYSTEM if setup else "")
note = getattr(toolbox, "system_note", None) # skills, and context from hooks (extensions.py)
system += note() if note else ""
msgs = [{"role": "system", "content": system}] + past_turns(history)
msgs.append({"role": "user", "content": question})
for step in range(max_steps):
Expand Down
Loading
Loading
0