Skip to content

The agent that grows with you

fix(acp): restore Accept Edits / Don't Ask as the session's owner-held edit policy

Teknium8729dd9e747d
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index c27749e066d..b1ccab1ce26 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -112,6 +112,8 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
self._mutations = PreparedMutations()
# Session -> title the editor was last shown (``session_info_update`` fires on a change).
self._titles = {}
+ # Session -> the mode (edit approval policy) the editor was last shown (``current_mode_update``).
+ self._modes = {}
# Session -> the owner's latest usage dict (``session.usage`` / ``session.stats``).
self._usage = {}
self._background = set()
@@ -288,7 +290,8 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
task = asyncio.get_running_loop().create_task(self._after_attach(session_id, editor_id))
self._background.add(task)
task.add_done_callback(self._background.discard)
- return {"models": models, "modes": session_modes(), "field_meta": meta}
+ self._modes[session_id] = session_modes(info).current_mode_id
+ return {"models": models, "modes": session_modes(info), "field_meta": meta}
async def _after_attach(self, session_id, editor_id):
from acp_adapter.gateway_session_meta import available_commands_update
@@ -540,25 +543,37 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
return session_id
async def set_session_mode(self, mode_id, session_id, **kwargs):
- """The advertised mode is the owner's own policy, so selecting it changes nothing; main's
- Accept Edits / Don't Ask need an editor-policy change the gateway has no verb for."""
+ """Main's Default / Accept Edits / Don't Ask: the session's edit approval policy on the owner."""
from acp.schema import SetSessionModeResponse
- from acp_adapter.gateway_session_meta import DEFAULT_MODE
- self._held_session(session_id)
- if mode_id != DEFAULT_MODE:
- raise GatewayClientError("acp_edit_policy_mutation_unavailable")
+ from acp_adapter.gateway_session_meta import MODE_TO_EDIT_APPROVAL_POLICY
+ if mode_id not in MODE_TO_EDIT_APPROVAL_POLICY:
+ raise GatewayClientError("invalid_params")
+ await self._set_edit_policy(self._held_session(session_id), MODE_TO_EDIT_APPROVAL_POLICY[mode_id])
return SetSessionModeResponse()
async def set_config_option(self, config_id, session_id, value=None, **kwargs):
"""Accepted so editors do not fail on their own config writes, as main did; only the edit
- approval policy has a meaning here, and only the owner's ``ask`` can be selected."""
+ approval policy has a meaning here, and it is the same owner setting the modes select."""
from acp.schema import SetSessionConfigOptionResponse
- from acp_adapter.gateway_session_meta import DEFAULT_EDIT_APPROVAL_POLICY, EDIT_APPROVAL_POLICY_CONFIG_ID
- self._held_session(session_id)
- if config_id == EDIT_APPROVAL_POLICY_CONFIG_ID and value != DEFAULT_EDIT_APPROVAL_POLICY:
- raise GatewayClientError("acp_edit_policy_mutation_unavailable")
+ from acp_adapter.gateway_session_meta import EDIT_APPROVAL_POLICY_CONFIG_ID, EDIT_APPROVAL_POLICY_TO_MODE
+ session_id = self._held_session(session_id)
+ if config_id == EDIT_APPROVAL_POLICY_CONFIG_ID:
+ if value not in EDIT_APPROVAL_POLICY_TO_MODE:
+ raise GatewayClientError("invalid_params")
+ await self._set_edit_policy(session_id, value)
return SetSessionConfigOptionResponse(config_options=[])
+ async def _set_edit_policy(self, session_id, policy):
+ """The owner's ``edit_policy`` mutation (revision-fenced, idle sessions only, like a model pick);
+ every surface attached to the session reads the committed policy from ``session.info``."""
+ from acp_adapter.gateway_session_meta import EDIT_APPROVAL_POLICY_TO_MODE
+ client = await self._client()
+ payload = {"policy": policy}
+ self._unacked.pop(session_id, None)
+ await self._mutations.apply(client, session_id, "edit_policy", payload)
+ self._mutations.acknowledge(session_id, "edit_policy", payload)
+ self._modes[session_id] = EDIT_APPROVAL_POLICY_TO_MODE[policy]
+
async def list_sessions(self, cursor=None, cwd=None, **kwargs):
from acp.schema import ListSessionsResponse, SessionInfo
from acp_adapter.catalog import catalog_sessions
@@ -978,6 +993,17 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
self._snapshots[sid]["_pending_watermark"] = (event.get("replay_epoch"), event.get("seq", 0))
self._changed.notify_all()
await self._project_title(sid, editor_id, payload.get("title"))
+ await self._project_mode(sid, editor_id, payload)
+
+ async def _project_mode(self, sid, editor_id, payload):
+ """Another surface's ``edit_policy`` change (its ``session.info``) as ``current_mode_update``."""
+ from acp_adapter.gateway_session_meta import EDIT_APPROVAL_POLICY_TO_MODE
+ mode = EDIT_APPROVAL_POLICY_TO_MODE.get(payload.get("edit_approval_policy"))
+ if mode is None or self._modes.get(sid, mode) == mode:
+ return
+ self._modes[sid] = mode
+ if self._conn:
+ await self._conn.session_update(session_id=editor_id, update=acp.update_current_mode(mode))
async def _project_usage(self, sid, editor_id, stats):
"""The owner's usage dict: kept for the turn's ``PromptResponse.usage``, shown as ``usage_update``."""
diff --git a/acp_adapter/gateway_session_meta.py b/acp_adapter/gateway_session_meta.py
index fa49b6f0955..08883f37194 100644
--- a/acp_adapter/gateway_session_meta.py
+++ b/acp_adapter/gateway_session_meta.py
@@ -18,11 +18,20 @@ from acp.schema import (
logger = logging.getLogger(__name__)
-# The gateway honours one editor edit policy, ``ask`` (``gateway/session_local_editor.py``), and has
-# no verb that changes it on a live session, so main's Accept Edits / Don't Ask are not offered.
+# Main's ACP modes (``acp_adapter/server.py`` ``_MODES``): mode id -> (edit approval policy, name,
+# description). The policy is the session's own on the owner (``session.mutate edit_policy``), enforced
+# where the edit runs (``gateway/session_local_editor.py``); sensitive paths always ask.
DEFAULT_MODE = "default"
DEFAULT_EDIT_APPROVAL_POLICY = "ask"
EDIT_APPROVAL_POLICY_CONFIG_ID = "edit_approval_policy"
+MODES: dict[str, tuple[str, str, str]] = {
+ "default": ("ask", "Default", "Ask before edits."),
+ "accept_edits": ("workspace_session", "Accept Edits",
+ "Auto-allow workspace and temp-dir edits; still asks for sensitive paths."),
+ "dont_ask": ("session", "Don't Ask", "Auto-allow file edits for this session except sensitive paths."),
+}
+MODE_TO_EDIT_APPROVAL_POLICY = {mode: spec[0] for mode, spec in MODES.items()}
+EDIT_APPROVAL_POLICY_TO_MODE = {spec[0]: mode for mode, spec in MODES.items()}
# Advertised name -> (description, input hint). ``prompt`` serves each through a gateway verb
# (``acp_adapter/gateway_commands.py``); ``/reset`` is the registry's alias of ``/new``.
@@ -59,9 +68,15 @@ def help_text() -> str:
return "\n".join(lines)
-def session_modes() -> SessionModeState:
- return SessionModeState(current_mode_id=DEFAULT_MODE, available_modes=[
- SessionMode(id=DEFAULT_MODE, name="Default", description="Ask before edits.")])
+def current_mode(info: dict) -> str:
+ """The mode of the session's edit approval policy (``session.info``); an owner without the field asks."""
+ return EDIT_APPROVAL_POLICY_TO_MODE.get(info.get("edit_approval_policy") or DEFAULT_EDIT_APPROVAL_POLICY,
+ DEFAULT_MODE)
+
+
+def session_modes(info: dict | None = None) -> SessionModeState:
+ return SessionModeState(current_mode_id=current_mode(info or {}), available_modes=[
+ SessionMode(id=mode, name=name, description=description) for mode, (_p, name, description) in MODES.items()])
def model_state(info: dict) -> SessionModelState | None:
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 8ddd7b8745c..d5df48a69db 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4550,7 +4550,7 @@ export interface PromptResolveUnknownParams {
admission_id: string
execution_generation: number
}
-/** ``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``; ``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace. ``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project. */
+/** ``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``; ``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace. ``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project. ``edit_policy`` (``{policy}``: ask / workspace_session / session) is an ACP session's edit approval (main's ACP modes). */
export interface SessionMutateParams {
session_id: string
request_id: string
@@ -4614,6 +4614,7 @@ export interface CanonicalSessionInfo {
desktop_protocol: string
profile_name: string
cwd?: string | null
+ edit_approval_policy?: 'ask' | 'workspace_session' | 'session' | null
launch_request?: Record<string, unknown> | null
reasoning_effort?: string | null
reasoning_effort_wire?: string | null
@@ -4984,6 +4985,7 @@ export interface CanonicalSnapshotInfo {
profile_id?: string | null
profile_name?: string | null
cwd?: string | null
+ edit_approval_policy?: 'ask' | 'workspace_session' | 'session' | null
launch_request?: Record<string, unknown> | null
reasoning_effort?: string | null
reasoning_effort_wire?: string | null
@@ -6766,7 +6768,7 @@ export interface CanonicalRpcMethods {
'session.info': { params: CanonicalSessionInfoParams; result: CanonicalSessionInfo }
'session.interrupt': { params: CanonicalControlParams; result: CanonicalSessionHandle }
'session.list': { params: CanonicalListParams; result: CanonicalListResult }
- /** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import). */
+ /** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, edit_policy, compress, import). */
'session.mutate': { params: SessionMutateParams; result: SessionMutateResult }
/** Local operator only: the owner deletes the ended sessions `hermes sessions prune` selected, skipping busy sessions and retained reset owners. */
'session.prune': { params: SessionPruneParams; result: SessionPruneResult }
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 63a15992b38..58218ff8a5c 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -10200,6 +10200,23 @@
"default": null,
"title": "Cwd"
},
+ "edit_approval_policy": {
+ "anyOf": [
+ {
+ "enum": [
+ "ask",
+ "workspace_session",
+ "session"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Edit Approval Policy"
+ },
"launch_request": {
"anyOf": [
{
@@ -10945,6 +10962,23 @@
"default": null,
"title": "Cwd"
},
+ "edit_approval_policy": {
+ "anyOf": [
+ {
+ "enum": [
+ "ask",
+ "workspace_session",
+ "session"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Edit Approval Policy"
+ },
"launch_request": {
"anyOf": [
{
@@ -37373,7 +37407,7 @@
},
"SessionMutateParams": {
"additionalProperties": false,
- "description": "``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;\n``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.\n``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite\nthe session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project.",
+ "description": "``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;\n``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.\n``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite\nthe session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project. ``edit_policy``\n(``{policy}``: ask / workspace_session / session) is an ACP session's edit approval (main's ACP modes).",
"properties": {
"session_id": {
"title": "Session Id",
@@ -47538,7 +47572,7 @@
},
{
"name": "session.mutate",
- "summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import).",
+ "summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, edit_policy, compress, import).",
"params": [
{
"name": "params",
diff --git a/gateway/session_local.py b/gateway/session_local.py
index f3745456d14..db068586639 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -336,14 +336,15 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
return staged
-def publish_local_policy(authority, session_id):
+def publish_local_policy(authority, session_id, *, evict=True):
from hermes_state_local import local_receipt
from gateway.session_policy import restore_policy
live = authority.sessions[session_id]
from gateway.session_local_recovery import local_adapter_map
adapter = local_adapter_map(authority)[Platform.LOCAL]
adapter.policies[live.source.chat_id] = restore_policy(local_receipt(authority.db, session_id)['policy'])
- authority.runner._evict_cached_agent(live.route)
+ if evict:
+ authority.runner._evict_cached_agent(live.route)
def _lazy_model(authority, policy):
@@ -409,7 +410,9 @@ def local_session_info(authority, ref):
'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
# Main's TUI labels a named profile's composer (``alpha ❯``) from this field.
'profile_name': served_profile_name(authority.profile_id),
- **({'cwd': policy.cwd} if policy else {})}
+ **({'cwd': policy.cwd} if policy else {}),
+ # An ACP session's edit approval policy: every attached surface reads the same one.
+ **({'edit_approval_policy': policy.edit_approval_policy} if policy and policy.source == 'acp' else {})}
peek = getattr(authority.runner, '_peek_session_state', None)
state = peek(live.route) if peek is not None else None
override = state.conversation.reasoning_override if state is not None else None # a typed /reasoning
diff --git a/gateway/session_local_editor.py b/gateway/session_local_editor.py
index add6b904335..b0f2182fa4e 100644
--- a/gateway/session_local_editor.py
+++ b/gateway/session_local_editor.py
@@ -52,10 +52,24 @@ def request_editor_edit(proposal):
return decision.get('resolved') and decision.get('choice') == 'once'
+def _policy_requester(policy):
+ """The session's edit approval policy in front of the editor's consent (main's ACP modes): Accept
+ Edits / Don't Ask let an edit run unasked; sensitive paths and everything else still ask."""
+ from acp_adapter.edit_approval import should_auto_approve_edit
+ if policy.edit_approval_policy == 'ask':
+ return request_editor_edit
+
+ def request(proposal):
+ if should_auto_approve_edit(proposal, policy.edit_approval_policy, policy.cwd):
+ return True
+ return request_editor_edit(proposal)
+ return request
+
+
@contextmanager
def editor_scope(policy):
from acp_adapter.edit_approval import set_edit_approval_requester, reset_edit_approval_requester
- token = set_edit_approval_requester(request_editor_edit if policy.source == 'acp' else None)
+ token = set_edit_approval_requester(_policy_requester(policy) if policy.source == 'acp' else None)
try:
yield
finally:
diff --git a/gateway/session_mutation_policy.py b/gateway/session_mutation_policy.py
index b75ea619960..626c92aa4f4 100644
--- a/gateway/session_mutation_policy.py
+++ b/gateway/session_mutation_policy.py
@@ -55,4 +55,17 @@ async def prepare_workspace(authority, live, payload, prepared):
return _rebind(authority, prepared, old, policy, git={'branch': branch, 'root': root})
-PREPARE = {'reasoning': prepare_reasoning, 'workspace': prepare_workspace}
+async def prepare_edit_policy(authority, live, payload, prepared):
+ """Main's ACP modes (Default / Accept Edits / Don't Ask) as the session's frozen edit approval
+ policy. Only an ACP session's edits ask an editor; selecting the current policy writes nothing."""
+ from gateway.session_policy import restore_policy
+ old = restore_policy(prepared['snapshot']['receipt']['policy'])
+ if old.source != 'acp':
+ raise RuntimeStoreError('invalid_params', field='payload.policy',
+ detail='only an ACP session has an editor edit approval policy')
+ if old.edit_approval_policy == payload['policy']:
+ return {'status': 'noop', 'edit_approval_policy': old.edit_approval_policy}
+ return _rebind(authority, prepared, old, replace(old, edit_approval_policy=payload['policy']))
+
+
+PREPARE = {'reasoning': prepare_reasoning, 'workspace': prepare_workspace, 'edit_policy': prepare_edit_policy}
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index a2797cda8e7..6df67e83dbf 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -16,7 +16,7 @@ logger = logging.getLogger(__name__)
_METADATA = frozenset({'rename', 'archive', 'sidebar'})
# Prepared off the commit like model, then published as a new frozen policy.
-_POLICY = frozenset({'model', 'reasoning', 'workspace', 'editor_mcp'})
+_POLICY = frozenset({'model', 'reasoning', 'workspace', 'editor_mcp', 'edit_policy'})
# Controls that leave the transcript alone authorize on the lineage owner (see ``_owner_ref``).
_OWNER_AUTHORIZED = _METADATA | {'delete'}
_FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})
@@ -289,7 +289,8 @@ def _project_committed(authority, ref, operation, result):
"""Publish a committed receipt's runtime projections (safe to repeat on exact retry)."""
if operation in _POLICY:
from gateway.session_local import publish_local_policy
- publish_local_policy(authority, ref.session_id)
+ # The edit policy is read per edit, never by the built agent: it keeps its agent (and prompt cache).
+ publish_local_policy(authority, ref.session_id, evict=operation != 'edit_policy')
# A drain that ran while the receipt committed off-loop saw the new stored policy beside
# the old live one and paused; with both now equal, queued input must run, not wait for
# the next submit or restart.
@@ -299,7 +300,7 @@ def _project_committed(authority, ref, operation, result):
# command still waiting for a turn boundary.
authority.runner._set_session_reasoning_override(authority.sessions[ref.session_id].route, None)
authority.sessions[ref.session_id].pending_reasoning = None
- if operation in {'model', 'reasoning', 'workspace'}:
+ if operation in {'model', 'reasoning', 'workspace', 'edit_policy'}:
# Every viewer repaints its model, reasoning pill or workspace from the published policy,
# as main's _emit_session_info did after the live change.
from gateway.session_local import local_session_info
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index bd689809bda..d55e0d71860 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -88,6 +88,10 @@ def _refuse(field, detail=None):
raise RuntimeStoreError('invalid_params', field=field, detail=detail)
+# ``acp_adapter/edit_approval.py``'s AUTO_APPROVE_* values, in main's ACP mode order.
+EDIT_APPROVAL_POLICIES = ('ask', 'workspace_session', 'session')
+
+
@dataclass(frozen=True)
class LocalSessionPolicy:
source: str
@@ -123,6 +127,9 @@ class LocalSessionPolicy:
# plain data: an exact retry is judged by them, never by the profile's current ones, and the session's
# tools run without every toolchain name they cover that the client did not send.
client_env_rules_json: str | None = None
+ # An ACP session's edit approval (``session.mutate edit_policy``; main's ACP modes): ``ask`` (Default),
+ # ``workspace_session`` (Accept Edits) or ``session`` (Don't Ask). Sensitive paths always ask.
+ edit_approval_policy: str = 'ask'
def client_env(self):
return None if self.client_env_json is None else json.loads(self.client_env_json)
@@ -934,6 +941,8 @@ def restore_policy(data):
or type(policy.coding_posture) is not bool
or not _valid_client_env(policy.client_env_json) or type(policy.client_env_remote) is not bool
or not _valid_client_env(policy.client_env_rules_json, list)
+ or policy.edit_approval_policy not in EDIT_APPROVAL_POLICIES
+ or (policy.edit_approval_policy != 'ask' and policy.source != 'acp')
or (policy.safe_mode and not policy.ignore_user_config)):
raise ValueError('invalid policy')
from dataclasses import replace
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index bb2032617bb..2b5f2a9b816 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -71,6 +71,8 @@ def policy_identity(policy, unhashed=()):
data.pop(name, None)
if not data.get('client_env_remote'):
data.pop('client_env_remote', None)
+ if data.get('edit_approval_policy', 'ask') == 'ask':
+ data.pop('edit_approval_policy', None)
for name in unhashed: # _legacy_identities: a field the stamping gateway did not have yet
data.pop(name, None)
return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
diff --git a/hermes_state_mutation_prepared.py b/hermes_state_mutation_prepared.py
index bde37bdc418..af4c2fa31af 100644
--- a/hermes_state_mutation_prepared.py
+++ b/hermes_state_mutation_prepared.py
@@ -85,8 +85,15 @@ def editor_mcp_in_transaction(db, conn, session_id, payload, prepared):
'mcp_servers': prepared['mcp_servers'], 'execution_generation': generation}
+def edit_policy_in_transaction(db, conn, session_id, payload, prepared):
+ snapshot, generation = _commit_policy(db, conn, session_id, prepared)
+ return {session_id, snapshot['target']}, {'edit_approval_policy': payload['policy'],
+ 'execution_generation': generation}
+
+
POLICY_HANDLERS = {'model': model_in_transaction, 'reasoning': reasoning_in_transaction,
- 'workspace': workspace_in_transaction, 'editor_mcp': editor_mcp_in_transaction}
+ 'workspace': workspace_in_transaction, 'editor_mcp': editor_mcp_in_transaction,
+ 'edit_policy': edit_policy_in_transaction}
_RECEIPTS = "FROM state_meta WHERE key GLOB 'gateway.mutation.v1.*' AND json_valid(value) "
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index c22fbe25a35..53853bd887a 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -31,6 +31,9 @@ def validate_action(operation, payload):
# hands the store only its fingerprint, so no transport credential reaches a receipt.
if operation == 'editor_mcp' and set(payload) == {'mcp_servers'} and _valid_editor_fingerprint(payload):
return
+ # An ACP session's edit approval policy (gateway/session_mutation_policy.py prepare_edit_policy).
+ if operation == 'edit_policy' and set(payload) == {'policy'} and payload['policy'] in {'ask', 'workspace_session', 'session'}:
+ return
if operation == 'compress' and _valid_compress_payload(payload):
return
if operation in {'delete', 'reset'} and not payload:
@@ -86,7 +89,7 @@ def apply_action(db, conn, session_id, operation, payload, *, prepared=None):
if operation == 'compress':
from hermes_state_mutation_compress import compress_in_transaction
return compress_in_transaction(db, conn, session_id, payload, prepared)
- if operation in {'model', 'reasoning', 'workspace', 'editor_mcp'}:
+ if operation in {'model', 'reasoning', 'workspace', 'editor_mcp', 'edit_policy'}:
from hermes_state_mutation_prepared import POLICY_HANDLERS
return POLICY_HANDLERS[operation](db, conn, session_id, payload, prepared)
if operation == 'branch':
diff --git a/tests/acp_adapter/test_gateway_controls.py b/tests/acp_adapter/test_gateway_controls.py
index cc204a2b4ae..2bd256bab39 100644
--- a/tests/acp_adapter/test_gateway_controls.py
+++ b/tests/acp_adapter/test_gateway_controls.py
@@ -35,11 +35,12 @@ async def test_cancel_uses_observed_generation_and_mutations_fail_explicitly(tmp
await agent.set_session_model(session_id="shared", model_id="new-model")
methods = [method for method, _ in calls]
assert methods and set(methods) <= {"session.resume", "session.mutate"}, methods
- # Edit-policy mode is still unsupported and must not reach the authority at all.
- before = len(calls)
- with pytest.raises(GatewayClientError, match="unavailable"):
+ # An edit-policy mode is the same canonical mutation: a stale answer propagates verbatim too.
+ calls.clear()
+ with pytest.raises(GatewayClientError, match="stale_generation"):
await agent.set_session_mode(session_id="shared", mode_id="dont_ask")
- assert len(calls) == before, "Unsupported operations must not reach an alternate writer"
+ methods = [method for method, _ in calls]
+ assert methods and set(methods) <= {"session.resume", "session.mutate"}, methods
@pytest.mark.asyncio
diff --git a/tests/acp_adapter/test_gateway_editor_wire.py b/tests/acp_adapter/test_gateway_editor_wire.py
index c4d07019bb0..127b28de3ae 100644
--- a/tests/acp_adapter/test_gateway_editor_wire.py
+++ b/tests/acp_adapter/test_gateway_editor_wire.py
@@ -19,7 +19,10 @@ class EditPeer(BaseHTTPRequestHandler):
self.server.requests.append(request)
# write_file refuses to replace an existing file this task never read in full
# (stale-overwrite guard), so the scripted model reads first, then edits.
- seen = sum(1 for m in request.get('messages', []) if m['role'] == 'tool')
+ # Counted since the latest user turn, so a second prompt in the session edits again.
+ messages = request.get('messages', [])
+ last_user = max((i for i, m in enumerate(messages) if m['role'] == 'user'), default=-1)
+ seen = sum(1 for m in messages[last_user + 1:] if m['role'] == 'tool')
tool = seen < 2
message = {'role': 'assistant', 'content': 'EDITOR_FINISHED'}
if seen == 0:
@@ -111,3 +114,55 @@ async def test_real_editor_diff_requires_native_consent_before_write(daemon, tmp
task.cancel()
with suppress(asyncio.CancelledError):
await task
+
+
+async def test_accept_edits_runs_a_workspace_edit_unasked_and_a_sensitive_one_still_asks(daemon, tmp_path, model_peer):
+ """ACP-7: Accept Edits is the session's ``edit_policy`` on the owner; a second surface reads it, a
+ workspace edit runs without a permission request, and a sensitive path (``.env``) still asks."""
+ target = tmp_path / 'owned.txt'
+ target.write_text('original edit')
+ model_peer.target = target
+ model_peer.RequestHandlerClass = EditPeer
+ async with viewer(daemon) as ws:
+ sid = (await ws.rpc('session.create', source='acp', cwd=str(tmp_path), request_id='accept'))['session_id']
+ assert (await ws.rpc('session.info', session_id=sid))['edit_approval_policy'] == 'ask'
+ async with editor(daemon, tmp_path) as acp:
+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})
+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])
+ modes = loaded['result']['modes']
+ assert modes['currentModeId'] == 'default', loaded
+ assert [m['id'] for m in modes['availableModes']] == ['default', 'accept_edits', 'dont_ask']
+ assert 'result' in await acp.rpc('session/set_mode', sessionId=sid, modeId='accept_edits')
+ # Every surface attached to the session sees the same policy.
+ assert (await ws.rpc('session.info', session_id=sid))['edit_approval_policy'] == 'workspace_session'
+ turn = await acp.rpc('session/prompt', sessionId=sid, prompt=[{'type': 'text', 'text': 'Edit it'}])
+ assert turn['result']['stopReason'] == 'end_turn', turn
+ assert target.read_text() == 'approved edit'
+ assert not any(f.get('method') == 'session/request_permission' for f in acp.frames)
+
+ sensitive = tmp_path / '.env'
+ sensitive.write_text('SECRET=1')
+ model_peer.target = sensitive
+ task = asyncio.create_task(acp.rpc('session/prompt', sessionId=sid,
+ prompt=[{'type': 'text', 'text': 'Edit the env file'}]))
+ try:
+ await async_wait_until(lambda: any(f.get('method') == 'session/request_permission' for f in acp.frames),
+ timeout=20, what='the sensitive edit permission request')
+ permission = next(f for f in acp.frames if f.get('method') == 'session/request_permission')
+ assert permission['params']['toolCall']['kind'] == 'edit', permission
+ acp.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'id': permission['id'], 'result': {
+ 'outcome': {'outcome': 'selected', 'optionId': 'deny'}}}).encode() + b'\n')
+ await acp.process.stdin.drain()
+ assert (await task)['result']['stopReason'] == 'end_turn'
+ assert sensitive.read_text() == 'SECRET=1'
+ finally:
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+ # A second editor attaching to the session is shown the session's mode.
+ async with editor(daemon, tmp_path) as second:
+ await second.rpc('initialize', protocolVersion=1, clientCapabilities={})
+ again = await second.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])
+ assert again['result']['modes']['currentModeId'] == 'accept_edits', again
diff --git a/tests/acp_adapter/test_gateway_session_commands.py b/tests/acp_adapter/test_gateway_session_commands.py
index 73bf339af8c..d1133ee75e7 100644
--- a/tests/acp_adapter/test_gateway_session_commands.py
+++ b/tests/acp_adapter/test_gateway_session_commands.py
@@ -113,13 +113,29 @@ async def test_a_steer_for_a_turn_that_just_ended_becomes_the_next_prompt():
@pytest.mark.asyncio
-async def test_only_the_owners_edit_policy_can_be_selected():
- agent = _agent(AsyncMock())
+async def test_modes_and_the_config_option_set_the_owners_edit_policy():
+ """ACP-7: main's modes are the session's ``edit_policy`` on the owner, one fenced mutation each."""
+ sent = []
+
+ async def rpc(method, **params):
+ if method == 'session.resume':
+ return {'revision': 3, 'execution_generation': 7}
+ assert method == 'session.mutate', method
+ sent.append((params['operation'], params['payload'], params['expected_generation']))
+ return {'session_id': 's', 'operation': 'edit_policy', 'revision': 4}
+
+ agent = _agent(rpc)
+ await agent.set_session_mode('accept_edits', 's')
+ await agent.set_config_option('edit_approval_policy', 's', 'session')
await agent.set_session_mode('default', 's')
- await agent.set_config_option('edit_approval_policy', 's', 'ask')
- with pytest.raises(GatewayClientError, match='acp_edit_policy_mutation_unavailable'):
- await agent.set_session_mode('accept_edits', 's')
- agent._gateway.rpc.assert_not_awaited()
+ assert sent == [('edit_policy', {'policy': 'workspace_session'}, 7), ('edit_policy', {'policy': 'session'}, 7),
+ ('edit_policy', {'policy': 'ask'}, 7)]
+ sent.clear()
+ with pytest.raises(GatewayClientError, match='invalid_params'):
+ await agent.set_session_mode('yolo', 's')
+ # Another config id is accepted and means nothing here, as on main.
+ await agent.set_config_option('theme', 's', 'dark')
+ assert sent == []
def _context_shown(agent):
diff --git a/tests/acp_adapter/test_policy_identity_compat.py b/tests/acp_adapter/test_policy_identity_compat.py
index 491fcb199e3..896a99fde3d 100644
--- a/tests/acp_adapter/test_policy_identity_compat.py
+++ b/tests/acp_adapter/test_policy_identity_compat.py
@@ -16,5 +16,6 @@ def test_policy_identity_preserves_pre_editor_credential_binding(tmp_path):
legacy.pop('client_env_json')
legacy.pop('client_env_remote')
legacy.pop('client_env_rules_json')
+ legacy.pop('edit_approval_policy')
expected = hashlib.sha256(json.dumps(legacy, sort_keys=True).encode()).hexdigest()
assert policy_identity(policy) == expected
diff --git a/tests/gateway/test_config_secret_scope.py b/tests/gateway/test_config_secret_scope.py
index 50f6d3e21b4..64f634ec1a3 100644
--- a/tests/gateway/test_config_secret_scope.py
+++ b/tests/gateway/test_config_secret_scope.py
@@ -21,7 +21,8 @@ CONFIG = ('model: {default: m1, provider: custom, base_url: "http://127.0.0.1:9/
'mcp_servers: {docs: {command: docs-mcp, env: {DOCS_TOKEN: mcp-token}}}\n')
# The policy fields an older gateway's reference did not hash (they did not exist when it was stamped).
_LATER_FIELDS = ('kanban_json', 'safe_mode', 'ignore_user_config', 'skills_prompt', 'editor_mcp_json',
- 'coding_posture', 'client_env_json', 'client_env_remote', 'client_env_rules_json')
+ 'coding_posture', 'client_env_json', 'client_env_remote', 'client_env_rules_json',
+ 'edit_approval_policy')
def _home(monkeypatch):
diff --git a/tests/gateway/test_session_edit_policy.py b/tests/gateway/test_session_edit_policy.py
new file mode 100644
index 00000000000..2600152dd19
--- /dev/null
+++ b/tests/gateway/test_session_edit_policy.py
@@ -0,0 +1,155 @@
+"""ACP-7: an ACP session's edit-approval policy (Default / Accept Edits / Don't Ask) is owner data.
+
+Main's in-process ACP kept the mode on its own session (``acp_adapter/server.py`` ``_MODES``). On the
+shared owner it is a field of the session's frozen LocalSessionPolicy, written by a revision-fenced
+``session.mutate edit_policy``, read back by every viewer's ``session.info``, restored after an owner
+restart, and enforced where the edit runs (``gateway/session_local_editor.py``): sensitive paths ask.
+"""
+import asyncio
+from dataclasses import replace
+from types import SimpleNamespace
+
+import pytest
+
+
+def _runner(store):
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,
+ _set_session_reasoning_override=lambda route, value: None,
+ _handle_message=None, _resolve_session_agent_runtime=lambda **k: ('frozen', {}))
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ return runner
+
+
+def _mutation(db, sid, request_id, payload, operation='edit_policy'):
+ snap = db.get_session(sid)
+ return {'id': request_id, 'method': 'session.mutate', 'params': {
+ 'session_id': sid, 'request_id': request_id, 'operation': operation, 'payload': payload,
+ 'expected_revision': snap['runtime_revision'], 'expected_generation': snap['runtime_generation']}}
+
+
+async def _info(connection, sid):
+ reply = await connection.dispatch({'id': 'i', 'method': 'session.info', 'params': {'session_id': sid}})
+ assert 'result' in reply, reply
+ return reply['result']
+
+
+async def test_edit_policy_is_a_durable_session_setting_every_viewer_reads(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_policy import policy_for_source
+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ first = await initialize_session_authority(_runner(store), profile_id='owned', instance_id='first')
+ editor = AuthorityConnection(first, object(), {'user_id': 'human'})
+ other = AuthorityConnection(first, object(), {'user_id': 'human'})
+ try:
+ created = await editor.dispatch({'id': 1, 'method': 'session.create', 'params': {
+ 'request_id': 'acp', 'source': 'acp', 'cwd': str(tmp_path), 'model': 'frozen',
+ 'editor': {'mcp_servers': [], 'edit_approval_policy': 'ask'}}})
+ sid = created['result']['session_id']
+ gui = (await editor.dispatch({'id': 2, 'method': 'session.create', 'params': {
+ 'request_id': 'gui', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen'}}))['result']['session_id']
+ # A client that never sets it keeps main's default: every edit asks.
+ assert (await _info(editor, sid))['edit_approval_policy'] == 'ask'
+ live = first.sessions[sid]
+ assert policy_for_source(first.runner, live.source).edit_approval_policy == 'ask'
+
+ applied = await editor.dispatch(_mutation(db, sid, 'm1', {'policy': 'workspace_session'}))
+ assert applied['result']['edit_approval_policy'] == 'workspace_session', applied
+ # The policy the next turn executes under, and what a second attached surface reads.
+ assert policy_for_source(first.runner, live.source).edit_approval_policy == 'workspace_session'
+ assert (await _info(other, sid))['edit_approval_policy'] == 'workspace_session'
+
+ bad = await editor.dispatch(_mutation(db, sid, 'm2', {'policy': 'yolo'}))
+ assert bad['error']['data']['reason'] == 'invalid_params', bad
+ # Only an ACP session has an editor edit policy; any other surface's edits never ask an editor.
+ refused = await editor.dispatch(_mutation(db, gui, 'm3', {'policy': 'session'}))
+ assert refused['error']['data']['reason'] == 'invalid_params', refused
+ finally:
+ await editor.close()
+ await other.close()
+
+ # An owner restart restores the session's policy from its stored receipt.
+ cold = await initialize_session_authority(_runner(store), profile_id='owned', instance_id='restarted')
+ viewer = AuthorityConnection(cold, object(), {'user_id': 'human'})
+ try:
+ resumed = await viewer.dispatch({'id': 3, 'method': 'session.resume', 'params': {'session_id': sid}})
+ assert 'result' in resumed, resumed
+ assert policy_for_source(cold.runner, cold.sessions[sid].source).edit_approval_policy == 'workspace_session'
+ assert (await _info(viewer, sid))['edit_approval_policy'] == 'workspace_session'
+ back = await viewer.dispatch(_mutation(db, sid, 'm4', {'policy': 'ask'}))
+ assert back['result']['edit_approval_policy'] == 'ask', back
+ finally:
+ await viewer.close()
+ store.close_all_db_handles()
+
+
+def test_a_policy_stored_before_the_field_restores_as_ask_with_its_identity_unchanged(tmp_path):
+ """A receipt main minted has no ``edit_approval_policy``: it restores as ``ask`` and its credential
+ reference (a whole-policy hash) still matches, so no stored session loses its launch secrets."""
+ from dataclasses import asdict
+ from gateway.session_policy import build_policy, restore_policy
+ from gateway.session_policy_credentials import policy_identity
+ policy = build_policy({'source': 'acp', 'cwd': str(tmp_path), 'model': 'fixture'}, {})
+ stored = asdict(policy)
+ stored.pop('edit_approval_policy')
+ old = restore_policy(stored)
+ assert old.edit_approval_policy == 'ask'
+ assert policy_identity(old) == policy_identity(policy)
+ assert policy_identity(replace(policy, edit_approval_policy='session')) != policy_identity(policy)
+ with pytest.raises(Exception):
+ restore_policy({**stored, 'edit_approval_policy': 'everything'})
+
+
[email protected]('name, policy, asks', [
+ ('edit.txt', 'ask', True), # Default: every edit asks
+ ('edit.txt', 'workspace_session', False), # Accept Edits: a workspace edit runs
+ ('.env', 'workspace_session', True), # ... a sensitive path still asks
+ ('edit.txt', 'session', False), # Don't Ask
+ ('.git/config', 'session', True), # ... a sensitive path still asks
+])
+async def test_the_owners_edit_guard_enforces_the_sessions_policy(tmp_path, name, policy, asks):
+ from acp_adapter.edit_approval import maybe_require_edit_approval
+ from gateway.session_policy import build_policy, policy_scope
+ from tools.approval import register_gateway_notify, unregister_gateway_notify
+ from tools.approval_context import reset_current_session_key, set_current_session_key
+
+ route = f'edit-policy-{policy}-{name}'
+ asked = []
+
+ def notify(data):
+ # The editor's consent prompt; denied here, so an asked edit never writes.
+ asked.append(data)
+ import threading
+ from tests.waiting import wait_until
+ from tools.approval import resolve_gateway_approval
+ # The waiter enqueues its entry right after this notify returns; deny it once it is there.
+ threading.Thread(target=lambda: wait_until(lambda: resolve_gateway_approval(route, 'deny'), timeout=10,
+ what='the edit approval to deny'), daemon=True).start()
+
+ register_gateway_notify(route, notify)
+ frozen = replace(build_policy({'source': 'acp', 'cwd': str(tmp_path), 'model': 'fixture'}, {}),
+ edit_approval_policy=policy)
+ path = tmp_path / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+
+ def guard():
+ token = set_current_session_key(route)
+ try:
+ with policy_scope(frozen):
+ return maybe_require_edit_approval('write_file', {'path': str(path), 'content': 'new'})
+ finally:
+ reset_current_session_key(token)
+ try:
+ result = await asyncio.wait_for(asyncio.to_thread(guard), 10)
+ finally:
+ unregister_gateway_notify(route)
+ assert bool(asked) is asks, (policy, name, asked)
+ assert (result is None) is (not asks), result
diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.py
index 63b6f742c5b..33f228f6e64 100644
--- a/tests/gateway/test_session_mutation_model.py
+++ b/tests/gateway/test_session_mutation_model.py
@@ -38,7 +38,7 @@ def test_model_commit_republishes_session_info(monkeypatch):
runner=SimpleNamespace(_set_session_reasoning_override=lambda *_args: None),
_schedule=lambda _ref: None,
)
- monkeypatch.setattr(session_local, "publish_local_policy", lambda *_args: None)
+ monkeypatch.setattr(session_local, "publish_local_policy", lambda *_args, **_kwargs: None)
monkeypatch.setattr(session_local, "local_session_info", lambda *_args: {"model": "switched"})
_project_committed(authority, SessionRef("profile", "session"), "model", {})
diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.py
index e4dfe831ded..0a677845dc0 100644
--- a/tui_gateway/contracts/canonical.py
+++ b/tui_gateway/contracts/canonical.py
@@ -83,7 +83,8 @@ class SessionMutateParams(Params):
"""``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;
``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.
``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite
- the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project."""
+ the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project. ``edit_policy``
+ (``{policy}``: ask / workspace_session / session) is an ACP session's edit approval (main's ACP modes)."""
session_id: str
request_id: str
@@ -105,7 +106,7 @@ class SessionMutateResult(OpenModel):
canonical_method("session.mutate", params=SessionMutateParams, result=SessionMutateResult,
doc="Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, "
- "delete, rewind, reset, model, reasoning, workspace, compress, import).")
+ "delete, rewind, reset, model, reasoning, workspace, edit_policy, compress, import).")
class SessionPruneParams(Params):
@@ -182,6 +183,8 @@ class CanonicalSessionInfo(SessionInventoryFields, OpenModel):
desktop_protocol: str
profile_name: str
cwd: str | None = None
+ # An ACP session's edit approval policy (``session.mutate edit_policy``): ask / workspace_session / session.
+ edit_approval_policy: Literal["ask", "workspace_session", "session"] | None = None
launch_request: dict[str, JsonValue] | None = None
reasoning_effort: str | None = None
reasoning_effort_wire: str | None = None
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index 1542b9d478e..b6734f17395 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -114,6 +114,7 @@ class CanonicalSnapshotInfo(SessionInventoryFields):
profile_id: str | None = None
profile_name: str | None = None
cwd: str | None = None
+ edit_approval_policy: Literal['ask', 'workspace_session', 'session'] | None = None
launch_request: dict[str, JsonValue] | None = None
reasoning_effort: str | None = None
reasoning_effort_wire: str | None = None