Files
hermes-agent/tools/connectors/run.py
Siddharth Balyan 7b0f11fc7b feat(connectors): no guest on page open, connector sign-in offer (#143248)
* feat(connectors): list hosted apps without creating a guest identity

Opening the desktop Connectors page used to create a Nous guest identity:
connectors.list, connectors.catalog, connectors.accounts and
connectors.policy.get each created one before answering, because the
Portal's catalog route needs a token. A user who only looked at the page
got an identity anyway.

While there is no identity yet (and one may still be created), those four
reads now answer without one: the catalog from a snapshot that ships with
Hermes, an empty connector list, no accounts and no rules. Connecting an
app still creates the identity, as before.

scripts/refresh_connector_catalog.py rewrites the snapshot from a
signed-in install. It leaves logos out: no client draws them.

* feat(free-tier): sign-in offer for guests who connected apps

Every free-tier sign-in offer keyed on the welcome trial, so a user on
their own model key who connected apps through a guest identity never saw
one.

The offer record now tracks two offers on the same schedule. `trial` is
unchanged. `connector` is for a guest without the trial that has connected
an app: each app that finishes connecting sets `has_connected_app` on the
guest state (so it dies with the guest) and counts as a finished task.
free_tier.status (still a pure local read) adds connector_nudge_due_in, and
free_tier.claim_nudge takes a `kind`.

The desktop reads the connector offer whether or not the trial is
available, re-reads the status after a turn or a page connect, and shows
connector copy instead of the free-allowance copy. After a page connect
settles it also re-reads the catalog and rules, so the bundled catalog
from before the identity existed is replaced by the account's own.

* fix(connectors): point the sign-in hint at `hermes auth upgrade`

`hermes connectors` told users to run `hermes login`, which no longer
exists. Both hints now say "Run `hermes auth upgrade` to sign in."

* feat(connectors): read the public catalog with no token; one guest rule per entry point

The bundled catalog snapshot listed apps a new guest cannot connect and
went stale whenever the catalog changed. With no token, the Connectors
page now reads the Nous Portal's public catalog route
(GET /api/v1/connectors/catalog/public), sent with no Authorization and
parsed with the existing catalog model. Once a token exists the page reads
the signed-in route, as before.

Whether an entry point may create the guest identity is now declared once
per entry point instead of checked inside handlers:
- managed_client(creates_guest=...) is required: connect (page, agent,
  card retry) and the explicit lists (CLI `hermes connectors list`, agent
  manage_connections status/display) pass True, unchanged.
- account RPCs declare creates_guest on _account_method: catalog,
  accounts and policy.get never create one; tools and the account writes
  still do.
- the page's connectors.list never creates one; connect does.

With no token the page reads give true answers: public catalog, empty
connected list, no accounts. The invented "unrestricted" policy is gone:
the desktop asks for rules only once the list has rows, which needs a
token, and policy.get without one refuses with sign-in-required.

Deleted: the bundled snapshot, its refresh script, and the no-identity
stubs.

* fix(connectors): CI and review round: older backends, outside connects, link connects, guest opt-out

- CI: test_legacy_fallback_ticket_profile_verbs faked managed_client with
  no arguments and gave the secondary profile no token, so the page list
  (now token-gated, creates_guest=False) never reached it. The fake takes
  the new keyword and the profile holds a token.
- Older backends: a trial claim sends free_tier.claim_nudge with no
  params again. An older backend rejects the unknown `kind` key and would
  have dropped the trial offer; the new backend defaults to the trial.
  Only the connector claim sends `kind`.
- Outside connects: while the page's list is empty (no identity), every
  finished turn or connect re-reads the list and catalog. An agent connect
  in a chat then moves the page to the signed-in routes and its rules.
- Link connects: an agent status read that sees a connected app on a
  guest without the flag arms the connector offer, so messaging and
  one-shot connects (no operation watcher) count too.
- Opt-out: the connector offer requires nous.guest to be allowed.

* fix(connectors): the Connectors page list arms the connector offer too

A guest whose apps were connected by an older Hermes has no has_connected_app flag, and only the operation watcher or the agent's status read set it. The page's connectors.list now passes its rows to note_connected_apps_seen, which owns the any-connected check for both list reads.

* fix(connectors): review round 3: accounts after an outside connect, retryable offer record

- An identity created outside the page (an agent connect in a chat) now also re-reads the accounts cached while there was none, so the new account row, rename and remove show up.
- note_app_connected records the connector task before it sets has_connected_app. The flag ends list-read sightings, so a failed schedule write no longer leaves the offer unarmed for good.
2026-10-23 06:08:27 +05:30

197 lines
7.5 KiB
Python

"""The one lifecycle every ``manage_connections`` operation follows, whatever the target kind.
``run_operation`` mints the op, registers it in ``live``, lets the kind prepare its targets (a
managed mint, an MCP catalog check), emits the card through the session callback, then loops:
sleep on ``op.wake`` for at most one tick, run the kind's ``observe`` hook, settle when every
target is resolved or the deadline passes. ``connection.respond`` reaches the loop by transitioning
the op through ``live`` and setting ``wake``; ``/stop`` sets the thread interrupt flag."""
from __future__ import annotations
import json
import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Sequence
from tools.connectors import live
from tools.connectors.contract import SettleReason
from tools.connectors.operation import ConnectionOperation, Target
UNKNOWN_TARGET = "unknown_target"
MIXED_KINDS = "mixed_kinds"
LINK_STILL_VALID = "link_still_valid"
SETTLED = "settled"
NOT_ALLOWED = "not_allowed"
REFUSED = "refused"
WATCH_INTERVAL_SECONDS = 5.0
# The interrupt flag has no wake hook, so the tick sleep is sliced and the flag read each slice.
_WAKE_SLICE_SECONDS = 0.25
Callback = Callable[[dict[str, Any]], Optional[str]]
@dataclass
class Kind:
"""Per-kind hooks. ``prepare`` runs once before the card; ``observe`` runs every tick and may
transition targets; ``note`` is the model-facing guidance appended to the settled result."""
prepare: Callable[[ConnectionOperation], None]
observe: Callable[[ConnectionOperation], None]
note: str
# Replaces the per-target result for an operation the model reads differently (the display card).
result: Optional[Callable[[ConnectionOperation], dict[str, Any]]] = None
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]
if any(target is None for target in targets):
return UNKNOWN_TARGET
if len({target.kind for target in targets}) != 1:
return MIXED_KINDS
stale = [target.name for target in targets if target.state in (TargetState.failed, TargetState.expired)]
if len(stale) != len(targets):
return LINK_STILL_VALID
if operation.settled:
return SETTLED
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 CARD_RETRY, managed_client, mint
client = managed_client(creates_guest=True, initiator=initiator or CARD_RETRY, call=operation.call)
mint(client, operation, stale, reinitiate=True, actor=Actor.user)
return None
from tools.connectors import catalog
from tools.connectors.mcp import retry
rerun = catalog.retry if catalog.owns(operation.op_id) else retry
return REFUSED if rerun(operation, stale) else None
def apply_answer(operation: ConnectionOperation, raw: str) -> None:
"""Hand the card's answer to the module running this operation (a catalog install or an MCP
one); a managed operation's card only skips and continues, which the MCP fold also covers."""
from tools.connectors import catalog, display, mcp
if isinstance(operation, display.DisplayOperation):
display.apply_answer(operation, raw)
return
(catalog.apply_answer if catalog.owns(operation.op_id) else mcp.apply_answer)(operation, raw)
def respond(operation: ConnectionOperation, raw: str) -> bool:
"""The card's answer: apply it, settle once every target is resolved, close a settled operation. Returns whether it settled; raises ``IllegalTransition`` for an answer the operation refuses."""
apply_answer(operation, raw)
if not operation.settled and operation.all_resolved:
operation.settle(SettleReason.all_resolved)
if operation.settled:
live.close(operation)
return operation.settled
def run_operation(
targets: list[Target],
kind: Kind,
*,
session_key: str,
tool_call_id: Optional[str],
connection_callback: Optional[Callback],
tick_seconds: Optional[float] = None,
with_urls_in_result: bool,
call: Optional[Any] = None,
) -> str:
"""Block the tool thread until the operation settles; return the tool's JSON string."""
return open_and_drive(
ConnectionOperation(targets, session_key=session_key, tool_call_id=tool_call_id, call=call),
kind,
connection_callback=connection_callback,
tick_seconds=tick_seconds,
with_urls_in_result=with_urls_in_result,
)
def open_and_drive(
operation: ConnectionOperation,
kind: Kind,
*,
connection_callback: Optional[Callback],
tick_seconds: Optional[float] = None,
with_urls_in_result: bool,
) -> str:
"""Register ``operation`` as the session's open one and drive it; one open per session."""
try:
live.open(operation)
except live.OperationAlreadyOpen as exc:
from tools.registry import tool_error
return tool_error(
f"a connection operation is already open in this session ({exc.existing.op_id}); it settles "
"when the user finishes with the card, on Continue, or at its deadline. Do not start another."
)
return drive_operation(
operation,
kind,
connection_callback=connection_callback,
tick_seconds=tick_seconds,
with_urls_in_result=with_urls_in_result,
)
def drive_operation(
operation: ConnectionOperation,
kind: Kind,
*,
connection_callback: Optional[Callback],
tick_seconds: Optional[float] = None,
with_urls_in_result: bool,
) -> str:
try:
kind.prepare(operation)
operation.settle_if_all_resolved()
if connection_callback is not None and not operation.settled:
connection_callback(operation.request_payload())
_watch(operation, kind, tick_seconds)
finally:
live.close(operation)
if kind.result is not None:
return json.dumps(kind.result(operation), ensure_ascii=False)
payload = operation.result(with_urls=with_urls_in_result)
payload["status"] = "settled"
payload["note"] = kind.note
return json.dumps(payload, ensure_ascii=False)
def _watch(operation: ConnectionOperation, kind: Kind, tick_seconds: Optional[float]) -> None:
from tools.interrupt import is_interrupted
tick = WATCH_INTERVAL_SECONDS if tick_seconds is None else tick_seconds
while not operation.settled:
if is_interrupted():
operation.settle(SettleReason.interrupt)
return
if time.time() >= operation.deadline_at:
operation.settle(SettleReason.deadline)
return
kind.observe(operation)
# The card or the clock may have settled the op during the read; its result is frozen.
if operation.settled or operation.settle_if_all_resolved():
return
_sleep_until_wake(operation, tick)
def _sleep_until_wake(operation: ConnectionOperation, tick: float) -> None:
"""Sleep up to one tick, leaving early on ``wake``, the deadline, or the interrupt flag."""
from tools.interrupt import is_interrupted
until = min(time.time() + tick, operation.deadline_at)
while not operation.settled and not is_interrupted():
remaining = until - time.time()
if remaining <= 0:
break
if operation.wake.wait(min(_WAKE_SLICE_SECONDS, remaining)):
break
operation.wake.clear()