From af5f3c4ec1526bb64c7ad0bb791014720d92ad81 Mon Sep 17 00:00:00 2001 From: Mauricio Morales <99351019+mauriciomdb@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:20:16 +0000 Subject: [PATCH 1/3] =?UTF-8?q?feat(agent):=20message=20people=20as=20an?= =?UTF-8?q?=20agent=20=E2=80=94=20connect,=20ask,=20replies=20and=20a=20si?= =?UTF-8?q?gned=20webhook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dailybot agent connect mints an agent credential with the login session and stores it in messenger.json (0600, token never printed). agent ask asks one person (options for a one-tap decision, --wait to block for the answer; exit 124 on timeout), agent replies returns new answers with a stored cursor, and agent webhook set/show/remove manage the signed webhook. The older API-key agent webhook and message commands are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AY6kxNxkCZG2pPJSh1Bxer --- AGENTS.md | 7 +- README.md | 20 + dailybot_cli/api_client.py | 151 ++++++ dailybot_cli/commands/agent.py | 28 +- dailybot_cli/commands/agent_messenger.py | 604 +++++++++++++++++++++++ dailybot_cli/config.py | 93 ++++ dailybot_cli/display.py | 114 +++++ docs/API_REFERENCE.md | 32 ++ docs/CONFIGURATION.md | 5 + tests/agent_messenger_test.py | 456 +++++++++++++++++ 10 files changed, 1507 insertions(+), 3 deletions(-) create mode 100644 dailybot_cli/commands/agent_messenger.py create mode 100644 tests/agent_messenger_test.py diff --git a/AGENTS.md b/AGENTS.md index 16cd3e1..c5064e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,8 +106,10 @@ dailybot_cli/ # Source package ├── version.py # `dailybot version` — install info + PyPI update check ├── upgrade.py # `dailybot upgrade` — auto-detect install method + self-update ├── uninstall.py # `dailybot uninstall` — auto-detect install method + remove - └── agent.py # `agent` group: configure, profiles, register, - # update, health, webhook, message, email + ├── agent.py # `agent` group: configure, profiles, register, + │ # update, health, webhook, message, email + └── agent_messenger.py # `agent connect / me / ask / replies`, `agent webhook + # set|show|remove` (agent credential, /v1/messaging/agents/) tests/ # pytest suite (file naming: *_test.py) ├── api_client_test.py # HTTP client mocking (all DailyBotClient methods) @@ -176,6 +178,7 @@ tests/ # pytest suite (file naming: *_test.py) ├── milestones_updates_test.py # milestone attachments/restore; project update get/edit/delete/attachments ├── tasks_reactions_test.py # reactions: who reacted, project-update react/unreact, full reactor lists ├── transport_errors_test.py # transport failures render as messages, not tracebacks +├── agent_messenger_test.py # agent messenger: store, wire (Agent scheme, no fallback), commands └── config_test.py # Config/credential file management .github/workflows/release.yml # Tag-triggered: PyPI + Linux binary + Homebrew diff --git a/README.md b/README.md index 335d4cc..7bbc0e1 100644 --- a/README.md +++ b/README.md @@ -603,6 +603,21 @@ Once installed, your agent **auto-routes by intent** — "report this to Dailybo > This repo **dogfoods** the skill: the pack is vendored at [`.agents/skills/dailybot/`](.agents/skills/dailybot/) so any agent working on the CLI uses it too. +### Ask a person and wait for the answer + +An agent can ask you (or a teammate) a question through Dailybot and wait for the reply — a one-tap decision when you give options. Organizations on the new Dailybot only. + +```bash +dailybot login # once, as the person who owns the agent +dailybot agent connect "Release bot" # once: stores the agent credential (mode 600) + +dailybot agent ask --to me@example.com "Deploy to production now?" \ + --option Yes --option "Not yet" --wait 30m --json # exit 0 answered, 124 timed out + +dailybot agent replies --wait 10m # answers since the last call +dailybot agent webhook set https://my-agent.example.com/dailybot # or get them pushed (signed) +``` + ### Quick start (interactive) If you only do one thing on a fresh install, run: @@ -1213,6 +1228,11 @@ same delivery path as `chat send`). | `dailybot agent register` | Register a new agent and organization (standalone) | | `dailybot agent update` | Submit an agent activity report | | `dailybot agent health` | Report or query agent health status | +| `dailybot agent connect ""` | Connect an agent you own so it can message people (needs `dailybot login`) | +| `dailybot agent me` | Show the agent behind the stored messenger credential | +| `dailybot agent ask --to ""` | Ask a person; `--option` for a one-tap decision, `--wait` to block for the answer | +| `dailybot agent replies` | Answers since the last call (`--wait`, `--follow`) | +| `dailybot agent webhook set ` / `show` / `remove` | The messenger webhook (signed with `X-Dailybot-Signature`) | | `dailybot agent webhook register` | Register a webhook for the agent | | `dailybot agent webhook unregister` | Unregister the agent's webhook | | `dailybot agent message send` | Send a message to an agent | diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 0855cbd..e21d04d 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -362,6 +362,16 @@ def _fill_meta(meta: dict[str, Any] | None, result: "PaginatedResult") -> None: # send it down the wrong recovery path. EXIT_TRANSPORT_ERROR: int = 8 +# Agent messenger (`dailybot agent connect / ask / replies / webhook`). An agent +# credential is sent as `Authorization: Agent dbagt_…` and only to the messaging doors. +MESSAGING_AGENTS_PATH: str = "/v1/messaging/agents/" +AGENT_TOKEN_SCHEME: str = "Agent" +AGENT_TOKEN_PREFIX: str = "dbagt_" +AGENT_CREDENTIAL_MODE: str = "agent" +MESSENGER_MAX_WAIT_SECS: int = 25 # the server's long-poll ceiling for /replies/ +# The ask body names the person with this field (participant id `usr_…` or email). +MESSENGER_ASK_PERSON_FIELD: str = "person" + class TransportError(httpx.HTTPError): """Raised when a request never produced a readable HTTP response. @@ -2631,6 +2641,147 @@ def open_conversation(self, users_uuids: list[str]) -> dict[str, Any]: ) return self._handle_response(response) + # --- Agent messenger (/v1/messaging/agents/…) --- + # + # `connect` is a person door (the `dailybot login` session as Bearer). Every other + # door here authenticates as the agent itself with `Authorization: Agent dbagt_…` + # and never falls back to another credential: the agent token is the identity. + # Messaging errors use one envelope, `{code, message, detail, retry_after, + # request_id}`, parsed by `_handle_messaging_response`. + + def _handle_messaging_response(self, response: httpx.Response) -> dict[str, Any]: + """Like :meth:`_handle_response`, for the messaging error envelope.""" + if response.status_code < 400: + return self._handle_response(response) + code: str | None = None + message: str = _fallback_detail(response) + retry_after: float | None = None + try: + body: Any = response.json() + except Exception: + body = None + if isinstance(body, dict): + raw_code: Any = body.get("code") + if isinstance(raw_code, str): + code = raw_code + raw_message: Any = body.get("message") or body.get("detail") + if isinstance(raw_message, str) and raw_message: + message = raw_message + raw_retry: Any = body.get("retry_after") + if isinstance(raw_retry, (int, float)) and not isinstance(raw_retry, bool): + retry_after = float(raw_retry) + if retry_after is None: + header_retry: str | None = response.headers.get("Retry-After") + if header_retry: + try: + retry_after = float(header_retry) + except ValueError: + retry_after = None + raise APIError( + status_code=response.status_code, + detail=message, + code=code, + retry_after=retry_after, + credential=self._agent_auth_mode, + ) + + def _agent_credential_request( + self, + method: str, + path: str, + agent_token: str, + *, + json: dict[str, Any] | None = None, + params: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: + """One request as the agent (`Authorization: Agent `), no fallback.""" + headers: dict[str, str] = _base_headers() + headers["Authorization"] = f"{AGENT_TOKEN_SCHEME} {agent_token}" + self._agent_auth_mode = AGENT_CREDENTIAL_MODE + kwargs: dict[str, Any] = { + "headers": headers, + "timeout": self.timeout if timeout is None else timeout, + } + if json is not None: + kwargs["json"] = json + if params is not None: + kwargs["params"] = params + response: httpx.Response = self._dispatch_guarded( + method, f"{self.api_url}{MESSAGING_AGENTS_PATH}{path}", **kwargs + ) + return self._handle_messaging_response(response) + + def messenger_connect(self, name: str, description: str | None = None) -> dict[str, Any]: + """POST /v1/messaging/agents/connect/ — the signed-in person connects an agent. + + Returns ``{"agent": {...}, "credential": {"id", "prefix", "token"}}``; the + token is shown once. The same name reuses the agent and mints a new credential. + """ + payload: dict[str, Any] = {"name": name} + if description: + payload["description"] = description + # A person door: the organization API key is never offered, not even as the + # fallback, so a refusal names the session's real problem. + api_key: str | None = self.api_key + self.api_key = None + try: + response: httpx.Response = self._request( + "POST", f"{self.api_url}{MESSAGING_AGENTS_PATH}connect/", json=payload + ) + finally: + self.api_key = api_key + return self._handle_messaging_response(response) + + def messenger_me(self, agent_token: str) -> dict[str, Any]: + """GET /v1/messaging/agents/me/ — the agent behind the credential.""" + return self._agent_credential_request("GET", "me/", agent_token) + + def messenger_ask( + self, + agent_token: str, + person: str, + text: str, + options: list[str] | None = None, + ) -> dict[str, Any]: + """POST /v1/messaging/agents/me/ask/ — ask one person (email or `usr_…` id).""" + payload: dict[str, Any] = {MESSENGER_ASK_PERSON_FIELD: person, "text": text} + if options: + payload["options"] = list(options) + return self._agent_credential_request("POST", "me/ask/", agent_token, json=payload) + + def messenger_replies( + self, agent_token: str, after: str | None = None, wait: int = 0 + ) -> dict[str, Any]: + """GET /v1/messaging/agents/me/replies/?after=&wait= — new answers, long-polled. + + ``wait`` is clamped to the server's 0..25 seconds; the read timeout leaves + room for the whole wait. + """ + bounded: int = max(0, min(int(wait), MESSENGER_MAX_WAIT_SECS)) + params: dict[str, Any] = {"wait": bounded} + if after: + params["after"] = after + return self._agent_credential_request( + "GET", + "me/replies/", + agent_token, + params=params, + timeout=self.timeout + bounded, + ) + + def messenger_webhook_get(self, agent_token: str) -> dict[str, Any]: + """GET /v1/messaging/agents/me/webhook/""" + return self._agent_credential_request("GET", "me/webhook/", agent_token) + + def messenger_webhook_set(self, agent_token: str, url: str) -> dict[str, Any]: + """PUT /v1/messaging/agents/me/webhook/ — the answer carries the secret, once.""" + return self._agent_credential_request("PUT", "me/webhook/", agent_token, json={"url": url}) + + def messenger_webhook_delete(self, agent_token: str) -> dict[str, Any]: + """DELETE /v1/messaging/agents/me/webhook/""" + return self._agent_credential_request("DELETE", "me/webhook/", agent_token) + # --- Agent message endpoints --- def send_agent_message( diff --git a/dailybot_cli/commands/agent.py b/dailybot_cli/commands/agent.py index fc84c18..538935a 100644 --- a/dailybot_cli/commands/agent.py +++ b/dailybot_cli/commands/agent.py @@ -9,6 +9,15 @@ from dailybot_cli import ledger from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli.commands.agent_messenger import ( + agent_ask, + agent_connect, + agent_me, + agent_replies, + webhook_remove, + webhook_set, + webhook_show, +) from dailybot_cli.commands.public_api_helpers import agent_error_message from dailybot_cli.config import ( RepoEnvError, @@ -746,7 +755,13 @@ def agent_health( @agent.group(name="webhook") def agent_webhook() -> None: - """Manage agent webhooks.""" + """Manage agent webhooks. + + \b + set / show / remove the agent messenger webhook (agent credential from + `dailybot agent connect`; signed deliveries of replies) + register / unregister the older agent-message webhook (API key or login) + """ pass @@ -1124,3 +1139,14 @@ def _attempt_register() -> dict[str, Any]: # Display result result["profile"] = slug print_registration_result(result) + + +# --- Agent messenger (agent credential from `agent connect`) --- + +agent.add_command(agent_connect) +agent.add_command(agent_me) +agent.add_command(agent_ask) +agent.add_command(agent_replies) +agent_webhook.add_command(webhook_set) +agent_webhook.add_command(webhook_show) +agent_webhook.add_command(webhook_remove) diff --git a/dailybot_cli/commands/agent_messenger.py b/dailybot_cli/commands/agent_messenger.py new file mode 100644 index 0000000..574f8dc --- /dev/null +++ b/dailybot_cli/commands/agent_messenger.py @@ -0,0 +1,604 @@ +"""Agent messenger commands: an agent asks a person through Dailybot and reads the answers. + +``dailybot agent connect`` (person door, needs ``dailybot login``) mints an agent +credential and stores it in ``messenger.json`` (0o600) under the agent profile slug. +``agent ask``, ``agent replies``, ``agent me`` and ``agent webhook set|show|remove`` +then authenticate as the agent itself (``Authorization: Agent dbagt_…``) against +``/v1/messaging/agents/…``. The older ``agent message`` / ``agent webhook +register|unregister`` commands (org API key flow) are untouched. + +The commands are registered on the ``agent`` group in ``commands/agent.py``. +""" + +import re +import time +from typing import Any, NoReturn + +import click + +from dailybot_cli.api_client import ( + AGENT_CREDENTIAL_MODE, + AGENT_TOKEN_PREFIX, + MESSENGER_MAX_WAIT_SECS, + APIError, + DailyBotClient, +) +from dailybot_cli.commands.public_api_helpers import ( + EXIT_NOT_AUTHENTICATED, + EXIT_NOT_FOUND, + EXIT_PERMISSION_DENIED, + EXIT_RATE_LIMITED, + EXIT_USAGE_ERROR, + emit_json, +) +from dailybot_cli.config import ( + MESSENGER_DEFAULT_PROFILE, + RepoProfileError, + get_api_url, + get_default_profile, + get_messenger_credential, + get_person_token, + load_repo_profile, + save_messenger_credential, + set_messenger_cursor, +) +from dailybot_cli.display import ( + print_error, + print_info, + print_messenger_agent, + print_messenger_connected, + print_messenger_question, + print_messenger_replies, + print_messenger_reply, + print_messenger_webhook, + print_success, + print_warning, +) + +# `agent ask --wait` gave up before anyone answered. Not 2: Click and this CLI use 2 +# for usage errors, and an agent must never read a typo as "nobody answered yet". +# 124 is the exit status `timeout(1)` uses for the same condition. +EXIT_ASK_TIMED_OUT: int = 124 +EXIT_GENERIC_ERROR: int = 1 + +ASK_MIN_OPTIONS: int = 2 +ASK_MAX_OPTIONS: int = 6 +# A long-poll page that answered at once: drain at most this many pages per call. +REPLIES_MAX_DRAIN_PAGES: int = 50 +# Between two follow polls when the server answered at once with nothing (no busy loop). +FOLLOW_IDLE_PAUSE_SECS: float = 1.0 +DURATION_MAX_SECS: int = 7 * 24 * 60 * 60 + +_DURATION_UNITS: dict[str, int] = {"s": 1, "m": 60, "h": 3600, "d": 86400} +_DURATION_RE: re.Pattern[str] = re.compile(r"^(?:(\d+)([smhd]))+$") +_DURATION_PART_RE: re.Pattern[str] = re.compile(r"(\d+)([smhd])") + +_FEATURE_DISABLED_CODE: str = "feature_disabled" +_NOT_CONNECTED_MESSAGE: str = ( + "This agent is not connected to Dailybot yet. Run: " + 'dailybot agent connect "" (after dailybot login)' +) +_MESSAGING_OFF_MESSAGE: str = ( + "Dailybot messaging is not available for this organization. Agents can message " + "people only in organizations on the new Dailybot." +) + + +class DurationType(click.ParamType): + """``30s``, ``10m``, ``1h30m``, ``2d`` or a bare number of seconds.""" + + name = "duration" + + def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> int: + if isinstance(value, int): + return value + text: str = str(value).strip().lower() + seconds: int + if text.isdigit(): + seconds = int(text) + elif _DURATION_RE.fullmatch(text): + seconds = sum( + int(amount) * _DURATION_UNITS[unit] + for amount, unit in _DURATION_PART_RE.findall(text) + ) + else: + self.fail(f"{value!r} is not a duration. Use e.g. 90s, 10m, 1h30m.", param, ctx) + if seconds <= 0 or seconds > DURATION_MAX_SECS: + self.fail("A duration must be between 1 second and 7 days.", param, ctx) + return seconds + + +DURATION: DurationType = DurationType() + + +# --- context ----------------------------------------------------------------- + + +def _profile_slug(ctx: click.Context, profile_flag: str | None) -> str: + """Which stored credential to use. + + ``-p`` on the command, then ``-p`` on the ``agent`` group, then the repo's + ``.dailybot/profile.json`` profile, then the agents.json default, then ``default``. + """ + if profile_flag: + return profile_flag + group_profile: Any = (ctx.obj or {}).get("profile") if isinstance(ctx.obj, dict) else None + if group_profile: + return str(group_profile) + try: + repo: dict[str, Any] = load_repo_profile() or {} + except RepoProfileError as exc: + print_error(str(exc)) + raise SystemExit(EXIT_GENERIC_ERROR) + if repo.get("profile"): + return str(repo["profile"]) + default: dict[str, Any] | None = get_default_profile() + if default and default.get("profile"): + return str(default["profile"]) + return MESSENGER_DEFAULT_PROFILE + + +def _fail(message: str, exit_code: int, json_mode: bool, code: str | None = None) -> NoReturn: + if json_mode: + emit_json({"error": message, "code": code, "exit_code": exit_code}) + else: + print_error(message) + raise SystemExit(exit_code) + + +def _agent_context(profile: str, json_mode: bool) -> tuple[DailyBotClient, str]: + """The client and the agent token for *profile*, bound to the host that minted it.""" + stored: dict[str, Any] | None = get_messenger_credential(profile) + if not stored: + _fail(_NOT_CONNECTED_MESSAGE, EXIT_NOT_AUTHENTICATED, json_mode, "not_connected") + minted_on: str = str(stored.get("api_url") or "").rstrip("/") + current: str = get_api_url().rstrip("/") + if minted_on and minted_on != current: + # Like the login session: a credential only travels to the API that issued it. + _fail( + f"The agent credential for profile '{profile}' belongs to {minted_on}, not " + f"{current}. Run dailybot agent connect again against this API.", + EXIT_NOT_AUTHENTICATED, + json_mode, + "credential_host_mismatch", + ) + return DailyBotClient(api_url=minted_on or None), str(stored["token"]) + + +def _exit_for_messenger_error(exc: APIError, json_mode: bool) -> NoReturn: + """Map a messaging refusal to a message and the CLI's shared exit codes.""" + code: str | None = exc.code + message: str = exc.detail or f"Request failed ({exc.status_code})." + exit_code: int = EXIT_GENERIC_ERROR + if exc.status_code == 401: + exit_code = EXIT_NOT_AUTHENTICATED + if exc.credential == AGENT_CREDENTIAL_MODE: + message = ( + "The agent credential was refused (revoked or expired). Run " + 'dailybot agent connect "" again.' + ) + else: + message = "Your Dailybot session has expired. Run: dailybot login" + elif code == _FEATURE_DISABLED_CODE: + exit_code = EXIT_PERMISSION_DENIED + message = _MESSAGING_OFF_MESSAGE + elif exc.status_code in (402, 403): + exit_code = EXIT_PERMISSION_DENIED + elif exc.status_code == 404: + exit_code = EXIT_NOT_FOUND + elif exc.status_code == 429: + exit_code = EXIT_RATE_LIMITED + if exc.retry_after: + message = f"{message} Retry in about {int(exc.retry_after)} seconds." + elif exc.status_code == 400: + exit_code = EXIT_USAGE_ERROR + _fail(message, exit_code, json_mode, code) + + +def _results(page: dict[str, Any]) -> list[dict[str, Any]]: + raw: Any = page.get("results") + return [item for item in raw if isinstance(item, dict)] if isinstance(raw, list) else [] + + +# --- connect / me -------------------------------------------------------------- + + +@click.command(name="connect") +@click.argument("name") +@click.option("--description", default=None, help="What the agent does (shown to people).") +@click.option("--profile", "-p", default=None, help="Profile to store the credential under.") +@click.option("--json", "json_mode", is_flag=True, default=False, help="Machine-readable output.") +@click.pass_context +def agent_connect( + ctx: click.Context, + name: str, + description: str | None, + profile: str | None, + json_mode: bool, +) -> None: + """Connect this agent to Dailybot so it can message people. + + Needs `dailybot login`. The agent acts in your organization and you are its + owner. Running it again with the same NAME reuses the agent and replaces the + stored credential with a fresh one. The credential is saved with mode 600 and + never printed; only its prefix is shown. + + \b + Examples: + dailybot agent connect "Release bot" + dailybot agent connect "Release bot" --description "Ships the API" -p release + """ + slug: str = _profile_slug(ctx, profile) + if not get_person_token(): + _fail( + "Connecting an agent needs a signed-in person. Run: dailybot login", + EXIT_NOT_AUTHENTICATED, + json_mode, + "not_authenticated", + ) + client: DailyBotClient = DailyBotClient(prefer_api_key=False) + try: + result: dict[str, Any] = client.messenger_connect(name, description) + except APIError as exc: + if exc.status_code == 404 and exc.code is None: + _fail( + "This Dailybot API does not offer agent messaging yet.", + EXIT_NOT_FOUND, + json_mode, + "not_supported", + ) + _exit_for_messenger_error(exc, json_mode) + agent_data: Any = result.get("agent") + credential: Any = result.get("credential") + token: Any = credential.get("token") if isinstance(credential, dict) else None + if ( + not isinstance(agent_data, dict) + or not isinstance(credential, dict) + or not isinstance(token, str) + or not token.startswith(AGENT_TOKEN_PREFIX) + ): + _fail( + "Dailybot answered without a usable agent credential. Try again.", + EXIT_GENERIC_ERROR, + json_mode, + "invalid_response", + ) + prefix: str = str(credential.get("prefix") or token[: len(AGENT_TOKEN_PREFIX) + 4]) + save_messenger_credential( + slug, + agent_id=str(agent_data.get("id") or ""), + agent_name=str(agent_data.get("name") or name), + token=token, + prefix=prefix, + credential_id=str(credential.get("id") or ""), + api_url=client.api_url, + ) + if json_mode: + emit_json( + { + "agent": agent_data, + "credential": {"id": credential.get("id"), "prefix": prefix}, + "profile": slug, + } + ) + return + print_messenger_connected(agent_data, prefix, slug) + print_info(f'Next: dailybot agent ask --to "Your question" -p {slug}') + + +@click.command(name="me") +@click.option("--profile", "-p", default=None, help="Profile whose credential to use.") +@click.option("--json", "json_mode", is_flag=True, default=False, help="Machine-readable output.") +@click.pass_context +def agent_me(ctx: click.Context, profile: str | None, json_mode: bool) -> None: + """Show the agent behind the stored credential (checks it still works).""" + slug: str = _profile_slug(ctx, profile) + client, token = _agent_context(slug, json_mode) + try: + agent_data: dict[str, Any] = client.messenger_me(token) + except APIError as exc: + _exit_for_messenger_error(exc, json_mode) + if json_mode: + emit_json(agent_data) + return + shown: Any = agent_data.get("agent") + print_messenger_agent(shown if isinstance(shown, dict) else agent_data, slug) + + +# --- ask ------------------------------------------------------------------------- + + +def _wait_for_answer( + client: DailyBotClient, + token: str, + question_id: str, + start_cursor: str | None, + deadline: float, +) -> dict[str, Any] | None: + """Long-poll replies until one answers *question_id* or the deadline passes. + + Reads from the profile's stored cursor without moving it, so `agent replies` + still sees every answer (including this one). + """ + cursor: str | None = start_cursor + while True: + remaining: float = deadline - time.monotonic() + if remaining <= 0: + return None + page: dict[str, Any] = client.messenger_replies(token, after=cursor, wait=int(remaining)) + for reply in _results(page): + if str(reply.get("question_id") or "") == question_id: + return reply + next_cursor: Any = page.get("next_cursor") + if isinstance(next_cursor, str) and next_cursor: + cursor = next_cursor + if not _results(page) and remaining > 1: + # The server answered early with nothing: do not spin. + time.sleep(min(FOLLOW_IDLE_PAUSE_SECS, remaining)) + + +@click.command(name="ask") +@click.argument("text") +@click.option("--to", "to", required=True, help="The person: their email or Dailybot id (usr_…).") +@click.option( + "--option", + "-o", + "options", + multiple=True, + help=f"An answer button; repeat {ASK_MIN_OPTIONS}-{ASK_MAX_OPTIONS} times for a decision.", +) +@click.option( + "--wait", + "wait", + type=DURATION, + default=None, + help="Wait this long for the answer (e.g. 90s, 30m, 2h).", +) +@click.option("--profile", "-p", default=None, help="Profile whose credential to use.") +@click.option("--json", "json_mode", is_flag=True, default=False, help="Machine-readable output.") +@click.pass_context +def agent_ask( + ctx: click.Context, + text: str, + to: str, + options: tuple[str, ...], + wait: int | None, + profile: str | None, + json_mode: bool, +) -> None: + """Ask a person a question through Dailybot. + + The person gets it in Dailybot (and their chat app) from this agent. With + --option they answer with one tap. With --wait the command blocks until they + answer or the time runs out. + + \b + Exit codes: + 0 asked (and, with --wait, answered) + 124 --wait ran out before an answer (ask again later with `agent replies`) + 2 bad flags (or the server refused the question as invalid) + 3 not connected, or the agent credential was refused + 4 this organization cannot use agent messaging + 6 rate limited (a person gets at most 10 agent questions a day) + + \b + Examples: + dailybot agent ask --to me@example.com "Deploy to production now?" \\ + --option Yes --option "Not yet" --wait 30m + dailybot agent ask --to me@example.com "Tests are green, PR is ready." --json + """ + labels: list[str] = [label.strip() for label in options if label.strip()] + if labels and not ASK_MIN_OPTIONS <= len(labels) <= ASK_MAX_OPTIONS: + _fail( + f"Give between {ASK_MIN_OPTIONS} and {ASK_MAX_OPTIONS} --option values, or none.", + EXIT_USAGE_ERROR, + json_mode, + "invalid_options", + ) + slug: str = _profile_slug(ctx, profile) + client, token = _agent_context(slug, json_mode) + stored: dict[str, Any] = get_messenger_credential(slug) or {} + start_cursor: str | None = stored.get("cursor") or None + try: + question: dict[str, Any] = client.messenger_ask(token, to, text, labels or None) + except APIError as exc: + _exit_for_messenger_error(exc, json_mode) + question_id: str = str(question.get("question_id") or "") + + if wait is None: + if json_mode: + emit_json({"status": "asked", "question": question}) + return + print_messenger_question(question, to) + print_info(f"Read the answer with: dailybot agent replies --wait 10m -p {slug}") + return + + if not json_mode: + print_messenger_question(question, to) + print_info("Waiting for the answer…") + try: + reply: dict[str, Any] | None = _wait_for_answer( + client, token, question_id, start_cursor, time.monotonic() + wait + ) + except APIError as exc: + _exit_for_messenger_error(exc, json_mode) + if reply is None: + if json_mode: + emit_json({"status": "timed_out", "question": question}) + else: + print_warning( + "No answer yet. It will still arrive: run `dailybot agent replies` later." + ) + raise SystemExit(EXIT_ASK_TIMED_OUT) + if json_mode: + emit_json({"status": "answered", "question": question, "reply": reply}) + return + print_messenger_reply(reply) + + +# --- replies ------------------------------------------------------------------- + + +def _fetch_new( + client: DailyBotClient, token: str, slug: str, cursor: str | None, wait: int +) -> tuple[list[dict[str, Any]], str | None]: + """One long-poll, then drain what is already waiting; the cursor is saved per page.""" + collected: list[dict[str, Any]] = [] + current_wait: int = wait + for _ in range(REPLIES_MAX_DRAIN_PAGES): + page: dict[str, Any] = client.messenger_replies(token, after=cursor, wait=current_wait) + results: list[dict[str, Any]] = _results(page) + next_cursor: Any = page.get("next_cursor") + if isinstance(next_cursor, str) and next_cursor and next_cursor != cursor: + cursor = next_cursor + set_messenger_cursor(slug, cursor) + collected.extend(results) + if not results: + break + current_wait = 0 + return collected, cursor + + +@click.command(name="replies") +@click.option( + "--wait", "wait", type=DURATION, default=None, help="Wait up to this long for a reply." +) +@click.option( + "--follow", "-f", is_flag=True, default=False, help="Keep printing replies until Ctrl-C." +) +@click.option("--profile", "-p", default=None, help="Profile whose credential to use.") +@click.option( + "--json", + "json_mode", + is_flag=True, + default=False, + help="Machine-readable output (one JSON object per reply with --follow).", +) +@click.pass_context +def agent_replies( + ctx: click.Context, + wait: int | None, + follow: bool, + profile: str | None, + json_mode: bool, +) -> None: + """Show the answers people sent this agent since the last call. + + The position is remembered per profile, so each call returns only new + replies. Without --wait it returns at once. + + \b + Examples: + dailybot agent replies + dailybot agent replies --wait 10m --json + dailybot agent replies --follow + """ + slug: str = _profile_slug(ctx, profile) + client, token = _agent_context(slug, json_mode) + stored: dict[str, Any] = get_messenger_credential(slug) or {} + cursor: str | None = stored.get("cursor") or None + + try: + if follow: + try: + while True: + replies, cursor = _fetch_new( + client, token, slug, cursor, MESSENGER_MAX_WAIT_SECS + ) + for reply in replies: + if json_mode: + emit_json(reply) + else: + print_messenger_reply(reply) + if not replies: + time.sleep(FOLLOW_IDLE_PAUSE_SECS) + except KeyboardInterrupt: + return + + deadline: float = time.monotonic() + (wait or 0) + replies = [] + while True: + remaining: int = max(0, int(deadline - time.monotonic())) + replies, cursor = _fetch_new(client, token, slug, cursor, remaining) + if replies or remaining <= 0: + break + if remaining > 1: + time.sleep(min(FOLLOW_IDLE_PAUSE_SECS, remaining)) + except APIError as exc: + _exit_for_messenger_error(exc, json_mode) + + if json_mode: + emit_json({"results": replies, "next_cursor": cursor}) + return + print_messenger_replies(replies) + + +# --- webhook (agent credential) ------------------------------------------------ + + +@click.command(name="set") +@click.argument("url") +@click.option("--profile", "-p", default=None, help="Profile whose credential to use.") +@click.option("--json", "json_mode", is_flag=True, default=False, help="Machine-readable output.") +@click.pass_context +def webhook_set(ctx: click.Context, url: str, profile: str | None, json_mode: bool) -> None: + """Have Dailybot POST this agent's replies to URL (https only). + + Needs `dailybot agent connect`. The answer shows the signing secret once. + Each delivery carries X-Dailybot-Signature: t=,v1=, the + HMAC-SHA256 of "." with the secret. + """ + if not url.lower().startswith("https://"): + _fail("The webhook URL must start with https://", EXIT_USAGE_ERROR, json_mode) + slug: str = _profile_slug(ctx, profile) + client, token = _agent_context(slug, json_mode) + try: + webhook: dict[str, Any] = client.messenger_webhook_set(token, url) + except APIError as exc: + _exit_for_messenger_error(exc, json_mode) + if json_mode: + emit_json(webhook) + return + print_messenger_webhook(webhook, title="Webhook set") + + +@click.command(name="show") +@click.option("--profile", "-p", default=None, help="Profile whose credential to use.") +@click.option("--json", "json_mode", is_flag=True, default=False, help="Machine-readable output.") +@click.pass_context +def webhook_show(ctx: click.Context, profile: str | None, json_mode: bool) -> None: + """Show this agent's webhook (needs `dailybot agent connect`).""" + slug: str = _profile_slug(ctx, profile) + client, token = _agent_context(slug, json_mode) + try: + webhook: dict[str, Any] = client.messenger_webhook_get(token) + except APIError as exc: + if exc.status_code == 404: + if json_mode: + emit_json({"webhook": None}) + else: + print_info("No webhook set. Replies wait for `dailybot agent replies`.") + return + _exit_for_messenger_error(exc, json_mode) + if json_mode: + emit_json(webhook) + return + print_messenger_webhook(webhook, title="Webhook") + + +@click.command(name="remove") +@click.option("--profile", "-p", default=None, help="Profile whose credential to use.") +@click.option("--json", "json_mode", is_flag=True, default=False, help="Machine-readable output.") +@click.pass_context +def webhook_remove(ctx: click.Context, profile: str | None, json_mode: bool) -> None: + """Stop webhook deliveries for this agent (needs `dailybot agent connect`).""" + slug: str = _profile_slug(ctx, profile) + client, token = _agent_context(slug, json_mode) + try: + client.messenger_webhook_delete(token) + except APIError as exc: + _exit_for_messenger_error(exc, json_mode) + if json_mode: + emit_json({"removed": True}) + return + print_success("Webhook removed. Replies wait for `dailybot agent replies`.") diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index 21b9cfc..d4309b7 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -1624,3 +1624,96 @@ def set_env_disabled(disabled: bool, *, cwd: Path | None = None) -> Path: }, cwd=cwd, ) + + +# --- Agent messenger credentials (messenger.json) --- +# +# One credential per agent profile slug, minted by `dailybot agent connect`. Kept in +# its own 0o600 file so the long-standing agents.json schema is untouched (Rule 16). +# Shape: {"profiles": {"": {"agent_id", "agent_name", "token", "prefix", +# "credential_id", "api_url", "cursor"}}}. A token is bound to the API host that +# minted it, like the login session. + +MESSENGER_FILE_NAME: str = "messenger.json" +MESSENGER_DEFAULT_PROFILE: str = "default" + + +def _messenger_path() -> Path: + return get_config_dir() / MESSENGER_FILE_NAME + + +def load_messenger() -> dict[str, Any]: + """Read messenger.json; ``{}`` when it is missing or unreadable.""" + path: Path = _messenger_path() + if not path.exists(): + return {} + try: + loaded: Any = json.loads(path.read_text()) + except (json.JSONDecodeError, OSError): + return {} + return loaded if isinstance(loaded, dict) else {} + + +def _save_messenger(data: dict[str, Any]) -> None: + _write_secret_file(_messenger_path(), json.dumps(data, indent=2)) + + +def get_messenger_credential(profile: str) -> dict[str, Any] | None: + """The stored agent credential for *profile*, or ``None``.""" + profiles: Any = load_messenger().get("profiles") + entry: Any = profiles.get(profile) if isinstance(profiles, dict) else None + if not isinstance(entry, dict) or not entry.get("token"): + return None + return {"profile": profile, **entry} + + +def save_messenger_credential( + profile: str, + *, + agent_id: str, + agent_name: str, + token: str, + prefix: str, + credential_id: str, + api_url: str, +) -> None: + """Store a freshly minted credential for *profile*. + + The reply cursor survives a new credential for the same agent on the same host; + any other change starts the cursor over. Re-read right before writing so a + concurrent cursor update is not lost. + """ + data: dict[str, Any] = load_messenger() + profiles: Any = data.get("profiles") + if not isinstance(profiles, dict): + profiles = {} + data["profiles"] = profiles + previous: Any = profiles.get(profile) + cursor: Any = None + if ( + isinstance(previous, dict) + and previous.get("agent_id") == agent_id + and previous.get("api_url") == api_url + ): + cursor = previous.get("cursor") + profiles[profile] = { + "agent_id": agent_id, + "agent_name": agent_name, + "token": token, + "prefix": prefix, + "credential_id": credential_id, + "api_url": api_url, + "cursor": cursor, + } + _save_messenger(data) + + +def set_messenger_cursor(profile: str, cursor: str | None) -> None: + """Remember where `agent replies` stopped for *profile* (no-op without a credential).""" + data: dict[str, Any] = load_messenger() + profiles: Any = data.get("profiles") + entry: Any = profiles.get(profile) if isinstance(profiles, dict) else None + if not isinstance(entry, dict): + return + entry["cursor"] = cursor + _save_messenger(data) diff --git a/dailybot_cli/display.py b/dailybot_cli/display.py index bad87b9..07b6283 100644 --- a/dailybot_cli/display.py +++ b/dailybot_cli/display.py @@ -2877,3 +2877,117 @@ def print_task_comments(comments: list[dict[str, Any]]) -> None: reacted: str = format_reactions(comment.get("reactions")) if reacted: console.print(f"{' ' if thread else ' '}{reacted}") + + +# --- Agent messenger (`dailybot agent connect / ask / replies / webhook`) --- + + +def _message_text(value: Any) -> Text: + """A person's message as plain text: control characters neutralized, newlines kept. + + ``Text`` never parses Rich markup, so a reply cannot style the terminal. + """ + lines: list[str] = [_neutralize(line) for line in str(value or "").splitlines()] + return Text("\n".join(lines) or "-") + + +def print_messenger_connected(agent: dict[str, Any], prefix: str, profile: str) -> None: + """The agent is connected; its credential is stored (only the prefix is shown).""" + table: Table = Table(show_header=False, box=None, padding=(0, 2)) + table.add_column(style="bold") + table.add_column() + table.add_row("Agent", Text(_neutralize(str(agent.get("name") or "")))) + table.add_row("Agent id", Text(_neutralize(str(agent.get("id") or "")))) + table.add_row("Credential", Text(f"{_neutralize(prefix)}… (stored, never shown)")) + table.add_row("Profile", Text(_neutralize(profile))) + console.print(Panel(table, title="[bold]Agent connected[/bold]", border_style="green")) + + +def print_messenger_agent(agent: dict[str, Any], profile: str) -> None: + """`agent me`: the agent behind the stored credential.""" + table: Table = Table(show_header=False, box=None, padding=(0, 2)) + table.add_column(style="bold") + table.add_column() + for key in ("name", "id", "description", "owner", "scopes"): + value: Any = agent.get(key) + if value in (None, "", [], {}): + continue + if isinstance(value, dict): + value = value.get("name") or value.get("email") or value.get("id") or "" + if isinstance(value, list): + value = ", ".join(str(item) for item in value) + table.add_row(key.capitalize(), Text(_neutralize(str(value)))) + table.add_row("Profile", Text(_neutralize(profile))) + console.print(Panel(table, title="[bold]Agent[/bold]", border_style="cyan")) + + +def print_messenger_question(question: dict[str, Any], to: str) -> None: + """The question was delivered.""" + options: Any = question.get("options") or [] + print_success(f"Asked {_neutralize(to)}.") + table: Table = Table(show_header=False, box=None, padding=(0, 2)) + table.add_column(style="bold") + table.add_column() + table.add_row("Question id", Text(_neutralize(str(question.get("question_id") or "")))) + table.add_row("Conversation", Text(_neutralize(str(question.get("conversation_id") or "")))) + if isinstance(options, list) and options: + labels: list[str] = [ + _neutralize(str(item.get("label") if isinstance(item, dict) else item)) + for item in options + ] + table.add_row("Options", Text(" | ".join(labels))) + console.print(table) + + +def print_messenger_reply(reply: dict[str, Any]) -> None: + """One answer: who, when, the choice (when a button was used) and the text.""" + sender: Any = reply.get("from") or {} + who: str = "" + if isinstance(sender, dict): + who = str(sender.get("name") or sender.get("email") or sender.get("id") or "") + header: Text = Text() + header.append(_neutralize(who) or "Someone", style="bold") + created: Any = reply.get("created_at") + if created: + header.append(f" {_neutralize(str(created))}", style="dim") + question_id: Any = reply.get("question_id") + if question_id: + header.append(f" question {_neutralize(str(question_id))}", style="dim") + console.print(header) + choice: Any = reply.get("choice") + if isinstance(choice, dict) and choice.get("label") is not None: + console.print(Text.assemble((" Choice: ", "bold"), _neutralize(str(choice.get("label"))))) + text: Any = reply.get("text") + if text: + body: Text = _message_text(text) + body.pad_left(2) + console.print(body) + + +def print_messenger_replies(replies: list[dict[str, Any]]) -> None: + """A batch of answers, or a quiet note when there are none.""" + if not replies: + print_info("No new replies.") + return + for reply in replies: + print_messenger_reply(reply) + + +def print_messenger_webhook(webhook: dict[str, Any], *, title: str) -> None: + """The agent's webhook; the secret appears only on the answer that carries it.""" + table: Table = Table(show_header=False, box=None, padding=(0, 2)) + table.add_column(style="bold") + table.add_column() + for key, value in webhook.items(): + if key == "secret" or value in (None, "", [], {}) or isinstance(value, (dict, list)): + continue + table.add_row(key.replace("_", " ").capitalize(), Text(_neutralize(str(value)))) + secret: Any = webhook.get("secret") + if secret: + table.add_row("Secret", Text(_neutralize(str(secret)))) + console.print(Panel(table, title=f"[bold]{escape(title)}[/bold]", border_style="green")) + if secret: + print_warning( + "The secret is shown only now. Store it where your receiver can read it; " + "it verifies the X-Dailybot-Signature header." + ) diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 9e6a821..f55c1ed 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -508,6 +508,26 @@ A health POST also drains pending messages — that's why `claim-all` is impleme Webhook URL receives `POST` with body containing the inbound message; if `--secret` was set, requests include `X-Webhook-Secret: `. +#### Agent messenger — `connect` / `me` / `ask` / `replies` / `webhook set|show|remove` + +An agent asks a person a question through Dailybot and reads the answer. Organizations on the new Dailybot only (`403 feature_disabled` otherwise → exit 4). + +| Command | What it does | +|---|---| +| `dailybot agent connect "" [--description ...] [-p ] [--json]` | **Needs `dailybot login`.** Connects an agent you own and stores its credential (`dbagt_…`) in `messenger.json` (`0o600`) under the profile slug. Never prints the token, only its prefix. Same name again → same agent, fresh credential. | +| `dailybot agent me [-p] [--json]` | The agent behind the stored credential (checks it still works). | +| `dailybot agent ask --to "" [-o