diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json index aeeba8785e..80d4231739 100644 --- a/.github/ci-budgets.json +++ b/.github/ci-budgets.json @@ -22,6 +22,7 @@ "python harness (agent-llamaindex)": 5, "python harness (agent-agno)": 5, "python harness (agent-strands)": 5, + "python harness (agent-strands-harness)": 5, "python harness (agent-pydantic-ai)": 5, "python harness (agent-adk)": 5, "python harness (agent-antigravity)": 5, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0a4aa91a04..ad9c7137ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1105,6 +1105,7 @@ jobs: - agent-llamaindex - agent-agno - agent-strands + - agent-strands-harness - agent-pydantic-ai - agent-adk - agent-antigravity diff --git a/agent-strands-harness/Dockerfile b/agent-strands-harness/Dockerfile new file mode 100644 index 0000000000..c2e63cf642 --- /dev/null +++ b/agent-strands-harness/Dockerfile @@ -0,0 +1,19 @@ +# The AWS Strands harness, as a Bot. The Strands Bot's image with strands-harness added and a +# different agent mounted; what the two share is copied from shared/. +FROM python:3.12-slim + +WORKDIR /app + +# Dependencies before source, so editing the Bot does not re-resolve the framework. +COPY agent-strands-harness/requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY agent-strands-harness/src ./src +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py \ + shared/gemini_signatures.py shared/empty_turns.py \ + shared/strands_bot.py shared/strands_system_prompt.py /shared/ + +ENV PORT=4217 +EXPOSE 4217 +# 0.0.0.0, not `::`. See agent-strands/Dockerfile. +CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "4217"] diff --git a/agent-strands-harness/requirements-test.txt b/agent-strands-harness/requirements-test.txt new file mode 100644 index 0000000000..a91d60c68a --- /dev/null +++ b/agent-strands-harness/requirements-test.txt @@ -0,0 +1,2 @@ +httpx==0.28.1 +pytest==9.0.2 diff --git a/agent-strands-harness/requirements.txt b/agent-strands-harness/requirements.txt new file mode 100644 index 0000000000..80db9bb625 --- /dev/null +++ b/agent-strands-harness/requirements.txt @@ -0,0 +1,11 @@ +# StrandsHarnessAgent is in the release after ag-ui-strands 1.0.4. Until that is published this +# line resolves to a release without it and the Bot fails at import; set the floor to the release +# that carries it when it lands. +ag-ui-strands +strands-agents +strands-harness +# See agent-strands/requirements.txt: 1.106.0 fails every model call in this harness. +litellm<1.106.0 +fastapi +python-multipart +uvicorn[standard] diff --git a/agent-strands-harness/src/main.py b/agent-strands-harness/src/main.py new file mode 100644 index 0000000000..b0550cbcc6 --- /dev/null +++ b/agent-strands-harness/src/main.py @@ -0,0 +1,92 @@ +"""The AWS Strands harness as a Bot, through `ag_ui_strands`, which AG-UI maintains. + +`agent-strands` is a bare `strands.Agent`: a model and whatever OpenBot grants it. The harness is +the same class with Amazon's agent assembled on it (context management, its own tools, delegation +to subagents, approvals), built by `strands_harness.create_harness`. Everything a Bot on Strands +shares is in `shared/strands_bot.py`; what is here is only what makes this one the harness. + +ONE HARNESS PER CONVERSATION. `StrandsHarnessAgent` calls `create_harness` for each thread, where +`StrandsAgent` would copy one agent. A harness does not survive being copied: its context manager +and background tasks stay with the agent they were built on. + +WHAT IS OPENBOT'S STAYS OPENBOT'S. The harness would keep memory, skills and sessions of its own, +in files beside it. A Bot's memory and skills arrive with every run and its conversations are +stored by Intelligence, so those three are off. So is the harness's note about the machine it runs +on, which would describe this container, not the Bot's computer. + +ITS OWN TOOLS ARE OFF. The harness can run commands, edit files and reach the web where it runs. +Here that is this container, past the server's gateway: no grant, no policy and no audit row. A +Bot's computer is the one OpenBot gives it, through tools the server checks. There is no switch +for them: letting a Bot act outside the gateway is a boundary for OpenBot to decide, not a +deployment's environment. With none of them on there is nothing for the harness's own approval +gate to ask about, so that is off as well. +""" + +import os +import sys +from pathlib import Path + +# The files every language in the box reads, and what this Bot shares with the Strands Bot: one +# level above this Bot in the repository, and one level above /app/src in the image the Dockerfile +# builds. +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from strands_bot import WithoutForwardedProps, WordsAsSaid, create_app, model_id, serve +from strands_system_prompt import RunSystemPrompt + +from ag_ui_strands import StrandsAgentConfig, StrandsHarnessAgent +from strands_harness import HARNESS_CONTRACT + +# The model row this Bot runs on is the Strands Bot's: the same framework, the same clients, the +# same models verified against them. +BOT = "agent-strands" + + +def _model_id() -> str: + return model_id(BOT) + + +def harness_options() -> dict: + """What `create_harness` is given for every conversation. + + `STRANDS_HARNESS_MODEL` names a model the harness reaches itself, as `provider/name` or a bare + Amazon Bedrock model id, with the credentials of this process. That is the AWS route: Claude + on Bedrock under the task's own role. Without it the model is OpenBot's, through the server's + gateway on each run's own key, exactly as the Strands Bot's is. + + None of the harness's own tools (`shell`, `read`, `write`, `edit`, `web_fetch`, `web_search`, + `programmatic_tool_caller`, `subagent`): see the module. What OpenBot grants reaches the agent + as tools the client runs, which are the server's to check, with its own rules, card and audit + row. + """ + return { + "model": (os.environ.get("STRANDS_HARNESS_MODEL") or "").strip() + or WordsAsSaid(model_id=_model_id()), + "builtin_tools": [], + "builtin_plugins": [], + "memory": False, + "skills": False, + } + + +# How long a conversation's harness is kept with nobody talking in it. A harness is a whole agent +# per conversation, and the integration keeps each until told otherwise, so without this the +# process holds every conversation it has ever had. One let go is built again from the messages +# OpenBot sends with the next run. One still waiting on an approval is kept until it is answered. +IDLE_SECONDS = 30 * 60 + + +class Bot(WithoutForwardedProps, StrandsHarnessAgent): + """The integration's harness agent, minus a run's forwarded props.""" + + +app = create_app("strands-harness") +serve( + app, + Bot( + name="openbot", + harness=harness_options(), + config=StrandsAgentConfig(thread_idle_timeout=IDLE_SECONDS), + # The harness's own contract first, then the role OpenBot sends with each run. + hooks=[RunSystemPrompt(HARNESS_CONTRACT)], + ), +) diff --git a/agent-strands-harness/tests/strands_bot_suite.py b/agent-strands-harness/tests/strands_bot_suite.py new file mode 100644 index 0000000000..42e230f57c --- /dev/null +++ b/agent-strands-harness/tests/strands_bot_suite.py @@ -0,0 +1,30 @@ +"""The Strands Bot's own suites, run against this Bot. + +The harness Bot is the Strands Bot with a different agent mounted, so what OpenBot asks of one it +asks of the other: the role in the system prompt, every other row as conversation data, the run's +own key on its model calls, a model name sent verbatim, forwarded props kept out. Those are written +once, in `agent-strands/tests`, against whatever `src.main` resolves to. Loading one of them from +here and then putting this Bot first on the path makes that this Bot's. +""" + +import importlib.util +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BOT = Path(__file__).resolve().parents[1] + + +def load(name: str) -> dict: + """The tests of `agent-strands/tests/.py`, to be run from the module that calls this.""" + spec = importlib.util.spec_from_file_location( + f"strands_bot_{name}", ROOT / "agent-strands" / "tests" / f"{name}.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + # The suite put its own Bot first on the path as it loaded. `src.main` is imported when a test + # runs, so whichever Bot is first then is the one tested. + sys.path.insert(0, str(BOT)) + sys.modules.pop("src.main", None) + sys.modules.pop("src", None) + return {key: value for key, value in vars(module).items() if not key.startswith("__")} diff --git a/agent-strands-harness/tests/test_conversation_contract.py b/agent-strands-harness/tests/test_conversation_contract.py new file mode 100644 index 0000000000..5aefd0c106 --- /dev/null +++ b/agent-strands-harness/tests/test_conversation_contract.py @@ -0,0 +1,9 @@ +"""`agent-strands/tests/test_conversation_contract.py`, against the harness Bot. See `strands_bot_suite.py`.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from strands_bot_suite import load + +globals().update(load("test_conversation_contract")) diff --git a/agent-strands-harness/tests/test_forwarded_props_stay_out.py b/agent-strands-harness/tests/test_forwarded_props_stay_out.py new file mode 100644 index 0000000000..3c03cc7075 --- /dev/null +++ b/agent-strands-harness/tests/test_forwarded_props_stay_out.py @@ -0,0 +1,9 @@ +"""`agent-strands/tests/test_forwarded_props_stay_out.py`, against the harness Bot. See `strands_bot_suite.py`.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from strands_bot_suite import load + +globals().update(load("test_forwarded_props_stay_out")) diff --git a/agent-strands-harness/tests/test_harness.py b/agent-strands-harness/tests/test_harness.py new file mode 100644 index 0000000000..7bd81a2478 --- /dev/null +++ b/agent-strands-harness/tests/test_harness.py @@ -0,0 +1,142 @@ +"""What makes this Bot the harness, and what it leaves to OpenBot.""" + +import importlib +import json +import sys +from pathlib import Path + +from fastapi.testclient import TestClient + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import conversation, fake_provider, openai_environment + +TOKEN = "contract-token" +HARNESS_VARIABLES = ("STRANDS_HARNESS_MODEL",) + + +def _main(monkeypatch, base, **harness): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + monkeypatch.setenv("OTEL_SDK_DISABLED", "true") + for key in HARNESS_VARIABLES: + monkeypatch.delenv(key, raising=False) + for key, value in {**openai_environment(base), **harness}.items(): + monkeypatch.setenv(key, value) + sys.modules.pop("src.main", None) + sys.modules.pop("src", None) + return importlib.import_module("src.main") + + +def _run(main, thread="harness-thread"): + response = TestClient(main.app).post( + "/", json=conversation(thread), headers={"x-openbot-agent-token": TOKEN} + ) + assert response.status_code == 200, response.text + events = [json.loads(line[5:]) for line in response.text.splitlines() if line.startswith("data:")] + assert not [event for event in events if event["type"] == "RUN_ERROR"], events + return events + + +def _offered(body: dict) -> list[str]: + return sorted(tool["function"]["name"] for tool in body.get("tools") or []) + + +def test_health_names_the_harness(monkeypatch): + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base) + assert TestClient(main.app).get("/health").json() == {"ok": True, "harness": "strands-harness"} + + +def test_each_conversation_gets_a_harness_of_its_own(monkeypatch): + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base) + _run(main, "one") + _run(main, "two") + # The agent is closed over by its route, so it is found by its class. + agents = [agent for bot in _bots(main) for agent in bot._agents_by_thread.values()] + assert len(agents) == 2 + one, two = agents + assert one is not two + # What copying one agent would have lost, and what makes it the harness. + assert one.context_manager is not None + assert one.context_manager is not two.context_manager + + +def _bots(main): + import gc + + return [obj for obj in gc.get_objects() if type(obj) is main.Bot] + + +def test_the_harness_contract_comes_before_the_role_openbot_sends(monkeypatch): + from strands_harness import HARNESS_CONTRACT + + with fake_provider() as (base, bodies): + _run(_main(monkeypatch, base)) + system = "\n".join( + part.get("text", "") if isinstance(part, dict) else str(part) + for message in bodies[-1]["messages"] + if message["role"] == "system" + for part in (message["content"] if isinstance(message["content"], list) else [message["content"]]) + ) + from harness_contract import STANDING_ROLE + + assert HARNESS_CONTRACT.splitlines()[0] in system + assert system.index(HARNESS_CONTRACT.splitlines()[0]) < system.index(STANDING_ROLE) + + +def test_none_of_the_harness_tools_that_act_here_is_offered_and_no_variable_turns_them_on(monkeypatch): + """They would run in this container, past the server's gateway.""" + monkeypatch.setenv("STRANDS_HARNESS_TOOLS", "shell, read") + monkeypatch.setenv("STRANDS_HARNESS_INTERVENTIONS", "ask") + with fake_provider() as (base, bodies): + main = _main(monkeypatch, base) + _run(main) + assert "interventions" not in main.harness_options() + acting = {"shell", "read", "write", "edit", "web_fetch", "web_search", "programmatic_tool_caller", "subagent"} + assert not acting & set(_offered(bodies[-1])) + + +def test_what_openbot_keeps_is_not_kept_twice(monkeypatch, tmp_path): + """No memory, skills or session files beside the process.""" + monkeypatch.chdir(tmp_path) + with fake_provider() as (base, bodies): + _run(_main(monkeypatch, base)) + assert not (tmp_path / ".agent").exists() + assert "search_memory" not in _offered(bodies[-1]) + # Nor the harness's note about the machine it runs on: that is this container. + assert "Working directory:" not in json.dumps(bodies[-1]) + + +def test_a_conversation_nobody_talks_in_is_let_go_and_comes_back_from_its_messages(monkeypatch): + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base) + _run(main, "quiet") + (bot,) = [bot for bot in _bots(main) if "quiet" in bot._agents_by_thread] + assert bot.config.thread_idle_timeout == main.IDLE_SECONDS + # As if the half hour had passed. + bot._thread_last_run_ended["quiet"] -= main.IDLE_SECONDS + _run(main, "busy") + assert set(bot._agents_by_thread) == {"busy"} + _run(main, "quiet") + assert set(bot._agents_by_thread) == {"busy", "quiet"} + + +def test_stopping_the_process_shuts_every_conversations_harness_down(monkeypatch): + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base) + with TestClient(main.app) as client: + response = client.post("/", json=conversation("closing"), headers={"x-openbot-agent-token": TOKEN}) + assert response.status_code == 200, response.text + (bot,) = [bot for bot in _bots(main) if "closing" in bot._agents_by_thread] + assert bot._agents_by_thread == {} + + +def test_a_named_model_is_the_harnesss_to_reach(monkeypatch): + """The AWS route: Bedrock with this process's credentials, not the server's gateway.""" + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base) + assert not isinstance(main.harness_options()["model"], str) + monkeypatch.setenv("STRANDS_HARNESS_MODEL", "bedrock/global.anthropic.claude-opus-5-5") + assert main.harness_options()["model"] == "bedrock/global.anthropic.claude-opus-5-5" diff --git a/agent-strands-harness/tests/test_learning_delivery.py b/agent-strands-harness/tests/test_learning_delivery.py new file mode 100644 index 0000000000..e72168631c --- /dev/null +++ b/agent-strands-harness/tests/test_learning_delivery.py @@ -0,0 +1,14 @@ +"""AWS Strands harness receives OpenBot's learned context and read tools.""" + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tests")) +sys.path.insert(0, str(ROOT / "agent-strands-harness")) + +from learning_harness_contract import assert_learning_delivery + + +def test_learned_catalog_and_both_read_tools_reach_the_model(monkeypatch): + assert_learning_delivery(monkeypatch, "agent-strands-harness", "/") diff --git a/agent-strands-harness/tests/test_main.py b/agent-strands-harness/tests/test_main.py new file mode 100644 index 0000000000..279285003f --- /dev/null +++ b/agent-strands-harness/tests/test_main.py @@ -0,0 +1,9 @@ +"""`agent-strands/tests/test_main.py`, against the harness Bot. See `strands_bot_suite.py`.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from strands_bot_suite import load + +globals().update(load("test_main")) diff --git a/agent-strands/Dockerfile b/agent-strands/Dockerfile index 43f61a1dc0..468ff8e066 100644 --- a/agent-strands/Dockerfile +++ b/agent-strands/Dockerfile @@ -9,7 +9,9 @@ COPY agent-strands/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-strands/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py shared/progress_reminder.py shared/empty_turns.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py \ + shared/gemini_signatures.py shared/progress_reminder.py shared/empty_turns.py \ + shared/strands_bot.py shared/strands_system_prompt.py /shared/ ENV PORT=4207 EXPOSE 4207 diff --git a/agent-strands/src/main.py b/agent-strands/src/main.py index f3546b07f4..fef497eda2 100644 --- a/agent-strands/src/main.py +++ b/agent-strands/src/main.py @@ -1,117 +1,40 @@ """AWS Strands as a Bot, through `ag_ui_strands`, which AG-UI maintains.""" -import hmac -import os import sys -from contextlib import aclosing from pathlib import Path -# The spec file every language in the box reads: one level above this Bot in the repository, and -# one level above /app/src in the image the Dockerfile builds. +# The files every language in the box reads, and what this Bot shares with the Strands harness +# Bot: one level above this Bot in the repository, and one level above /app/src in the image the +# Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from empty_turns import without_empty_turns -from model_providers import bot_settings, litellm_model_id -from run_model_key import RunModelKey -import gemini_signatures +from strands_bot import WithoutForwardedProps, WordsAsSaid, create_app, model_id, serve +from strands_system_prompt import RunSystemPrompt -# A tool call handed back to Gemini 3 goes with Google's placeholder for its thought signature, -# which the integration does not carry between runs. See gemini_signatures.py. -gemini_signatures.install() - -from ag_ui_strands import StrandsAgent, add_strands_fastapi_endpoint -from fastapi import FastAPI, Request -from fastapi.responses import JSONResponse +from ag_ui_strands import StrandsAgent from strands import Agent -from strands.models.litellm import LiteLLMModel from src.reminders import ProgressReminder -from src.system_prompt import RunSystemPrompt, invocation_state - - -def _model_id() -> str: - """`provider/model`, which is how litellm addresses one. - - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already - contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an - OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is - `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. - """ - settings = bot_settings("agent-strands") - provider = settings.provider - model = settings.model - return litellm_model_id(provider, model) - - -class WordsAsSaid(LiteLLMModel): - """LiteLLM, sending each step with only the words the model said. - - A step with no words goes as no words, never as LiteLLM's "[System: Empty message content - sanitised to satisfy protocol]", which Claude would read as its own line and say again - (`shared/empty_turns.py`). Only the request each call sends changes: the agent's messages are - left as they were. - """ - def format_request(self, messages, *args, **kwargs): - request = super().format_request(messages, *args, **kwargs) - return {**request, "messages": without_empty_turns(request["messages"])} +BOT = "agent-strands" -app = FastAPI() -# Each run's model calls carry its own gateway token, in its organization. See run_model_key.py. -app.add_middleware(RunModelKey) - -TOKEN_HEADER = "x-openbot-agent-token" - - -@app.middleware("http") -async def refuse_without_the_server_token(request: Request, call_next): - """Everything but `/health`, which Compose polls before any token exists.""" - if request.url.path != "/health": - expected = (os.environ.get("MANAGED_AGENT_TOKEN") or "").strip() - offered = (request.headers.get(TOKEN_HEADER) or "").strip() - if not expected or not hmac.compare_digest(offered.encode("utf-8"), expected.encode("utf-8")): - return JSONResponse({"error": "unauthorised"}, status_code=401) - return await call_next(request) - - -@app.get("/health") -async def health(): - return {"ok": True, "harness": "strands"} - - -class WithoutForwardedProps(StrandsAgent): - """None of a run's forwarded props goes on to the integration. +def _model_id() -> str: + return model_id(BOT) - The one this Bot uses, its model route, was read on the way in (`RunModelKey`); the rest are the - server's, which nothing here reads, and whatever the browser sent. The integration takes - `injectA2UITool` as an order: it adds a tool that calls the model again and, given a tool's - name, takes that granted tool away from the run. - """ - async def run(self, input_data, *, invocation_state=None): - async with aclosing( - super().run( - input_data.model_copy(update={"forwarded_props": {}}), - invocation_state=invocation_state, - ) - ) as events: - async for event in events: - yield event +class Bot(WithoutForwardedProps, StrandsAgent): + """The integration's agent, minus a run's forwarded props.""" +app = create_app("strands") # The role arrives as system messages on every run and becomes that run's system prompt; see -# `system_prompt.py` for why the integration cannot be left to do it. A word now and then on a -# long job: see `reminders.py`. -add_strands_fastapi_endpoint( +# `strands_system_prompt.py` for why the integration cannot be left to do it. A word now and then +# on a long job: see `reminders.py`. +serve( app, - WithoutForwardedProps( + Bot( name="openbot", agent=Agent(model=WordsAsSaid(model_id=_model_id())), hooks=[RunSystemPrompt(), ProgressReminder()], ), - "/", - invocation_state_provider=invocation_state, ) diff --git a/agent-strands/src/reminders.py b/agent-strands/src/reminders.py index e9e9c4f5a3..2d7ab68a33 100644 --- a/agent-strands/src/reminders.py +++ b/agent-strands/src/reminders.py @@ -4,7 +4,7 @@ person, the next model call is sent a short reminder to say a line, right after the fifth step's results, once per silent stretch. -It goes in through the same seam as the conversation rows in `system_prompt.py`, and as the library +It goes in through the same seam as the conversation rows in `strands_system_prompt.py`, and as the library adds AG-UI context: a hook on `BeforeModelCallEvent` adds it to the turns the model is about to be sent, and one on `AfterModelCallEvent` takes it out again. So it is in each model call and nowhere else: not in the history the library keeps, the snapshots it sends the browser or what Intelligence @@ -33,7 +33,7 @@ SAID, reminder_places, ) -from src.system_prompt import _merge, _undo +from strands_system_prompt import _merge, _undo # Where the reminders a model call added are kept until it ends, on the per-thread agent. _APPLIED = "_openbot_progress_reminders_applied" diff --git a/app/src/components/approvals/bot-approval-notice.tsx b/app/src/components/approvals/bot-approval-notice.tsx new file mode 100644 index 0000000000..3a9dd675c2 --- /dev/null +++ b/app/src/components/approvals/bot-approval-notice.tsx @@ -0,0 +1,166 @@ +import type { Message } from "@ag-ui/core"; +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { + answersFor, + asksForApproval, + botRaisedInterrupts, + expired, + type HeldInterrupt, + type InterruptAnswer, + interruptedCall, +} from "@/lib/copilot/bot-raised-interrupts"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; + +type InterruptedAgent = { + pendingInterrupts: HeldInterrupt[]; + messages: readonly Message[]; + isRunning: boolean; + subscribe(subscriber: { + onRunInitialized?: () => void; + onRunFinalized?: () => void; + onRunFailed?: () => void; + }): { unsubscribe(): void }; +}; + +/** + * What a Bot stopped its own run to ask, with the person's answer to it. + * + * Only for a wait the Bot raised itself; OpenBot's own approvals have their cards + * (`bot-raised-interrupts.ts` says which is which). The answer is sent as the next run's `resume`, + * which is how AG-UI carries one. + */ +export function BotApprovalNotice({ + agent, + botName, + ready, + run, +}: { + agent: InterruptedAgent; + botName: string; + ready: boolean; + run: (resume: InterruptAnswer[]) => Promise; +}) { + const [, redraw] = useState(0); + const [busy, setBusy] = useState(false); + const [problem, setProblem] = useState(null); + // The agent's interrupts change when a run ends or starts, which is not a render of its own. + useEffect(() => { + const again = () => redraw((count) => count + 1); + const watching = agent.subscribe({ + onRunInitialized: again, + onRunFinalized: again, + onRunFailed: again, + }); + return () => watching.unsubscribe(); + }, [agent]); + + // Set when a click found the Bot no longer takes the decision, so the card says so from then on. + const [lapsed, setLapsed] = useState(false); + + const waiting = ready ? botRaisedInterrupts(agent.pendingInterrupts) : []; + if (waiting.length === 0 || agent.isRunning) return null; + const approvals = waiting.filter(asksForApproval); + /* + * A decision the Bot still takes. One whose time is over can only be let go: the AG-UI client + * refuses an answer to it before anything is sent, so Allow did nothing and the conversation was + * stuck. Read when the card draws and again at the click, which may come much later. + */ + const open = lapsed ? [] : approvals.filter((asked) => !expired(asked)); + + const answer = async (approved: boolean) => { + if (busy) return; + const now = new Date(); + // Allowing what the Bot no longer waits on would be sent as letting it go: said first instead. + if (approved && approvals.some((asked) => expired(asked, now))) { + setLapsed(true); + return; + } + setBusy(true); + setProblem(null); + try { + await run(answersFor(agent.pendingInterrupts, approved, now)); + } catch (error) { + setProblem(failureOf(error, "Couldn't send your answer. Try again.")); + } finally { + setBusy(false); + } + }; + + return ( +
+ {open.length > 0 ? ( +

{botName} asks before it goes on

+ ) : approvals.length > 0 ? ( +

+ {botName} waited too long for this answer and no longer takes it +

+ ) : ( +

+ {botName} is waiting for an answer this app can't give +

+ )} + {waiting.map((interrupt) => { + const call = interruptedCall(interrupt, agent.messages); + // What the Bot asks, in its own words. Not an error's: nothing here failed. + const asked = interrupt.message; + return ( +
+ {/* + * The call itself when the conversation has it: its name and what it was given, as the + * person would check them. A harness words its question for a terminal (`Approve + * "shell"? Input: {...}`), so its words are only for a wait that names no call. + */} + {call ? ( + <> +

+ Use {call.name} +

+

+ {call.args} +

+ + ) : asked ? ( +

{asked}

+ ) : null} +
+ ); + })} + {problem ? ( +

+ {failureSaid(problem)} +

+ ) : null} +
+ {open.length > 0 ? ( + <> + + + + ) : ( + + )} +
+
+ ); +} diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index 7430124e69..e00a97d8eb 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -15,6 +15,7 @@ import { useSyncExternalStore, } from "react"; import { BotOrb } from "@/components/agents/bot-orb"; +import { BotApprovalNotice } from "@/components/approvals/bot-approval-notice"; import { ConversationAllowances } from "@/components/approvals/conversation-allowances"; import { ANSWER_PROMPT, @@ -103,6 +104,7 @@ import { whileObserved, } from "@/lib/copilot/approval-context"; import { offerItsOwnTools } from "@/lib/copilot/bot-offer"; +import type { InterruptAnswer } from "@/lib/copilot/bot-raised-interrupts"; import { isBrokenStream, STREAM_BROKE } from "@/lib/copilot/broken-stream"; import { endsOnStep, @@ -282,6 +284,8 @@ const STOP_FAILED = "Couldn't stop the Bot. Try again."; /** What a turn that never left the browser says, with the person's words back in the box. */ const NOT_SENT = "Your message wasn't sent. Try again."; +/** An answer to a Bot's own wait that never left this browser (`answerBotWait`). */ +const ANSWER_NOT_SENT = "Your answer wasn't sent. Try again."; type ChannelActivitySignature = { agentId: string; @@ -2783,14 +2787,7 @@ export function ChannelChat({ throw new StillWorkingError(); } - const turn = {}; - turnTokens.current.add(turn); - turnsRef.current += 1; - setTurnsInFlight(turnsRef.current); - if (turnsRef.current === 1) { - void setChannelBusy({ channelId: channel.id, busy: true }); - } - try { + return duringTurn(async () => { const reply = await deliver(trimmed, attachments, sent); /* * The person left while this turn was running (holding control of the Bot's browser, say) and the turn went on @@ -2807,6 +2804,23 @@ export function ChannelChat({ reportRef.current(reply || (drawn?.text ?? ""), runtimeAgentId); } return reply; + }); + }; + + /** + * Count `work` as a turn of this conversation for as long as it goes: what `turnsInFlight` says + * above, the roster's working indicator, and the chat open next if this one closes meanwhile. + */ + const duringTurn = async (work: () => Promise): Promise => { + const turn = {}; + turnTokens.current.add(turn); + turnsRef.current += 1; + setTurnsInFlight(turnsRef.current); + if (turnsRef.current === 1) { + void setChannelBusy({ channelId: channel.id, busy: true }); + } + try { + return await work(); } finally { turnsRef.current -= 1; setTurnsInFlight(turnsRef.current); @@ -2829,6 +2843,58 @@ export function ChannelChat({ } }; + /** + * Send the person's answer to a wait the Bot raised itself, as the `resume` of a run. + * + * A TURN LIKE ANY OTHER, WITHOUT A MESSAGE. It is counted and watched as `say`'s are, so what the + * Bot goes on to say reaches the roster and a run that fails is said under the transcript. Sent + * bare, neither happened: `copilotkit.runAgent` resolves on a failed run (`turnFailure`), so a + * gateway's 503 looked like an answer that went, with the card back and nothing said. + * + * THROWS ONLY WHEN THE RUN NEVER LEFT THIS BROWSER, so the card says so beside its buttons: a run + * the agent refused on its own checks reaches no subscriber, and nothing else would say it. One + * that failed on the way is already said under the transcript, by the same `fail` as any turn. + */ + const answerBotWait = (resume: InterruptAnswer[]) => + duringTurn(async () => { + const target = agentRef.current; + setRunError(null); + turnFailure.current = null; + turnRefused.current = false; + stoppedHere.current = false; + reportedReply.current = null; + assistantMessagesBeforeRun.current = new Set( + target.messages + .filter((message) => message.role === "assistant") + .map((message) => message.id), + ); + /* + * A wait OpenBot holds beside the Bot's is the server's to carry on, decided on its own card. + * The agent refuses a run that leaves any wait it holds unaddressed, so with both replayed + * Allow sent nothing at all. Let go of here as before any message; see the module. + */ + releaseServerOwnedInterrupts(target); + let started = false; + const watching = target.subscribe({ + onRunInitialized: () => { + started = true; + }, + }); + awaitingReply.current = true; + setRunsInFlight((count) => count + 1); + try { + await whileObserved(target, () => + copilotkit.runAgent({ agent: target, resume }), + ); + } finally { + watching.unsubscribe(); + awaitingReply.current = false; + setRunsInFlight((count) => count - 1); + } + if (!started && turnFailure.current === null) + throw new Error(ANSWER_NOT_SENT); + }); + useEffect(() => { /* * `laterRun` is a RUN_ERROR from a run of a turn still going here after its first run has @@ -3359,6 +3425,13 @@ export function ChannelChat({ {channel.active ? ( ) : null} + {/* What the Bot stopped its own run to ask; the answer is the next run's `resume`. */} + ; +}; + +/** One answer to an interrupt, as a run's `resume` carries it. */ +export type InterruptAnswer = { + interruptId: string; + status: "resolved" | "cancelled"; + payload?: unknown; +}; + +/** + * The interrupts a Bot raised itself, which only this app can answer. + * + * MOST WAITS ARE THE SERVER'S. An approval, a question or a sign-in OpenBot asks for is answered on + * its own card and carried on by the server (`server-owned-interrupts.ts`). A Bot connected by its + * address can also stop a run on its own: a harness that asks before it runs one of its own tools, a + * graph's `interrupt()`. The server passes that through untouched, and passes its answer back + * (`endpointResume` in the server's copilot.ts), so the run waits on whoever holds the conversation. + * Left unanswered, the conversation is stuck: the agent refuses every later run ("pending + * interrupt(s) not addressed by resume"). + */ +export function botRaisedInterrupts( + pending: readonly T[], +): T[] { + return pending.filter((interrupt) => !serverOwnedInterrupt(interrupt)); +} + +/** + * Whether an interrupt asks yes or no: its answer is an object whose one required field is the + * boolean `approved`. That is what an approval asked by a Bot's own harness looks like on AG-UI; + * anything else has an answer this app cannot draw a form for, and can only be let go. + */ +export function asksForApproval(interrupt: HeldInterrupt): boolean { + const schema = interrupt.responseSchema; + if (!schema || typeof schema !== "object") return false; + const { properties, required } = schema as { + properties?: Record; + required?: unknown; + }; + return ( + properties?.approved?.type === "boolean" && + Array.isArray(required) && + required.length === 1 && + required[0] === "approved" + ); +} + +/** The call an interrupt is about, from the conversation: its name and its arguments as sent. */ +export function interruptedCall( + interrupt: HeldInterrupt, + messages: readonly Message[], +): { name: string; args: string } | undefined { + if (!interrupt.toolCallId) return undefined; + for (const message of messages) { + if (message.role !== "assistant") continue; + const call = message.toolCalls?.find( + (candidate) => candidate.id === interrupt.toolCallId, + ); + if (call) + return { name: call.function.name, args: call.function.arguments }; + } + return undefined; +} + +/** + * Whether an interrupt's time to be answered is over. The AG-UI client refuses a decision on one + * before anything is sent ("expired at ... Cancel it to continue the thread"), so it can only be + * let go. + */ +export function expired(interrupt: HeldInterrupt, now = new Date()): boolean { + if (interrupt.expiresAt === undefined) return false; + return new Date(interrupt.expiresAt) <= now; +} + +/** + * The `resume` that answers the interrupts the Bot raised, given the person's decision on them. A + * run must address all of them at once, so one decision covers each approval the Bot asked for in + * that step. An interrupt that is not a yes or no, or whose time is over, is cancelled, which lets + * the conversation go on. + * + * NOT THE SERVER'S. A wait OpenBot holds beside these is decided on its own card and carried on by + * the server, and is let go of on the agent before this is sent (`releaseServerOwnedInterrupts`), as + * before any message: the agent refuses a run that leaves one it still holds unaddressed. + */ +export function answersFor( + pending: readonly HeldInterrupt[], + approved: boolean, + now = new Date(), +): InterruptAnswer[] { + return botRaisedInterrupts(pending).map((interrupt) => + asksForApproval(interrupt) && !expired(interrupt, now) + ? { interruptId: interrupt.id, status: "resolved", payload: { approved } } + : { interruptId: interrupt.id, status: "cancelled" }, + ); +} diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 762429302d..d8ec871821 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -158,6 +158,31 @@ function showsOpenBotOnThisComputer(): Promise { * told "not found" and drew the router's error in its place. Told "not found" in the organization * it knows (signed out since, or no longer in it), it is asked the way it is before signing in. */ +/** + * `deployment` at `default`, asked as nobody: without the page's cookies. + * + * ONE OPENBOT REFUSES NOBODY: a single-user one in a container, which answers only a browser that + * came in through its entry address, and knows that browser by a cookie (the server's + * request-trust.ts). Asked without cookies it said "permission denied", on every page, to the very + * browser it had let in: no deployment facts, so no release check and no attachment limits, and a + * failed request in the console each time. That refusal is about the browser, not about a person, + * so the page asks once more with its cookies. Any other OpenBot answers the first ask. + */ +async function asNobody(options: { + signal?: AbortSignal; + fallback: string; +}): Promise { + try { + return await getDeployment(DEPLOYMENT_ORGANIZATION, { + ...options, + credentials: "omit", + }); + } catch (error) { + if (!(error instanceof ClientError) || error.status !== 403) throw error; + return getDeployment(DEPLOYMENT_ORGANIZATION, options); + } +} + export async function readDeployment(options: { signal?: AbortSignal; fallback: string; @@ -169,17 +194,10 @@ export async function readDeployment(options: { } catch (error) { if (!(error instanceof ClientError) || error.status !== 404) throw error; if (await showsOpenBotOnThisComputer()) throw error; - return getDeployment(DEPLOYMENT_ORGANIZATION, { - ...options, - credentials: "omit", - }); + return asNobody(options); } } - if (!(await showsOpenBotOnThisComputer())) - return getDeployment(DEPLOYMENT_ORGANIZATION, { - ...options, - credentials: "omit", - }); + if (!(await showsOpenBotOnThisComputer())) return asNobody(options); try { return await getDeployment(DEPLOYMENT_ORGANIZATION, options); } catch (error) { @@ -188,11 +206,7 @@ export async function readDeployment(options: { .organizations[0]; // In no organization (removed from the last one): what this OpenBot offers anybody, asked as nobody, so the // sign-in screen and the page for somebody in no organization can still offer a way back in. - if (!own) - return getDeployment(DEPLOYMENT_ORGANIZATION, { - ...options, - credentials: "omit", - }); + if (!own) return asNobody(options); return getDeployment(own.id, options); } } diff --git a/app/tests/bot-approval-resume.test.tsx b/app/tests/bot-approval-resume.test.tsx new file mode 100644 index 0000000000..46bfb3ce4d --- /dev/null +++ b/app/tests/bot-approval-resume.test.tsx @@ -0,0 +1,339 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import type { Message, RunAgentInput } from "@ag-ui/core"; +import { RunAgentInputSchema } from "@ag-ui/core/schemas"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { OPENBOT_WAITING_METADATA } from "@openbot/shared/waiting"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { z } from "zod"; +import { ChannelChat } from "@/components/channels/channel-chat"; +import { type AgentChannel, channelKeys } from "@/lib/channels/queries"; +import { queryClient } from "@/query-client"; +import { MY_CAPABILITIES_PATH } from "./admin-settings-api"; +import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; +import { answerBotsList, botPath } from "./bots-api"; +import { settleReactWork } from "./settle-react-work"; +import { botComponentsPath, botComponentsResponse } from "./components-api"; + +/** + * The card for a wait a Bot raised itself (a harness asking before it runs one of its own tools), + * answered by the person in the browser. + * + * Found in review, each with the conversation left stuck: the Bot's wait replayed beside one of + * OpenBot's own, where Allow sent nothing; a wait whose time was over, which neither button could + * answer; and an answer whose run failed, which looked like one that went. + * + * The real provider, ChannelChat and the real AG-UI agent; only the HTTP boundary is synthetic. + */ + +const NativeResponse = globalThis.Response; +const channel: AgentChannel = { + id: "waiting-channel", + name: "Reply to Sam about the spec", + agentIds: ["waiting-bot"], + threadId: "waiting-thread", + active: true, + lastMessageAt: "2026-10-31T05:51:00.000Z", +}; +const ask = { + id: "ask", + role: "user", + content: "Reply to Sam about the spec", +} satisfies Message; +const call = { + id: "asked-to-send", + role: "assistant", + content: "", + toolCalls: [ + { + id: "call-shell", + type: "function", + function: { name: "shell", arguments: '{"command":"ls"}' }, + }, + { + id: "call-send", + type: "function", + function: { + name: "mcp__notion__notion-create-comment", + arguments: '{"text":"Friday works."}', + }, + }, + ], +} satisfies Message; + +/** What the replayed run ended on. */ +let interrupts: Record[]; +/** What the runtime answers a run with, when it is not the run's events. */ +let runStatus: number | null; +let runRequests: RunAgentInput[] = []; +let runEvents: (input: RunAgentInput) => unknown[]; +const ActivitySchema = z.object({ + botId: z.string().nullable(), + text: z.string(), +}); +let activity: z.infer[] = []; +/** Each time the conversation said a turn started or ended, in order. */ +let busy: boolean[] = []; +let originalFetch: typeof fetch; + +function sse(events: unknown[]) { + return new NativeResponse( + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { headers: { "content-type": "text/event-stream" } }, + ); +} + +beforeAll(() => { + GlobalRegistrator.register(); + originalFetch = globalThis.fetch; + globalThis.fetch = Object.assign( + async (input: Parameters[0], init?: RequestInit) => { + const url = new URL( + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url, + "http://localhost", + ); + const bots = answerBotsList(url, init, { visible: [] }); + if (bots) return bots; + if (url.pathname === botGrantsPath("waiting-bot")) + return botGrantsResponse(); + // What the Bot's runs are offered is read from these, as the server answers them. + if (url.pathname === botPath("waiting-bot")) + return NativeResponse.json({ + bot: { id: "waiting-bot", visibility: "public", canManage: true }, + }); + if (url.pathname === botComponentsPath("waiting-bot")) + return botComponentsResponse(); + if (url.pathname === MY_CAPABILITIES_PATH) + return NativeResponse.json({ capabilities: {}, enforced: false }); + if (url.pathname.endsWith("/info")) + return NativeResponse.json({ + version: "fixture", + agents: { + "waiting-bot": { description: "Fixture", capabilities: {} }, + }, + mode: "sse", + telemetryDisabled: true, + }); + // The conversation's last run, replayed: it asked to send and stopped for the person. + if (url.pathname.endsWith("/connect")) + return sse([ + { type: "RUN_STARTED", threadId: channel.threadId, runId: "task" }, + { type: "MESSAGES_SNAPSHOT", messages: [ask, call] }, + { + type: "RUN_FINISHED", + threadId: channel.threadId, + runId: "task", + outcome: { type: "interrupt", interrupts }, + }, + ]); + if (url.pathname.endsWith("/run")) { + const request = + input instanceof Request ? input : new Request(url, init); + const body = RunAgentInputSchema.parse(await request.json()); + runRequests.push(body); + if (runStatus !== null) + return new NativeResponse("unavailable", { status: runStatus }); + return sse(runEvents(body)); + } + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/activity$/.test( + url.pathname, + ) + ) { + const request = + input instanceof Request ? input : new Request(url, init); + activity.push(ActivitySchema.parse(await request.json())); + return new NativeResponse(null, { status: 204 }); + } + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/signal-busy$/.test( + url.pathname, + ) + ) { + const request = + input instanceof Request ? input : new Request(url, init); + busy.push( + z.object({ busy: z.boolean() }).parse(await request.json()).busy, + ); + return new NativeResponse(null, { status: 204 }); + } + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/voice-sessions$/.test( + url.pathname, + ) + ) + return NativeResponse.json({ sessions: [], nextCursor: null }); + if (/\/threads\/[^/]+\/messages$/.test(url.pathname)) + return NativeResponse.json({ messages: [ask, call] }); + throw new Error(`Unexpected fixture request: ${url.pathname}`); + }, + { + preconnect() { + throw new Error("Unexpected fixture preconnect"); + }, + }, + ); +}); +afterEach(() => { + cleanup(); + queryClient.clear(); +}); +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +function mounting() { + runRequests = []; + runStatus = null; + activity = []; + busy = []; + runEvents = (input) => [ + { type: "RUN_STARTED", threadId: input.threadId, runId: input.runId }, + { type: "RUN_FINISHED", threadId: input.threadId, runId: input.runId }, + ]; + queryClient.setQueryData(channelKeys.list(), { + pages: [ + { + channels: [ + { + ...channel, + summary: null, + lastMessage: "Waiting for your approval.", + lastMessageAgentId: "waiting-bot", + createdAt: "2026-10-31T05:50:00.000Z", + pinned: false, + lastReadAt: null, + }, + ], + nextCursor: null, + }, + ], + pageParams: [""], + }); + return render( + + + + + , + ); +} + +/** What a harness sends when it asks before running one of its own tools. */ +const fromTheBot = { + id: "bot-wait", + reason: "tool_call", + toolCallId: "call-shell", + message: 'Approve "shell"?', + responseSchema: { + type: "object", + properties: { approved: { type: "boolean" } }, + required: ["approved"], + }, +}; +/** A wait OpenBot holds itself, decided on its own card and carried on by the server. */ +const fromTheServer = { + id: "call-send", + reason: "human_input", + message: "This action is waiting for your approval.", + metadata: { + [OPENBOT_WAITING_METADATA]: { + kind: "approval", + approvalId: "approval-1", + requestId: "approval-1", + }, + }, +}; + +function replying(text: string) { + runEvents = (input) => [ + { type: "RUN_STARTED", threadId: input.threadId, runId: input.runId }, + { type: "TEXT_MESSAGE_START", messageId: "went-on", role: "assistant" }, + { type: "TEXT_MESSAGE_CONTENT", messageId: "went-on", delta: text }, + { type: "TEXT_MESSAGE_END", messageId: "went-on" }, + { type: "RUN_FINISHED", threadId: input.threadId, runId: input.runId }, + ]; +} + +async function press(view: ReturnType, name: string) { + const user = userEvent.setup({ document: view.container.ownerDocument }); + await user.click(await view.findByRole("button", { name })); +} + +test("Allow goes out though the replayed run also ended on a wait of OpenBot's own", async () => { + interrupts = [fromTheBot, fromTheServer]; + const view = mounting(); + replying("Listed the files."); + + await press(view, "Allow"); + + await waitFor(() => expect(runRequests).toHaveLength(1)); + // Only the Bot's wait is answered from here: OpenBot's decision stays on its server path. + expect(runRequests[0]?.resume).toEqual([ + { + interruptId: "bot-wait", + status: "resolved", + payload: { approved: true }, + }, + ]); +}); + +test("what the Bot says after the answer reaches the roster, as a turn that started and ended once", async () => { + interrupts = [fromTheBot]; + const view = mounting(); + replying("Listed the files."); + + await press(view, "Don't allow"); + + await waitFor(() => + expect(activity.at(-1)).toEqual({ + botId: "waiting-bot", + text: "Listed the files.", + }), + ); + expect(runRequests[0]?.resume).toEqual([ + { + interruptId: "bot-wait", + status: "resolved", + payload: { approved: false }, + }, + ]); + await waitFor(() => expect(busy).toEqual([true, false])); +}); + +test("a wait whose time is over can be let go, so the conversation goes on", async () => { + interrupts = [{ ...fromTheBot, expiresAt: "2020-01-01T00:00:00.000Z" }]; + const view = mounting(); + + await press(view, "Carry on without it"); + + await waitFor(() => expect(runRequests).toHaveLength(1)); + expect(runRequests[0]?.resume).toEqual([ + { interruptId: "bot-wait", status: "cancelled" }, + ]); + // No decision is offered on what the Bot no longer takes one for. + expect(view.queryByRole("button", { name: "Allow" })).toBe(null); +}); + +test("an answer whose run fails says so, and the card is still there to try again", async () => { + interrupts = [fromTheBot]; + const view = mounting(); + runStatus = 503; + + await press(view, "Allow"); + + await waitFor(() => expect(runRequests).toHaveLength(1)); + await waitFor(() => + expect(view.container.querySelector('[role="alert"]')).not.toBe(null), + ); + await view.findByRole("button", { name: "Allow" }); + await waitFor(() => expect(busy).toEqual([true, false])); +}); diff --git a/app/tests/bot-raised-interrupts.test.ts b/app/tests/bot-raised-interrupts.test.ts new file mode 100644 index 0000000000..19d682ae1d --- /dev/null +++ b/app/tests/bot-raised-interrupts.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "bun:test"; +import type { Message } from "@ag-ui/core"; +import { OPENBOT_WAITING_METADATA } from "@openbot/shared/waiting"; +import { + answersFor, + asksForApproval, + botRaisedInterrupts, + expired, + interruptedCall, +} from "@/lib/copilot/bot-raised-interrupts"; + +const yesOrNo = { + type: "object", + properties: { approved: { type: "boolean" } }, + required: ["approved"], +}; +/** What a Strands harness sends when it asks before running one of its own tools. */ +const fromTheBot = { + id: "int-1", + reason: "tool_call", + toolCallId: "call-1", + responseSchema: yesOrNo, +}; +const fromTheServer = { + id: "call-2", + reason: "human_input", + metadata: { [OPENBOT_WAITING_METADATA]: { requestId: "r1" } }, +}; +const aQuestion = { + id: "int-3", + reason: "input_required", + responseSchema: { type: "object", properties: { city: { type: "string" } } }, +}; + +describe("a wait the Bot raised itself", () => { + test("is told apart from one the server answers", () => { + expect(botRaisedInterrupts([fromTheBot, fromTheServer])).toEqual([ + fromTheBot, + ]); + }); + + test("asks yes or no when its one required answer is the boolean `approved`", () => { + expect(asksForApproval(fromTheBot)).toBe(true); + expect(asksForApproval(aQuestion)).toBe(false); + expect(asksForApproval({ id: "bare" })).toBe(false); + expect( + asksForApproval({ + id: "more", + responseSchema: { ...yesOrNo, required: ["approved", "reason"] }, + }), + ).toBe(false); + }); + + test("names the call it is about, from the conversation", () => { + const messages: Message[] = [ + { id: "u", role: "user", content: "run it" }, + { + id: "a", + role: "assistant", + toolCalls: [ + { + id: "call-1", + type: "function", + function: { name: "shell", arguments: '{"command":"ls"}' }, + }, + ], + }, + ]; + expect(interruptedCall(fromTheBot, messages)).toEqual({ + name: "shell", + args: '{"command":"ls"}', + }); + expect(interruptedCall(aQuestion, messages)).toBeUndefined(); + }); + + test("is answered with the decision, and the server's waits are left to the server", () => { + expect(answersFor([fromTheBot, fromTheServer], true)).toEqual([ + { interruptId: "int-1", status: "resolved", payload: { approved: true } }, + ]); + expect(answersFor([fromTheBot], false)).toEqual([ + { + interruptId: "int-1", + status: "resolved", + payload: { approved: false }, + }, + ]); + }); + + test("is cancelled when its answer is not a yes or no, so the conversation can go on", () => { + expect(answersFor([aQuestion], true)).toEqual([ + { interruptId: "int-3", status: "cancelled" }, + ]); + }); +}); + +describe("a wait whose time is over", () => { + const past = { ...fromTheBot, expiresAt: "2020-01-01T00:00:00.000Z" }; + const later = { ...fromTheBot, expiresAt: "2999-01-01T00:00:00.000Z" }; + + test("is told by its `expiresAt`, and one without is never over", () => { + expect(expired(past)).toBe(true); + expect(expired(later)).toBe(false); + expect(expired(fromTheBot)).toBe(false); + }); + + test("is let go whatever the decision, since the Bot takes none on it", () => { + expect(answersFor([past], true)).toEqual([ + { interruptId: "int-1", status: "cancelled" }, + ]); + expect(answersFor([later], true)).toEqual([ + { interruptId: "int-1", status: "resolved", payload: { approved: true } }, + ]); + }); +}); diff --git a/app/tests/second-organization.test.tsx b/app/tests/second-organization.test.tsx index b8c5d19d77..c3a46dafc2 100644 --- a/app/tests/second-organization.test.tsx +++ b/app/tests/second-organization.test.tsx @@ -63,6 +63,12 @@ const DEPLOYMENT_ADMINS_ONLY = { "Only an admin of the default organization can do this for now, because it applies to every organization here. Ask one of them.", retryable: false, }; +/** What a single-user OpenBot with an install token says to a request that does not carry it. */ +const INSTALL_TOKEN_REFUSAL = { + ...DEPLOYMENT_ADMINS_ONLY, + detail: + "This OpenBot only answers its own app. Open it from the OpenBot app, or use an API key.", +}; const NOT_FOUND = { type: "https://open.bot/errors/organization-not-found", title: "Organization not found.", @@ -354,6 +360,26 @@ test("signed in outside `default`, the app's first load learns what OpenBot offe ]); }); +test("an OpenBot that answers only the browser it let in is asked again with that browser's cookies", async () => { + // A single-user OpenBot in a container knows its one browser by a cookie, and refuses a request without it: the + // deployment asked as nobody, on every page. Refused that way, it is asked once more as the page. + setCurrentOrganization(undefined); + answer = (path, asNobody) => + path === "/api/v2/organizations/default/deployment" && !asNobody + ? Response.json(FACTS) + : problem(INSTALL_TOKEN_REFUSAL); + const capabilities = await freshClient().fetchQuery( + deploymentCapabilitiesQueryOptions(), + ); + expect(capabilities).toMatchObject({ generativeUi: true }); + expect(sent.map((request) => request.path)).toEqual([ + "/api/v2/organizations/default/deployment", + "/api/v2/organizations/default/deployment", + ]); + // The first ask, without cookies, is the one refused; nothing else is. + expect(refused).toHaveLength(1); +}); + test("once the organization is known, what OpenBot offers is asked there, and nobody signed in asks at `default`", async () => { setCurrentOrganization(HARBOR.id); answer = (path) => diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 9939166665..440379d83a 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -224,6 +224,7 @@ export const PYTHON_HARNESSES = [ "agent-llamaindex", "agent-agno", "agent-strands", + "agent-strands-harness", "agent-pydantic-ai", "agent-adk", "agent-antigravity", diff --git a/shared/strands_bot.py b/shared/strands_bot.py new file mode 100644 index 0000000000..5e8550c002 --- /dev/null +++ b/shared/strands_bot.py @@ -0,0 +1,129 @@ +"""What every Bot on AWS Strands is made of, whichever way its agent is built. + +Two Bots run on Strands: `agent-strands`, a plain `strands.Agent`, and `agent-strands-harness`, +the Strands harness. They differ in how a conversation's agent is assembled and in nothing else: +the same model route, the same token check, the same system prompt and the same refusal to hand a +run's forwarded props to the integration. That part is here, and each Bot's `main.py` is what is +left: which agent, and its name. +""" + +import hmac +import os +import sys +from contextlib import aclosing, asynccontextmanager +from pathlib import Path + +# The other files every language in the box reads live beside this one: in the repository under +# shared/, and in an image wherever its Dockerfile copies them. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import gemini_signatures +from empty_turns import without_empty_turns +from model_providers import bot_settings, litellm_model_id +from run_model_key import RunModelKey +from strands_system_prompt import invocation_state + +# A tool call handed back to Gemini 3 goes with Google's placeholder for its thought signature, +# which the integration does not carry between runs. See gemini_signatures.py. +gemini_signatures.install() + +from ag_ui_strands import add_strands_fastapi_endpoint +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse +from strands.models.litellm import LiteLLMModel + +TOKEN_HEADER = "x-openbot-agent-token" + + +def model_id(bot: str) -> str: + """`provider/model`, which is how litellm addresses one. + + The model half is whatever the endpoint publishes, slashes included. litellm takes the first + path component as the provider and sends the rest as the model name, so a name that already + contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an + OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is + `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, + and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) + or sent only the second half to the endpoint. + """ + settings = bot_settings(bot) + return litellm_model_id(settings.provider, settings.model) + + +class WordsAsSaid(LiteLLMModel): + """LiteLLM, sending each step with only the words the model said. + + A step with no words goes as no words, never as LiteLLM's "[System: Empty message content + sanitised to satisfy protocol]", which Claude would read as its own line and say again + (`shared/empty_turns.py`). Only the request each call sends changes: the agent's messages are + left as they were. + """ + + def format_request(self, messages, *args, **kwargs): + request = super().format_request(messages, *args, **kwargs) + return {**request, "messages": without_empty_turns(request["messages"])} + + +def create_app(harness: str) -> FastAPI: + """The Bot's app before its agent is mounted: the run's model key, the token check, `/health`.""" + + @asynccontextmanager + async def lifespan(app: FastAPI): + """What the Bot's agent holds past a run is let go when the process stops serving.""" + yield + for close in app.state.closing: + await close() + + app = FastAPI(lifespan=lifespan) + app.state.closing = [] + # Each run's model calls carry its own gateway token, in its organization. See run_model_key.py. + app.add_middleware(RunModelKey) + + @app.middleware("http") + async def refuse_without_the_server_token(request: Request, call_next): + """Everything but `/health`, which Compose polls before any token exists.""" + if request.url.path != "/health": + expected = (os.environ.get("MANAGED_AGENT_TOKEN") or "").strip() + offered = (request.headers.get(TOKEN_HEADER) or "").strip() + if not expected or not hmac.compare_digest(offered.encode("utf-8"), expected.encode("utf-8")): + return JSONResponse({"error": "unauthorised"}, status_code=401) + return await call_next(request) + + @app.get("/health") + async def health(): + return {"ok": True, "harness": harness} + + return app + + +class WithoutForwardedProps: + """None of a run's forwarded props goes on to the integration. + + Mixed in ahead of the integration's agent class. The one prop this Bot uses, its model route, + was read on the way in (`RunModelKey`); the rest are the server's, which nothing here reads, and + whatever the browser sent. The integration takes `injectA2UITool` as an order: it adds a tool + that calls the model again and, given a tool's name, takes that granted tool away from the run. + """ + + async def run(self, input_data, *, invocation_state=None): + async with aclosing( + super().run( + input_data.model_copy(update={"forwarded_props": {}}), + invocation_state=invocation_state, + ) + ) as events: + async for event in events: + yield event + + +def serve(app: FastAPI, agent) -> None: + """Mount the Bot's agent at `/`. + + The role arrives as system messages on every run and becomes that run's system prompt; see + `strands_system_prompt.py` for why the integration cannot be left to do it. The agent is built + with `RunSystemPrompt` among its hooks, and this is the other half: what that hook reads. + """ + add_strands_fastapi_endpoint(app, agent, "/", invocation_state_provider=invocation_state) + # A harness keeps work between runs (background tasks, connections) and says how to end it. + shutdown = getattr(agent, "shutdown", None) + if callable(shutdown): + app.state.closing.append(shutdown) diff --git a/agent-strands/src/system_prompt.py b/shared/strands_system_prompt.py similarity index 96% rename from agent-strands/src/system_prompt.py rename to shared/strands_system_prompt.py index 627461b5bb..d977c846fb 100644 --- a/agent-strands/src/system_prompt.py +++ b/shared/strands_system_prompt.py @@ -205,8 +205,14 @@ def register_hooks(self, registry: Any, **_kwargs: Any) -> None: registry.add_callback(AfterModelCallEvent, self._after_model_call) def _before_invocation(self, event: BeforeInvocationEvent) -> None: + state = event.invocation_state or {} + # Only a run OpenBot sent carries the key. An invocation without it is one the framework + # started itself: the Strands harness hands its hooks to the subagents it delegates to, + # and such a delegate keeps the prompt it was given. + if KEY not in state: + return parts = [self.base] if self.base else [] - parts.extend((event.invocation_state or {}).get(KEY) or []) + parts.extend(state.get(KEY) or []) event.agent.system_prompt = "\n\n".join(parts) or None def _before_model_call(self, event: BeforeModelCallEvent) -> None: