From 2a442225cdb3c7ab62834b70b7a1c12da0e17f0c Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Fri, 27 Nov 2026 16:53:00 +0100 Subject: [PATCH 1/9] Answer a Bot that stops its own run to ask before it uses a tool --- CHANGELOG.md | 10 ++ .../approvals/bot-approval-notice.tsx | 146 ++++++++++++++++++ app/src/components/channels/channel-chat.tsx | 17 ++ app/src/lib/copilot/bot-raised-interrupts.ts | 90 +++++++++++ app/tests/bot-raised-interrupts.test.ts | 93 +++++++++++ 5 files changed, 356 insertions(+) create mode 100644 app/src/components/approvals/bot-approval-notice.tsx create mode 100644 app/src/lib/copilot/bot-raised-interrupts.ts create mode 100644 app/tests/bot-raised-interrupts.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 945dee7611..4b315e5422 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **A Bot that stops to ask before it uses a tool can be answered.** A Bot connected by its address + can pause its own run to ask, as a harness does before it runs one of its own tools. The + conversation now shows what the Bot wants to use and with what, with Allow and Don't allow; a wait + that is not a yes or no can be let go. Before, nothing showed and the conversation was stuck: + every later message was refused until the wait was answered. + +- **A single-user OpenBot in a container tells its browser about the deployment.** It refused the + page's first question about the deployment on every page, so the release check and attachment + limits were missing. The page now asks once more as the browser that was let in. + - **Notifications in the browser, with OpenBot closed.** Settings, Notifications has a new switch, Notifications in this browser. Turned on, a Bot's replies, questions and approvals reach that browser as push notifications, as "Where updates go" routes push, and a click opens the 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..052d016e8f --- /dev/null +++ b/app/src/components/approvals/bot-approval-notice.tsx @@ -0,0 +1,146 @@ +import type { Message } from "@ag-ui/core"; +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { + answersFor, + asksForApproval, + botRaisedInterrupts, + 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]); + + const waiting = ready ? botRaisedInterrupts(agent.pendingInterrupts) : []; + if (waiting.length === 0 || agent.isRunning) return null; + const approvals = waiting.filter(asksForApproval); + + const answer = async (approved: boolean) => { + if (busy) return; + setBusy(true); + setProblem(null); + try { + await run(answersFor(agent.pendingInterrupts, approved)); + } catch (error) { + setProblem(failureOf(error, "Couldn't send your answer. Try again.")); + } finally { + setBusy(false); + } + }; + + return ( +
+ {approvals.length > 0 ? ( +

{botName} asks before it goes on

+ ) : ( +

+ {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} +
+ {approvals.length > 0 ? ( + <> + + + + ) : ( + + )} +
+
+ ); +} diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index 21c3992088..85310fe8ec 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 { answerMessage, @@ -2667,6 +2668,22 @@ export function ChannelChat({ {channel.active ? ( ) : null} + {/* What the Bot stopped its own run to ask; the answer is the next run's `resume`. */} + { + setRunsInFlight((count) => count + 1); + try { + await whileObserved(agent, () => + copilotkit.runAgent({ agent, resume }), + ); + } finally { + setRunsInFlight((count) => count - 1); + } + }} + /> ; +}; + +/** 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; +} + +/** + * The `resume` that answers every interrupt the agent holds, given the person's decision on those + * the Bot raised. 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 is cancelled, which lets the + * conversation go on. + */ +export function answersFor( + pending: readonly HeldInterrupt[], + approved: boolean, +): InterruptAnswer[] { + return botRaisedInterrupts(pending).map((interrupt) => + asksForApproval(interrupt) + ? { interruptId: interrupt.id, status: "resolved", payload: { approved } } + : { interruptId: interrupt.id, status: "cancelled" }, + ); +} diff --git a/app/tests/bot-raised-interrupts.test.ts b/app/tests/bot-raised-interrupts.test.ts new file mode 100644 index 0000000000..5396c15e63 --- /dev/null +++ b/app/tests/bot-raised-interrupts.test.ts @@ -0,0 +1,93 @@ +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, + 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" }, + ]); + }); +}); From d02732974d305eec00e29f1bb8c221adaaea6c85 Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Fri, 27 Nov 2026 16:53:00 +0100 Subject: [PATCH 2/9] Ask a single-user OpenBot about its deployment again as the browser it let in --- app/src/lib/deployment/queries.ts | 42 +++++++++++++++++--------- app/tests/second-organization.test.tsx | 26 ++++++++++++++++ 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 4b003776b9..0cb5618144 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -126,6 +126,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; @@ -137,17 +162,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) { @@ -156,11 +174,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/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) => From 824aad89cb4ac0d11facea7775004092393d2271 Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Fri, 27 Nov 2026 16:53:01 +0100 Subject: [PATCH 3/9] AWS Strands harness as a Bot, sharing the Strands Bot's server --- .github/workflows/ci.yml | 1 + agent-strands-harness/Dockerfile | 18 ++ agent-strands-harness/requirements-test.txt | 2 + agent-strands-harness/requirements.txt | 11 ++ agent-strands-harness/src/main.py | 105 ++++++++++++ .../tests/strands_bot_suite.py | 30 ++++ .../tests/test_conversation_contract.py | 9 + .../tests/test_forwarded_props_stay_out.py | 9 + agent-strands-harness/tests/test_harness.py | 161 ++++++++++++++++++ .../tests/test_learning_delivery.py | 14 ++ agent-strands-harness/tests/test_main.py | 9 + agent-strands/Dockerfile | 3 +- agent-strands/src/main.py | 85 ++------- scripts/ci-changes.ts | 1 + shared/strands_bot.py | 108 ++++++++++++ .../strands_system_prompt.py | 8 +- 16 files changed, 500 insertions(+), 74 deletions(-) create mode 100644 agent-strands-harness/Dockerfile create mode 100644 agent-strands-harness/requirements-test.txt create mode 100644 agent-strands-harness/requirements.txt create mode 100644 agent-strands-harness/src/main.py create mode 100644 agent-strands-harness/tests/strands_bot_suite.py create mode 100644 agent-strands-harness/tests/test_conversation_contract.py create mode 100644 agent-strands-harness/tests/test_forwarded_props_stay_out.py create mode 100644 agent-strands-harness/tests/test_harness.py create mode 100644 agent-strands-harness/tests/test_learning_delivery.py create mode 100644 agent-strands-harness/tests/test_main.py create mode 100644 shared/strands_bot.py rename agent-strands/src/system_prompt.py => shared/strands_system_prompt.py (96%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 988ed090d8..7cabe83b57 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -709,6 +709,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..abd2986822 --- /dev/null +++ b/agent-strands-harness/Dockerfile @@ -0,0 +1,18 @@ +# 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/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..9023dc1e3e --- /dev/null +++ b/agent-strands-harness/src/main.py @@ -0,0 +1,105 @@ +"""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 UNLESS ASKED FOR. The harness can run commands and edit files 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. `STRANDS_HARNESS_TOOLS` +turns the harness's own on, for a deployment that has decided to; see `harness_options`. +""" + +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, create_app, model_id, serve +from strands_system_prompt import RunSystemPrompt + +from ag_ui_strands import StrandsAgentConfig, StrandsHarnessAgent +from strands.models.litellm import LiteLLMModel +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 _listed(name: str) -> list[str]: + return [item.strip() for item in (os.environ.get(name) or "").split(",") if item.strip()] + + +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. + + `STRANDS_HARNESS_TOOLS` is the harness's own tools to switch on, comma-separated: `shell`, + `read`, `write`, `edit`, `web_fetch`, `web_search`, `programmatic_tool_caller`, `subagent`. + They act where this process runs and the server does not see them. + + `STRANDS_HARNESS_INTERVENTIONS` gates those tools: `ask`, `smart`, or a policy in plain words. + The run stops on an approval the person answers in the conversation. Only those tools: what + OpenBot grants stays OpenBot's to ask about; see where the Bot is built, below. + """ + return { + "model": (os.environ.get("STRANDS_HARNESS_MODEL") or "").strip() + or LiteLLMModel(model_id=_model_id()), + "builtin_tools": _listed("STRANDS_HARNESS_TOOLS"), + "interventions": (os.environ.get("STRANDS_HARNESS_INTERVENTIONS") or "").strip() or None, + "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)], + # THE HARNESS'S GATE ASKS ABOUT EVERY TOOL THE AGENT HAS, and here most of them are not the + # harness's: they are the ones OpenBot grants, which reach the agent as tools the client + # runs. Those are the server's to check, with its own rules, card and audit row. Left to the + # harness as well, a Bot stopped to ask about `askApproval` itself, the tool that asks, and + # the person was shown OpenBot's card and the harness's question for one step. + gate_client_tools=False, + ), +) 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..c766bc38db --- /dev/null +++ b/agent-strands-harness/tests/test_harness.py @@ -0,0 +1,161 @@ +"""What makes this Bot the harness, and what it leaves to OpenBot.""" + +import importlib +import json +import sys +from pathlib import Path + +import pytest +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", "STRANDS_HARNESS_TOOLS", "STRANDS_HARNESS_INTERVENTIONS") + + +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_by_default(monkeypatch): + """They would run in this container, past the server's gateway.""" + with fake_provider() as (base, bodies): + _run(_main(monkeypatch, base)) + 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_deployment_can_switch_the_harness_tools_on(monkeypatch): + with fake_provider() as (base, bodies): + _run(_main(monkeypatch, base, STRANDS_HARNESS_TOOLS="shell, read")) + assert {"shell", "read"} <= set(_offered(bodies[-1])) + assert "write" not in _offered(bodies[-1]) + + +@pytest.mark.parametrize("value,expected", [("", None), (" ", None), ("ask", "ask")]) +def test_interventions_come_from_the_environment(monkeypatch, value, expected): + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base, STRANDS_HARNESS_INTERVENTIONS=value) + assert main.harness_options()["interventions"] == expected + + +def test_the_gate_is_kept_to_the_harnesss_tools(monkeypatch): + """A tool OpenBot grants is run by the client, and the server already asks about it.""" + with fake_provider() as (base, _bodies): + main = _main(monkeypatch, base, STRANDS_HARNESS_INTERVENTIONS="ask") + (bot,) = [bot for bot in _bots(main) if bot._harness_options["interventions"] == "ask"] + assert bot._gate_client_tools is False + + +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 ab9c308d7d..8ddeadef9d 100644 --- a/agent-strands/Dockerfile +++ b/agent-strands/Dockerfile @@ -9,7 +9,8 @@ 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/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.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 2c12411e46..bec1ec7b71 100644 --- a/agent-strands/src/main.py +++ b/agent-strands/src/main.py @@ -1,95 +1,36 @@ """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 model_providers import bot_settings -from run_model_key import RunModelKey +from strands_bot import WithoutForwardedProps, create_app, model_id, serve +from strands_system_prompt import RunSystemPrompt -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.system_prompt import RunSystemPrompt, invocation_state +BOT = "agent-strands" def _model_id() -> str: - """`provider/model`, which is how litellm addresses one. + return model_id(BOT) - 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 f"{provider}/{model}" +class Bot(WithoutForwardedProps, StrandsAgent): + """The integration's agent, minus a run's forwarded props.""" -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. - - 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 - - -# 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. -add_strands_fastapi_endpoint( +app = create_app("strands") +serve( app, - WithoutForwardedProps( + Bot( name="openbot", agent=Agent(model=LiteLLMModel(model_id=_model_id())), hooks=[RunSystemPrompt()], ), - "/", - invocation_state_provider=invocation_state, ) diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 9959caf796..386481c768 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -139,6 +139,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..3ca07c86cd --- /dev/null +++ b/shared/strands_bot.py @@ -0,0 +1,108 @@ +"""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)) +from model_providers import bot_settings +from run_model_key import RunModelKey +from strands_system_prompt import invocation_state + +from ag_ui_strands import add_strands_fastapi_endpoint +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse + +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 f"{settings.provider}/{settings.model}" + + +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: From cda0a76b7e6dfaa7886bb77fa660b471086103ff Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Fri, 27 Nov 2026 16:53:00 +0100 Subject: [PATCH 4/9] Answer a Bot that stops its own run to ask before it uses a tool --- CHANGELOG.md | 10 ++ .../approvals/bot-approval-notice.tsx | 146 ++++++++++++++++++ app/src/components/channels/channel-chat.tsx | 17 ++ app/src/lib/copilot/bot-raised-interrupts.ts | 90 +++++++++++ app/tests/bot-raised-interrupts.test.ts | 93 +++++++++++ 5 files changed, 356 insertions(+) create mode 100644 app/src/components/approvals/bot-approval-notice.tsx create mode 100644 app/src/lib/copilot/bot-raised-interrupts.ts create mode 100644 app/tests/bot-raised-interrupts.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b5822ccde5..0059e3ed38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **A Bot that stops to ask before it uses a tool can be answered.** A Bot connected by its address + can pause its own run to ask, as a harness does before it runs one of its own tools. The + conversation now shows what the Bot wants to use and with what, with Allow and Don't allow; a wait + that is not a yes or no can be let go. Before, nothing showed and the conversation was stuck: + every later message was refused until the wait was answered. + +- **A single-user OpenBot in a container tells its browser about the deployment.** It refused the + page's first question about the deployment on every page, so the release check and attachment + limits were missing. The page now asks once more as the browser that was let in. + **Before upgrading.** - **Migrations run at start: six, and all are expands.** The database moves from 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..052d016e8f --- /dev/null +++ b/app/src/components/approvals/bot-approval-notice.tsx @@ -0,0 +1,146 @@ +import type { Message } from "@ag-ui/core"; +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { + answersFor, + asksForApproval, + botRaisedInterrupts, + 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]); + + const waiting = ready ? botRaisedInterrupts(agent.pendingInterrupts) : []; + if (waiting.length === 0 || agent.isRunning) return null; + const approvals = waiting.filter(asksForApproval); + + const answer = async (approved: boolean) => { + if (busy) return; + setBusy(true); + setProblem(null); + try { + await run(answersFor(agent.pendingInterrupts, approved)); + } catch (error) { + setProblem(failureOf(error, "Couldn't send your answer. Try again.")); + } finally { + setBusy(false); + } + }; + + return ( +
+ {approvals.length > 0 ? ( +

{botName} asks before it goes on

+ ) : ( +

+ {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} +
+ {approvals.length > 0 ? ( + <> + + + + ) : ( + + )} +
+
+ ); +} diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index a0a396a7a1..cf2efc7718 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 { answerMessage, @@ -3050,6 +3051,22 @@ export function ChannelChat({ {channel.active ? ( ) : null} + {/* What the Bot stopped its own run to ask; the answer is the next run's `resume`. */} + { + setRunsInFlight((count) => count + 1); + try { + await whileObserved(agent, () => + copilotkit.runAgent({ agent, resume }), + ); + } finally { + setRunsInFlight((count) => count - 1); + } + }} + /> ; +}; + +/** 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; +} + +/** + * The `resume` that answers every interrupt the agent holds, given the person's decision on those + * the Bot raised. 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 is cancelled, which lets the + * conversation go on. + */ +export function answersFor( + pending: readonly HeldInterrupt[], + approved: boolean, +): InterruptAnswer[] { + return botRaisedInterrupts(pending).map((interrupt) => + asksForApproval(interrupt) + ? { interruptId: interrupt.id, status: "resolved", payload: { approved } } + : { interruptId: interrupt.id, status: "cancelled" }, + ); +} diff --git a/app/tests/bot-raised-interrupts.test.ts b/app/tests/bot-raised-interrupts.test.ts new file mode 100644 index 0000000000..5396c15e63 --- /dev/null +++ b/app/tests/bot-raised-interrupts.test.ts @@ -0,0 +1,93 @@ +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, + 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" }, + ]); + }); +}); From f328c251ba7d09043371ca82b2053ce199fe8150 Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Fri, 27 Nov 2026 16:53:00 +0100 Subject: [PATCH 5/9] Ask a single-user OpenBot about its deployment again as the browser it let in --- app/src/lib/deployment/queries.ts | 42 +++++++++++++++++--------- app/tests/second-organization.test.tsx | 26 ++++++++++++++++ 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 4b003776b9..0cb5618144 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -126,6 +126,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; @@ -137,17 +162,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) { @@ -156,11 +174,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/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) => From abd16d405732791a16dfea135f59ae5f81c416fa Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Thu, 3 Dec 2026 13:35:41 +0100 Subject: [PATCH 6/9] Leave the harness's gate to the integration, which keeps it off the client's tools --- agent-strands-harness/src/main.py | 9 ++------- agent-strands-harness/tests/test_harness.py | 8 -------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/agent-strands-harness/src/main.py b/agent-strands-harness/src/main.py index bf082c073d..be66965651 100644 --- a/agent-strands-harness/src/main.py +++ b/agent-strands-harness/src/main.py @@ -61,7 +61,8 @@ def harness_options() -> dict: `STRANDS_HARNESS_INTERVENTIONS` gates those tools: `ask`, `smart`, or a policy in plain words. The run stops on an approval the person answers in the conversation. Only those tools: what - OpenBot grants stays OpenBot's to ask about; see where the Bot is built, below. + OpenBot grants reaches the agent as tools the client runs, and the integration keeps the + harness's gate off those. They are the server's to check, with its own rules, card and audit row. """ return { "model": (os.environ.get("STRANDS_HARNESS_MODEL") or "").strip() @@ -94,11 +95,5 @@ class Bot(WithoutForwardedProps, StrandsHarnessAgent): 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)], - # THE HARNESS'S GATE ASKS ABOUT EVERY TOOL THE AGENT HAS, and here most of them are not the - # harness's: they are the ones OpenBot grants, which reach the agent as tools the client - # runs. Those are the server's to check, with its own rules, card and audit row. Left to the - # harness as well, a Bot stopped to ask about `askApproval` itself, the tool that asks, and - # the person was shown OpenBot's card and the harness's question for one step. - gate_client_tools=False, ), ) diff --git a/agent-strands-harness/tests/test_harness.py b/agent-strands-harness/tests/test_harness.py index c766bc38db..a44395c632 100644 --- a/agent-strands-harness/tests/test_harness.py +++ b/agent-strands-harness/tests/test_harness.py @@ -120,14 +120,6 @@ def test_interventions_come_from_the_environment(monkeypatch, value, expected): assert main.harness_options()["interventions"] == expected -def test_the_gate_is_kept_to_the_harnesss_tools(monkeypatch): - """A tool OpenBot grants is run by the client, and the server already asks about it.""" - with fake_provider() as (base, _bodies): - main = _main(monkeypatch, base, STRANDS_HARNESS_INTERVENTIONS="ask") - (bot,) = [bot for bot in _bots(main) if bot._harness_options["interventions"] == "ask"] - assert bot._gate_client_tools is False - - 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) From 95500d95a8133498ed2fc67547bd4eceda9ea547 Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Thu, 3 Dec 2026 14:53:25 +0100 Subject: [PATCH 7/9] Take the release note out of CHANGELOG.md: it goes in the pull request's description --- CHANGELOG.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dce3b15f6e..20b215ff8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,16 +8,6 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased -- **A Bot that stops to ask before it uses a tool can be answered.** A Bot connected by its address - can pause its own run to ask, as a harness does before it runs one of its own tools. The - conversation now shows what the Bot wants to use and with what, with Allow and Don't allow; a wait - that is not a yes or no can be let go. Before, nothing showed and the conversation was stuck: - every later message was refused until the wait was answered. - -- **A single-user OpenBot in a container tells its browser about the deployment.** It refused the - page's first question about the deployment on every page, so the release check and attachment - limits were missing. The page now asks once more as the browser that was let in. - ## 1.2.9 **Before upgrading.** From a97deb75660f59a8994848b8938d480337e62208 Mon Sep 17 00:00:00 2001 From: Markus Ecker Date: Fri, 4 Dec 2026 11:33:42 +0100 Subject: [PATCH 8/9] Answering a Bot's own wait: sent beside a wait of OpenBot's, let go once its time is over, and tracked as a turn - A wait OpenBot holds beside the Bot's is released on the agent before the answer is sent, as before any message: with both replayed, Allow sent nothing. - A wait whose time is over can only be let go. The card says so and offers that, and a click checks again. - The answer runs as a turn like any other, so what the Bot goes on to say reaches the roster and a failed run is said under the transcript; one that never left the browser is said on the card. --- .../approvals/bot-approval-notice.tsx | 26 +- app/src/components/channels/channel-chat.tsx | 92 ++++- app/src/lib/copilot/bot-raised-interrupts.ts | 27 +- app/tests/bot-approval-resume.test.tsx | 339 ++++++++++++++++++ app/tests/bot-raised-interrupts.test.ts | 21 ++ 5 files changed, 479 insertions(+), 26 deletions(-) create mode 100644 app/tests/bot-approval-resume.test.tsx diff --git a/app/src/components/approvals/bot-approval-notice.tsx b/app/src/components/approvals/bot-approval-notice.tsx index 052d016e8f..3a9dd675c2 100644 --- a/app/src/components/approvals/bot-approval-notice.tsx +++ b/app/src/components/approvals/bot-approval-notice.tsx @@ -5,6 +5,7 @@ import { answersFor, asksForApproval, botRaisedInterrupts, + expired, type HeldInterrupt, type InterruptAnswer, interruptedCall, @@ -54,16 +55,31 @@ export function BotApprovalNotice({ 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)); + await run(answersFor(agent.pendingInterrupts, approved, now)); } catch (error) { setProblem(failureOf(error, "Couldn't send your answer. Try again.")); } finally { @@ -77,8 +93,12 @@ export function BotApprovalNotice({ data-bot-approval role="status" > - {approvals.length > 0 ? ( + {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 @@ -116,7 +136,7 @@ export function BotApprovalNotice({

) : null}
- {approvals.length > 0 ? ( + {open.length > 0 ? ( <>