Repository navigation
fix(subagent): refuse tool requests once a stop is in progress - #20743
Conversation
A Stop tears the sub-agent's session down first and cancels the run task after that. The dashboard approval wait turns that cancel into a denial, so the run loop resumes and reads its next event. When the session reset hangs or raises and the kill fallback also fails, the stream is still live, and the next permission request went through the normal ladder: a grant such as slot trust or --approval yolo approved a tool after the user pressed Stop. The permission branch now bails every request as "stopped" once _reap_started, user_stopped or reaped is set, before any grant or person is consulted. The bail is the ladder's own: the SEL row is written with error "stopped" and the request is rejected bare on the wire. "stopped" joins BailReason and the sub-agent refusal rows, and the run's ladder-entry ratchet counts the new bail. The cancel swallow in ApprovalCoordinator.request is unchanged; it is documented as intended (deny on timeout or cancellation).
The stop check at the top of the permission branch ran once, before the branch's own awaits (the diagnostics write and the subagent_tool event) and before the ladder's (the spec hooks, the gate, a person's wait). A Stop landing in any of them, while its session reset was still hanging, let the request reach the wire as an approval: parent_policy=auto, the gate's auto-approve or a person's yes sent approve_tool after the Stop. Policy gains a live stopping predicate. settle reads it before its first stage and before it asks a person, and _allow reads it at the commit point of every approval. Once it holds, the request goes through the same audited stopped bail. The run passes its predicate (_reap_started, user_stopped or reaped). _allow also hands the predicate to the wire, because approve_tool still awaits the security floor's thread hop and the stdin write lock before it writes the allow. AcpWire passes it as withdraw_if to a provider type that declares approval_withdrawable (AcpProvider, AcpSessionProvider), and both transports read it after the floor and under the write lock, right before the frame is written: AcpClient through its before_write check, the shared runtime through a withdrawal_check it runs ahead of its own liveness check. Once it holds, no byte is written, the request's records are put back, and ApprovalWithdrawn makes _allow bail the request as stopped: audited, and answered once with the agent's reject. A timed grant's deadline stays in the runtime's before_write, which runs after the liveness check, so a runtime that died during the lock wait still raises AcpRuntimeDead rather than GrantEnded. The stop bail now ends the run, as the limit bails do: the loop breaks instead of continuing, after the bail at the top of the branch and after a settle the ladder bailed as stopped, and the stream's own ending arms record the stop. A person's no that a stop's cancel caused still reads on, so a stream the stop tore down ends at its next read, as before. Ported onto main after acp/client.py was split: the AcpClient.approve_tool change now lives in acp/client_permissions.py. Co-authored-by: cixuuz <26782336+cixuuz@users.noreply.github.com>
UX Review (Opus 5.5) — ⏭️ skippedRevision |
Design Review (Opus 5.5) — ✅ PASSDesign-level review of Design-Verdict: PASS Verify that [DESIGN-REVIEWED] a3a2e3f Description read[DESCRIPTION-READ] b5bfce88c8a4aee7839c0857515d1b470e43312ffb939e65d3f8b262e454c34b That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with |
First Principles Review (Opus 5.5) — 🟡 CONCERNSPremise-level review of First-Principles-Verdict: CONCERNS The run-loop and ladder stop checks already close the reported hole. The transport-level Not justified as shipped
What this change shipsInventory (5 items) — 4 justifiedIntent: a sub-agent the user stopped never gets another tool approved, even when its teardown fails. This is a FIX.
[FIRST-PRINCIPLES-REVIEWED] a3a2e3f Description read[DESCRIPTION-READ] 8dde8cf83aaa94dbbe6f8547870b12c345b5834b92c6705cf6709b9ae6f226df That sha256 names the PR description this verdict read. Recompute it with |
Opus 5.5 Review — ✅ no blocking findingsReviewed Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
GPT 6.1 Review — ✅ no blocking findingsGPT 6.1 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
chenmingwei23
left a comment
There was a problem hiding this comment.
Batch approval: readiness: passed, no merge conflict, checks green.
…ng census kirodotdev#20743 gave AcpProvider an `approval_withdrawable` class flag and a `withdraw_if` keyword on `approve_tool`. The frozen census added with kirodotdev#20838 listed neither, so test_acp_bindings failed on main. Add the flag and update the `approve_tool` signature digest. Fixes kirodotdev#20893
Problem / Motivation
Goal: A sub-agent that the user has stopped never gets another tool approved, even when its session teardown fails.
A Stop on a running sub-agent tears its session down first and cancels the run task after that (
subagent_manager/terminal.py, the reset in_force_reap, then_cancel_task_intentionally). When the run is waiting on a person for a tool approval through the dashboard,ApprovalCoordinator.requestturns that cancel into a denial, so the run loop resumes and reads its next event.When the teardown works, that read hits the dead stream and the run ends. The trigger needs two failures together: the session reset hangs past
_RESET_TIMEOUTor raises, AND the SIGKILL fallback after it also fails to stop the process. Then the stream is still live. The backend's next permission request went through the normal ladder, and a grant that answers without a card (slot trust,--approval yoloorreads,auto_approve_sources,parent_policy=auto, a hook grant) approved a tool after the user pressed Stop.Observed in-process with the real run loop, the real stop and the real approval coordinator, with fakes for the backend, the reset and the kill. The order in every run was: Stop, reset, kill failed, cancel, the approval returns denied, tool A rejected, the backend sends tool B, B is granted,
approve_toolis sent for B.Why it matters
A tool that runs after a Stop is the worst outcome a stop can have: the user pressed Stop to prevent exactly that. The likelihood is low, because it needs both a failed session reset and a failed kill.
Not a goal
ApprovalCoordinator.request(except (asyncio.TimeoutError, asyncio.CancelledError): return False), or its question twin. That behaviour is documented as intended ("Request interactive approval and deny on timeout or cancellation",DashboardState.request_approval). Re-raising there would change that documented contract for every caller ofDashboardState.request_approval, not only sub-agent runs; this fix closes the hole at the one place that approves tools for a sub-agent run.shutdown())._force_reapsets_reap_startedbefore either branch, so the guard applies there too, but that path was not driven separately.What changed (motivation → approach → change)
subagent_manager/run.pynever checked whether a stop was in progress. The stop's own ordering (teardown before cancel) was the only thing that kept the request from being read, and that ordering does not hold when the teardown fails. A check made once, at the top of the branch, is not enough either: the branch awaits the diagnostics write and thesubagent_toolevent, and the ladder awaits the spec hooks, the gate and a person, so a stop can land after the check and before the approval is sent.tool_permission.Policygainsstopping, a live predicate.settlereads it before its first stage (tool_permission.py:410) and before it asks a person (tool_permission.py:437), and_allowreads it at the commit point of every approval (tool_permission.py:521), with no await between that read andwire.allow. A grant, the gate's hit and a person's yes all reach the wire only through_allow, so once the predicate holds the request is answered bytool_permission.bail(..., "stopped"): the SEL row is written witherror: "stopped"and the request is rejected bare on the wire. The run passes its predicate (_reap_started,user_stoppedorreaped;subagent_manager/run.py:280, wired atsubagent_manager/run.py:2087) and also reads it when it reads a request (subagent_manager/run.py:3266), before any floor, grant or person is consulted."stopped"joinsBailReasonand the sub-agent refusal rows, so a Stop is recorded as a stop, not as a turn limit or a person's no._allow's read:approve_toolstill awaits the security floor's thread hop and the stdin write lock before it writes the allow._allowhands the predicate to the wire (tool_permission.py:524), andAcpWirepasses it aswithdraw_ifto a provider type that declaresapproval_withdrawable(tool_permission.py:553):AcpProviderandAcpSessionProvider, while any other provider keeps the baseapproval_withdrawableofFalse(providers/base.py:119). Once the floor's thread hop returns, both transports readwithdraw_ifagain (acp/session_handle.py:2556,acp/client_permissions.py:282), and once more under the write lock right before the frame is written (acp/session_handle.py:2583,acp/client_permissions.py:303). The shared runtime reads it aswithdrawal_check, ahead of its own liveness check (acp/runtime.py:5453), and keeps a caller'sbefore_write, where a timed grant's deadline goes, after that check (acp/runtime.py:5450): a runtime that died while the answer waited for the lock raisesAcpRuntimeDead, so the chat path takes the session-reset recovery instead of asking a person about an ended grant.AcpClienthas no liveness check under its lock and reads the withdrawal in itsbefore_write, ahead of the deadline. Once it holds, no byte of the allow is written, the request's records are put back, andpermission_floor.ApprovalWithdrawnmakes_allowbail the request asstopped(tool_permission.py:525), answered once with the agent's own reject option.subagent_manager/run.py:3275) and after a settle the ladder bailed asstopped(subagent_manager/run.py:3364), and the stream's own ending arms record the stop (with_reap_startedset, the reap's ending:subagent_manager/run.py:3629). A person's no that a stop's cancel caused reads on, so a stream the stop tore down still ends at its next read, as before.docs/system-specs/modules/subagent.mdanddocs/system-specs/common/injected-messages.mdlist the new bail beside the two limit bails, and the first says where the stop is read and what ends the run;docs/system-specs/modules/acp-client.mddocumentswithdraw_if.AcpClient's methods intoacp/client_*owner modules.AcpClient.approve_tool's change (thewithdraw_ifreads and the put-back of the request's records) now lives inacp/client_permissions.py; the put-back is the module-level helper_restore_withdrawn(client, ...), not a new bound member, so the frozen member inventory intest/test_client_bindings.pychanges only inapprove_tool's signature digest (the new optionalwithdraw_ifkeyword).Backwards compatibility
Compatible: a run with no stop in progress takes exactly the path it takes today; the new branch runs only for a run that is already being stopped, and it answers each request through the existing bail. An approval without
withdraw_ifreaches the transport exactly as before: each layer passes the keyword on only when it is given.Removes nothing: the change adds one refusal rung, one optional
Policyfield (stopping, defaultNone, so the task runner's ladder takes its path unchanged) and the reads of it, the optional keywordswithdraw_if(approve_toolon both providers and both transports) andwithdrawal_check(AcpRuntime.send_responseand its protocol), the class attributeapproval_withdrawable(defaultFalse) andpermission_floor.ApprovalWithdrawn; no key, row, rung, path or public function is removed or renamed.Tests
Tests are @javenciu's from #18955, unchanged except the one digest above. #18955's body lists what each one locks in and its red/green runs against main.
On this branch (origin/main 213339f + 2 commits),
pytest -n 8:test/test_subagent_stop_refuses_permission.py,test/test_tool_permission.py,test/test_transport_permission_floor.py,test/test_eval_subagent_deny_notice.py,test/test_client_bindings.py: 633 passed. This includestest_a_stop_landing_in_the_transport_awaits_writes_no_approval[dedicated-floor|write_lock], which drivesAcpProviderover the realAcpClient, so the portedclient_permissions.approve_toolis covered.test/test_acp*,test/test_session*,test/test_subagent*andtest/test_chat_runner*files that nameapprove_tool,client_permissions,send_responseorwithdraw(-n 16): 3,209 passed, 1 skipped.black, isort, flake8 on the 15 changed Python files, mypy on the 10 changed source files,
./scripts/docs-lint.shandCOMMENT_HISTORY_BASE_REF=origin/main scripts/check_comment_history.py: all exit 0.Manual verification
N/A: the trigger needs a session reset and a kill that both fail, which the unit tests drive with fakes; no real process is signalled.
Related Issues
Fixes #20734
Replaces #18955
All credit to @javenciu, who found the bug, wrote the fix and its tests in #18955. This same-repo PR carries their two commits (authorship kept) onto current main, which had split
acp/client.pyand so conflicted with the fork.Pattern harvest
Rule candidate: review-prompt
Pattern: a stop that relies on its own ordering (tear down, then cancel) to keep a loop from acting, with no check of the stop flag at the point where the loop grants or executes work.
Checklist
feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)Contribution License Agreement
Contributions are accepted under the project's Apache-2.0 license; see the Licensing section of CONTRIBUTING.md.