diff --git a/.agents/skills/verify-sdk/references/feature-map/S13-security-confirmation.md b/.agents/skills/verify-sdk/references/feature-map/S13-security-confirmation.md index 86e73781e80..f05dad491fd 100644 --- a/.agents/skills/verify-sdk/references/feature-map/S13-security-confirmation.md +++ b/.agents/skills/verify-sdk/references/feature-map/S13-security-confirmation.md @@ -180,7 +180,7 @@ Preconditions: --check async.tool_step.messages.0 eq "the values are and " \ --check async.tool_step.seconds lt 10 ``` - Known failure (reproduced 2026-10-13, not yet filed): when the first lookup is triggered by masking a tool observation (`ToolDefinition.__call__` → `mask_secrets_in_model`), the state lock is still held during the HTTP request. The secrets service's `update_secrets` call therefore blocks until httpx's 30 s timeout, the lookup fails, and the back-off then leaves the value unmasked. Evidence: `async.tool_step.messages.0` is `"the values are loop-val and "` and `async.tool_step.seconds` is `30.5`, while the message-step case is masked and takes `0.1` s. + Expected: both cases are masked in well under a second. Before #6642 the tool case made the lookup inside the tool, while `arun()` held the state lock, so the server's `update_secrets` call waited on that lock and the value stayed unmasked after httpx's 30 s timeout; `astep` now resolves lookups with the lock released before running tools, as it does before masking an agent message. - **A real model labels its own actions (`S13.llm-analyzer`, `S13.confirm-wait`, `S13.confirm-approve-reject`).** Live. The model is asked to run `ls` and then `rm -rf scratch`; `ConfirmRisky()` stops, and the program rejects until the agent finishes. A model that declines to propose the deletion at all (DeepSeek Flash did on 2026-11-03: it only listed and read `scratch/`) leaves the confirmation path unexercised, and the program exits 3. ```sh export SDK_VERIFY_RUN=$(control-sdk new --llm deepseek-flash --field run) diff --git a/openhands-sdk/openhands/sdk/agent/agent.py b/openhands-sdk/openhands/sdk/agent/agent.py index 294dd9bf23a..496c9063071 100644 --- a/openhands-sdk/openhands/sdk/agent/agent.py +++ b/openhands-sdk/openhands/sdk/agent/agent.py @@ -705,6 +705,17 @@ async def _aexecute_actions( loop an ``await`` boundary between every tool invocation. """ state = conversation.state + # Each tool masks its observation in a worker thread while arun() holds + # the state lock. A lookup made there may call a server on this event + # loop that registers secrets on the conversation, which needs that lock + # (#6642). Resolve lookups first with the lock released, as astep does + # for agent messages, so masking under the lock finds them cached. + while True: + sources = dict(state.secret_registry.secret_sources) + async with conversation._released_state_lock_during_io(): + await asyncio.to_thread(state.secret_registry.resolve_uncached_values) + if sources == state.secret_registry.secret_sources: + break batch = await _ActionBatch.aprepare( action_events, state=state, diff --git a/openhands-sdk/openhands/sdk/conversation/secret_registry.py b/openhands-sdk/openhands/sdk/conversation/secret_registry.py index 685f5d462b3..4081e3042b2 100644 --- a/openhands-sdk/openhands/sdk/conversation/secret_registry.py +++ b/openhands-sdk/openhands/sdk/conversation/secret_registry.py @@ -282,6 +282,25 @@ def get_all_secrets_as_env_vars( env_vars[name] = value return env_vars + def resolve_uncached_values(self) -> None: + """Resolve every source whose value is not cached yet, for masking. + + ``get_value()`` may do blocking network I/O, so a failed lookup backs off + for ``FAILED_LOOKUP_RETRY_SECONDS`` instead of retrying on every output + and every ACP chunk. Callers that hold the conversation's state lock can + run this first with the lock released, so that masking under the lock + finds every value cached and does no lookup there. + """ + now = time.monotonic() + for key in list(self.secret_sources): + if key in self._exported_values: + continue + failed_at = self._failed_lookups.get(key) + if failed_at is not None and now - failed_at < FAILED_LOOKUP_RETRY_SECONDS: + continue + if not self.get_secret_value(key): + self._failed_lookups[key] = now + def mask_secrets_in_output(self, text: str) -> str: """Mask secret values in the given text. @@ -299,17 +318,7 @@ def mask_secrets_in_output(self, text: str) -> str: if not text: return text - # Resolve uncached sources, backing off on failure: get_value() may do - # blocking network I/O and masking runs per output and per ACP chunk. - now = time.monotonic() - for key in list(self.secret_sources): - if key in self._exported_values: - continue - failed_at = self._failed_lookups.get(key) - if failed_at is not None and now - failed_at < FAILED_LOOKUP_RETRY_SECONDS: - continue - if not self.get_secret_value(key): - self._failed_lookups[key] = now + self.resolve_uncached_values() masked_text = text with self._exported_values_lock: diff --git a/tests/sdk/agent/test_async_secret_masking.py b/tests/sdk/agent/test_async_secret_masking.py index 93d258cf32f..6fe6f0635fa 100644 --- a/tests/sdk/agent/test_async_secret_masking.py +++ b/tests/sdk/agent/test_async_secret_masking.py @@ -4,7 +4,12 @@ from openhands.sdk import Agent, Conversation from openhands.sdk.conversation.state import ConversationExecutionStatus -from openhands.sdk.event import ActionEvent, MessageEvent, SecurityAnalysisEvent +from openhands.sdk.event import ( + ActionEvent, + MessageEvent, + ObservationEvent, + SecurityAnalysisEvent, +) from openhands.sdk.llm import Message, TextContent from openhands.sdk.llm.message import MessageToolCall from openhands.sdk.secret import LookupSecret @@ -208,3 +213,79 @@ async def serve_secret(reader, writer): await asyncio.to_thread(conversation.close) server.close() await server.wait_closed() + + +@pytest.mark.asyncio +async def test_async_tool_observation_lookup_does_not_wait_on_state_lock(tmp_path): + """A lookup first triggered by a tool's output must not run under the lock. + + The loopback server registers a secret while answering, which takes the + state lock. If the tool masked its observation (and so made the lookup) + while arun() held that lock, the request would block until httpx's 30 s + timeout and the value would stay unmasked (#6642). + """ + requested = asyncio.Event() + + async def serve_secret(reader, writer): + await reader.readuntil(b"\r\n\r\n") + requested.set() + await asyncio.to_thread( + conversation.update_secrets, {"NESTED": "nested-secret-value"} + ) + body = b"loopback-secret-value" + writer.write( + b"HTTP/1.1 200 OK\r\nContent-Length: " + + str(len(body)).encode() + + b"\r\nConnection: close\r\n\r\n" + + body + ) + await writer.drain() + writer.close() + await writer.wait_closed() + + server = await asyncio.start_server(serve_secret, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + llm = TestLLM.from_messages( + [ + Message( + role="assistant", + content=[], + tool_calls=[ + MessageToolCall( + id="think-0", + origin="completion", + name="think", + arguments='{"thought":"test"}', + ) + ], + ), + Message(role="assistant", content=[TextContent(text="done")]), + ] + ) + conversation = Conversation( + agent=Agent( + llm=llm, + tools=[], + include_default_tools=["FinishTool", "ThinkTool"], + ), + workspace=str(tmp_path), + visualizer=None, + secrets={"TEST_TOKEN": LookupSecret(url=f"http://127.0.0.1:{port}/secret")}, + ) + try: + conversation.send_message("hello") + await asyncio.wait_for(conversation.arun(), timeout=10) + assert requested.is_set() + assert any( + isinstance(event, ObservationEvent) and event.tool_name == "think" + for event in conversation.state.events + ) + registry = conversation.state.secret_registry + assert ( + registry.mask_secrets_in_output("loopback-secret-value") + == "" + ) + finally: + await asyncio.to_thread(conversation.close) + server.close() + await server.wait_closed()