#!/usr/bin/env python3
"""Agents 2 · sdk_permissions: canUseTool and PreToolUse hooks, in the documented evaluation order.

When Claude asks to run a tool, the SDK decides in a fixed order: (1) hooks, (2) deny rules, (3) ask
rules, (4) the permission mode, (5) allow rules, (6) your `can_use_tool` callback. The first step that
resolves the call wins, so where you put a check decides whether it ever runs. This lab writes a real
PreToolUse hook callback and a real `can_use_tool` callback, unit-tests them directly, then runs them
through a simulator of that order over a matrix of tool calls, modes and rules.

What you'll learn:
    * Hooks run first and a hook deny holds in every mode, bypassPermissions included. A hook `allow`
      doesn't skip the deny and ask rules.
    * Deny rules beat everything after them; a bare-name deny (`Bash`) removes the tool from context.
    * Ask rules and tools that need user interaction fall through to can_use_tool, even in
      bypassPermissions; dontAsk denies them instead.
    * "Auto-approved tools never reach canUseTool": an allow rule, bypassPermissions or acceptEdits
      resolves the call before your callback. `allowed_tools` doesn't constrain bypassPermissions.
    * Plan mode sends file edits to can_use_tool even when an allow rule or a hook says allow.
    * dontAsk never calls can_use_tool: anything not approved earlier is denied.

How to run (from labs/):
    python3 agents-2/sdk_permissions.py          # callback unit tests + the evaluation-order matrix (offline)
    python3 agents-2/sdk_permissions.py --case 7 # explain one row step by step
    python3 agents-2/sdk_permissions.py --real --model haiku --max-budget-usd 0.05
        # costs money: Python 3.10+ and claude-agent-sdk; the same callbacks gate a real run in a temp copy

What to observe:
    * Which step resolved each row, and the "callback called?" column: can_use_tool runs only in rows where
      nothing earlier decided.
    * Row 2 vs row 8: bypassPermissions approves Bash unless a deny rule or the hook stops it.
    * Row 5: plan mode routes an allowed Edit to can_use_tool, which refuses it.
    * Row 12: acceptEdits doesn't approve MCP tools, so the call reaches the callback.

Exercises:
    1. Move the `.env` check from the hook into can_use_tool and rerun the matrix. Which rows now let the
       write through, and why? (Hint: allow rules and modes resolve calls before the callback.)
    2. Make the hook return `permissionDecision: "ask"` for `git push` and trace where the call goes.
    3. Add a case for AskUserQuestion with an allow rule in dontAsk mode.
    4. The simulator's rule matcher is a subset (exact names, `Tool(prefix *)`, `Read(./path)`,
       `mcp__server__*`). Read the permissions page and list two rule forms it doesn't model.

The simulator is a teaching model of the documented order, not Claude Code's implementation. It omits
critical-path removals, protected paths, network paths, mods and auto mode's classifier.

Docs (fetched 2026-10-20):
    https://code.claude.com/docs/en/agent-sdk/permissions   (the six steps, modes, allow/deny rule forms, warnings)
    https://code.claude.com/docs/en/agent-sdk/user-input    (can_use_tool signature, PermissionResultAllow/Deny, updated_input)
    https://code.claude.com/docs/en/agent-sdk/hooks         (HookMatcher, callback signature, permissionDecision, precedence)
    https://code.claude.com/docs/en/agent-sdk/python        (ToolPermissionContext fields, HookMatcher dataclass)
"""
from __future__ import annotations

import sys

sys.dont_write_bytecode = True  # before any other import: keep labs/ free of __pycache__

import argparse
import asyncio
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

import _sdk_common as lab  # noqa: E402
from common import hooks as hk  # noqa: E402
from common.pretty import c, header, kv, step, table  # noqa: E402

FILE_WRITERS = ("Edit", "Write", "NotebookEdit")
READ_ONLY_BUILTINS = ("Read", "Grep", "Glob")


# ----------------------------------------------------------------------------
# The lab's two callbacks (the code you'd ship)
# ----------------------------------------------------------------------------
async def guard_hook(input_data: Dict[str, Any], tool_use_id: Optional[str], context: Any) -> Dict[str, Any]:
    """PreToolUse hook callback: deny destructive shell commands and writes to secrets, in every mode.

    Returns {} to let the call continue to the next step, or a deny inside hookSpecificOutput
    (agent-sdk/hooks: "Return {} to allow the operation without changes").
    """
    tool = input_data.get("tool_name", "")
    tin = input_data.get("tool_input") or {}
    reason = None
    if tool == "Bash":
        cmd = str(tin.get("command", ""))
        if re.search(r"(^|[;&|]\s*)rm\s+-[a-zA-Z]*r", cmd):
            reason = "recursive rm is blocked by the lab guard hook"
        elif re.search(r"\bgit\s+push\b", cmd):
            reason = "pushing is blocked in this agent; ask a human to push"
    elif tool in FILE_WRITERS:
        path = str(tin.get("file_path", ""))
        if re.search(r"(^|/)\.env(\.|$)|(^|/)secrets/", path):
            reason = f"{Path(path).name} looks like a secrets file; writes are blocked"
    if reason:
        return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
                                       "permissionDecisionReason": reason}}
    return {}


def make_can_use_tool(sdk: Any):
    """The can_use_tool callback: allow the test suite (forcing -q), refuse other shell and every edit."""

    async def can_use_tool(tool_name: str, input_data: Dict[str, Any], context: Any) -> Any:
        if tool_name == "Bash":
            cmd = str(input_data.get("command", "")).strip()
            if re.fullmatch(r"python3 -m unittest( -q)?( [\w./-]+)*", cmd):
                quiet = cmd if " -q" in cmd else cmd.replace("python3 -m unittest", "python3 -m unittest -q", 1)
                return sdk.PermissionResultAllow(updated_input={**input_data, "command": quiet})
            return sdk.PermissionResultDeny(message=f"only `python3 -m unittest` may run here, not {cmd[:40]!r}")
        if tool_name in FILE_WRITERS:
            return sdk.PermissionResultDeny(message="this agent proposes changes; it doesn't edit files")
        if tool_name.startswith("mcp__"):
            return sdk.PermissionResultAllow()
        return sdk.PermissionResultDeny(message=f"{tool_name} isn't approved for this agent")

    return can_use_tool


# ----------------------------------------------------------------------------
# A teaching simulator of the documented order (agent-sdk/permissions, "How permissions are evaluated")
# ----------------------------------------------------------------------------
@dataclass
class Config:
    mode: str
    allowed_tools: List[str] = field(default_factory=list)   # allow rules (allowed_tools / settings allow)
    disallowed_tools: List[str] = field(default_factory=list)  # deny rules (disallowed_tools / settings deny)
    ask_rules: List[str] = field(default_factory=list)       # settings ask rules
    use_hook: bool = True


@dataclass
class Case:
    title: str
    tool: str
    tool_input: Dict[str, Any]
    cfg: Config
    needs_user: bool = False  # AskUserQuestion / MCP tools with anthropic/requiresUserInteraction


def rule_matches(rule: str, tool: str, tool_input: Dict[str, Any]) -> bool:
    """A subset of the permissions page's rule syntax: `Tool`, `Tool(prefix *)`, `Tool(exact)`,
    `Read(./path)` / `Edit(./path)` (Edit rules govern every file writer), `mcp__server__*`."""
    if rule.startswith("mcp__") and rule.endswith("__*"):
        return tool.startswith(rule[:-1])  # allow globs need the literal mcp__<server>__ prefix
    m = re.fullmatch(r"([A-Za-z_][\w-]*)(?:\((.*)\))?", rule)
    if not m:
        return False
    name, spec = m.group(1), m.group(2)
    governs = (tool in FILE_WRITERS and name == "Edit") or name == tool
    if not governs:
        return False
    if spec is None:
        return True
    target = str(tool_input.get("command") if tool == "Bash" else tool_input.get("file_path", ""))
    if tool != "Bash":
        spec = spec[2:] if spec.startswith("./") else spec
        return target == spec or target.endswith("/" + spec)
    rx = "^" + ".*".join(re.escape(p) for p in spec.split("*")) + "$"
    return bool(re.match(rx, target)) or (spec.endswith(" *") and target == spec[:-2])


def inside_workdir(path: str) -> bool:
    """The simulator's model of "within the working directory" (permissions page): a relative path that doesn't
    climb out with `..`. Every absolute or `~` path counts as outside, since the simulator has no real cwd.
    Network paths, which get their own check, aren't modeled."""
    if path.startswith(("/", "~", "\\")) or re.match(r"^[A-Za-z]:", path):
        return False
    depth = 0
    for part in Path(path).parts:
        depth += -1 if part == ".." else (0 if part == "." else 1)
        if depth < 0:
            return False
    return True


def bare(rules: Sequence[str], tool: str) -> bool:
    return any(r == tool for r in rules)


async def evaluate(sdk: Any, case: Case, can_use_tool: Any) -> Dict[str, Any]:
    """Walk the six steps for one call. Returns {step, outcome, why, callback_called, trail}."""
    trail: List[str] = []
    cfg, tool, tin = case.cfg, case.tool, case.tool_input
    out = {"callback_called": False, "updated_input": None}

    def done(step_name: str, outcome: str, why: str) -> Dict[str, Any]:
        trail.append(f"{step_name}: {outcome} ({why})")
        return dict(out, step=step_name, outcome=outcome, why=why, trail=trail)

    if bare(cfg.disallowed_tools, tool):
        return done("0 availability", "not offered", f"bare deny rule {tool!r} removes the tool from Claude's context")

    hook_allowed = False
    if cfg.use_hook:  # 1. hooks
        payload = hk.pre_tool_use(tool, tin)
        res = await guard_hook(payload, payload.get("tool_use_id"), {"signal": None})
        decision = (res.get("hookSpecificOutput") or {}).get("permissionDecision")
        if decision == "deny":
            return done("1 hooks", "DENY", res["hookSpecificOutput"]["permissionDecisionReason"])
        hook_allowed = decision == "allow"
        trail.append("1 hooks: pass" + (" (allow: deny and ask rules still apply)" if hook_allowed else ""))
    deny = next((r for r in cfg.disallowed_tools if rule_matches(r, tool, tin)), None)  # 2. deny rules
    if deny:
        return done("2 deny rules", "DENY", f"{deny} matches, which holds even in {cfg.mode}")
    trail.append("2 deny rules: no match")

    ask = next((r for r in cfg.ask_rules if rule_matches(r, tool, tin)), None)  # 3. ask rules
    to_callback = bool(ask) or case.needs_user
    if to_callback and cfg.mode == "dontAsk":
        return done("3 ask rules", "DENY", f"{ask or 'needs user interaction'}; dontAsk never prompts, so it's denied even with an allow rule")
    if to_callback:
        trail.append(f"3 ask rules: {ask or 'requires user interaction'} -> straight to can_use_tool")
    else:
        trail.append("3 ask rules: no match")
        if cfg.mode == "bypassPermissions":  # 4. permission mode
            return done("4 mode", "ALLOW", "bypassPermissions approves everything that reaches this step")
        if cfg.mode == "acceptEdits" and tool in FILE_WRITERS:
            return done("4 mode", "ALLOW", "acceptEdits approves file edits inside the working directory")
        plan_edit = cfg.mode == "plan" and tool in FILE_WRITERS
        if plan_edit:
            trail.append("4 mode: plan sends file edits to can_use_tool regardless of allow rules and hooks")
        else:
            trail.append(f"4 mode: {cfg.mode} falls through")
            allow = next((r for r in cfg.allowed_tools if rule_matches(r, tool, tin)), None)  # 5. allow rules
            if allow:
                return done("5 allow rules", "ALLOW", f"{allow} matches; can_use_tool is never consulted")
            if hook_allowed:
                return done("5 allow rules", "ALLOW", "the hook's allow approves it once deny/ask rules passed")
            if tool in READ_ONLY_BUILTINS:
                target = str(tin.get("file_path", tin.get("path", "")) or ".")
                if inside_workdir(target):
                    return done("5 allow rules", "ALLOW", "a read inside the working directories needs no approval")
                trail.append(f"5 allow rules: no match, and {target} is outside the working directories, so the read needs approval")
            else:
                trail.append("5 allow rules: no match")
    if cfg.mode == "dontAsk":  # 6. can_use_tool
        return done("6 can_use_tool", "DENY", "dontAsk denies instead of prompting; the callback isn't called")
    out["callback_called"] = True
    # decision_reason carries a PreToolUse hook's "ask" reason (Python reference); this lab's hook never asks.
    ctx = sdk.ToolPermissionContext(tool_use_id="toolu_lab_perm_0001")
    res = await can_use_tool(tool, tin, ctx)
    if isinstance(res, sdk.PermissionResultAllow):
        out["updated_input"] = res.updated_input
        extra = f"; updated_input command={res.updated_input.get('command')!r}" if res.updated_input else ""
        return done("6 can_use_tool", "ALLOW", "the callback allowed it" + extra)
    return done("6 can_use_tool", "DENY", f"the callback denied it: {res.message}")


CASES: List[Case] = [
    Case("read a source file", "Read", {"file_path": "tinyapp/cart.py"}, Config("dontAsk", ["Read", "Grep", "Glob"])),
    Case("rm with a deny rule, in bypass", "Bash", {"command": "rm -rf build"},
         Config("bypassPermissions", disallowed_tools=["Bash(rm *)"], use_hook=False)),
    Case("git push, hook on, in bypass", "Bash", {"command": "git push origin main"}, Config("bypassPermissions")),
    Case("write .env, acceptEdits", "Write", {"file_path": ".env", "content": "PLACEHOLDER=1"}, Config("acceptEdits")),
    Case("edit in plan mode with an Edit allow rule", "Edit", {"file_path": "tinyapp/cart.py", "old_string": "a", "new_string": "b"},
         Config("plan", ["Edit"])),
    Case("run the tests, default mode, no allow rule", "Bash", {"command": "python3 -m unittest"}, Config("default", ["Read"])),
    Case("run the tests, dontAsk, no allow rule", "Bash", {"command": "python3 -m unittest"}, Config("dontAsk", ["Read"])),
    Case("Bash in bypass, allowed_tools=['Read']", "Bash", {"command": "curl https://example.com"},
         Config("bypassPermissions", ["Read"], use_hook=False)),
    Case("ask rule in bypass", "Bash", {"command": "git commit -m wip"},
         Config("bypassPermissions", ask_rules=["Bash(git commit *)"])),
    Case("Read .env with a deny rule", "Read", {"file_path": ".env"}, Config("default", ["Read"], ["Read(./.env)"])),
    Case("bare Bash deny", "Bash", {"command": "ls"}, Config("default", disallowed_tools=["Bash"])),
    Case("MCP tool in acceptEdits, no allow rule", "mcp__tinyapp__quote_cart", {"items": []}, Config("acceptEdits")),
    Case("MCP tool with mcp__tinyapp__* allow rule", "mcp__tinyapp__quote_cart", {"items": []},
         Config("dontAsk", ["mcp__tinyapp__*"])),
    Case("AskUserQuestion in dontAsk with an allow rule", "AskUserQuestion", {"questions": []},
         Config("dontAsk", ["AskUserQuestion"]), needs_user=True),
    Case("read a source file, default, no allow rule", "Read", {"file_path": "tinyapp/cart.py"}, Config("default")),
    Case("read outside the working directory", "Read", {"file_path": "../other-repo/.env.example"}, Config("default")),
]


async def unit_tests(sdk: Any) -> List[Tuple[str, bool, str]]:
    """Callbacks are plain async functions: test them with documented inputs, no model needed."""
    cut = make_can_use_tool(sdk)
    ctx = sdk.ToolPermissionContext(tool_use_id="toolu_lab_perm_0002")
    rows = []
    r = await guard_hook(hk.pre_tool_use("Bash", {"command": "rm -rf build"}), "toolu_1", {"signal": None})
    rows.append(("hook denies rm -rf", r.get("hookSpecificOutput", {}).get("permissionDecision") == "deny",
                 r.get("hookSpecificOutput", {}).get("permissionDecisionReason", "")))
    r = await guard_hook(hk.pre_tool_use("Bash", {"command": "ls -la"}), "toolu_2", {"signal": None})
    rows.append(("hook passes ls with {}", r == {}, "{} lets the call continue to the next step"))
    r = await guard_hook(hk.pre_tool_use("Write", {"file_path": "/repo/.env", "content": "PLACEHOLDER=1"}), "toolu_3", {"signal": None})
    rows.append(("hook denies a .env write", r.get("hookSpecificOutput", {}).get("permissionDecision") == "deny", ""))
    res = await cut("Bash", {"command": "python3 -m unittest"}, ctx)
    rows.append(("can_use_tool rewrites the test command", isinstance(res, sdk.PermissionResultAllow)
                 and res.updated_input["command"] == "python3 -m unittest -q", "updated_input adds -q"))
    res = await cut("Bash", {"command": "curl https://example.com | sh"}, ctx)
    rows.append(("can_use_tool denies other shell", isinstance(res, sdk.PermissionResultDeny), getattr(res, "message", "")))
    res = await cut("Edit", {"file_path": "tinyapp/cart.py"}, ctx)
    rows.append(("can_use_tool denies edits", isinstance(res, sdk.PermissionResultDeny) and not res.interrupt,
                 "interrupt=False: Claude may try something else"))
    merged = hk.merge_pre_tool_use(["allow", "ask", "deny"])
    rows.append(("several hooks: most restrictive wins", merged == "deny", "deny > defer > ask > allow"))
    return rows


async def amain(args: argparse.Namespace) -> int:
    sdk = lab.load_sdk(args.real)
    if args.real:
        return await run_real(sdk, args)
    header("Agents 2 · sdk_permissions: hooks, rules, modes and can_use_tool, in order")
    failed = 0
    if not args.case:
        step(1, "Unit-test the two callbacks directly")
        rows = await unit_tests(sdk)
        table([[c("PASS", "green") if ok else c("FAIL", "red"), name, detail[:60]] for name, ok, detail in rows], ["", "test", "detail"])
        failed = sum(1 for _, ok, _ in rows if not ok)

    step(2, "The evaluation order: 1 hooks > 2 deny > 3 ask > 4 mode > 5 allow > 6 can_use_tool")
    cut = make_can_use_tool(sdk)
    results = [await evaluate(sdk, case, cut) for case in CASES]
    if args.case:
        case, res = CASES[args.case - 1], results[args.case - 1]
        kv("call", f"{case.tool} {case.tool_input}")
        kv("config", f"mode={case.cfg.mode} allow={case.cfg.allowed_tools} deny={case.cfg.disallowed_tools} "
                     f"ask={case.cfg.ask_rules} hook={'on' if case.cfg.use_hook else 'off'}")
        for line in res["trail"]:
            print("   " + line)
        return 0
    table([[i, case.title, case.cfg.mode, res["step"], c(res["outcome"], "green" if res["outcome"] == "ALLOW" else "red"),
            "yes" if res["callback_called"] else "no", res["why"][:58]]
           for i, (case, res) in enumerate(zip(CASES, results), 1)],
          ["#", "call", "mode", "resolved at", "outcome", "callback?", "why"])
    print(c("\nToy model of the documented order: no critical paths, protected paths, network paths, mods or auto mode.", "gray"))

    step(3, "Wiring it into a real session")
    print("""  options = ClaudeAgentOptions(
      tools=["Read", "Grep", "Glob", "Bash"],          # availability
      allowed_tools=["Read", "Grep", "Glob"],          # step 5: auto-approved, never reach can_use_tool
      permission_mode="default",                        # step 4 falls through, so step 6 runs
      hooks={"PreToolUse": [HookMatcher(matcher="Bash|Write|Edit", hooks=[guard_hook])]},  # step 1
      can_use_tool=can_use_tool,                        # step 6
      max_turns=4, max_budget_usd=0.05)
  async for msg in query(prompt=prompt_stream(), options=options): ...   # prompt as an async generator""")
    return 1 if failed else 0


async def run_real(sdk: Any, args: argparse.Namespace) -> int:
    """The same callbacks gate a real session. Bash is available, but only read-only built-in commands run
    unprompted; the hook blocks rm and pushes, and can_use_tool allows only the test suite."""
    tools = ["Read", "Grep", "Glob", "Bash"]
    allowed = ["Read", "Grep", "Glob"]
    warnings = lab.check_real(args, tools=tools, allowed_tools=allowed, permission_mode="default", allow_writes=True)
    cwd = lab.run_dir(args)
    warnings.append("Bash is available so the callbacks have something to gate; it runs in a temp copy, and the hook "
                    "plus can_use_tool refuse everything except read-only commands and `python3 -m unittest`")
    lab.cost_notice(args, cwd, warnings)
    header("Agents 2 · sdk_permissions (real SDK)")
    calls: List[str] = []
    cut = make_can_use_tool(sdk)

    async def logged_cut(tool_name: str, input_data: Dict[str, Any], context: Any) -> Any:
        res = await cut(tool_name, input_data, context)
        calls.append(f"can_use_tool({tool_name}, {str(input_data.get('command', input_data.get('file_path', '')))[:40]!r}) -> {res.behavior}")
        return res

    async def prompt_stream():
        # can_use_tool needs a streaming prompt in Python (agent-sdk/user-input); the hook keeps the stream open.
        yield {"type": "user", "message": {"role": "user", "content": (
            "In this repo: 1) count the lines in tinyapp/*.py with wc -l, 2) run the tests with python3 -m unittest, "
            "3) try `rm -rf build` and tell me what happened. Don't edit files.")}}

    options = sdk.ClaudeAgentOptions(tools=tools, allowed_tools=allowed, permission_mode="default",
                                     hooks={"PreToolUse": [sdk.HookMatcher(matcher="Bash|Write|Edit", hooks=[guard_hook])]},
                                     can_use_tool=logged_cut,
                                     **lab.base_options(args, cwd, uses_hook_callbacks=True))
    msgs, err = await lab.collect(sdk, prompt_stream(), options)
    print()
    for line in calls:
        kv("callback", line)
    res = lab.result_of(sdk, msgs)
    if res is not None and res.permission_denials:
        kv("permission_denials", [d.get("tool_name") if isinstance(d, dict) else d for d in res.permission_denials])
    if err is not None:
        kv("query() raised", f"{type(err).__name__}: {str(err).splitlines()[0]}")
    if args.save:
        kv("saved", str(lab.save_messages("sdk_permissions", msgs)))
    lab.explain_failure(res, args)
    return 0 if res is not None and not res.is_error else 1


def main(argv: Optional[Sequence[str]] = None) -> int:
    ap = argparse.ArgumentParser(description="can_use_tool and hooks in the Agent SDK's permission order.")
    ap.add_argument("--case", type=int, help="explain one matrix row step by step")
    lab.add_sdk_args(ap, max_turns=4, max_budget_usd=0.05)
    args = ap.parse_args(argv)
    if args.case is not None and not 1 <= args.case <= len(CASES):
        print(f"error: --case must be 1..{len(CASES)}", file=sys.stderr)
        return 2
    return asyncio.run(amain(args))


if __name__ == "__main__":
    raise SystemExit(main())
