Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agents): website login vault and connect cards for agents (#1082)
Ruben Lütke7830faed42f1
diff --git a/dodaios/agent_chat/credential_requests.py b/dodaios/agent_chat/credential_requests.pyindex 163323c0ae..f1d778daad 100644--- a/dodaios/agent_chat/credential_requests.py+++ b/dodaios/agent_chat/credential_requests.py@@ -46,31 +46,56 @@ def _text(value: Any, limit: int) -> str:return " ".join(str(value or "").split())[:limit]+#: The two kinds of field: one secret value, or a website login (two values).+TOKEN: Final[str] = "token" # noqa: S105 — a field kind, not a secret+LOGIN: Final[str] = "login"+#: Connect cards (dodaios/society/connect_tool.py): ``env`` is the plugin id or CLI name.+PLUGIN: Final[str] = "plugin"+CLI: Final[str] = "cli"+KINDS: Final[frozenset[str]] = frozenset({TOKEN, LOGIN, PLUGIN, CLI})++@dataclass(frozen=True, slots=True)class CredentialSpec:- """What the field asks for. ``env`` is validated by the asking tool."""+ """What the field asks for. ``env`` is validated by the asking tool.++ A ``login`` field asks for a username and a password for the website at+ ``url``; its ``env`` is the login's key and the submitted value is one+ JSON object with both.+ """env: strlabel: strdescription: str = ""placeholder: str = ""replace: bool = False+ kind: str = TOKEN+ url: str = ""@classmethoddef build(cls, env: str, label: Any, description: Any = "", placeholder: Any = "",- *, replace: bool = False,+ *, replace: bool = False, kind: Any = TOKEN, url: Any = "",) -> CredentialSpec:name = _text(label, 80)if not name:raise ValueError("label is required: say what the credential is, e.g. 'GitHub token'")- return cls(env, name, _text(description, 400), _text(placeholder, 80), replace)+ field_kind = kind if kind in KINDS else TOKEN+ return cls(+ env, name, _text(description, 400), _text(placeholder, 80), replace,+ field_kind, _text(url, 300) if field_kind == LOGIN else "",+ )def to_payload(self) -> dict[str, Any]:- return {+ payload: dict[str, Any] = {"env": self.env, "label": self.label, "description": self.description,"placeholder": self.placeholder, "replace": self.replace,}+ if self.kind != TOKEN:+ payload["kind"] = self.kind+ if self.kind == LOGIN:+ payload["url"] = self.url+ return payloadclass _OpenCredential:@@ -134,6 +159,7 @@ class CredentialRequests:str(payload.get("env") or ""), payload.get("label"),payload.get("description"), payload.get("placeholder"),replace=bool(payload.get("replace")),+ kind=payload.get("kind") or TOKEN, url=payload.get("url") or "",)assert self._restore_save is not Nonesave = self._restore_save(session_id, spec)@@ -155,7 +181,10 @@ class CredentialRequests:raise RuntimeError("this chat has no running turn to ask in")# Repeated asks for the same variable reuse the person's existing field.for rid, card in self._open.items():- if card.session_id == session_id and not card.done and card.spec.env == spec.env:+ if (+ card.session_id == session_id and not card.done+ and card.spec.env == spec.env and card.spec.kind == spec.kind+ ):return ridkey = (session_id, turn_id)if self._asked.get(key, 0) >= MAX_REQUESTS_PER_TURN:diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.pyindex a5d6a7f9d5..bd5e8f8674 100644--- a/dodaios/agent_chat/service.py+++ b/dodaios/agent_chat/service.py@@ -2900,20 +2900,40 @@ class AgentChatService:@staticmethoddef _restore_credential_save(session_id: str, spec: CredentialSpec) -> Callable | None:"""Rebuild only a Society field's save callback, never a stored secret."""- from dodaios.society.credentials import save_requested_credential, validate_env_name+ from dodaios.agent_chat.credential_requests import CLI, LOGIN, PLUGIN+ from dodaios.society.credentials import (+ login_key,+ login_site,+ save_requested_credential,+ save_requested_login,+ validate_env_name,+ )from dodaios.society.surface import agent_id_ofagent_id = agent_id_of(session_id)if agent_id is None:return None+ if spec.kind in (PLUGIN, CLI):+ from dodaios.society.connect_tool import connect_save++ return connect_save(spec.kind, spec.env)try:- validate_env_name(spec.env)+ if spec.kind == LOGIN:+ login_key(spec.env)+ login_site(spec.url)+ else:+ validate_env_name(spec.env)except ValueError:log.warning("agent chat: ignored invalid stored credential field metadata")return Noneasync def save(value: str) -> None:- await save_requested_credential(agent_id, spec.env, value, label=spec.label)+ if spec.kind == LOGIN:+ await save_requested_login(+ agent_id, spec.env, value, url=spec.url, label=spec.label+ )+ else:+ await save_requested_credential(agent_id, spec.env, value, label=spec.label)return savediff --git a/dodaios/agent_chat/turn_completion.py b/dodaios/agent_chat/turn_completion.pyindex 4565275e92..4775865e49 100644--- a/dodaios/agent_chat/turn_completion.py+++ b/dodaios/agent_chat/turn_completion.py@@ -165,7 +165,7 @@ class TurnCompletion:elif kind == "tool_call":name = str(payload.get("name") or "").rsplit("__", 1)[-1].lower()self.calls[str(payload.get("call_id") or "")] = (name, payload.get("input") or {})- if name == CREDENTIAL_TOOL:+ if name in (CREDENTIAL_TOOL, LOGIN_TOOL):self.credential_asked = Trueelif kind == "tool_result":name, _ = self.calls.pop(str(payload.get("call_id") or ""), ("", {}))@@ -304,7 +304,9 @@ class TurnCompletion:f"stored, but you did not call {CREDENTIAL_TOOL}. Secrets reach you only through "f"that tool. Call {CREDENTIAL_TOOL} now for each credential the task needs (env, ""label, and a description of what it is for and where the user creates it), wait "- "for its result, then continue the original task. Do not ask for the value in the "+ f"for its result, then continue the original task. For a website login (username "+ f"and password to sign in with your browser) call {LOGIN_TOOL} instead. "+ "Do not ask for the value in the ""chat and do not repeat the request in plain text. Stored credentials right now: "+ (", ".join(stored) if stored else "none")+ ". If the task needs no credential from the user, finish without mentioning one."@@ -325,6 +327,8 @@ class TurnCompletion:#: The secure credential field's tool (dodaios/society/credential_tool.py).CREDENTIAL_TOOL = "society_request_credential"+#: The website login card's tool (dodaios/society/login_tool.py).+LOGIN_TOOL = "society_request_login"async def _stored_credentials(session_id: str) -> list[str] | None:diff --git a/dodaios/core/response_style.py b/dodaios/core/response_style.pyindex cdb4e94274..6e4c5bbbf5 100644--- a/dodaios/core/response_style.py+++ b/dodaios/core/response_style.py@@ -37,5 +37,6 @@ KEEP_GOING_ON_TOOL_FAILURE = (#: Society agents: the one way a secret reaches an agent (dodaios/society/credential_tool.py).CREDENTIAL_GUIDANCE = ("Secrets reach you only through society_request_credential, as environment variables "- "in society_shell; never ask for, show or store one anywhere else."+ "in society_shell, and website logins only through society_request_login, as browser "+ "placeholders; never ask for, show or store one anywhere else.")diff --git a/dodaios/society/browser/bridge.py b/dodaios/society/browser/bridge.pyindex b4a15a6b0f..54e9205be0 100644--- a/dodaios/society/browser/bridge.py+++ b/dodaios/society/browser/bridge.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport json+import loggingfrom dataclasses import replacefrom pathlib import Pathfrom typing import Any@@ -12,6 +13,8 @@ from uuid import UUID, uuid4from dodaios.core.protocols import BrainMessage, BrainRequest, ImageBlock, ToolResult+log = logging.getLogger(__name__)+def brain_messages(rows: list[dict[str, Any]]) -> tuple[BrainMessage, ...]:messages = []@@ -81,6 +84,20 @@ async def wait_for_browser_approval(runtime: Any, approval_id: str, session: Anyawait runtime.approvals.resolve(approval_id, approve=False, note="Browser task ended")+async def stored_logins(agent_id: str) -> dict[str, dict[str, str]]:+ """The agent's website logins, each bound to its own site (credentials.py)."""+ from ..credentials import current_vault++ vault = current_vault()+ if vault is None:+ return {}+ try:+ return await asyncio.to_thread(vault.browser_secrets, agent_id)+ except Exception: # noqa: BLE001 — a broken store costs the logins, not the task+ log.warning("society browser: stored logins unavailable for %s", agent_id)+ return {}++async def execute_live(runtime: Any, caller: Any, jobs: Any, args: dict, ctx: Any, *, read_only: bool = False) -> ToolResult:@@ -299,6 +316,7 @@ async def execute_live(files.append(str(path))if args.get("url"):task = f"Start at {args['url']}. " + task+ logins = await stored_logins(caller.agent_id)try:result = await live.run(caller,@@ -310,6 +328,7 @@ async def execute_live(files=files,trace_id=turn_trace,chat_session_id=chat_session_id,+ sensitive_data=logins,)except Exception as exc:# The tool result reports the failure to both the chat and the planner.@@ -318,6 +337,14 @@ async def execute_live(None,stopped_message if (caller.agent_id, turn_trace) in live.stopped_turns else str(exc),)+ if logins:+ from ..credentials import current_vault++ vault = current_vault()+ if vault is not None:+ # The runner already swaps typed values for placeholders; this also+ # catches a value a page echoed in a form the runner did not know.+ result = await asyncio.to_thread(vault.redact_payload, caller.agent_id, result)result["usage"] = usage_totalresult["provider"] = providerresult["model"] = caller.modeldiff --git a/dodaios/society/browser/live.py b/dodaios/society/browser/live.pyindex 48ccbdffd8..270e04c910 100644--- a/dodaios/society/browser/live.py+++ b/dodaios/society/browser/live.py@@ -900,6 +900,7 @@ class LiveSessions:files: list[str] | None = None,trace_id: str = "",chat_session_id: str = "",+ sensitive_data: dict[str, dict[str, str]] | None = None,) -> dict:session = await self.ensure(agent)await claim_browser(session, chat_session_id)@@ -926,6 +927,7 @@ class LiveSessions:"model": agent.model,"vision": vision,"files": files or [],+ "sensitive_data": sensitive_data or {},},timeout=600,)diff --git a/dodaios/society/browser/live_runner.py b/dodaios/society/browser/live_runner.pyindex 8c972943ba..26efa4ee50 100644--- a/dodaios/society/browser/live_runner.py+++ b/dodaios/society/browser/live_runner.py@@ -29,6 +29,52 @@ os.environ["BROWSER_USE_LOGGING_LEVEL"] = "error"PROTOCOL_VERSION = 2+_SECRET_TAG = "<secret>" # noqa: S105 — the placeholder tag, not a secret+_HIDE_ACTIVE_FIELD = """() => {+ let el = document.activeElement;+ while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement;+ if (el && "value" in el) el.style.setProperty("-webkit-text-security", "disc", "important");+}"""+++def typed_secret(proposal: dict) -> bool:+ """The action types a stored login placeholder."""+ return any(+ isinstance(params, dict) and _SECRET_TAG in str(params.get("text") or "")+ for params in proposal.values()+ )+++def scrub_secrets(secrets: dict | None, value: Any) -> Any:+ """``value`` with every stored login value replaced by its placeholder."""+ if not secrets:+ return value+ pairs = sorted(+ (+ (secret, name)+ for scoped in secrets.values()+ if isinstance(scoped, dict)+ for name, secret in scoped.items()+ if secret+ ),+ key=lambda pair: len(pair[0]),+ reverse=True,+ )++ def walk(item: Any) -> Any:+ if isinstance(item, str):+ for secret, name in pairs:+ item = item.replace(secret, f"<secret>{name}</secret>")+ return item+ if isinstance(item, dict):+ return {key: walk(child) for key, child in item.items()}+ if isinstance(item, list):+ return [walk(child) for child in item]+ return item++ return walk(value)++def emit(kind: str, **values: Any) -> None:WIRE.write(json.dumps({"kind": kind, **values}, ensure_ascii=True) + "\n")WIRE.flush()@@ -815,6 +861,8 @@ class Worker:result = ActionResult(error=f"{type(exc).__name__}: browser action failed")finally:worker.visual_action = False+ if typed_secret(proposal):+ await worker.hide_typed_value()emit("action_result", id=answer["permit"], result=result.model_dump(mode="json"))return result@@ -828,8 +876,13 @@ class Worker:register_window_actions(tools, self, ActionResult)started = time.monotonic()+ secrets = args.get("sensitive_data") or Noneself.agent = Agent(task=args["task"],+ # Stored website logins: the model writes <secret>name</secret>, the+ # browser types the value only on its site, and every observation the+ # model reads has the value replaced by the placeholder again.+ sensitive_data=secrets,llm=JarvisModel(),browser=self.browser,tools=tools,@@ -872,7 +925,7 @@ class Worker:max_steps=args.get("max_steps", 25), on_step_start=before_step, on_step_end=step)successful = history.is_successful() is True- return {+ return scrub_secrets(secrets, {"ok": successful,"final_result": history.final_result(),"urls": history.urls(),@@ -882,7 +935,7 @@ class Worker:"error": None if successful else "Browser task did not complete successfully",# One SDK owns downloads; a second Playwright save would duplicate files."artifacts": sorted(set(self.browser.downloaded_files) - previous_downloads),- }+ })finally:self.agent = Noneself.cursor_on = False@@ -892,6 +945,17 @@ class Worker:self.pointer.clear()self.step_idle.set()+ async def hide_typed_value(self) -> None:+ """Draw the field the agent just typed a secret into as dots.++ A password field already is; a username or email field would show the+ value in the next screenshot the model reads.+ """+ # A page that blocks the style still never hands the text to the model.+ with contextlib.suppress(Exception):+ page = await self.focused()+ await page.evaluate(_HIDE_ACTIVE_FIELD)+async def command(self, op: str, args: dict) -> dict:# Cancellation must stay available while a transition waits for the job.if op in {"run", "cancel", "shutdown"}:diff --git a/dodaios/society/browser/session.py b/dodaios/society/browser/session.pyindex af6bf35d79..ec8ea7dc0a 100644--- a/dodaios/society/browser/session.py+++ b/dodaios/society/browser/session.py@@ -319,6 +319,7 @@ class BrowserJobs:start_url: str = "",on_step: StepCallback | None = None,wall_s: float = RUN_WALL_S,+ sensitive_data: dict[str, dict[str, str]] | None = None,) -> BrowserOutcome:async with self._lock(agent.agent_id):proc = await self._spawn(agent.agent_id)@@ -335,6 +336,8 @@ class BrowserJobs:"calculate_cost": True,})+ if sensitive_data:+ request["sensitive_data"] = sensitive_datatry:await self._send(proc, request)done = await self._read_lines(proc, wall_s=wall_s, on_line=on_step)diff --git a/dodaios/society/browser/tool.py b/dodaios/society/browser/tool.pyindex f26e17b7bf..e1b5649d24 100644--- a/dodaios/society/browser/tool.py+++ b/dodaios/society/browser/tool.py@@ -223,6 +223,9 @@ class BrowserTool:except LLMUnavailable as exc:return _failure(exc.reason, str(exc))steps_seen: list[dict[str, Any]] = []+ from .bridge import stored_logins++ logins = await stored_logins(caller.agent_id)async def _on_step(event: dict[str, Any]) -> None:if event.get("kind") != "step":@@ -251,6 +254,7 @@ class BrowserTool:max_steps=int(args.get("max_steps") or DEFAULT_MAX_STEPS),start_url=str(args.get("url") or "").strip(),on_step=_on_step,+ sensitive_data=logins,)except BrowserUnavailable as exc:return _failure(exc.reason, str(exc))diff --git a/dodaios/society/connect_tool.py b/dodaios/society/connect_tool.pynew file mode 100644index 0000000000..5c7734344d--- /dev/null+++ b/dodaios/society/connect_tool.py@@ -0,0 +1,285 @@+"""``society_request_connect``: an agent asks the person to connect a plugin or CLI.++The chat shows a small card with the service's logo and a Connect button+("Connect GitHub · Lets Ada read your issues"). The button runs the same+sign-in the Plugins and CLIs pages run; when it finishes, the card reports+back and this side checks that the connection really exists before the agent+hears "connected". Nothing secret passes through the card: the sign-in+happens with the provider, its token goes to the existing token store.++The card reuses the secure field plumbing (credential_requests.py) with the+kinds ``plugin`` and ``cli``: it stays open across turns and restarts, and+the agent checks it on a later turn with ``wait_for``.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any, Final++from dodaios.agent_chat.credential_requests import (+ CANCELLED,+ CLI,+ DECLINED,+ MAX_REQUESTS_PER_TURN,+ PLUGIN,+ SAVED,+ CredentialSpec,+ TooManyCredentialRequests,+)+from dodaios.core.protocols import ToolResult++from .credentials import CredentialError+from .routine_runner import is_routine_session++log = logging.getLogger(__name__)++__all__ = ["CONNECT_TOOL_NAME", "RequestConnectTool", "connect_save", "resolve_target"]++CONNECT_TOOL_NAME: Final[str] = "society_request_connect"+++@dataclass(frozen=True, slots=True)+class Target:+ kind: str+ id: str+ label: str+ connected: bool | None+++def _plugin(raw: str) -> Target | None:+ from dodaios.marketplace.catalog_data import load_catalog++ catalog = load_catalog()+ for candidate in (raw, raw.replace("-", "_"), raw.replace("_", "-")):+ spec = catalog.by_id(candidate)+ if spec is not None:+ return Target(PLUGIN, spec.id, spec.display_name, _plugin_connected(spec.id))+ return None+++def _plugin_connected(plugin_id: str) -> bool | None:+ from .runtime import current_runtime++ rt = current_runtime()+ state = getattr(rt, "_plugin_state", None) if rt is not None else None+ if not callable(state):+ return None+ try:+ _catalog_ids, usable = state()+ except Exception: # noqa: BLE001 — unknown state is reported as unknown+ log.warning("society connect: plugin state unavailable", exc_info=True)+ return None+ return plugin_id in set(usable)+++def _cli(raw: str) -> Target | None:+ from dodaios.clis.shared import get_active_registry++ registry = get_active_registry()+ if registry is None:+ return None+ spec = registry.catalog().get(raw)+ if spec is None:+ return None+ status = registry.status_of(spec.name)+ connected = None if status is None else bool(+ status.installed and status.auth_status == "connected"+ )+ return Target(CLI, spec.name, spec.display_name, connected)+++def resolve_target(kind: str, raw: str) -> Target | None:+ """The plugin or CLI ``raw`` names, with its current connection state."""+ ident = str(raw or "").strip().lower()+ if not ident:+ return None+ if kind == PLUGIN:+ return _plugin(ident)+ if kind == CLI:+ return _cli(ident)+ return None+++def connect_save(kind: str, target_id: str) -> Callable[[str], Awaitable[None]]:+ """The card's receipt: accepted only when the connection really exists now."""++ async def save(_value: str) -> None:+ if kind == CLI:+ from dodaios.clis.shared import get_active_registry++ registry = get_active_registry()+ if registry is not None:+ try:+ await registry.refresh_status(target_id)+ except Exception: # noqa: BLE001 — the cached status still decides+ log.debug("society connect: CLI re-check failed", exc_info=True)+ target = await asyncio.to_thread(resolve_target, kind, target_id)+ if target is None or target.connected is False:+ raise CredentialError(+ "Not connected yet. Finish signing in, then press Connect again.",+ code="not_connected",+ )++ return save+++class RequestConnectTool:+ """Ask the person to connect a plugin or CLI through a card in the chat."""++ name: str = CONNECT_TOOL_NAME+ risk_tier: str = "safe"+ is_action_tool: bool = False+ description: str = (+ "Ask the user to connect a Dodaios plugin (kind 'plugin', a marketplace id such as "+ "'github', 'notion', 'gmail') or a command-line tool (kind 'cli', a CLI name such as "+ "'gh', 'vercel'). It shows a small card with the service's logo and a Connect button "+ "in the user's chat; the button starts the normal sign-in. Use it when a task needs "+ "a service that is listed but not connected, instead of telling the user to go to "+ "the Plugins page. Give in reason what you will do with it, one sentence in the "+ "user's language. A connected service returns 'connected' at once. While the user "+ "has not finished, the call returns 'waiting' with a request_id; do not poll. The "+ "card stays open; on a later turn, wait_for checks it."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "kind": {"type": "string", "enum": [PLUGIN, CLI]},+ "id": {"type": "string", "description": "The plugin id or the CLI name."},+ "reason": {+ "type": "string",+ "description": "One sentence: what you will do once it is connected.",+ },+ "wait_for": {+ "type": "string",+ "description": "The request_id of an earlier 'waiting' result. Send it alone.",+ },+ },+ }++ def __init__(self, runtime: Any, agent_id: str, *, session_id: str) -> None:+ self._runtime = runtime+ self._agent_id = agent_id+ self._session_id = session_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ wait_for = str(args.get("wait_for") or "").strip()+ if wait_for:+ return await self._check_existing(wait_for)+ kind = str(args.get("kind") or "").strip().lower()+ if kind not in (PLUGIN, CLI):+ return _invalid("kind must be 'plugin' or 'cli'")+ raw = str(args.get("id") or "")+ try:+ target = await asyncio.to_thread(resolve_target, kind, raw)+ except Exception: # noqa: BLE001 — a broken catalog is reported, not raised+ log.warning("society connect: catalog unavailable", exc_info=True)+ return _invalid("the catalog is not available right now")+ if target is None:+ return _invalid(+ f"no {kind} named {raw!r}. Use an id from your capability list or the "+ "Plugins / CLIs catalog."+ )+ if target.connected:+ return ToolResult(+ success=True,+ output={"status": "connected", "kind": kind, "id": target.id},+ )+ if is_routine_session(self._session_id):+ return ToolResult(+ success=False,+ output={"status": "unattended", "id": target.id},+ error=f"Routines cannot ask to connect {target.label}. Report it instead.",+ )+ reason = " ".join(str(args.get("reason") or "").split())+ if not reason:+ return _invalid("reason is required: say what you will do once it is connected")+ spec = CredentialSpec.build(target.id, target.label, reason, kind=kind)+ service = self._runtime.chat_service()+ if service is None or not callable(getattr(service, "open_credential_request", None)):+ return _nobody(target.label)+ try:+ request_id = await service.open_credential_request(+ self._session_id, spec, connect_save(kind, target.id), asker=self._asker()+ )+ except TooManyCredentialRequests as exc: # The limit is the visible tool error.+ return ToolResult(+ success=False,+ output={"status": "limit", "id": target.id},+ error=f"Card limit reached: {exc}. At most {MAX_REQUESTS_PER_TURN} per turn.",+ )+ except RuntimeError as exc: # No running turn: reported as unattended.+ log.info("society connect: %s cannot ask here (%s)", self._agent_id, exc)+ return _nobody(target.label)+ return await self._status(service, request_id, spec)++ async def _check_existing(self, request_id: str) -> ToolResult:+ service = self._runtime.chat_service()+ try:+ await service.restore_credential_requests(self._session_id)+ spec = service.credential_request_spec(self._session_id, request_id)+ except (AttributeError, KeyError): # An unknown id is the visible tool error.+ return _invalid("no connect card with that id in this chat")+ return await self._status(service, request_id, spec)++ async def _status(self, service: Any, request_id: str, spec: CredentialSpec) -> ToolResult:+ status = await service.wait_credential_request(self._session_id, request_id, 0)+ if status is None:+ return ToolResult(+ success=True,+ output={+ "status": "waiting",+ "request_id": request_id,+ "id": spec.env,+ "note": (+ f"The user has not connected {spec.label} yet. The card stays open. "+ "Continue unrelated work or finish your reply now; do not poll. On a "+ f'later turn, check it with {{"wait_for": "{request_id}"}}.'+ ),+ },+ )+ if status == SAVED:+ return ToolResult(+ success=True,+ output={+ "status": "connected",+ "kind": spec.kind,+ "id": spec.env,+ "note": f"{spec.label} is connected; its tools reach you from the next turn.",+ },+ )+ if status == CANCELLED:+ return ToolResult(+ success=False,+ output={"status": CANCELLED, "id": spec.env},+ error="The user stopped this turn. Do not continue the task.",+ )+ reason = "The user declined." if status == DECLINED else "The card closed."+ return ToolResult(+ success=False,+ output={"status": status, "id": spec.env},+ error=(+ f"{reason} {spec.label} is not connected. Continue without it where you can. "+ "Do not ask again in this turn."+ ),+ )++ def _asker(self) -> str:+ cached = getattr(self._runtime, "cached_agent", None)+ agent = cached(self._agent_id) if callable(cached) else None+ return str(getattr(agent, "name", "") or "")+++def _invalid(detail: str) -> ToolResult:+ return ToolResult(success=False, output=None, error=f"invalid request: {detail}")+++def _nobody(label: str) -> ToolResult:+ return ToolResult(+ success=False,+ output={"status": "unattended"},+ error=f"Nobody can connect {label} in this run. Report that the user has to do it.",+ )diff --git a/dodaios/society/credential_tool.py b/dodaios/society/credential_tool.pyindex f2f742c0cf..5fbebb7877 100644--- a/dodaios/society/credential_tool.py+++ b/dodaios/society/credential_tool.py@@ -76,7 +76,9 @@ class RequestCredentialTool:"stays open until the user saves or cancels, even if the turn ends. Continue unrelated ""work and respond to new messages while the user obtains the credential. If nothing ""else can be done now, finish your reply so the user can ask questions. On a later "- "turn, wait_for checks the existing field's status immediately without opening another."+ "turn, wait_for checks the existing field's status immediately without opening another. "+ "To sign in to a website in your browser with a username and password, use "+ "society_request_login instead.")schema: dict[str, Any] = {"type": "object",diff --git a/dodaios/society/credentials.py b/dodaios/society/credentials.pyindex 56d3f08f5a..3405bbbeec 100644--- a/dodaios/society/credentials.py+++ b/dodaios/society/credentials.py@@ -36,7 +36,7 @@ from collections.abc import Mappingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Final, Protocol-from urllib.parse import quote+from urllib.parse import quote, urlsplitlog = logging.getLogger(__name__)@@ -45,7 +45,10 @@ __all__ = ["CredentialError","CredentialInfo","CredentialVault",+ "LoginInfo","MAX_VALUE_CHARS",+ "login_key",+ "login_site","validate_env_name",]@@ -190,6 +193,27 @@ async def save_requested_credential(await asyncio.to_thread(vault.store, agent_id, env, value, label=label)+async def save_requested_login(+ agent_id: str, key: str, raw: str, *, url: str, label: str = "",+) -> None:+ """Store the two values the login form sent as one JSON object."""+ try:+ body = json.loads(raw)+ except (TypeError, ValueError):+ raise CredentialError("Enter the username or email and the password.") from None+ if not isinstance(body, dict):+ raise CredentialError("Enter the username or email and the password.")+ vault = current_vault()+ if vault is None:+ raise CredentialError(+ "The credential store is unavailable. Please try again shortly.", code="storage_failed",+ )+ await asyncio.to_thread(+ vault.store_login, agent_id, key, body.get("username"), body.get("password"),+ url=url, label=label,+ )++def validate_env_name(raw: Any) -> str:"""The environment variable name ``raw`` asks for, or ``CredentialError``."""name = str(raw or "").strip()@@ -214,6 +238,99 @@ def _encodings(value: str) -> list[str]:return [form for form in forms if len(form) >= _MIN_REDACT_CHARS]+#: A login's key names its browser placeholders: ``<secret>reddit_password</secret>``.+_LOGIN_KEY: Final[re.Pattern[str]] = re.compile(r"^[a-z][a-z0-9_]{0,39}$")+_LOGIN_SLOT_PREFIX: Final[str] = "society_login"+#: Second-level labels under which a country code is the public suffix (co.uk, com.au).+_SHARED_SECOND_LEVEL: Final[frozenset[str]] = frozenset(+ {"ac", "co", "com", "edu", "gov", "ltd", "net", "ne", "or", "org", "plc"}+)+MAX_LOGIN_FIELD_CHARS: Final[int] = 1024+++def login_key(raw: Any) -> str:+ """``raw`` (a label such as "Hacker News") as a placeholder key (``hacker_news``)."""+ key = re.sub(r"[^a-z0-9]+", "_", str(raw or "").casefold()).strip("_")+ if key and not key[0].isalpha():+ key = f"site_{key}"+ key = key[:40].rstrip("_")+ if not _LOGIN_KEY.fullmatch(key):+ raise CredentialError("site must name the website, e.g. 'Reddit' or 'Hacker News'")+ return key+++def login_site(raw: Any) -> tuple[str, str]:+ """The sign-in page ``raw`` as ``(https URL, registrable domain)``.++ The domain decides where the browser may type the login: the site itself+ and its subdomains, over HTTPS only. Anything that is not a public web+ address (an IP, localhost, another scheme) is refused.+ """+ text = str(raw or "").strip()+ if text and "://" not in text:+ text = f"https://{text}"+ parts = urlsplit(text)+ host = (parts.hostname or "").casefold().rstrip(".")+ if parts.scheme not in {"https", "http"} or not host or "." not in host:+ raise CredentialError("url must be the website's address, e.g. https://www.reddit.com")+ labels = host.split(".")+ if all(label.isdigit() for label in labels) or not all(+ re.fullmatch(r"[a-z0-9-]{1,63}", label) for label in labels+ ):+ raise CredentialError("url must be a website's domain name, not an IP address")+ shared = labels[-2] in _SHARED_SECOND_LEVEL and len(labels[-1]) == 2+ if shared and len(labels) < 3:+ raise CredentialError("url must name one website, not a whole country domain")+ keep = 3 if shared else 2+ domain = ".".join(labels[-keep:])+ path = parts.path or "/"+ return f"https://{host}{path}"[:300], domain+++def _login_field(value: Any, what: str, *, strip: bool) -> str:+ text = str(value if isinstance(value, str) else "")+ if strip:+ text = text.strip()+ if not text.strip():+ raise CredentialError(f"Enter the {what} before saving.")+ if len(text) > MAX_LOGIN_FIELD_CHARS:+ raise CredentialError(f"The {what} is too long.")+ if any(ord(ch) < 32 or ord(ch) == 127 for ch in text):+ raise CredentialError(f"The {what} must be a single line without control characters.")+ return text+++@dataclass(frozen=True, slots=True)+class LoginInfo:+ """A website login the agent may use in its browser: never the values."""++ key: str+ label: str+ url: str+ domain: str+ created_ms: int+ updated_ms: int++ @property+ def placeholders(self) -> tuple[str, str]:+ return (f"{self.key}_username", f"{self.key}_password")++ @property+ def domain_pattern(self) -> str:+ """browser-use's pattern: the domain and its subdomains, HTTPS only."""+ return f"*.{self.domain}"++ def to_dict(self) -> dict[str, Any]:+ return {+ "key": self.key,+ "label": self.label,+ "url": self.url,+ "domain": self.domain,+ "created_ms": self.created_ms,+ "updated_ms": self.updated_ms,+ }++@dataclass(frozen=True, slots=True)class CredentialInfo:"""What the index knows about one stored credential: never its value."""@@ -241,6 +358,8 @@ class CredentialVault:self._lock = threading.Lock()#: Values by agent, loaded once per process for scrubbing and env building.self._values: dict[str, dict[str, str]] = {}+ #: Website logins by agent and key: (username, password).+ self._logins: dict[str, dict[str, tuple[str, str]]] = {}#: (needle, env) per agent, longest first, so a longer secret that#: contains a shorter one is masked whole.self._masks: dict[str, list[tuple[str, str]]] = {}@@ -258,7 +377,7 @@ class CredentialVault:raise ValueError("Agent credential index escapes the vault")return Path(path)- def _read_index(self, agent_id: str) -> dict[str, CredentialInfo]:+ def _read_raw(self, agent_id: str) -> dict[str, Any]:path = self._index_path(agent_id)try:raw = json.loads(path.read_text(encoding="utf-8"))@@ -267,8 +386,31 @@ class CredentialVault:except (OSError, ValueError):log.warning("society credentials: unreadable index %s", path, exc_info=True)return {}+ return raw if isinstance(raw, dict) else {}++ def _read_logins(self, agent_id: str) -> dict[str, LoginInfo]:+ rows: dict[str, LoginInfo] = {}+ for entry in self._read_raw(agent_id).get("logins", []):+ if not isinstance(entry, dict):+ continue+ key = str(entry.get("key") or "")+ domain = str(entry.get("domain") or "")+ if not _LOGIN_KEY.fullmatch(key) or not domain:+ continue+ rows[key] = LoginInfo(+ key=key,+ label=str(entry.get("label") or "")[:120],+ url=str(entry.get("url") or "")[:300],+ domain=domain[:253],+ created_ms=int(entry.get("created_ms") or 0),+ updated_ms=int(entry.get("updated_ms") or 0),+ )+ return rows++ def _read_index(self, agent_id: str) -> dict[str, CredentialInfo]:+ raw = self._read_raw(agent_id)rows: dict[str, CredentialInfo] = {}- for entry in raw.get("credentials", []) if isinstance(raw, dict) else []:+ for entry in raw.get("credentials", []):if not isinstance(entry, dict):continueenv = str(entry.get("env") or "")@@ -282,10 +424,20 @@ class CredentialVault:)return rows- def _write_index(self, agent_id: str, rows: Mapping[str, CredentialInfo]) -> None:+ def _write_index(+ self,+ agent_id: str,+ rows: Mapping[str, CredentialInfo] | None = None,+ logins: Mapping[str, LoginInfo] | None = None,+ ) -> None:+ """Write the index; the half not passed is kept as it is on disk."""+ rows = self._read_index(agent_id) if rows is None else rows+ logins = self._read_logins(agent_id) if logins is None else loginspath = self._index_path(agent_id)path.parent.mkdir(parents=True, exist_ok=True)- body = {"credentials": [rows[name].to_dict() for name in sorted(rows)]}+ body: dict[str, Any] = {"credentials": [rows[name].to_dict() for name in sorted(rows)]}+ if logins:+ body["logins"] = [logins[key].to_dict() for key in sorted(logins)]tmp = path.with_suffix(".json.tmp")tmp.write_text(json.dumps(body, indent=2, ensure_ascii=False), encoding="utf-8")tmp.replace(path)@@ -372,6 +524,7 @@ class CredentialVault:"""Drop the cached values (caller holds the lock); the next read reloads."""self._generation += 1self._values.pop(agent_id, None)+ self._logins.pop(agent_id, None)self._masks.pop(agent_id, None)def values(self, agent_id: str) -> dict[str, str]:@@ -382,14 +535,21 @@ class CredentialVault:if cached is not None:return dict(cached)rows = self._read_index(agent_id)+ login_rows = self._read_logins(agent_id)generation = self._generationloaded = self._load(agent_id, rows)+ logins = self._load_logins(agent_id, login_rows)with self._lock:if generation != self._generation:continue # a store or delete ran meanwhile: load againself._values[agent_id] = loaded+ self._logins[agent_id] = logins+ needles = [(value, env) for env, value in loaded.items()]+ for key, (username, password) in logins.items():+ needles.append((username, f"{key} username"))+ needles.append((password, f"{key} password"))self._masks[agent_id] = sorted(- ((form, env) for env, value in loaded.items() for form in _encodings(value)),+ ((form, name) for value, name in needles for form in _encodings(value)),key=lambda pair: len(pair[0]),reverse=True,)@@ -407,16 +567,147 @@ class CredentialVault:)return loaded+ def _load_logins(+ self, agent_id: str, rows: Mapping[str, LoginInfo]+ ) -> dict[str, tuple[str, str]]:+ loaded: dict[str, tuple[str, str]] = {}+ for key in rows:+ username = self._secrets.get(self._login_slot(agent_id, key, "username"))+ password = self._secrets.get(self._login_slot(agent_id, key, "password"))+ if username and password:+ loaded[key] = (username, password)+ else:+ log.warning("society credentials: login %s for %s is incomplete", key, agent_id)+ return loaded++ @staticmethod+ def _login_slot(agent_id: str, key: str, field: str) -> str:+ return f"{_LOGIN_SLOT_PREFIX}.{_SAFE_ID.sub('_', agent_id)}.{key}.{field}"++ # ------------------------------------------------------------- logins++ def list_logins(self, agent_id: str) -> list[LoginInfo]:+ with self._lock:+ rows = self._read_logins(agent_id)+ return [rows[key] for key in sorted(rows)]++ def has_login(self, agent_id: str, key: str) -> bool:+ """Both values are really there, not only the index row."""+ self.values(agent_id)+ with self._lock:+ return key in self._logins.get(agent_id, {})++ def store_login(+ self,+ agent_id: str,+ key: str,+ username: Any,+ password: Any,+ *,+ url: str,+ label: str = "",+ ) -> LoginInfo:+ """Save a website login: both values go to the store, the index keeps the site."""+ key = login_key(key)+ site_url, domain = login_site(url)+ user_value = _login_field(username, "username or email", strip=True)+ pass_value = _login_field(password, "password", strip=False)+ now = int(time.time() * 1000)+ with self._lock:+ logins = self._read_logins(agent_id)+ previous = logins.get(key)+ info = LoginInfo(+ key=key,+ label=(label.strip() or (previous.label if previous else key))[:120],+ url=site_url,+ domain=domain,+ created_ms=previous.created_ms if previous else now,+ updated_ms=now,+ )+ slots = {+ self._login_slot(agent_id, key, "username"): user_value,+ self._login_slot(agent_id, key, "password"): pass_value,+ }+ before: dict[str, str | None] = {}+ try:+ for slot, value in slots.items():+ before[slot] = self._secrets.get(slot)+ if not self._secrets.set(slot, value) or self._secrets.get(slot) != value:+ raise CredentialError("unverified", code="storage_failed")+ logins[key] = info+ self._write_index(agent_id, logins=logins)+ except Exception:+ # Never log the exception: a store backend may echo the value.+ for slot, old in before.items():+ try:+ if old is not None:+ self._secrets.set(slot, old)+ else:+ self._secrets.delete(slot)+ except Exception:+ log.error("society credentials: login rollback failed for %s", key)+ raise CredentialError(+ "The login could not be stored. Please try saving again.",+ code="storage_failed",+ ) from None+ finally:+ self._forget(agent_id)+ log.info("society credentials: stored login %s for %s", key, agent_id)+ return info++ def delete_login(self, agent_id: str, key: str) -> bool:+ """Forget a website login; False when it was never stored."""+ with self._lock:+ logins = self._read_logins(agent_id)+ if key not in logins:+ return False+ for field in ("username", "password"):+ slot = self._login_slot(agent_id, key, field)+ if self._secrets.get(slot) is not None and not self._secrets.delete(slot):+ raise CredentialError("the credential store could not delete the login")+ logins.pop(key)+ self._write_index(agent_id, logins=logins)+ self._forget(agent_id)+ log.info("society credentials: deleted login %s for %s", key, agent_id)+ return True++ def browser_secrets(self, agent_id: str) -> dict[str, dict[str, str]]:+ """browser-use ``sensitive_data``: each login bound to its own site.++ The browser types a value only on a page of that site; the model sees+ and writes the placeholder names, never the values.+ """+ self.values(agent_id)+ with self._lock:+ values = dict(self._logins.get(agent_id, {}))+ rows = self._read_logins(agent_id)+ out: dict[str, dict[str, str]] = {}+ for key, (username, password) in values.items():+ info = rows.get(key)+ if info is None:+ continue+ user_name, pass_name = info.placeholders+ out.setdefault(info.domain_pattern, {}).update(+ {user_name: username, pass_name: password}+ )+ return out+def is_loaded(self, agent_id: str) -> bool:return agent_id in self._values+ def _any_secret(self, agent_id: str) -> bool:+ if self.values(agent_id):+ return True+ with self._lock:+ return bool(self._logins.get(agent_id))+def shell_env(self, agent_id: str) -> dict[str, str]:"""The variables an agent's own ``society_shell`` commands run with."""return self.values(agent_id)def redact(self, agent_id: str, text: str) -> str:"""``text`` with every credential value of ``agent_id`` masked (may read the store)."""- if not text or not self.values(agent_id):+ if not text or not self._any_secret(agent_id):return textfor needle, env in self._masks.get(agent_id, ()):if needle in text:@@ -425,7 +716,7 @@ class CredentialVault:def redact_payload(self, agent_id: str, payload: Any) -> Any:"""``payload`` with every string in it redacted; unchanged objects are reused."""- if not self.values(agent_id):+ if not self._any_secret(agent_id):return payloadif isinstance(payload, str):return self.redact(agent_id, payload)diff --git a/dodaios/society/login_tool.py b/dodaios/society/login_tool.pynew file mode 100644index 0000000000..55cdf32296--- /dev/null+++ b/dodaios/society/login_tool.py@@ -0,0 +1,257 @@+"""``society_request_login``: an agent asks the person for a website login.++The chat shows a small card ("Sign in to Reddit · Opens a secure form"); the+person opens it, enters the username or email and the password, and saves.+Both values go from that form into the agent's credential vault+(credentials.py) and never into the chat, a prompt or this tool's result.++The agent uses the login only through its browser (``society_browser``): the+browser model sees and writes the placeholders ``<secret>reddit_username</secret>``+and ``<secret>reddit_password</secret>``, and browser-use types the real value+only on a page of that site. What it typed is masked in everything the model+reads back. The values are never set in ``society_shell``.+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any, Final++from dodaios.agent_chat.credential_requests import (+ CANCELLED,+ DECLINED,+ LOGIN,+ MAX_REQUESTS_PER_TURN,+ SAVED,+ CredentialSpec,+ TooManyCredentialRequests,+)+from dodaios.core.protocols import ToolResult++from . import credentials+from .credentials import LoginInfo, login_key, login_site+from .routine_runner import is_routine_session++log = logging.getLogger(__name__)++__all__ = ["LOGIN_TOOL_NAME", "RequestLoginTool", "login_usage_note"]++LOGIN_TOOL_NAME: Final[str] = "society_request_login"+++def login_usage_note(info: LoginInfo) -> str:+ """How the agent uses a stored login without ever seeing it."""+ user, password = info.placeholders+ return (+ f"Sign in with society_browser on {info.domain}. In the browser task write the "+ f"placeholders literally: username <secret>{user}</secret>, password "+ f"<secret>{password}</secret>. The browser types the real values only on "+ f"{info.domain} and its subdomains; you never see them. Never ask the user to type "+ "the login in the chat and never try to read the typed values back."+ )+++class RequestLoginTool:+ """Ask the person for a website login through a secure form in the chat."""++ name: str = LOGIN_TOOL_NAME+ risk_tier: str = "safe"+ is_action_tool: bool = False+ description: str = (+ "REQUIRED whenever a task needs you to sign in to a website in your browser with the "+ "user's account (for example Reddit, Hacker News, X, LinkedIn, a shop or a forum). "+ "It shows a small card in the user's chat that opens a secure form for the username "+ "or email and the password; the values go to the system credential store. You NEVER "+ "see them: in society_browser you write the placeholders "+ "<secret><site>_username</secret> and <secret><site>_password</secret>, and the "+ "browser types the real values only on that website. This is the ONLY way to get a "+ "website login: never ask for a username or password in your reply or a question "+ "card. For an API key or token use society_request_credential instead. Give site "+ "(the service's name, e.g. 'Reddit'), url (its sign-in page) and in description why "+ "you need to sign in, in the user's language. A login you already have is not asked "+ "for again: the call returns 'available' with the placeholders. Set replace only when "+ "the site rejected the stored login. While the user has not answered yet, the call "+ "returns immediately with status 'waiting' and a request_id; do not poll. The card "+ "stays open until the user saves or cancels. On a later turn, wait_for checks it."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "site": {+ "type": "string",+ "description": "The service's name, 1-3 words, e.g. 'Reddit', 'Hacker News'.",+ },+ "url": {+ "type": "string",+ "description": "The sign-in page, e.g. https://www.reddit.com/login.",+ },+ "description": {+ "type": "string",+ "description": "One sentence: why you need to sign in there.",+ },+ "replace": {+ "type": "boolean",+ "description": "Ask again although a login is stored (the site rejected it).",+ },+ "wait_for": {+ "type": "string",+ "description": (+ "Check a previously opened card on a later turn: the request_id from a "+ "'waiting' result. Returns immediately. Send it alone."+ ),+ },+ },+ }++ def __init__(self, runtime: Any, agent_id: str, *, session_id: str) -> None:+ self._runtime = runtime+ self._agent_id = agent_id+ self._session_id = session_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ wait_for = str(args.get("wait_for") or "").strip()+ if wait_for:+ return await self._check_existing(wait_for)+ try:+ site = str(args.get("site") or "").strip()+ key = login_key(site)+ url, _domain = login_site(args.get("url"))+ spec = CredentialSpec.build(+ key, site, args.get("description"), "",+ replace=bool(args.get("replace")), kind=LOGIN, url=url,+ )+ if not spec.description:+ raise ValueError("description is required: say why you need to sign in")+ except ValueError as exc: # A malformed request goes back to the agent to fix.+ return ToolResult(success=False, output=None, error=f"invalid request: {exc}")+ vault = credentials.current_vault()+ if vault is None:+ return ToolResult(+ success=False, output=None, error="The credential store is not available yet."+ )+ if not spec.replace and await asyncio.to_thread(vault.has_login, self._agent_id, key):+ return self._ready("available", vault, key)+ if is_routine_session(self._session_id):+ return ToolResult(+ success=False,+ output={"status": "unattended", "site": site},+ error=(+ f"Routines run unattended and cannot ask for the {site} login. Report "+ "that the user has to provide it in your chat."+ ),+ )+ service = self._runtime.chat_service()+ if service is None or not callable(getattr(service, "open_credential_request", None)):+ return _nobody(site)+ agent_id = self._agent_id++ async def save(value: str) -> None:+ await credentials.save_requested_login(+ agent_id, key, value, url=url, label=spec.label+ )++ try:+ request_id = await service.open_credential_request(+ self._session_id, spec, save, asker=self._asker()+ )+ except TooManyCredentialRequests as exc: # The limit is the visible tool error.+ return ToolResult(+ success=False,+ output={"status": "limit", "site": site},+ error=(+ f"Field limit reached: {exc}. At most {MAX_REQUESTS_PER_TURN} new fields "+ "can be opened per turn. Reuse existing pending fields."+ ),+ )+ except RuntimeError as exc: # No running turn: reported as unattended.+ log.info("society login: %s cannot ask here (%s)", agent_id, exc)+ return _nobody(site)+ return await self._status(service, request_id, key, site)++ async def _check_existing(self, request_id: str) -> ToolResult:+ service = self._runtime.chat_service()+ try:+ await service.restore_credential_requests(self._session_id)+ spec = service.credential_request_spec(self._session_id, request_id)+ except (AttributeError, KeyError): # An unknown id is the visible tool error.+ return ToolResult(+ success=False,+ output=None,+ error="No login card with that id in this chat.",+ )+ return await self._status(service, request_id, spec.env, spec.label)++ async def _status(self, service: Any, request_id: str, key: str, site: str) -> ToolResult:+ status = await service.wait_credential_request(self._session_id, request_id, 0)+ if status is None:+ return ToolResult(+ success=True,+ output={+ "status": "waiting",+ "request_id": request_id,+ "site": site,+ "note": (+ "The user has not saved the login yet. The card stays open until they "+ "save or cancel, also after this turn ends. Continue unrelated work or "+ "finish your reply now. Do not poll in this turn. On a later turn, check "+ f'it with {{"wait_for": "{request_id}"}}.'+ ),+ },+ )+ if status == SAVED:+ vault = credentials.current_vault()+ if vault is not None:+ return self._ready(SAVED, vault, key)+ if status == CANCELLED:+ return ToolResult(+ success=False,+ output={"status": CANCELLED, "site": site},+ error="The user stopped this turn. Do not continue the task.",+ )+ reason = (+ "The user declined to provide it."+ if status == DECLINED+ else "The card closed without a login."+ )+ return ToolResult(+ success=False,+ output={"status": status, "site": site},+ error=(+ f"{reason} No {site} login is stored. Continue without signing in where you "+ "can, and tell the user what needs it. Do not ask again in this turn."+ ),+ )++ def _ready(self, status: str, vault: Any, key: str) -> ToolResult:+ info = next((row for row in vault.list_logins(self._agent_id) if row.key == key), None)+ if info is None:+ return ToolResult(success=False, output=None, error="The login was not stored.")+ user, password = info.placeholders+ return ToolResult(+ success=True,+ output={+ "status": status,+ "site": info.label,+ "domain": info.domain,+ "username_placeholder": f"<secret>{user}</secret>",+ "password_placeholder": f"<secret>{password}</secret>",+ "note": login_usage_note(info),+ },+ )++ def _asker(self) -> str:+ cached = getattr(self._runtime, "cached_agent", None)+ agent = cached(self._agent_id) if callable(cached) else None+ return str(getattr(agent, "name", "") or "")+++def _nobody(site: str) -> ToolResult:+ return ToolResult(+ success=False,+ output={"status": "unattended", "site": site},+ error=(+ f"Nobody can enter the {site} login in this run. Report that the user has to "+ "provide it in your chat."+ ),+ )diff --git a/dodaios/society/surface.py b/dodaios/society/surface.pyindex ea58b4bad1..334c503a3f 100644--- a/dodaios/society/surface.py+++ b/dodaios/society/surface.py@@ -51,10 +51,12 @@ from .capabilities import (tool_name_for_capability,)from .coding_threads import CodingThreadTool+from .connect_tool import CONNECT_TOOL_NAME, RequestConnectToolfrom .conversation_tool import ConversationRecallTool, RoutineInvokeTool, RoutineListToolfrom .credential_tool import CREDENTIAL_TOOL_NAME, RequestCredentialToolfrom .display_name import LIVE, display_name, lead_display_namefrom .learning import RunLearnedSkillTool+from .login_tool import LOGIN_TOOL_NAME, RequestLoginToolfrom .memory import resolve_society_vaultfrom .roster import (PAIR_SESSION_MARKER,@@ -340,6 +342,10 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:tools[CREDENTIAL_TOOL_NAME] = cast(Tool, RequestCredentialTool(rt, agent_id, session_id=session_id))+ tools[LOGIN_TOOL_NAME] = cast(Tool, RequestLoginTool(rt, agent_id, session_id=session_id))+ tools[CONNECT_TOOL_NAME] = cast(+ Tool, RequestConnectTool(rt, agent_id, session_id=session_id)+ )if rt.browser.is_installed() or rt.browser.live.model_resolver is not None:from .browser.tool import BrowserTool@@ -356,7 +362,12 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:#: Tools that ask the person themselves: a gate card in front of them would ask twice.-_UNGATED: Final[tuple[str, ...]] = (ASK_USER_TOOL_NAME, CREDENTIAL_TOOL_NAME)+_UNGATED: Final[tuple[str, ...]] = (+ ASK_USER_TOOL_NAME,+ CREDENTIAL_TOOL_NAME,+ LOGIN_TOOL_NAME,+ CONNECT_TOOL_NAME,+)#: Argument keys that name WHAT a mixed-action tool does (``gmail: send``)._VERB_KEYS: Final[tuple[str, ...]] = ("action", "operation", "method", "command", "mode")@@ -900,17 +911,32 @@ async def _credential_line(rt: Any, agent_id: str) -> str:from .credentials import vault_fortry:- rows = await asyncio.to_thread(vault_for(rt.data_dir).list, agent_id)+ vault = vault_for(rt.data_dir)+ rows = await asyncio.to_thread(vault.list, agent_id)+ logins = await asyncio.to_thread(vault.list_logins, agent_id)except Exception: # noqa: BLE001 — an unreadable index costs this line, not the turnlog.warning("society: credential index unavailable for %s", agent_id, exc_info=True)return ""if not rows:- return "\nStored credentials: none."- names = ", ".join(f"{row.env} ({row.label})" if row.label else row.env for row in rows)- return (- "\nStored credentials, set as environment variables in society_shell (values are "- f"never shown to you): {names}."- )+ line = "\nStored credentials: none."+ else:+ names = ", ".join(f"{row.env} ({row.label})" if row.label else row.env for row in rows)+ line = (+ "\nStored credentials, set as environment variables in society_shell (values are "+ f"never shown to you): {names}."+ )+ if logins:+ sites = "; ".join(+ f"{info.label} on {info.domain}: <secret>{info.placeholders[0]}</secret> / "+ f"<secret>{info.placeholders[1]}</secret>"+ for info in logins+ )+ line += (+ "\nStored website logins, typed only by society_browser on their own site (write "+ f"the placeholders literally in the browser task; values are never shown to you): "+ f"{sites}."+ )+ return line# ------------------------------------------------------------------ briefingdiff --git a/dodaios/ui/web/frontend/src/components/agentchat/ChatPromptCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/ChatPromptCard.tsxnew file mode 100644index 0000000000..13804310f4--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/ChatPromptCard.tsx@@ -0,0 +1,149 @@+import { useEffect, useId, useRef, type ReactNode } from "react";+import { createPortal } from "react-dom";+import { Check, X } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++/**+ * The compact card an agent puts in the chat when the person has to do one+ * thing: sign in, connect a service. A tile (logo or key), a title, one quiet+ * line and one button. Settled, it keeps the tile and says what happened.+ */+export function ChatPromptCard({+ testId,+ tile,+ title,+ subtitle,+ action,+ settled,+}: {+ testId: string;+ tile: ReactNode;+ title: string;+ subtitle?: ReactNode;+ action?: ReactNode;+ settled?: { tone: "success" | "muted"; label: string };+}) {+ return (+ <div+ data-testid={testId}+ data-state={settled ? settled.tone : "open"}+ className="my-2 flex w-full max-w-md items-center gap-3 rounded-2xl border border-border bg-card px-3.5 py-3"+ >+ <div className="grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-xl border border-border bg-background text-muted-foreground">+ {tile}+ </div>+ <div className="min-w-0 flex-1">+ <p className="m-0 truncate text-sm font-medium text-foreground">{title}</p>+ {settled ? (+ <p+ className={cn(+ "m-0 flex items-center gap-1 truncate text-xs",+ settled.tone === "success" ? "text-emerald-500" : "text-muted-foreground",+ )}+ >+ {settled.tone === "success" ? <Check aria-hidden className="h-3.5 w-3.5 shrink-0" /> : null}+ <span className="truncate">{settled.label}</span>+ </p>+ ) : subtitle ? (+ <p className="m-0 truncate text-xs text-muted-foreground">{subtitle}</p>+ ) : null}+ </div>+ {settled ? null : action}+ </div>+ );+}++/** The card's one button: a soft pill, like the reference chat. */+export function ChatPromptButton({+ children,+ onClick,+ disabled,+ testId,+}: {+ children: ReactNode;+ onClick: () => void;+ disabled?: boolean;+ testId?: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ data-testid={testId}+ className="shrink-0 rounded-full bg-muted px-4 py-1.5 text-sm font-medium text-foreground transition-colors hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"+ >+ {children}+ </button>+ );+}++/** A small centred popup over the chat; Escape or the backdrop closes it. */+export function ChatPopup({+ title,+ tile,+ onClose,+ children,+ testId,+}: {+ title: string;+ tile?: ReactNode;+ onClose: () => void;+ children: ReactNode;+ testId?: string;+}) {+ const t = useT();+ const titleId = useId();+ const panel = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const previous = document.activeElement as HTMLElement | null;+ panel.current?.querySelector<HTMLElement>("input, button[type=submit]")?.focus();+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => {+ window.removeEventListener("keydown", onKey);+ previous?.focus?.();+ };+ }, [onClose]);+ return createPortal(+ <div+ className="fixed inset-0 z-[80] grid place-items-center bg-black/50 p-4"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget) onClose();+ }}+ >+ <div+ ref={panel}+ role="dialog"+ aria-modal="true"+ aria-labelledby={titleId}+ data-testid={testId}+ className="w-full max-w-sm rounded-2xl border border-border bg-card p-5 text-foreground shadow-2xl"+ >+ <div className="mb-4 flex items-center gap-3">+ {tile ? (+ <div className="grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-xl border border-border bg-background text-muted-foreground">+ {tile}+ </div>+ ) : null}+ <h2 id={titleId} className="m-0 min-w-0 flex-1 truncate text-base font-semibold">+ {title}+ </h2>+ <button+ type="button"+ onClick={onClose}+ aria-label={t("login_card.close")}+ className="grid h-8 w-8 place-items-center rounded-full text-muted-foreground hover:bg-muted"+ >+ <X aria-hidden className="h-4 w-4" />+ </button>+ </div>+ {children}+ </div>+ </div>,+ document.body,+ );+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/ConnectCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/ConnectCard.tsxnew file mode 100644index 0000000000..d4406f6384--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/ConnectCard.tsx@@ -0,0 +1,251 @@+import { memo, useEffect, useRef, useState } from "react";+import { fill, useT } from "@/i18n";+import { AgentChatApiError, declineAgentChatCredential, submitAgentChatCredential } from "@/lib/agentChatApi";+import { requestPluginFocus } from "@/lib/customConnector";+import { openExternalUrl } from "@/lib/openExternal";+import { useEventStore } from "@/store/events";+import { useAgentChat } from "./AgentChatStoreContext";+import { ChatPromptButton, ChatPromptCard } from "./ChatPromptCard";+import { ToolChoiceIcon } from "./ToolChoiceChips";+import type { CredentialState } from "./reduce";+import type { ToolChoice } from "./toolChoices";++/**+ * An agent asks the person to connect a plugin or CLI+ * (dodaios/society/connect_tool.py). The card shows the service's logo and a+ * Connect button that runs the same sign-in as the Plugins and CLIs pages.+ * Once the service reports connected, the card tells the agent's chat; the+ * backend checks the connection again before the agent hears "connected".+ */++const POLL_MS = 2_500;+const GIVE_UP_MS = 10 * 60_000;++type Phase =+ | { kind: "idle" }+ | { kind: "waiting"; code?: string; verifyUrl?: string }+ | { kind: "failed"; message: string };++function iconRow(credential: CredentialState): ToolChoice {+ const plugin = credential.kind === "plugin";+ return {+ id: `${plugin ? "plugin" : "cli"}:${credential.env}`,+ label: credential.label,+ description: "",+ category: plugin ? "plugins" : "cli",+ group: "",+ brand: credential.env,+ available: false,+ tool_names: [],+ skill: "",+ };+}++async function postJson(url: string, body?: unknown): Promise<Record<string, unknown>> {+ const res = await fetch(url, {+ method: "POST",+ headers: body === undefined ? undefined : { "Content-Type": "application/json" },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) throw new Error(String(data.error_code ?? data.detail ?? `HTTP ${res.status}`));+ return data;+}++async function pluginConnected(id: string): Promise<boolean> {+ const res = await fetch("/api/marketplace/plugins");+ if (!res.ok) return false;+ const data = (await res.json()) as { plugins?: { id: string; status?: string }[] };+ return (data.plugins ?? []).some((p) => p.id === id && p.status === "connected");+}++async function cliConnected(name: string): Promise<{ connected: boolean; installed: boolean }> {+ const data = await postJson(`/api/clis/${encodeURIComponent(name)}/check`);+ return { connected: Boolean(data.connected), installed: Boolean(data.installed) };+}++export const ConnectCard = memo(function ConnectCard({ credential }: { credential: CredentialState }) {+ const t = useT();+ const sessionId = useAgentChat((s) => s.activeSessionId);+ const setActiveSection = useEventStore((s) => s.setActiveSection);+ const [phase, setPhase] = useState<Phase>({ kind: "idle" });+ const [resolved, setResolved] = useState<string | null>(null);+ const stop = useRef<() => void>(() => {});+ const reporting = useRef(false);+ const status = resolved ?? credential.status;+ const label = credential.label;+ const tile = <ToolChoiceIcon row={iconRow(credential)} size={24} />;++ useEffect(() => () => stop.current(), []);++ const report = async (value: "connected" | "declined") => {+ if (reporting.current || !sessionId) return;+ reporting.current = true;+ try {+ const result =+ value === "connected"+ ? await submitAgentChatCredential(sessionId, credential.requestId, "connected")+ : await declineAgentChatCredential(sessionId, credential.requestId);+ stop.current();+ setResolved(result.status);+ } catch (err) {+ reporting.current = false;+ const closed = err instanceof AgentChatApiError && (err.status === 404 || err.status === 410);+ // "not_connected": the service is not ready yet; keep watching.+ if (closed) setPhase({ kind: "failed", message: t("credential_card.expired") });+ }+ };++ /** Watch until the service is connected, then report it once. */+ const watch = (check: () => Promise<boolean>) => {+ stop.current();+ let alive = true;+ const started = Date.now();+ const tick = async () => {+ if (!alive) return;+ try {+ if (await check()) {+ alive = false;+ await report("connected");+ return;+ }+ } catch {+ // A failed check is retried on the next tick.+ }+ if (Date.now() - started > GIVE_UP_MS) {+ alive = false;+ setPhase({ kind: "failed", message: t("connect_card.timeout") });+ return;+ }+ timer = window.setTimeout(() => void tick(), POLL_MS);+ };+ let timer = window.setTimeout(() => void tick(), POLL_MS);+ stop.current = () => {+ alive = false;+ window.clearTimeout(timer);+ };+ };++ const connectPlugin = async () => {+ const id = credential.env;+ let flow: Record<string, unknown>;+ try {+ flow = await postJson(`/api/marketplace/plugins/${encodeURIComponent(id)}/connect/start`);+ } catch {+ // Token paste, an instance address or a pending client: the Plugins page+ // has the full dialog. The card keeps watching for the connection.+ requestPluginFocus(id);+ setActiveSection("plugins");+ setPhase({ kind: "waiting" });+ watch(() => pluginConnected(id));+ return;+ }+ const flowId = String(flow.flow_id ?? "");+ if (flow.kind === "device_flow") {+ const verifyUrl = String(flow.verification_uri_complete ?? flow.verification_uri ?? "");+ if (verifyUrl) await openExternalUrl(verifyUrl);+ setPhase({ kind: "waiting", code: String(flow.user_code ?? ""), verifyUrl });+ } else {+ if (flow.open_url) await openExternalUrl(String(flow.open_url));+ setPhase({ kind: "waiting" });+ }+ if (flow.kind === "local" || !flowId) {+ watch(() => pluginConnected(id));+ return;+ }+ watch(async () => {+ const res = await fetch(+ `/api/marketplace/plugins/${encodeURIComponent(id)}/connect/poll/${encodeURIComponent(flowId)}`,+ );+ if (res.status === 404) return pluginConnected(id);+ const data = (await res.json()) as { state?: string; error?: string };+ if (data.state === "error") {+ stop.current();+ setPhase({ kind: "failed", message: fill(t("connect_card.failed"), { label }) });+ return false;+ }+ return data.state === "connected";+ });+ };++ const connectCli = async () => {+ const name = credential.env;+ const state = await cliConnected(name).catch(() => ({ connected: false, installed: true }));+ if (state.connected) {+ await report("connected");+ return;+ }+ await postJson(`/api/clis/${encodeURIComponent(name)}/spawn-external`, {+ kind: state.installed ? "login" : "install",+ method: null,+ });+ setPhase({ kind: "waiting" });+ watch(async () => (await cliConnected(name)).connected);+ };++ const connect = () => {+ setPhase({ kind: "waiting" });+ const run = credential.kind === "plugin" ? connectPlugin : connectCli;+ run().catch(() => setPhase({ kind: "failed", message: fill(t("connect_card.failed"), { label }) }));+ };++ if (status !== null) {+ const done = status === "saved";+ return (+ <ChatPromptCard+ testId="connect-card"+ tile={tile}+ title={fill(t("connect_card.title"), { label })}+ settled={{+ tone: done ? "success" : "muted",+ label: fill(t(done ? "connect_card.connected" : "connect_card.declined"), { label }),+ }}+ />+ );+ }++ const subtitle =+ phase.kind === "waiting"+ ? phase.code+ ? fill(t("connect_card.code"), { code: phase.code })+ : t("connect_card.waiting")+ : phase.kind === "failed"+ ? phase.message+ : credential.description || fill(t("connect_card.subtitle"), { agent: credential.asker || t("credential_card.fallback_agent") });++ return (+ <div className="flex flex-col">+ <ChatPromptCard+ testId="connect-card"+ tile={tile}+ title={fill(t("connect_card.title"), { label })}+ subtitle={subtitle}+ action={+ <span className="flex shrink-0 items-center gap-1">+ {phase.kind !== "waiting" ? (+ <button+ type="button"+ onClick={() => void report("declined")}+ className="rounded-full px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-muted"+ >+ {t("connect_card.not_now")}+ </button>+ ) : null}+ <ChatPromptButton onClick={connect} disabled={phase.kind === "waiting"} testId="connect-card-connect">+ {phase.kind === "waiting" ? t("connect_card.connecting") : t("connect_card.connect")}+ </ChatPromptButton>+ </span>+ }+ />+ {phase.kind === "waiting" && phase.verifyUrl ? (+ <button+ type="button"+ onClick={() => void openExternalUrl(phase.verifyUrl!)}+ className="-mt-1 mb-2 ml-1 self-start text-xs text-muted-foreground underline-offset-2 hover:underline"+ >+ {t("connect_card.open_again")}+ </button>+ ) : null}+ </div>+ );+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsxindex 501ad14082..637c7e216f 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx+++ b/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx@@ -4,6 +4,8 @@ import { fill, useT } from "@/i18n";import { AgentChatApiError, declineAgentChatCredential, submitAgentChatCredential, type CredentialResult } from "@/lib/agentChatApi";import { useAgentChat } from "./AgentChatStoreContext";import { ActionCard } from "./actionCard/ActionCard";+import { ConnectCard } from "./ConnectCard";+import { LoginCard } from "./LoginCard";import type { CredentialState } from "./reduce";/**@@ -16,6 +18,12 @@ import type { CredentialState } from "./reduce";*/export const CredentialCard = memo(function CredentialCard({ credential }: { credential: CredentialState }) {+ if (credential.kind === "login") return <LoginCard credential={credential} />;+ if (credential.kind === "plugin" || credential.kind === "cli") return <ConnectCard credential={credential} />;+ return <TokenCard credential={credential} />;+});++function TokenCard({ credential }: { credential: CredentialState }) {const t = useT();const descriptionId = useId();const agent = credential.asker || t("credential_card.fallback_agent");@@ -29,7 +37,7 @@ export const CredentialCard = memo(function CredentialCard({ credential }: { cre)}</div>);-});+}function OpenCard({ credential, descriptionId }: { credential: CredentialState; descriptionId: string }) {const t = useT();diff --git a/dodaios/ui/web/frontend/src/components/agentchat/LoginCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/LoginCard.tsxnew file mode 100644index 0000000000..6bf291ae5e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/LoginCard.tsx@@ -0,0 +1,201 @@+import { memo, useId, useRef, useState, type FormEvent } from "react";+import { KeyRound, Lock, ShieldCheck } from "lucide-react";+import { fill, useT } from "@/i18n";+import { AgentChatApiError, declineAgentChatCredential, submitAgentChatCredential } from "@/lib/agentChatApi";+import { useAgentChat } from "./AgentChatStoreContext";+import { ChatPopup, ChatPromptButton, ChatPromptCard } from "./ChatPromptCard";+import type { CredentialState } from "./reduce";++/**+ * An agent asks to sign in to a website for the person+ * (dodaios/society/login_tool.py). The card opens a small form; the username+ * and password go from it to the agent's vault in one request and are never+ * kept in the chat. The agent's browser types them only on that site, and the+ * agent itself only ever sees placeholders.+ */+export const LoginCard = memo(function LoginCard({ credential }: { credential: CredentialState }) {+ const t = useT();+ const [open, setOpen] = useState(false);+ const [resolved, setResolved] = useState<string | null>(null);+ const status = resolved ?? credential.status;+ const site = credential.label;+ const title = fill(t("login_card.title"), { site });+ if (status !== null) {+ const saved = status === "saved";+ return (+ <ChatPromptCard+ testId="login-card"+ tile={<KeyRound aria-hidden className="h-4 w-4" strokeWidth={1.75} />}+ title={title}+ settled={{+ tone: saved ? "success" : "muted",+ label: fill(t(saved ? "login_card.saved" : "login_card.declined"), { site }),+ }}+ />+ );+ }+ return (+ <>+ <ChatPromptCard+ testId="login-card"+ tile={<KeyRound aria-hidden className="h-4 w-4" strokeWidth={1.75} />}+ title={title}+ subtitle={t("login_card.subtitle")}+ action={+ <ChatPromptButton onClick={() => setOpen(true)} testId="login-card-open">+ {t("login_card.open")}+ </ChatPromptButton>+ }+ />+ {open ? (+ <LoginForm credential={credential} onClose={() => setOpen(false)} onDone={(s) => { setResolved(s); setOpen(false); }} />+ ) : null}+ </>+ );+});++function hostOf(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./, "");+ } catch {+ return "";+ }+}++function LoginForm({+ credential,+ onClose,+ onDone,+}: {+ credential: CredentialState;+ onClose: () => void;+ onDone: (status: string) => void;+}) {+ const t = useT();+ const sessionId = useAgentChat((s) => s.activeSessionId);+ const [username, setUsername] = useState("");+ const [password, setPassword] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const sending = useRef(false);+ const errorId = useId();+ const agent = credential.asker || t("credential_card.fallback_agent");+ const host = hostOf(credential.url);++ const failure = (err: unknown): string => {+ if (err instanceof AgentChatApiError) {+ if (err.code === "storage_failed") return t("login_card.storage_failed");+ if (err.code === "request_busy") return t("credential_card.request_busy");+ if (err.code === "request_closed" || err.status === 404 || err.status === 410) return t("credential_card.expired");+ if (err.status === 400 || err.status === 422) return t("login_card.invalid");+ }+ if (err instanceof TypeError) return t("credential_card.network_error");+ return t("login_card.failed");+ };++ const run = async (action: (sid: string) => Promise<{ ok: boolean; status: string; request_id: string }>, expected: string) => {+ if (sending.current || !sessionId) return;+ sending.current = true;+ setBusy(true);+ setError(null);+ try {+ const result = await action(sessionId);+ if (!result.ok || result.status !== expected || result.request_id !== credential.requestId) {+ throw new AgentChatApiError("credential-unconfirmed", 502);+ }+ setUsername("");+ setPassword("");+ onDone(result.status);+ } catch (err) {+ setError(failure(err));+ sending.current = false;+ setBusy(false);+ }+ };++ const submit = (event: FormEvent) => {+ event.preventDefault();+ if (!username.trim() || !password) return;+ const body = JSON.stringify({ username: username.trim(), password });+ void run((sid) => submitAgentChatCredential(sid, credential.requestId, body), "saved");+ };++ const field =+ "h-[38px] w-full rounded-lg border border-border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60";++ return (+ <ChatPopup+ title={fill(t("login_card.title"), { site: credential.label })}+ tile={<Lock aria-hidden className="h-4 w-4" strokeWidth={1.75} />}+ onClose={onClose}+ testId="login-form"+ >+ {credential.description ? (+ <p className="m-0 mb-3 text-sm leading-6 text-muted-foreground [overflow-wrap:anywhere]">+ {credential.description}+ </p>+ ) : null}+ <form onSubmit={submit} className="flex flex-col gap-2.5" aria-describedby={error ? errorId : undefined}>+ <label className="flex flex-col gap-1 text-xs font-medium text-muted-foreground">+ {t("login_card.username")}+ <input+ type="text"+ value={username}+ onChange={(event) => setUsername(event.target.value)}+ disabled={busy}+ autoComplete="off"+ autoCorrect="off"+ autoCapitalize="off"+ spellCheck={false}+ data-1p-ignore+ data-lpignore="true"+ name={`login-user-${credential.requestId}`}+ maxLength={1024}+ className={field}+ />+ </label>+ <label className="flex flex-col gap-1 text-xs font-medium text-muted-foreground">+ {t("login_card.password")}+ <input+ type="password"+ value={password}+ onChange={(event) => setPassword(event.target.value)}+ disabled={busy}+ autoComplete="new-password"+ data-1p-ignore+ data-lpignore="true"+ name={`login-pass-${credential.requestId}`}+ maxLength={1024}+ className={field}+ />+ </label>+ <p className="m-0 flex items-start gap-1.5 text-xs leading-5 text-muted-foreground">+ <ShieldCheck aria-hidden className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <span>{fill(t("login_card.footer"), { agent, host: host || credential.label })}</span>+ </p>+ {error ? (+ <p id={errorId} role="alert" className="m-0 text-xs text-destructive">+ {error}+ </p>+ ) : null}+ <div className="mt-1 flex items-center justify-between gap-2">+ <button+ type="button"+ onClick={() => void run((sid) => declineAgentChatCredential(sid, credential.requestId), "declined")}+ disabled={busy}+ className="rounded-full px-3 py-1.5 text-sm text-muted-foreground hover:bg-muted disabled:opacity-60"+ >+ {t("login_card.decline")}+ </button>+ <button+ type="submit"+ disabled={busy || !username.trim() || !password}+ className="rounded-full bg-foreground px-4 py-1.5 text-sm font-medium text-background transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ {busy ? t("credential_card.saving") : t("login_card.save")}+ </button>+ </div>+ </form>+ </ChatPopup>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/agentchat/LoginConnectCards.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/LoginConnectCards.test.tsxnew file mode 100644index 0000000000..d472fd49d9--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentchat/LoginConnectCards.test.tsx@@ -0,0 +1,102 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { ThreadTurn } from "@/components/agentic/threads/ThreadTimeline";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import { createAgentChatStore } from "@/store/agentChat";+import { AgentChatStoreProvider } from "./AgentChatStoreContext";+import { EMPTY_TIMELINE, reduceEvents, type ToolBlock, type TurnItem } from "./reduce";++let seq = 0;+function ev(kind: string, payload: Record<string, unknown>): AgentChatEvent {+ return { seq: ++seq, ts_ms: 1000, kind, payload } as AgentChatEvent;+}++const USER = "[email protected]";+const PASSWORD = "correct horse battery";++function card(tool: string, payload: Record<string, unknown>, extra: AgentChatEvent[] = []): AgentChatEvent[] {+ return [+ ev("turn_started", { turn_id: "t1" }),+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: `mcp__jarvis__${tool}`, input: {} }),+ ev("credential_required", { turn_id: "t1", request_id: "r1", asker: "Ada", replace: false, ...payload }),+ ...extra,+ ];+}++const LOGIN = { kind: "login", env: "reddit", label: "Reddit", url: "https://www.reddit.com/login", description: "To post your thread." };+const CONNECT = { kind: "plugin", env: "github", label: "GitHub", description: "To read your issues." };++function draw(events: AgentChatEvent[]) {+ const store = createAgentChatStore("society");+ store.setState({ activeSessionId: "society:ada" });+ return render(+ <AgentChatStoreProvider store={store}>+ <ThreadTurn turn={reduceEvents(EMPTY_TIMELINE, events).items[0] as TurnItem} prompts="inline" />+ </AgentChatStoreProvider>,+ );+}++afterEach(() => {+ cleanup();+ seq = 0;+ vi.restoreAllMocks();+});++describe("login and connect cards", () => {+ it("attach to their own tool calls with their kind", () => {+ const login = reduceEvents(EMPTY_TIMELINE, card("society_request_login", LOGIN)).items[0] as TurnItem;+ expect((login.blocks[0] as ToolBlock).credential).toMatchObject({ kind: "login", url: LOGIN.url, status: null });+ const connect = reduceEvents(EMPTY_TIMELINE, card("society_request_connect", CONNECT)).items[0] as TurnItem;+ expect((connect.blocks[0] as ToolBlock).callId).toBe("c1");+ expect((connect.blocks[0] as ToolBlock).credential?.kind).toBe("plugin");+ });++ it("opens a form and sends both values in one request, never keeping them", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(JSON.stringify({ ok: true, request_id: "r1", status: "saved" }), { status: 200 }),+ );+ draw(card("society_request_login", LOGIN));+ expect(screen.getByTestId("login-card").textContent).toContain("Reddit");+ fireEvent.click(screen.getByTestId("login-card-open"));+ const form = screen.getByTestId("login-form");+ const [user, pass] = Array.from(form.querySelectorAll("input"));+ expect(pass.getAttribute("type")).toBe("password");+ fireEvent.change(user, { target: { value: ` ${USER} ` } });+ fireEvent.change(pass, { target: { value: PASSWORD } });+ fireEvent.submit(form.querySelector("form")!);+ await waitFor(() => expect(screen.queryByTestId("login-form")).toBeNull());+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toContain("/credentials/r1");+ expect(JSON.parse(JSON.parse(String(init.body)).value)).toEqual({ username: USER, password: PASSWORD });+ expect(screen.getByTestId("login-card").getAttribute("data-state")).toBe("success");+ expect(document.body.innerHTML).not.toContain(PASSWORD);+ });++ it("shows the saved state once the login is resolved", () => {+ draw(card("society_request_login", LOGIN, [+ ev("credential_resolved", { turn_id: "t1", request_id: "r1", env: "reddit", status: "saved" }),+ ]));+ expect(screen.getByTestId("login-card").getAttribute("data-state")).toBe("success");+ expect(screen.queryByTestId("login-card-open")).toBeNull();+ });++ it("offers Connect with the service's name and closes once connected", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {+ const url = String(input);+ if (url.endsWith("/connect/start")) {+ return new Response(JSON.stringify({ flow_id: "f1", plugin_id: "github", kind: "local", open_url: null }), { status: 200 });+ }+ if (url === "/api/marketplace/plugins") {+ return new Response(JSON.stringify({ plugins: [{ id: "github", status: "connected" }] }), { status: 200 });+ }+ return new Response(JSON.stringify({ ok: true, request_id: "r1", status: "saved" }), { status: 200 });+ });+ draw(card("society_request_connect", CONNECT));+ expect(screen.getByTestId("connect-card").textContent).toContain("GitHub");+ fireEvent.click(screen.getByTestId("connect-card-connect"));+ await waitFor(() => expect(screen.getByTestId("connect-card").getAttribute("data-state")).toBe("success"), { timeout: 6000 });+ const reported = fetchMock.mock.calls.find(([url]) => String(url).includes("/credentials/r1"));+ expect(JSON.parse(String((reported![1] as RequestInit).body)).value).toBe("connected");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.tsindex b68cf5ebaa..0d3169df55 100644--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts@@ -141,6 +141,14 @@ export function isQuestionTool(name: string): boolean {export interface CredentialState {requestId: string;asker: string;+ /**+ * `token`: one secret value. `login`: a website username and password+ * (society/login_tool.py). `plugin` / `cli`: connect a service+ * (society/connect_tool.py); then `env` is the plugin id or CLI name.+ */+ kind: CredentialKind;+ /** The sign-in page of a `login` card. */+ url: string;env: string;label: string;description: string;@@ -150,11 +158,19 @@ export interface CredentialState {status: string | null;}+export type CredentialKind = "token" | "login" | "plugin" | "cli";+/** The tool an agent asks for a credential with — bare or behind an MCP prefix. */export const CREDENTIAL_TOOL = "society_request_credential";+/** The tools that open the same kind of card: a website login, a connection. */+const CARD_TOOLS = [CREDENTIAL_TOOL, "society_request_login", "society_request_connect"];export function isCredentialTool(name: string): boolean {- return name === CREDENTIAL_TOOL || name.endsWith(`__${CREDENTIAL_TOOL}`);+ return CARD_TOOLS.some((tool) => name === tool || name.endsWith(`__${tool}`));+}++function credentialKind(raw: unknown): CredentialKind {+ return raw === "login" || raw === "plugin" || raw === "cli" ? raw : "token";}/** The call shows a card the person answers: a question or a credential field. */@@ -1266,6 +1282,8 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const credential: CredentialState = {requestId,asker: str(p.asker),+ kind: credentialKind(p.kind),+ url: str(p.url),env,label: str(p.label) || env,description: str(p.description),diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex c29a113e67..82f8b3507f 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -7597,6 +7597,36 @@"request_busy": "Dieser Token wird bereits geprüft. Warte kurz und versuche es dann erneut.","failed": "Die Zugangsdaten konnten nicht gespeichert werden."},+ "login_card": {+ "title": "Bei {site} anmelden",+ "subtitle": "Öffnet ein sicheres Formular",+ "open": "Öffnen",+ "username": "Benutzername oder E-Mail",+ "password": "Passwort",+ "footer": "Sicher gespeichert. {agent} sieht es nie; der Browser tippt es nur auf {host} ein.",+ "save": "Speichern",+ "decline": "Nicht jetzt",+ "close": "Schließen",+ "saved": "{site}-Login gespeichert",+ "declined": "{site}-Login nicht angegeben",+ "invalid": "Gib den Benutzernamen oder die E-Mail und das Passwort ein.",+ "storage_failed": "Der Login konnte nicht sicher gespeichert werden. Bitte versuche es erneut.",+ "failed": "Der Login konnte nicht gespeichert werden."+ },+ "connect_card": {+ "title": "{label} verbinden",+ "subtitle": "{agent} braucht das, um weiterzumachen",+ "connect": "Verbinden",+ "connecting": "Verbinde…",+ "not_now": "Nicht jetzt",+ "waiting": "Schließ die Anmeldung ab, die Karte aktualisiert sich selbst",+ "code": "Gib auf der Anmeldeseite den Code {code} ein",+ "open_again": "Anmeldeseite erneut öffnen",+ "timeout": "Noch keine Verbindung. Drück auf Verbinden, um es erneut zu versuchen.",+ "failed": "{label} konnte nicht verbunden werden. Versuch es erneut.",+ "connected": "{label} verbunden",+ "declined": "{label} nicht verbunden"+ },"question_card": {"aria": "Rückfrage des Agenten","title_one": "{agent} hat eine Frage",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex ee37101bb2..0ee7f74fd4 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -7597,6 +7597,36 @@"request_busy": "This token is already being checked. Please wait, then try again.","failed": "The credential could not be stored."},+ "login_card": {+ "title": "Sign in to {site}",+ "subtitle": "Opens a secure form",+ "open": "Open",+ "username": "Username or email",+ "password": "Password",+ "footer": "Stored securely. {agent} never sees it; the browser types it only on {host}.",+ "save": "Save",+ "decline": "Not now",+ "close": "Close",+ "saved": "{site} login saved",+ "declined": "{site} login not provided",+ "invalid": "Enter the username or email and the password.",+ "storage_failed": "The login could not be saved securely. Please try again.",+ "failed": "The login could not be stored."+ },+ "connect_card": {+ "title": "Connect {label}",+ "subtitle": "{agent} needs this to continue",+ "connect": "Connect",+ "connecting": "Connecting…",+ "not_now": "Not now",+ "waiting": "Finish signing in, the card updates by itself",+ "code": "Enter code {code} on the sign-in page",+ "open_again": "Open the sign-in page again",+ "timeout": "No connection yet. Press Connect to try again.",+ "failed": "{label} could not be connected. Try again.",+ "connected": "{label} connected",+ "declined": "{label} not connected"+ },"question_card": {"aria": "Question from the agent","title_one": "{agent} has a question",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex c55324f152..4eba4c32f9 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -7597,6 +7597,36 @@"request_busy": "Este token ya se está comprobando. Espera un momento e inténtalo de nuevo.","failed": "No se pudo guardar la credencial."},+ "login_card": {+ "title": "Iniciar sesión en {site}",+ "subtitle": "Abre un formulario seguro",+ "open": "Abrir",+ "username": "Usuario o correo",+ "password": "Contraseña",+ "footer": "Se guarda de forma segura. {agent} nunca lo ve; el navegador solo lo escribe en {host}.",+ "save": "Guardar",+ "decline": "Ahora no",+ "close": "Cerrar",+ "saved": "Inicio de sesión de {site} guardado",+ "declined": "Inicio de sesión de {site} no proporcionado",+ "invalid": "Introduce el usuario o correo y la contraseña.",+ "storage_failed": "No se pudo guardar el inicio de sesión de forma segura. Inténtalo de nuevo.",+ "failed": "No se pudo guardar el inicio de sesión."+ },+ "connect_card": {+ "title": "Conectar {label}",+ "subtitle": "{agent} lo necesita para continuar",+ "connect": "Conectar",+ "connecting": "Conectando…",+ "not_now": "Ahora no",+ "waiting": "Termina de iniciar sesión; la tarjeta se actualiza sola",+ "code": "Introduce el código {code} en la página de inicio de sesión",+ "open_again": "Abrir de nuevo la página de inicio de sesión",+ "timeout": "Aún no hay conexión. Pulsa Conectar para intentarlo de nuevo.",+ "failed": "No se pudo conectar {label}. Inténtalo de nuevo.",+ "connected": "{label} conectado",+ "declined": "{label} no conectado"+ },"question_card": {"aria": "Pregunta del agente","title_one": "{agent} tiene una pregunta",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex dd4c288b70..5a34af4003 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -7597,6 +7597,36 @@"request_busy": "Este token já está a ser verificado. Aguarda e tenta novamente.","failed": "Não foi possível guardar a credencial."},+ "login_card": {+ "title": "Entrar em {site}",+ "subtitle": "Abre um formulário seguro",+ "open": "Abrir",+ "username": "Utilizador ou e-mail",+ "password": "Palavra-passe",+ "footer": "Guardado em segurança. {agent} nunca o vê; o navegador só o escreve em {host}.",+ "save": "Guardar",+ "decline": "Agora não",+ "close": "Fechar",+ "saved": "Início de sessão de {site} guardado",+ "declined": "Início de sessão de {site} não fornecido",+ "invalid": "Introduz o utilizador ou e-mail e a palavra-passe.",+ "storage_failed": "Não foi possível guardar o início de sessão em segurança. Tenta novamente.",+ "failed": "Não foi possível guardar o início de sessão."+ },+ "connect_card": {+ "title": "Ligar {label}",+ "subtitle": "{agent} precisa disto para continuar",+ "connect": "Ligar",+ "connecting": "A ligar…",+ "not_now": "Agora não",+ "waiting": "Conclui o início de sessão; o cartão atualiza-se sozinho",+ "code": "Introduz o código {code} na página de início de sessão",+ "open_again": "Abrir novamente a página de início de sessão",+ "timeout": "Ainda sem ligação. Carrega em Ligar para tentar novamente.",+ "failed": "Não foi possível ligar {label}. Tenta novamente.",+ "connected": "{label} ligado",+ "declined": "{label} não ligado"+ },"question_card": {"aria": "Pergunta do agente","title_one": "{agent} tem uma pergunta",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 084535bf49..d78d1f9c05 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -7597,6 +7597,36 @@"request_busy": "正在检查此令牌。请稍等后重试。","failed": "无法保存凭据。"},+ "login_card": {+ "title": "登录 {site}",+ "subtitle": "打开安全表单",+ "open": "打开",+ "username": "用户名或邮箱",+ "password": "密码",+ "footer": "已安全保存。{agent} 永远看不到它;浏览器只会在 {host} 上输入。",+ "save": "保存",+ "decline": "暂不",+ "close": "关闭",+ "saved": "{site} 登录信息已保存",+ "declined": "未提供 {site} 登录信息",+ "invalid": "请输入用户名或邮箱以及密码。",+ "storage_failed": "无法安全保存登录信息,请重试。",+ "failed": "无法保存登录信息。"+ },+ "connect_card": {+ "title": "连接 {label}",+ "subtitle": "{agent} 需要它才能继续",+ "connect": "连接",+ "connecting": "正在连接…",+ "not_now": "暂不",+ "waiting": "完成登录后,卡片会自动更新",+ "code": "在登录页面输入代码 {code}",+ "open_again": "再次打开登录页面",+ "timeout": "尚未连接。点击连接重试。",+ "failed": "无法连接 {label},请重试。",+ "connected": "{label} 已连接",+ "declined": "{label} 未连接"+ },"question_card": {"aria": "智能体的提问","title_one": "{agent} 有一个问题",diff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.pyindex 398830dd83..8714bdb026 100644--- a/dodaios/ui/web/society_routes.py+++ b/dodaios/ui/web/society_routes.py@@ -741,6 +741,42 @@ async def delete_agent_credential(agent_id: str, env: str, request: Request) ->return {"ok": True, "env": env}+ "/agents/{agent_id}/logins",+ summary="List the website logins an agent stored (sites only, never the values)",+)+async def list_agent_logins(agent_id: str, request: Request) -> dict[str, Any]:+ from dodaios.society.credentials import vault_for++ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ rows = await asyncio.to_thread(vault_for(rt.data_dir).list_logins, agent.agent_id)+ return {"agent_id": agent.agent_id, "logins": [row.to_dict() for row in rows]}+++ "/agents/{agent_id}/logins/{key}",+ summary="Delete one of an agent's stored website logins",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def delete_agent_login(agent_id: str, key: str, request: Request) -> dict[str, Any]:+ from dodaios.society.credentials import CredentialError, vault_for++ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ try:+ deleted = await asyncio.to_thread(vault_for(rt.data_dir).delete_login, agent.agent_id, key)+ except CredentialError as exc:+ raise HTTPException(500, str(exc)) from exc+ if not deleted:+ raise HTTPException(404, "no such login")+ return {"ok": True, "key": key}++async def _valid_group_members(rt: SocietyRuntime, members: list[str]) -> list[str]:if len(set(members)) != len(members):raise HTTPException(422, "group members must be unique")diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 5bfa2547eb..d40686b6c7 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -122,6 +122,12 @@ WITHHELD: Final[dict[str, str]] = {"DELETE /api/society/agents/{agent_id}/credentials/{env}": ("deleting a stored credential breaks the agent's work and stays with the owner"),+ "GET /api/society/agents/{agent_id}/logins": (+ "an agent's stored website logins are the owner's business, managed in the app only"+ ),+ "DELETE /api/society/agents/{agent_id}/logins/{key}": (+ "deleting a stored login breaks the agent's sign-in and stays with the owner"+ ),"POST /api/society/agents/{agent_id}/kill": ("kill_switch stops the whole house; killing ONE agent's runs needs the ""context of watching them, which a remote client does not have"diff --git a/tests/unit/society/test_agent_logins.py b/tests/unit/society/test_agent_logins.pynew file mode 100644index 0000000000..64c12621b2--- /dev/null+++ b/tests/unit/society/test_agent_logins.py@@ -0,0 +1,293 @@+"""Website logins and connect cards: the agent signs in and connects without seeing secrets."""++from __future__ import annotations++import asyncio+import json+import sys+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.agent_chat.credential_requests import CLI, LOGIN, PLUGIN, CredentialSpec+from dodaios.agent_chat.service import AgentChatService, _Running+from dodaios.agent_chat.store import AgentChatStore+from dodaios.society import connect_tool, credentials+from dodaios.society.connect_tool import RequestConnectTool, Target+from dodaios.society.credentials import CredentialError, CredentialVault, login_key, login_site+from dodaios.society.login_tool import LOGIN_TOOL_NAME, RequestLoginTool+from tests.fakes.fake_secret_store import FakeSecretStore++USER = "[email protected]"+PASSWORD = "c0rrect horse battery" # noqa: S105 — a test value+SID = "society:ada"+++def vault(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> CredentialVault:+ store = CredentialVault(tmp_path / "credentials", secrets=FakeSecretStore())+ monkeypatch.setattr(credentials, "current_vault", lambda: store)+ return store+++# ------------------------------------------------------------------ the vault+++def test_a_site_is_bound_to_its_registrable_domain() -> None:+ assert login_site("https://www.reddit.com/login") == (+ "https://www.reddit.com/login", "reddit.com"+ )+ assert login_site("news.ycombinator.com/login")[1] == "ycombinator.com"+ assert login_site("https://forum.example.co.uk/")[1] == "example.co.uk"+ for bad in ("", "localhost", "http://127.0.0.1/login", "ftp://example.com", "co.uk"):+ with pytest.raises(CredentialError):+ login_site(bad)+ assert login_key("Hacker News") == "hacker_news"+ assert login_key("9gag") == "site_9gag"+ with pytest.raises(CredentialError):+ login_key(" ")+++def test_a_login_keeps_its_values_out_of_the_index(vault: CredentialVault) -> None:+ vault.store("ada", "GITHUB_TOKEN", "ghp_" + "x" * 30)+ info = vault.store_login(+ "ada", "reddit", f" {USER} ", PASSWORD, url="https://www.reddit.com/login", label="Reddit"+ )+ assert info.placeholders == ("reddit_username", "reddit_password")+ assert vault.has_login("ada", "reddit") and not vault.has_login("bob", "reddit")+ index = next(vault._root.glob("*.json")).read_text(encoding="utf-8")+ assert USER not in index and PASSWORD not in index+ assert json.loads(index)["logins"][0]["domain"] == "reddit.com"+ # Tokens and logins share the index file; writing one keeps the other.+ assert [row.env for row in vault.list("ada")] == ["GITHUB_TOKEN"]+ assert vault.browser_secrets("ada") == {+ "*.reddit.com": {"reddit_username": USER, "reddit_password": PASSWORD}+ }+ # Logins never become shell variables.+ assert set(vault.shell_env("ada")) == {"GITHUB_TOKEN"}+ vault.delete("ada", "GITHUB_TOKEN")+ assert [row.key for row in vault.list_logins("ada")] == ["reddit"]+ assert vault.delete_login("ada", "reddit") and not vault.delete_login("ada", "reddit")+ assert vault.browser_secrets("ada") == {}+++def test_both_login_values_are_masked_wherever_they_show_up(vault: CredentialVault) -> None:+ vault.store_login("ada", "reddit", USER, PASSWORD, url="reddit.com")+ masked = vault.redact_payload("ada", {"text": f"signed in as {USER} with {PASSWORD}"})+ assert USER not in json.dumps(masked) and PASSWORD not in json.dumps(masked)+ assert "[credential reddit password]" in masked["text"]+++def test_bad_logins_are_refused_and_nothing_is_kept(tmp_path: Path) -> None:+ vault = CredentialVault(tmp_path, secrets=FakeSecretStore())+ for user, password in (("", PASSWORD), (USER, ""), (USER, "two\nlines"), (USER, None)):+ with pytest.raises(CredentialError):+ vault.store_login("ada", "reddit", user, password, url="reddit.com")+ refusing = CredentialVault(tmp_path, secrets=FakeSecretStore(refuse=True))+ with pytest.raises(CredentialError):+ refusing.store_login("ada", "reddit", USER, PASSWORD, url="reddit.com")+ assert refusing.list_logins("ada") == []+++# ------------------------------------------------------------------ the login card+++async def _service_with_turn(tmp_path: Path, session_id: str = SID):+ svc = AgentChatService(AgentChatStore(":memory:"), assistant_name=lambda: "Testo")+ session = svc.store.create_session(+ provider="fakeprov", model="m", effort="high", cwd=str(tmp_path),+ session_id=session_id, surface="society",+ )+ run = _Running("turn-1", asyncio.Event())+ run.task = asyncio.create_task(asyncio.sleep(3600))+ svc._running[session.session_id] = run+ return svc, session.session_id, run.task+++async def _next(q: asyncio.Queue, kind: str) -> dict[str, Any]:+ while True:+ ev = await asyncio.wait_for(q.get(), timeout=5)+ if ev["kind"] == kind:+ return ev["payload"]+++def _runtime(service: Any) -> SimpleNamespace:+ return SimpleNamespace(+ chat_service=lambda: service, cached_agent=lambda _id: SimpleNamespace(name="Ada")+ )+++_LOGIN_ARGS = {+ "site": "Reddit",+ "url": "https://www.reddit.com/login",+ "description": "To post your launch thread.",+}+++async def test_the_login_card_saves_both_values_and_the_agent_gets_placeholders(+ tmp_path: Path, vault+) -> None:+ svc, sid, task = await _service_with_turn(tmp_path)+ q = svc.subscribe(sid)+ tool = RequestLoginTool(_runtime(svc), "ada", session_id=sid)+ first = await asyncio.wait_for(tool.execute(dict(_LOGIN_ARGS), None), timeout=1)+ assert first.success and first.output["status"] == "waiting"+ card = await _next(q, "credential_required")+ assert card["kind"] == LOGIN and card["env"] == "reddit" and card["label"] == "Reddit"+ assert card["url"] == "https://www.reddit.com/login" and card["asker"] == "Ada"+ with pytest.raises(CredentialError): # a half-filled form keeps the card open+ await svc.submit_credential(sid, card["request_id"], json.dumps({"username": USER}))+ body = json.dumps({"username": USER, "password": PASSWORD})+ assert await svc.submit_credential(sid, card["request_id"], body)+ result = await tool.execute({"wait_for": card["request_id"]}, None)+ assert result.success and result.output["status"] == "saved"+ expected = "<secret>reddit_password</secret>"+ assert result.output["password_placeholder"] == expected # noqa: S105+ assert result.output["domain"] == "reddit.com"+ leaked = json.dumps(result.output) + json.dumps(svc.store.list_events(sid))+ assert USER not in leaked and PASSWORD not in leaked+ again = await tool.execute(dict(_LOGIN_ARGS), None)+ assert again.success and again.output["status"] == "available"+ task.cancel()+++async def test_a_restored_login_card_still_saves_into_the_vault(tmp_path: Path, vault) -> None:+ spec = CredentialSpec.build(+ "reddit", "Reddit", "why", kind=LOGIN, url="https://www.reddit.com/login"+ )+ save = AgentChatService._restore_credential_save(SID, spec)+ assert save is not None+ await save(json.dumps({"username": USER, "password": PASSWORD}))+ assert vault.browser_secrets("ada")["*.reddit.com"]["reddit_username"] == USER+++async def test_bad_login_requests_never_open_a_card(vault) -> None:+ opened: list[Any] = []+ service = SimpleNamespace(open_credential_request=lambda *a, **k: opened.append(a))+ tool = RequestLoginTool(_runtime(service), "ada", session_id=SID)+ for bad in ({"url": "http://10.0.0.1/"}, {"site": " "}, {"description": " "}):+ result = await tool.execute({**_LOGIN_ARGS, **bad}, None)+ assert not result.success and "invalid request" in (result.error or "")+ routine = RequestLoginTool(_runtime(service), "ada", session_id="society:ada:routine:t:r")+ assert (await routine.execute(dict(_LOGIN_ARGS), None)).output["status"] == "unattended"+ assert opened == []+++def test_the_login_and_connect_tools_are_offered_outside_routines(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from dodaios.society import surface++ browser = SimpleNamespace(is_installed=lambda: False, live=SimpleNamespace(model_resolver=None))+ rt = SimpleNamespace(browser=browser, chat_service=lambda: None, cached_agent=lambda _: None)+ monkeypatch.setattr(surface, "current_runtime", lambda: rt)+ canonical = SimpleNamespace(session_id="society:ada", cwd="", permission_mode="")+ routine = SimpleNamespace(+ session_id="society:ada:routine:t1:run1", cwd="", permission_mode="bypass"+ )+ offered = surface.society_tools(None, None, canonical)+ assert LOGIN_TOOL_NAME in offered and connect_tool.CONNECT_TOOL_NAME in offered+ assert LOGIN_TOOL_NAME not in surface.society_tools(None, None, routine)+++async def test_the_briefing_names_stored_logins_by_placeholder(+ tmp_path: Path, vault, monkeypatch: pytest.MonkeyPatch+) -> None:+ from dodaios.society.surface import _credential_line++ monkeypatch.setattr(credentials, "vault_for", lambda _data_dir: vault)+ vault.store_login("ada", "hacker_news", USER, PASSWORD, url="news.ycombinator.com")+ line = await _credential_line(SimpleNamespace(data_dir=tmp_path), "ada")+ assert "<secret>hacker_news_password</secret>" in line+ assert vault.list_logins("ada")[0].domain == "ycombinator.com"+ assert USER not in line and PASSWORD not in line+++# ------------------------------------------------------------------ the browser+++def _runner():+ previous = sys.stdout+ try:+ from dodaios.society.browser import live_runner+ finally:+ sys.stdout = previous+ return live_runner+++def test_the_runner_hands_back_placeholders_instead_of_typed_values() -> None:+ live_runner = _runner()+ secrets = {"*.reddit.com": {"reddit_username": USER, "reddit_password": PASSWORD}}+ result = live_runner.scrub_secrets(+ secrets, {"final_result": f"Logged in as {USER}", "errors": [f"bad {PASSWORD}"]}+ )+ assert result == {+ "final_result": "Logged in as <secret>reddit_username</secret>",+ "errors": ["bad <secret>reddit_password</secret>"],+ }+ assert live_runner.typed_secret({"input": {"index": 3, "text": "<secret>x</secret>"}})+ assert not live_runner.typed_secret({"input": {"index": 3, "text": "hello"}})+ assert live_runner.scrub_secrets(None, {"a": 1}) == {"a": 1}+++async def test_the_browser_run_receives_only_this_agents_logins(vault) -> None:+ from dodaios.society.browser.bridge import stored_logins++ vault.store_login("ada", "reddit", USER, PASSWORD, url="reddit.com")+ assert await stored_logins("ada") == {+ "*.reddit.com": {"reddit_username": USER, "reddit_password": PASSWORD}+ }+ assert await stored_logins("bob") == {}+++# ------------------------------------------------------------------ the connect card+++async def test_the_connect_card_closes_only_once_the_service_is_connected(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ state = {"connected": False}++ def resolve(kind: str, raw: str) -> Target | None:+ if raw != "github":+ return None+ return Target(kind, "github", "GitHub", state["connected"])++ monkeypatch.setattr(connect_tool, "resolve_target", resolve)+ svc, sid, task = await _service_with_turn(tmp_path)+ q = svc.subscribe(sid)+ tool = RequestConnectTool(_runtime(svc), "ada", session_id=sid)+ args = {"kind": PLUGIN, "id": "github", "reason": "To read your open issues."}+ first = await tool.execute(dict(args), None)+ assert first.success and first.output["status"] == "waiting"+ card = await _next(q, "credential_required")+ assert card["kind"] == PLUGIN and card["env"] == "github" and card["label"] == "GitHub"+ with pytest.raises(CredentialError): # the card cannot claim a connection that is not there+ await svc.submit_credential(sid, card["request_id"], "connected")+ state["connected"] = True+ assert await svc.submit_credential(sid, card["request_id"], "connected")+ done = await tool.execute({"wait_for": card["request_id"]}, None)+ assert done.success and done.output["status"] == "connected"+ again = await tool.execute(dict(args), None)+ assert again.output["status"] == "connected" # no second card+ unknown = await tool.execute({**args, "id": "nope"}, None)+ assert not unknown.success and "no plugin named" in (unknown.error or "")+ wrong = await tool.execute({**args, "kind": "mcp"}, None)+ assert not wrong.success+ task.cancel()+++async def test_a_restored_connect_card_still_checks_the_connection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ connect_tool, "resolve_target", lambda kind, raw: Target(kind, raw, "gh", False)+ )+ save = AgentChatService._restore_credential_save(+ SID, CredentialSpec.build("gh", "GitHub CLI", "why", kind=CLI)+ )+ assert save is not None+ with pytest.raises(CredentialError):+ await save("connected")diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.pyindex 839fee71c3..93d62970c2 100644--- a/tests/unit/society/test_surface.py+++ b/tests/unit/society/test_surface.py@@ -174,6 +174,8 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pa"society_invoke_routine","society_ask_user","society_request_credential",+ "society_request_login",+ "society_request_connect","society_share_template",*FOLDER,}@@ -197,6 +199,8 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pa"society_invoke_routine","society_ask_user","society_request_credential",+ "society_request_login",+ "society_request_connect","society_share_template",*FOLDER,}