edit_approval.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """Pre-execution ACP edit approval helpers.
  2. Intentionally isolated from the generic tool registry: ACP binds an edit
  3. approval requester in a ContextVar for the duration of one ACP agent run; CLI,
  4. gateway, and other sessions leave it unset and therefore bypass this guard.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import json
  9. import logging
  10. import re
  11. import tempfile
  12. from contextvars import ContextVar, Token
  13. from dataclasses import dataclass
  14. from itertools import count
  15. from pathlib import Path
  16. from typing import Any, Callable
  17. logger = logging.getLogger(__name__)
  18. @dataclass(frozen=True)
  19. class EditProposal:
  20. """A proposed single-file edit that can be shown to an ACP client."""
  21. tool_name: str
  22. path: str
  23. old_text: str | None
  24. new_text: str
  25. arguments: dict[str, Any]
  26. # Every file the edit will actually touch. ``path`` may be a comma-joined
  27. # display string for multi-file V4A patches; ``paths`` is the authoritative
  28. # set for auto-approve checks. Empty means "``path`` alone".
  29. paths: tuple[str, ...] = ()
  30. EditApprovalRequester = Callable[[EditProposal], bool]
  31. _EDIT_APPROVAL_REQUESTER: ContextVar[EditApprovalRequester | None] = ContextVar("ACP_EDIT_APPROVAL_REQUESTER", default=None)
  32. _PERMISSION_REQUEST_IDS = count(1)
  33. SENSITIVE_AUTO_APPROVE_NAMES = {".env", ".env.local", ".env.production", "id_rsa", "id_ed25519"}
  34. AUTO_APPROVE_ASK = "ask"
  35. AUTO_APPROVE_WORKSPACE = "workspace_session"
  36. AUTO_APPROVE_SESSION = "session"
  37. _V4A_FILE_RE = re.compile(r'^\*\*\*\s+(?:Update|Add|Delete)\s+File:\s*(.+)$', re.MULTILINE)
  38. _V4A_MOVE_RE = re.compile(r'^\*\*\*\s+Move\s+File:\s*(.+?)\s*->\s*(.+)$', re.MULTILINE)
  39. def set_edit_approval_requester(requester: EditApprovalRequester | None) -> Token:
  40. """Bind an ACP edit approval requester for the current context."""
  41. return _EDIT_APPROVAL_REQUESTER.set(requester)
  42. def reset_edit_approval_requester(token: Token) -> None:
  43. """Restore a previous edit approval requester binding."""
  44. _EDIT_APPROVAL_REQUESTER.reset(token)
  45. def _read_text_if_exists(path: str) -> str | None:
  46. p = Path(path).expanduser()
  47. if p.is_file():
  48. return p.read_text(encoding="utf-8-sig", errors="replace")
  49. if p.exists():
  50. raise OSError(f"Cannot edit non-file path: {path}")
  51. return None
  52. def _required_path(arguments: dict[str, Any]) -> str:
  53. path = str(arguments.get("path") or "")
  54. if not path:
  55. raise ValueError("path required")
  56. from tools.file_tools_paths import _resolve_path_for_task
  57. return str(_resolve_path_for_task(path))
  58. def _proposal_for_write_file(arguments: dict[str, Any]) -> EditProposal:
  59. path = _required_path(arguments)
  60. content = arguments.get("content")
  61. if content is None:
  62. raise ValueError("content required")
  63. return EditProposal("write_file", path, _read_text_if_exists(path), str(content), dict(arguments))
  64. def _proposal_for_patch_replace(arguments: dict[str, Any]) -> EditProposal:
  65. path = _required_path(arguments)
  66. old_string, new_string = arguments.get("old_string"), arguments.get("new_string")
  67. if old_string is None or new_string is None:
  68. raise ValueError("old_string and new_string required")
  69. old_text = _read_text_if_exists(path)
  70. if old_text is None:
  71. raise ValueError(f"Failed to read file: {path}")
  72. from tools.fuzzy_match import fuzzy_find_and_replace
  73. new_text, match_count, _strategy, error = fuzzy_find_and_replace(
  74. old_text, str(old_string), str(new_string), bool(arguments.get("replace_all", False)))
  75. if error or match_count == 0:
  76. raise ValueError(error or f"Could not find match for old_string in {path}")
  77. return EditProposal("patch", path, old_text, new_text, dict(arguments))
  78. def _extract_v4a_patch_paths(patch_body: str) -> list[str]:
  79. paths = [m.group(1).strip() for m in _V4A_FILE_RE.finditer(patch_body)]
  80. for match in _V4A_MOVE_RE.finditer(patch_body):
  81. paths.extend(match.group(i).strip() for i in (1, 2))
  82. return [p for p in paths if p]
  83. def _proposal_for_patch_v4a(arguments: dict[str, Any]) -> EditProposal:
  84. patch_body = arguments.get("patch")
  85. if not isinstance(patch_body, str) or not patch_body:
  86. raise ValueError("patch content required")
  87. paths = [_required_path({'path': path}) for path in _extract_v4a_patch_paths(patch_body)]
  88. if not paths:
  89. raise ValueError("no file paths found in V4A patch")
  90. single = len(paths) == 1
  91. # ACP only supports a single diff payload: surface the exact V4A patch as new_text so
  92. # patch-mode calls are permissioned and denied patches cannot mutate.
  93. return EditProposal(
  94. "patch", paths[0] if single else ", ".join(paths),
  95. _read_text_if_exists(paths[0]) if single else None, patch_body, dict(arguments),
  96. tuple(paths),
  97. )
  98. # (tool_name, patch mode or None) -> proposal builder.
  99. _PROPOSAL_BUILDERS = {
  100. ("write_file", None): _proposal_for_write_file, ("patch", "replace"): _proposal_for_patch_replace,
  101. ("patch", "patch"): _proposal_for_patch_v4a,
  102. }
  103. def build_edit_proposal(tool_name: str, arguments: dict[str, Any]) -> EditProposal | None:
  104. """Return an edit proposal for supported file mutation calls."""
  105. mode = arguments.get("mode", "replace") if tool_name == "patch" else None
  106. builder = _PROPOSAL_BUILDERS.get((tool_name, mode))
  107. return builder(arguments) if builder else None
  108. def _is_sensitive_auto_approve_path(path: str) -> bool:
  109. lowered = {part.lower() for part in Path(path).expanduser().parts}
  110. return bool(lowered & {".git", ".ssh"}) or Path(path).name.lower() in SENSITIVE_AUTO_APPROVE_NAMES
  111. def should_auto_approve_edit(proposal: EditProposal, policy: str, cwd: str | None = None) -> bool:
  112. """Return whether an ACP edit proposal may bypass the prompt for this session.
  113. Session-scoped and conservative: sensitive paths still ask under autonomous policies."""
  114. policy = str(policy or AUTO_APPROVE_ASK).strip()
  115. # Multi-file V4A proposals join paths into one display string; the checks
  116. # must run per real target or a sensitive/escaped file hides in the join.
  117. paths = proposal.paths or (proposal.path,)
  118. if policy == AUTO_APPROVE_ASK or any(_is_sensitive_auto_approve_path(p) for p in paths):
  119. return False
  120. resolved = [Path(p).expanduser().resolve(strict=False) for p in paths]
  121. if policy == AUTO_APPROVE_SESSION:
  122. return True
  123. if policy == AUTO_APPROVE_WORKSPACE:
  124. # tempfile.gettempdir() is the real temp root on every platform
  125. # (``/private/tmp`` on macOS since resolve() follows the symlink).
  126. tmp = Path(tempfile.gettempdir()).resolve(strict=False)
  127. ws = Path(cwd).expanduser().resolve(strict=False) if cwd else None
  128. return all(
  129. path.is_relative_to(tmp) or (ws is not None and path.is_relative_to(ws))
  130. for path in resolved)
  131. return False
  132. def _denied(message: str) -> str:
  133. return json.dumps({"error": message}, ensure_ascii=False)
  134. def maybe_require_edit_approval(tool_name: str, arguments: dict[str, Any]) -> str | None:
  135. """Run ACP edit approval if bound.
  136. Returns a JSON tool-error string when the edit must be blocked, otherwise
  137. ``None`` so dispatch can continue. Requester exceptions deny by default."""
  138. requester = _EDIT_APPROVAL_REQUESTER.get()
  139. if requester is None:
  140. return None
  141. try:
  142. proposal = build_edit_proposal(tool_name, arguments)
  143. except Exception as exc:
  144. logger.warning("Could not build ACP edit approval proposal for %s: %s", tool_name, exc)
  145. return _denied(f"Edit approval denied: could not prepare diff ({exc})")
  146. if proposal is None:
  147. return None
  148. try:
  149. approved = bool(requester(proposal))
  150. except Exception as exc:
  151. logger.warning("ACP edit approval requester failed: %s", exc)
  152. approved = False
  153. return None if approved else _denied("Edit approval denied by ACP client; file was not modified.")
  154. def build_acp_edit_tool_call(proposal: EditProposal):
  155. """Build the ToolCallUpdate payload for ACP request_permission."""
  156. import acp
  157. from agent.redact import redact_approval_display
  158. # The title is display text; the diff keeps the raw path the client opens.
  159. return acp.update_tool_call(
  160. f"edit-approval-{next(_PERMISSION_REQUEST_IDS)}", title=f"Approve edit: {redact_approval_display(proposal.path)}",
  161. kind="edit",
  162. status="pending",
  163. content=[acp.tool_diff_content(path=proposal.path, old_text=proposal.old_text, new_text=proposal.new_text)],
  164. raw_input={"tool": proposal.tool_name, "arguments": proposal.arguments},
  165. )
  166. def make_acp_edit_approval_requester(
  167. request_permission_fn: Callable, loop: asyncio.AbstractEventLoop, session_id: str,
  168. timeout: float | None = None, auto_approve_getter: Callable[[], tuple[str, str | None]] | None = None,
  169. send_update: Callable[[object], None] | None = None,
  170. ) -> EditApprovalRequester:
  171. """Return a sync requester that bridges edit proposals to ACP permissions."""
  172. def _requester(proposal: EditProposal) -> bool:
  173. from acp.schema import PermissionOption
  174. from acp_adapter.permissions import await_permission, resolve_permission_timeout
  175. if auto_approve_getter is not None:
  176. try:
  177. policy, cwd = auto_approve_getter()
  178. if should_auto_approve_edit(proposal, policy, cwd):
  179. logger.info("Auto-approved ACP edit under policy %s: %s", policy, proposal.path)
  180. return True
  181. except Exception:
  182. logger.debug("ACP edit auto-approval policy check failed", exc_info=True)
  183. response, _timed_out = await_permission(
  184. request_permission_fn, loop, session_id, tool_call=build_acp_edit_tool_call(proposal),
  185. options=[PermissionOption(option_id="allow_once", kind="allow_once", name="Allow edit"),
  186. PermissionOption(option_id="deny", kind="reject_once", name="Deny")],
  187. timeout=resolve_permission_timeout(timeout), what="Edit approval request", send_update=send_update,
  188. )
  189. outcome = getattr(response, "outcome", None)
  190. return getattr(outcome, "outcome", None) == "selected" and getattr(outcome, "option_id", None) == "allow_once"
  191. return _requester