|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +from dataclasses import dataclass |
| 6 | +from typing import Any, Callable |
| 7 | + |
| 8 | + |
| 9 | +class StopRun(Exception): |
| 10 | + def __init__(self, reason: str): |
| 11 | + super().__init__(reason) |
| 12 | + self.reason = reason |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(frozen=True) |
| 16 | +class Budget: |
| 17 | + max_plan_steps: int = 6 |
| 18 | + max_execute_steps: int = 8 |
| 19 | + max_tool_calls: int = 8 |
| 20 | + max_seconds: int = 60 |
| 21 | + |
| 22 | + |
| 23 | +def _stable_json(value: Any) -> str: |
| 24 | + if value is None or isinstance(value, (bool, int, float, str)): |
| 25 | + return json.dumps(value, ensure_ascii=True, sort_keys=True) |
| 26 | + if isinstance(value, list): |
| 27 | + return "[" + ",".join(_stable_json(item) for item in value) + "]" |
| 28 | + if isinstance(value, dict): |
| 29 | + parts = [] |
| 30 | + for key in sorted(value): |
| 31 | + parts.append( |
| 32 | + json.dumps(str(key), ensure_ascii=True) + ":" + _stable_json(value[key]) |
| 33 | + ) |
| 34 | + return "{" + ",".join(parts) + "}" |
| 35 | + return json.dumps(str(value), ensure_ascii=True) |
| 36 | + |
| 37 | + |
| 38 | +def args_hash(args: dict[str, Any]) -> str: |
| 39 | + raw = _stable_json(args or {}) |
| 40 | + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12] |
| 41 | + |
| 42 | + |
| 43 | +def validate_plan_action( |
| 44 | + action: Any, *, max_plan_steps: int, allowed_tools: set[str] |
| 45 | +) -> list[dict[str, Any]]: |
| 46 | + if not isinstance(action, dict): |
| 47 | + raise StopRun("invalid_plan:not_object") |
| 48 | + |
| 49 | + kind = action.get("kind") |
| 50 | + if kind == "invalid": |
| 51 | + raise StopRun("invalid_plan:non_json") |
| 52 | + if kind != "plan": |
| 53 | + raise StopRun("invalid_plan:bad_kind") |
| 54 | + |
| 55 | + allowed_top_keys = {"kind", "steps"} |
| 56 | + if set(action.keys()) - allowed_top_keys: |
| 57 | + raise StopRun("invalid_plan:extra_keys") |
| 58 | + |
| 59 | + steps = action.get("steps") |
| 60 | + if not isinstance(steps, list) or not steps: |
| 61 | + raise StopRun("invalid_plan:missing_steps") |
| 62 | + if len(steps) < 3: |
| 63 | + raise StopRun("invalid_plan:min_steps") |
| 64 | + if len(steps) > max_plan_steps: |
| 65 | + raise StopRun("invalid_plan:max_steps") |
| 66 | + |
| 67 | + normalized: list[dict[str, Any]] = [] |
| 68 | + seen_ids: set[str] = set() |
| 69 | + |
| 70 | + for index, step in enumerate(steps, start=1): |
| 71 | + if not isinstance(step, dict): |
| 72 | + raise StopRun(f"invalid_plan:step_{index}_not_object") |
| 73 | + |
| 74 | + allowed_step_keys = {"id", "title", "tool", "args"} |
| 75 | + if set(step.keys()) - allowed_step_keys: |
| 76 | + raise StopRun(f"invalid_plan:step_{index}_extra_keys") |
| 77 | + |
| 78 | + step_id = step.get("id") |
| 79 | + if not isinstance(step_id, str) or not step_id.strip(): |
| 80 | + raise StopRun(f"invalid_plan:step_{index}_missing_id") |
| 81 | + if step_id in seen_ids: |
| 82 | + raise StopRun("invalid_plan:duplicate_step_id") |
| 83 | + seen_ids.add(step_id) |
| 84 | + |
| 85 | + title = step.get("title") |
| 86 | + if not isinstance(title, str) or not title.strip(): |
| 87 | + raise StopRun(f"invalid_plan:step_{index}_missing_title") |
| 88 | + |
| 89 | + tool = step.get("tool") |
| 90 | + if not isinstance(tool, str) or not tool.strip(): |
| 91 | + raise StopRun(f"invalid_plan:step_{index}_missing_tool") |
| 92 | + tool = tool.strip() |
| 93 | + if tool not in allowed_tools: |
| 94 | + raise StopRun(f"invalid_plan:tool_not_allowed:{tool}") |
| 95 | + |
| 96 | + args = step.get("args", {}) |
| 97 | + if args is None: |
| 98 | + args = {} |
| 99 | + if not isinstance(args, dict): |
| 100 | + raise StopRun(f"invalid_plan:step_{index}_bad_args") |
| 101 | + |
| 102 | + normalized.append( |
| 103 | + { |
| 104 | + "id": step_id.strip(), |
| 105 | + "title": title.strip(), |
| 106 | + "tool": tool, |
| 107 | + "args": args, |
| 108 | + } |
| 109 | + ) |
| 110 | + |
| 111 | + return normalized |
| 112 | + |
| 113 | + |
| 114 | +class ToolGateway: |
| 115 | + def __init__( |
| 116 | + self, |
| 117 | + *, |
| 118 | + allow: set[str], |
| 119 | + registry: dict[str, Callable[..., dict[str, Any]]], |
| 120 | + budget: Budget, |
| 121 | + ): |
| 122 | + self.allow = set(allow) |
| 123 | + self.registry = registry |
| 124 | + self.budget = budget |
| 125 | + self.tool_calls = 0 |
| 126 | + self.seen_calls: set[str] = set() |
| 127 | + |
| 128 | + def call(self, name: str, args: dict[str, Any]) -> dict[str, Any]: |
| 129 | + self.tool_calls += 1 |
| 130 | + if self.tool_calls > self.budget.max_tool_calls: |
| 131 | + raise StopRun("max_tool_calls") |
| 132 | + |
| 133 | + if name not in self.allow: |
| 134 | + raise StopRun(f"tool_denied:{name}") |
| 135 | + |
| 136 | + tool = self.registry.get(name) |
| 137 | + if tool is None: |
| 138 | + raise StopRun(f"tool_missing:{name}") |
| 139 | + |
| 140 | + signature = f"{name}:{args_hash(args)}" |
| 141 | + if signature in self.seen_calls: |
| 142 | + raise StopRun("loop_detected") |
| 143 | + self.seen_calls.add(signature) |
| 144 | + |
| 145 | + try: |
| 146 | + return tool(**args) |
| 147 | + except TypeError as exc: |
| 148 | + raise StopRun(f"tool_bad_args:{name}") from exc |
| 149 | + except Exception as exc: |
| 150 | + raise StopRun(f"tool_error:{name}") from exc |
0 commit comments