File size: 6,848 Bytes
aa1490a 1ad1eea aa1490a 8145bee aa1490a 0e600b9 aa1490a 8145bee aa1490a 8145bee aa1490a 1ad1eea aa1490a 0e600b9 aa1490a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | """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"
|