Skip to content

The agent that grows with you

feat(connectors): thread call ids to the gateway and log every connector outcome

Siddharth Balyanceaef9ad594c
diff --git a/agent/inline_tool_executors.py b/agent/inline_tool_executors.py
index deb0547d34a..75a497d3b59 100644
--- a/agent/inline_tool_executors.py
+++ b/agent/inline_tool_executors.py
@@ -185,6 +185,7 @@ def _manage_connections(agent, args: dict, ctx: InlineToolContext) -> Any:
result = manage_connections(
args, session_id=getattr(agent, "session_id", None), tool_call_id=ctx.tool_call_id,
+ turn_id=getattr(agent, "_current_turn_id", None) or None,
connection_callback=getattr(agent, "connection_callback", None),
connectors_available=gateway_config.connectors_available,
)
diff --git a/model_tools.py b/model_tools.py
index 2230a73f19f..30a9c4a1a5a 100644
--- a/model_tools.py
+++ b/model_tools.py
@@ -698,7 +698,8 @@ def _emit_post_tool_call_hook(
def _dispatch_bridge_tool(function_name: str, function_args: dict[str, Any],
- enabled_toolsets: Optional[list[str]], disabled_toolsets: Optional[list[str]]):
+ enabled_toolsets: Optional[list[str]], disabled_toolsets: Optional[list[str]],
+ ids: Optional[_CallIds] = None):
"""Handle a Tool Search bridge call (tool_search / tool_describe / tool_call).
None when *function_name* is not a bridge tool; ``(result, None)`` for a
@@ -719,10 +720,12 @@ def _dispatch_bridge_tool(function_name: str, function_args: dict[str, Any],
except Exception:
current_defs = []
args = function_args or {}
+ from tools.managed_gateway_identity import CallRef
+ call = CallRef(turn_id=ids.turn_id, tool_call_id=ids.tool_call_id) if ids else None
if function_name == ts.TOOL_SEARCH_NAME:
- return ts.dispatch_tool_search(args, current_tool_defs=current_defs), None
+ return ts.dispatch_tool_search(args, current_tool_defs=current_defs, call=call), None
if function_name == ts.TOOL_DESCRIBE_NAME:
- return ts.dispatch_tool_describe(args, current_tool_defs=current_defs), None
+ return ts.dispatch_tool_describe(args, current_tool_defs=current_defs, call=call), None
underlying_name, underlying_args, err = ts.resolve_underlying_call(args)
if err or not underlying_name:
return tool_error(err or "tool_call could not be resolved"), None
@@ -831,7 +834,7 @@ def _execute_tool(function_name: str, function_args: dict[str, Any], original_ar
def _dispatch(next_args: dict[str, Any]) -> Any:
from tools.connectors import dispatch_connector_call, is_connector_name
if is_connector_name(function_name):
- return dispatch_connector_call(function_name, next_args, ids.tool_call_id)
+ return dispatch_connector_call(function_name, next_args, ids.tool_call_id, ids.turn_id)
return registry.dispatch(function_name, next_args, **dispatch_kwargs)
with _approval_observability(ids):
@@ -899,7 +902,7 @@ def handle_function_call(
# Tool Search bridge: tool_search / tool_describe are catalog reads handled
# inline; tool_call is unwrapped so every downstream hook (pre/post, edit
# approval, guardrails) sees the real tool name, never the bridge.
- bridged = _dispatch_bridge_tool(function_name, function_args, enabled_toolsets, disabled_toolsets)
+ bridged = _dispatch_bridge_tool(function_name, function_args, enabled_toolsets, disabled_toolsets, ids)
if bridged is not None:
result, underlying = bridged
if underlying is None:
diff --git a/tests/tools/test_connector_accounts.py b/tests/tools/test_connector_accounts.py
index c9225c6827b..ea95bbe2d4d 100644
--- a/tests/tools/test_connector_accounts.py
+++ b/tests/tools/test_connector_accounts.py
@@ -53,7 +53,7 @@ def test_the_account_a_call_ran_under_reaches_the_model_on_both_dispatch_paths(m
monkeypatch.setattr(config, "connectors_available", lambda: True)
monkeypatch.setattr(bridge, "connectors_available", lambda: True)
invalidate_check_fn_cache()
- monkeypatch.setattr(bridge, "_default_client_factory", lambda: ConnectorClient(
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: ConnectorClient(
transport=_ExecuteTransport(), endpoint_resolver=lambda: "https://gateway.test",
header_provider=lambda _url: {"Authorization": "Bearer t"}))
kwargs = dict(enabled_toolsets=["connections"], session_id="s", skip_pre_tool_call_hook=True,
@@ -172,7 +172,7 @@ def test_try_again_on_a_named_account_repairs_the_account_it_minted_not_the_name
from tools.connectors.contract import Actor, TargetState
gateway = _Gateway()
- monkeypatch.setattr("tools.connectors.managed.managed_client", lambda: gateway)
+ monkeypatch.setattr("tools.connectors.managed.managed_client", lambda **_: gateway)
operation = op.ConnectionOperation([op.Target("gmail", "connector", "reconnect", alias="work")], session_key="s1")
operation.transition("gmail", TargetState.initiated, Actor.backend_watcher, connection_id="ca_work")
operation.transition("gmail", TargetState.failed, Actor.backend_watcher, detail="expired")
diff --git a/tests/tools/test_connector_bridge_wiring.py b/tests/tools/test_connector_bridge_wiring.py
index 0fcc06ec075..18b77b5be62 100644
--- a/tests/tools/test_connector_bridge_wiring.py
+++ b/tests/tools/test_connector_bridge_wiring.py
@@ -513,7 +513,7 @@ def _connectors_on(monkeypatch, client_factory):
monkeypatch.setattr(config, "connectors_available", lambda: True)
monkeypatch.setattr(bridge, "connectors_available", lambda: True)
- monkeypatch.setattr(bridge, "_default_client_factory", client_factory)
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: client_factory())
invalidate_check_fn_cache()
diff --git a/tests/tools/test_connector_dispatch_policy.py b/tests/tools/test_connector_dispatch_policy.py
index 20941305723..e2c29cba32d 100644
--- a/tests/tools/test_connector_dispatch_policy.py
+++ b/tests/tools/test_connector_dispatch_policy.py
@@ -54,7 +54,7 @@ def test_remote_entries_run_request_hook_and_execution_policies(monkeypatch, blo
wire.extend(planned)
return [{"data": "remote-ok", "error": None} for _ in planned]
- monkeypatch.setattr(bridge, "_default_client_factory", Client)
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: Client())
kwargs = dict(enabled_toolsets=["connections"], session_id="policy-session", tool_call_id="policy-call",
skip_pre_tool_call_hook=True, skip_tool_request_middleware=True,
skip_tool_execution_middleware=True)
@@ -94,7 +94,7 @@ def test_stop_during_a_connector_batch_leaves_unstarted_entries_unsent(monkeypat
set_interrupt(True) # /stop lands while the first entry is on the wire.
return [{"data": "remote-ok", "error": None} for _ in planned]
- monkeypatch.setattr(bridge, "_default_client_factory", Client)
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: Client())
calls = [{"name": f"connectors__gmail__{tool}", "arguments": {}}
for tool in ("FETCH_EMAILS", "SEND_EMAIL", "CREATE_DRAFT")]
try:
@@ -118,6 +118,6 @@ def test_disabled_connections_cannot_be_called_through_a_stale_schema(monkeypatc
monkeypatch.setattr(config, "connectors_available", lambda: False)
monkeypatch.setattr(managed, "managed_client",
- lambda: (_ for _ in ()).throw(AssertionError("disabled connector attempted I/O")))
+ lambda **_: (_ for _ in ()).throw(AssertionError("disabled connector attempted I/O")))
result = json.loads(registry.dispatch("manage_connections", {"action": "connect", "connectors": ["gmail"]}))
assert "not available" in result["error"]
diff --git a/tests/tools/test_connector_local_batches.py b/tests/tools/test_connector_local_batches.py
index a79c6acb27f..da51a29b680 100644
--- a/tests/tools/test_connector_local_batches.py
+++ b/tests/tools/test_connector_local_batches.py
@@ -25,7 +25,7 @@ def test_local_batches_rejected_before_any_entry_executes(monkeypatch, mixed):
assert name is None and "exactly one entry" in error
invoked = []
monkeypatch.setattr(model_tools.registry, "dispatch", lambda *a, **kw: invoked.append(a))
- monkeypatch.setattr(bridge, "_default_client_factory", lambda: invoked.append("gateway"))
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: invoked.append("gateway"))
result = json.loads(model_tools.handle_function_call(
"tool_call", {"calls": calls}, enabled_toolsets=["connections", "session_search", "todo"]))
assert "exactly one entry" in result["error"]
diff --git a/tests/tools/test_connector_session_scope.py b/tests/tools/test_connector_session_scope.py
index 7a69886e6e5..8c59823c9c3 100644
--- a/tests/tools/test_connector_session_scope.py
+++ b/tests/tools/test_connector_session_scope.py
@@ -45,8 +45,8 @@ def test_connector_scope_controls_schema_discovery_and_execution(monkeypatch, en
remote.append("status")
return []
- monkeypatch.setattr(bridge, "_default_client_factory", Client)
- monkeypatch.setattr(managed, "managed_client", Client)
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: Client())
+ monkeypatch.setattr(managed, "managed_client", lambda **_: Client())
scope = {"enabled_toolsets": enabled, "disabled_toolsets": disabled}
defs = model_tools.get_tool_definitions(**scope, quiet_mode=True, skip_tool_search_assembly=True)
assert ("manage_connections" in {td["function"]["name"] for td in defs}) is allowed
diff --git a/tests/tools/test_connector_wire_identity.py b/tests/tools/test_connector_wire_identity.py
new file mode 100644
index 00000000000..f09a1b13c5b
--- /dev/null
+++ b/tests/tools/test_connector_wire_identity.py
@@ -0,0 +1,174 @@
+"""Caller identity on connector requests: the User-Agent always, correlation ids only with consent,
+the gateway's request id logged on every outcome, and ``initiator`` on each connect path."""
+
+import json
+import logging
+
+import pytest
+
+from gateway.session_context import clear_session_vars, set_session_vars
+from hermes_cli.config import get_config_path
+from tools.connectors.gateway.client import ConnectorClient
+from tools.managed_gateway_identity import CallRef, connector_headers, user_agent
+
+
+class _Response:
+ def __init__(self, status, body, request_id="gw-req-1"):
+ self.status_code = status
+ self._body = body
+ self.headers = {"x-request-id": request_id}
+
+ def json(self):
+ return self._body
+
+
+class _Transport:
+ def __init__(self, *responses):
+ self.responses = list(responses)
+ self.sent = []
+
+ def request(self, method, url, *, headers=None, json=None, timeout=None):
+ self.sent.append({"url": url, "headers": dict(headers or {}), "json": json})
+ return self.responses.pop(0)
+
+
+def _client(transport, **kwargs):
+ return ConnectorClient(
+ transport=transport, endpoint_resolver=lambda: "https://gw.test",
+ header_provider=lambda url: {"Authorization": "Bearer t"}, **kwargs,
+ )
+
+
+def _consent(send: bool):
+ path = get_config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(f"telemetry:\n shared_metrics:\n enabled: true\n send: {str(send).lower()}\n")
+
+
+def platform():
+ tokens = []
+
+ def bind(name):
+ tokens.extend(set_session_vars(platform=name, cron_session=""))
+
+ yield bind
+ clear_session_vars(tokens)
+
+
[email protected](("bound", "surface"), [
+ ("", "cli"), ("tui", "tui"), ("desktop", "desktop"), ("telegram", "gateway"), ("api_server", "api"),
+])
+def test_user_agent_names_the_session_surface(platform, bound, surface):
+ if bound:
+ platform(bound)
+ agent = user_agent()
+ product, _, rest = agent.partition(" ")
+ assert product.startswith("hermes-agent/") and len(product) > len("hermes-agent/")
+ assert rest.startswith(f"({surface}; ") and rest.endswith(")")
+ assert rest[len(surface) + 3:-1] in {"linux", "macos", "windows", "unknown"}
+
+
[email protected]("send", [False, True])
+def test_correlation_ids_go_only_with_send_consent(send):
+ _consent(send)
+ transport = _Transport(_Response(200, {"schemas": {}}), _Response(200, {"schemas": {}}))
+ client = _client(transport, call=CallRef(turn_id="turn-1", tool_call_id="call-1"))
+ client.schemas(["GMAIL_SEND_EMAIL"])
+ client.schemas(["GMAIL_SEND_EMAIL"])
+
+ first, second = (sent["headers"] for sent in transport.sent)
+ assert first["User-Agent"].startswith("hermes-agent/")
+ correlation = {k for k in first if k.startswith("x-nous-hermes-") or k == "x-request-id"}
+ if not send:
+ assert correlation == set()
+ return
+ assert first["x-nous-hermes-turn"] == "turn-1" and first["x-nous-hermes-tool-call"] == "call-1"
+ assert first["x-request-id"] != second["x-request-id"] # one id per HTTP attempt
+ assert not any(k.startswith("x-hermes-") for k in first) # the gateway strips only x-nous-
+
+
+def test_session_header_is_the_conversation_root(monkeypatch):
+ from agent.portal_tags import reset_conversation_context, set_conversation_context
+
+ _consent(True)
+ token = set_conversation_context("root-session")
+ try:
+ assert connector_headers()["x-nous-hermes-session"] == "root-session"
+ finally:
+ reset_conversation_context(token)
+
+
+def test_gateway_request_id_is_logged_on_failure_and_success(caplog):
+ transport = _Transport(
+ _Response(200, {"schemas": {}}, request_id="ok-id"),
+ _Response(403, {"error": {"code": "TOOL_NOT_ALLOWED", "message": "no"}}, request_id="bad-id"),
+ )
+ client = _client(transport, call=CallRef(tool_call_id="call-9"))
+ with caplog.at_level(logging.DEBUG, logger="tools.managed_gateway_identity"):
+ client.schemas(["X"])
+ with pytest.raises(Exception) as raised:
+ client.schemas(["X"])
+ assert raised.value.request_id == "bad-id"
+ lines = [(r.levelno, r.getMessage()) for r in caplog.records]
+ assert (logging.DEBUG, "connector connectors.schemas 200 - request_id=ok-id dispatch=call-9") in lines
+ assert (logging.WARNING,
+ "connector connectors.schemas 403 TOOL_NOT_ALLOWED request_id=bad-id dispatch=call-9") in lines
+
+
+def test_a_not_yet_created_account_stays_debug(caplog):
+ transport = _Transport(_Response(404, {"error": "connection_not_found"}))
+ with caplog.at_level(logging.DEBUG, logger="tools.managed_gateway_identity"):
+ assert _client(transport).account_status("acct-1") is None
+ assert [r.levelno for r in caplog.records] == [logging.DEBUG]
+ assert "connectors.accounts 404" in caplog.records[0].getMessage()
+
+
+def _mint_ok(names):
+ return _Response(200, {"results": [{"connector": n, "status": "initiated", "connectUrl": "https://l"} for n in names]})
+
+
+def test_each_connect_path_names_its_initiator(monkeypatch):
+ from tools.connectors import managed
+ from tools.connectors.contract import Actor, TargetState
+ from tools.connectors.operation import ConnectionOperation, Target
+ from tools.connectors.run import reissue
+
+ transport = _Transport(_mint_ok(["gmail"]), _mint_ok(["gmail"]), _mint_ok(["gmail"]))
+ monkeypatch.setattr(managed, "ensure_guest_identity", lambda: None)
+ real = ConnectorClient
+ monkeypatch.setattr("tools.connectors.gateway.client.ConnectorClient", lambda **kw: real(
+ transport=transport, endpoint_resolver=lambda: "https://gw.test",
+ header_provider=lambda url: {"Authorization": "Bearer t"}, **kw))
+
+ for initiator in (managed.AGENT_TOOL, managed.DESKTOP_PAGE):
+ operation = ConnectionOperation([Target("gmail", "connector", "connect")])
+ client = managed.managed_client() if initiator == managed.AGENT_TOOL else managed.managed_client(initiator=initiator)
+ managed.mint(client, operation, ["gmail"], reinitiate=False, actor=Actor.backend_watcher)
+
+ operation.transition("gmail", TargetState.failed, Actor.backend_watcher)
+ assert reissue(operation, ["gmail"]) is None # the card's Try again
+
+ assert [sent["json"]["initiator"] for sent in transport.sent] == ["agent_tool", "desktop_page", "card_retry"]
+
+
+def test_operation_logs_open_transitions_and_settle(caplog):
+ from tools.connectors import live
+ from tools.connectors.contract import Actor, SettleReason, TargetState
+ from tools.connectors.operation import ConnectionOperation, Target
+
+ operation = ConnectionOperation([Target("gmail", "connector", "connect")], session_key="s-log")
+ with caplog.at_level(logging.INFO, logger="tools.connectors"):
+ live.open(operation)
+ operation.transition("gmail", TargetState.initiated, Actor.backend_watcher)
+ operation.transition("gmail", TargetState.connected, Actor.backend_watcher)
+ operation.settle(SettleReason.all_resolved)
+ live.close(operation)
+ op = operation.op_id
+ assert [r.getMessage() for r in caplog.records if r.levelno == logging.INFO] == [
+ f"connection op {op} opened: connector:gmail:connect",
+ f"connection op {op}: gmail pending -> initiated by backend_watcher",
+ f"connection op {op}: gmail initiated -> connected by backend_watcher",
+ f"connection op {op} settled by all_resolved: gmail=connected",
+ ]
+ assert json.dumps(operation.snapshot()) # snapshot still serializes
diff --git a/tests/tools/test_connectors_guest_on_first_use.py b/tests/tools/test_connectors_guest_on_first_use.py
index ce24df17159..cdfae3cb04f 100644
--- a/tests/tools/test_connectors_guest_on_first_use.py
+++ b/tests/tools/test_connectors_guest_on_first_use.py
@@ -35,6 +35,9 @@ def test_first_hosted_action_creates_one_connectors_only_guest(nas, monkeypatch)
class Gateway:
"""Reads the bearer the way the real gateway client does on every request."""
+ def __init__(self, **_):
+ pass
+
def list_connectors(self, *, timeout=None):
bearers.append(read_nous_access_token())
return [{"connector": "gmail", "enabled": True, "connected": False}]
@@ -68,7 +71,7 @@ def test_tool_search_without_an_identity_sends_nothing(nas, monkeypatch):
from tools.connectors.tool import MANAGE_CONNECTIONS_SCHEMA
from tools.tool_search import dispatch_tool_search
- def no_client():
+ def no_client(**_):
raise AssertionError("no gateway client may be built before an identity exists")
monkeypatch.setattr("tools.connectors.gateway.client.ConnectorClient", no_client)
diff --git a/tests/tui_gateway/test_connector_accounts_rpc.py b/tests/tui_gateway/test_connector_accounts_rpc.py
index 4c332cb1ddf..259b60e79e7 100644
--- a/tests/tui_gateway/test_connector_accounts_rpc.py
+++ b/tests/tui_gateway/test_connector_accounts_rpc.py
@@ -55,6 +55,9 @@ def test_account_connect_with_an_alias_mints_that_account(monkeypatch):
minted = threading.Event()
class Client:
+ def __init__(self, **_):
+ pass
+
def connections(self, names, *, reinitiate=False, alias=None, **_):
mints.append((tuple(names), reinitiate, alias))
minted.set()
@@ -89,6 +92,9 @@ def test_a_session_retry_for_another_account_does_not_re_mint_the_open_one(monke
mints = []
class Client:
+ def __init__(self, **_):
+ pass
+
def connections(self, names, **kwargs):
mints.append((tuple(names), kwargs.get("alias")))
return {"results": []}
@@ -126,6 +132,9 @@ def test_a_session_retry_with_the_open_accounts_id_reissues_it(monkeypatch):
mints = []
class Client:
+ def __init__(self, **_):
+ pass
+
def connections(self, names, **kwargs):
mints.append((tuple(names), kwargs.get("connection_id")))
return {"results": [{"connector": n, "status": "initiated", "connect_url": "https://l/2",
diff --git a/tests/tui_gateway/test_connector_operation_rpc.py b/tests/tui_gateway/test_connector_operation_rpc.py
index 32f79c7a8f4..6f6b3b3a09d 100644
--- a/tests/tui_gateway/test_connector_operation_rpc.py
+++ b/tests/tui_gateway/test_connector_operation_rpc.py
@@ -191,6 +191,9 @@ def test_panel_connect_reissues_only_a_dead_link(owned, monkeypatch):
mints = []
class Client:
+ def __init__(self, **_):
+ pass
+
def connections(self, names, *, reinitiate=False, **_):
mints.append((tuple(names), reinitiate))
return {"results": [{"connector": n, "status": "initiated", "connect_url": f"https://l/{n}/2"} for n in names]}
@@ -221,6 +224,9 @@ def test_a_failed_reissue_leaves_the_row_failed_with_no_link(owned, monkeypatch,
operation.transition("notion", dead, actor, detail="vendor: nope")
class Client:
+ def __init__(self, **_):
+ pass
+
def connections(self, names, *, reinitiate=False, **_):
return {"results": [{"connector": n, "status": "failed", "status_reason": "vendor: still no"} for n in names]}
diff --git a/tools/connectors/account.py b/tools/connectors/account.py
index d169338c2d5..5374b8f3b41 100644
--- a/tools/connectors/account.py
+++ b/tools/connectors/account.py
@@ -41,9 +41,11 @@ def find_or_start_operation(
profile_home: str | None,
alias: str | None = None,
repair_id: str | None = None,
+ initiator: str | None = None,
) -> AccountOperationStart:
"""``alias`` names the one account of ``names[0]`` to connect; ``repair_id`` names the existing
- account a reconnect repairs. The caller passes one name with either."""
+ account a reconnect repairs. The caller passes one name with either. ``initiator`` goes on the
+ connect request; none leaves the gateway to record it as unknown."""
with _start_lock:
if operation := _matching_open_operation(names, alias=alias, repair_id=repair_id, profile_home=profile_home):
return AccountOperationStart(operation=operation, started=False)
@@ -54,7 +56,7 @@ def find_or_start_operation(
started = AccountOperationStart(operation=operation, started=True)
context = contextvars.copy_context()
thread = threading.Thread(
- target=lambda: context.run(_run, started, action),
+ target=lambda: context.run(_run, started, action, initiator),
daemon=True,
name="connector-account-operation",
)
@@ -67,11 +69,15 @@ def find_or_start_operation(
return started
-def _run(start: AccountOperationStart, action: str) -> None:
+def _run(start: AccountOperationStart, action: str, initiator: str | None) -> None:
+ from hermes_logging import clear_session_context, set_session_context
+
+ # Tag this thread's log lines with the operation, the way a turn thread carries its session.
+ set_session_context(start.operation.session_key)
try:
drive_operation(
start.operation,
- managed.managed_kind(managed.managed_client(), action, force=False),
+ managed.managed_kind(managed.managed_client(initiator=initiator), action, force=False),
connection_callback=lambda _payload: start.done.set(),
tick_seconds=managed.WATCH_TICK_SECONDS,
with_urls_in_result=False,
@@ -81,6 +87,7 @@ def _run(start: AccountOperationStart, action: str) -> None:
start.failed = True
finally:
start.done.set()
+ clear_session_context()
def wait_for_prepare(start: AccountOperationStart) -> bool:
diff --git a/tools/connectors/dispatch.py b/tools/connectors/dispatch.py
index f00b4f9af17..af615a89c79 100644
--- a/tools/connectors/dispatch.py
+++ b/tools/connectors/dispatch.py
@@ -8,11 +8,11 @@ from tools.connectors.gateway.config import MAX_CALLS_PER_DISPATCH
from tools.connectors.gateway.merge import assemble_results, fill_remote_failure, partition_calls
-def dispatch_connector_call(name, arguments, tool_call_id):
+def dispatch_connector_call(name, arguments, tool_call_id, turn_id=None):
from tools.connectors.gateway.bridge import run_remote
partition = partition_calls([{"name": name, "arguments": arguments}])
- entries = run_remote(partition.remote, tool_call_id, availability=None, client_factory=None)
+ entries = run_remote(partition.remote, tool_call_id, availability=None, client_factory=None, turn_id=turn_id)
entry = entries[0]
return json.dumps({key: value for key, value in entry.items() if key in {"response", "error", "account"}},
ensure_ascii=False)
diff --git a/tools/connectors/gateway/bridge.py b/tools/connectors/gateway/bridge.py
index a2455577c6f..2793e5d753c 100644
--- a/tools/connectors/gateway/bridge.py
+++ b/tools/connectors/gateway/bridge.py
@@ -8,6 +8,7 @@ from tools.connectors.gateway.config import connectors_available, guest_identity
from tools.connectors.gateway.errors import GatewayAuthError, GatewayUnavailable, ToolGatewayError
from tools.connectors.gateway.merge import fill_remote_failure, splice_remote_results
from tools.connectors.gateway.names import parse_connector_name, vendor_slug_candidates
+from tools.managed_gateway_identity import CallRef
logger = logging.getLogger(__name__)
@@ -50,13 +51,13 @@ def _leg_failure(exc: Exception) -> Optional[str]:
return UNREACHABLE
-def _default_client_factory():
+def _default_client_factory(call: Optional[CallRef] = None):
"""The real client for the model's read and execute legs. These never create an identity."""
from tools.connectors.gateway.client import ConnectorClient
if guest_identity_pending():
raise GatewayAuthError(NOT_SET_UP_MESSAGE, code=NOT_SET_UP)
- return ConnectorClient()
+ return ConnectorClient(call=call)
def connector_search_hits(
@@ -64,18 +65,19 @@ def connector_search_hits(
*,
availability: Optional[Callable[[], bool]] = None,
client_factory: Optional[Callable[[], Any]] = None,
+ call: Optional[CallRef] = None,
) -> ConnectorLeg:
try:
available = (availability or connectors_available)()
if not available or not queries:
return ConnectorLeg()
- client = (client_factory or _default_client_factory)()
+ client = client_factory() if client_factory else _default_client_factory(call)
return ConnectorLeg(payload=client.search(list(queries)) or {})
except GatewayUnavailable:
logger.debug("Connector search skipped: gateway dark")
return ConnectorLeg()
except Exception as exc:
- logger.debug("Connector search failed (D32): %s", exc)
+ logger.warning("Connector search failed (D32): %s", exc)
return ConnectorLeg(failure=_leg_failure(exc))
@@ -84,6 +86,7 @@ def connector_describe(
*,
availability: Optional[Callable[[], bool]] = None,
client_factory: Optional[Callable[[], Any]] = None,
+ call: Optional[CallRef] = None,
) -> ConnectorLeg:
try:
available = (availability or connectors_available)()
@@ -103,7 +106,7 @@ def connector_describe(
request_slugs.append(slug)
if not wanted:
return ConnectorLeg()
- client = (client_factory or _default_client_factory)()
+ client = client_factory() if client_factory else _default_client_factory(call)
response = client.schemas(request_slugs) or {}
schemas = response.get("schemas") if isinstance(response.get("schemas"), dict) else {}
tools: dict[str, Any] = {}
@@ -124,7 +127,7 @@ def connector_describe(
logger.debug("Connector describe skipped: gateway dark")
return ConnectorLeg()
except Exception as exc:
- logger.debug("Connector describe failed (D32): %s", exc)
+ logger.warning("Connector describe failed (D32): %s", exc)
return ConnectorLeg(failure=_leg_failure(exc))
@@ -134,6 +137,7 @@ def run_remote(
*,
availability: Optional[Callable[[], bool]],
client_factory: Optional[Callable[[], Any]],
+ turn_id: Optional[str] = None,
) -> list[dict[str, Any]]:
try:
available = (availability or connectors_available)()
@@ -157,13 +161,14 @@ def run_remote(
from tools.connectors.gateway.client import return_to_args
try:
- client = (client_factory or _default_client_factory)()
+ client = client_factory() if client_factory else _default_client_factory(
+ CallRef(turn_id=turn_id, tool_call_id=dispatch_id))
# A CONNECTION_REQUIRED link minted by this call is the user's next click, so the call names
# the surface that browser should come back to.
remote_results = client.execute(wire_planned, **return_to_args())
entries = splice_remote_results(planned, remote_results)
except ToolGatewayError as exc:
- logger.debug(
+ logger.warning(
"Connector execute for dispatch %s failed (%s): %s",
dispatch_id,
exc.code,
@@ -202,7 +207,7 @@ def run_remote(
fallback_results = client.execute(fallback_planned, **return_to_args())
fallback_entries = splice_remote_results(fallback_planned, fallback_results)
except ToolGatewayError as exc:
- logger.debug(
+ logger.warning(
"Connector execute fallback for dispatch %s failed (%s): %s",
dispatch_id,
exc.code,
diff --git a/tools/connectors/live.py b/tools/connectors/live.py
index 03a880b9dd1..05e9833494c 100644
--- a/tools/connectors/live.py
+++ b/tools/connectors/live.py
@@ -7,6 +7,7 @@ session's profile scope) resolves it through ``hermes_home_key``."""
from __future__ import annotations
+import logging
import threading
from typing import Dict, Optional, Tuple
@@ -14,6 +15,9 @@ from hermes_constants import get_process_hermes_home, hermes_home_key
from tools.connectors.operation import ConnectionOperation
+logger = logging.getLogger(__name__)
+
+
class OperationAlreadyOpen(RuntimeError):
def __init__(self, existing: ConnectionOperation):
super().__init__(f"session {existing.session_key!r} already has operation {existing.op_id} open")
@@ -42,6 +46,8 @@ def open(operation: ConnectionOperation) -> None:
if existing is not None and not existing.settled:
raise OperationAlreadyOpen(existing)
_open[key] = operation
+ logger.info("connection op %s opened: %s", operation.op_id,
+ ", ".join(f"{t.kind}:{t.name}:{t.action}" for t in operation.targets))
def current(session_key: str, *, profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
diff --git a/tools/connectors/managed.py b/tools/connectors/managed.py
index a1eb60d7181..60472d47014 100644
--- a/tools/connectors/managed.py
+++ b/tools/connectors/managed.py
@@ -45,16 +45,22 @@ NOTE = (
GUEST_SETUP_FAILED = "GUEST_SETUP_FAILED"
+# The connect request's ``initiator``: manage_connections, the Connectors page, the card's Try again.
+AGENT_TOOL = "agent_tool"
+DESKTOP_PAGE = "desktop_page"
+CARD_RETRY = "card_retry"
-def managed_client():
+
+def managed_client(*, initiator: Optional[str] = AGENT_TOOL, call: Optional[Any] = None):
"""The real gateway client for a user action. The first one creates the guest identity when the
- user has none: every hosted action is a request for an app."""
+ user has none: every hosted action is a request for an app. ``initiator`` names who asked, so
+ every link the client mints is attributed."""
from tools.connectors.gateway.client import ConnectorClient
from tools.connectors.gateway.errors import ToolGatewayError
if setup_error := ensure_guest_identity():
raise ToolGatewayError(setup_error, code=GUEST_SETUP_FAILED, retryable=True)
- return ConnectorClient()
+ return ConnectorClient(initiator=initiator, call=call)
def managed_kind(client: Any, action: str, force: bool) -> Kind:
@@ -132,7 +138,7 @@ def _status_for(client: Any, target: Target, *, timeout: float) -> Optional[dict
except RateLimited:
raise
except Exception as exc:
- logger.debug("connector account read failed for %s: %s", target.name, exc)
+ logger.warning("connector account read failed for %s: %s", target.name, exc)
return None
@@ -358,15 +364,19 @@ def run_managed_action(
client_factory: Optional[Callable[[], Any]] = None,
session_id: Optional[str] = None,
tool_call_id: Optional[str] = None,
+ turn_id: Optional[str] = None,
connection_callback: Optional[Callable[[dict[str, Any]], Optional[str]]] = None,
connectors_available: Optional[Callable[[], bool]] = None,
) -> str:
+ from tools.managed_gateway_identity import CallRef
+
if connectors_available is not None and not connectors_available():
return tool_error("Connectors are not available in this session.")
try:
if action == "rename":
return _rename_result(targets[0])
- client = (client_factory or managed_client)()
+ call = CallRef(turn_id=turn_id, tool_call_id=tool_call_id)
+ client = client_factory() if client_factory else managed_client(call=call)
if action == "status":
return _status_result(client, [t.name for t in targets])
if not targets:
@@ -385,7 +395,7 @@ def run_managed_action(
connection_callback=connection_callback, with_urls_in_result=False,
)
except Exception as exc:
- logger.debug("manage_connections %s failed: %s", action, exc)
+ logger.warning("manage_connections %s failed: %s", action, exc)
if getattr(exc, "code", None) == GUEST_SETUP_FAILED:
return tool_error(str(exc))
return tool_error(
diff --git a/tools/connectors/operation.py b/tools/connectors/operation.py
index 73adcae6d55..380b2249589 100644
--- a/tools/connectors/operation.py
+++ b/tools/connectors/operation.py
@@ -1,7 +1,9 @@
-"""One backend-owned connection operation per ``manage_connections`` call. Pure data, no I/O."""
+"""One backend-owned connection operation per ``manage_connections`` call. Pure data; its only
+I/O is one local log line per state change and per settle."""
from __future__ import annotations
+import logging
import threading
import time
import uuid
@@ -10,6 +12,8 @@ from typing import Any, Callable, ClassVar, Dict, List, Optional
from tools.connectors.contract import Actor, SettleReason, TargetState, allowed, resolves
+logger = logging.getLogger(__name__)
+
# Not a config key: a user-tunable wait with clamp rails was a foot-gun (PR1 shipped one, unmerged).
OPERATION_DEADLINE_SECONDS = 300.0
@@ -135,6 +139,7 @@ class ConnectionOperation:
if extra:
target.extra = dict(extra)
snapshot = self._bump_locked()
+ logger.info("connection op %s: %s %s -> %s by %s", self.op_id, name, change["from"], to.value, actor.value)
self.wake.set()
self._changed(change, snapshot)
return change
@@ -197,6 +202,8 @@ class ConnectionOperation:
if not target.resolved:
target.state = TargetState.not_connected
self._settled_snapshot = self._bump_locked()
+ outcomes = ", ".join(f"{t.name}={t.state.value}" for t in self.targets)
+ logger.info("connection op %s settled by %s: %s", self.op_id, by.value, outcomes)
self.wake.set()
self._changed(None, self._settled_snapshot)
return True
diff --git a/tools/connectors/run.py b/tools/connectors/run.py
index 444ec3aa2c9..041cf06f53c 100644
--- a/tools/connectors/run.py
+++ b/tools/connectors/run.py
@@ -41,7 +41,7 @@ class Kind:
note: str
-def reissue(operation: ConnectionOperation, names: Sequence[str]) -> Optional[str]:
+def reissue(operation: ConnectionOperation, names: Sequence[str], *, initiator: Optional[str] = None) -> Optional[str]:
from tools.connectors.contract import Actor, TargetState, allowed
targets = [operation.target(name) for name in names]
@@ -57,9 +57,9 @@ def reissue(operation: ConnectionOperation, names: Sequence[str]) -> Optional[st
if any(allowed(target.kind, target.state, TargetState.initiated) is None for target in targets):
return NOT_ALLOWED
if targets[0].kind == "connector":
- from tools.connectors.managed import managed_client, mint
+ from tools.connectors.managed import CARD_RETRY, managed_client, mint
- mint(managed_client(), operation, stale, reinitiate=True, actor=Actor.user)
+ mint(managed_client(initiator=initiator or CARD_RETRY), operation, stale, reinitiate=True, actor=Actor.user)
return None
from tools.connectors import catalog
from tools.connectors.mcp import retry
diff --git a/tools/connectors/search.py b/tools/connectors/search.py
index 1789ce3e094..2e49c78c858 100644
--- a/tools/connectors/search.py
+++ b/tools/connectors/search.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import functools
import logging
from typing import Any, Dict, Iterable, List, Optional, Tuple
@@ -51,11 +52,14 @@ def _connector_entry(name: str, connector: str, slug: str, schema: dict[str, Any
def connector_entries_by_group(
queries: list[str],
connector_search: Optional[Any] = None,
+ call: Optional[Any] = None,
) -> tuple[list[list[CatalogEntry]], Optional[str]]:
per_query: list[list[CatalogEntry]] = [[] for _ in queries]
try:
if connector_search is None:
- from tools.connectors.gateway.bridge import connector_search_hits as connector_search
+ from tools.connectors.gateway.bridge import connector_search_hits
+
+ connector_search = functools.partial(connector_search_hits, call=call)
leg = connector_search([{"use_case": q} for q in queries])
if leg.failure:
return per_query, leg.failure
@@ -93,7 +97,7 @@ def connector_entries_by_group(
picked[name] = (slug, _connector_entry(name, str(schema["connector"]), slug, schema))
per_query[position] = [entry for _, entry in picked.values()]
except Exception:
- logger.debug("connector search merge failed (D32)", exc_info=True)
+ logger.warning("connector search merge failed (D32)", exc_info=True)
return [[] for _ in queries], UNREACHABLE
return per_query, None
@@ -102,13 +106,16 @@ def remote_schemas_for(
names: list[str],
current_tool_defs: list[dict[str, Any]],
connector_describe: Optional[Any] = None,
+ call: Optional[Any] = None,
) -> tuple[dict[str, dict[str, Any]], Optional[str]]:
connector_names = [n for n in names if is_connector_name(n)]
if not connector_names or not connections_in_scope(current_tool_defs):
return {}, None
try:
if connector_describe is None:
- from tools.connectors.gateway.bridge import connector_describe
+ from tools.connectors.gateway.bridge import connector_describe as describe
+
+ connector_describe = functools.partial(describe, call=call)
leg = connector_describe(connector_names)
if leg.failure:
return {}, leg.failure
@@ -117,5 +124,5 @@ def remote_schemas_for(
return tools, None
return {}, (UNREACHABLE if leg.payload else None)
except Exception:
- logger.debug("connector describe merge failed (D32)", exc_info=True)
+ logger.warning("connector describe merge failed (D32)", exc_info=True)
return {}, UNREACHABLE
diff --git a/tools/connectors/tool.py b/tools/connectors/tool.py
index 59528d18fc6..b916a96d3a4 100644
--- a/tools/connectors/tool.py
+++ b/tools/connectors/tool.py
@@ -21,6 +21,7 @@ def manage_connections(
mcp_backend: Optional[Any] = None,
session_id: Optional[str] = None,
tool_call_id: Optional[str] = None,
+ turn_id: Optional[str] = None,
connection_callback: Optional[Callable[[dict[str, Any]], Optional[str]]] = None,
connectors_available: Optional[Callable[[], bool]] = None,
) -> str:
@@ -40,7 +41,7 @@ def manage_connections(
return run_managed_action(
action, managed, args,
- client_factory=client_factory, session_id=session_id, tool_call_id=tool_call_id,
+ client_factory=client_factory, session_id=session_id, tool_call_id=tool_call_id, turn_id=turn_id,
connection_callback=connection_callback, connectors_available=connectors_available,
)
@@ -154,7 +155,8 @@ registry.register(
# a cached schema agree. Read as a module attribute so tests patch
# ``gateway.config.connectors_available`` at one seam.
handler=lambda args, **kw: manage_connections(
- args, session_id=kw.get("session_id"), connectors_available=gateway_config.connectors_available,
+ args, session_id=kw.get("session_id"), tool_call_id=kw.get("tool_call_id"),
+ connectors_available=gateway_config.connectors_available,
),
check_fn=lambda: gateway_config.connectors_available(),
emoji="🔗",
diff --git a/tools/tool_search.py b/tools/tool_search.py
index d17a3e289dc..c17c91305a3 100644
--- a/tools/tool_search.py
+++ b/tools/tool_search.py
@@ -429,7 +429,7 @@ def _string_list_arg(args: dict[str, Any], key: str, *, dedupe: bool, max_items:
def dispatch_tool_search(args: dict[str, Any], *, current_tool_defs: list[dict[str, Any]],
config: Optional[ToolSearchConfig] = None,
- connector_search: Optional[Any] = None) -> str:
+ connector_search: Optional[Any] = None, call: Optional[Any] = None) -> str:
config = config or load_config()
queries, err = _string_list_arg(args, "queries", dedupe=False, max_items=_MAX_QUERIES_PER_CALL,
retry_hint="Retry with fewer, more targeted queries.")
@@ -443,7 +443,7 @@ def dispatch_tool_search(args: dict[str, Any], *, current_tool_defs: list[dict[s
hosted_failure: Optional[str] = None
if connections_in_scope(current_tool_defs):
remote_entries, hosted_failure = connector_entries_by_group(
- queries, connector_search=connector_search)
+ queries, connector_search=connector_search, call=call)
results: list[dict[str, Any]] = []
tools_map: dict[str, dict[str, Any]] = {}
available_sources = _available_source_summary(catalog)
@@ -472,7 +472,7 @@ def dispatch_tool_search(args: dict[str, Any], *, current_tool_defs: list[dict[s
def dispatch_tool_describe(args: dict[str, Any], *, current_tool_defs: list[dict[str, Any]],
config: Optional[ToolSearchConfig] = None,
- connector_describe: Optional[Any] = None) -> str:
+ connector_describe: Optional[Any] = None, call: Optional[Any] = None) -> str:
config = config or load_config_readonly()
names, err = _string_list_arg(
args, "names", dedupe=True, max_items=_MAX_DESCRIBE_NAMES_PER_CALL,
@@ -481,7 +481,7 @@ def dispatch_tool_describe(args: dict[str, Any], *, current_tool_defs: list[dict
return err
deferrable = _deferrable_in(current_tool_defs)
by_name = {name: _fn(td) for td, name in zip(deferrable, _tool_def_names(deferrable)) if name}
- remote_schemas, hosted_failure = remote_schemas_for(names, current_tool_defs, connector_describe)
+ remote_schemas, hosted_failure = remote_schemas_for(names, current_tool_defs, connector_describe, call=call)
tools: dict[str, dict[str, Any]] = {}
not_found: list[str] = []
diff --git a/tui_gateway/methods_connectors.py b/tui_gateway/methods_connectors.py
index 25a4b253756..6d5c0d051ed 100644
--- a/tui_gateway/methods_connectors.py
+++ b/tui_gateway/methods_connectors.py
@@ -207,6 +207,7 @@ def _account_connector_list(rid):
def _account_connector_connect(rid, request):
from tools.connectors import account
+ from tools.connectors.managed import DESKTOP_PAGE
from tui_gateway.connector_payload import connector_ui_payload
from tui_gateway.contracts.connectors import ConnectorErrorReason
@@ -214,13 +215,13 @@ def _account_connector_connect(rid, request):
try:
start = account.find_or_start_operation(
request.connectors, action=action, profile_home=_account_home(request), alias=request.alias,
- repair_id=request.connection_id)
+ repair_id=request.connection_id, initiator=DESKTOP_PAGE)
if not start.started:
from tools.connectors.contract import TargetState
targets = [start.operation.target(name) for name in request.connectors]
if any(target.state in (TargetState.failed, TargetState.expired) for target in targets):
- return _reissue(rid, start.operation, {"connectors": request.connectors})
+ return _reissue(rid, start.operation, {"connectors": request.connectors}, initiator=DESKTOP_PAGE)
return _ok(rid, connector_ui_payload(_operation_view(start.operation)))
if not account.wait_for_prepare(start):
return _ok(rid, connector_ui_payload(_operation_view(start.operation)))
@@ -262,7 +263,7 @@ def _connector_rpc(rid, params, action):
_current_runtime_session_record.reset(runtime_token)
-def _reissue(rid, operation, args):
+def _reissue(rid, operation, args, *, initiator=None):
from tools.connectors.run import (
LINK_STILL_VALID,
MIXED_KINDS,
@@ -275,7 +276,7 @@ def _reissue(rid, operation, args):
from tui_gateway.connector_payload import connector_ui_payload
from tui_gateway.contracts.connectors import ConnectorErrorReason
- reason = reissue(operation, args["connectors"])
+ reason = reissue(operation, args["connectors"], initiator=initiator)
if reason == UNKNOWN_TARGET:
return _connector_rpc_error(rid, 4004, ConnectorErrorReason.unknown_target, "No such target on the open operation.")
if reason == MIXED_KINDS: