import dataclasses import typing from failure import Failure from claude_code.session import subagent_transcript FILE_TOOLS = ("Edit", "MultiEdit", "Write") @dataclasses.dataclass(frozen=True) class Call: tool: str given: dict[str, typing.Any] cwd: str # The subagent the call comes from, such as prose-reviewer; empty for the session's own agent. agent: str = "" # The transcript of the agent that makes the call: a subagent's own, not its session's. transcript: str = "" def parsed_call(hook_input: object) -> Call | Failure: if not isinstance(hook_input, dict): return Failure("the hook input is no object") tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd") if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str): return Failure("the hook input has no string tool_name and cwd and object tool_input") agent, agent_id, transcript = hook_input.get("agent_type"), hook_input.get("agent_id"), hook_input.get("transcript_path") transcript = transcript if isinstance(transcript, str) else "" if isinstance(agent_id, str) and transcript: # Inside a subagent, transcript_path still names the session's transcript. transcript = subagent_transcript(transcript, agent_id) return Call(tool, given, cwd, agent if isinstance(agent, str) else "", transcript) def text(given: dict[str, typing.Any], key: str) -> str: value = given.get(key) return value if isinstance(value, str) else "" def applied(call: Call, before: str) -> tuple[str, str]: """The text a file call writes, and the whole file it leaves.""" if call.tool == "Write": content = text(call.given, "content") return content, content edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)] after = before for edit in edits: old, new = text(edit, "old_string"), text(edit, "new_string") after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1) return "\n".join(text(edit, "new_string") for edit in edits), after