Skip to content

The agent that grows with you

fix(vault): automatic one-time codes run inside the backend's fill_context

Teknium5c4c661ae6c7
diff --git a/tests/tools/test_browser_vault_plugin_isolation.py b/tests/tools/test_browser_vault_plugin_isolation.py
index 1fbdee22a88..c03859d0680 100644
--- a/tests/tools/test_browser_vault_plugin_isolation.py
+++ b/tests/tools/test_browser_vault_plugin_isolation.py
@@ -364,3 +364,68 @@ def test_a_plugin_breaking_its_contract_only_breaks_itself(vault_home, page):
assert listed["errors"] == [{"backend": "broken", "error": "The broken login backend returned an invalid value."}]
out = json.loads(_vault({"action": "fill", "handle": "broken:1"}))
assert out["error_type"] == "backend_unavailable" and page.secret_evals == []
+
+
+# A manager session that only exists inside the backend's fill_context (an unlocked CLI session, a lock).
+_CONTEXT_BACKEND = '''
+import contextlib
+from agent.vault_backends.base import LoginBackend
+from agent.vault_store import VaultItemMeta
+
+class Backend(LoginBackend):
+ name, prefix, display_name = "ctxvault", "ctxvault:", "Ctx"
+
+ def __init__(self):
+ self.calls, self.active = [], False
+
+ @contextlib.contextmanager
+ def fill_context(self):
+ self.calls.append("enter")
+ self.active = True
+ try:
+ yield
+ finally:
+ self.active = False
+ self.calls.append("exit")
+
+ def list_items(self):
+ return [self.get_meta("ctxvault:1")]
+
+ def get_meta(self, handle):
+ return VaultItemMeta(id=handle, kind="login", label="Ctx", origin="https://example.com",
+ created_at="2026-01-01T00:00:00Z", has_otp=True)
+
+ def resolve_password(self, handle):
+ return "unused"
+
+ def resolve_otp(self, handle):
+ self.calls.append("resolve_otp")
+ if not self.active:
+ raise RuntimeError("manager session is closed")
+ return "{code}"
+'''
+
+
+def test_plugin_otp_is_minted_and_written_inside_the_backends_fill_context(vault_home, page, monkeypatch):
+ from tools import browser_vault_tool
+
+ code = "739251"
+ home, _local, load = vault_home
+ _write_plugin(home, "ctx_vault", _CONTEXT_BACKEND.format(code=code), " ctx.register_login_backend(Backend())\n")
+ load(["ctx_vault"], {"ctxvault": "true"})
+ backend = _backend("ctxvault")
+ otp_field = {"autocomplete": "one-time-code", "formIndex": 0, "index": 0, "label": "", "name": "otp", "type": "text"}
+ monkeypatch.setattr(browser_vault_tool, "_eval_js", lambda task_id, expr: {"success": True, "result": json.dumps([otp_field])})
+
+ def secret_eval(task_id, expression):
+ backend.calls.append("write")
+ page.secret_evals.append(expression)
+ return {"success": True, "result": json.dumps({"filled": 1})}
+
+ monkeypatch.setattr(browser_vault_tool, "_eval_js_secret", secret_eval)
+
+ out = json.loads(_vault({"action": "enter_code", "handle": "ctxvault:1"}))
+ assert out["success"] is True and out["source"] == "ctxvault", out
+ assert backend.calls == ["enter", "resolve_otp", "write", "exit"]
+ assert code in page.secret_evals[0] and code not in json.dumps(out)
+
diff --git a/tools/browser_vault_context.py b/tools/browser_vault_context.py
index be6fa71cf3a..095c7698e75 100644
--- a/tools/browser_vault_context.py
+++ b/tools/browser_vault_context.py
@@ -1,4 +1,5 @@
-"""Run a vault fill inside the selected backend's ``fill_context`` (a plugin backend's lock/snapshot).
+"""Run a vault fill, or an automatic one-time-code entry, inside the selected backend's ``fill_context``
+(a plugin backend's lock/snapshot/manager session).
A plugin backend's failure arrives as ``PluginBackendError`` (fixed text, see
``agent/vault_backends/plugin.py``) and becomes a typed refusal; built-in backends behave as before.
@@ -22,3 +23,22 @@ def with_backend_fill_context(fill):
except PluginBackendError as exc:
return json.dumps({"success": False, "error_type": "backend_unavailable", "error": str(exc)})
return wrapped
+
+
+def write_backend_code(backend, handle, write):
+ """Mint the backend's one-time code for ``handle`` and ``write`` it, both inside ``fill_context``, as a
+ password fill is. ``None`` when the backend has no code (or failed to give one): the caller asks the user."""
+ from agent.vault_backends.plugin import PluginBackendError
+
+ written = None
+ try:
+ with backend.fill_context():
+ try:
+ code = backend.resolve_otp(handle)
+ except Exception: # health: allow BLE001 -- no automatic code; the user is asked instead
+ code = None
+ if code:
+ written = write(code)
+ except PluginBackendError: # the plugin's context failed to open or close; a code already written stands
+ pass
+ return written
diff --git a/tools/browser_vault_tool.py b/tools/browser_vault_tool.py
index 3e7ba6e48a8..c2ab5f0685d 100644
--- a/tools/browser_vault_tool.py
+++ b/tools/browser_vault_tool.py
@@ -379,43 +379,39 @@ def browser_vault_enter_code(handle: str = "", task_id: Optional[str] = None) ->
"error": ("No one-time-code field on the current page. If the site wants a passkey, hardware key or "
"an approval tap in an app, tell the user to complete it on their device and wait for the page to move on.")})
- code: Optional[str] = None
- source = "user"
- if meta is not None:
- try:
- code = backend.resolve_otp(handle)
- except Exception:
- code = None
- if code:
- source = backend.name
+ def write(code: str, source: str) -> str:
+ register_vault_redaction_value(code)
+ fills = build_otp_fills(otp_controls, code)
+ result = _eval_js_secret(effective_task_id, build_fill_js(fills, expected_origin=origin, nonce=nonce))
+ del code
+ if not result.get("success"):
+ return json.dumps({"success": False, "error": str(result.get("error") or "fill failed")[:200]})
+ parsed = _parse_json_result(result.get("result"))
+ if isinstance(parsed, str):
+ parsed = _parse_json_result(parsed)
+ if isinstance(parsed, dict) and parsed.get("refused") == "origin_changed":
+ return json.dumps({"success": False, "error_type": "origin_changed", "error": "The page navigated before the code could be entered. Nothing was written."})
+ filled = int(parsed.get("filled", 0)) if isinstance(parsed, dict) else 0
+ return json.dumps({"success": bool(filled), "filled_fields": filled, "origin": origin, "source": source,
+ "next": "Submit the form (many sites auto-submit when the last digit lands)."})
+
+ if meta is not None: # a saved login on its bound origin: mint + write inside the backend's fill_context
+ written = write_backend_code(backend, handle, lambda code: write(code, backend.name))
+ if written is not None:
+ return written
+ prompt = get_code_prompt_callback()
+ if prompt is None or not can_prompt_here():
+ return json.dumps({"success": False, "error_type": "prompt_unavailable",
+ "error": (f"{site} asks for a one-time code and this session cannot ask the user (headless/cron/API). "
+ "Save an authenticator key for this login so codes can be generated automatically.")})
+ code = (prompt(site, "") or "").strip().replace(" ", "").replace("-", "")
if not code:
- prompt = get_code_prompt_callback()
- if prompt is None or not can_prompt_here():
- return json.dumps({"success": False, "error_type": "prompt_unavailable",
- "error": (f"{site} asks for a one-time code and this session cannot ask the user (headless/cron/API). "
- "Save an authenticator key for this login so codes can be generated automatically.")})
- code = (prompt(site, "") or "").strip().replace(" ", "").replace("-", "")
- if not code:
- return json.dumps({"success": False, "error_type": "code_declined",
- "error": "The user did not enter a code. Do not ask again this turn."})
-
- register_vault_redaction_value(code)
- fills = build_otp_fills(otp_controls, code)
- result = _eval_js_secret(effective_task_id, build_fill_js(fills, expected_origin=origin, nonce=nonce))
- del code
- if not result.get("success"):
- return json.dumps({"success": False, "error": str(result.get("error") or "fill failed")[:200]})
- parsed = _parse_json_result(result.get("result"))
- if isinstance(parsed, str):
- parsed = _parse_json_result(parsed)
- if isinstance(parsed, dict) and parsed.get("refused") == "origin_changed":
- return json.dumps({"success": False, "error_type": "origin_changed", "error": "The page navigated before the code could be entered. Nothing was written."})
- filled = int(parsed.get("filled", 0)) if isinstance(parsed, dict) else 0
- return json.dumps({"success": bool(filled), "filled_fields": filled, "origin": origin, "source": source,
- "next": "Submit the form (many sites auto-submit when the last digit lands)."})
+ return json.dumps({"success": False, "error_type": "code_declined",
+ "error": "The user did not enter a code. Do not ask again this turn."})
+ return write(code, "user")
-from tools.browser_vault_context import with_backend_fill_context
+from tools.browser_vault_context import with_backend_fill_context, write_backend_code
@with_backend_fill_context
diff --git a/website/docs/developer-guide/browser-vault-plugin.md b/website/docs/developer-guide/browser-vault-plugin.md
index c90e9dfbfed..bf93baf1866 100644
--- a/website/docs/developer-guide/browser-vault-plugin.md
+++ b/website/docs/developer-guide/browser-vault-plugin.md
@@ -98,7 +98,9 @@ plugins Hermes offers this seam to; it is not a sandbox either.
`fill_context()` defaults to a no-op. A backend may return its own context manager to lock fills and
freeze credential-reference/origin configuration for the whole operation, so a reload cannot pair old
-metadata with a newly configured secret. Hermes enters it only for fills of your own handles, calls it
+metadata with a newly configured secret. Hermes enters it only for fills of your own handles (a
+password fill, and an automatic one-time code for `browser_vault action=enter_code`, both through the
+in-page write), calls it
with no arguments, and exits it with `(None, None, None)`, so you never see the core's exception. Release
on exit even when the fill failed. A fill lock does not serialize unrelated browser navigation.