Skip to content

Commit 0292398

Browse files
HenkDzteknium1
authored andcommitted
fix(acp): use modes for edit auto-approval
1 parent f70e0b8 commit 0292398

5 files changed

Lines changed: 166 additions & 88 deletions

File tree

‎acp_adapter/events.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ def make_tool_progress_cb(
117117
loop: asyncio.AbstractEventLoop,
118118
tool_call_ids: Dict[str, Deque[str]],
119119
tool_call_meta: Dict[str, Dict[str, Any]],
120+
edit_approval_policy_getter: Callable[[], tuple[str, str | None]] | None = None,
120121
) -> Callable:
121122
"""Create a ``tool_progress_callback`` for AIAgent.
122123
@@ -162,7 +163,20 @@ def _tool_progress(event_type: str, name: str = None, preview: str = None, args:
162163
logger.debug("Failed to capture ACP edit snapshot for %s", name, exc_info=True)
163164
tool_call_meta[tc_id] = {"args": args, "snapshot": snapshot}
164165

165-
update = build_tool_start(tc_id, name, args)
166+
edit_diff = None
167+
if name in {"write_file", "patch"} and edit_approval_policy_getter is not None:
168+
try:
169+
from acp_adapter.edit_approval import build_edit_proposal, should_auto_approve_edit
170+
171+
proposal = build_edit_proposal(name, args)
172+
if proposal is not None:
173+
policy, cwd = edit_approval_policy_getter()
174+
if should_auto_approve_edit(proposal, policy, cwd):
175+
edit_diff = proposal
176+
except Exception:
177+
logger.debug("Failed to prepare auto-approved ACP edit diff for %s", name, exc_info=True)
178+
179+
update = build_tool_start(tc_id, name, args, edit_diff=edit_diff)
166180
_send_update(conn, session_id, loop, update)
167181

168182
return _tool_progress

‎acp_adapter/server.py‎

Lines changed: 75 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,10 @@
4545
SetSessionModeResponse,
4646
ResourceContentBlock,
4747
SessionCapabilities,
48-
SessionConfigOptionSelect,
49-
SessionConfigSelectOption,
5048
SessionForkCapabilities,
5149
SessionListCapabilities,
50+
SessionMode,
51+
SessionModeState,
5252
SessionModelState,
5353
SessionResumeCapabilities,
5454
SessionInfo,
@@ -499,6 +499,17 @@ class HermesACPAgent(acp.Agent):
499499

500500
_EDIT_APPROVAL_POLICY_CONFIG_ID = "edit_approval_policy"
501501
_EDIT_APPROVAL_POLICY_DEFAULT = "ask"
502+
_MODE_DEFAULT = "default"
503+
_MODE_ACCEPT_EDITS = "accept_edits"
504+
_MODE_DONT_ASK = "dont_ask"
505+
_MODE_TO_EDIT_APPROVAL_POLICY = {
506+
_MODE_DEFAULT: "ask",
507+
_MODE_ACCEPT_EDITS: "workspace_session",
508+
_MODE_DONT_ASK: "session",
509+
}
510+
_EDIT_APPROVAL_POLICY_TO_MODE = {
511+
value: key for key, value in _MODE_TO_EDIT_APPROVAL_POLICY.items()
512+
}
502513

503514
def __init__(self, session_manager: SessionManager | None = None):
504515
super().__init__()
@@ -513,47 +524,43 @@ def on_connect(self, conn: acp.Client) -> None:
513524
logger.info("ACP client connected")
514525

515526

516-
def _session_config_options(self, state: SessionState) -> list[Any]:
517-
values = getattr(state, "config_options", None)
518-
if not isinstance(values, dict):
519-
values = {}
520-
current = str(values.get(self._EDIT_APPROVAL_POLICY_CONFIG_ID) or self._EDIT_APPROVAL_POLICY_DEFAULT)
521-
allowed = {"ask", "workspace_session", "session"}
522-
if current not in allowed:
523-
current = self._EDIT_APPROVAL_POLICY_DEFAULT
524-
return [
525-
SessionConfigOptionSelect(
526-
id=self._EDIT_APPROVAL_POLICY_CONFIG_ID,
527-
name="Edit approvals",
528-
description="Control ACP edit approvals for this session.",
529-
category="permissions",
530-
type="select",
531-
current_value=current,
532-
options=[
533-
SessionConfigSelectOption(
534-
value="ask",
535-
name="Ask before edits",
536-
description="Require approval for every file edit.",
537-
),
538-
SessionConfigSelectOption(
539-
value="workspace_session",
540-
name="Auto-allow workspace edits",
541-
description="Allow workspace and /tmp edits for this session; still asks for sensitive paths.",
542-
),
543-
SessionConfigSelectOption(
544-
value="session",
545-
name="Auto-allow all edits this session",
546-
description="Allow file edits for this session except sensitive paths.",
547-
),
548-
],
549-
)
550-
]
527+
def _session_modes(self, state: SessionState) -> SessionModeState:
528+
"""Return ACP session modes while preserving Zed's separate model picker.
529+
530+
Zed renders ``config_options`` in the prominent selector slot where the
531+
model picker was visible. Claude/Codex expose policy-like controls as ACP
532+
modes, which coexist with the model picker, so Hermes maps edit approval
533+
policy onto modes instead of advertising config options.
534+
"""
535+
536+
current = str(getattr(state, "mode", "") or self._MODE_DEFAULT)
537+
if current not in self._MODE_TO_EDIT_APPROVAL_POLICY:
538+
current = self._MODE_DEFAULT
539+
return SessionModeState(
540+
current_mode_id=current,
541+
available_modes=[
542+
SessionMode(
543+
id=self._MODE_DEFAULT,
544+
name="Default",
545+
description="Ask before edits.",
546+
),
547+
SessionMode(
548+
id=self._MODE_ACCEPT_EDITS,
549+
name="Accept Edits",
550+
description="Auto-allow workspace and /tmp edits; still asks for sensitive paths.",
551+
),
552+
SessionMode(
553+
id=self._MODE_DONT_ASK,
554+
name="Don't Ask",
555+
description="Auto-allow file edits for this session except sensitive paths.",
556+
),
557+
],
558+
)
551559

552560
def _edit_approval_policy_for_state(self, state: SessionState) -> tuple[str, str | None]:
553-
values = getattr(state, "config_options", None)
554-
if not isinstance(values, dict):
555-
values = {}
556-
return str(values.get(self._EDIT_APPROVAL_POLICY_CONFIG_ID) or self._EDIT_APPROVAL_POLICY_DEFAULT), state.cwd
561+
mode = str(getattr(state, "mode", "") or self._MODE_DEFAULT)
562+
policy = self._MODE_TO_EDIT_APPROVAL_POLICY.get(mode, self._EDIT_APPROVAL_POLICY_DEFAULT)
563+
return policy, state.cwd
557564

558565
@staticmethod
559566
def _encode_model_choice(provider: str | None, model: str | None) -> str:
@@ -1040,7 +1047,7 @@ async def new_session(
10401047
return NewSessionResponse(
10411048
session_id=state.session_id,
10421049
models=self._build_model_state(state),
1043-
config_options=self._session_config_options(state),
1050+
modes=self._session_modes(state),
10441051
)
10451052

10461053
async def load_session(
@@ -1084,7 +1091,7 @@ async def load_session(
10841091
self._schedule_usage_update(state)
10851092
return LoadSessionResponse(
10861093
models=self._build_model_state(state),
1087-
config_options=self._session_config_options(state),
1094+
modes=self._session_modes(state),
10881095
)
10891096

10901097
async def resume_session(
@@ -1116,7 +1123,7 @@ async def resume_session(
11161123
self._schedule_usage_update(state)
11171124
return ResumeSessionResponse(
11181125
models=self._build_model_state(state),
1119-
config_options=self._session_config_options(state),
1126+
modes=self._session_modes(state),
11201127
)
11211128

11221129
async def cancel(self, session_id: str, **kwargs: Any) -> None:
@@ -1150,7 +1157,7 @@ async def fork_session(
11501157
return ForkSessionResponse(
11511158
session_id=new_id,
11521159
models=self._build_model_state(state) if state is not None else None,
1153-
config_options=self._session_config_options(state) if state is not None else None,
1160+
modes=self._session_modes(state) if state is not None else None,
11541161
)
11551162

11561163
async def list_sessions(
@@ -1307,7 +1314,14 @@ async def prompt(
13071314
streamed_message = False
13081315

13091316
if conn:
1310-
tool_progress_cb = make_tool_progress_cb(conn, session_id, loop, tool_call_ids, tool_call_meta)
1317+
tool_progress_cb = make_tool_progress_cb(
1318+
conn,
1319+
session_id,
1320+
loop,
1321+
tool_call_ids,
1322+
tool_call_meta,
1323+
edit_approval_policy_getter=lambda: self._edit_approval_policy_for_state(state),
1324+
)
13111325
reasoning_cb = make_thinking_cb(conn, session_id, loop)
13121326
step_cb = make_step_cb(conn, session_id, loop, tool_call_ids, tool_call_meta)
13131327
message_cb = make_message_cb(conn, session_id, loop)
@@ -1849,9 +1863,12 @@ async def set_session_mode(
18491863
if state is None:
18501864
logger.warning("Session %s: mode switch requested for missing session", session_id)
18511865
return None
1852-
setattr(state, "mode", mode_id)
1866+
normalized_mode = str(mode_id or "").strip()
1867+
if normalized_mode not in self._MODE_TO_EDIT_APPROVAL_POLICY:
1868+
normalized_mode = self._MODE_DEFAULT
1869+
setattr(state, "mode", normalized_mode)
18531870
self.session_manager.save_session(session_id)
1854-
logger.info("Session %s: mode switched to %s", session_id, mode_id)
1871+
logger.info("Session %s: mode switched to %s", session_id, normalized_mode)
18551872
return SetSessionModeResponse()
18561873

18571874
async def set_config_option(
@@ -1863,11 +1880,15 @@ async def set_config_option(
18631880
logger.warning("Session %s: config update requested for missing session", session_id)
18641881
return None
18651882

1866-
options = getattr(state, "config_options", None)
1867-
if not isinstance(options, dict):
1868-
options = {}
1869-
options[str(config_id)] = value
1870-
setattr(state, "config_options", options)
1883+
if str(config_id) == self._EDIT_APPROVAL_POLICY_CONFIG_ID:
1884+
mode = self._EDIT_APPROVAL_POLICY_TO_MODE.get(str(value), self._MODE_DEFAULT)
1885+
setattr(state, "mode", mode)
1886+
else:
1887+
options = getattr(state, "config_options", None)
1888+
if not isinstance(options, dict):
1889+
options = {}
1890+
options[str(config_id)] = value
1891+
setattr(state, "config_options", options)
18711892
self.session_manager.save_session(session_id)
18721893
logger.info("Session %s: config option %s updated", session_id, config_id)
1873-
return SetSessionConfigOptionResponse(config_options=self._session_config_options(state))
1894+
return SetSessionConfigOptionResponse(config_options=[])

‎acp_adapter/tools.py‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -928,23 +928,43 @@ def build_tool_start(
928928
tool_call_id: str,
929929
tool_name: str,
930930
arguments: Dict[str, Any],
931+
*,
932+
edit_diff: Any = None,
931933
) -> ToolCallStart:
932934
"""Create a ToolCallStart event for the given hermes tool invocation."""
933935
kind = get_tool_kind(tool_name)
934936
title = build_tool_title(tool_name, arguments)
935937
locations = extract_locations(arguments)
936938

937939
if tool_name == "patch":
938-
mode = arguments.get("mode", "replace")
939-
path = arguments.get("path") or "patch input"
940-
content = [_text(f"Preparing {mode} edit for {path}. Approval prompt shows the diff.")]
940+
if edit_diff is not None:
941+
content = [
942+
acp.tool_diff_content(
943+
path=edit_diff.path,
944+
old_text=edit_diff.old_text,
945+
new_text=edit_diff.new_text,
946+
)
947+
]
948+
else:
949+
mode = arguments.get("mode", "replace")
950+
path = arguments.get("path") or "patch input"
951+
content = [_text(f"Preparing {mode} edit for {path}. Approval prompt shows the diff.")]
941952
return acp.start_tool_call(
942953
tool_call_id, title, kind=kind, content=content, locations=locations,
943954
)
944955

945956
if tool_name == "write_file":
946-
path = arguments.get("path", "")
947-
content = [_text(f"Preparing write to {path}. Approval prompt shows the diff." if path else "Preparing file write. Approval prompt shows the diff.")]
957+
if edit_diff is not None:
958+
content = [
959+
acp.tool_diff_content(
960+
path=edit_diff.path,
961+
old_text=edit_diff.old_text,
962+
new_text=edit_diff.new_text,
963+
)
964+
]
965+
else:
966+
path = arguments.get("path", "")
967+
content = [_text(f"Preparing write to {path}. Approval prompt shows the diff." if path else "Preparing file write. Approval prompt shows the diff.")]
948968
return acp.start_tool_call(
949969
tool_call_id, title, kind=kind, content=content, locations=locations,
950970
)

‎tests/acp/test_server.py‎

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
PromptResponse,
2525
ResumeSessionResponse,
2626
SessionModelState,
27+
SessionModeState,
2728
SetSessionConfigOptionResponse,
2829
SetSessionModelResponse,
2930
SetSessionModeResponse,
@@ -52,31 +53,34 @@ def agent(mock_manager):
5253
"""HermesACPAgent backed by a mock session manager."""
5354
return HermesACPAgent(session_manager=mock_manager)
5455

55-
@pytest.mark.asyncio
56-
async def test_new_session_includes_edit_approval_config_option(self, agent):
57-
resp = await agent.new_session(cwd="/tmp")
58-
59-
assert resp.config_options
60-
option = resp.config_options[0]
61-
assert option.id == "edit_approval_policy"
62-
assert option.current_value == "ask"
63-
assert {choice.value for choice in option.options} == {
64-
"ask",
65-
"workspace_session",
66-
"session",
67-
}
6856

69-
@pytest.mark.asyncio
70-
async def test_set_config_option_persists_edit_approval_policy(self, agent):
71-
resp = await agent.new_session(cwd="/tmp")
72-
update = await agent.set_config_option(
73-
"edit_approval_policy",
74-
resp.session_id,
75-
"workspace_session",
76-
)
57+
@pytest.mark.asyncio
58+
async def test_new_session_exposes_edit_approvals_as_modes_not_config_options(agent):
59+
resp = await agent.new_session(cwd="/tmp")
60+
61+
assert resp.config_options is None
62+
assert isinstance(resp.modes, SessionModeState)
63+
assert resp.modes.current_mode_id == "default"
64+
assert [(mode.id, mode.name) for mode in resp.modes.available_modes] == [
65+
("default", "Default"),
66+
("accept_edits", "Accept Edits"),
67+
("dont_ask", "Don't Ask"),
68+
]
69+
70+
71+
@pytest.mark.asyncio
72+
async def test_set_config_option_persists_edit_approval_policy_without_advertising_config(agent):
73+
resp = await agent.new_session(cwd="/tmp")
74+
update = await agent.set_config_option(
75+
"edit_approval_policy",
76+
resp.session_id,
77+
"workspace_session",
78+
)
79+
state = agent.session_manager.get_session(resp.session_id)
7780

78-
assert isinstance(update, SetSessionConfigOptionResponse)
79-
assert update.config_options[0].current_value == "workspace_session"
81+
assert isinstance(update, SetSessionConfigOptionResponse)
82+
assert update.config_options == []
83+
assert getattr(state, "mode", None) == "accept_edits"
8084

8185

8286
# ---------------------------------------------------------------------------
@@ -891,11 +895,11 @@ class TestSessionConfiguration:
891895
@pytest.mark.asyncio
892896
async def test_set_session_mode_returns_response(self, agent):
893897
new_resp = await agent.new_session(cwd="/tmp")
894-
resp = await agent.set_session_mode(mode_id="chat", session_id=new_resp.session_id)
898+
resp = await agent.set_session_mode(mode_id="accept_edits", session_id=new_resp.session_id)
895899
state = agent.session_manager.get_session(new_resp.session_id)
896900

897901
assert isinstance(resp, SetSessionModeResponse)
898-
assert getattr(state, "mode", None) == "chat"
902+
assert getattr(state, "mode", None) == "accept_edits"
899903

900904
@pytest.mark.asyncio
901905
async def test_router_accepts_stable_session_config_methods(self, agent):
@@ -904,7 +908,7 @@ async def test_router_accepts_stable_session_config_methods(self, agent):
904908

905909
mode_result = await router(
906910
"session/set_mode",
907-
{"modeId": "chat", "sessionId": new_resp.session_id},
911+
{"modeId": "accept_edits", "sessionId": new_resp.session_id},
908912
False,
909913
)
910914
config_result = await router(
@@ -918,8 +922,7 @@ async def test_router_accepts_stable_session_config_methods(self, agent):
918922
)
919923

920924
assert mode_result == {}
921-
assert config_result["configOptions"]
922-
assert config_result["configOptions"][0]["id"] == "edit_approval_policy"
925+
assert config_result["configOptions"] == []
923926

924927
@pytest.mark.asyncio
925928
async def test_router_accepts_unstable_model_switch_when_enabled(self, agent):

0 commit comments

Comments
 (0)