loopable / api /agent_tools.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
1ad1eea verified
Raw History Blame
6.85 kB
"""Assistant-only tools, separate from the public AI API registry (C11).
Tool functions receive ``fn(session, args)`` with the signed-in deps.Session.
For module compatibility, a function with exactly one parameter receives ``fn(args)``.
Modules declare TOOLS entries with name, schema, fn and effect; loading is lazy.
"""
import copy
import importlib
import json
import logging
import re
from core import external_tools
EFFECTS = ("read", "write", "delete")
AGENT_TOOL_MODULES = ("schedule_tools", "ticket_tools", "loopy_tools", "web_task_tools", "assistant_open_items")
_TOOLS = {}
_LOG = logging.getLogger(__name__)
def register(name, schema, fn, *, effect):
if not isinstance(name, str) or not name or name == "confirm_change" or name in external_tools.TOOLS:
raise ValueError("An Assistant tool must have its own name.")
if effect not in EFFECTS:
raise ValueError("An Assistant tool must declare read, write or delete.")
if not isinstance(schema, dict) or schema.get("type") != "object":
raise ValueError("An Assistant tool schema must be a JSON schema object.")
try:
json.dumps(schema, allow_nan=False)
except (TypeError, ValueError) as exc:
raise ValueError("An Assistant tool schema must contain JSON values.") from exc
if not callable(fn):
raise ValueError("An Assistant tool must have a callable function.")
_TOOLS[name] = {"name": name, "schema": copy.deepcopy(schema), "fn": fn, "effect": effect}
def load_modules():
from core import keychain
# Minting changes only capability metadata. Credentials are entered through the
# public form, so every channel may return this link without a write confirmation.
register("connector_setup_link", {
"type": "object",
"description": "Create a one-time HTTPS setup link for your connector. Enter credentials only through the link.",
"properties": {
"connector": {"type": "string", "enum": sorted(keychain.ENTRY_TYPES)},
"scope": {"type": "string", "enum": ["personal", "business"]},
},
"required": ["connector", "scope"],
"additionalProperties": False,
}, _connector_setup_link, effect="read")
for name in AGENT_TOOL_MODULES:
try:
module = importlib.import_module(name)
refresh = getattr(module, "refresh_tools", None)
if callable(refresh):
refresh()
except ModuleNotFoundError as exc:
if exc.name == name:
_LOG.info("Assistant tool module %s is unavailable", name)
else:
_LOG.warning("Assistant tool module %s has an unavailable dependency (%s)", name, exc.name)
continue
except Exception as exc:
_LOG.warning("Assistant tool module %s is unavailable (%s)", name, type(exc).__name__)
continue
for entry in getattr(module, "TOOLS", ()):
# One malformed entry from another lane's module must not take every turn down.
try:
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
except (KeyError, TypeError, ValueError) as exc:
_LOG.info("Assistant tool entry in %s was skipped (%s)", name, type(exc).__name__)
# S72-T26: the directory sits outside AGENT_TOOL_MODULES, which verify_query pins exactly.
# A failure here must not take every turn down.
try:
import agent_directory
for entry in agent_directory.TOOLS:
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
except Exception as exc: # noqa: BLE001
_LOG.warning("Assistant directory tool is unavailable (%s)", type(exc).__name__)
# S72-T27: agent messages, outside AGENT_TOOL_MODULES for the same reason.
try:
import agent_inbox
for entry in agent_inbox.TOOLS:
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
except Exception as exc: # noqa: BLE001
_LOG.warning("Assistant inbox tool is unavailable (%s)", type(exc).__name__)
_NOT_A_NAME = r"(?!(?:me|us|my|our|the|a|an|what|how|who|which|when|why|where|about)\b)"
_DIRECTORY = tuple(re.compile(p) for p in (
r"^who (?:uses|is using) loopable\b",
r"^who(?: is| are)? (?:in|on) (?:my|our) (?:workspace|team)\b",
r"^who has access to \w",
r"^what access does \w[\w .'-]* have\b",
))
_INBOX = tuple(re.compile(p) for p in (
r"^(?:please )?ask " + _NOT_A_NAME + r"\w+(?: \w+)? for (?:edit |view )?access to \w",
r"^(?:please )?request (?:edit |view )?access to \w",
r"^(?:please )?tell " + _NOT_A_NAME + r"\w+(?: \w+)? (?:that|to|about|we|i|our|the|my|it)\b",
r"^(?:please )?ask " + _NOT_A_NAME + r"\w+(?: \w+)? (?:whether|if|about) \w",
))
def admitted_tools(question):
"""The tools a directory or inbox question admits without a database match, else empty."""
text = " ".join(str(question or "").casefold().replace("\u2019", "'").split()).strip(" ?.!")
if not text:
return frozenset()
if any(p.search(text) for p in _INBOX):
return frozenset({"workspace_people", "agent_message"})
try:
import agent_directory
if agent_directory.admits(question):
return frozenset({"workspace_people"})
except Exception: # noqa: BLE001
pass
if any(p.search(text) for p in _DIRECTORY):
return frozenset({"workspace_people"})
return frozenset()
def _connector_setup_link(session, args):
from routes_forms import mint_setup_link
return mint_setup_link(args, session=session)
def registered():
return {name: {**entry, "schema": copy.deepcopy(entry["schema"])}
for name, entry in _TOOLS.items()}
def classify(name, args):
if not isinstance(name, str):
return "write"
if name in _TOOLS:
return _TOOLS[name]["effect"]
args = args if isinstance(args, dict) else {}
if name in ("sheet_delete_tab", "view_delete", "app_delete"):
return "delete"
if name == "database_object" and args.get("action") in ("record_delete", "field_delete"):
return "delete"
if name in ("view_object", "worksheet_object") and args.get("action") == "delete":
return "delete"
operations = args.get("operations")
if name == "validated_batch" and isinstance(operations, list) and any(
classify(op.get("name"), op.get("arguments", {})) == "delete"
for op in operations if isinstance(op, dict)):
return "delete"
if name not in external_tools.TOOLS:
return "write"
return "write" if external_tools.is_write(name, args) else "read"