File size: 13,910 Bytes
9ad4b87
 
 
d598032
9ad4b87
 
 
 
 
868b75a
 
cf09724
 
 
 
868b75a
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
 
cf09724
 
868b75a
cf09724
868b75a
 
 
cf09724
 
 
868b75a
 
 
 
 
 
 
 
 
 
 
 
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
301db09
 
9ad4b87
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad4b87
 
868b75a
9ad4b87
 
cf09724
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
85f794d
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ca2251
 
 
 
 
 
 
9ad4b87
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
 
9ad4b87
cf09724
 
9ad4b87
 
 
 
cf09724
 
 
9ad4b87
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Discover MCP groups and adapt the previous tool names."""
import copy
import importlib
import json
import pkgutil

from core import external_tools, sheets


_GROUP_MODULE_NAMES = {"data": "table"}
TABLE_ALIAS_NOTE = "The data tool is deprecated for one release. Use table for the Table module."
GUIDE_TOOL = "loopable_guide"
# One intent schema for the base specs and the served tools/list, so the two cannot drift.
INTENT_SCHEMA = {"type": "string", "minLength": 1, "maxLength": 500,
    "description": "State why you are making this call. Required for every write, including confirmation."}


def canonical_name(name):
    """Resolve the previous Table group key without advertising a second group."""
    return "table" if name == "data" else name


def _prefixed_action(name, arguments):
    """Strip a repeated group prefix from an action, as in sheet_write_cells, when the rest is exact."""
    group = groups().get(canonical_name(name))
    action = arguments.get("action") if isinstance(arguments, dict) else None
    if group is None or not isinstance(action, str) or action in group["actions"]:
        return arguments
    inner = arguments.get("arguments")
    if action == group["name"] and isinstance(inner, dict) and inner.get("action") in group["actions"]:
        # The group name sent as the action, with the real action inside arguments, unwraps one level.
        rest = {key: value for key, value in inner.items() if key != "action"}
        return {**arguments, "action": inner["action"], "arguments": rest}
    for prefix in {name, canonical_name(name)}:
        for joint in ("_", "."):
            if action.startswith(prefix + joint) and action[len(prefix) + 1:] in group["actions"]:
                return {**arguments, "action": action[len(prefix) + 1:]}
    return arguments


def canonical_call(name, arguments):
    """Adapt Table group aliases and dotted actions before normal admission."""
    if name == GUIDE_TOOL + ".read":
        return GUIDE_TOOL, arguments
    if name == "data":
        return "table", _prefixed_action("data", arguments)
    if not isinstance(name, str):
        return name, arguments
    prefix, separator, action = name.partition(".")
    if not separator:
        return name, _prefixed_action(name, arguments)
    if prefix not in {"table", "data"}:
        return name, arguments
    entry = groups().get("table", {}).get("actions", {}).get(action)
    if entry is None:
        return name, arguments
    if not isinstance(arguments, dict):
        return "table", arguments
    metadata = {key: value for key, value in arguments.items() if key in {"intent", "purpose", "about"}}
    args = {key: value for key, value in arguments.items() if key not in metadata}
    if entry.get("legacy_action") is not None:
        args.setdefault("action", entry["legacy_action"])
    return "table", {"action": action, "arguments": args, **metadata}


def legacy_action(name, *, action=None, read=None, destructive=False):
    """Bind one legacy operation to a fixed read or write class."""
    tool = external_tools.TOOLS[name]
    schema = copy.deepcopy(tool["inputSchema"])
    if action is not None:
        schema["properties"]["action"] = {"enum": [action]}
    if read is None:
        read = not tool["write"]
    return {
        "read": read, "destructive": destructive, "confirm": True,
        "schema": schema,
        "handler": lambda ctx, args: external_tools.dispatch(ctx, name, args),
        "legacy_name": name, "legacy_action": action,
    }


def groups():
    """Find group modules without requiring optional groups to be installed."""
    found = {}
    importlib.invalidate_caches()
    for module in sorted(pkgutil.iter_modules(__path__), key=lambda item: item.name):
        if module.name.startswith("_") or module.ispkg:
            continue
        group = importlib.import_module(f"{__name__}.{module.name}").GROUP
        name = group["name"]
        if (name != _GROUP_MODULE_NAMES.get(module.name, module.name) or name in found
                or name in external_tools.TOOLS or name == "loopable_guide"):
            raise ValueError("Invalid tool group name")
        if not all(isinstance(group[key], str) and group[key] for key in ("name", "title", "guide")):
            raise ValueError("Invalid tool group description")
        if not isinstance(group["actions"], dict) or not group["actions"]:
            raise ValueError("A tool group needs actions")
        for key, entry in group["actions"].items():
            if not isinstance(key, str) or not key:
                raise ValueError("Invalid tool action name")
            if any(type(entry[field]) is not bool for field in ("read", "destructive", "confirm")):
                raise ValueError("Tool action effects must be explicit")
            if not isinstance(entry["schema"], dict) or not callable(entry["handler"]):
                raise ValueError("A tool action needs a schema and handler")
            # Receipt checks are read-only and return True only with current object access.
            if "receipt_access" in entry and not callable(entry["receipt_access"]):
                raise ValueError("A receipt access check must be callable")
            if entry["read"] and entry["destructive"]:
                raise ValueError("A read action cannot be destructive")
            if not entry["read"] and not entry["confirm"] and (name, key) not in {
                    ("requests", "send"), ("requests", "send_message"), ("intelligence", "create_wiki")}:
                raise ValueError("Only requests.send, requests.send_message and intelligence.create_wiki may write without confirmation")
        found[name] = group
    return found


def _kind(rule):
    """Name the JSON type a schema rule accepts, in plain words."""
    if not isinstance(rule, dict):
        return "value"
    if isinstance(rule.get("enum"), list) and rule["enum"]:
        return "one of " + ", ".join(str(choice) for choice in rule["enum"])
    kind = rule.get("type")
    if isinstance(kind, list):
        return " or ".join(str(item) for item in kind)
    if isinstance(kind, str):
        return kind
    branches = rule.get("oneOf") or rule.get("anyOf") or []
    kinds = list(dict.fromkeys(_kind(branch) for branch in branches))
    return " or ".join(kinds) or "value"


def _example(key, rule):
    """Return a placeholder value of the type a schema rule accepts."""
    if not isinstance(rule, dict):
        return "<" + key + ">"
    if isinstance(rule.get("enum"), list) and len(rule["enum"]) == 1:
        return rule["enum"][0]
    kind = rule.get("type")
    if kind == "array":
        return [_example(key, rule.get("items"))]
    if kind == "object":
        return {}
    if kind in ("integer", "number"):
        return max(1, rule.get("minimum", 1))
    if kind == "boolean":
        return True
    return "<" + key + ">"


def call_shape(group, action, schema, sent=None, example=None):
    """Name the current address, the argument shape and any key the caller got wrong."""
    schema = schema if isinstance(schema, dict) else {}
    properties = schema.get("properties", {})
    required = [key for key in schema.get("required", ()) if key in properties]
    shown = example if isinstance(example, dict) else {key: _example(key, properties[key]) for key in required}
    sentences = []
    if isinstance(sent, dict):
        stray = sorted(str(key) for key in sent if key not in properties)
        missing = [key for key in required if key not in sent]
        if stray and schema.get("additionalProperties") is False:
            sentences.append(", ".join(stray) + (" is not an argument of " if len(stray) == 1
                                                 else " are not arguments of ") + action + ".")
        if missing:
            sentences.append(", ".join(missing) + (" is required." if len(missing) == 1 else " are required."))
    sentences.append("Call " + group + " with " + json.dumps(
        {"action": action, "arguments": shown}, separators=(", ", ": ")) + ".")
    optional = [key for key in properties if key not in required and key not in shown
                and key not in {"action", "arguments"}]
    if optional:
        sentences.append("Optional arguments: " + ", ".join(
            key + " (" + _kind(properties[key]) + ")" for key in optional) + ".")
    elif not properties or set(properties) <= {"action", "arguments"}:
        sentences.append(action + " takes no arguments.")
    return " ".join(sentences)


def resolve(name, arguments):
    """Validate the selected action before a preview or handler can run."""
    group = groups().get(canonical_name(name)) if isinstance(name, str) else None
    if group is None:
        return None
    action = arguments.get("action") if isinstance(arguments, dict) else None
    if isinstance(arguments, dict) and (not isinstance(action, str) or action not in group["actions"]):
        # A bare group name as the action gets one clause naming the mix-up before the action list.
        named = group["name"] + " is the tool name, not an action. " if action == group["name"] else ""
        raise sheets.SheetRefusal("tool_arguments_invalid", (
            named + "Tool arguments must match the published input schema. Set action to one of the "
            + group["name"] + " actions: " + ", ".join(group["actions"]) + ". Put that action's inputs inside "
            "arguments, and intent, about and purpose beside action and arguments."))
    entry = group["actions"][arguments["action"]] if isinstance(arguments, dict) else None
    try:
        external_tools.validate_arguments(arguments, {
            "type": "object", "properties": {
                "action": {"type": "string", "enum": list(group["actions"])},
                "arguments": {"type": "object"},
            }, "required": ["action"], "additionalProperties": False,
        })
        args = arguments.get("arguments", {})
        if entry.get("legacy_name") in {"query_database", "list_databases"}:
            args = external_tools.table_read_arguments(entry["legacy_name"], args, entry["schema"])
        else:
            external_tools.validate_arguments(args, entry["schema"])
    except sheets.SheetRefusal as exc:
        if exc.code != "tool_arguments_invalid" or entry is None:
            raise
        # S79-T11: a schema refusal names the current tool, action and argument shape.
        stray = sorted(str(key) for key in arguments if key not in {"action", "arguments"})
        beside = (", ".join(stray) + (" goes" if len(stray) == 1 else " go")
                  + " inside arguments, not beside action. ") if stray else ""
        inner = arguments.get("arguments")
        raise sheets.SheetRefusal(exc.code, exc.message + " " + beside + call_shape(
            group["name"], arguments["action"], entry["schema"],
            inner if isinstance(inner, dict) else {}, entry.get("example"))) from exc
    legacy = entry.get("legacy_name")
    if legacy and external_tools.is_write(legacy, args) == entry["read"]:
        raise sheets.SheetRefusal(
            "tool_arguments_invalid", "Choose the action that matches this change.")
    return entry, args


def legacy_target(name, arguments):
    """Return the grouped address for each supported legacy operation."""
    for group_name, group in groups().items():
        for action, entry in group["actions"].items():
            if entry.get("legacy_name") != name:
                continue
            fixed = entry.get("legacy_action")
            if fixed is not None and arguments.get("action") != fixed:
                continue
            if external_tools.is_write(name, arguments) == entry["read"]:
                continue
            return group_name, {"action": action, "arguments": copy.deepcopy(arguments)}
    if name.endswith("_object") and isinstance(arguments.get("action"), str):
        # A native handler that replaced a legacy object action keeps the grouped address.
        operation = name.removesuffix("_object") + "." + arguments["action"]
        for group_name, group in groups().items():
            entry = group["actions"].get(operation)
            if entry is not None and not entry.get("legacy_name"):
                return group_name, {"action": operation, "arguments": copy.deepcopy(arguments)}
    if name == "confirm_change":
        return name, copy.deepcopy(arguments)
    raise KeyError(name)


def action_grants(entry, group=""):
    """Use the handler's declared grants for caller capability reporting."""
    legacy = entry.get("legacy_name")
    if legacy:
        return external_tools.TOOLS[legacy]["grants"]
    grants = ("ai_apps", "intelligence") if group == "intelligence" else ("ai_apps",)
    return tuple(dict.fromkeys((*grants, *entry.get("grants", ()))))


def writes(group):
    """Tell whether any action in a group writes."""
    return any(not entry["read"] for entry in group["actions"].values())


def tool_specs():
    """Publish compact group summaries with call metadata and conservative effect hints."""
    import wiki_log
    return [{
        "name": name, "description": group["guide"],
        "inputSchema": {"type": "object", "properties": {
            "action": {"type": "string"}, "arguments": {"type": "object"},
            "intent": copy.deepcopy(INTENT_SCHEMA), "about": copy.deepcopy(external_tools.ABOUT_SCHEMA),
            "purpose": copy.deepcopy(wiki_log.PURPOSE_SCHEMA),
        }, "required": ["action", "intent"] if writes(group) else ["action"], "additionalProperties": False},
        "annotations": {
            "title": group["title"],
            "readOnlyHint": all(entry["read"] for entry in group["actions"].values()),
            "destructiveHint": any(entry["destructive"] for entry in group["actions"].values()),
            "openWorldHint": True,
        },
    } for name, group in groups().items()]