Skip to content

Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.

OpenBot

Guido Vizosof238ce97ce0e
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..dfe07704
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..b03d0cc9
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,85 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+# Least privilege by default. Jobs that need more must declare it locally.
+permissions:
+ contents: read
+
+# The newest push on a branch wins; main runs are retained for badge and release history.
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+
+jobs:
+ # Formatting, linting, typing and tests are independent checks, so each reports its own result.
+ static:
+ name: format, lint, types
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ # Checkout leaves a usable credential in the runner otherwise, which every later step and
+ # every action it calls can read. Nothing here pushes.
+ persist-credentials: false
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
+ with:
+ bun-version: 1.3.14
+ - run: bun install --frozen-lockfile
+ - run: bun run format:check
+ - run: bun run lint
+ - run: bun run typecheck
+
+ test:
+ name: tests
+ runs-on: ubuntu-latest
+ # The suite includes a real database integration test. Without a database it fails on every run,
+ # including on main, which trains everyone to read a red CI as normal. pgvector rather than plain
+ # postgres because the knowledge schema uses the extension.
+ services:
+ postgres:
+ image: pgvector/pgvector:pg17
+ env:
+ POSTGRES_DB: openbot
+ POSTGRES_USER: openbot
+ POSTGRES_PASSWORD: openbot
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd "pg_isready -U openbot -d openbot"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 10
+ env:
+ DATABASE_URL: postgres://openbot:openbot@localhost:5432/openbot
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
+ with:
+ bun-version: 1.3.14
+ - run: bun install --frozen-lockfile
+ # Not the db:migrate script: that one loads ../.env, which does not exist in CI. DATABASE_URL
+ # comes from the job env instead, which drizzle.config.ts already reads.
+ - run: bunx drizzle-kit migrate --config=drizzle.config.ts
+ working-directory: server
+ # A passing job must include the expected test floor. Import-time failures can otherwise skip
+ # files before their tests are registered.
+ - run: bun run test:ci
+
+ build:
+ name: build
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
+ with:
+ bun-version: 1.3.14
+ - run: bun install --frozen-lockfile
+ - run: bun run build
diff --git a/.github/workflows/security_zizmor.yml b/.github/workflows/security_zizmor.yml
new file mode 100644
index 00000000..60cfab5b
--- /dev/null
+++ b/.github/workflows/security_zizmor.yml
@@ -0,0 +1,56 @@
+name: security / zizmor
+
+# zizmor runs static analysis over every workflow under .github/workflows looking for the well-known
+# classes of GitHub Actions footguns: template injection from untrusted input, dangerous triggers
+# like `pull_request_target`, unpinned `uses:` refs, excessive token scopes, secret exfiltration
+# through job outputs, and a long tail of others.
+#
+# Public pull requests make workflow inputs and token scopes a security boundary.
+#
+# Findings at `low` confidence and above fail the job. Intentional exceptions belong in
+# `.github/zizmor.yml` with a justification.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - ".github/workflows/**"
+ - ".github/actions/**"
+ - ".github/zizmor.yml"
+ pull_request:
+ paths:
+ - ".github/workflows/**"
+ - ".github/actions/**"
+ - ".github/zizmor.yml"
+ schedule:
+ # Catch findings introduced by newly-published advisories even in a week when no workflow changed.
+ - cron: "0 9 * * 1"
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ zizmor:
+ name: Static analysis (zizmor)
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Run zizmor
+ # `min-severity: low` blocks on the broadest set of findings without flagging
+ # hypothetical-only informational notes.
+ uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2
+ with:
+ min-severity: low
+ advanced-security: false
+ config: .github/zizmor.yml
diff --git a/.github/zizmor.yml b/.github/zizmor.yml
new file mode 100644
index 00000000..4f88bf79
--- /dev/null
+++ b/.github/zizmor.yml
@@ -0,0 +1,15 @@
+# zizmor configuration, static analysis for GitHub Actions workflows.
+#
+# Docs: https://docs.zizmor.sh/configuration/
+#
+# This lives at `.github/zizmor.yml` because zizmor discovers it there. The workflow at
+# `.github/workflows/security_zizmor.yml` runs it and fails on findings at the configured level.
+#
+# Findings that cannot be remediated belong under `rules:` with a justification. Blanket suppressions
+# are not allowed.
+
+rules:
+ # `template-injection` flags untrusted ${{ }} expansions inside `run:` scripts. Route values
+ # through `env:` and reference the environment variable inside the shell.
+ template-injection:
+ ignore: []
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..110393c7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,236 @@
+# OpenBot
+
+Bots are teammates you hand real work to. They sign in to apps and websites and use them the way you do, on a computer that stays theirs between sessions. Name one, give it a role, grant it access as it earns it, and talk to it in a channel.
+
+OpenBot is the open one. It runs on your own machine, it takes any AG-UI agent you bring, and it puts the boundaries where they belong.
+
+**Every Bot gets a computer of its own.** Not one machine per account that everything you have made shares. Each Bot gets a container to itself: its own Chromium holding its own logins, its own filesystem, and only the tools you granted it. No Bot can read another's files or reuse another's sign-ins, so separate Bots really are separate boundaries.
+
+**Every action is decided before it happens and recorded after.** Each page opened, file written, MCP tool called and component drawn goes past a policy you write, and into a trail that keeps what was allowed and what was refused, every refusal naming the rule that refused it. When a Bot reaches something it should not do alone it stops and asks, and you can take the wheel in its browser and hand it back.
+
+**It answers in components, not only prose.** Charts, tables and forms are drawn into the conversation, and you can write a new component in the browser and publish it without a rebuild. Threads and memory are durable through CopilotKit Intelligence.
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="assets/architecture-dark.svg">
+ <img src="assets/architecture-light.svg" alt="You talk to the server, which sends the turn to a Bot over AG-UI. Every tool call the Bot makes comes back through the gateway, which resolves the target, decides it against your policy, records an audit row, and only then acts, or refuses and names the rule. Allowed browser and file actions reach that Bot's own computer, one container each with its own Chromium, logins and workspace, built by the supervisor. Decisions land in PostgreSQL and threads in CopilotKit Intelligence.">
+</picture>
+
+> **Alpha, and under active development.** OpenBot is early. Expect rough edges and bugs, and expect things to move. Issues and pull requests are welcome.
+
+> **Runs on your machine.** Everything below is written for a laptop. Out of the box OpenBot runs with `OPENBOT_DEV_NO_AUTH`, which skips signing in and admits every request as one administrator; [Google sign-in](#sign-in-with-google) can be wired up instead.
+
+## Requirements
+
+- Docker, for PostgreSQL, browser computers, the supervisor, and the shipped Bots.
+- [Bun](https://bun.sh) 1.3+, for the app and API server.
+- A CopilotKit Intelligence project and license.
+- A model key. The proof-of-concept Bot uses OpenAI; the LangGraph Bot can use OpenAI, Anthropic, or Google.
+
+## Quick start
+
+1. Create `.env`:
+
+ ```sh
+ cp .env.example .env
+ ```
+
+2. Get CopilotKit Intelligence credentials:
+
+ ```sh
+ npx --yes copilotkit@latest login
+ npx --yes copilotkit@latest project select
+ npx --yes copilotkit@latest license --write
+ ```
+
+ Put the `cpk-...` runtime key from `project select` in `.env` as
+ `INTELLIGENCE_API_KEY`. `license --write` writes
+ `COPILOTKIT_LICENSE_TOKEN` into the existing `.env`.
+
+3. Fill the remaining required values:
+
+ - `OPENAI_API_KEY`
+
+ Keep the managed Intelligence URLs from `.env.example` unless you run Intelligence yourself. The example `KEY_ENCRYPTION_KEY` is public and fine locally; generate your own with:
+
+ ```sh
+ openssl rand -base64 32
+ ```
+
+4. Install and run:
+
+ ```sh
+ bun install
+ bash scripts/start.sh
+ ```
+
+5. Open <http://localhost:3010>.
+
+`scripts/start.sh` starts Docker services, applies migrations, starts the API server on port 3001, starts the app on port 3010, and checks that the services answer their own health routes before printing next steps.
+
+## Try it
+
+- Open `/bot` and ask: `Open news.ycombinator.com and tell me the top story.`
+- Ask the Bot to fill out <https://httpbin.org/forms/post>, then inspect `/admin/audit`.
+- Open `/admin/boundaries`, add a deny rule or preset, and retry the same browser action.
+- Create a teammate from `/agents`, give it a standing role, and start a channel with it.
+
+## Main surfaces
+
+| Route | Purpose |
+| -------------------- | ------------------------------------------------------------------ |
+| `/` | Start and browse channels. |
+| `/agents` | Create, edit, duplicate, hide, delete, and launch teammates. |
+| `/channel/:id` | Converse with one teammate and view its live screen/profile panel. |
+| `/bot` | Direct chat with a Bot; `?agent=<id>` selects one. |
+| `/skills` | Create and enable personal skills. |
+| `/settings` | User preferences. |
+| `/admin/connectors` | Configure deployment knowledge sources. |
+| `/admin/credentials` | Store write-only encrypted credentials. |
+| `/admin/computers` | View, stop, and reset Bot computers. |
+| `/admin/boundaries` | Configure browser/file/MCP action policy. |
+| `/admin/components` | Publish components and govern which Bots may use them. |
+| `/admin/playground` | Draft and publish sandboxed components in the browser. |
+| `/admin/plugins` | Configure MCP servers, MCP grants, and deployment skills. |
+| `/admin/audit` | Review permitted, refused, and failed actions. |
+
+## Bring your own agent
+
+Any AG-UI endpoint can be a Bot.
+
+From `/agents`, create a teammate with:
+
+- name, title, and role description;
+- private or public visibility;
+- optional AG-UI endpoint;
+- optional write-only authorization header.
+
+The server validates agent endpoints with the same target checks used for browser navigation. If no custom endpoint is set, product-created teammates use `MANAGED_AGENT_AG_UI_URL`.
+
+Tenant package agents are declared in `agents.yaml` as either:
+
+- `built-in`, with a system prompt; or
+- `remote-ag-ui`, with an endpoint.
+
+See [docs/configuration.md](docs/configuration.md) and [docs/teammates.md](docs/teammates.md).
+
+## Configuration
+
+`.env.example` is the source template. The API server refuses to start without:
+
+- `DATABASE_URL`
+- `KEY_ENCRYPTION_KEY`
+- `MANAGED_AGENT_AG_UI_URL`
+- `INTELLIGENCE_API_URL`
+- `INTELLIGENCE_GATEWAY_WS_URL`
+- `INTELLIGENCE_API_KEY`
+- `COPILOTKIT_LICENSE_TOKEN`
+
+Settings worth knowing:
+
+| Variable | Use |
+| ------------------------------------ | ------------------------------------------------------------------------- |
+| `OPENBOT_DEV_NO_AUTH` | Admits every request as one administrator. How OpenBot runs today. |
+| `COMPUTER_TOKEN` | Secret every Bot computer request must present. `start.sh` sets one. |
+| `SUPERVISOR_TOKEN` | Secret the supervisor requires. `start.sh` sets one. |
+| `COMPUTER_SUPERVISOR_URL` | Gives each Bot a computer of its own instead of one shared computer. |
+| `COMPUTER_RUNTIME` | Set to `runsc` to run computers under gVisor, where the host has it. |
+| `AGENT_COMPUTER_POLICY` | JSON action policy. Malformed JSON stops server startup. |
+| `AGENT_COMPUTER_ALLOW_PRIVATE_HOSTS` | Lets a Bot reach this machine's own services. |
+| `TENANT_PACKAGE_DIR` | Directory containing tenant YAML. Defaults to `../examples/fintech`. |
+| `DEPLOYMENT_ID` | Names this deployment when two share one Intelligence project. |
+
+Full reference: [docs/configuration.md](docs/configuration.md).
+
+## Architecture
+
+| Service | Port | Purpose |
+| ------------------------ | -------------------------- | ------------------------------------------------------------------------------------------------ |
+| `app` | 3010 | React/Vite UI. |
+| `server` | 3001 | Hono API, CopilotKit runtime, auth, policy, audit, plugins, components, teammates, and channels. |
+| `agent-computer` | 4100 | Chromium plus `/workspace` and browser profile. |
+| `agent-bot` | 4200 | Proof-of-concept AG-UI Bot. |
+| `agent-langgraph` | 4201 | LangGraph AG-UI Bot. |
+| `supervisor` | 4500 host / 4300 container | Creates and manages one computer per Bot. |
+| PostgreSQL with pgvector | 5432 | Product data, policy, audit, credentials, grants, channels, knowledge, and component metadata. |
+| CopilotKit Intelligence | external | Durable threads and memory. |
+
+The server gateway is the product/API path for Bot browser and file tool calls.
+It resolves the target, evaluates policy, writes an audit row, and then calls
+`agent-computer`. The computer also exposes lower-level token-protected service
+endpoints; keep them private and do not use them to bypass the gateway.
+
+More detail: [docs/architecture.md](docs/architecture.md).
+
+## Components, MCP, and skills
+
+- Compiled React components live in `app/src/components/gallery/` and register through the app.
+- Sandboxed components are authored in `/admin/playground`, then published without a rebuild.
+- Component use is checked at call time. A component must exist, be published, and not be withheld from the Bot.
+- Component data functions are granted per component; the shipped functions read the audit trail.
+- Curated MCP catalogue entries ship for Atlassian, Box, Slack, Salesforce, and ServiceNow.
+- Custom MCP servers must pass URL checks and are treated fail-closed.
+- Skills are instructions, not capabilities. Personal skills can be attached only to Bots the author owns; deployment skills are admin-owned.
+
+## Sign in with Google
+
+`OPENBOT_DEV_NO_AUTH` is the default because it needs no OAuth credentials and no consent screen. To sign in for real instead, create a Google OAuth client and set all four of these together:
+
+```sh
+BETTER_AUTH_URL=http://localhost:3001
+BETTER_AUTH_SECRET= # openssl rand -base64 32, at least 32 characters
+GOOGLE_OAUTH_CLIENT_ID=
+GOOGLE_OAUTH_CLIENT_SECRET=
+```
+
+Then set the two that decide who gets in and from where:
+
+- `TRUSTED_ORIGINS` — where the app is served from, `http://localhost:3010` locally. It defaults to `http://localhost:3000`, which is not where `start.sh` serves the app.
+- `INITIAL_ADMIN_EMAILS` — comma separated. An address listed here becomes an administrator the first time it signs in; everybody else becomes a user.
+
+Remove `OPENBOT_DEV_NO_AUTH`, then restart: the sign-in button is written into the app's generated config at startup, so it appears only once all four settings are present. Accounts, sessions and roles are stored in the same PostgreSQL database as everything else.
+
+A partial set is refused rather than ignored: the server will not start with `BETTER_AUTH_SECRET` or `BETTER_AUTH_URL` but no client credentials, or with a secret shorter than 32 characters.
+
+## Keeping it to your machine
+
+- `agent-computer` drives a browser holding real logins. `docker-compose.yml` binds it to loopback; leave it there.
+- Store credentials through `/admin/credentials`, which encrypts them. Do not put credential values in tenant YAML or in committed files.
+- `AGENT_COMPUTER_ALLOW_PRIVATE_HOSTS` lets a Bot reach services on this machine. Unset it if you would rather it could not.
+
+## Development
+
+```sh
+bun run format:check
+bun run lint
+bun run typecheck
+bun run test
+bun run build
+```
+
+After changing the Drizzle schema:
+
+```sh
+bun run --filter server db:generate
+bun run --filter server db:migrate
+```
+
+Use `bash scripts/start.sh` for the whole stack. Use `bun run dev` only when you want the app and server without the Docker Bots and computers.
+
+## Documentation
+
+- [docs/README.md](docs/README.md)
+- [docs/architecture.md](docs/architecture.md)
+- [docs/configuration.md](docs/configuration.md)
+- [docs/development.md](docs/development.md)
+- [docs/teammates.md](docs/teammates.md)
+
+## Contributing
+
+- Open an issue or coordinate before starting substantial work.
+- Keep changes focused and update docs when setup, configuration, architecture, or user behavior changes.
+- Keep secrets, service-account JSON, customer data, and local transcripts out of the repository.
+- Run the checks in [Development](#development) before opening a pull request.
+
+## License
+
+[MIT](./LICENSE) © CopilotKit
diff --git a/agent-bot/bun.lock b/agent-bot/bun.lock
new file mode 100644
index 00000000..a271da5d
--- /dev/null
+++ b/agent-bot/bun.lock
@@ -0,0 +1,101 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@openbot/agent-bot",
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "openai": "^4.104.0",
+ },
+ },
+ },
+ "packages": {
+ "@ag-ui/core": ["@ag-ui/[email protected]", "", { "dependencies": { "zod": "^3.22.4" } }, "sha512-gho1OWjNE6E3Rl7ZEZ1wr2CEpUHjLFU0FqzCZZk439TicLu+BfLCMkMokB07bMGlRmbJ60hM6LW60iOVauCx+Q=="],
+
+ "@ag-ui/encoder": ["@ag-ui/[email protected]", "", { "dependencies": { "@ag-ui/core": "0.0.57", "@ag-ui/proto": "0.0.57" } }, "sha512-ifD9NctR4xyPDR58xF9GK1bj/S8oECFkTeDfuYD8tXdbcOstIJ2TOqU2zhiCKnw7Vw+zR9Qv3TbsM9E7Gi9X3Q=="],
+
+ "@ag-ui/proto": ["@ag-ui/[email protected]", "", { "dependencies": { "@ag-ui/core": "0.0.57", "@bufbuild/protobuf": "^2.2.5", "@protobuf-ts/protoc": "^2.11.1" } }, "sha512-pPENOZt0P6ibH8sCTgq05wLYXi5t3P9B5r/1bWYehXjUxtyOdnukSlWM++SsCIwUXsQdm/b3aBgGjEeTF7RenA=="],
+
+ "@bufbuild/protobuf": ["@bufbuild/[email protected]", "", {}, "sha512-C3UGsiCwSprE2NKIIFA3hCDlpXTMCAXRZuEVp88L1GY36Y41+rYL5fryE+nOFhp4p4JPQvdV8PQ4DWgHgeTE+w=="],
+
+ "@protobuf-ts/protoc": ["@protobuf-ts/[email protected]", "", { "bin": { "protoc": "protoc.js" } }, "sha512-mUZJaV0daGO6HUX90o/atzQ6A7bbN2RSuHtdwo8SSF2Qoe3zHwa4IHyCN1evftTeHfLmdz+45qo47sL+5P8nyg=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="],
+
+ "@types/node-fetch": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "form-data": "^4.0.4" } }, "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw=="],
+
+ "abort-controller": ["[email protected]", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
+
+ "agentkeepalive": ["[email protected]", "", { "dependencies": { "humanize-ms": "^1.2.1" } }, "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ=="],
+
+ "asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],
+
+ "call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
+
+ "combined-stream": ["[email protected]", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="],
+
+ "delayed-stream": ["[email protected]", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
+
+ "dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
+
+ "es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
+
+ "es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
+
+ "es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="],
+
+ "es-set-tostringtag": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="],
+
+ "event-target-shim": ["[email protected]", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="],
+
+ "form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.4", "mime-types": "^2.1.35" } }, "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ=="],
+
+ "form-data-encoder": ["[email protected]", "", {}, "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="],
+
+ "formdata-node": ["[email protected]", "", { "dependencies": { "node-domexception": "1.0.0", "web-streams-polyfill": "4.0.0-beta.3" } }, "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ=="],
+
+ "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
+
+ "get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
+
+ "get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
+
+ "gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
+
+ "has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
+
+ "has-tostringtag": ["[email protected]", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="],
+
+ "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
+
+ "humanize-ms": ["[email protected]", "", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="],
+
+ "math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
+
+ "mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
+
+ "mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
+
+ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
+
+ "node-domexception": ["[email protected]", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
+
+ "node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
+
+ "openai": ["[email protected]", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" }, "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA=="],
+
+ "tr46": ["[email protected]", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
+
+ "web-streams-polyfill": ["[email protected]", "", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="],
+
+ "webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
+
+ "whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+ }
+}
diff --git a/agent-bot/package.json b/agent-bot/package.json
new file mode 100644
index 00000000..40391a10
--- /dev/null
+++ b/agent-bot/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@openbot/agent-bot",
+ "license": "MIT",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "bun --watch src/index.ts",
+ "start": "bun src/index.ts"
+ },
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "openai": "^4.104.0"
+ }
+}
diff --git a/agent-computer/Dockerfile b/agent-computer/Dockerfile
new file mode 100644
index 00000000..594db89e
--- /dev/null
+++ b/agent-computer/Dockerfile
@@ -0,0 +1,29 @@
+# The Bot's computer uses Playwright's image so Chromium and its system libraries stay matched.
+#
+# The image tag and Playwright dependency must be pinned to the same exact version. Bump both or
+# neither.
+FROM mcr.microsoft.com/playwright:v1.62.1-noble
+
+# unzip is not in the Playwright image and bun's installer needs it.
+RUN apt-get update && apt-get install -y --no-install-recommends unzip \
+ && rm -rf /var/lib/apt/lists/* \
+ && curl -fsSL https://bun.sh/install | bash
+ENV PATH="/root/.bun/bin:${PATH}"
+
+WORKDIR /app
+COPY agent-computer/package.json ./
+RUN bun install
+
+COPY agent-computer/src ./src
+
+# Durable working directory. Bot-produced files that must survive replacement live here.
+RUN mkdir -p /workspace
+ENV WORKSPACE_DIR=/workspace
+
+ENV PORT=4100
+EXPOSE 4100
+# Readiness is exposed through Docker health so the supervisor need not know the network route.
+HEALTHCHECK --interval=2s --timeout=3s --start-period=2s --retries=30 \
+ CMD bun -e "const r = await fetch('http://localhost:4100/health'); process.exit(r.ok ? 0 : 1)"
+
+CMD ["bun", "src/index.ts"]
diff --git a/agent-computer/bun.lock b/agent-computer/bun.lock
new file mode 100644
index 00000000..929dce1d
--- /dev/null
+++ b/agent-computer/bun.lock
@@ -0,0 +1,146 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@openbot/agent-computer",
+ "dependencies": {
+ "playwright": "1.62.1",
+ "spiffe": "^0.5.1",
+ "yaml": "^2.9.0",
+ },
+ "devDependencies": {
+ "typescript": "^5.9.3",
+ },
+ },
+ },
+ "packages": {
+ "@grpc/grpc-js": ["@grpc/[email protected]", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ=="],
+
+ "@grpc/proto-loader": ["@grpc/[email protected]", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
+
+ "@js-sdsl/ordered-map": ["@js-sdsl/[email protected]", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
+
+ "@peculiar/asn1-cms": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "@peculiar/asn1-x509-attr": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-VKQz6sJYgSxtGaK6UdnNBUx7hmSdg0K331qrEWh5qxpQsyZGWBjxbq05AJ2bTWWjd7d+nJIxFzwvsR5T7DWC/A=="],
+
+ "@peculiar/asn1-csr": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SbxRzHiWnRdiDuiiji/RLsJxu2au4hmSZSKK7GQOgNr2BVvheAlFQST9qqzRchUcZ6wvcyRuPXIfYXVzLoZ/5g=="],
+
+ "@peculiar/asn1-ecc": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-vNspHtTd9h6e8c2lMW+B/VHEUD+HRFV0fj/Gvz7SaJbwiecA8dxd96UTFPYI1PR8k7qwjjW9AFEyI+LuyVi4Kw=="],
+
+ "@peculiar/asn1-pfx": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.9.0", "@peculiar/asn1-pkcs8": "^2.9.0", "@peculiar/asn1-rsa": "^2.9.0", "@peculiar/asn1-schema": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-A6bX+gZr69U38Pg1mWvPrM1eRba6L6kLR8iVG+bJtKj3qSv2rSNmlXLtej7ZOkEWt6xL6PiJD73uFEdQI3BXCg=="],
+
+ "@peculiar/asn1-pkcs8": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-1JH4FliKQ3trkMD17X+bKGsph5TsiM+AiiqnVKr1wxA/GoUSDHiWG/zROzLAbDIA7eclBCjQsp8hrBEJk7LRUQ=="],
+
+ "@peculiar/asn1-pkcs9": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.9.0", "@peculiar/asn1-pfx": "^2.9.0", "@peculiar/asn1-pkcs8": "^2.9.0", "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "@peculiar/asn1-x509-attr": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-igArY6bpCI6tOPm2EU9QPrXuKq2s1iraLCTym4UlooYdzcRDIPCRUN9TAEcqZ5rZhA+HiPdFKTbDP9vneN/tsg=="],
+
+ "@peculiar/asn1-rsa": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-vOD7Q4UmQWhlMYuWJawS2sD+/JcPKJNtyQuFZx09r+KFhm5/HxfGak63y/m56cpBjmb5k6PeRlQf1fvLQAieUA=="],
+
+ "@peculiar/asn1-schema": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-AKvPMOM7LfK0uFe1m7o7+veOa8xQGPqsqOrKi3QKgCElzwjGp39mbhr2g7mt/v/mXQHiIvJmDj5cJS173x8Q9Q=="],
+
+ "@peculiar/asn1-x509": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-b9Na83rhRFQBd5CuMmuEqokYhmyWUbG7mNZl/thGhBwLpCdiZ85TZ3WFhF7OVgOekC5uKhLk4C3HKtdiScCMdQ=="],
+
+ "@peculiar/asn1-x509-attr": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.0", "@peculiar/asn1-x509": "^2.9.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-f+u+EyGjfPvPzvr0+rlh/TFEO7LWt84mEwQynCUYr4F6urf/8s6+ESJ23qfSn1aamkZR6AuBNaC62iEsGvp0+w=="],
+
+ "@peculiar/json-schema": ["@peculiar/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w=="],
+
+ "@peculiar/utils": ["@peculiar/[email protected]", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="],
+
+ "@peculiar/webcrypto": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.7.0", "@peculiar/json-schema": "^1.1.12", "@peculiar/utils": "^2.0.2", "tslib": "^2.8.1", "webcrypto-core": "^1.9.2" } }, "sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ=="],
+
+ "@peculiar/x509": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.6.0", "@peculiar/asn1-csr": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.0", "@peculiar/asn1-pkcs9": "^2.6.0", "@peculiar/asn1-rsa": "^2.6.0", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.0", "pvtsutils": "^1.3.6", "reflect-metadata": "^0.2.2", "tslib": "^2.8.1", "tsyringe": "^4.10.0" } }, "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA=="],
+
+ "@protobuf-ts/grpc-transport": ["@protobuf-ts/[email protected]", "", { "dependencies": { "@protobuf-ts/runtime": "^2.11.1", "@protobuf-ts/runtime-rpc": "^2.11.1" }, "peerDependencies": { "@grpc/grpc-js": "^1.6.0" } }, "sha512-l6wrcFffY+tuNnuyrNCkRM8hDIsAZVLA8Mn7PKdVyYxITosYh60qW663p9kL6TWXYuDCL3oxH8ih3vLKTDyhtg=="],
+
+ "@protobuf-ts/runtime": ["@protobuf-ts/[email protected]", "", {}, "sha512-KuDaT1IfHkugM2pyz+FwiY80ejWrkH1pAtOBOZFuR6SXEFTsnb/jiQWQ1rCIrcKx2BtyxnxW6BWwsVSA/Ie+WQ=="],
+
+ "@protobuf-ts/runtime-rpc": ["@protobuf-ts/[email protected]", "", { "dependencies": { "@protobuf-ts/runtime": "^2.11.1" } }, "sha512-4CqqUmNA+/uMz00+d3CYKgElXO9VrEbucjnBFEjqI4GuDrEQ32MaI3q+9qPBvIGOlL4PmHXrzM32vBPWRhQKWQ=="],
+
+ "@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
+
+ "@protobufjs/base64": ["@protobufjs/[email protected]", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
+
+ "@protobufjs/codegen": ["@protobufjs/[email protected]", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],
+
+ "@protobufjs/eventemitter": ["@protobufjs/[email protected]", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],
+
+ "@protobufjs/fetch": ["@protobufjs/[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],
+
+ "@protobufjs/float": ["@protobufjs/[email protected]", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
+
+ "@protobufjs/path": ["@protobufjs/[email protected]", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
+
+ "@protobufjs/pool": ["@protobufjs/[email protected]", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
+
+ "@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg=="],
+
+ "ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
+
+ "asn1js": ["[email protected]", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.1.5", "tslib": "^2.8.1" } }, "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg=="],
+
+ "cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
+
+ "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
+
+ "color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
+
+ "emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
+
+ "fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
+
+ "get-caller-file": ["[email protected]", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
+
+ "is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
+
+ "lodash.camelcase": ["[email protected]", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
+
+ "long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
+
+ "playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.62.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg=="],
+
+ "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw=="],
+
+ "protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="],
+
+ "pvtsutils": ["[email protected]", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="],
+
+ "pvutils": ["[email protected]", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="],
+
+ "reflect-metadata": ["[email protected]", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
+
+ "require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
+
+ "spiffe": ["[email protected]", "", { "dependencies": { "@grpc/grpc-js": "^1.14.3", "@peculiar/webcrypto": "^1.5.0", "@peculiar/x509": "^1.14.3", "@protobuf-ts/grpc-transport": "^2.11.1", "@protobuf-ts/runtime": "^2.11.1", "@protobuf-ts/runtime-rpc": "^2.11.1" } }, "sha512-oCHXpMDo0WFXDXPKl6h7pzA1ub6xzp4fnsAEvJwydEeWjIaJsT0lCB06ix8KvIgAcyRZ06rejCjBxRXmaxhn3w=="],
+
+ "string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "tsyringe": ["[email protected]", "", { "dependencies": { "tslib": "^1.9.3" } }, "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
+
+ "webcrypto-core": ["[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.7.0", "@peculiar/json-schema": "^1.1.12", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q=="],
+
+ "wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
+
+ "y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
+
+ "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
+
+ "yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="],
+
+ "yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
+
+ "tsyringe/tslib": ["[email protected]", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
+ }
+}
diff --git a/agent-computer/src/aria-snapshot.ts b/agent-computer/src/aria-snapshot.ts
new file mode 100644
index 00000000..9086edd7
--- /dev/null
+++ b/agent-computer/src/aria-snapshot.ts
@@ -0,0 +1,252 @@
+/**
+ * Turning Playwright's aria snapshot into the flat element list the tool contract publishes.
+ *
+ * Playwright's `mode: "ai"` output is YAML: each entry is a mapping whose key describes the element
+ * and whose value is that control's contents. A YAML parser preserves quoted values, colons, escaped
+ * quotes, multi-line values and deeper indentation.
+ *
+ * Parsed under the failsafe schema, which resolves every scalar as a string. What a control contains
+ * is text, and nothing here wants it typed.
+ *
+ * What remains to parse by hand is one descriptor per element,
+ * `textbox "Customer name:" [ref=e5] [checked]`, and that is scanned rather than matched, because the
+ * parts can contain one another: an accessible name can hold a bracket and a flag can hold a quote.
+ *
+ * This module has no Playwright import, so parser tests do not need a browser.
+ */
+
+import { parse as parseYaml } from "yaml";
+
+/** How many elements a snapshot will describe. Bounded for the same reason the text extract is. */
+const SNAPSHOT_ELEMENT_LIMIT = 200;
+
+/**
+ * The roles worth handing to a Bot that wants to act.
+ *
+ * Role allow-list, not a CSS selector list. `mode: "ai"` returns the whole accessible tree, which on
+ * a real page is mostly headings, paragraphs and generic containers. What a Bot needs in order to fill
+ * in a form is the controls, and naming them by ARIA role is both shorter and more correct than
+ * guessing at tag names: a `div[role=button]` is a button here, and Playwright has already worked out
+ * which is which.
+ */
+const INTERACTIVE_ROLES = new Set([
+ "button",
+ "checkbox",
+ "combobox",
+ "link",
+ "listbox",
+ "menuitem",
+ "menuitemcheckbox",
+ "menuitemradio",
+ "option",
+ "radio",
+ "searchbox",
+ "slider",
+ "spinbutton",
+ "switch",
+ "tab",
+ "textbox",
+]);
+
+/** The roles whose unchecked state is meaningful, so absence of `[checked]` means false, not unknown. */
+const CHECKABLE_ROLES = new Set([
+ "checkbox",
+ "menuitemcheckbox",
+ "menuitemradio",
+ "radio",
+ "switch",
+]);
+
+/**
+ * One thing on the page a Bot can act on.
+ *
+ * Mirrors `SnapshotElement` in the server's published contract (`server/src/computer/schema.ts`), the
+ * same way the workspace entry type does. Duplicated rather than shared because this process is a
+ * separate deployable with no code in common with the server; the two must be changed together, and a
+ * field added here and not there is invisible until a Bot asks for it.
+ */
+export type SnapshotElement = {
+ ref: string;
+ role: string;
+ name: string;
+ /** Present for form controls, so the Bot can tell an empty field from a filled one. */
+ value?: string;
+ disabled?: boolean;
+ checked?: boolean;
+};
+
+/** The descriptor half of an entry: everything before the colon. */
+type Descriptor = {
+ role: string;
+ name: string;
+ flags: Map<string, string>;
+};
+
+/**
+ * Read `textbox "Customer name:" [ref=e5] [checked]`.
+ *
+ * Scanned left to right rather than matched with a pattern, because the parts can contain each other:
+ * an accessible name can contain a bracket, and a flag value can contain a quote. A single expression
+ * that handles every page is not maintainable.
+ */
+export function parseDescriptor(text: string): Descriptor | null {
+ const trimmed = text.trim();
+ if (!trimmed) return null;
+
+ // The role runs up to the first space, quote or bracket.
+ let index = 0;
+ while (
+ index < trimmed.length &&
+ trimmed[index] !== " " &&
+ trimmed[index] !== '"' &&
+ trimmed[index] !== "["
+ ) {
+ index += 1;
+ }
+ const role = trimmed.slice(0, index);
+ if (!role) return null;
+
+ let name = "";
+ const flags = new Map<string, string>();
+
+ while (index < trimmed.length) {
+ const char = trimmed[index];
+
+ if (char === '"') {
+ // The accessible name, consuming escapes so a name containing a quote survives intact.
+ index += 1;
+ let collected = "";
+ while (index < trimmed.length && trimmed[index] !== '"') {
+ if (trimmed[index] === "\\" && index + 1 < trimmed.length) {
+ collected += trimmed[index + 1];
+ index += 2;
+ continue;
+ }
+ collected += trimmed[index];
+ index += 1;
+ }
+ index += 1;
+ name = collected;
+ continue;
+ }
+
+ if (char === "[") {
+ index += 1;
+ let collected = "";
+ while (index < trimmed.length && trimmed[index] !== "]") {
+ collected += trimmed[index];
+ index += 1;
+ }
+ index += 1;
+ const equals = collected.indexOf("=");
+ if (equals === -1) {
+ flags.set(collected.trim(), "");
+ } else {
+ flags.set(
+ collected.slice(0, equals).trim(),
+ collected.slice(equals + 1).trim(),
+ );
+ }
+ continue;
+ }
+
+ index += 1;
+ }
+
+ return { role, name, flags };
+}
+
+/** Build an element from a descriptor and whatever YAML gave as its value, or null if not actionable. */
+function toElement(
+ descriptor: Descriptor,
+ value: unknown,
+): SnapshotElement | null {
+ if (!INTERACTIVE_ROLES.has(descriptor.role)) return null;
+
+ const ref = descriptor.flags.get("ref");
+ // No ref means nothing can be done to it, so it is noise in a list whose entire purpose is acting.
+ if (!ref) return null;
+
+ const element: SnapshotElement = {
+ ref,
+ role: descriptor.role,
+ name: descriptor.name.slice(0, 200),
+ };
+
+ // Values arrive as text, with quoting and escapes already resolved.
+ if (typeof value === "string") {
+ const text = value.trim();
+ if (text) element.value = text.slice(0, 200);
+ }
+
+ if (descriptor.flags.has("disabled")) element.disabled = true;
+
+ // Playwright emits `[checked]` only when something is checked, so absence is ambiguous on its own: a
+ // Bot cannot tell an unticked box from a control that does not tick. Reported as false for the roles
+ // that can be checked, and left off entirely for the ones that cannot.
+ if (descriptor.flags.has("checked")) {
+ element.checked = descriptor.flags.get("checked") !== "false";
+ } else if (CHECKABLE_ROLES.has(descriptor.role)) {
+ element.checked = false;
+ }
+
+ return element;
+}
+
+/** Turn an aria snapshot into the flat element list the tool contract publishes. */
+export function parseAriaSnapshot(yaml: string): {
+ elements: SnapshotElement[];
+ truncated: boolean;
+} {
+ const elements: SnapshotElement[] = [];
+ let truncated = false;
+
+ const push = (element: SnapshotElement): void => {
+ if (elements.length >= SNAPSHOT_ELEMENT_LIMIT) {
+ truncated = true;
+ return;
+ }
+ elements.push(element);
+ };
+
+ let tree: unknown;
+ try {
+ tree = parseYaml(yaml, { schema: "failsafe" });
+ } catch {
+ // A snapshot that will not parse yields no elements rather than throwing. The caller's next move is
+ // to take another one, and an exception here would reach the Bot as a broken computer.
+ return { elements: [], truncated: false };
+ }
+
+ /** Depth first: the tree nests by containment, and a flat list is what a Bot acts on. */
+ const walk = (node: unknown): void => {
+ if (truncated) return;
+
+ if (Array.isArray(node)) {
+ for (const child of node) walk(child);
+ return;
+ }
+
+ if (typeof node === "string") {
+ // An entry with no value: `- button "Submit order" [ref=e44]`.
+ const descriptor = parseDescriptor(node);
+ const element = descriptor ? toElement(descriptor, undefined) : null;
+ if (element) push(element);
+ return;
+ }
+
+ if (node && typeof node === "object") {
+ for (const [key, value] of Object.entries(node)) {
+ const descriptor = parseDescriptor(key);
+ const element = descriptor ? toElement(descriptor, value) : null;
+ if (element) push(element);
+ // Descend regardless of whether this entry was actionable: a `group "Pizza Size"` is not, and
+ // its radios are.
+ if (value && typeof value === "object") walk(value);
+ }
+ }
+ };
+
+ walk(tree);
+ return { elements, truncated };
+}
diff --git a/agent-computer/src/identity.ts b/agent-computer/src/identity.ts
new file mode 100644
index 00000000..38cfa2e0
--- /dev/null
+++ b/agent-computer/src/identity.ts
@@ -0,0 +1,100 @@
+/**
+ * This computer's own identity, asked of the local SPIRE agent.
+ *
+ * No identity is baked in. There is no key in the image and no secret in the environment: the computer
+ * asks the agent over a unix socket, and the agent decides what it is by inspecting the container the
+ * request came from and matching the label the supervisor set when it created it. So a computer
+ * cannot claim to be a Bot it is not, and an unregistered container is issued nothing, which is
+ * the property that makes this worth more than a name in a header.
+ *
+ * The `spiffe` package rather than a hand-rolled gRPC client: it is the maintained Node client for
+ * the Workload API and gets the streaming semantics right.
+ *
+ * A deployment without SPIRE gets `null` and carries on. Identity is available where the deployment
+ * supports it, not a condition of the computer running.
+ */
+
+const SOCKET = process.env.SPIFFE_ENDPOINT_SOCKET;
+
+export type Identity = {
+ spiffeId: string;
+ /** How many identities this workload was issued, so an over-broad entry is visible rather than silent. */
+ issued: number;
+};
+
+let cached: Identity | null = null;
+let attempted = false;
+
+/**
+ * The Workload API is a stream that stays open for rotation. The first batch is the answer, so this
+ * takes it and lets go rather than holding a subscription open for the life of the process.
+ */
+function firstSvid(
+ socket: string,
+ timeoutMs: number,
+): Promise<Identity | null> {
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (value: Identity | null) => {
+ if (settled) return;
+ settled = true;
+ resolve(value);
+ };
+
+ const timer = setTimeout(() => finish(null), timeoutMs);
+
+ void (async () => {
+ try {
+ const { createClient } = (await import("spiffe")) as {
+ createClient: (address: string) => {
+ fetchX509SVID(request: Record<string, never>): {
+ responses: {
+ onMessage(
+ handler: (response: {
+ svids: { spiffeId: string }[];
+ }) => void,
+ ): void;
+ onError(handler: (error: unknown) => void): void;
+ };
+ };
+ };
+ };
+
+ const client = createClient(`unix://${socket}`);
+ const call = client.fetchX509SVID({});
+
+ call.responses.onMessage((response) => {
+ clearTimeout(timer);
+ const first = response.svids?.[0];
+ finish(
+ first
+ ? { spiffeId: first.spiffeId, issued: response.svids.length }
+ : null,
+ );
+ });
+ call.responses.onError(() => {
+ clearTimeout(timer);
+ finish(null);
+ });
+ } catch {
+ clearTimeout(timer);
+ finish(null);
+ }
+ })();
+ });
+}
+
+export async function identity(): Promise<Identity | null> {
+ if (!SOCKET) return null;
+ if (cached || attempted) return cached;
+ attempted = true;
+
+ cached = await firstSvid(SOCKET, 5_000);
+ if (!cached) {
+ // Once, not on every health check: worth knowing, not worth drowning the log.
+ console.warn(
+ "This computer has a SPIRE socket but was issued no identity. Either no entry matches its labels, or the agent is not answering.",
+ );
+ }
+ return cached;
+}
diff --git a/agent-computer/src/index.ts b/agent-computer/src/index.ts
new file mode 100644
index 00000000..f8690607
--- /dev/null
+++ b/agent-computer/src/index.ts
@@ -0,0 +1,1067 @@
+import { serve } from "bun";
+import type { Page } from "playwright";
+import { parseAriaSnapshot, type SnapshotElement } from "./aria-snapshot";
+import { isOpenPath, matchesToken, offeredToken } from "./authorisation";
+import {
+ type Control,
+ ControlError,
+ ControlRequestError,
+ createControl,
+ NO_SECRET_PENDING,
+ TAKE_CONTROL_FIRST,
+} from "./control";
+import { identity } from "./identity";
+import { createProfiles, VIEWPORT } from "./profiles";
+import {
+ type InputMessage,
+ type Screencast,
+ startScreencast,
+} from "./screencast";
+import {
+ createWorkspace,
+ WorkspaceFileError,
+ WorkspacePathError,
+} from "./workspace";
+
+/**
+ * The Bot's computer: one long-lived browser, reachable over HTTP.
+ *
+ * Acting on a page lives in this process because only this process holds the browser. In the
+ * intended deployment path, the server gateway decides whether an action may run and records the
+ * audit row before calling this process. This process has no policy engine and no audit trail of its
+ * own; its direct-port boundary is the computer token.
+ *
+ * `/files/read` and `/files/write` reach the durable workspace volume, confined to
+ * it by workspace.ts. Reading and writing are the two operations a Bot needs to keep notes between
+ * turns.
+ *
+ * Elements are addressed by reference, not by pixel. `/snapshot` stamps every interactive element
+ * with a ref and hands back a compact list; `/click` and `/type` take one of those refs. That is the
+ * accessibility-tree-first driver this is built on, and it is why filling in a form needs no
+ * vision model at all: the Bot reads a list of fields rather than squinting at a picture and guessing
+ * coordinates. Pixels remain the eventual fallback for canvas-style pages that expose no elements.
+ *
+ * One browser stays open so state survives between
+ * turns: a session it signed into an hour ago is still signed in now. Launching per request would
+ * make every task start from a cold, logged-out browser, which is the behaviour we are specifically
+ * trying not to have.
+ *
+ * It authenticates its caller: every request must present the secret below, and the process refuses
+ * to start without one. That is a lock on the door rather than a reason to put the door somewhere
+ * public. It still belongs on the deployment network, behind the server that decides who is asking.
+ */
+
+/**
+ * The secret every caller must present.
+ *
+ * This process drives a browser that holds real logins. Policy, audit, actor identity and SPIFFE
+ * identity live in the server and are not on the direct computer port.
+ *
+ * Refusing to start without a token makes missing authentication a deployment failure, never an open
+ * computer.
+ */
+const COMPUTER_TOKEN = process.env.COMPUTER_TOKEN?.trim();
+if (!COMPUTER_TOKEN) {
+ console.error(
+ "COMPUTER_TOKEN is not set. This process drives a browser holding real logins and will not start without the secret its caller must present.",
+ );
+ process.exit(1);
+}
+
+const PORT = Number.parseInt(process.env.PORT ?? "4100", 10);
+const NAVIGATION_TIMEOUT_MS = Number.parseInt(
+ process.env.NAVIGATION_TIMEOUT_MS ?? "30000",
+ 10,
+);
+
+/**
+ * How long one action waits for its element.
+ *
+ * Much shorter than a navigation. Playwright waits for a control to become clickable, which is the
+ * behaviour we want, but a ref that no longer resolves would otherwise hang for the full navigation
+ * timeout before saying so, and the person is sitting watching a screen that is not changing.
+ */
+const ACTION_TIMEOUT_MS = Number.parseInt(
+ process.env.ACTION_TIMEOUT_MS ?? "10000",
+ 10,
+);
+
+/**
+ * How much page text a navigation hands back.
+ *
+ * Bounded because a page can be megabytes and the text goes into a model's context, where a single
+ * unbounded page can push the rest of the conversation out. Generous enough that the visible part of
+ * an ordinary page arrives whole, which is what the answer is usually made of.
+ */
+const TEXT_EXTRACT_LIMIT = 6000;
+
+/**
+ * Which snapshot the caller's refs came from.
+ *
+ * Kept as a caller-facing guard even though Playwright enforces the real thing underneath. The
+ * published tool contract says an action carries the `snapshotId` it got, and a mismatch is answered
+ * with "take a new snapshot", which is a clearer message for a model than an element that merely fails
+ * to resolve. Playwright's `aria-ref` engine is the runtime enforcement: it resolves a ref only against
+ * the most recent snapshot, only while the element is still connected to the document, and it mints a
+ * new ref if an element's role or accessible name changed, so a recycled node cannot inherit an old one.
+ */
+/** Per-Bot browser-control state. Profiles are isolated, but this process is not a security boundary. */
+type BotSession = {
+ control: Control;
+ /** This Bot's snapshot generation. See the note above on staleness. */
+ snapshotId: number;
+ /** The one live screen viewer for this Bot, if a person is watching. */
+ viewer?: {
+ socket: unknown;
+ cast: Screencast;
+ /** Stops the loop that keeps the cast pointed at whatever page the Bot is actually on. */
+ follow?: ReturnType<typeof setInterval>;
+ };
+};
+
+const sessions = new Map<string, BotSession>();
+
+function sessionFor(botId: string): BotSession {
+ const existing = sessions.get(botId);
+ if (existing) return existing;
+ const created: BotSession = { control: createControl(), snapshotId: 0 };
+ sessions.set(botId, created);
+ return created;
+}
+
+/**
+ * Sent by the server as a header on every call. Absent means the caller does not know or does not
+ * care, such as a health check, and that gets the default computer rather than an error, because
+ * refusing it would make the container undemonstrable on its own.
+ */
+function botIdOf(request: Request, fallback?: string | null): string {
+ return (
+ request.headers.get("x-openbot-bot-id")?.trim() ||
+ fallback?.trim() ||
+ DEFAULT_BOT_ID
+ );
+}
+
+/**
+ * The Bot's durable files.
+ *
+ * Rooted at WORKSPACE_DIR, which the image creates and docker-compose mounts as a volume, so what a
+ * Bot saves outlives the container. Built once at boot: the root is fixed, and resolving it per request
+ * would only add a syscall to every call. Everything about why confinement is harder than it looks
+ * lives in workspace.ts.
+ */
+const workspace = createWorkspace(process.env.WORKSPACE_DIR ?? "/workspace");
+
+/**
+ * Who has the wheel, as a state machine in its own module.
+ *
+ * The state machine lives in `control.ts` so it can be tested without importing Playwright.
+ */
+
+/**
+ * The Bot's browser and the profile that outlives it. See profiles.ts.
+ *
+ * `chromium.launch()` gives a fresh anonymous profile every time. Persistent profiles live on a
+ * mounted volume so sign-in state survives the container.
+ */
+const profiles = createProfiles(process.env.PROFILES_DIR ?? "/profiles");
+
+/**
+ * The id normally arrives as a header on every request. This is the fallback for a caller that has no
+ * Bot to name, such as a health check, so the container stays demonstrable on its own rather than
+ * refusing everything that is not the server.
+ */
+const DEFAULT_BOT_ID = process.env.COMPUTER_BOT_ID ?? "shared";
+
+async function currentPage(botId: string): Promise<Page> {
+ return profiles.page(botId);
+}
+
+/**
+ * The page as text, the way a reader sees it.
+ *
+ * Script and style bodies are dropped rather than included: they are the bulk of a modern page and
+ * none of it is what anybody asked about, so leaving them in spends the extract on noise and pushes
+ * the actual article past the limit.
+ */
+async function readablePageText(
+ target: Page,
+): Promise<{ text: string; truncated: boolean }> {
+ const raw = await target.evaluate(() => {
+ const clone = document.body?.cloneNode(true) as HTMLElement | undefined;
+ if (!clone) return "";
+ for (const node of clone.querySelectorAll("script, style, noscript, svg")) {
+ node.remove();
+ }
+ return clone.innerText ?? "";
+ });
+
+ const collapsed = raw.replace(/\n{3,}/g, "\n\n").trim();
+ return {
+ text: collapsed.slice(0, TEXT_EXTRACT_LIMIT),
+ truncated: collapsed.length > TEXT_EXTRACT_LIMIT,
+ };
+}
+
+/**
+ * Describe everything on the page a Bot can act on.
+ *
+ * Uses Playwright's AI snapshot rather than stamping attributes into the DOM. `ariaSnapshot` keeps
+ * refs outside the page, survives framework re-renders, resolves accessible names, reports current
+ * values and checked state, filters to actionable elements and descends into iframes.
+ */
+async function snapshotPage(
+ session: BotSession,
+ target: Page,
+): Promise<{
+ snapshotId: number;
+ url: string;
+ title: string;
+ elements: SnapshotElement[];
+ truncated: boolean;
+}> {
+ session.snapshotId += 1;
+ const yaml = await target.ariaSnapshot({ mode: "ai" });
+ return {
+ snapshotId: session.snapshotId,
+ url: target.url(),
+ title: await target.title(),
+ ...parseAriaSnapshot(yaml),
+ };
+}
+
+/**
+ * Resolve a ref to a locator, refusing anything from a superseded snapshot.
+ *
+ * `aria-ref=` is a first-party Playwright selector engine, and it is the same one its MCP server uses.
+ * The generation check here is the caller-facing half; see the note on `snapshotId` for why both exist.
+ */
+function locateRef(
+ session: BotSession,
+ target: Page,
+ ref: string,
+ expectedSnapshotId: number | undefined,
+) {
+ if (
+ expectedSnapshotId !== undefined &&
+ expectedSnapshotId !== session.snapshotId
+ ) {
+ throw new StaleSnapshotError(
+ `That list of elements is out of date: it was taken for snapshot ${expectedSnapshotId} and the page is now at ${session.snapshotId}. Take a new snapshot and use the refs from it.`,
+ );
+ }
+ return target.locator(`aria-ref=${ref}`);
+}
+
+/**
+ * The element, or a refusal that says what to do about it.
+ *
+ * A generation check is not an existence check. A ref from
+ * the current snapshot that names nothing on the page, because a model invented it or because the
+ * page moved on without a new snapshot being taken, passes `locateRef` and then simply waits. The
+ * action times out, and the caller gets a generic failure carrying Playwright's internal call log
+ * instead of the actionable answer: take a fresh snapshot.
+ *
+ * `count()` resolves immediately rather than waiting, so a ref that names nothing is refused in
+ * milliseconds instead of holding the action open for the full timeout.
+ */
+async function resolveRef(
+ session: BotSession,
+ target: Page,
+ ref: string,
+ expectedSnapshotId: number | undefined,
+) {
+ const locator = locateRef(session, target, ref, expectedSnapshotId);
+ if ((await locator.count()) === 0) {
+ throw new StaleSnapshotError(
+ `Nothing on this page has the ref ${ref}. Take a new snapshot and use the refs it returns.`,
+ );
+ }
+ return locator;
+}
+
+class StaleSnapshotError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "StaleSnapshotError";
+ }
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+/**
+ * One live viewer at a time per Bot, so a reconnect replaces rather than stacks, and two people
+ * watching two different Bots do not fight over one cast.
+ *
+ * A second cast on the same page would have Chrome encoding every frame twice and both sockets acking
+ * independently, which stalls both. One person drives; one cast.
+ */
+async function stopViewer(session: BotSession): Promise<void> {
+ const current = session.viewer;
+ session.viewer = undefined;
+ if (current?.follow) clearInterval(current.follow);
+ await current?.cast.stop();
+}
+
+/** How often the cast checks that it is still showing the page the Bot is on. */
+const FOLLOW_INTERVAL_MS = 1_000;
+
+/** What a live-screen socket carries: the Bot whose screen it is showing. */
+type StreamData = { botId: string };
+
+serve<StreamData>({
+ port: PORT,
+ idleTimeout: 120,
+ /**
+ * The live screen, pushed by Chrome rather than polled.
+ *
+ * Upgraded here rather than served as HTTP because the whole point is that frames arrive when the
+ * page changes and input goes back over the same connection. See screencast.ts for why polling was
+ * not good enough once a person had to type into this.
+ */
+ websocket: {
+ async open(ws) {
+ const session = sessionFor(ws.data.botId);
+ try {
+ await stopViewer(session);
+
+ const send = (frame: unknown) => {
+ // A closed socket starts a fresh cast on the next connection.
+ try {
+ ws.send(JSON.stringify(frame));
+ } catch {
+ void stopViewer(session);
+ }
+ };
+
+ /*
+ * The cast follows the Bot's current page. Re-checking also handles a page being closed
+ * underneath us without a listener per page.
+ */
+ let casting: Page | undefined;
+ const attach = async () => {
+ const target = await currentPage(ws.data.botId);
+ if (target === casting) return;
+ const previous = session.viewer;
+ const cast = await startScreencast(target, send);
+ casting = target;
+ session.viewer = { socket: ws, cast, follow: previous?.follow };
+ // The old cast stops after the replacement is running, so the screen does not go blank.
+ await previous?.cast.stop().catch(() => undefined);
+ };
+
+ await attach();
+ const follow = setInterval(() => {
+ void attach().catch(() => undefined);
+ }, FOLLOW_INTERVAL_MS);
+ if (session.viewer) session.viewer.follow = follow;
+ } catch (error) {
+ ws.send(
+ JSON.stringify({
+ type: "error",
+ error: describe(error, "The screen could not be started."),
+ }),
+ );
+ ws.close();
+ }
+ },
+
+ async message(ws, raw) {
+ const session = sessionFor(ws.data.botId);
+ if (!session.viewer) return;
+ let message: InputMessage;
+ try {
+ message = JSON.parse(String(raw)) as InputMessage;
+ } catch {
+ return;
+ }
+ // A person's input is accepted only while they hold the wheel. The socket being open is not permission:
+ // without this check, anything that could reach this port could drive the browser while a Bot
+ // was working, which is the one thing the control state exists to prevent.
+ //
+ // Refuse with an error so the surface can explain why input is ignored.
+ if (!session.control.humanMayDrive()) {
+ ws.send(JSON.stringify({ type: "error", error: TAKE_CONTROL_FIRST }));
+ return;
+ }
+ try {
+ await session.viewer.cast.send(message);
+ } catch (error) {
+ // Reported rather than swallowed. A dispatch that fails means the person's input did nothing,
+ // and they must not be left believing it landed.
+ console.error(
+ JSON.stringify({
+ type: "screencast-input-error",
+ message: message.type,
+ error: String(error),
+ }),
+ );
+ ws.send(
+ JSON.stringify({
+ type: "error",
+ error: describe(error, "That input could not be applied."),
+ }),
+ );
+ }
+ },
+
+ async close(ws) {
+ await stopViewer(sessionFor(ws.data.botId));
+ },
+ },
+ async fetch(request, server) {
+ const url = new URL(request.url);
+
+ /*
+ * Nothing below this line happens for an untrusted caller.
+ *
+ * `/health` is the single exception: it names no Bot, touches no browser and reports nothing but
+ * whether this process is up, and a container orchestrator has to be able to ask that without
+ * holding a secret.
+ *
+ * The websocket upgrade is checked here too. A browser cannot set headers on an upgrade, so the
+ * stream carries the token as a query
+ * parameter the same way it already carries the Bot.
+ */
+ if (
+ !isOpenPath(url.pathname) &&
+ !matchesToken(COMPUTER_TOKEN, offeredToken(request.headers, url))
+ ) {
+ // Says nothing about what is here. A refusal that describes the endpoint it is protecting is a
+ // directory listing for whoever is knocking.
+ return json({ error: "Not authorised." }, 401);
+ }
+
+ // Resolved once per request. Everything below that touches a browser, a takeover or a snapshot
+ // goes through this Bot's session, so there is no path where one Bot's call reaches another's.
+ const botId = botIdOf(request);
+ const session = sessionFor(botId);
+
+ if (url.pathname === "/stream") {
+ /*
+ * The socket carries the Bot in the query because it cannot do it in a header. Every other call here names
+ * its Bot in `x-openbot-bot-id`, but a websocket client sends no custom headers on the upgrade,
+ * so the stream, and only the stream, also accepts the Bot as a query parameter. The header
+ * still wins where there is one.
+ */
+ const streamBotId = botIdOf(request, url.searchParams.get("bot"));
+ if (server.upgrade(request, { data: { botId: streamBotId } }))
+ return undefined as unknown as Response;
+ return json({ error: "Expected a WebSocket upgrade." }, 400);
+ }
+
+ /*
+ * `/live` stays absent. A page served by this process can only be opened by putting the secret in
+ * a URL, where it lands in history and logs. The React app is the guarded way to watch a Bot.
+ */
+
+ // Who has the wheel. Polled by the surface alongside the screen, so the person sees the Bot ask
+ // for help without having to reload anything.
+ if (url.pathname === "/control" && request.method === "GET") {
+ return json(session.control.get());
+ }
+
+ // The Bot asking for help. It does not take control: it says it is stuck and why, and a person
+ // decides. A Bot that could hand itself to a human could also hand a human a page they never
+ // asked to see.
+ if (url.pathname === "/control/request" && request.method === "POST") {
+ const body = (await request.json().catch(() => null)) as {
+ reason?: unknown;
+ } | null;
+ return json(session.control.requestHelp(body?.reason));
+ }
+
+ // The Bot asking for one value it must not be told. It has already focused the field.
+ if (url.pathname === "/control/secret" && request.method === "POST") {
+ const body = (await request.json().catch(() => null)) as {
+ label?: unknown;
+ ref?: unknown;
+ snapshotId?: unknown;
+ } | null;
+ try {
+ return json(session.control.requestSecret(body ?? {}));
+ } catch (error) {
+ if (error instanceof ControlRequestError) {
+ return json({ error: error.message }, 400);
+ }
+ throw error;
+ }
+ }
+
+ /**
+ * A person supplying that value.
+ *
+ * Scoped by the pending request rather than by a control handover: it is usable only while the Bot
+ * has actually asked for a secret, and the request is cleared the moment it is answered, so this
+ * cannot be used as a general back door to type into the page.
+ *
+ * The value is typed and forgotten. Not stored on `control`, not returned in the response, not
+ * logged. The response says how many characters arrived, which is enough for the surface to
+ * confirm something was sent and useless to anybody reading it later.
+ *
+ * It types and does not submit. Committing a form is a separate action through the gateway and
+ * audit trail; secret entry only places the value in the named field.
+ */
+ if (url.pathname === "/human/secret" && request.method === "POST") {
+ const pending = session.control.pendingSecret();
+ if (!pending) {
+ return json({ error: NO_SECRET_PENDING }, 409);
+ }
+ const body = (await request.json().catch(() => null)) as {
+ text?: unknown;
+ } | null;
+ if (typeof body?.text !== "string" || !body.text) {
+ return json({ error: "A value is required." }, 400);
+ }
+ try {
+ const target = await currentPage(botId);
+ // Focus the field the Bot named, and let this throw if it cannot be found. A secret must not
+ // be reported as delivered unless a field receives it.
+ //
+ // No generation check here: a Bot may take another snapshot after asking for a secret, while
+ // the ref remains protected by Playwright's `aria-ref` rules.
+ //
+ // `aria-ref` resolves a ref only against the most recent snapshot, only while the element is
+ // still connected, and mints a
+ // new ref when an element's role or accessible name changes, so a recycled node cannot
+ // inherit an old one. If the ref resolves, it is the field the Bot meant. If it does not,
+ // nothing is typed, which is the outcome the generation check existed to guarantee.
+ const field = locateRef(session, target, pending.ref, undefined);
+ await field.click({ timeout: ACTION_TIMEOUT_MS });
+ await field.fill(body.text, { timeout: ACTION_TIMEOUT_MS });
+ const characters = body.text.length;
+ // Cleared only after it actually landed, so a failure leaves the request open and the person
+ // can try again rather than being told to start over.
+ session.control.secretSupplied();
+ return json({ supplied: true, characters, url: target.url() });
+ } catch (error) {
+ if (error instanceof StaleSnapshotError) {
+ return json({ error: error.message, stale: true }, 409);
+ }
+ // The field is gone, which is unretryable, so the request is closed rather than left open.
+ // Keeping it open is right for a mistyped value and wrong here: the person would retype their
+ // password into the same dead ref for ever. Clearing it also unblocks the Bot, which can see
+ // on its next turn that nothing is pending and ask again against a fresh snapshot.
+ session.control.secretSupplied();
+ return json(
+ {
+ error: describe(
+ error,
+ "That value could not be entered: the field is no longer on the page. Ask the assistant to request it again.",
+ ),
+ },
+ 502,
+ );
+ }
+ }
+
+ if (url.pathname === "/control/take" && request.method === "POST") {
+ return json(session.control.take());
+ }
+
+ if (url.pathname === "/control/release" && request.method === "POST") {
+ // `reason` is dropped on release: it described the thing the person was asked to do, and once
+ // they have done it, leaving it set would have the surface still showing the old request.
+ return json(session.control.release());
+ }
+
+ // A person's input, by pixel. The Bot addresses elements by reference because it reads a list; a
+ // person addresses them by pointing, because they are looking at a picture. Different problem,
+ // different endpoint, and only usable while they hold the wheel.
+ if (HUMAN_INPUT.has(url.pathname) && request.method === "POST") {
+ if (!session.control.humanMayDrive()) {
+ return json({ error: TAKE_CONTROL_FIRST }, 409);
+ }
+ const body = (await request.json().catch(() => null)) as Record<
+ string,
+ unknown
+ > | null;
+ try {
+ const target = await currentPage(botId);
+ return json(await performHumanInput(target, url.pathname, body ?? {}));
+ } catch (error) {
+ return json({ error: describe(error, "That did not work.") }, 502);
+ }
+ }
+
+ if (url.pathname === "/health") {
+ const [profile] = profiles.summary([botId]);
+ return json({
+ status: "ok",
+ // `browser` kept as it was: it is in the published contract and start.sh reads it.
+ browser: profile?.running ?? false,
+ profile,
+ // Which Bot this computer can prove it is, when the deployment runs SPIRE. Null is a
+ // deployment without it, not a failure, and it is reported rather than omitted so the
+ // difference between "no identity here" and "identity broken" is visible.
+ identity: await identity(),
+ });
+ }
+
+ /**
+ * The computers this process holds. The shape is a list because the admin surface is a
+ * list, and because a Bot that has a profile has a computer whether or not a browser is running
+ * for it this second.
+ */
+ if (url.pathname === "/computers" && request.method === "GET") {
+ return json({ computers: profiles.summary(await profiles.known()) });
+ }
+
+ /**
+ * Stop the browser, keep what it knows.
+ *
+ * Closed gracefully so Chromium flushes its profile, and deliberately
+ * not restarted here: the next request starts it again, which is the same path as a first ever
+ * start, so there is no second way for a browser to come into existence.
+ */
+ if (url.pathname === "/computers/stop" && request.method === "POST") {
+ const wasRunning = await profiles.stop(botId);
+ // The wheel goes back to the Bot because the controlled browser no longer exists.
+ session.control.release();
+ return json({ stopped: true, wasRunning });
+ }
+
+ /**
+ * Forget everything and start over.
+ *
+ * Signs the computer out of everything by deleting the profile. Irreversible, which is why it is
+ * its own endpoint rather than a flag on the one above: a person clicking "stop" must not be able
+ * to discard a login by mistyping a parameter.
+ */
+ if (url.pathname === "/computers/reset" && request.method === "POST") {
+ await profiles.reset(botId);
+ // Reset releases control because any previous browser session and pending secret request are gone.
+ session.control.release();
+ return json({ reset: true, botId });
+ }
+
+ if (url.pathname === "/navigate" && request.method === "POST") {
+ const body = (await request.json().catch(() => null)) as {
+ url?: unknown;
+ } | null;
+ if (typeof body?.url !== "string") {
+ return json({ error: "A url is required." }, 400);
+ }
+
+ const startedAt = Date.now();
+ try {
+ session.control.assertBotMayAct();
+ const target = await currentPage(botId);
+ await target.goto(body.url, {
+ waitUntil: "domcontentloaded",
+ timeout: NAVIGATION_TIMEOUT_MS,
+ });
+ // A new document wipes every stamp, so every ref handed out before now is meaningless.
+ // Bumping the generation makes an action carrying one fail with "take a new snapshot" rather
+ // than fall through to a selector that matches nothing and read as a missing element.
+ session.snapshotId += 1;
+ const extract = await readablePageText(target);
+ return json({
+ url: target.url(),
+ title: await target.title(),
+ text: extract.text,
+ truncated: extract.truncated,
+ elapsedMs: Date.now() - startedAt,
+ });
+ } catch (error) {
+ // A person holding the wheel is not a failed navigation; the Bot should wait.
+ if (error instanceof ControlError) {
+ return json({ error: error.message, humanHasControl: true }, 409);
+ }
+ // The page is the Bot's working surface, so a failed navigation is reported rather than
+ // thrown: the transcript needs to say what happened, and the browser stays usable.
+ return json(
+ {
+ error:
+ error instanceof Error ? error.message : "Navigation failed.",
+ },
+ 502,
+ );
+ }
+ }
+
+ if (url.pathname === "/screenshot" && request.method === "GET") {
+ try {
+ const target = await currentPage(botId);
+ const buffer = await target.screenshot({ type: "png" });
+ const size = target.viewportSize() ?? { width: 1280, height: 800 };
+ return json({
+ base64: buffer.toString("base64"),
+ width: size.width,
+ height: size.height,
+ capturedAt: new Date().toISOString(),
+ // Which page this is a picture of. A browser that has not been sent anywhere sits on
+ // `about:blank`, and a screenshot of that is a valid, entirely white PNG, indistinguishable
+ // from a real page to anything looking only at the bytes. The transcript needs to tell
+ // those apart to avoid presenting a blank browser as though it were a loaded page.
+ url: target.url(),
+ });
+ } catch (error) {
+ return json(
+ {
+ error:
+ error instanceof Error ? error.message : "Screenshot failed.",
+ },
+ 502,
+ );
+ }
+ }
+
+ // The Bot's files. Confined to the workspace by workspace.ts. Nothing here decides whether a Bot
+ // MAY touch a path: the gateway in front of this process does that.
+ if (url.pathname === "/files/read" && request.method === "POST") {
+ const body = (await request.json().catch(() => null)) as {
+ path?: unknown;
+ } | null;
+ try {
+ return json(await workspace.read(String(body?.path ?? "")));
+ } catch (error) {
+ return json(
+ { error: describe(error, "The file could not be read.") },
+ fileStatus(error),
+ );
+ }
+ }
+
+ if (url.pathname === "/files/list" && request.method === "POST") {
+ const body = (await request.json().catch(() => null)) as {
+ path?: unknown;
+ } | null;
+ try {
+ return json(
+ await workspace.list(
+ typeof body?.path === "string" ? body.path : undefined,
+ ),
+ );
+ } catch (error) {
+ return json(
+ { error: describe(error, "The folder could not be listed.") },
+ fileStatus(error),
+ );
+ }
+ }
+
+ if (url.pathname === "/files/write" && request.method === "POST") {
+ const body = (await request.json().catch(() => null)) as {
+ path?: unknown;
+ contents?: unknown;
+ append?: unknown;
+ } | null;
+ if (typeof body?.contents !== "string") {
+ return json({ error: "The contents to write are required." }, 400);
+ }
+ try {
+ return json(
+ await workspace.write(String(body?.path ?? ""), body.contents, {
+ append: body.append === true,
+ }),
+ );
+ } catch (error) {
+ return json(
+ { error: describe(error, "The file could not be written.") },
+ fileStatus(error),
+ );
+ }
+ }
+
+ // The current page as text, without navigating anywhere.
+ //
+ // Reading must be available after actions too. Returning page text only from `/navigate` would be enough if
+ // opening a page were the only way to change what is on screen. It is not: the Bot presses
+ // "Submit order", the page becomes a confirmation, and it has no way to find out what the
+ // confirmation said. "I clicked the button" is not an answer to what happened.
+ if (url.pathname === "/read" && request.method === "GET") {
+ try {
+ const target = await currentPage(botId);
+ const extract = await readablePageText(target);
+ return json({
+ url: target.url(),
+ title: await target.title(),
+ text: extract.text,
+ truncated: extract.truncated,
+ });
+ } catch (error) {
+ return json(
+ { error: describe(error, "Reading the page failed.") },
+ 502,
+ );
+ }
+ }
+
+ // The list of things on the page a Bot can act on. POST rather than GET because it mutates the
+ // page, stamping every element it describes, and a GET that changes the document is a lie that
+ // caches and prefetchers eventually punish.
+ if (url.pathname === "/snapshot" && request.method === "POST") {
+ try {
+ return json(await snapshotPage(session, await currentPage(botId)));
+ } catch (error) {
+ return json({ error: describe(error, "Snapshot failed.") }, 502);
+ }
+ }
+
+ if (ACTIONS.has(url.pathname) && request.method === "POST") {
+ const body = (await request
+ .json()
+ .catch(() => null)) as ActionBody | null;
+ if (!body) {
+ return json({ error: "An action needs a JSON body." }, 400);
+ }
+
+ const startedAt = Date.now();
+ try {
+ session.control.assertBotMayAct();
+ const target = await currentPage(botId);
+ const detail = await performAction(
+ session,
+ target,
+ url.pathname,
+ body,
+ // The caller going away is the stop signal: the surface aborts its request, the server
+ // aborts the one it made to this computer, and Bun aborts this one in turn.
+ request.signal,
+ );
+ return json({ ...detail, elapsedMs: Date.now() - startedAt });
+ } catch (error) {
+ /*
+ * Stopped, not failed. The signal is checked rather than the error text: Playwright words an
+ * abort differently per call, and the caller's own request going away is the fact that
+ * matters either way.
+ *
+ * Logged because the response is not observed after the caller aborts. The log distinguishes
+ * "stopped in time" from "ran to completion after cancellation".
+ */
+ if (request.signal.aborted) {
+ console.info(
+ JSON.stringify({
+ type: "action-stopped",
+ action: url.pathname,
+ ref: typeof body.ref === "string" ? body.ref : undefined,
+ elapsedMs: Date.now() - startedAt,
+ }),
+ );
+ // 499, the convention for a client that closed the request: this is not the computer
+ // failing, and a 502 here would be counted as one.
+ return json({ error: "Stopped.", stopped: true }, 499);
+ }
+ // A stale ref is the caller's mistake and is fixable by taking a new snapshot, so it is a 409
+ // rather than a 502: the computer is fine and retrying the same call unchanged will not help.
+ if (error instanceof StaleSnapshotError) {
+ return json({ error: error.message, stale: true }, 409);
+ }
+ // 409 as well, and for the same reason: nothing is broken, the caller simply has to wait.
+ if (error instanceof ControlError) {
+ return json({ error: error.message, humanHasControl: true }, 409);
+ }
+ return json({ error: describe(error, "The action failed.") }, 502);
+ }
+ }
+
+ return json({ error: "Not found." }, 404);
+ },
+});
+
+type ActionBody = {
+ ref?: unknown;
+ snapshotId?: unknown;
+ text?: unknown;
+ key?: unknown;
+ deltaY?: unknown;
+ submit?: unknown;
+};
+
+const ACTIONS = new Set(["/click", "/type", "/key", "/scroll"]);
+
+const HUMAN_INPUT = new Set([
+ "/human/click",
+ "/human/type",
+ "/human/key",
+ "/human/scroll",
+]);
+
+/**
+ * Carry out one thing a person did with their mouse or keyboard.
+ *
+ * Coordinates are viewport pixels, which the surface works out from the screenshot it is displaying:
+ * it knows the image's natural size and the size it drew it at, so it can scale a click back. Doing
+ * that conversion in the browser rather than here keeps this endpoint bound to page coordinates
+ * rather than window coordinates.
+ *
+ * Nothing a person types here reaches the model. It goes from their keyboard to this browser and
+ * stops. That is what makes a password or a one-time code safe to enter during a takeover: not a
+ * filter that strips it out afterwards, but a path the model is not on. The same reason the value is
+ * never returned and never logged below.
+ */
+async function performHumanInput(
+ target: Page,
+ action: string,
+ body: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const at = (): { x: number; y: number } => {
+ const x = typeof body.x === "number" ? body.x : Number.NaN;
+ const y = typeof body.y === "number" ? body.y : Number.NaN;
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
+ throw new Error("A click needs an x and a y inside the page.");
+ }
+ // Clamped rather than rejected. A click a pixel outside the viewport is a rounding artefact of
+ // scaling the screenshot, not a mistake worth refusing.
+ return {
+ x: Math.min(Math.max(x, 0), VIEWPORT.width - 1),
+ y: Math.min(Math.max(y, 0), VIEWPORT.height - 1),
+ };
+ };
+
+ if (action === "/human/click") {
+ const { x, y } = at();
+ await target.mouse.click(x, y);
+ return { action: "human_click", url: target.url() };
+ }
+
+ if (action === "/human/type") {
+ if (typeof body.text !== "string") {
+ throw new Error("Typing needs text.");
+ }
+ // `insertText` rather than per-key typing: a person pasting a one-time code should not have it
+ // arrive one character at a time into a field that reformats as you go.
+ await target.keyboard.insertText(body.text);
+ // Length only, never the value. See the note above about the model not being on this path.
+ return {
+ action: "human_type",
+ characters: body.text.length,
+ url: target.url(),
+ };
+ }
+
+ if (action === "/human/key") {
+ if (typeof body.key !== "string" || !body.key) {
+ throw new Error("A key press needs a key name.");
+ }
+ await target.keyboard.press(body.key);
+ return { action: "human_key", key: body.key, url: target.url() };
+ }
+
+ const deltaY = typeof body.deltaY === "number" ? body.deltaY : 400;
+ await target.mouse.wheel(0, deltaY);
+ return { action: "human_scroll", deltaY, url: target.url() };
+}
+
+/**
+ * Carry out one action on the page.
+ *
+ * Every action that addresses an element goes through {@link locateRef}, so the staleness check
+ * cannot be forgotten at a call site. `/key` and `/scroll` may omit a ref and act on the page itself,
+ * which is how a Bot presses Enter to submit or scrolls to bring more of a long form into view.
+ *
+ * Stop has to reach the browser. `signal` is the caller's request going away, the person pressed
+ * Stop, and the abort travels from the surface, through the server, to here. Without passing it on,
+ * pressing Stop ended the run in the transcript while the click it was meant to prevent carried on
+ * landing on a live page. Stop must reach the browser before a high-impact click lands.
+ */
+async function performAction(
+ session: BotSession,
+ target: Page,
+ action: string,
+ body: ActionBody,
+ signal?: AbortSignal,
+): Promise<Record<string, unknown>> {
+ // Passed to every Playwright call below. It does not disable the timeout, which still applies.
+ const acting = { timeout: ACTION_TIMEOUT_MS, ...(signal ? { signal } : {}) };
+ const expected =
+ typeof body.snapshotId === "number" ? body.snapshotId : undefined;
+ const ref = typeof body.ref === "string" && body.ref ? body.ref : undefined;
+
+ if (action === "/click") {
+ if (!ref) throw new Error("A click needs the ref of an element to click.");
+ await (await resolveRef(session, target, ref, expected)).click(acting);
+ return { action: "click", ref, url: target.url() };
+ }
+
+ if (action === "/type") {
+ if (!ref) throw new Error("Typing needs the ref of a field to type into.");
+ if (typeof body.text !== "string") {
+ throw new Error("Typing needs the text to enter.");
+ }
+ const field = await resolveRef(session, target, ref, expected);
+ // `fill` rather than keystrokes: it clears the field first, which is what "put this value in
+ // this box" means. Typing into a field a previous attempt half-filled otherwise appends, and the
+ // form ends up with "AlicAlice" in it.
+ await field.fill(body.text, acting);
+ if (body.submit === true) {
+ await field.press("Enter", acting);
+ }
+ // The text itself is deliberately NOT returned. It is echoed nowhere: this response is read by
+ // the model and logged by the server, and a value typed into a form is exactly where a password
+ // or a card number lives. The caller already knows what it sent.
+ return {
+ action: "type",
+ ref,
+ characters: body.text.length,
+ submitted: body.submit === true,
+ url: target.url(),
+ };
+ }
+
+ if (action === "/key") {
+ if (typeof body.key !== "string" || !body.key) {
+ throw new Error("A key press needs a key name, such as Enter or Tab.");
+ }
+ if (ref) {
+ await (await resolveRef(session, target, ref, expected)).press(
+ body.key,
+ acting,
+ );
+ } else {
+ await target.keyboard.press(body.key);
+ }
+ return { action: "key", key: body.key, ref, url: target.url() };
+ }
+
+ // Scroll. A plain wheel event on the page, which is what moves a long form, rather than scrolling a
+ // specific element into view: the Bot asked to see further down, not to hunt for one control.
+ const deltaY = typeof body.deltaY === "number" ? body.deltaY : 600;
+ await target.mouse.wheel(0, deltaY);
+ return { action: "scroll", deltaY, url: target.url() };
+}
+
+function describe(error: unknown, fallback: string): string {
+ return error instanceof Error ? error.message : fallback;
+}
+
+/**
+ * Which status a file failure deserves.
+ *
+ * A path outside the workspace is the caller asking for something it may never have, so 403: retrying
+ * it unchanged will never work, and it is not a fault. A missing file or an oversized write is a 400,
+ * because a different request would succeed. Collapsing both into 500 would tell the Bot the computer
+ * is broken and invite it to try the same thing again.
+ */
+function fileStatus(error: unknown): 400 | 403 | 500 {
+ if (error instanceof WorkspacePathError) return 403;
+ if (error instanceof WorkspaceFileError) return 400;
+ return 500;
+}
+
+console.info(`agent-computer listening on http://localhost:${PORT}`);
+
+/**
+ * Hand the profile back before dying.
+ *
+ * `docker stop` and a Kubernetes eviction both send SIGTERM and then wait, so this is the window in
+ * which Chromium can flush its profile to the volume. This is the graceful-shutdown path for normal
+ * container restarts.
+ *
+ * `stop_grace_period` in docker-compose.yml is what gives this time to run.
+ */
+for (const signal of ["SIGTERM", "SIGINT"] as const) {
+ process.on(signal, () => {
+ void (async () => {
+ console.info(`${signal}: closing the browser so its profile is flushed`);
+ await profiles.closeAll();
+ process.exit(0);
+ })();
+ });
+}
diff --git a/agent-computer/src/profiles.ts b/agent-computer/src/profiles.ts
new file mode 100644
index 00000000..de45097d
--- /dev/null
+++ b/agent-computer/src/profiles.ts
@@ -0,0 +1,261 @@
+/**
+ * The Bot's browser, and the profile that outlives it.
+ *
+ * A persistent profile lets a Bot remain signed in across process and container restarts.
+ *
+ * Persistent context, not a saved storage state. Playwright can export cookies and localStorage as
+ * JSON and replay them, and that is the wrong tool here: it captures what the automation knew about,
+ * on demand, and misses IndexedDB, service workers, and anything written after the snapshot.
+ * `launchPersistentContext` points Chromium at a real user-data directory, so the browser persists
+ * its own state the way it does on a desktop. On a mounted volume, that directory outlives the
+ * container.
+ *
+ * Profile behavior in this image and Playwright version:
+ * - A cookie with an expiry survives close-and-reopen. So does localStorage.
+ * - A session cookie (no expiry) does not, and should not: Chromium drops those on restart, exactly
+ * as a desktop browser does. Any "stay signed in" worth the name sets an expiring cookie, but this
+ * is why a site that only ever issues session cookies will still ask a Bot to sign in again.
+ * - Killing the browser process with SIGKILL leaves no stale singleton lock in the profile, and the
+ * profile reopens with its cookies intact. The widely-reported `SingletonLock` breakage does not
+ * reproduce here. The defensive sweep below stays anyway, because it is three lines and the
+ * failure it prevents is "the computer never comes back".
+ *
+ * One profile per Bot. Two Bots sharing a profile share their logins, which makes "this Bot may reach
+ * Salesforce" unenforceable: whatever one signs into, the other is signed into. Each Bot gets its own
+ * directory, so its cookies and its storage are its own.
+ *
+ * A profile is not a container. Two Bots in this process are isolated from each other's cookies, not
+ * from each other's kernel, filesystem or memory.
+ *
+ * Container-per-Bot needs something privileged to create containers, and the API server must never be
+ * that: access to the Docker socket is unrestricted root on the host. Stop and reset are
+ * operations this process applies to its own browser, so the same design works under Compose,
+ * Kubernetes or ECS, where the orchestrator's own restart policy brings a process back.
+ */
+import { readdir, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { type BrowserContext, chromium, type Page } from "playwright";
+import { egressFor, egressLabel } from "./egress";
+
+/** The viewport, which is what a person's click coordinates are relative to. */
+export const VIEWPORT = { width: 1280, height: 800 };
+
+/**
+ * Files Chromium uses to refuse a second instance on one profile.
+ *
+ * Swept on the way in rather than the way out, because the way out is the case that does not happen:
+ * a container that is killed does not get to run cleanup. If this process is starting, no browser of
+ * ours is running, so any lock here is by definition from a life that has already ended.
+ */
+const SINGLETON_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
+
+/**
+ * How the browser is started, and why each flag is here.
+ *
+ * `--password-store=basic` makes a durable profile work in a container. Chromium normally encrypts
+ * cookie values with a desktop keyring; containers have no stable gnome-keyring or kwallet, so the
+ * default fallback can make stored cookies unreadable after restart.
+ *
+ * `basic` pins it to Chromium's own fixed fallback, which is deterministic and survives restarts.
+ * This is obfuscation at rest, not protection. Anything that can read the volume can read the
+ * cookies. The volume's own permissions are the security boundary.
+ */
+const LAUNCH_ARGS = [
+ "--no-sandbox",
+ "--disable-dev-shm-usage",
+ "--password-store=basic",
+];
+
+/**
+ * How long to let a closing browser finish writing before moving on.
+ *
+ * The profile's Cookies file may be rewritten shortly after `close()` is called. This delay stays
+ * clear of that window while remaining inside the container's
+ * 30s stop grace period, so a shutdown never becomes the reason a computer does not come back.
+ */
+const CLOSE_SETTLE_MS = 2_000;
+
+/** What a Bot's browser looks like from outside. */
+export type BotBrowser = {
+ botId: string;
+ context: BrowserContext;
+ page: Page;
+};
+
+export type ProfileSummary = {
+ botId: string;
+ /** Whether a browser is running for this Bot right now. */
+ running: boolean;
+ /** When this Bot's browser was last started, or null if it is not running. */
+ startedAt: string | null;
+ /** The proxy its traffic leaves through, by host only. Never the credentials. */
+ egress: string | null;
+};
+
+/**
+ * Close a context and wait for Chromium to finish writing.
+ *
+ * Chromium batches cookie writes and commits them as it exits, while `close()` only asks it to exit.
+ * Bounded, because a shutdown that hangs must never be the reason a computer does not come back. We
+ * would rather lose the last few seconds of cookies than never restart.
+ */
+async function closeAndWait(context: BrowserContext): Promise<void> {
+ await context.close().catch(() => undefined);
+ // A fixed settle is used because persistent contexts do not expose a reliable browser-exit signal.
+ await new Promise((resolve) => setTimeout(resolve, CLOSE_SETTLE_MS));
+}
+
+export function createProfiles(root: string) {
+ /** One running browser per Bot. */
+ const live = new Map<
+ string,
+ { context: BrowserContext; page: Page; startedAt: string }
+ >();
+ /** Launches in flight, so a cold computer is started once however many callers ask at once. */
+ const starting = new Map<string, Promise<Page>>();
+
+ const directoryFor = (botId: string): string => join(root, botId);
+
+ const sweepLocks = async (dir: string): Promise<void> => {
+ await Promise.all(
+ SINGLETON_FILES.map((name) =>
+ rm(join(dir, name), { force: true }).catch(() => undefined),
+ ),
+ );
+ };
+
+ return {
+ /**
+ * The Bot's page, starting its browser if it is not running.
+ *
+ * Started on first use rather than at boot, and re-created if it died: a crashed Chromium would
+ * otherwise leave this process alive and answering the same error for every request until the
+ * container restarts. This turns that into one slow request instead of an outage.
+ */
+ async page(botId: string): Promise<Page> {
+ /*
+ * One launch at a time per Bot. Calls that arrive during a launch wait for that launch instead
+ * of starting another browser against the same profile directory.
+ */
+ const launching = starting.get(botId);
+ if (launching) return launching;
+
+ const existing = live.get(botId);
+ if (
+ existing?.context.browser()?.isConnected() &&
+ !existing.page.isClosed()
+ ) {
+ return existing.page;
+ }
+ if (existing) {
+ // Half-dead: the browser went away, or its page did. Dropped rather than repaired, because a
+ // context whose browser has gone is not usable for anything.
+ await existing.context.close().catch(() => undefined);
+ live.delete(botId);
+ }
+
+ const launch = (async () => {
+ const dir = directoryFor(botId);
+ await sweepLocks(dir);
+ const proxy = egressFor(botId, process.env);
+ const context = await chromium.launchPersistentContext(dir, {
+ args: LAUNCH_ARGS,
+ viewport: VIEWPORT,
+ // This process owns shutdown. Playwright's signal handlers kill Chromium immediately on
+ // SIGTERM, before pending cookie writes have time to flush.
+ handleSIGTERM: false,
+ handleSIGINT: false,
+ handleSIGHUP: false,
+ ...(proxy ? { proxy } : {}),
+ });
+ // Persistent contexts open with a page already; reuse it rather than leaving an extra blank tab.
+ const page = context.pages()[0] ?? (await context.newPage());
+ live.set(botId, { context, page, startedAt: new Date().toISOString() });
+ return page;
+ })();
+
+ starting.set(botId, launch);
+ try {
+ return await launch;
+ } finally {
+ // Cleared whether it worked or not so a failed launch does not pin future calls to a rejected
+ // promise.
+ starting.delete(botId);
+ }
+ },
+
+ /**
+ * Close this Bot's browser without touching what it knows.
+ *
+ * Gracefully, so Chromium flushes its profile. This is what "kill" means for a Bot's computer: the
+ * browser stops, the login survives, and the next request starts it again where it left off.
+ */
+ async stop(botId: string): Promise<boolean> {
+ const existing = live.get(botId);
+ if (!existing) return false;
+ live.delete(botId);
+ await closeAndWait(existing.context);
+ return true;
+ },
+
+ /**
+ * Forget everything this Bot knows and start over.
+ *
+ * The browser is closed before the directory is deleted: deleting a profile
+ * out from under a running Chromium is how you get a browser that is alive, writing to files that
+ * no longer exist, and reporting success. Nothing is recreated here, the next request starts a
+ * clean browser, which is the same path as a first ever start and so needs no second code path.
+ */
+ async reset(botId: string): Promise<void> {
+ await this.stop(botId);
+ await rm(directoryFor(botId), { recursive: true, force: true });
+ },
+
+ /**
+ * Every Bot that has a computer, whether or not one is running.
+ *
+ * Read from disk rather than from memory, because a Bot's computer exists as long as its profile
+ * does: after a restart nothing is running and every login is still there, and an admin page that
+ * listed only live browsers would show an empty screen and imply the logins were gone.
+ */
+ async known(): Promise<string[]> {
+ const onDisk = await readdir(root, { withFileTypes: true }).catch(
+ () => [],
+ );
+ return [
+ ...new Set([
+ ...onDisk.filter((e) => e.isDirectory()).map((e) => e.name),
+ ...live.keys(),
+ ]),
+ ].sort();
+ },
+
+ /** What the admin surface lists. Running or not, because a Bot that has a profile has a computer. */
+ summary(botIds: string[]): ProfileSummary[] {
+ const known = new Set([...botIds, ...live.keys()]);
+ return [...known].sort().map((botId) => {
+ const running = live.get(botId);
+ return {
+ botId,
+ running: Boolean(running),
+ startedAt: running?.startedAt ?? null,
+ egress: egressLabel(botId, process.env),
+ };
+ });
+ },
+
+ /**
+ * Close every browser, for shutdown.
+ *
+ * `docker stop` and a Kubernetes eviction both send SIGTERM and then wait. Closing the contexts
+ * here gives Chromium the chance to flush its profile within that grace period.
+ */
+ async closeAll(): Promise<void> {
+ const contexts = [...live.values()];
+ live.clear();
+ await Promise.all(contexts.map((c) => closeAndWait(c.context)));
+ },
+ };
+}
+
+export type Profiles = ReturnType<typeof createProfiles>;
diff --git a/agent-computer/src/screencast.ts b/agent-computer/src/screencast.ts
new file mode 100644
index 00000000..9bc27c11
--- /dev/null
+++ b/agent-computer/src/screencast.ts
@@ -0,0 +1,214 @@
+/**
+ * Live screen and live input over one WebSocket, using Chrome's own screencast.
+ *
+ * Chrome pushes frames as the page changes, which supports human takeover better than polling a PNG
+ * once a second.
+ *
+ * This follows permissively-licensed references: `steel-dev/steel-browser`'s `casting.handler.ts`
+ * (Apache-2.0) for the server loop and Chrome DevTools' `InputModel.ts` (BSD-3) for key event
+ * translation.
+ *
+ * noVNC is not used because it requires Xvfb, x11vnc and websockify, while this container runs
+ * headless. This implementation streams the page and forwards input through the Chrome DevTools
+ * Protocol.
+ */
+import type { CDPSession, Page } from "playwright";
+
+/** What the surface sends us. */
+export type InputMessage =
+ | {
+ type: "mouse";
+ event: "pressed" | "released" | "moved";
+ x: number;
+ y: number;
+ button?: "left" | "right" | "middle";
+ clickCount?: number;
+ modifiers?: number;
+ }
+ | {
+ type: "wheel";
+ x: number;
+ y: number;
+ deltaX: number;
+ deltaY: number;
+ modifiers?: number;
+ }
+ | {
+ type: "key";
+ event: "down" | "up";
+ key: string;
+ code: string;
+ text?: string;
+ modifiers?: number;
+ }
+ | { type: "text"; text: string };
+
+/** What we send back. */
+export type FrameMessage = {
+ type: "frame";
+ /** Base64 JPEG. Chrome's own encoding; we do not re-encode. */
+ data: string;
+ width: number;
+ height: number;
+};
+
+/**
+ * Chrome's virtual key codes, for the keys that need one.
+ *
+ * `Input.dispatchKeyEvent` is not satisfied by `key` alone. A form field will ignore a bare Backspace
+ * or Enter unless `windowsVirtualKeyCode` is set, which is the common reason a hand-written
+ * screencast works for letters but not editing keys. Lifted from the mapping DevTools uses for the
+ * same purpose.
+ */
+const VIRTUAL_KEY_CODES: Record<string, number> = {
+ Backspace: 8,
+ Tab: 9,
+ Enter: 13,
+ Shift: 16,
+ Control: 17,
+ Alt: 18,
+ Escape: 27,
+ " ": 32,
+ PageUp: 33,
+ PageDown: 34,
+ End: 35,
+ Home: 36,
+ ArrowLeft: 37,
+ ArrowUp: 38,
+ ArrowRight: 39,
+ ArrowDown: 40,
+ Delete: 46,
+};
+
+function virtualKeyCode(key: string): number {
+ if (VIRTUAL_KEY_CODES[key] !== undefined) return VIRTUAL_KEY_CODES[key];
+ // A single printable character carries its own code point, upper-cased, which is what Chrome expects
+ // for a key event as opposed to the text it produces.
+ if (key.length === 1) return key.toUpperCase().charCodeAt(0);
+ return 0;
+}
+
+export type Screencast = {
+ /** Stop the cast and detach. Safe to call twice. */
+ stop: () => Promise<void>;
+ /** Apply one thing the person did. */
+ send: (message: InputMessage) => Promise<void>;
+};
+
+/**
+ * Start casting `page` to `onFrame`, and return a handle that accepts input.
+ *
+ * `maxWidth`/`maxHeight` cap what Chrome encodes; it scales to fit and tells us the real dimensions in
+ * the metadata, which the surface needs in order to map a click back. Capping matters because the cost
+ * of a frame is mostly encoding, and oversized casts waste bandwidth.
+ */
+export async function startScreencast(
+ page: Page,
+ onFrame: (frame: FrameMessage) => void,
+ options: { maxWidth?: number; maxHeight?: number; quality?: number } = {},
+): Promise<Screencast> {
+ const client: CDPSession = await page.context().newCDPSession(page);
+ let stopped = false;
+
+ type ScreencastFrame = {
+ data: string;
+ sessionId: number;
+ metadata: { deviceWidth: number; deviceHeight: number };
+ };
+
+ client.on("Page.screencastFrame", (event: ScreencastFrame) => {
+ const { data, sessionId, metadata } = event;
+ // Acknowledge every frame. Chrome will not send the next one until the current is acked, which is
+ // the backpressure that stops a slow client drowning in frames. Forgetting this is why a naive
+ // implementation delivers one frame and then appears to hang.
+ void client
+ .send("Page.screencastFrameAck", { sessionId })
+ .catch(() => undefined);
+ if (stopped) return;
+ onFrame({
+ type: "frame",
+ data,
+ width: metadata.deviceWidth,
+ height: metadata.deviceHeight,
+ });
+ });
+
+ await client.send("Page.startScreencast", {
+ format: "jpeg",
+ quality: options.quality ?? 70,
+ maxWidth: options.maxWidth ?? 1280,
+ maxHeight: options.maxHeight ?? 800,
+ // One frame per change, not per interval. Chrome decides when something moved.
+ everyNthFrame: 1,
+ });
+
+ return {
+ async stop() {
+ if (stopped) return;
+ stopped = true;
+ await client.send("Page.stopScreencast").catch(() => undefined);
+ await client.detach().catch(() => undefined);
+ },
+
+ async send(message: InputMessage) {
+ if (stopped) return;
+ if (message.type === "mouse") {
+ await client.send("Input.dispatchMouseEvent", {
+ type:
+ message.event === "pressed"
+ ? "mousePressed"
+ : message.event === "released"
+ ? "mouseReleased"
+ : "mouseMoved",
+ x: message.x,
+ y: message.y,
+ button: message.button ?? "left",
+ // Chrome needs a non-zero clickCount on press/release or the page sees a move that happens
+ // to have a button set, and no click ever fires.
+ clickCount: message.event === "moved" ? 0 : (message.clickCount ?? 1),
+ modifiers: message.modifiers ?? 0,
+ });
+ return;
+ }
+
+ if (message.type === "wheel") {
+ await client.send("Input.dispatchMouseEvent", {
+ type: "mouseWheel",
+ x: message.x,
+ y: message.y,
+ deltaX: message.deltaX,
+ deltaY: message.deltaY,
+ modifiers: message.modifiers ?? 0,
+ });
+ return;
+ }
+
+ if (message.type === "key") {
+ const code = virtualKeyCode(message.key);
+ await client.send("Input.dispatchKeyEvent", {
+ // `keyDown` only when there is text to insert; otherwise `rawKeyDown`, which is what Chrome
+ // expects for keys that do not produce a character. Sending keyDown with no text makes
+ // editing keys arrive as nothing.
+ type:
+ message.event === "up"
+ ? "keyUp"
+ : message.text
+ ? "keyDown"
+ : "rawKeyDown",
+ key: message.key,
+ code: message.code,
+ ...(message.text ? { text: message.text } : {}),
+ windowsVirtualKeyCode: code,
+ nativeVirtualKeyCode: code,
+ modifiers: message.modifiers ?? 0,
+ });
+ return;
+ }
+
+ // A block of text at once: a paste, or a one-time code the person did not type character by
+ // character. `Input.insertText` bypasses key events entirely, which is correct here, it is not
+ // pretending to be a keyboard.
+ await client.send("Input.insertText", { text: message.text });
+ },
+ };
+}
diff --git a/agent-computer/src/workspace.ts b/agent-computer/src/workspace.ts
new file mode 100644
index 00000000..4e06f09d
--- /dev/null
+++ b/agent-computer/src/workspace.ts
@@ -0,0 +1,299 @@
+/**
+ * The Bot's files, and the boundary they must not escape.
+ *
+ * The computer has a `/workspace` volume so that anything a Bot should still have next week
+ * survives the container. A Bot can read and write in it, which turns a durable directory into an
+ * attack surface: the process runs as root inside its container, so `write_file("../../etc/passwd")`
+ * is the obvious first thing to try and `read_file("../../root/.ssh/id_rsa")` the second.
+ *
+ * Path confinement is enforced in three layers:
+ *
+ * 1. Absolute paths are refused outright. A Bot names a file relative to its own workspace; there is
+ * no legitimate request that begins with `/`.
+ * 2. The resolved path must be inside the root lexically. This catches `..` traversal.
+ * 3. The resolved path must still be inside the root after symlinks are followed. This is the layer
+ * people miss: a symlink placed inside the workspace (by an earlier write, or by a page the Bot
+ * downloaded something from) passes the lexical check and then points anywhere on the filesystem.
+ * For a write, the file may not exist yet, so it is the deepest existing ancestor that gets
+ * resolved, which is the directory the write will actually land in.
+ *
+ * A factory taking its root as an argument rather than reading the environment, so the confinement
+ * can be tested against a temporary directory instead of being taken on trust.
+ */
+import {
+ mkdir,
+ readdir,
+ readFile,
+ realpath,
+ stat,
+ writeFile,
+} from "node:fs/promises";
+import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
+
+export class WorkspacePathError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "WorkspacePathError";
+ }
+}
+
+export class WorkspaceFileError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "WorkspaceFileError";
+ }
+}
+
+export type WorkspaceLimits = {
+ /**
+ * Most bytes a read hands back.
+ *
+ * Bounded for the same reason page text is: the contents go into a model's context, and one large
+ * file would push the rest of the conversation out of it.
+ */
+ readBytes: number;
+ /** Most bytes a single write accepts, so a loop cannot fill the volume. */
+ writeBytes: number;
+ /** Most entries a listing describes, so a Bot cannot paste a whole disk into its own context. */
+ listEntries: number;
+};
+
+/**
+ * One thing in the workspace. Folders included so a Bot can see the shape, not just the leaves.
+ *
+ * Mirrors `WorkspaceEntry` in the server's published contract (`server/src/computer/schema.ts`), the
+ * same way `SnapshotElement` does. Duplicated rather than shared because this process is a separate
+ * deployable with no code in common with the server; the two must be changed together, and a field
+ * added here and not there is invisible until a Bot asks for it.
+ */
+export type WorkspaceEntry = {
+ /** Relative to the workspace root, which is the only form a request may use. */
+ path: string;
+ kind: "file" | "folder";
+ bytes?: number;
+};
+
+export const DEFAULT_WORKSPACE_LIMITS: WorkspaceLimits = {
+ readBytes: 64_000,
+ writeBytes: 1_000_000,
+ listEntries: 500,
+};
+
+export function createWorkspace(
+ rootPath: string,
+ limits: WorkspaceLimits = DEFAULT_WORKSPACE_LIMITS,
+) {
+ /**
+ * Turn a Bot's requested path into a real one inside the workspace, or refuse.
+ *
+ * `forWrite` changes only which part of the path must already exist: a read resolves the file
+ * itself, a write resolves the directory it would be created in.
+ */
+ async function resolvePath(
+ requested: string,
+ forWrite: boolean,
+ ): Promise<string> {
+ if (typeof requested !== "string" || !requested.trim()) {
+ throw new WorkspacePathError("A file path is required.");
+ }
+ const wanted = requested.trim();
+
+ if (isAbsolute(wanted)) {
+ throw new WorkspacePathError(
+ "Use a path relative to your workspace, not an absolute one.",
+ );
+ }
+ // Refused explicitly rather than left to the containment check, so the Bot is told what it did
+ // wrong and can correct it, instead of receiving a generic denial it may retry verbatim.
+ if (wanted.split(/[\\/]/).includes("..")) {
+ throw new WorkspacePathError(
+ "A file path may not contain '..'. You can only reach files inside your own workspace.",
+ );
+ }
+
+ const root = await realpath(rootPath);
+ const target = resolve(root, wanted);
+ assertInside(root, target);
+
+ // Layer three. Resolve what exists on disk and check again, because everything above
+ // reasons about the path as text and a symlink makes the text a lie.
+ const anchor = forWrite ? dirname(target) : target;
+ let realAnchor: string;
+ try {
+ realAnchor = await realpath(anchor);
+ } catch {
+ if (!forWrite) {
+ throw new WorkspaceFileError(`There is no file at ${wanted}.`);
+ }
+ // The parent directory does not exist yet. Walk up to the nearest one that does and verify it,
+ // so a write into a new subdirectory is allowed but cannot be aimed through a symlink.
+ realAnchor = await nearestExistingAncestor(root, anchor);
+ }
+ assertInside(root, realAnchor, wanted);
+
+ // For a write, return the full lexical target. It is already proven contained lexically, and the
+ // deepest existing directory is proven contained after symlinks, so `mkdir -p` can only create the
+ // rest inside the workspace.
+ return forWrite ? target : realAnchor;
+ }
+
+ return {
+ resolvePath,
+
+ /**
+ * What is in the workspace.
+ *
+ * Recursive, because a Bot that saved `reports/august/summary.csv` needs to find it again, and a
+ * listing that stops at the first level would show a `reports` directory and no way in. Bounded by
+ * entry count for the same reason everything else here is bounded.
+ */
+ async list(requested = "."): Promise<{
+ path: string;
+ entries: WorkspaceEntry[];
+ truncated: boolean;
+ }> {
+ const root = await realpath(rootPath);
+ // "." and "" both mean the workspace itself, which `resolvePath` would reject as a bare relative
+ // path with nothing in it. Anything else goes through the same confinement as a read.
+ const start =
+ requested === "." || requested.trim() === ""
+ ? root
+ : await resolvePath(requested, false);
+
+ const info = await stat(start).catch(() => null);
+ if (!info) {
+ throw new WorkspaceFileError(`There is no folder at ${requested}.`);
+ }
+ if (!info.isDirectory()) {
+ throw new WorkspaceFileError(`${requested} is a file, not a folder.`);
+ }
+
+ const entries: WorkspaceEntry[] = [];
+ let truncated = false;
+
+ const walk = async (dir: string): Promise<void> => {
+ if (truncated) return;
+ const found = await readdir(dir, { withFileTypes: true });
+ for (const item of found) {
+ if (entries.length >= limits.listEntries) {
+ truncated = true;
+ return;
+ }
+ const full = `${dir}/${item.name}`;
+ // Relative to the workspace root, because that is the only form a Bot may name in a request.
+ const shown = full.slice(root.length + 1);
+ if (item.isDirectory()) {
+ entries.push({ path: shown, kind: "folder" });
+ await walk(full);
+ continue;
+ }
+ if (!item.isFile()) continue;
+ const size = await stat(full).catch(() => null);
+ entries.push({
+ path: shown,
+ kind: "file",
+ ...(size ? { bytes: size.size } : {}),
+ });
+ }
+ };
+
+ await walk(start);
+ return { path: requested, entries, truncated };
+ },
+
+ /** Read a text file. Bounded, and it says when it gave you less than the whole thing. */
+ async read(requested: string): Promise<{
+ path: string;
+ text: string;
+ truncated: boolean;
+ bytes: number;
+ }> {
+ const full = await resolvePath(requested, false);
+ const info = await stat(full).catch(() => null);
+ if (!info) {
+ throw new WorkspaceFileError(`There is no file at ${requested}.`);
+ }
+ if (info.isDirectory()) {
+ throw new WorkspaceFileError(
+ `${requested} is a directory, not a file.`,
+ );
+ }
+
+ const buffer = await readFile(full);
+ const slice = buffer.subarray(0, limits.readBytes);
+ return {
+ path: requested,
+ // Decoded as UTF-8. A binary file therefore comes back as replacement characters rather
+ // than as a base64 blob nothing can read: this tool is for the notes, CSVs and JSON a Bot
+ // actually works with, and pretending otherwise would invite it to try images.
+ text: slice.toString("utf8"),
+ truncated: buffer.byteLength > slice.byteLength,
+ bytes: buffer.byteLength,
+ };
+ },
+
+ /** Write a text file, creating parent directories inside the workspace as needed. */
+ async write(
+ requested: string,
+ contents: string,
+ options: { append?: boolean } = {},
+ ): Promise<{ path: string; bytes: number; appended: boolean }> {
+ if (typeof contents !== "string") {
+ throw new WorkspaceFileError("The contents to write must be text.");
+ }
+ const bytes = Buffer.byteLength(contents, "utf8");
+ if (bytes > limits.writeBytes) {
+ throw new WorkspaceFileError(
+ `That is ${bytes} bytes and the limit is ${limits.writeBytes}.`,
+ );
+ }
+
+ const full = await resolvePath(requested, true);
+ await mkdir(dirname(full), { recursive: true });
+ await writeFile(full, contents, {
+ encoding: "utf8",
+ flag: options.append ? "a" : "w",
+ });
+ return { path: requested, bytes, appended: options.append === true };
+ },
+ };
+}
+
+export type Workspace = ReturnType<typeof createWorkspace>;
+
+/** Containment, as a path comparison that cannot be fooled by a shared prefix. */
+function assertInside(root: string, candidate: string, shown?: string): void {
+ const rel = relative(root, candidate);
+ // `relative` returns "" for the root itself, which is inside. It returns something starting with
+ // ".." for anything outside, and an absolute path when the two are on different roots. Comparing
+ // with startsWith on the raw strings instead would let "/workspace-evil" pass as "/workspace".
+ const outside =
+ rel !== "" &&
+ (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel));
+ if (outside) {
+ throw new WorkspacePathError(
+ `${shown ?? candidate} is outside your workspace, so it cannot be reached.`,
+ );
+ }
+}
+
+/** The closest ancestor of `target` that exists, never above `root`. */
+async function nearestExistingAncestor(
+ root: string,
+ target: string,
+): Promise<string> {
+ let current = target;
+ for (;;) {
+ try {
+ return await realpath(current);
+ } catch {
+ const parent = dirname(current);
+ if (parent === current) {
+ // Ran out of path without finding anything. Only reachable if the root itself vanished.
+ throw new WorkspacePathError("The workspace directory is missing.");
+ }
+ assertInside(root, parent);
+ current = parent;
+ }
+ }
+}
diff --git a/agent-computer/tests/aria-snapshot.test.ts b/agent-computer/tests/aria-snapshot.test.ts
new file mode 100644
index 00000000..d9b77fde
--- /dev/null
+++ b/agent-computer/tests/aria-snapshot.test.ts
@@ -0,0 +1,205 @@
+import { describe, expect, test } from "bun:test";
+import { parseAriaSnapshot, parseDescriptor } from "../src/aria-snapshot";
+
+/**
+ * The parser, tested against captured Playwright output.
+ *
+ * The fixture below is copied from `ariaSnapshot({ mode: "ai" })` against httpbin's form in the
+ * container, after filling one field and ticking two boxes. Captured output matters because the real
+ * shape includes nested wrappers and quoted text that plausible hand-written YAML can miss.
+ *
+ * Note what the real output shows that a plausible guess did not: flags come in any order
+ * (`[checked] [active] [ref=e19]`, with ref last), Playwright quotes any value containing a colon, and
+ * the tree nests several levels through `generic` and `paragraph` wrappers that carry refs of their own.
+ */
+const CAPTURED = `- generic [ref=e2]:
+ - paragraph [ref=e3]:
+ - generic [ref=e4]:
+ - text: "Customer name:"
+ - textbox "Customer name:" [ref=e5]: Katherine Johnson
+ - paragraph [ref=e6]:
+ - generic [ref=e7]:
+ - text: "Telephone:"
+ - textbox "Telephone:" [ref=e8]
+ - group "Pizza Size" [ref=e12]:
+ - paragraph [ref=e14]:
+ - generic [ref=e15]:
+ - radio "Small" [ref=e16]
+ - text: Small
+ - paragraph [ref=e17]:
+ - generic [ref=e18]:
+ - radio "Medium" [checked] [active] [ref=e19]
+ - text: Medium
+ - group "Pizza Toppings" [ref=e23]:
+ - paragraph [ref=e25]:
+ - generic [ref=e26]:
+ - checkbox "Bacon" [ref=e27]
+ - text: Bacon
+ - paragraph [ref=e28]:
+ - generic [ref=e29]:
+ - checkbox "Extra Cheese" [checked] [ref=e30]
+ - text: Extra Cheese
+ - button "Submit order" [ref=e44]`;
+
+describe("parseAriaSnapshot, against captured output", () => {
+ test("the fixture is genuinely valid YAML", () => {
+ // The guard against the mistake that made this rewrite necessary: an invented fixture will most
+ // likely fail here first.
+ expect(() => Bun.YAML.parse(CAPTURED)).not.toThrow();
+ });
+
+ test("keeps the controls and drops the scaffolding", () => {
+ const { elements } = parseAriaSnapshot(CAPTURED);
+ // `generic`, `paragraph`, `group` and `text` all carry refs but are not things a Bot can act on,
+ // and a list full of them is what makes a model pick the wrong element.
+ expect(elements.map((e) => e.role)).toEqual([
+ "textbox",
+ "textbox",
+ "radio",
+ "radio",
+ "checkbox",
+ "checkbox",
+ "button",
+ ]);
+ });
+
+ test("finds controls nested several levels deep", () => {
+ const names = parseAriaSnapshot(CAPTURED).elements.map((e) => e.name);
+ // The radios live under group > paragraph > generic. A parser reading only the top level would
+ // return two textboxes and call that the page.
+ expect(names).toContain("Small");
+ expect(names).toContain("Extra Cheese");
+ });
+
+ test("reads ref, role and accessible name", () => {
+ const { elements } = parseAriaSnapshot(CAPTURED);
+ expect(elements[0]).toMatchObject({
+ ref: "e5",
+ role: "textbox",
+ name: "Customer name:",
+ });
+ expect(elements.at(-1)).toMatchObject({
+ ref: "e44",
+ role: "button",
+ name: "Submit order",
+ });
+ });
+
+ test("reads a control's value, and omits it when empty", () => {
+ const { elements } = parseAriaSnapshot(CAPTURED);
+ expect(elements[0]?.value).toBe("Katherine Johnson");
+ expect(elements[1]?.value).toBeUndefined();
+ });
+
+ test("reports checked AND unchecked for things that can be checked", () => {
+ const byName = new Map(
+ parseAriaSnapshot(CAPTURED).elements.map((e) => [e.name, e]),
+ );
+ expect(byName.get("Medium")?.checked).toBe(true);
+ expect(byName.get("Extra Cheese")?.checked).toBe(true);
+ // Playwright emits nothing for an unchecked control; false is inferred so a Bot can see the state
+ // rather than assuming it.
+ expect(byName.get("Small")?.checked).toBe(false);
+ expect(byName.get("Bacon")?.checked).toBe(false);
+ // A button cannot be checked, so the field is absent rather than false.
+ expect(byName.get("Submit order")).not.toHaveProperty("checked");
+ });
+
+ test("empty and unparseable input produce no elements rather than throwing", () => {
+ expect(parseAriaSnapshot("").elements).toEqual([]);
+ expect(parseAriaSnapshot("\t- [[[ not yaml").elements).toEqual([]);
+ expect(parseAriaSnapshot("").truncated).toBe(false);
+ });
+
+ test("the element list is bounded, and says when it was cut", () => {
+ const many = Array.from(
+ { length: 250 },
+ (_, index) => `- button "B${index}" [ref=e${index}]`,
+ ).join("\n");
+ const { elements, truncated } = parseAriaSnapshot(many);
+ expect(elements).toHaveLength(200);
+ expect(truncated).toBe(true);
+ });
+});
+
+describe("values a real parser handles and a pattern got wrong", () => {
+ test("a quoted numeric value is not left with its quotes", () => {
+ // Numeric-looking text remains a string, so one-time codes are not coerced.
+ const { elements } = parseAriaSnapshot(
+ '- textbox "Code" [ref=e1]: "123456"',
+ );
+ expect(elements[0]?.value).toBe("123456");
+ });
+
+ test("a value containing a colon survives", () => {
+ const { elements } = parseAriaSnapshot(
+ '- textbox "Homepage" [ref=e1]: "https://example.com:8443/path"',
+ );
+ expect(elements[0]?.value).toBe("https://example.com:8443/path");
+ });
+
+ test("an escaped quote inside a value survives", () => {
+ const { elements } = parseAriaSnapshot(
+ '- textbox "Note" [ref=e1]: "she said \\"yes\\""',
+ );
+ expect(elements[0]?.value).toBe('she said "yes"');
+ });
+
+ /**
+ * Playwright quotes a value only when it has to, so the ones a Bot most often needs to read back
+ * arrive bare: a telephone number, a postcode, an order reference.
+ */
+ test.each([
+ ["555-0142", "a telephone number keeps both groups"],
+ ["90210-1234", "a postcode keeps its extension"],
+ ["0142-555", "a reference keeps its leading zero"],
+ ["007", "a padded number keeps its padding"],
+ ["2026-08-16", "a date stays the text on the page"],
+ ["20:30", "a time is not read as a number"],
+ ["1.2.3", "a version is not read as a number"],
+ ["true", "a field holding a word is that word"],
+ ])("an unquoted %s survives: %s", (written) => {
+ const { elements } = parseAriaSnapshot(
+ `- textbox "Field" [ref=e1]: ${written}`,
+ );
+ expect(elements[0]?.value).toBe(written);
+ });
+});
+
+describe("parseDescriptor", () => {
+ test("flags are read in any order, including ref last", () => {
+ // Exactly what the captured output does: `[checked] [active] [ref=e19]`.
+ const descriptor = parseDescriptor(
+ 'radio "Medium" [checked] [active] [ref=e19]',
+ );
+ expect(descriptor?.role).toBe("radio");
+ expect(descriptor?.name).toBe("Medium");
+ expect(descriptor?.flags.get("ref")).toBe("e19");
+ expect(descriptor?.flags.has("checked")).toBe(true);
+ });
+
+ test("an escaped quote inside a name is unescaped", () => {
+ const descriptor = parseDescriptor(
+ 'button "Delete \\"draft\\" now" [ref=e2]',
+ );
+ expect(descriptor?.name).toBe('Delete "draft" now');
+ });
+
+ test("a bracket inside the name is not mistaken for a flag", () => {
+ // The reason this is scanned rather than matched: the parts can contain each other.
+ const descriptor = parseDescriptor('button "Save [draft]" [ref=e3]');
+ expect(descriptor?.name).toBe("Save [draft]");
+ expect(descriptor?.flags.get("ref")).toBe("e3");
+ });
+
+ test("an unnamed control still parses", () => {
+ const descriptor = parseDescriptor("button [ref=e1]");
+ expect(descriptor).toMatchObject({ role: "button", name: "" });
+ expect(descriptor?.flags.get("ref")).toBe("e1");
+ });
+
+ test("junk yields nothing rather than a half-built descriptor", () => {
+ expect(parseDescriptor("")).toBeNull();
+ expect(parseDescriptor(" ")).toBeNull();
+ });
+});
diff --git a/agent-computer/tests/authorisation.test.ts b/agent-computer/tests/authorisation.test.ts
new file mode 100644
index 00000000..9ec6521b
--- /dev/null
+++ b/agent-computer/tests/authorisation.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, test } from "bun:test";
+import { isOpenPath, matchesToken, offeredToken } from "../src/authorisation";
+
+/**
+ * The check that stands in front of a Bot's browser.
+ *
+ * Every case here is one that was reachable before it existed: taking the wheel, navigating a live
+ * page, listing the Bot's files, with no sign-in and no audit row.
+ */
+
+const SECRET = "a-long-development-secret";
+
+describe("matching the secret", () => {
+ test("the right secret is accepted", () => {
+ expect(matchesToken(SECRET, SECRET)).toBeTrue();
+ });
+
+ test("a wrong secret of the same length is refused", () => {
+ const wrong = `${SECRET.slice(0, -1)}X`;
+ expect(wrong).toHaveLength(SECRET.length);
+ expect(matchesToken(SECRET, wrong)).toBeFalse();
+ });
+
+ test("a correct prefix is refused", () => {
+ // The case the constant-time comparison exists for: guessing forwards must not get warmer.
+ expect(matchesToken(SECRET, SECRET.slice(0, 5))).toBeFalse();
+ });
+
+ test("an empty offer is refused", () => {
+ expect(matchesToken(SECRET, "")).toBeFalse();
+ });
+
+ test("an empty EXPECTED secret refuses everything, including an empty offer", () => {
+ // A computer that came up without a secret must be unreachable rather than open to anybody who
+ // also sends nothing, which is what a plain equality check would have done.
+ expect(matchesToken("", "")).toBeFalse();
+ expect(matchesToken("", "anything")).toBeFalse();
+ });
+});
+
+describe("finding the secret a caller offered", () => {
+ const url = (path: string) => new URL(`http://computer.test${path}`);
+
+ test("a header", () => {
+ const headers = new Headers({ "x-openbot-computer-token": SECRET });
+ expect(offeredToken(headers, url("/snapshot"))).toBe(SECRET);
+ });
+
+ test("a bearer token", () => {
+ const headers = new Headers({ authorization: `Bearer ${SECRET}` });
+ expect(offeredToken(headers, url("/snapshot"))).toBe(SECRET);
+ });
+
+ test("the stream takes it from the query, because an upgrade carries no headers", () => {
+ const headers = new Headers();
+ expect(offeredToken(headers, url(`/stream?bot=b&token=${SECRET}`))).toBe(
+ SECRET,
+ );
+ });
+
+ test("the stream does NOT accept a header instead", () => {
+ // Not a restriction that matters for security, both are checked against the same secret, but
+ // the socket has one way in, and a surface that sent the header would fail loudly rather than
+ // appearing to work until somebody looked.
+ const headers = new Headers({ "x-openbot-computer-token": SECRET });
+ expect(offeredToken(headers, url("/stream?bot=b"))).toBe("");
+ });
+
+ test("nothing offered is an empty string, not a crash", () => {
+ expect(offeredToken(new Headers(), url("/snapshot"))).toBe("");
+ });
+});
+
+describe("what an unauthenticated caller may reach", () => {
+ test("health, and nothing else", () => {
+ expect(isOpenPath("/health")).toBeTrue();
+ for (const path of [
+ "/control/take",
+ "/navigate",
+ "/snapshot",
+ "/files/list",
+ "/files/read",
+ "/stream",
+ "/live",
+ "/",
+ ]) {
+ expect(isOpenPath(path)).toBeFalse();
+ }
+ });
+});
diff --git a/agent-computer/tests/control.test.ts b/agent-computer/tests/control.test.ts
new file mode 100644
index 00000000..95570332
--- /dev/null
+++ b/agent-computer/tests/control.test.ts
@@ -0,0 +1,238 @@
+import { describe, expect, test } from "bun:test";
+import {
+ ControlError,
+ ControlRequestError,
+ createControl,
+} from "../src/control";
+
+/**
+ * The wheel, tested on both paths.
+ *
+ * This is the piece standing between two drivers and one page, and until now it had no tests at all, * it lived as a `let` inside the file that imports playwright, so a test could not reach it without
+ * launching Chrome. What is checked here is mostly the refusal path, because that is where this
+ * component earns its keep: a Bot clicking while a person types, a secret typed when nothing asked for
+ * one, a request answered twice, a handover that leaves a password box open behind it.
+ *
+ * A fake clock is injected so `since` can be asserted rather than shrugged at.
+ */
+function fixture() {
+ let tick = 0;
+ const at = () => `2026-08-14T00:00:0${tick}.000Z`;
+ const control = createControl(() => {
+ tick += 1;
+ return at();
+ });
+ return { control };
+}
+
+describe("the happy path: ask, hand over, hand back", () => {
+ test("starts with the Bot driving and nothing pending", () => {
+ const { control } = fixture();
+ const state = control.get();
+ expect(state.holder).toBe("bot");
+ expect(state.requested).toBe(false);
+ expect(state.reason).toBeUndefined();
+ expect(control.pendingSecret()).toBeNull();
+ // Nothing to refuse yet.
+ expect(() => control.assertBotMayAct()).not.toThrow();
+ });
+
+ test("the Bot asking for help does NOT hand itself the human's authority", () => {
+ const { control } = fixture();
+ const state = control.requestHelp("There is a login wall.");
+ // The flag is raised and a person decides. A Bot that could take control on its own behalf could
+ // also hand a person a page they never asked to see.
+ expect(state.requested).toBe(true);
+ expect(state.reason).toBe("There is a login wall.");
+ expect(state.holder).toBe("bot");
+ // And it may still act while it waits: asking is not being blocked.
+ expect(() => control.assertBotMayAct()).not.toThrow();
+ });
+
+ test("taking the wheel keeps the reason and lowers the flag", () => {
+ const { control } = fixture();
+ control.requestHelp("Sign in to continue.");
+ const state = control.take();
+ expect(state.holder).toBe("human");
+ // The reason survives, because it is the thing the person was just asked to do.
+ expect(state.reason).toBe("Sign in to continue.");
+ // The request is answered, so the surface stops asking.
+ expect(state.requested).toBe(false);
+ expect(control.humanMayDrive()).toBe(true);
+ });
+
+ test("handing back returns the wheel and clears the old request", () => {
+ const { control } = fixture();
+ control.requestHelp("Sign in to continue.");
+ control.take();
+ const state = control.release();
+ expect(state.holder).toBe("bot");
+ // Dropped on purpose: leaving it set has the surface still showing a request that was dealt with.
+ expect(state.reason).toBeUndefined();
+ expect(state.requested).toBe(false);
+ expect(control.humanMayDrive()).toBe(false);
+ expect(() => control.assertBotMayAct()).not.toThrow();
+ });
+
+ test("`since` moves on a handover and not on a request", () => {
+ const { control } = fixture();
+ const created = control.get().since;
+ control.requestHelp("Stuck.");
+ // Asking for help is not a change of driver, so the clock does not restart.
+ expect(control.get().since).toBe(created);
+ expect(control.take().since).not.toBe(created);
+ });
+});
+
+describe("the crappy paths: two drivers, one page", () => {
+ test("the Bot is refused while a person holds the wheel", () => {
+ const { control } = fixture();
+ control.take();
+ expect(() => control.assertBotMayAct()).toThrow(ControlError);
+ // Refused with a reason the Bot can act on, wait, rather than a bare failure.
+ expect(() => control.assertBotMayAct()).toThrow(/hand it back/);
+ });
+
+ test("the refusal lifts the moment the person hands back", () => {
+ const { control } = fixture();
+ control.take();
+ control.release();
+ expect(() => control.assertBotMayAct()).not.toThrow();
+ });
+
+ test("a person's input is not applied merely because they asked", () => {
+ const { control } = fixture();
+ control.requestHelp("Sign in.");
+ // The Bot asked for help and no person has taken the wheel. An open socket is not permission: this is
+ // what stops anything that can reach the port from driving the browser mid-task.
+ expect(control.humanMayDrive()).toBe(false);
+ });
+
+ test("taking the wheel twice is not a way to lose the reason", () => {
+ const { control } = fixture();
+ control.requestHelp("Sign in.");
+ control.take();
+ const state = control.take();
+ expect(state.holder).toBe("human");
+ expect(state.reason).toBe("Sign in.");
+ });
+
+ test("handing back when the Bot already has it is harmless", () => {
+ const { control } = fixture();
+ const state = control.release();
+ expect(state.holder).toBe("bot");
+ expect(() => control.assertBotMayAct()).not.toThrow();
+ });
+
+ test("the caller cannot reach in and change the state it was handed", () => {
+ const { control } = fixture();
+ const state = control.get();
+ state.holder = "human";
+ // A copy, so reading the state is not a way to take the wheel.
+ expect(control.get().holder).toBe("bot");
+ });
+
+ test("junk reasons fall back to something a person can read", () => {
+ const { control } = fixture();
+ // The wire carries whatever the caller sent. An empty or non-string reason must not leave the
+ // person staring at a blank explanation of why they have just been handed a browser.
+ for (const junk of ["", " ", null, undefined, 42, {}]) {
+ const { control: fresh } = fixture();
+ expect(fresh.requestHelp(junk).reason).toBe(
+ "The assistant needs a person to continue.",
+ );
+ }
+ expect(control.requestHelp(" Trimmed. ").reason).toBe("Trimmed.");
+ });
+});
+
+describe("the crappy paths: secrets", () => {
+ test("a secret request must name the field it goes in", () => {
+ const { control } = fixture();
+ // The version without this typed the value into whatever happened to have focus, and reported
+ // success when that was nothing at all.
+ for (const bad of [{}, { ref: "" }, { ref: " " }, { ref: 7 }]) {
+ expect(() => control.requestSecret(bad)).toThrow(ControlRequestError);
+ }
+ // A request error, not a control refusal: the caller asked wrongly and no driver changed.
+ expect(() => control.requestSecret({})).toThrow(/which field/);
+ expect(control.pendingSecret()).toBeNull();
+ });
+
+ test("a secret request records the label and the field, and nothing else", () => {
+ const { control } = fixture();
+ const state = control.requestSecret({
+ label: " the six-digit code ",
+ ref: "e12",
+ snapshotId: 3,
+ });
+ expect(state.secretWanted).toBe("the six-digit code");
+ expect(state.secretRef).toBe("e12");
+ expect(state.secretSnapshotId).toBe(3);
+ expect(control.pendingSecret()).toEqual({ ref: "e12", snapshotId: 3 });
+ });
+
+ test("an unlabelled request still says something honest", () => {
+ const { control } = fixture();
+ expect(control.requestSecret({ ref: "e1" }).secretWanted).toBe(
+ "the value this page is asking for",
+ );
+ });
+
+ test("a non-numeric snapshotId is dropped rather than carried as junk", () => {
+ const { control } = fixture();
+ const state = control.requestSecret({ ref: "e1", snapshotId: "3" });
+ // Carried through to `locateRef`, where a string would prevent the numeric staleness check from
+ // matching and could let a stale field accept the secret.
+ expect(state.secretSnapshotId).toBeUndefined();
+ });
+
+ test("nothing is pending until the Bot asks", () => {
+ const { control } = fixture();
+ // What makes the masked box scoped rather than a general-purpose way to type into the page.
+ expect(control.pendingSecret()).toBeNull();
+ });
+
+ test("a supplied secret closes the request, so it cannot be answered twice", () => {
+ const { control } = fixture();
+ control.requestSecret({ ref: "e12", label: "code" });
+ control.secretSupplied();
+ expect(control.pendingSecret()).toBeNull();
+ expect(control.get().secretWanted).toBeUndefined();
+ expect(control.get().secretRef).toBeUndefined();
+ });
+
+ test("a FAILED attempt leaves the request open", () => {
+ const { control } = fixture();
+ control.requestSecret({ ref: "e12", label: "code" });
+ // `secretSupplied` is called only after the value reached the field, so a field that could not be
+ // found leaves this pending and the person can try again instead of starting over.
+ expect(control.pendingSecret()).not.toBeNull();
+ });
+
+ test("handing the wheel over or back closes any pending secret", () => {
+ for (const handover of ["take", "release"] as const) {
+ const { control } = fixture();
+ control.requestSecret({ ref: "e12", label: "password" });
+ control[handover]();
+ // A person who drove the browser themselves has dealt with the login. A masked box still asking
+ // for a password afterwards is asking for a secret nothing is waiting for.
+ expect(control.pendingSecret()).toBeNull();
+ expect(control.get().secretWanted).toBeUndefined();
+ }
+ });
+
+ test("the secret VALUE is never anywhere in the state", () => {
+ const { control } = fixture();
+ control.requestSecret({ ref: "e12", label: "one-time code" });
+ // The machine has no field that could hold it, and this test exists to fail if one is ever added.
+ // The value passes through a single request, into the page, and is not kept.
+ const serialised = JSON.stringify(control.get());
+ expect(serialised).not.toContain("value:");
+ expect(
+ Object.keys(control.get())
+ .filter((k) => /secret/i.test(k))
+ .sort(),
+ ).toEqual(["secretRef", "secretSnapshotId", "secretWanted"]);
+ });
+});
diff --git a/agent-langgraph/Dockerfile b/agent-langgraph/Dockerfile
new file mode 100644
index 00000000..a8223fa8
--- /dev/null
+++ b/agent-langgraph/Dockerfile
@@ -0,0 +1,18 @@
+# The framework Bot. Same shape as agent-bot and the same absence of a browser: this process speaks
+# AG-UI and talks to a model, and the computer it drives is a separate container with its own
+# lifecycle. Two Bots in the box rather than one, so "any AG-UI agent is a Bot" is demonstrated by
+# two implementations that share nothing but the protocol.
+FROM oven/bun:1.3-alpine
+
+WORKDIR /app
+COPY agent-langgraph/package.json ./agent-langgraph/
+RUN cd agent-langgraph && bun install
+
+# The repo's own layout, kept exactly, so `../../shared/bot-prompt` resolves the same here as it
+# does on a laptop. Flattening src to /app/src would change the depth and break only on deploy.
+COPY shared ./shared
+COPY agent-langgraph/src ./agent-langgraph/src
+
+ENV PORT=4201
+EXPOSE 4201
+CMD ["bun", "agent-langgraph/src/index.ts"]
diff --git a/agent-langgraph/package.json b/agent-langgraph/package.json
new file mode 100644
index 00000000..8e25cf9d
--- /dev/null
+++ b/agent-langgraph/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "@openbot/agent-langgraph",
+ "license": "MIT",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "bun --watch src/index.ts",
+ "start": "bun src/index.ts"
+ },
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "@langchain/anthropic": "^1.5.6",
+ "@langchain/core": "^1.2.8",
+ "@langchain/google-genai": "^2.2.0",
+ "@langchain/langgraph": "^1.4.10",
+ "@langchain/openai": "^1.5.8"
+ }
+}
diff --git a/agent-langgraph/src/index.ts b/agent-langgraph/src/index.ts
new file mode 100644
index 00000000..d6fa1503
--- /dev/null
+++ b/agent-langgraph/src/index.ts
@@ -0,0 +1,357 @@
+import type { BaseEvent, RunAgentInput } from "@ag-ui/core";
+import { EventEncoder } from "@ag-ui/encoder";
+import { ChatAnthropic } from "@langchain/anthropic";
+import {
+ AIMessage,
+ type BaseMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+} from "@langchain/core/messages";
+import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
+import {
+ END,
+ MessagesAnnotation,
+ START,
+ StateGraph,
+} from "@langchain/langgraph";
+import { ChatOpenAI } from "@langchain/openai";
+import { serve } from "bun";
+import { SYSTEM_PROMPT } from "../../shared/bot-prompt";
+
+/**
+ * The same Bot, on a framework.
+ *
+ * `agent-bot` is a proof of concept written against a model SDK; this process uses framework integrations while
+ * keeping the same AG-UI endpoint contract.
+ *
+ * A Bot is a registry row pointing at an AG-UI endpoint, so adding a framework does not require
+ * server changes.
+ *
+ * The model API stops being ours. `agent-bot` speaks `/v1/chat/completions` by hand, which is why
+ * gpt-5.6 cannot be used there without rewriting its streaming loop: those models reject function
+ * tools on that endpoint and require the Responses API. Here it is `useResponsesApi`, one line,
+ * because the migration belongs to the people who maintain the integration.
+ *
+ * The tool loop still runs on the client, exactly as it does in `agent-bot`: a Bot's actions happen
+ * on a browser the person is watching, and the surface remains the place that executes those tools.
+ * The graph provides model orchestration without changing that contract.
+ */
+
+const PORT = Number.parseInt(process.env.PORT ?? "4201", 10);
+
+/**
+ * Which model drives this Bot, and from whom.
+ *
+ * The framework integration owns provider-specific HTTP and streaming details. The proof-of-concept Bot
+ * speaks one provider's HTTP API
+ * directly, so changing provider there means rewriting its streaming loop and its message
+ * translation. Here it is a name and a key, because the integrations already exist and are
+ * maintained by the people whose API it is.
+ *
+ * Each provider reads its own key. A deployment that only runs Anthropic never needs an OpenAI key,
+ * which is the point of making this configurable rather than assuming one vendor.
+ *
+ * The default is unchanged so the two shipped Bots stay comparable out of the box.
+ */
+const PROVIDER = (process.env.BOT_PROVIDER ?? "openai").toLowerCase();
+const MODEL = process.env.BOT_MODEL ?? defaultModelFor(PROVIDER);
+/** OpenAI only. Its newer models require the Responses API, which the integration handles. */
+const USE_RESPONSES_API = process.env.BOT_RESPONSES_API === "true";
+
+function defaultModelFor(provider: string): string {
+ if (provider === "anthropic") return "claude-sonnet-4-5";
+ if (provider === "google") return "gemini-2.5-flash";
+ return "gpt-5.5";
+}
+
+/**
+ * The key this provider needs, checked at startup rather than on the first run.
+ *
+ * Refusing to start matches the computer-token posture:
+ * a missing key should fail in front of whoever is deploying, not as a conversation that errors in
+ * front of somebody trying to use it.
+ */
+const KEY_VARIABLE: Record<string, string> = {
+ openai: "OPENAI_API_KEY",
+ anthropic: "ANTHROPIC_API_KEY",
+ google: "GOOGLE_API_KEY",
+};
+
+const keyVariable = KEY_VARIABLE[PROVIDER];
+if (!keyVariable) {
+ console.error(
+ `BOT_PROVIDER=${PROVIDER} is not one this Bot knows. Use openai, anthropic or google.`,
+ );
+ process.exit(1);
+}
+const API_KEY = process.env[keyVariable]?.trim();
+if (!API_KEY) {
+ console.error(
+ `${keyVariable} is not set, and BOT_PROVIDER=${PROVIDER} needs it. This Bot cannot answer without a model.`,
+ );
+ process.exit(1);
+}
+
+/** Translate the conversation AG-UI carries into LangChain's message classes. */
+function toLangChainMessages(input: RunAgentInput): BaseMessage[] {
+ const messages: BaseMessage[] = [new SystemMessage(SYSTEM_PROMPT)];
+
+ for (const message of input.messages) {
+ if (message.role === "user") {
+ messages.push(new HumanMessage(String(message.content ?? "")));
+ continue;
+ }
+ if (message.role === "system" || message.role === "developer") {
+ messages.push(new SystemMessage(String(message.content ?? "")));
+ continue;
+ }
+ if (message.role === "tool") {
+ // Tool results are appended so the model can continue from the completed call.
+ messages.push(
+ new ToolMessage({
+ tool_call_id: message.toolCallId,
+ content: String(message.content ?? ""),
+ }),
+ );
+ continue;
+ }
+ if (message.role === "assistant") {
+ messages.push(
+ new AIMessage({
+ content: message.content ?? "",
+ tool_calls:
+ message.toolCalls?.map((call) => ({
+ id: call.id,
+ name: call.function.name,
+ // LangChain wants parsed arguments where AG-UI carries the raw string. A call whose
+ // arguments did not parse is passed as empty rather than dropped: the model needs to
+ // see that it made the call, or it makes it again.
+ args: parseArguments(call.function.arguments),
+ })) ?? [],
+ }),
+ );
+ }
+ }
+
+ return messages;
+}
+
+function parseArguments(raw: string): Record<string, unknown> {
+ try {
+ const parsed = JSON.parse(raw || "{}");
+ return typeof parsed === "object" && parsed !== null
+ ? (parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Every tool comes from the caller. This service publishes none of its own, on purpose.
+ *
+ * Same rule as `agent-bot`: a new capability on the front end needs no change here.
+ */
+function toBoundTools(input: RunAgentInput) {
+ if (!input.tools?.length) return [];
+ return input.tools.map((tool) => ({
+ type: "function" as const,
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.parameters as Record<string, unknown>,
+ },
+ }));
+}
+
+/**
+ * The chat model, from whichever provider this deployment chose.
+ *
+ * Every one of these binds tools the same way and streams the same way, which is exactly why the
+ * rest of this file does not know which one it got.
+ */
+function buildModel() {
+ if (PROVIDER === "anthropic") {
+ return new ChatAnthropic({
+ model: MODEL,
+ apiKey: API_KEY,
+ streaming: true,
+ });
+ }
+ if (PROVIDER === "google") {
+ return new ChatGoogleGenerativeAI({
+ model: MODEL,
+ apiKey: API_KEY,
+ streaming: true,
+ });
+ }
+ return new ChatOpenAI({
+ model: MODEL,
+ apiKey: API_KEY,
+ streaming: true,
+ ...(USE_RESPONSES_API ? { useResponsesApi: true } : {}),
+ });
+}
+
+/**
+ * The graph.
+ *
+ * One node is enough while the tool loop lives on the client. The graph provides model orchestration
+ * without changing the AG-UI contract.
+ */
+function buildGraph(input: RunAgentInput) {
+ const model = buildModel();
+
+ const tools = toBoundTools(input);
+ const bound = tools.length > 0 ? model.bindTools(tools) : model;
+
+ return new StateGraph(MessagesAnnotation)
+ .addNode("answer", async (state) => ({
+ messages: [await bound.invoke(state.messages)],
+ }))
+ .addEdge(START, "answer")
+ .addEdge("answer", END)
+ .compile();
+}
+
+async function runAgent(input: RunAgentInput): Promise<Response> {
+ const encoder = new EventEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const utf8 = new TextEncoder();
+ const send = (event: BaseEvent) =>
+ controller.enqueue(utf8.encode(encoder.encodeSSE(event)));
+
+ send({
+ type: "RUN_STARTED",
+ threadId: input.threadId,
+ runId: input.runId,
+ } as BaseEvent);
+
+ const messageId = `msg_${input.runId}`;
+ let textOpen = false;
+
+ try {
+ const graph = buildGraph(input);
+ const events = await graph.streamEvents(
+ { messages: toLangChainMessages(input) },
+ { version: "v2" },
+ );
+
+ // Accumulated rather than emitted per chunk, because a tool call's arguments arrive in
+ // fragments and AG-UI wants one call. The framework hands back assembled `tool_calls` on the
+ // final message, which is precisely the plumbing agent-bot does by hand.
+ let finalMessage: AIMessage | null = null;
+
+ for await (const event of events) {
+ if (event.event === "on_chat_model_stream") {
+ const chunk = event.data?.chunk as
+ | { content?: unknown }
+ | undefined;
+ const text =
+ typeof chunk?.content === "string" ? chunk.content : "";
+ if (!text) continue;
+
+ if (!textOpen) {
+ send({
+ type: "TEXT_MESSAGE_START",
+ messageId,
+ role: "assistant",
+ } as BaseEvent);
+ textOpen = true;
+ }
+ send({
+ type: "TEXT_MESSAGE_CONTENT",
+ messageId,
+ delta: text,
+ } as BaseEvent);
+ }
+
+ if (event.event === "on_chat_model_end") {
+ const output = event.data?.output as AIMessage | undefined;
+ if (output) finalMessage = output;
+ }
+ }
+
+ if (textOpen) {
+ send({ type: "TEXT_MESSAGE_END", messageId } as BaseEvent);
+ }
+
+ for (const call of finalMessage?.tool_calls ?? []) {
+ send({
+ type: "TOOL_CALL_START",
+ toolCallId: call.id ?? `call_${input.runId}_${call.name}`,
+ toolCallName: call.name,
+ parentMessageId: messageId,
+ } as BaseEvent);
+ send({
+ type: "TOOL_CALL_ARGS",
+ toolCallId: call.id ?? `call_${input.runId}_${call.name}`,
+ delta: JSON.stringify(call.args ?? {}),
+ } as BaseEvent);
+ send({
+ type: "TOOL_CALL_END",
+ toolCallId: call.id ?? `call_${input.runId}_${call.name}`,
+ } as BaseEvent);
+ }
+
+ send({
+ type: "RUN_FINISHED",
+ threadId: input.threadId,
+ runId: input.runId,
+ } as BaseEvent);
+ } catch (error) {
+ // A text message left open would strand the surface mid-message, so it is closed before the
+ // error is reported. agent-bot has the same hazard and the same ordering.
+ if (textOpen) {
+ send({ type: "TEXT_MESSAGE_END", messageId } as BaseEvent);
+ }
+ send({
+ type: "RUN_ERROR",
+ message:
+ error instanceof Error
+ ? error.message
+ : "The Bot could not answer.",
+ } as BaseEvent);
+ } finally {
+ controller.close();
+ }
+ },
+ });
+
+ return new Response(stream, {
+ headers: {
+ "content-type": encoder.getContentType(),
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ },
+ });
+}
+
+serve({
+ port: PORT,
+ idleTimeout: 120,
+ async fetch(request) {
+ const url = new URL(request.url);
+
+ if (url.pathname === "/health") {
+ return Response.json({
+ status: "ok",
+ provider: PROVIDER,
+ model: MODEL,
+ framework: "langgraph",
+ responsesApi: USE_RESPONSES_API,
+ });
+ }
+
+ if (url.pathname === "/ag-ui" && request.method === "POST") {
+ const input = (await request.json()) as RunAgentInput;
+ return runAgent(input);
+ }
+
+ return Response.json({ error: "Not found." }, { status: 404 });
+ },
+});
+
+console.info(`agent-langgraph listening on http://localhost:${PORT}/ag-ui`);
diff --git a/app/src/components/admin/admin-sidebar.tsx b/app/src/components/admin/admin-sidebar.tsx
new file mode 100644
index 00000000..1a5559e9
--- /dev/null
+++ b/app/src/components/admin/admin-sidebar.tsx
@@ -0,0 +1,171 @@
+import {
+ IconArrowLeft,
+ IconCode,
+ IconDeviceDesktop,
+ IconKey,
+ IconLayoutGrid,
+ IconListDetails,
+ IconPlugConnected,
+ IconPuzzle,
+ IconShieldCheck,
+} from "@tabler/icons-react";
+import { Link, type LinkOptions } from "@tanstack/react-router";
+import type * as React from "react";
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarGroup,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarMenu,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarRail,
+} from "@/components/ui/sidebar";
+
+const appLinkOptions = { to: "/" } satisfies LinkOptions;
+const adminLinkOptions = { to: "/admin" } satisfies LinkOptions;
+
+/**
+ * The same three groups, in the same order, as the admin index.
+ *
+ * A rail that lists eight things flat asks somebody to know which of them is the one they want. The
+ * grouping is the only navigation help this screen offers, so it has to agree with the page it
+ * navigates to — two different orderings of the same eight links is worse than either ordering.
+ */
+const GROUPS: {
+ label: string;
+ items: {
+ icon: React.ComponentType<{ className?: string }>;
+ linkOptions: LinkOptions;
+ title: string;
+ }[];
+}[] = [
+ {
+ label: "What Bots can reach",
+ items: [
+ {
+ title: "Connectors",
+ icon: IconPlugConnected,
+ linkOptions: { to: "/admin/connectors" },
+ },
+ {
+ title: "Credentials",
+ icon: IconKey,
+ linkOptions: { to: "/admin/credentials" },
+ },
+ {
+ title: "Boundaries",
+ icon: IconShieldCheck,
+ linkOptions: { to: "/admin/boundaries" },
+ },
+ {
+ title: "Computers",
+ icon: IconDeviceDesktop,
+ linkOptions: { to: "/admin/computers" },
+ },
+ ],
+ },
+ {
+ label: "What Bots can do",
+ items: [
+ {
+ title: "Plugins",
+ icon: IconPuzzle,
+ linkOptions: { to: "/admin/plugins" },
+ },
+ {
+ title: "Components",
+ icon: IconLayoutGrid,
+ linkOptions: { to: "/admin/components" },
+ },
+ {
+ title: "Playground",
+ icon: IconCode,
+ linkOptions: { to: "/admin/playground" },
+ },
+ ],
+ },
+ {
+ label: "What happened",
+ items: [
+ {
+ title: "Audit",
+ icon: IconListDetails,
+ linkOptions: { to: "/admin/audit" },
+ },
+ ],
+ },
+];
+
+export function AdminSidebar({
+ ...props
+}: React.ComponentProps<typeof Sidebar>) {
+ return (
+ <Sidebar {...props}>
+ <SidebarHeader>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ size="lg"
+ render={(props) => (
+ <Link {...appLinkOptions} {...props}>
+ <IconArrowLeft className="mr-2 h-4 w-4" />
+ Back to app
+ </Link>
+ )}
+ />
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarHeader>
+ <SidebarContent>
+ <SidebarGroup>
+ <SidebarMenu>
+ <SidebarMenuItem>
+ {/*
+ * `activeOptions.exact`, because /admin is a prefix of every other route here and
+ * would otherwise light up on all of them.
+ */}
+ <SidebarMenuButton
+ render={(props) => (
+ <Link
+ {...adminLinkOptions}
+ activeOptions={{ exact: true }}
+ activeProps={{ className: "bg-foreground/5" }}
+ {...props}
+ >
+ Overview
+ </Link>
+ )}
+ />
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarGroup>
+ {GROUPS.map((group) => (
+ <SidebarGroup key={group.label}>
+ <SidebarGroupLabel>{group.label}</SidebarGroupLabel>
+ <SidebarMenu>
+ {group.items.map((item) => (
+ <SidebarMenuItem key={item.title}>
+ <SidebarMenuButton
+ render={(props) => (
+ <Link
+ {...item.linkOptions}
+ activeProps={{ className: "bg-foreground/5" }}
+ {...props}
+ >
+ <item.icon className="mr-2 h-4 w-4" />
+ {item.title}
+ </Link>
+ )}
+ />
+ </SidebarMenuItem>
+ ))}
+ </SidebarMenu>
+ </SidebarGroup>
+ ))}
+ </SidebarContent>
+ <SidebarRail />
+ </Sidebar>
+ );
+}
diff --git a/app/src/components/agents/agent-profile.tsx b/app/src/components/agents/agent-profile.tsx
new file mode 100644
index 00000000..c0b18245
--- /dev/null
+++ b/app/src/components/agents/agent-profile.tsx
@@ -0,0 +1,261 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
+import { type ReactNode, useState } from "react";
+import { AbstractAvatar } from "@/components/agents/abstract-avatar";
+import { AgentFields } from "@/components/agents/agent-fields";
+import { Button } from "@/components/ui/button";
+import { Separator } from "@/components/ui/separator";
+import { Skeleton } from "@/components/ui/skeleton";
+import { agentInputFrom } from "@/lib/agents/form";
+import {
+ deleteAgentMutationOptions,
+ duplicateAgentMutationOptions,
+ setAgentHiddenMutationOptions,
+ updateAgentMutationOptions,
+} from "@/lib/agents/mutations";
+import { agentQueryOptions } from "@/lib/agents/queries";
+
+function Tag({ children }: { children: ReactNode }) {
+ return (
+ <span className="inline-flex items-center rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground">
+ {children}
+ </span>
+ );
+}
+
+function ProfileSkeleton() {
+ return (
+ <div className="flex w-full flex-col gap-6 p-8">
+ <header className="flex flex-col items-center gap-3">
+ <Skeleton className="size-20 shrink-0 rounded-full" />
+ <div className="flex w-full flex-col items-center gap-1.5">
+ <Skeleton className="h-7 w-44" />
+ <Skeleton className="h-4 w-28" />
+ </div>
+ <div className="flex gap-1.5">
+ <Skeleton className="h-5 w-16 rounded-full" />
+ <Skeleton className="h-5 w-24 rounded-full" />
+ </div>
+ </header>
+ <div className="grid gap-2">
+ <Skeleton className="h-3 w-10" />
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-2/3" />
+ </div>
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-9 w-full" />
+ <Skeleton className="h-9 w-full" />
+ <Skeleton className="h-9 w-full" />
+ </div>
+ </div>
+ );
+}
+
+export function AgentProfile({ agentId }: { agentId: string }) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ // State is keyed by teammate id because this panel can remain open while its target changes.
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [confirmingDeleteId, setConfirmingDeleteId] = useState<string | null>(
+ null,
+ );
+ const isEditing = editingId === agentId;
+ const isConfirmingDelete = confirmingDeleteId === agentId;
+
+ const agent = useQuery(agentQueryOptions(agentId));
+ const updateAgent = useMutation(updateAgentMutationOptions(queryClient));
+ const duplicateAgent = useMutation(
+ duplicateAgentMutationOptions(queryClient),
+ );
+ const setHidden = useMutation(setAgentHiddenMutationOptions(queryClient));
+ const deleteAgent = useMutation(deleteAgentMutationOptions(queryClient));
+
+ if (agent.isPending) {
+ return <ProfileSkeleton />;
+ }
+ if (agent.error || !agent.data) {
+ return (
+ <p className="p-8 text-sm text-destructive" role="alert">
+ Could not load this teammate.
+ </p>
+ );
+ }
+
+ const profile = agent.data;
+ const actionError =
+ duplicateAgent.error ?? setHidden.error ?? deleteAgent.error;
+
+ return (
+ <div className="flex w-full flex-col gap-6 p-8">
+ <header className="flex flex-col items-center gap-3 text-center">
+ <AbstractAvatar
+ name={profile.name}
+ seed={profile.avatarSeed}
+ size={80}
+ />
+ <div className="flex w-full flex-col items-center gap-0.5">
+ <h1 className="w-full text-balance text-2xl font-semibold leading-tight tracking-tight">
+ {profile.name}
+ </h1>
+ <p className="w-full text-balance text-sm text-muted-foreground">
+ {profile.title}
+ </p>
+ </div>
+
+ <div className="flex flex-wrap justify-center gap-1.5">
+ <Tag>{profile.visibility === "private" ? "Private" : "Public"}</Tag>
+ {profile.systemOwned ? <Tag>System owned</Tag> : null}
+ </div>
+ </header>
+
+ {isEditing ? (
+ <AgentFields
+ defaultValues={{
+ name: profile.name,
+ roleDescription: profile.roleDescription,
+ title: profile.title,
+ visibility: profile.visibility,
+ endpoint: profile.endpoint ?? "",
+ // The server never sends credentials back to the client.
+ authValue: "",
+ }}
+ hasAuth={profile.hasAuth}
+ error={updateAgent.error}
+ onCancel={() => setEditingId(null)}
+ onSubmit={async (values) => {
+ await updateAgent.mutateAsync({
+ agentId,
+ input: agentInputFrom(values),
+ });
+ setEditingId(null);
+ }}
+ submitLabel="Save changes"
+ />
+ ) : (
+ <section className="grid gap-2">
+ <h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ Role
+ </h2>
+ <p className="text-sm whitespace-pre-wrap text-pretty">
+ {profile.roleDescription}
+ </p>
+ </section>
+ )}
+
+ {actionError ? (
+ <p className="text-sm text-destructive" role="alert">
+ {actionError.message}
+ </p>
+ ) : null}
+
+ {isEditing ? null : (
+ <div className="flex flex-col gap-2 w-full mt-6">
+ <Button
+ className="w-full text-sm!"
+ onClick={async () => {
+ await navigate({
+ search: { agent: agentId },
+ to: "/channel/new",
+ });
+ }}
+ >
+ Start channel
+ </Button>
+
+ <Button
+ className="w-full text-sm!"
+ disabled={duplicateAgent.isPending}
+ onClick={async () => {
+ const copy = await duplicateAgent.mutateAsync(agentId);
+ await navigate({ search: { agent: copy.id }, to: "/agents" });
+ }}
+ variant="outline"
+ >
+ {duplicateAgent.isPending ? "Duplicating…" : "Duplicate"}
+ </Button>
+
+ <Button
+ className="w-full text-sm!"
+ disabled={setHidden.isPending}
+ onClick={async () => {
+ await setHidden.mutateAsync({
+ agentId,
+ hidden: !profile.hidden,
+ });
+ if (!profile.hidden)
+ await navigate({ search: {}, to: "/agents" });
+ }}
+ variant="outline"
+ >
+ {setHidden.isPending
+ ? profile.hidden
+ ? "Unhiding…"
+ : "Hiding…"
+ : profile.hidden
+ ? "Unhide"
+ : "Hide"}
+ </Button>
+
+ {profile.hidden ? (
+ <p className="-mt-1 text-xs text-muted-foreground">
+ Hidden from your agents list. This changes nothing for anyone
+ else.
+ </p>
+ ) : null}
+
+ {profile.canManage ? (
+ <Button
+ className="w-full text-sm!"
+ onClick={() => setEditingId(agentId)}
+ variant="outline"
+ >
+ Edit
+ </Button>
+ ) : null}
+
+ {profile.canManage ? (
+ <>
+ <Separator className="my-1" />
+
+ {isConfirmingDelete ? (
+ <div className="flex flex-col gap-2">
+ <p className="text-sm">
+ Delete <span className="font-medium">{profile.name}</span>?
+ This cannot be undone.
+ </p>
+ {/* Cancel remains closest to the original Delete button position. */}
+ <Button
+ className="w-full text-sm!"
+ onClick={() => setConfirmingDeleteId(null)}
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ <Button
+ className="w-full text-sm!"
+ disabled={deleteAgent.isPending}
+ onClick={async () => {
+ await deleteAgent.mutateAsync(agentId);
+ await navigate({ search: {}, to: "/agents" });
+ }}
+ variant="destructive"
+ >
+ {deleteAgent.isPending ? "Deleting…" : "Delete"}
+ </Button>
+ </div>
+ ) : (
+ <Button
+ className="w-full text-sm!"
+ onClick={() => setConfirmingDeleteId(agentId)}
+ variant="destructive"
+ >
+ Delete
+ </Button>
+ )}
+ </>
+ ) : null}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/app/src/components/agents/orb/agent-orb.tsx b/app/src/components/agents/orb/agent-orb.tsx
new file mode 100644
index 00000000..1857e41f
--- /dev/null
+++ b/app/src/components/agents/orb/agent-orb.tsx
@@ -0,0 +1,437 @@
+import { cn } from "@/lib/utils";
+import {
+ type MotionStyle,
+ motion,
+ type TargetAndTransition,
+ type Transition,
+ useReducedMotion,
+ useTransform,
+} from "motion/react";
+import {
+ type AIAmplitude,
+ type AIState,
+ getAIStateMotion,
+ useAmplitudeValue,
+} from "./ai-core";
+
+const SIZE_THRESHOLD_SMALL = 50;
+const SIZE_THRESHOLD_TINY = 30;
+const SIZE_THRESHOLD_MEDIUM = 100;
+const BLUR_MULTIPLIER_SMALL = 0.008;
+const BLUR_MIN_SMALL = 1;
+const BLUR_MULTIPLIER_LARGE = 0.015;
+const BLUR_MIN_LARGE = 4;
+const CONTRAST_MULTIPLIER_SMALL = 0.004;
+const CONTRAST_MIN_SMALL = 1.2;
+const CONTRAST_MULTIPLIER_LARGE = 0.008;
+const CONTRAST_MIN_LARGE = 1.5;
+const DOT_SIZE_MULTIPLIER_SMALL = 0.004;
+const DOT_SIZE_MIN_SMALL = 0.05;
+const DOT_SIZE_MULTIPLIER_LARGE = 0.008;
+const DOT_SIZE_MIN_LARGE = 0.1;
+const SHADOW_MULTIPLIER_SMALL = 0.004;
+const SHADOW_MIN_SMALL = 0.5;
+const SHADOW_MULTIPLIER_LARGE = 0.008;
+const SHADOW_MIN_LARGE = 2;
+const MASK_RADIUS_TINY = "0%";
+const MASK_RADIUS_SMALL = "5%";
+const MASK_RADIUS_MEDIUM = "15%";
+const MASK_RADIUS_LARGE = "25%";
+const CONTRAST_TINY = 1.1;
+const CONTRAST_MULTIPLIER_FINAL = 1.2;
+const CONTRAST_MIN_FINAL = 1.3;
+
+/** Loud audio tightens the gradient, which reads as the orb "focusing". */
+const AMPLITUDE_BLUR_FALLOFF = 0.45;
+/** Amplitude adds at most 12% of extra size on top of the state scale. */
+const AMPLITUDE_SCALE_GAIN = 0.12;
+/** Single lateral nudge used to signal `error`, well under 200ms. */
+const ERROR_SHAKE_KEYFRAMES = [0, -3, 3, 0];
+const ERROR_SHAKE_DURATION = 0.18;
+const EASE_IN_OUT = [0.645, 0.045, 0.355, 1] as const;
+const GLOW_BLUR_RATIO = 0.28;
+const GLOW_MAX_OPACITY = 0.7;
+/** Depth rim, as a fraction of the orb size. */
+const RIM_RATIO = 0.06;
+const RIM_MIN = 1.5;
+/** Sheen drift period at rest, before the state speed divides it. */
+const DRIFT_BASE_SECONDS = 12;
+/** `idle` breathes: a slow, shallow scale cycle that never draws attention. */
+const BREATHE_SCALE = [1, 1.035, 1];
+const BREATHE_SECONDS = 5.5;
+const SPRING_DEFAULT: Transition = {
+ bounce: 0.1,
+ duration: 0.25,
+ type: "spring",
+};
+
+export interface AgentOrbProps {
+ /**
+ * Live audio level, 0–1. Pass the `MotionValue` from `useAudioAmplitude` so
+ * the signal never re-renders React.
+ */
+ amplitude?: AIAmplitude;
+ /** Ambient rotation period in seconds, before the state speed multiplier. */
+ animationDuration?: number;
+ className?: string;
+ colors?: {
+ bg?: string;
+ c1?: string;
+ c2?: string;
+ c3?: string;
+ /** Fourth mesh stop. More stops means fewer visible repeats per rotation. */
+ c4?: string;
+ };
+ size?: string;
+ /** Shared AI state driving speed, scale, saturation and reactivity. */
+ state?: AIState;
+}
+
+const AgentOrb: React.FC<AgentOrbProps> = ({
+ size = "192px",
+ className,
+ colors,
+ animationDuration = 20,
+ amplitude,
+ state = "idle",
+}) => {
+ const shouldReduceMotion = useReducedMotion();
+ const amplitudeValue = useAmplitudeValue(amplitude);
+ const stateMotion = getAIStateMotion(state);
+
+ /**
+ * Higher chroma than the original pastels.
+ *
+ * The first palette sat at chroma 0.12–0.15, which washes out once the mesh is
+ * blurred and the dot pattern is overlaid on top. Pushing to ~0.2 and adding a
+ * saturate() pass to the mesh is what makes the colour survive all that.
+ */
+ const defaultColors = {
+ bg: "oklch(92% 0.03 300)",
+ c1: "oklch(68% 0.21 350)", // Pink
+ c2: "oklch(70% 0.18 210)", // Blue
+ c3: "oklch(66% 0.2 285)", // Violet
+ c4: "oklch(72% 0.19 325)", // Magenta, the fourth stop for variety
+ };
+
+ const finalColors = { ...defaultColors, ...colors };
+ // The bloom stays in the orb's own palette — see the note in ai-orb-aura.
+ const glowColor = finalColors.c2;
+
+ // Extract numeric value from size for calculations
+ const sizeValue = Number.parseInt(size.replace("px", ""), 10);
+
+ // Responsive calculations based on size
+ const blurAmount =
+ sizeValue < SIZE_THRESHOLD_SMALL
+ ? Math.max(sizeValue * BLUR_MULTIPLIER_SMALL, BLUR_MIN_SMALL) // Reduced blur for small sizes
+ : Math.max(sizeValue * BLUR_MULTIPLIER_LARGE, BLUR_MIN_LARGE);
+
+ const contrastAmount =
+ sizeValue < SIZE_THRESHOLD_SMALL
+ ? Math.max(sizeValue * CONTRAST_MULTIPLIER_SMALL, CONTRAST_MIN_SMALL) // Reduced contrast for small sizes
+ : Math.max(sizeValue * CONTRAST_MULTIPLIER_LARGE, CONTRAST_MIN_LARGE);
+
+ const dotSize =
+ sizeValue < SIZE_THRESHOLD_SMALL
+ ? Math.max(sizeValue * DOT_SIZE_MULTIPLIER_SMALL, DOT_SIZE_MIN_SMALL) // Smaller dots for small sizes
+ : Math.max(sizeValue * DOT_SIZE_MULTIPLIER_LARGE, DOT_SIZE_MIN_LARGE);
+
+ const shadowSpread =
+ sizeValue < SIZE_THRESHOLD_SMALL
+ ? Math.max(sizeValue * SHADOW_MULTIPLIER_SMALL, SHADOW_MIN_SMALL) // Reduced shadow for small sizes
+ : Math.max(sizeValue * SHADOW_MULTIPLIER_LARGE, SHADOW_MIN_LARGE);
+
+ // Adjust mask radius based on size to reduce black center in small sizes
+ const getMaskRadius = (value: number) => {
+ if (value < SIZE_THRESHOLD_TINY) {
+ return MASK_RADIUS_TINY;
+ }
+ if (value < SIZE_THRESHOLD_SMALL) {
+ return MASK_RADIUS_SMALL;
+ }
+ if (value < SIZE_THRESHOLD_MEDIUM) {
+ return MASK_RADIUS_MEDIUM;
+ }
+ return MASK_RADIUS_LARGE;
+ };
+
+ const maskRadius = getMaskRadius(sizeValue);
+
+ // Use more subtle contrast for very small sizes
+ const getFinalContrast = (value: number) => {
+ if (value < SIZE_THRESHOLD_TINY) {
+ return CONTRAST_TINY; // Very subtle contrast for tiny sizes
+ }
+ if (value < SIZE_THRESHOLD_SMALL) {
+ return Math.max(
+ contrastAmount * CONTRAST_MULTIPLIER_FINAL,
+ CONTRAST_MIN_FINAL,
+ ); // Reduced contrast for small sizes
+ }
+ return contrastAmount;
+ };
+
+ const finalContrast = getFinalContrast(sizeValue);
+
+ // Reactivity is gated by the state preset: `thinking` barely listens so the
+ // orb keeps churning internally instead of throbbing with room noise.
+ const reactivity = shouldReduceMotion ? 0 : stateMotion.reactivity;
+
+ const reactiveBlur = useTransform(amplitudeValue, (level) => {
+ const focus = 1 - level * reactivity * AMPLITUDE_BLUR_FALLOFF;
+ return `${blurAmount * focus}px`;
+ });
+
+ const reactiveScale = useTransform(
+ amplitudeValue,
+ (level) => stateMotion.scale + level * reactivity * AMPLITUDE_SCALE_GAIN,
+ );
+
+ const loopDuration = shouldReduceMotion
+ ? animationDuration
+ : animationDuration / stateMotion.speed;
+
+ // Rim thickness scales with the orb, so the lit edge reads the same at 24px
+ // and at 240px instead of swallowing the small one.
+ const rim = Math.max(sizeValue * RIM_RATIO, RIM_MIN);
+ // The sheen drifts slower than the mesh rotates; a busier state speeds it up
+ // a touch without matching the rotation, which would look mechanical.
+ const driftDuration = (DRIFT_BASE_SECONDS / (1 + stateMotion.speed)) * 2;
+
+ const getRootAnimate = (): TargetAndTransition => {
+ if (shouldReduceMotion) {
+ return { scale: 1, x: 0 };
+ }
+ if (state === "error") {
+ return { scale: 1, x: ERROR_SHAKE_KEYFRAMES };
+ }
+ if (stateMotion.motif === "breathe") {
+ return { scale: BREATHE_SCALE, x: 0 };
+ }
+ return { scale: 1, x: 0 };
+ };
+
+ const getRootTransition = (): Transition => {
+ if (shouldReduceMotion) {
+ return { duration: 0 };
+ }
+ if (state === "error") {
+ return { duration: ERROR_SHAKE_DURATION, ease: EASE_IN_OUT };
+ }
+ if (stateMotion.motif === "breathe") {
+ return {
+ duration: BREATHE_SECONDS,
+ ease: EASE_IN_OUT,
+ repeat: Number.POSITIVE_INFINITY,
+ };
+ }
+ return SPRING_DEFAULT;
+ };
+
+ return (
+ // The gradient disc clips its own overflow, so the bloom and the status
+ // motif have to live in a wrapper rather than inside it.
+ <motion.div
+ animate={getRootAnimate()}
+ className={cn("relative", className)}
+ style={
+ {
+ "--orb-size": size,
+ height: size,
+ width: size,
+ } as MotionStyle
+ }
+ transition={getRootTransition()}
+ >
+ {/* Bloom tinted by the state's semantic accent. */}
+ <motion.div
+ animate={{ opacity: stateMotion.glow * GLOW_MAX_OPACITY }}
+ className="absolute rounded-full"
+ style={{
+ background: `radial-gradient(circle at 50% 50%, ${glowColor} 0%, transparent 64%)`,
+ filter: `blur(calc(var(--orb-size) * ${GLOW_BLUR_RATIO}))`,
+ inset: "-12%",
+ }}
+ transition={shouldReduceMotion ? { duration: 0 } : SPRING_DEFAULT}
+ />
+
+ <motion.div
+ className="agent-orb"
+ style={
+ {
+ "--animation-duration": `${loopDuration}s`,
+ "--bg": finalColors.bg,
+ "--blur-amount": reactiveBlur,
+ "--c1": finalColors.c1,
+ "--c2": finalColors.c2,
+ "--c3": finalColors.c3,
+ "--c4": finalColors.c4,
+ "--contrast-amount": finalContrast,
+ "--dot-size": `${dotSize}px`,
+ "--drift-duration": `${driftDuration}s`,
+ "--mask-radius": maskRadius,
+ "--rim": `${rim}px`,
+ "--shadow-spread": `${shadowSpread}px`,
+ // Saturation and hue only affect the gradient disc. Applying them
+ // to the whole component would desaturate the semantic accent too,
+ // and `error` would lose the very red that identifies it.
+ filter: `saturate(${stateMotion.saturation}) hue-rotate(${stateMotion.hueRotate}deg)`,
+ height: "100%",
+ scale: reactiveScale,
+ width: "100%",
+ } as MotionStyle
+ }
+ >
+ {/* Specular sheen and depth rim. The mesh alone reads as a flat blurred
+ disc; a drifting highlight plus a lit top edge and shaded bottom are
+ what make it read as a sphere. */}
+ <span aria-hidden="true" className="agent-orb-layer agent-orb-sheen" />
+ <span aria-hidden="true" className="agent-orb-layer agent-orb-rim" />
+ <style>{`
+ @property --angle {
+ syntax: "<angle>";
+ inherits: false;
+ initial-value: 0deg;
+ }
+
+ .agent-orb {
+ display: grid;
+ grid-template-areas: "stack";
+ overflow: hidden;
+ border-radius: 50%;
+ position: relative;
+ isolation: isolate;
+ }
+
+ .agent-orb::before,
+ .agent-orb::after,
+ .agent-orb > .agent-orb-layer {
+ content: "";
+ display: block;
+ grid-area: stack;
+ width: 100%;
+ height: 100%;
+ border-radius: 50%;
+ }
+
+ /* Glassy highlight that drifts, so the sheen never sits still enough to
+ read as a printed-on gradient. */
+ .agent-orb-sheen {
+ background:
+ radial-gradient(circle at 30% 24%, hsl(0 0% 100% / 0.32), transparent 34%),
+ radial-gradient(circle at 72% 80%, hsl(0 0% 100% / 0.07), transparent 48%);
+ mix-blend-mode: screen;
+ animation: agent-drift var(--drift-duration) ease-in-out infinite alternate;
+ }
+
+ /* Lit top edge, shaded bottom, thin inner ring. */
+ .agent-orb-rim {
+ box-shadow:
+ inset 0 0 0 1px hsl(0 0% 100% / 0.16),
+ inset 0 calc(var(--rim) * 1) calc(var(--rim) * 2) hsl(0 0% 100% / 0.22),
+ inset 0 calc(var(--rim) * -1.2) calc(var(--rim) * 2.4) hsl(0 0% 0% / 0.4);
+ pointer-events: none;
+ }
+
+ @keyframes agent-drift {
+ 0% { transform: translate(-6%, -4%) scale(1.05); }
+ 100% { transform: translate(7%, 6%) scale(1.12); }
+ }
+
+ .agent-orb::before {
+ background:
+ conic-gradient(
+ from calc(var(--angle) * 2) at 25% 70%,
+ var(--c3),
+ transparent 20% 80%,
+ var(--c3)
+ ),
+ conic-gradient(
+ from calc(var(--angle) * 2) at 45% 75%,
+ var(--c2),
+ transparent 30% 60%,
+ var(--c2)
+ ),
+ conic-gradient(
+ from calc(var(--angle) * -3) at 80% 20%,
+ var(--c1),
+ transparent 40% 60%,
+ var(--c1)
+ ),
+ conic-gradient(
+ from calc(var(--angle) * 1.5) at 60% 35%,
+ var(--c4),
+ transparent 25% 75%,
+ var(--c4)
+ ),
+ conic-gradient(
+ from calc(var(--angle) * 2) at 15% 5%,
+ var(--c2),
+ transparent 10% 90%,
+ var(--c2)
+ ),
+ conic-gradient(
+ from calc(var(--angle) * 1) at 20% 80%,
+ var(--c1),
+ transparent 10% 90%,
+ var(--c1)
+ ),
+ conic-gradient(
+ from calc(var(--angle) * -2) at 85% 10%,
+ var(--c3),
+ transparent 20% 80%,
+ var(--c3)
+ );
+ box-shadow: inset var(--bg) 0 0 var(--shadow-spread)
+ calc(var(--shadow-spread) * 0.2);
+ /* The saturate() pass is what keeps the colour alive after the blur
+ and the overlaid dot pattern have both eaten into it. */
+ filter: blur(var(--blur-amount)) contrast(var(--contrast-amount))
+ saturate(1.4);
+ animation: rotate var(--animation-duration) linear infinite;
+ }
+
+ .agent-orb::after {
+ background-image: radial-gradient(
+ circle at center,
+ var(--bg) var(--dot-size),
+ transparent var(--dot-size)
+ );
+ background-size: calc(var(--dot-size) * 2) calc(var(--dot-size) * 2);
+ backdrop-filter: blur(calc(var(--blur-amount) * 2))
+ contrast(calc(var(--contrast-amount) * 2));
+ mix-blend-mode: overlay;
+ }
+
+ /* Apply mask only when radius is greater than 0 */
+ .agent-orb[style*="--mask-radius: 0%"]::after {
+ mask-image: none;
+ }
+
+ .agent-orb:not([style*="--mask-radius: 0%"])::after {
+ mask-image: radial-gradient(
+ black var(--mask-radius),
+ transparent 75%
+ );
+ }
+
+ @keyframes rotate {
+ to {
+ --angle: 360deg;
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .agent-orb::before,
+ .agent-orb-sheen {
+ animation: none;
+ }
+ }
+ `}</style>
+ </motion.div>
+ </motion.div>
+ );
+};
+
+export default AgentOrb;
diff --git a/app/src/components/agents/orb/ai-core.tsx b/app/src/components/agents/orb/ai-core.tsx
new file mode 100644
index 00000000..a1f13a63
--- /dev/null
+++ b/app/src/components/agents/orb/ai-core.tsx
@@ -0,0 +1,395 @@
+"use client";
+
+import {
+ type MotionValue,
+ useAnimationFrame,
+ useMotionValue,
+} from "motion/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+/**
+ * The single state contract shared by every SmoothUI AI component.
+ *
+ * Passing the same value to an orb, a prompt input and a tool card makes the
+ * whole surface move as one organism instead of a set of independent widgets.
+ */
+export type AIState =
+ | "idle"
+ | "listening"
+ | "thinking"
+ | "streaming"
+ | "done"
+ | "error";
+
+/**
+ * A behavioural hint each component expresses **in its own material**.
+ *
+ * Deliberately not an overlay. Bolting one shared graphic onto every orb makes
+ * four different materials look like the same widget wearing a costume, and it
+ * pushes literal iconography (a checkmark, a warning ring) onto pieces that are
+ * decorative by nature. Instead: a shader warps, a canvas ring loses harmonics,
+ * a character changes expression. Same vocabulary, different flesh.
+ */
+export type AIStateMotif =
+ | "breathe"
+ | "receive"
+ | "scan"
+ | "pulse"
+ | "ping"
+ | "fault";
+
+/** Semantic accent applied on top of the component's own palette. */
+export type AIStateAccent = "success" | "danger" | null;
+
+/** Motion parameters a component reads to render a given {@link AIState}. */
+export type AIStateMotion = {
+ /** Semantic colour override, so status is carried by hue and not only motion. */
+ accent: AIStateAccent;
+ /** Outer bloom strength, 0–1. */
+ glow: number;
+ /** Palette hue rotation in degrees. Small shifts read as a mood change. */
+ hueRotate: number;
+ /** Overall motion energy, 0–1. Scales ambient loops and displacement. */
+ intensity: number;
+ /** Behavioural hint; each component expresses it in its own material. */
+ motif: AIStateMotif;
+ /** Seconds between discrete pulses, for rhythmic behaviour. */
+ pulseSeconds: number;
+ /**
+ * How far a shader's domain warp pushes the field, 0–1. Low values read as a
+ * calm surface; high values churn without the silhouette growing.
+ */
+ turbulence: number;
+ /** Revolutions per second of the noise field — the slow tumble. */
+ tumble: number;
+ /** How much external amplitude reaches the surface, 0 = ignore it. */
+ reactivity: number;
+ /** Chroma multiplier. Below 1 desaturates. */
+ saturation: number;
+ /** Resting scale of the surface, 1 = no change. */
+ scale: number;
+ /** Ambient loop speed multiplier, 1 = the component's base tempo. */
+ speed: number;
+};
+
+/**
+ * Per-state presets.
+ *
+ * Deliberate choices worth keeping:
+ * - `thinking` has `scale: 1` — internal churn only, so layout stays calm while
+ * the model works. Growing the surface here makes pages feel unstable.
+ * - `error` desaturates instead of growing, so it reads as a state change
+ * rather than an attention grab.
+ * - `done` overshoots once; components are expected to settle back to `idle`.
+ * - Each state owns a distinct `motif`, so the six states are told apart by
+ * what moves, not by how fast it moves.
+ */
+export const AI_STATE_MOTION: Record<AIState, AIStateMotion> = {
+ done: {
+ accent: "success",
+ glow: 0.7,
+ hueRotate: 0,
+ intensity: 0.4,
+ motif: "ping",
+ pulseSeconds: 0.65,
+ reactivity: 0,
+ saturation: 1,
+ scale: 1.1,
+ speed: 0.8,
+ // The field settles almost flat — stillness is what reads as "finished".
+ tumble: 0.02,
+ turbulence: 0.08,
+ },
+ error: {
+ accent: "danger",
+ glow: 0.25,
+ hueRotate: 0,
+ intensity: 0.5,
+ motif: "fault",
+ pulseSeconds: 0.9,
+ reactivity: 0,
+ saturation: 0.3,
+ scale: 0.96,
+ speed: 1,
+ // Tumble stalls while turbulence stays mid: the surface twitches in place
+ // instead of flowing, which is what a fault feels like.
+ tumble: 0,
+ turbulence: 0.55,
+ },
+ idle: {
+ accent: null,
+ glow: 0.15,
+ hueRotate: 0,
+ intensity: 0.3,
+ motif: "breathe",
+ pulseSeconds: 4.5,
+ reactivity: 0,
+ saturation: 0.75,
+ scale: 0.94,
+ speed: 0.6,
+ tumble: 0.012,
+ turbulence: 0.14,
+ },
+ listening: {
+ accent: null,
+ glow: 0.6,
+ hueRotate: 0,
+ intensity: 0.75,
+ motif: "receive",
+ pulseSeconds: 1.6,
+ reactivity: 1,
+ saturation: 1.05,
+ scale: 1.06,
+ speed: 1,
+ tumble: 0.03,
+ turbulence: 0.42,
+ },
+ streaming: {
+ accent: null,
+ glow: 0.45,
+ hueRotate: -10,
+ intensity: 0.6,
+ motif: "pulse",
+ pulseSeconds: 1.25,
+ reactivity: 0.6,
+ saturation: 1,
+ scale: 1.02,
+ speed: 1.4,
+ tumble: 0.06,
+ turbulence: 0.5,
+ },
+ thinking: {
+ accent: null,
+ glow: 0.35,
+ hueRotate: 18,
+ intensity: 1,
+ motif: "scan",
+ pulseSeconds: 1.1,
+ reactivity: 0.15,
+ saturation: 1,
+ scale: 1,
+ speed: 2.4,
+ // High churn, unchanged silhouette: the work is visible without the orb
+ // growing and unsettling the layout around it.
+ tumble: 0.14,
+ turbulence: 0.95,
+ },
+};
+
+/** Semantic accents. Deliberately not tokens — orbs render outside a theme. */
+export const AI_ACCENT_COLORS: Record<"success" | "danger", string> = {
+ danger: "oklch(63% 0.21 25)",
+ success: "oklch(72% 0.17 150)",
+};
+
+/**
+ * Colour used by a state's overlay motif: the semantic accent when the state
+ * has one, otherwise the component's own secondary colour.
+ */
+export const getAIStateAccentColor = (
+ state: AIState | undefined,
+ fallback: string,
+): string => {
+ const accent = AI_STATE_MOTION[state ?? "idle"]?.accent;
+ return accent ? AI_ACCENT_COLORS[accent] : fallback;
+};
+
+/** Motion preset for a state, falling back to `idle` for unknown values. */
+export const getAIStateMotion = (state: AIState | undefined): AIStateMotion =>
+ AI_STATE_MOTION[state ?? "idle"] ?? AI_STATE_MOTION.idle;
+
+/**
+ * Amplitude accepted by every reactive AI component.
+ *
+ * A `MotionValue` is the preferred form: it updates outside React, so a 60fps
+ * audio signal never triggers a re-render.
+ */
+export type AIAmplitude = number | MotionValue<number> | undefined;
+
+const isMotionValue = (value: AIAmplitude): value is MotionValue<number> =>
+ typeof value === "object" && value !== null && "get" in value;
+
+/**
+ * Normalises the `amplitude` prop into a stable `MotionValue<number>` so
+ * component internals only deal with one shape.
+ */
+export const useAmplitudeValue = (
+ amplitude: AIAmplitude,
+): MotionValue<number> => {
+ const fallback = useMotionValue(0);
+ const numeric = typeof amplitude === "number" ? amplitude : null;
+
+ useEffect(() => {
+ if (numeric !== null) {
+ fallback.set(numeric);
+ }
+ }, [numeric, fallback]);
+
+ return isMotionValue(amplitude) ? amplitude : fallback;
+};
+
+export type AudioAmplitudeStatus =
+ | "idle"
+ | "requesting"
+ | "active"
+ | "denied"
+ | "unsupported";
+
+export type UseAudioAmplitudeOptions = {
+ /** Request microphone access as soon as the hook mounts. */
+ autoStart?: boolean;
+ /**
+ * Envelope smoothing, 0–1. Higher is smoother and lazier; the default keeps
+ * attack snappy so an orb reacts on the first syllable.
+ */
+ smoothing?: number;
+ /** FFT size handed to the analyser node. Must be a power of two. */
+ fftSize?: number;
+};
+
+export type UseAudioAmplitudeResult = {
+ /** Smoothed RMS level, 0–1, as a `MotionValue`. */
+ amplitude: MotionValue<number>;
+ status: AudioAmplitudeStatus;
+ start: () => Promise<void>;
+ stop: () => void;
+};
+
+const DEFAULT_SMOOTHING = 0.55;
+const DEFAULT_FFT_SIZE = 512;
+/** Raw RMS rarely exceeds ~0.3 for speech, so normalise into a usable 0–1. */
+const RMS_TO_UNIT = 3.2;
+/** Attack is faster than release so peaks land immediately and decay gently. */
+const ATTACK_FACTOR = 0.35;
+
+/**
+ * Reads microphone loudness as a 0–1 `MotionValue`.
+ *
+ * SSR-safe, permission-aware, and silent on failure — a denied prompt leaves
+ * the amplitude at 0 so the consuming component simply falls back to its
+ * ambient animation.
+ */
+export const useAudioAmplitude = (
+ options: UseAudioAmplitudeOptions = {},
+): UseAudioAmplitudeResult => {
+ const {
+ autoStart = false,
+ smoothing = DEFAULT_SMOOTHING,
+ fftSize = DEFAULT_FFT_SIZE,
+ } = options;
+
+ const amplitude = useMotionValue(0);
+ const [status, setStatus] = useState<AudioAmplitudeStatus>("idle");
+
+ const contextRef = useRef<AudioContext | null>(null);
+ const streamRef = useRef<MediaStream | null>(null);
+ const analyserRef = useRef<AnalyserNode | null>(null);
+ const bufferRef = useRef<Float32Array<ArrayBuffer> | null>(null);
+
+ const stop = useCallback(() => {
+ for (const track of streamRef.current?.getTracks() ?? []) {
+ track.stop();
+ }
+ streamRef.current = null;
+ analyserRef.current = null;
+ bufferRef.current = null;
+ contextRef.current?.close();
+ contextRef.current = null;
+ amplitude.set(0);
+ setStatus("idle");
+ }, [amplitude]);
+
+ const start = useCallback(async () => {
+ if (analyserRef.current) {
+ return;
+ }
+
+ const AudioContextCtor =
+ typeof window === "undefined"
+ ? undefined
+ : (window.AudioContext ??
+ (window as unknown as { webkitAudioContext?: typeof AudioContext })
+ .webkitAudioContext);
+
+ if (!(AudioContextCtor && navigator.mediaDevices?.getUserMedia)) {
+ setStatus("unsupported");
+ return;
+ }
+
+ setStatus("requesting");
+
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ const context = new AudioContextCtor();
+ const analyser = context.createAnalyser();
+ analyser.fftSize = fftSize;
+ context.createMediaStreamSource(stream).connect(analyser);
+
+ streamRef.current = stream;
+ contextRef.current = context;
+ analyserRef.current = analyser;
+ bufferRef.current = new Float32Array(analyser.fftSize);
+ setStatus("active");
+ } catch {
+ setStatus("denied");
+ }
+ }, [fftSize]);
+
+ useEffect(() => {
+ if (autoStart) {
+ start();
+ }
+ return stop;
+ }, [autoStart, start, stop]);
+
+ useAnimationFrame(() => {
+ const analyser = analyserRef.current;
+ const buffer = bufferRef.current;
+ if (!(analyser && buffer)) {
+ return;
+ }
+
+ analyser.getFloatTimeDomainData(buffer);
+
+ let sumOfSquares = 0;
+ for (const sample of buffer) {
+ sumOfSquares += sample * sample;
+ }
+ const rms = Math.sqrt(sumOfSquares / buffer.length);
+ const target = Math.min(1, rms * RMS_TO_UNIT);
+
+ const previous = amplitude.get();
+ const factor = target > previous ? smoothing * ATTACK_FACTOR : smoothing;
+ amplitude.set(previous + (target - previous) * (1 - factor));
+ });
+
+ return { amplitude, start, status, stop };
+};
+
+/**
+ * Amplitude generator for demos, docs and previews — no microphone involved.
+ *
+ * Produces a plausible speech-like envelope whose energy follows the current
+ * {@link AIState}, so every example can show the reactive behaviour without
+ * asking the visitor for permissions.
+ */
+export const useSimulatedAmplitude = (
+ state: AIState = "idle",
+): MotionValue<number> => {
+ const amplitude = useMotionValue(0);
+ const motion = getAIStateMotion(state);
+
+ useAnimationFrame((time) => {
+ const t = time / 1000;
+ // Three detuned sines read as organic; a single sine reads as a metronome.
+ const envelope =
+ 0.5 +
+ 0.3 * Math.sin(t * 2.1 * motion.speed) +
+ 0.14 * Math.sin(t * 5.3 * motion.speed + 1.7) +
+ 0.06 * Math.sin(t * 11.7 * motion.speed + 0.4);
+
+ amplitude.set(Math.min(1, Math.max(0, envelope * motion.intensity)));
+ });
+
+ return amplitude;
+};
diff --git a/app/src/components/app-sidebar/app-sidebar.tsx b/app/src/components/app-sidebar/app-sidebar.tsx
new file mode 100644
index 00000000..eed28233
--- /dev/null
+++ b/app/src/components/app-sidebar/app-sidebar.tsx
@@ -0,0 +1,384 @@
+import {
+ IconBolt,
+ IconLogout,
+ IconPlus,
+ IconSearch,
+ IconSettings,
+ IconShieldLock,
+ IconBox,
+} from "@tabler/icons-react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Link, type LinkOptions, useNavigate } from "@tanstack/react-router";
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+import type * as React from "react";
+import { useState } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@/components/ui/input-group";
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarGroup,
+ SidebarHeader,
+ SidebarMenu,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarRail,
+} from "@/components/ui/sidebar";
+import { signOutMutationOptions } from "@/lib/auth/mutations";
+import { currentUserQueryOptions } from "@/lib/auth/queries";
+import {
+ type ChannelSummary,
+ channelListQueryOptions,
+} from "@/lib/channels/queries";
+import { useChannelEvents } from "@/lib/channels/use-channel-events";
+import { appConfig } from "@/lib/generated/application-config";
+import { Button } from "../ui/button";
+import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
+import { Channel } from "./channel";
+
+const appLinkOptions = { to: "/" } satisfies LinkOptions;
+const adminLinkOptions = { to: "/admin" } satisfies LinkOptions;
+const settingsLinkOptions = { to: "/settings" } satisfies LinkOptions;
+
+const userMenuItemClassName = "gap-2 px-2 py-1.5";
+
+function UserAvatar() {
+ const { data: currentUser } = useQuery(currentUserQueryOptions());
+ const initials =
+ currentUser?.name
+ ?.trim()
+ .split(/\s+/)
+ .slice(0, 2)
+ .map((part) => part[0]?.toUpperCase())
+ .join("") ?? currentUser?.email.slice(0, 2).toUpperCase();
+
+ return (
+ <div className="size-[28px] bg-muted-foreground/10 text-foreground/70 rounded-full flex items-center justify-center text-xs overflow-hidden">
+ {initials}
+ </div>
+ );
+}
+
+/**
+ * Cap layout animation because `layout` measures every animated row on each reorder.
+ */
+const MAX_ANIMATED_ROWS = 60;
+
+const ENTRANCE_SECONDS = 0.2;
+const EASE_OUT = [0.23, 1, 0.32, 1] as const;
+
+/**
+ * The roster, narrowed to what the person typed.
+ *
+ * Matches the channel's name and the last thing said in it, because those are the two things the
+ * row actually shows — searching against something invisible returns results a person cannot
+ * account for. Message history beyond the last line is not here to search: it lives in the thread
+ * store, and reaching for it is a server endpoint rather than a filter.
+ *
+ * An empty query returns the input array unchanged rather than a copy, so typing and clearing does
+ * not hand `AnimatePresence` a new array identity and restage the whole list.
+ */
+function matchingChannels(
+ channels: ChannelSummary[] | undefined,
+ query: string,
+): ChannelSummary[] {
+ if (!channels) {
+ return [];
+ }
+ const needle = query.trim().toLowerCase();
+ if (!needle) {
+ return channels;
+ }
+ return channels.filter((channel) =>
+ [channel.name, channel.lastMessage].some((field) =>
+ field?.toLowerCase().includes(needle),
+ ),
+ );
+}
+
+/**
+ * A roster row that can animate.
+ *
+ * Two movements only: a channel that did not exist fades in, and a channel that was just spoken in
+ * moves to the top. Nothing else animates, a roster that reacts to being read is a roster that
+ * moves under the cursor.
+ */
+function ChannelRow({
+ channel,
+ animateOrder,
+}: {
+ channel: ChannelSummary;
+ animateOrder: boolean;
+}) {
+ const shouldReduceMotion = useReducedMotion();
+ return (
+ <motion.div
+ animate={{ opacity: 1, transform: "translateY(0px)" }}
+ initial={{
+ opacity: 0,
+ transform: shouldReduceMotion ? "none" : "translateY(-8px)",
+ }}
+ exit={{ opacity: 0 }}
+ layout={animateOrder && !shouldReduceMotion ? "position" : false}
+ transition={{ duration: ENTRANCE_SECONDS, ease: EASE_OUT }}
+ >
+ <Channel
+ channelId={channel.id}
+ participantIds={channel.agentIds}
+ name={channel.name}
+ lastMessage={channel.lastMessage ?? undefined}
+ lastMessageAt={
+ channel.lastMessageAt
+ ? relativeTime(channel.lastMessageAt)
+ : undefined
+ }
+ />
+ </motion.div>
+ );
+}
+
+export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
+ const { data: currentUser } = useQuery(currentUserQueryOptions());
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const signOut = useMutation(signOutMutationOptions(queryClient));
+ const channels = useQuery(channelListQueryOptions());
+ // One socket for the app, opened where the roster is kept live.
+ useChannelEvents();
+ const [search, setSearch] = useState("");
+ const searching = search.trim().length > 0;
+ const visibleChannels = matchingChannels(channels.data, search);
+ /*
+ * FILTERING DOES NOT ANIMATE. Rows exit and relayout on every keystroke otherwise, which is a
+ * list thrashing under somebody who is still typing — and the moving target is the very thing
+ * they are trying to read. Order animation is for a channel that was just spoken in, which is
+ * occasional; this is not.
+ */
+ const animateOrder =
+ !searching && (channels.data?.length ?? 0) <= MAX_ANIMATED_ROWS;
+
+ const handleSignOut = async () => {
+ await signOut.mutateAsync();
+ await navigate({ to: "/sign" });
+ };
+
+ return (
+ <Sidebar {...props}>
+ <SidebarHeader className="h-12 p-2">
+ <SidebarMenu>
+ <SidebarMenuItem className="flex flex-row gap-1.5">
+ <SidebarMenuButton
+ className="font-semibold text-[14px] tracking-tighter h-full leading-tight"
+ render={(props) => (
+ <Link {...appLinkOptions} {...props}>
+ {appConfig.brand.productName}
+ </Link>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ render={(props) => (
+ <Link
+ {...props}
+ to="/channel/new"
+ activeProps={{
+ className: "bg-foreground/5",
+ }}
+ />
+ )}
+ >
+ <IconPlus />
+ </Button>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarHeader>
+ <SidebarContent className="scroll-fade-b">
+ <SidebarMenu>
+ <SidebarGroup className="gap-px">
+ <SidebarMenuItem>
+ <InputGroup className="bg-background text-sm rounded-lg h-9">
+ <InputGroupInput
+ aria-label="Search channels"
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder="Search..."
+ value={search}
+ />
+ <InputGroupAddon>
+ <IconSearch />
+ </InputGroupAddon>
+ </InputGroup>
+ </SidebarMenuItem>
+ <div className="w-full h-2" />
+ {/*
+ * TWO DIFFERENT NOTHINGS, AND SAYING THE WRONG ONE IS ALARMING. A roster nobody has
+ * used yet needs telling how to start. A roster that simply does not match what is in
+ * the box has to say so and quote it back — told "you don't have channels yet" while
+ * holding a typo, a person reads their conversations as gone.
+ */}
+ {searching && visibleChannels.length === 0 ? (
+ <div className="py-4">
+ <Empty className="border border-dashed min-h-[40dvh]">
+ <EmptyHeader>
+ <EmptyTitle>No channels match your search</EmptyTitle>
+ <EmptyDescription className="text-pretty">
+ Nothing here is named “{search.trim()}”, and nobody has
+ said it recently either.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </div>
+ ) : null}
+ {!searching && channels.data?.length === 0 ? (
+ <div className="py-4">
+ <Empty className="border border-dashed min-h-[40dvh]">
+ <EmptyHeader>
+ <EmptyTitle>You don't have channels yet</EmptyTitle>
+ <EmptyDescription className="text-pretty">
+ Start talking to agents and your channels will appear
+ here.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </div>
+ ) : null}
+ <AnimatePresence initial={false}>
+ {visibleChannels.map((channel) => (
+ <ChannelRow
+ key={channel.id}
+ animateOrder={animateOrder}
+ channel={channel}
+ />
+ ))}
+ </AnimatePresence>
+ </SidebarGroup>
+ </SidebarMenu>
+ </SidebarContent>
+ <SidebarFooter>
+ <SidebarMenu className="gap-px">
+ <SidebarMenuItem>
+ {/* Beside Agents rather than inside Admin: writing a skill is something anybody does. */}
+ <SidebarMenuButton
+ className="hover:bg-foreground/5 h-10"
+ render={(props) => (
+ <Link
+ {...props}
+ to="/skills"
+ activeProps={{
+ className: "bg-foreground/5",
+ }}
+ />
+ )}
+ >
+ <div className="size-[28px] flex items-center justify-center">
+ <IconBox />
+ </div>
+ <span className="text-sm trackint-tight">Skills</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ className="hover:bg-foreground/5 h-10"
+ render={(props) => (
+ <Link
+ {...props}
+ to="/agents"
+ activeProps={{
+ className: "bg-foreground/5",
+ }}
+ />
+ )}
+ >
+ <div className="size-[28px] flex items-center justify-center">
+ <IconBolt />
+ </div>
+ <span className="text-sm trackint-tight">Agents</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ <SidebarMenuItem>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <SidebarMenuButton className="hover:bg-foreground/5 h-10" />
+ }
+ >
+ <UserAvatar />
+ <span className="text-sm trackint-tight">
+ {currentUser?.name || currentUser?.email}
+ </span>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="p-1.5"
+ side="top"
+ sideOffset={8}
+ >
+ {/* Admin routes are server-guarded; hide the entry for users who cannot open them. */}
+ {currentUser?.role === "admin" ? (
+ <DropdownMenuItem
+ className={userMenuItemClassName}
+ render={<Link {...adminLinkOptions} />}
+ >
+ <IconShieldLock />
+ Admin
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem
+ className={userMenuItemClassName}
+ render={<Link {...settingsLinkOptions} />}
+ >
+ <IconSettings />
+ Settings
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className={userMenuItemClassName}
+ disabled={signOut.isPending}
+ onClick={handleSignOut}
+ variant="destructive"
+ >
+ <IconLogout />
+ Log out
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuItem>
+ </SidebarMenu>
+ </SidebarFooter>
+ <SidebarRail />
+ </Sidebar>
+ );
+}
+
+const RELATIVE_UNITS = [
+ { limit: 60_000, divisor: 1_000, unit: "second" },
+ { limit: 3_600_000, divisor: 60_000, unit: "minute" },
+ { limit: 86_400_000, divisor: 3_600_000, unit: "hour" },
+ { limit: 604_800_000, divisor: 86_400_000, unit: "day" },
+ { limit: Number.POSITIVE_INFINITY, divisor: 604_800_000, unit: "week" },
+] as const;
+
+const relativeFormat = new Intl.RelativeTimeFormat(undefined, {
+ numeric: "auto",
+});
+
+/** Locale-aware relative timestamp, e.g. "2 minutes ago". */
+function relativeTime(iso: string) {
+ const elapsed = Date.now() - new Date(iso).getTime();
+ const scale =
+ RELATIVE_UNITS.find(({ limit }) => Math.abs(elapsed) < limit) ??
+ RELATIVE_UNITS[RELATIVE_UNITS.length - 1];
+ return relativeFormat.format(
+ -Math.round(elapsed / scale.divisor),
+ scale.unit,
+ );
+}
diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx
new file mode 100644
index 00000000..8f26fa7c
--- /dev/null
+++ b/app/src/components/channels/channel-chat.tsx
@@ -0,0 +1,342 @@
+import type { Message } from "@ag-ui/core";
+import {
+ UseAgentUpdate,
+ useAgent,
+ useCopilotKit,
+} from "@copilotkit/react-core/v2";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { toAgentOptions } from "@/components/channels/composer";
+import { ConversationView } from "@/components/channels/conversation-view";
+import {
+ seedMessage,
+ takeFirstMessage,
+ transcriptMessages,
+} from "@/components/channels/transcript-messages";
+import { agentListQueryOptions } from "@/lib/agents/queries";
+import { recordChannelActivityMutationOptions } from "@/lib/channels/mutations";
+import type { AgentChannel } from "@/lib/channels/queries";
+import { useActiveBot } from "@/lib/copilot/active-bot";
+import { ConversationProvider } from "@/lib/copilot/conversation";
+import { repairUnansweredToolCalls } from "@/lib/copilot/repair-history";
+import { useSkillCommands } from "@/lib/plugins/skill-commands";
+
+/**
+ * Backstop for the first message of a new channel; a stalled join must not lose the message.
+ */
+const SEND_WITHOUT_JOIN_AFTER_MS = 1500;
+
+/**
+ * One channel's conversation with one teammate.
+ *
+ * The local agent id is channel-scoped so two channels with the same teammate keep separate
+ * durable threads.
+ */
+export function ChannelChat({
+ channel,
+ runtimeAgentId,
+}: {
+ channel: AgentChannel;
+ runtimeAgentId: string;
+}) {
+ // The core attaches the frontend tool registry; direct agent runs do not.
+ const { copilotkit } = useCopilotKit();
+ // Mentions are scoped to the channel's permitted agents.
+ const { data: agentProfiles } = useQuery(agentListQueryOptions());
+ const { agent, isReady } = useAgent({
+ agentId: `channel:${channel.id}`,
+ runtimeAgentId,
+ threadId: channel.threadId,
+ updates: [
+ UseAgentUpdate.OnMessagesChanged,
+ UseAgentUpdate.OnRunStatusChanged,
+ ],
+ });
+
+ /**
+ * First-message seed from the compose screen. It is taken once per mount and retained until the
+ * agent has its own messages because joining a fresh thread can temporarily empty the agent.
+ */
+ const [seed] = useState<Message | null>(() => {
+ const pending = takeFirstMessage(channel.id);
+ return pending ? seedMessage(pending, crypto.randomUUID()) : null;
+ });
+
+ /** Cleared by the send-on-mount effect without restarting it. */
+ const seedRef = useRef(seed);
+ seedRef.current = seed;
+
+ /** Promise gate for ordering the first message after the thread join when possible. */
+ const openJoinGate = useRef<() => void>(() => {});
+ const joinGate = useRef<Promise<void> | null>(null);
+ if (joinGate.current === null) {
+ joinGate.current = new Promise<void>((resolve) => {
+ openJoinGate.current = resolve;
+ });
+ }
+ const joinGatePromise = joinGate.current;
+
+ /** Promise gate so messages typed before runtime readiness wait instead of being discarded. */
+ const openReadyGate = useRef<() => void>(() => {});
+ const readyGate = useRef<Promise<void> | null>(null);
+ if (readyGate.current === null) {
+ readyGate.current = new Promise<void>((resolve) => {
+ openReadyGate.current = resolve;
+ });
+ }
+ const readyGatePromise = readyGate.current;
+ const isReadyRef = useRef(isReady);
+ isReadyRef.current = isReady;
+ useEffect(() => {
+ if (isReady) openReadyGate.current();
+ }, [isReady]);
+
+ // Join the gateway socket, restore durable history, then release the first-message gate.
+ useEffect(() => {
+ if (!isReady) return;
+ let current = true;
+
+ void (async () => {
+ try {
+ await copilotkit.connectAgent({ agent });
+ } catch {
+ // Reported by the run-failure subscriber below; history is still worth restoring.
+ }
+
+ try {
+ const response = await fetch(
+ `/api/copilotkit/threads/${encodeURIComponent(channel.threadId)}/messages?agentId=${encodeURIComponent(runtimeAgentId)}`,
+ { credentials: "include" },
+ );
+ if (response.ok && current) {
+ const stored = (await response.json())?.messages;
+ // Never overwrite local messages that arrived while history was loading.
+ if (
+ Array.isArray(stored) &&
+ stored.length > 0 &&
+ agent.messages.length === 0
+ ) {
+ agent.setMessages(stored);
+ }
+ }
+ } catch {
+ // An unreadable history is not a reason to block the composer.
+ } finally {
+ // Release even on join/restore failure; the gate orders messages, not withholds them.
+ openJoinGate.current();
+ }
+ })();
+
+ return () => {
+ current = false;
+ };
+ }, [copilotkit, agent, isReady, channel.threadId, runtimeAgentId]);
+
+ // Tool calls from this conversation act on this teammate's own computer.
+ useActiveBot(runtimeAgentId);
+
+ const skillCommands = useSkillCommands(runtimeAgentId);
+
+ // Run failures arrive as events and are reported only for turns started in this mount.
+ const [runError, setRunError] = useState<string | null>(null);
+ const awaitingReply = useRef(false);
+
+ /**
+ * Tell the roster what was just said. Failures here must not block the conversation.
+ */
+ const recordActivity = useMutation(recordChannelActivityMutationOptions());
+ const report = (text: string, agentId: string | null) => {
+ const trimmed = text.trim();
+ if (!trimmed) return;
+ recordActivity.mutate({
+ agentId,
+ at: new Date().toISOString(),
+ channelId: channel.id,
+ text: trimmed,
+ });
+ };
+ const reportRef = useRef(report);
+ reportRef.current = report;
+
+ /**
+ * Send a user turn through the channel, including activity reporting and history repair.
+ */
+ const say = async (text: string, skillInstructions: string[] = []) => {
+ const trimmed = text.trim();
+ if (!trimmed) return;
+
+ // Wait briefly for the runtime agent instance before adding the message.
+ if (!isReadyRef.current) {
+ await Promise.race([
+ readyGatePromise,
+ new Promise((resolve) =>
+ setTimeout(resolve, SEND_WITHOUT_JOIN_AFTER_MS),
+ ),
+ ]);
+ }
+
+ setRunError(null);
+ awaitingReply.current = true;
+
+ /*
+ * THE SKILL GOES IN FRONT OF THE MESSAGE, AS A SYSTEM TURN. A `/` chip is one token in the
+ * composer; what it stands for is the instruction added here, ahead of what the person typed, so
+ * the Bot reads the job before the request.
+ *
+ * A system message rather than text prepended to theirs, because the two are not the same kind
+ * of thing: the transcript should show what a person said, and pasting the skill into their
+ * words puts sentences in their mouth and makes the reply quote instructions back at them.
+ *
+ * `transcriptMessages` draws user and assistant turns, so this never appears on screen — the
+ * chip is what says a skill was used, and it stays visible in the message they sent.
+ */
+ for (const instruction of skillInstructions) {
+ agent.addMessage({
+ content: instruction,
+ id: crypto.randomUUID(),
+ role: "system",
+ });
+ }
+
+ agent.addMessage({
+ content: trimmed,
+ id: crypto.randomUUID(),
+ role: "user",
+ });
+ report(trimmed, null);
+
+ // Providers reject later turns if prior tool calls have no result; repair before sending.
+ const repaired = repairUnansweredToolCalls(agent.messages);
+ if (repaired !== agent.messages) {
+ agent.setMessages(repaired as typeof agent.messages);
+ }
+
+ await copilotkit.runAgent({ agent });
+ };
+
+ useEffect(() => {
+ const fail = (message: string) => {
+ if (!awaitingReply.current) return;
+ awaitingReply.current = false;
+ setRunError(message);
+ };
+ const subscription = agent.subscribe?.({
+ onRunErrorEvent: ({ event }) =>
+ fail(event?.message ?? "The Bot stopped without saying why."),
+ onRunFailed: ({ error }) =>
+ fail(
+ error instanceof Error
+ ? error.message
+ : "The Bot stopped without saying why.",
+ ),
+ onRunFinishedEvent: () => {
+ const wasOurs = awaitingReply.current;
+ awaitingReply.current = false;
+ if (!wasOurs) return;
+
+ const reply = [...agent.messages]
+ .reverse()
+ .find((message) => message.role === "assistant");
+ const content = typeof reply?.content === "string" ? reply.content : "";
+ if (content) reportRef.current(content, runtimeAgentId);
+ },
+ });
+ return () => subscription?.unsubscribe();
+ }, [agent, runtimeAgentId]);
+
+ /** Stable reference for effects and component callbacks. */
+ const sayRef = useRef(say);
+ sayRef.current = say;
+
+ /**
+ * Component buttons speak as user turns without forcing every transcript card to re-render.
+ */
+ const askFromComponent = useCallback((text: string) => {
+ void sayRef.current(text);
+ }, []);
+
+ /**
+ * Send the create-channel seed once, after the join gate opens or the backstop expires.
+ */
+ useEffect(() => {
+ const pending = seedRef.current;
+ if (!pending) return;
+ seedRef.current = null;
+
+ void (async () => {
+ await Promise.race([
+ joinGatePromise,
+ new Promise((resolve) =>
+ setTimeout(resolve, SEND_WITHOUT_JOIN_AFTER_MS),
+ ),
+ ]);
+ await sayRef.current(
+ typeof pending.content === "string" ? pending.content : "",
+ );
+ })();
+
+ // Keep `seed` in state; transcriptMessages hides it as soon as agent messages exist.
+ }, [joinGatePromise]);
+
+ return (
+ <ConversationProvider ask={askFromComponent}>
+ <ConversationView
+ agents={toAgentOptions(agentProfiles, channel.agentIds)}
+ busy={agent.isRunning}
+ // The `/` menu exposes only skills granted to this Bot.
+ commands={skillCommands}
+ // Readiness is handled by `say`; deletion is the only disabled-chat state.
+ disabled={!channel.active}
+ messages={transcriptMessages(agent.messages, seed)}
+ notice={
+ <>
+ {runError ? (
+ <p
+ className="pb-2 text-sm text-destructive"
+ data-testid="channel-run-error"
+ role="alert"
+ >
+ {runError}
+ </p>
+ ) : null}
+ {channel.active ? null : (
+ <p className="pb-2 text-sm text-muted-foreground" role="status">
+ This teammate has been deleted. The conversation stays readable,
+ but it can no longer reply.
+ </p>
+ )}
+ </>
+ }
+ onSubmit={async (draft) => {
+ // `draft.agentId` carries the @mentioned teammate, but nothing routes on it yet: this
+ // channel is pinned to one `runtimeAgentId` for the life of its thread, so honouring a
+ // per-message mention is a change to that binding, not to the composer.
+ //
+ // `commandIds` are the `/` chips that survived into the send, in the order they were
+ // typed. Resolved against the same list the menu was built from, so a chip left over from
+ // a skill that has since been revoked resolves to nothing rather than to a stale
+ // instruction — the menu is refetched, and this reads from it.
+ const skillInstructions = draft.commandIds
+ .map(
+ (id) =>
+ skillCommands.find((command) => command.id === id)?.prompt,
+ )
+ .filter((instruction): instruction is string =>
+ Boolean(instruction),
+ );
+
+ await say(draft.text, skillInstructions);
+ }}
+ /**
+ * Stop through the core so the abort signal reaches frontend tools; `say` repairs any
+ * unanswered tool call before the next turn.
+ */
+ onStop={() => {
+ awaitingReply.current = false;
+ copilotkit.stopAgent({ agent });
+ }}
+ pending={agent.isRunning}
+ />
+ </ConversationProvider>
+ );
+}
diff --git a/app/src/components/channels/composer/draft.ts b/app/src/components/channels/composer/draft.ts
new file mode 100644
index 00000000..bfd4a2ef
--- /dev/null
+++ b/app/src/components/channels/composer/draft.ts
@@ -0,0 +1,133 @@
+import {
+ getChipsByTrigger,
+ isSegmentsEmpty,
+ mergeAdjacentTextSegments,
+ type Segment,
+ segmentsToPlainText,
+ text,
+} from "prompt-area/helpers";
+
+/**
+ * Pure boundary between prompt-area segments and OpenBot's message draft model.
+ */
+
+export const AGENT_TRIGGER = "@";
+export const COMMAND_TRIGGER = "/";
+
+export type ComposerDraft = {
+ /** Plain text, with chips flattened back to `@Agent` / `/command`. */
+ text: string;
+ /**
+ * The single agent this message is addressed to, or `null` to let the channel pick its default.
+ *
+ * Exactly one responding agent per message, which is enforced on the
+ * way in by `enforceSingleAgent` rather than validated here.
+ */
+ agentId: string | null;
+ /** Commands that survive into the sent message, in the order they were typed. */
+ commandIds: string[];
+ isEmpty: boolean;
+};
+
+export function toDraft(segments: Segment[]): ComposerDraft {
+ const agentChips = getChipsByTrigger(segments, AGENT_TRIGGER);
+ const commandChips = getChipsByTrigger(segments, COMMAND_TRIGGER);
+
+ return {
+ text: segmentsToPlainText(segments).trim(),
+ agentId: agentChips.at(-1)?.value ?? null,
+ commandIds: commandChips.map((chip) => chip.value),
+ isEmpty: isSegmentsEmpty(segments),
+ };
+}
+
+/** Collapse multiple agent mentions to the most recent one while preserving identity on no-op. */
+export function enforceSingleAgent(segments: Segment[]): Segment[] {
+ const agentChipCount = getChipsByTrigger(segments, AGENT_TRIGGER).length;
+ if (agentChipCount <= 1) {
+ return segments;
+ }
+
+ let remaining = agentChipCount;
+ const kept = segments.filter((segment) => {
+ if (segment.type !== "chip" || segment.trigger !== AGENT_TRIGGER) {
+ return true;
+ }
+ remaining -= 1;
+ return remaining === 0;
+ });
+
+ return mergeAdjacentTextSegments(kept);
+}
+
+/**
+ * What a `/command` does once it has been picked from the dropdown.
+ *
+ * - `chip` keeps the chip in the message, so the runtime receives it as structured data.
+ * - `prompt` expands into editable text, for the channel's seeded suggested prompts.
+ * - `action` runs client-side and never reaches the runtime.
+ *
+ * prompt-area always resolves a dropdown selection into a chip, so `prompt` and `action` are
+ * applied here on the next change instead of being special-cased inside the editor.
+ */
+export type CommandKind = "chip" | "prompt" | "action";
+
+export type CommandOption = {
+ id: string;
+ name: string;
+ description?: string;
+ /** Defaults to `chip`. */
+ kind?: CommandKind;
+ /** Text substituted for the command when `kind` is `prompt`. */
+ prompt?: string;
+ /** Side effect run when `kind` is `action`. */
+ run?: () => void;
+};
+
+export type AppliedCommands = {
+ segments: Segment[];
+ /** Actions to run after the new segments are committed to state. */
+ actions: (() => void)[];
+};
+
+/**
+ * Rewrites `prompt` and `action` command chips, leaving `chip` commands (and everything else)
+ * alone. Side effects are returned rather than run so the transform stays pure and testable.
+ */
+export function applyCommandChips(
+ segments: Segment[],
+ commands: readonly CommandOption[],
+): AppliedCommands {
+ const byId = new Map(commands.map((command) => [command.id, command]));
+ const actions: (() => void)[] = [];
+ let changed = false;
+
+ const rewritten = segments.flatMap<Segment>((segment) => {
+ if (segment.type !== "chip" || segment.trigger !== COMMAND_TRIGGER) {
+ return [segment];
+ }
+
+ const command = byId.get(segment.value);
+ const kind = command?.kind ?? "chip";
+
+ if (kind === "prompt") {
+ changed = true;
+ return command?.prompt ? [text(command.prompt)] : [];
+ }
+
+ if (kind === "action") {
+ changed = true;
+ if (command?.run) {
+ actions.push(command.run);
+ }
+ return [];
+ }
+
+ return [segment];
+ });
+
+ return {
+ segments: changed ? mergeAdjacentTextSegments(rewritten) : segments,
+ actions,
+ };
+}
diff --git a/app/src/components/channels/conversation-view.tsx b/app/src/components/channels/conversation-view.tsx
new file mode 100644
index 00000000..fcb5d6d6
--- /dev/null
+++ b/app/src/components/channels/conversation-view.tsx
@@ -0,0 +1,71 @@
+import type { Message } from "@ag-ui/core";
+import type { ReactNode } from "react";
+import { ChatTranscript } from "@/components/channels/chat-transcript";
+import {
+ type AgentOption,
+ type CommandOption,
+ Composer,
+ type ComposerDraft,
+} from "@/components/channels/composer";
+
+export function ConversationView({
+ messages,
+ busy = false,
+ notice,
+ agents = [],
+ commands,
+ disabled = false,
+ pending = false,
+ onSubmit,
+ onStop,
+}: {
+ messages: readonly Message[];
+ busy?: boolean;
+ /** Shown above the composer. An error, or why this conversation is read-only. */
+ notice?: ReactNode;
+ agents?: readonly AgentOption[];
+ /**
+ * The `/` menu for this Bot's granted skills, supplied by the route that owns grant loading.
+ */
+ commands?: readonly CommandOption[];
+ disabled?: boolean;
+ pending?: boolean;
+ onSubmit: (draft: ComposerDraft) => void | Promise<void>;
+ /** Stop the Bot mid-answer; forwarded to turn the send button into a stop button. */
+ onStop?: () => void;
+}) {
+ return (
+ <div className="flex flex-col flex-1 min-h-0">
+ <div className="flex flex-1 min-h-0">
+ {/*
+ * The command NAMES, joined, rather than the option objects.
+ *
+ * The transcript needs them only to tell a real skill chip from a message that happens to
+ * begin with a slash, and its message rows are memoised on primitives — handing them an
+ * array would give every message a new prop identity on each refetch and re-render the whole
+ * conversation to change nothing.
+ */}
+ <ChatTranscript
+ busy={busy}
+ commandNames={(commands ?? [])
+ .map((command) => command.name)
+ .join(",")}
+ messages={messages}
+ />
+ </div>
+ <div className="max-w-2xl mx-auto w-full px-0 pb-4 shrink-0">
+ {notice}
+ <Composer
+ agents={agents}
+ {...(commands ? { commands } : {})}
+ className="w-full mt-auto"
+ compact
+ disabled={disabled}
+ onStop={onStop}
+ onSubmit={onSubmit}
+ pending={pending}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/app/src/components/channels/tool-boundary.tsx b/app/src/components/channels/tool-boundary.tsx
new file mode 100644
index 00000000..c53d6082
--- /dev/null
+++ b/app/src/components/channels/tool-boundary.tsx
@@ -0,0 +1,40 @@
+import { Component, type ReactNode } from "react";
+
+/**
+ * A component that throws must not take the conversation with it.
+ *
+ * Browser-authored components render in the transcript from model-supplied arguments, sometimes
+ * while a tool call is still streaming. A render failure is isolated to the component card and shown
+ * as a user-readable failure line; stacks stay in the developer console.
+ */
+export class ToolRenderBoundary extends Component<
+ { name: string; children: ReactNode },
+ { failed: boolean }
+> {
+ state = { failed: false };
+
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+
+ componentDidCatch(error: unknown) {
+ // Keep stack details out of the conversation while preserving them for component authors.
+ console.error(
+ "[gallery] a component failed to render",
+ this.props.name,
+ error,
+ );
+ }
+
+ render() {
+ if (this.state.failed) {
+ return (
+ <p className="my-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
+ <span className="font-medium">{this.props.name}</span> could not be
+ drawn. The rest of this conversation is unaffected.
+ </p>
+ );
+ }
+ return this.props.children;
+ }
+}
diff --git a/app/src/components/channels/tool-line.tsx b/app/src/components/channels/tool-line.tsx
new file mode 100644
index 00000000..643907f1
--- /dev/null
+++ b/app/src/components/channels/tool-line.tsx
@@ -0,0 +1,78 @@
+import type { ReactNode } from "react";
+
+/**
+ * One line for one thing a Bot did.
+ *
+ * Every tool call in the transcript draws through this, so a browser action, an MCP call and a
+ * refusal read as the same kind of event. Detail stays behind a disclosure so the transcript keeps a
+ * single-line action rhythm.
+ *
+ * While it is still running the text shimmers, which is the only signal that the Bot is working on
+ * something with nothing to show yet.
+ */
+export function ToolLine({
+ label,
+ detail,
+ running,
+ refused,
+ failed,
+ children,
+}: {
+ /** What was done, in a couple of words: "Searched Slack", "Filled in", "Read the page". */
+ label: string;
+ /** What it was done to. Muted, and truncated rather than wrapped. */
+ detail?: string;
+ running?: boolean;
+ /** A policy or a boundary said no. Final: nothing the Bot does differently will help. */
+ refused?: boolean;
+ /** It was permitted and did not work. A different request might. */
+ failed?: boolean;
+ /** Shown when the line is expanded. Without it the line is not expandable. */
+ children?: ReactNode;
+}) {
+ const tone = refused
+ ? "text-destructive"
+ : failed
+ ? "text-amber-600 dark:text-amber-500"
+ : "text-muted-foreground";
+
+ const text = (
+ <span
+ className={`inline-flex min-w-0 max-w-full items-baseline gap-1.5 text-sm ${tone} ${
+ running ? "tool-line-running" : ""
+ }`}
+ >
+ <span className="shrink-0">
+ {refused ? "Blocked" : failed ? `${label}, didn't work` : label}
+ </span>
+ {detail ? <span className="truncate opacity-70">{detail}</span> : null}
+ </span>
+ );
+
+ if (!children) return <div className="my-1.5">{text}</div>;
+
+ return (
+ <details className="tool-line my-1.5 min-w-0">
+ {/*
+ * Native <details> owns expansion because SDK tool renderers can be re-invoked independently
+ * of this component's React state.
+ */}
+ <summary className="flex cursor-pointer list-none items-baseline gap-1.5">
+ <span
+ aria-hidden
+ className="tool-line-chevron shrink-0 text-xs text-muted-foreground transition-transform"
+ >
+ ▸
+ </span>
+ {text}
+ </summary>
+ {/*
+ * Headings are cut down to the size of the surrounding text. A tool result is markdown a
+ * server wrote for a model, so its `#` is a section marker rather than a page title.
+ */}
+ <div className="mt-2 max-h-80 overflow-auto border-l pl-3 text-xs [&_h1]:text-sm [&_h2]:text-xs [&_h3]:text-xs [&_h4]:text-xs [&_h1]:font-medium [&_h2]:font-medium [&_h3]:font-medium">
+ {children}
+ </div>
+ </details>
+ );
+}
diff --git a/app/src/components/channels/transcript-messages.ts b/app/src/components/channels/transcript-messages.ts
new file mode 100644
index 00000000..25737ed1
--- /dev/null
+++ b/app/src/components/channels/transcript-messages.ts
@@ -0,0 +1,46 @@
+import type { Message } from "@ag-ui/core";
+
+/**
+ * What a transcript shows while a brand-new channel is still joining.
+ *
+ * Channel join replaces the agent's local messages with restored thread history. The first message
+ * is held here as a seed until restored messages arrive, then ignored to avoid duplicate rendering.
+ */
+export function transcriptMessages(
+ messages: readonly Message[],
+ seed: Message | null,
+): readonly Message[] {
+ if (messages.length > 0 || seed === null) {
+ return messages;
+ }
+ return [seed];
+}
+
+/** The person's message, in the shape the transcript and the agent both take. */
+export function seedMessage(text: string, id: string): Message {
+ return { id, role: "user", content: text };
+}
+
+/**
+ * The message a channel was created by, waiting for the screen that will send it.
+ *
+ * A module-level map rather than router state because `HistoryState` is an empty interface and
+ * typing a value into it means augmenting `@tanstack/history`, which is not a dependency of this
+ * app. It also earns something router state would not give: taking is destructive, so a component
+ * that mounts twice cannot send the same message twice.
+ *
+ * Deliberately not persisted. A reload finds nothing here, which is correct, by then the message
+ * is in the thread and arrives through the normal replay.
+ */
+const firstMessages = new Map<string, string>();
+
+export function stashFirstMessage(channelId: string, text: string): void {
+ firstMessages.set(channelId, text);
+}
+
+/** Read the pending first message and forget it. Null for a channel opened any other way. */
+export function takeFirstMessage(channelId: string): string | null {
+ const text = firstMessages.get(channelId) ?? null;
+ firstMessages.delete(channelId);
+ return text;
+}
diff --git a/app/src/components/computer/placeholder.tsx b/app/src/components/computer/placeholder.tsx
new file mode 100644
index 00000000..57dfab79
--- /dev/null
+++ b/app/src/components/computer/placeholder.tsx
@@ -0,0 +1,162 @@
+import type { SVGProps } from "react";
+
+/**
+ * Decorative waiting artwork for the fixed-size computer frame.
+ */
+export function ComputerPlaceholder(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ viewBox="0 0 1200 800"
+ preserveAspectRatio="xMidYMin slice"
+ fill="none"
+ aria-hidden="true"
+ focusable="false"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g clipPath="url(#clip0_2002_10)">
+ <path fill="#fff" d="M0 0H1200V800H0z" />
+ <path fill="url(#paint0_linear_2002_10)" d="M0 0H1200V754H0z" />
+ <g
+ opacity={0.93}
+ filter="url(#filter0_n_2002_10)"
+ style={{
+ mixBlendMode: "lighten",
+ }}
+ >
+ <path
+ transform="rotate(180 1201 754)"
+ fill="url(#paint1_radial_2002_10)"
+ d="M1201 754H2402V1509H1201z"
+ />
+ </g>
+ <g
+ filter="url(#filter1_n_2002_10)"
+ style={{
+ mixBlendMode: "color-burn",
+ }}
+ >
+ <path fill="#F0F0F0" fillOpacity={0.84} d="M0 0H1200V754H0z" />
+ </g>
+ </g>
+ <defs>
+ <filter
+ id="filter0_n_2002_10"
+ x={0}
+ y={-1}
+ width={1201}
+ height={755}
+ filterUnits="userSpaceOnUse"
+ colorInterpolationFilters="sRGB"
+ >
+ <feFlood floodOpacity={0} result="BackgroundImageFix" />
+ <feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
+ <feTurbulence
+ type="fractalNoise"
+ baseFrequency="0.76923078298568726 0.76923078298568726"
+ stitchTiles="stitch"
+ numOctaves={3}
+ result="noise"
+ seed={2673}
+ />
+ <feComponentTransfer in="noise" result="coloredNoise1">
+ <feFuncR type="linear" slope={2} intercept={-0.5} />
+ <feFuncG type="linear" slope={2} intercept={-0.5} />
+ <feFuncB type="linear" slope={2} intercept={-0.5} />
+ <feFuncA
+ type="discrete"
+ tableValues="1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"
+ />
+ </feComponentTransfer>
+ <feComposite
+ operator="in"
+ in2="shape"
+ in="coloredNoise1"
+ result="noise1Clipped"
+ />
+ <feComponentTransfer in="noise1Clipped" result="color1">
+ <feFuncA type="table" tableValues="0 0.15" />
+ </feComponentTransfer>
+ <feMerge result="effect1_noise_2002_10">
+ <feMergeNode in="shape" />
+ <feMergeNode in="color1" />
+ </feMerge>
+ </filter>
+ <filter
+ id="filter1_n_2002_10"
+ x={0}
+ y={0}
+ width={1200}
+ height={754}
+ filterUnits="userSpaceOnUse"
+ colorInterpolationFilters="sRGB"
+ >
+ <feFlood floodOpacity={0} result="BackgroundImageFix" />
+ <feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
+ <feTurbulence
+ type="fractalNoise"
+ baseFrequency="2 2"
+ stitchTiles="stitch"
+ numOctaves={3}
+ result="noise"
+ seed={7521}
+ />
+ <feColorMatrix
+ in="noise"
+ type="luminanceToAlpha"
+ result="alphaNoise"
+ />
+ <feComponentTransfer in="alphaNoise" result="coloredNoise1">
+ <feFuncA
+ type="discrete"
+ tableValues="1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"
+ />
+ </feComponentTransfer>
+ <feComposite
+ operator="in"
+ in2="shape"
+ in="coloredNoise1"
+ result="noise1Clipped"
+ />
+ <feFlood floodColor="rgba(0, 0, 0, 0.25)" result="color1Flood" />
+ <feComposite
+ operator="in"
+ in2="noise1Clipped"
+ in="color1Flood"
+ result="color1"
+ />
+ <feMerge result="effect1_noise_2002_10">
+ <feMergeNode in="shape" />
+ <feMergeNode in="color1" />
+ </feMerge>
+ </filter>
+ <linearGradient
+ id="paint0_linear_2002_10"
+ x1={1200}
+ y1={-53.8571}
+ x2={-274.518}
+ y2={423.589}
+ gradientUnits="userSpaceOnUse"
+ >
+ <stop stopColor="#FFB8E7" />
+ <stop offset={1} stopColor="#2EE297" />
+ </linearGradient>
+ <radialGradient
+ id="paint1_radial_2002_10"
+ cx={0}
+ cy={0}
+ r={1}
+ gradientTransform="matrix(229.838 -1654.36 2337.29 481.415 2278.37 2408.36)"
+ gradientUnits="userSpaceOnUse"
+ >
+ <stop offset={0.420388} stopColor="#9DF200" />
+ <stop offset={0.66} stopColor="#0099A9" />
+ <stop offset={1} stopColor="#fff" />
+ </radialGradient>
+ <clipPath id="clip0_2002_10">
+ <path fill="#fff" d="M0 0H1200V800H0z" />
+ </clipPath>
+ </defs>
+ </svg>
+ );
+}
diff --git a/app/src/components/computer/take-the-wheel.ts b/app/src/components/computer/take-the-wheel.ts
new file mode 100644
index 00000000..725a443a
--- /dev/null
+++ b/app/src/components/computer/take-the-wheel.ts
@@ -0,0 +1,110 @@
+/**
+ * Computer control API helpers and screenshot-to-page coordinate conversion.
+ */
+
+export type ControlState = {
+ holder: "bot" | "human";
+ since: string;
+ reason?: string;
+ requested: boolean;
+ /** What the Bot is waiting for, by name only. Present means show the masked prompt. */
+ secretWanted?: string;
+};
+
+async function callControl(
+ computerId: string,
+ path: string,
+ init?: RequestInit,
+): Promise<ControlState | null> {
+ const response = await fetch(`/api/computers/${computerId}${path}`, {
+ credentials: "include",
+ ...init,
+ });
+ if (!response.ok) return null;
+ return (await response.json()) as ControlState;
+}
+
+export function readControl(computerId: string) {
+ return callControl(computerId, "/control");
+}
+
+export function takeControl(computerId: string) {
+ return callControl(computerId, "/control/take", { method: "POST" });
+}
+
+export function releaseControl(computerId: string) {
+ return callControl(computerId, "/control/release", { method: "POST" });
+}
+
+/**
+ * Supply a secret synchronously and never echo the value back to the UI.
+ */
+export async function supplySecret(
+ computerId: string,
+ text: string,
+): Promise<{ ok: boolean; error?: string }> {
+ try {
+ const response = await fetch(`/api/computers/${computerId}/human/secret`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ text }),
+ });
+ if (response.ok) return { ok: true };
+ const body = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+ return { ok: false, error: body?.error ?? "That could not be entered." };
+ } catch {
+ return {
+ ok: false,
+ error: "The assistant's computer could not be reached.",
+ };
+ }
+}
+
+/**
+ * Serializes human input requests without blocking the caller; ordering matters for typed secrets.
+ */
+let inputQueue: Promise<unknown> = Promise.resolve();
+
+/**
+ * Send one human input event. Returns immediately; delivery is ordered.
+ */
+export function sendHumanInput(
+ computerId: string,
+ kind: "click" | "type" | "key" | "scroll",
+ body: Record<string, unknown>,
+): void {
+ inputQueue = inputQueue
+ .then(() =>
+ fetch(`/api/computers/${computerId}/human/${kind}`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ )
+ // Fire-and-forget: the user can see/retry input failures, while the input queue must keep moving.
+ .catch(() => undefined);
+}
+
+/**
+ * Convert display coordinates on a scaled screenshot into browser viewport coordinates.
+ */
+export function pageCoordinates(
+ image: { naturalWidth: number; naturalHeight: number },
+ rect: { left: number; top: number; width: number; height: number },
+ event: { clientX: number; clientY: number },
+): { x: number; y: number } | null {
+ if (!rect.width || !rect.height) return null;
+ if (!image.naturalWidth || !image.naturalHeight) return null;
+
+ const withinX = event.clientX - rect.left;
+ const withinY = event.clientY - rect.top;
+
+ return {
+ x: Math.round((withinX / rect.width) * image.naturalWidth),
+ y: Math.round((withinY / rect.height) * image.naturalHeight),
+ };
+}
diff --git a/app/src/components/gallery/charts.tsx b/app/src/components/gallery/charts.tsx
new file mode 100644
index 00000000..6ea488e8
--- /dev/null
+++ b/app/src/components/gallery/charts.tsx
@@ -0,0 +1,450 @@
+import { z } from "zod";
+import type { GalleryComponent } from "@/lib/copilot/gallery-registry";
+import { GalleryFrame } from "./frame";
+import { seriesColour } from "./palette";
+
+const point = z.object({
+ label: z
+ .string()
+ .describe("What this point is called, e.g. a month or a team"),
+ value: z.number().describe("Its value"),
+});
+
+const common = {
+ title: z.string().describe("A short title for the chart"),
+ caption: z
+ .string()
+ .optional()
+ .describe(
+ "One line under the title saying what the reader should take from it",
+ ),
+};
+
+/** Charts share a height so several in one answer do not stagger down the page. */
+const HEIGHT = 180;
+
+function formatNumber(value: number): string {
+ if (Math.abs(value) >= 1000) {
+ return value.toLocaleString(undefined, { maximumFractionDigits: 0 });
+ }
+ return String(Math.round(value * 100) / 100);
+}
+
+/** Nothing to draw is a sentence. An empty axis reads as a component that failed. */
+function Empty() {
+ return (
+ <p className="py-10 text-center text-sm text-muted-foreground">
+ There is no data to chart.
+ </p>
+ );
+}
+
+function Legend({ items }: { items: { label: string; colour: string }[] }) {
+ return (
+ <ul className="mt-3 flex flex-wrap gap-x-4 gap-y-1">
+ {items.map((item) => (
+ <li className="flex items-center gap-1.5 text-xs" key={item.label}>
+ <span
+ className="size-2 shrink-0 rounded-[3px]"
+ style={{ background: item.colour }}
+ />
+ <span className="text-muted-foreground">{item.label}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+export const BarChartProps = z.object({
+ ...common,
+ points: z
+ .array(point)
+ .describe("One bar per point, in the order they should appear"),
+});
+
+export function BarChartCard({
+ title,
+ caption,
+ points: given,
+}: Partial<z.infer<typeof BarChartProps>>) {
+ const points = given ?? [];
+ const max = Math.max(...points.map((entry) => entry.value ?? 0), 0);
+ return (
+ <GalleryFrame caption={caption} title={title}>
+ {points.length === 0 ? (
+ <Empty />
+ ) : (
+ // Columns stretch to full row height so percentage bar heights use the chart area.
+ <div className="flex items-stretch gap-2" style={{ height: HEIGHT }}>
+ {points.map((entry, index) => (
+ <div
+ className="flex min-w-0 flex-1 flex-col items-center justify-end gap-1.5"
+ key={entry.label}
+ >
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {formatNumber(entry.value)}
+ </span>
+ {/* The bar lives in its own flexible box so the number above and the label below keep
+ their natural height and only the bar itself scales. */}
+ <div className="flex w-full flex-1 items-end">
+ <div
+ className="w-full rounded-t-md transition-[height]"
+ style={{
+ // Normalize to the largest bar so similar values still show their differences.
+ height:
+ max > 0
+ ? `${Math.max((entry.value / max) * 100, 2)}%`
+ : "2%",
+ background: seriesColour(index),
+ }}
+ />
+ </div>
+ <span className="w-full truncate text-center text-xs text-muted-foreground">
+ {entry.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </GalleryFrame>
+ );
+}
+
+export const PieChartProps = z.object({
+ ...common,
+ points: z
+ .array(point)
+ .describe("One slice per point. Values are summed to make the whole"),
+});
+
+export function PieChartCard({
+ title,
+ caption,
+ points: given,
+}: Partial<z.infer<typeof PieChartProps>>) {
+ const points = given ?? [];
+ const size = 160;
+ const stroke = 28;
+ const radius = (size - stroke) / 2;
+ const circumference = 2 * Math.PI * radius;
+ const total = points.reduce((sum, entry) => sum + (entry.value || 0), 0);
+
+ let travelled = 0;
+ const slices = points.map((entry, index) => {
+ const arc = total > 0 ? (entry.value / total) * circumference : 0;
+ const slice = {
+ ...entry,
+ arc,
+ offset: -travelled,
+ colour: seriesColour(index),
+ };
+ travelled += arc;
+ return slice;
+ });
+
+ return (
+ <GalleryFrame caption={caption} title={title}>
+ {points.length === 0 || total <= 0 ? (
+ <Empty />
+ ) : (
+ <div className="flex flex-wrap items-center gap-6">
+ {/* One circle per slice: dasharray controls length and dashoffset controls start. */}
+ <svg
+ aria-hidden="true"
+ className="shrink-0 -rotate-90"
+ height={size}
+ viewBox={`0 0 ${size} ${size}`}
+ width={size}
+ >
+ {slices.map((slice) => (
+ <circle
+ cx={size / 2}
+ cy={size / 2}
+ fill="none"
+ key={slice.label}
+ r={radius}
+ stroke={slice.colour}
+ strokeDasharray={`${slice.arc} ${circumference - slice.arc}`}
+ strokeDashoffset={slice.offset}
+ strokeWidth={stroke}
+ />
+ ))}
+ </svg>
+ <ul className="min-w-0 flex-1 space-y-1.5">
+ {slices.map((slice) => (
+ <li className="flex items-center gap-2 text-sm" key={slice.label}>
+ <span
+ className="size-2.5 shrink-0 rounded-[3px]"
+ style={{ background: slice.colour }}
+ />
+ <span className="min-w-0 flex-1 truncate">{slice.label}</span>
+ <span className="tabular-nums text-muted-foreground">
+ {Math.round((slice.value / total) * 100)}%
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </GalleryFrame>
+ );
+}
+
+/* -------------------------------------------------------------------------- Line and area */
+
+const seriesSchema = z.object({
+ name: z.string().describe("What this line is called"),
+ values: z
+ .array(z.number())
+ .describe("One value per label, in the same order"),
+});
+
+export const LineChartProps = z.object({
+ ...common,
+ labels: z.array(z.string()).describe("The x axis, e.g. months"),
+ series: z.array(seriesSchema).describe("One line per series"),
+});
+
+type LineArgs = z.infer<typeof LineChartProps>;
+
+/**
+ * Line and area are the same geometry, so they are the same function.
+ *
+ * Sharing the scaler keeps line and area charts aligned.
+ */
+function Plot({
+ labels,
+ series,
+ filled,
+}: { labels: string[]; series: { name: string; values: number[] }[] } & {
+ filled: boolean;
+}) {
+ const width = 520;
+ const height = HEIGHT;
+ const pad = { top: 8, right: 8, bottom: 18, left: 8 };
+
+ const all = series.flatMap((line) => line.values);
+ const max = Math.max(...all, 0);
+ const min = Math.min(...all, 0);
+ const span = max - min || 1;
+ const steps = Math.max(labels.length - 1, 1);
+
+ const xAt = (index: number) =>
+ pad.left + (index / steps) * (width - pad.left - pad.right);
+ const yAt = (value: number) =>
+ pad.top + (1 - (value - min) / span) * (height - pad.top - pad.bottom);
+
+ return (
+ <>
+ <svg
+ aria-hidden="true"
+ className="w-full"
+ height={height}
+ preserveAspectRatio="none"
+ viewBox={`0 0 ${width} ${height}`}
+ >
+ {/* Two guide lines give slope context without turning the chart into a grid. */}
+ {[0.5, 1].map((fraction) => (
+ <line
+ className="stroke-border"
+ key={fraction}
+ strokeDasharray="3 3"
+ x1={pad.left}
+ x2={width - pad.right}
+ y1={pad.top + fraction * (height - pad.top - pad.bottom)}
+ y2={pad.top + fraction * (height - pad.top - pad.bottom)}
+ />
+ ))}
+ {series.map((line, index) => {
+ const points = line.values.map(
+ (value, i) => `${xAt(i)},${yAt(value)}`,
+ );
+ const colour = seriesColour(index);
+ return (
+ <g key={line.name}>
+ {filled ? (
+ <polygon
+ fill={colour}
+ fillOpacity={0.14}
+ points={`${xAt(0)},${height - pad.bottom} ${points.join(" ")} ${xAt(line.values.length - 1)},${height - pad.bottom}`}
+ />
+ ) : null}
+ <polyline
+ fill="none"
+ points={points.join(" ")}
+ stroke={colour}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ />
+ </g>
+ );
+ })}
+ </svg>
+ <div className="flex justify-between">
+ {labels.map((label) => (
+ <span className="truncate text-xs text-muted-foreground" key={label}>
+ {label}
+ </span>
+ ))}
+ </div>
+ {series.length > 1 ? (
+ <Legend
+ items={series.map((line, index) => ({
+ label: line.name,
+ colour: seriesColour(index),
+ }))}
+ />
+ ) : null}
+ </>
+ );
+}
+
+export function LineChartCard(args: Partial<LineArgs>) {
+ const labels = args.labels ?? [];
+ const series = (args.series ?? []).map((line) => ({
+ name: line.name ?? "",
+ values: line.values ?? [],
+ }));
+ return (
+ <GalleryFrame caption={args.caption} title={args.title}>
+ {series.length === 0 || labels.length === 0 ? (
+ <Empty />
+ ) : (
+ <Plot filled={false} labels={labels} series={series} />
+ )}
+ </GalleryFrame>
+ );
+}
+
+export const AreaChartProps = LineChartProps;
+
+export function AreaChartCard(args: Partial<LineArgs>) {
+ const labels = args.labels ?? [];
+ const series = (args.series ?? []).map((line) => ({
+ name: line.name ?? "",
+ values: line.values ?? [],
+ }));
+ return (
+ <GalleryFrame caption={args.caption} title={args.title}>
+ {series.length === 0 || labels.length === 0 ? (
+ <Empty />
+ ) : (
+ <Plot filled labels={labels} series={series} />
+ )}
+ </GalleryFrame>
+ );
+}
+
+/* -------------------------------------------------------------------------- Progress */
+
+export const ProgressChartProps = z.object({
+ ...common,
+ points: z
+ .array(
+ point.extend({
+ target: z.number().describe("What the value is measured against"),
+ }),
+ )
+ .describe("One row per thing being tracked"),
+});
+
+/**
+ * Progress against a target, distinct from comparing independent bars.
+ */
+export function ProgressChartCard({
+ title,
+ caption,
+ points: given,
+}: Partial<z.infer<typeof ProgressChartProps>>) {
+ const points = given ?? [];
+ return (
+ <GalleryFrame caption={caption} title={title}>
+ {points.length === 0 ? (
+ <Empty />
+ ) : (
+ <ul className="space-y-3">
+ {points.map((entry, index) => {
+ const share =
+ entry.target > 0
+ ? Math.min((entry.value / entry.target) * 100, 100)
+ : 0;
+ return (
+ <li key={entry.label}>
+ <div className="flex items-baseline justify-between gap-4 text-sm">
+ <span className="min-w-0 truncate">{entry.label}</span>
+ <span className="tabular-nums text-muted-foreground">
+ {formatNumber(entry.value)} / {formatNumber(entry.target)}
+ </span>
+ </div>
+ <div className="mt-1.5 h-2 w-full overflow-hidden rounded-full bg-foreground/5">
+ <div
+ className="h-full rounded-full"
+ style={{
+ width: `${share}%`,
+ background: seriesColour(index),
+ }}
+ />
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </GalleryFrame>
+ );
+}
+
+/** Gallery component registration kept beside the chart implementations. */
+export const GALLERY: GalleryComponent[] = [
+ {
+ name: "showBarChart",
+ title: "Bar chart",
+ kind: "chart",
+ description:
+ "Show values as a bar chart. Use when comparing a handful of named things, teams, months, categories. Not for a trend over time, which is showLineChart.",
+ parameters: BarChartProps,
+ Component: BarChartCard as GalleryComponent["Component"],
+ confirmation: "The bar chart is now on screen for the person.",
+ },
+ {
+ name: "showPieChart",
+ title: "Donut chart",
+ kind: "chart",
+ description:
+ "Show how a whole is divided, as a donut with a legend. Use only when the parts sum to something meaningful, and prefer a bar chart above about six slices.",
+ parameters: PieChartProps,
+ Component: PieChartCard as GalleryComponent["Component"],
+ confirmation: "The donut chart is now on screen for the person.",
+ },
+ {
+ name: "showLineChart",
+ title: "Line chart",
+ kind: "chart",
+ description:
+ "Show one or more series over an ordered axis, usually time. Every series must have one value per label.",
+ parameters: LineChartProps,
+ Component: LineChartCard as GalleryComponent["Component"],
+ confirmation: "The line chart is now on screen for the person.",
+ },
+ {
+ name: "showAreaChart",
+ title: "Area chart",
+ kind: "chart",
+ description:
+ "The same as showLineChart with the area under each line filled. Use for volume or accumulation rather than for a rate.",
+ parameters: AreaChartProps,
+ Component: AreaChartCard as GalleryComponent["Component"],
+ confirmation: "The area chart is now on screen for the person.",
+ },
+ {
+ name: "showProgress",
+ title: "Progress against target",
+ kind: "chart",
+ description:
+ "Show values against their targets as progress bars. Use for 'are we there yet' questions, budget spent against budget, done against planned.",
+ parameters: ProgressChartProps,
+ Component: ProgressChartCard as GalleryComponent["Component"],
+ confirmation: "The progress chart is now on screen for the person.",
+ },
+];
diff --git a/app/src/components/gallery/decisions.tsx b/app/src/components/gallery/decisions.tsx
new file mode 100644
index 00000000..539d18ee
--- /dev/null
+++ b/app/src/components/gallery/decisions.tsx
@@ -0,0 +1,267 @@
+import { useState } from "react";
+import { z } from "zod";
+import { Button } from "@/components/ui/button";
+import type { GalleryComponent } from "@/lib/copilot/gallery-registry";
+import { Badge, GalleryFrame } from "./frame";
+
+/**
+ * Human-in-the-loop gallery components. `respond` resolves the suspended Bot run, and completed
+ * cards render the recorded answer rather than active controls.
+ */
+
+/** What the render props carry. Narrowed here so each component reads as its own small contract. */
+type Waiting<T> =
+ | {
+ status: "inProgress";
+ args: Partial<T>;
+ respond: undefined;
+ result: undefined;
+ }
+ | {
+ status: "executing";
+ args: T;
+ respond: (result: unknown) => Promise<void>;
+ result: undefined;
+ }
+ | { status: "complete"; args: T; respond: undefined; result: string };
+
+export const ApprovalCardProps = z.object({
+ title: z.string().describe("What is being approved, in a few words"),
+ summary: z
+ .string()
+ .describe("What the person is agreeing to, in one or two sentences"),
+ details: z
+ .array(z.object({ label: z.string(), value: z.string() }))
+ .optional()
+ .describe(
+ "The facts they need in order to decide, e.g. amount, vendor, date",
+ ),
+ approveLabel: z.string().optional().describe("Defaults to Approve"),
+ rejectLabel: z.string().optional().describe("Defaults to Decline"),
+});
+
+type ApprovalArgs = z.infer<typeof ApprovalCardProps>;
+
+export function ApprovalCard(props: Waiting<ApprovalArgs> & { name?: string }) {
+ const { args, status, respond } = props;
+ const [note, setNote] = useState("");
+ const [sending, setSending] = useState<"approved" | "declined" | null>(null);
+
+ const answer = async (decision: "approved" | "declined") => {
+ if (!respond) return;
+ setSending(decision);
+ // Include the note in the same tool result that resumes the Bot.
+ await respond({ decision, note: note.trim() || undefined });
+ };
+
+ if (status === "inProgress") {
+ return (
+ <GalleryFrame title={args.title ?? "Waiting for the assistant…"}>
+ <p className="text-sm text-muted-foreground">Preparing the request…</p>
+ </GalleryFrame>
+ );
+ }
+
+ const decided =
+ status === "complete" ? readDecision(props.result) : undefined;
+
+ return (
+ <GalleryFrame
+ action={
+ decided ? (
+ <Badge tone={decided === "approved" ? "positive" : "negative"}>
+ {decided === "approved" ? "Approved" : "Declined"}
+ </Badge>
+ ) : (
+ <Badge tone="caution">Waiting on you</Badge>
+ )
+ }
+ title={args.title}
+ >
+ <p className="text-sm">{args.summary}</p>
+
+ {args.details?.length ? (
+ <dl className="mt-3 grid grid-cols-[minmax(0,9rem)_1fr] gap-x-4 gap-y-1.5 text-sm">
+ {args.details.map((detail) => (
+ <div className="contents" key={detail.label}>
+ <dt className="truncate text-muted-foreground">{detail.label}</dt>
+ <dd className="min-w-0 break-words">{detail.value}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
+
+ {decided ? null : (
+ <div className="mt-4 space-y-2">
+ <input
+ aria-label="A reason, if you want to give one"
+ className="w-full rounded-md border border-border bg-transparent px-3 py-1.5 text-sm"
+ disabled={Boolean(sending)}
+ onChange={(event) => setNote(event.target.value)}
+ placeholder="A reason, if you want to give one"
+ value={note}
+ />
+ <div className="flex gap-2">
+ <Button
+ disabled={Boolean(sending)}
+ onClick={() => void answer("approved")}
+ size="sm"
+ >
+ {sending === "approved"
+ ? "Sending…"
+ : (args.approveLabel ?? "Approve")}
+ </Button>
+ <Button
+ disabled={Boolean(sending)}
+ onClick={() => void answer("declined")}
+ size="sm"
+ variant="outline"
+ >
+ {sending === "declined"
+ ? "Sending…"
+ : (args.rejectLabel ?? "Decline")}
+ </Button>
+ </div>
+ </div>
+ )}
+ </GalleryFrame>
+ );
+}
+
+export const ChoiceCardProps = z.object({
+ title: z.string().describe("The question being asked"),
+ summary: z
+ .string()
+ .optional()
+ .describe("Any context the person needs to choose"),
+ options: z
+ .array(
+ z.object({
+ id: z
+ .string()
+ .describe("What comes back to you when this one is picked"),
+ label: z.string(),
+ description: z.string().optional(),
+ }),
+ )
+ .describe("The options, in the order they should be offered"),
+});
+
+type ChoiceArgs = z.infer<typeof ChoiceCardProps>;
+
+export function ChoiceCard(props: Waiting<ChoiceArgs>) {
+ const { args, status, respond } = props;
+ const [sending, setSending] = useState<string | null>(null);
+
+ if (status === "inProgress") {
+ return (
+ <GalleryFrame title={args.title ?? "Waiting for the assistant…"}>
+ <p className="text-sm text-muted-foreground">Preparing the question…</p>
+ </GalleryFrame>
+ );
+ }
+
+ const chosen = status === "complete" ? readChoice(props.result) : undefined;
+
+ return (
+ <GalleryFrame
+ action={
+ chosen ? (
+ <Badge tone="positive">Answered</Badge>
+ ) : (
+ <Badge tone="caution">Waiting on you</Badge>
+ )
+ }
+ caption={args.summary}
+ title={args.title}
+ >
+ <ul className="space-y-2">
+ {(args.options ?? []).map((option) => {
+ const picked = chosen === option.id;
+ return (
+ <li key={option.id}>
+ <button
+ className={`w-full rounded-lg border px-3 py-2 text-left text-sm transition-colors ${
+ picked
+ ? "border-emerald-500/40 bg-emerald-500/10"
+ : chosen
+ ? "border-border opacity-50"
+ : "border-border hover:bg-foreground/5"
+ }`}
+ disabled={Boolean(chosen) || Boolean(sending)}
+ onClick={async () => {
+ if (!respond) return;
+ setSending(option.id);
+ await respond({ choice: option.id, label: option.label });
+ }}
+ type="button"
+ >
+ <span className="font-medium">{option.label}</span>
+ {option.description ? (
+ <span className="block text-xs text-muted-foreground">
+ {option.description}
+ </span>
+ ) : null}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </GalleryFrame>
+ );
+}
+
+/**
+ * Read completed answers defensively from the runtime's serialized tool result.
+ */
+function readResult(
+ result: string | undefined,
+): Record<string, unknown> | undefined {
+ if (!result) return undefined;
+ try {
+ const parsed = JSON.parse(result);
+ return typeof parsed === "object" && parsed !== null
+ ? (parsed as Record<string, unknown>)
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function readDecision(
+ result: string | undefined,
+): "approved" | "declined" | undefined {
+ const value = readResult(result)?.decision;
+ return value === "approved" || value === "declined" ? value : undefined;
+}
+
+function readChoice(result: string | undefined): string | undefined {
+ const value = readResult(result)?.choice;
+ return typeof value === "string" ? value : undefined;
+}
+
+/**
+ * `kind: "decision"` is what makes these suspend the run: they are registered with
+ * `useHumanInTheLoop` rather than as ordinary tools, and the person's answer IS the tool result, so
+ * there is no confirmation line to give the model.
+ */
+export const GALLERY: GalleryComponent[] = [
+ {
+ name: "askApproval",
+ title: "Approval",
+ kind: "decision",
+ description:
+ "Ask the person to approve or decline something, and WAIT for their answer. Use before doing anything you cannot undo, spending money, sending a message, changing a record. You are given their decision and any reason they typed.",
+ parameters: ApprovalCardProps,
+ Component: ApprovalCard as GalleryComponent["Component"],
+ },
+ {
+ name: "askChoice",
+ title: "Choice",
+ kind: "decision",
+ description:
+ "Ask the person to pick one of several options, and WAIT for their answer. Use when you cannot sensibly guess which one they meant. You are given the id of the option they chose.",
+ parameters: ChoiceCardProps,
+ Component: ChoiceCard as GalleryComponent["Component"],
+ },
+];
diff --git a/app/src/components/gallery/palette.ts b/app/src/components/gallery/palette.ts
new file mode 100644
index 00000000..5789fcf6
--- /dev/null
+++ b/app/src/components/gallery/palette.ts
@@ -0,0 +1,26 @@
+/**
+ * Fixed chart palette. Models do not choose series colours, so a series keeps the same colour across
+ * charts and avoids state colours such as refusal red.
+ */
+export const SERIES_COLOURS = [
+ "#6366f1",
+ "#10b981",
+ "#f59e0b",
+ "#0ea5e9",
+ "#8b5cf6",
+ "#ec4899",
+] as const;
+
+export function seriesColour(index: number): string {
+ return SERIES_COLOURS[index % SERIES_COLOURS.length] as string;
+}
+
+/**
+ * Red and green mean something. Kept out of `SERIES_COLOURS` so a chart cannot accidentally colour
+ * an ordinary series in the shade this app uses for a refusal.
+ */
+export const STATE_COLOURS = {
+ positive: "#10b981",
+ caution: "#f59e0b",
+ negative: "#ef4444",
+} as const;
diff --git a/app/src/components/layout/detail-panel.tsx b/app/src/components/layout/detail-panel.tsx
new file mode 100644
index 00000000..5328bd4a
--- /dev/null
+++ b/app/src/components/layout/detail-panel.tsx
@@ -0,0 +1,105 @@
+import { IconX } from "@tabler/icons-react";
+import { motion, useReducedMotion } from "motion/react";
+import type { ReactNode } from "react";
+import { Button } from "@/components/ui/button";
+
+/**
+ * A main pane with a detail pane that slides in beside it.
+ *
+ * The open/closed state belongs to the caller, in practice a search parameter, so opening a detail
+ * is a real navigation: it survives a reload, it can be linked to, and Back closes it.
+ *
+ * The pane is animated by width and the content inside it is given that width outright, so the
+ * content is laid out once and the pane reveals it.
+ */
+
+const ANIMATION_DURATION_SECONDS = 0.3;
+const DEFAULT_DETAIL_WIDTH = 400;
+
+/** Strong ease-out. The browser's built-in curve is too weak to read as deliberate. */
+const EASE_OUT = [0.23, 1, 0.32, 1] as const;
+
+/**
+ * The content overlaps the tail of the pane rather than following it.
+ *
+ * Delaying content slightly but ending with the pane keeps the reveal as one motion.
+ */
+const CONTENT_ENTRANCE_SECONDS = 0.18;
+const CONTENT_ENTRANCE_DELAY_SECONDS = 0.12;
+const CONTENT_ENTRANCE_OFFSET = "translateY(8px)";
+
+export function DetailPanel({
+ open,
+ onClose,
+ title,
+ detail,
+ detailWidth = DEFAULT_DETAIL_WIDTH,
+ children,
+}: {
+ open: boolean;
+ onClose: () => void;
+ /** Rendered at the left of the detail pane's header row, beside the close button. */
+ title?: ReactNode;
+ detail?: ReactNode;
+ /** Open width of the detail pane, in pixels. */
+ detailWidth?: number;
+ children: ReactNode;
+}) {
+ // Reduced motion keeps the fade, which explains the change, and drops the movement.
+ const shouldReduceMotion = useReducedMotion();
+
+ return (
+ <div className="flex h-full min-h-0">
+ <div className="flex flex-1 min-w-0 flex-col">{children}</div>
+ <motion.div
+ animate={{ width: open ? detailWidth : 0 }}
+ className="shrink-0 overflow-hidden"
+ // No entry animation on first paint: URL-opened panels should appear as initial state.
+ initial={false}
+ transition={{
+ duration: shouldReduceMotion ? 0 : ANIMATION_DURATION_SECONDS,
+ ease: EASE_OUT,
+ }}
+ >
+ <div
+ className="flex h-full flex-col bg-sidebar border-l border-border"
+ style={{ width: detailWidth }}
+ >
+ {/* Rendered for the whole animation, so the way out is available immediately. */}
+ <div className="h-12 shrink-0 sticky top-0 flex flex-row items-center justify-between px-2 gap-2">
+ <div className="flex min-w-0 w-full items-center gap-1.5">
+ {title}
+ </div>
+ <div className="flex flex-row gap-1.5">
+ <Button onClick={onClose} variant="ghost" size="icon">
+ <IconX className="size-4.5" />
+ </Button>
+ </div>
+ </div>
+ {/*
+ * Unmount while closed so dismissed form state and detail queries do not remain active.
+ */}
+ {open ? (
+ <motion.div
+ animate={{ opacity: 1, transform: "translateY(0px)" }}
+ className="flex-1 min-h-0 overflow-y-auto"
+ initial={{
+ opacity: 0,
+ transform: shouldReduceMotion
+ ? "none"
+ : CONTENT_ENTRANCE_OFFSET,
+ }}
+ transition={{
+ delay: shouldReduceMotion ? 0 : CONTENT_ENTRANCE_DELAY_SECONDS,
+ duration: CONTENT_ENTRANCE_SECONDS,
+ ease: EASE_OUT,
+ }}
+ >
+ {detail}
+ </motion.div>
+ ) : null}
+ </div>
+ </motion.div>
+ </div>
+ );
+}
diff --git a/app/src/components/layout/stagger.tsx b/app/src/components/layout/stagger.tsx
new file mode 100644
index 00000000..bdef36bd
--- /dev/null
+++ b/app/src/components/layout/stagger.tsx
@@ -0,0 +1,68 @@
+import { motion, useReducedMotion } from "motion/react";
+import type * as React from "react";
+
+import { EASE_OUT, ENTRANCE_SECONDS } from "@/lib/motion";
+
+/**
+ * A row or card arriving as part of a list.
+ *
+ * WHY A LIST ANIMATES AT ALL. A configuration screen is a stack of unrelated decisions, and when
+ * they all appear on the same frame there is nothing telling the eye where to start. A short
+ * cascade down the list does that, and nothing else — it is not decoration, and it is not here to
+ * be noticed.
+ *
+ * 40ms apart, which is the middle of the 30–80ms that reads as one movement rather than as items
+ * queueing. Past that it stops being a cascade and starts being a wait.
+ *
+ * CAPPED, because the cost of a stagger is paid by whatever is last. Twelve items at 40ms is 480ms
+ * before the final one starts; a list of forty would leave the bottom half sitting blank for two
+ * seconds while somebody is already trying to read it. Past the cap everything arrives together.
+ */
+const STAGGER_SECONDS = 0.04;
+const STAGGER_CAP = 12;
+
+/**
+ * ONLY ON MOUNT, AND THIS IS THE LOAD-BEARING PART. `initial`/`animate` run when the element
+ * mounts, and these lists re-render constantly — a grant toggled, a query refetched, a filter
+ * typed. If the entrance replayed on those, granting a plugin would make the whole page flicker.
+ * React keeps the elements mounted across those renders, so it does not.
+ *
+ * The corollary is that anything which REMOUNTS a list must not use this: switching a tab, or
+ * paging a table, would replay the cascade every time. Those lists are left alone deliberately.
+ */
+export function StaggerItem({
+ children,
+ className,
+ index,
+}: {
+ children: React.ReactNode;
+ className?: string;
+ /** Position in the list. Delay is derived from it, so it must be the render index. */
+ index: number;
+}) {
+ const shouldReduceMotion = useReducedMotion();
+ const delay = Math.min(index, STAGGER_CAP) * STAGGER_SECONDS;
+
+ return (
+ <motion.div
+ animate={{ opacity: 1, transform: "translateY(0px)" }}
+ className={className}
+ /*
+ * The full transform string rather than motion's `y` shorthand: the shorthand is not
+ * hardware accelerated and drops frames exactly when the main thread is busy, which on these
+ * screens is while the list it belongs to is still being fetched.
+ */
+ initial={{
+ opacity: 0,
+ transform: shouldReduceMotion ? "none" : "translateY(6px)",
+ }}
+ transition={{
+ delay: shouldReduceMotion ? 0 : delay,
+ duration: ENTRANCE_SECONDS,
+ ease: EASE_OUT,
+ }}
+ >
+ {children}
+ </motion.div>
+ );
+}
diff --git a/app/src/components/skills/edit-skill.tsx b/app/src/components/skills/edit-skill.tsx
new file mode 100644
index 00000000..fa26cad2
--- /dev/null
+++ b/app/src/components/skills/edit-skill.tsx
@@ -0,0 +1,99 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
+import { SkillAgents } from "@/components/skills/skill-agents";
+import { SkillFields } from "@/components/skills/skill-fields";
+import { pluginKeys, pluginsPageQueryOptions } from "@/lib/plugins/queries";
+import type { SkillFormValues } from "@/lib/skills/form";
+
+/**
+ * Editing a skill, in the same panel that writes one.
+ *
+ * THERE IS NO EDIT ENDPOINT, AND NONE IS NEEDED. `POST /api/plugins/skills` upserts on the slug:
+ * `installSkill` does `onConflictDoUpdate` and deliberately leaves `owner_user_id` alone, so a
+ * re-save changes the words and never quietly changes whose skill it is. The route has already
+ * refused anyone editing a skill that is not theirs before it gets that far.
+ */
+export function EditSkill({ slug }: { slug: string }) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const { data, isPending } = useQuery(pluginsPageQueryOptions());
+
+ /*
+ * Read from the list already on screen rather than fetched again. It is the same request the page
+ * behind this panel just made, so react-query serves it from cache and the form is filled on the
+ * first frame instead of flashing empty fields at somebody who came here to change one word.
+ */
+ const skill = data?.skills.find((candidate) => candidate.slug === slug);
+
+ const saveSkill = useMutation({
+ mutationFn: async (values: SkillFormValues) => {
+ const response = await fetch("/api/plugins/skills", {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(values),
+ });
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+ throw new Error(body?.error ?? "The skill could not be saved.");
+ }
+ return response.json();
+ },
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: pluginKeys.all }),
+ });
+
+ if (!skill) {
+ return (
+ <div className="mx-auto flex w-full max-w-xl flex-col gap-6 p-8">
+ <p className="text-muted-foreground text-sm">
+ {isPending
+ ? "Loading…"
+ : /*
+ * Said plainly rather than shown as an empty form. A skill can be missing because it
+ * was deleted in another tab, or because the link names one that is somebody else's —
+ * and an empty form here would invite them to write it back into existence under a
+ * slug they may not own.
+ */
+ "That skill no longer exists, or it is not yours to edit."}
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mx-auto flex w-full max-w-xl flex-col gap-6 p-8">
+ <header>
+ <h1 className="text-2xl font-semibold">Edit skill</h1>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Changes apply the next time <code>/{skill.slug}</code> is used. Agents
+ already carrying it keep it.
+ </p>
+ </header>
+
+ <SkillFields
+ defaultValues={{
+ slug: skill.slug,
+ title: skill.title,
+ summary: skill.summary ?? "",
+ instructions: skill.instructions,
+ }}
+ error={saveSkill.error}
+ /*
+ * Passed down rather than rendered after the form, so it lands above Save changes. Granting
+ * still saves on its own the instant a button is pressed — `SkillFields` keeps it out of the
+ * form's state and only decides where it sits.
+ */
+ footer={<SkillAgents grantedTo={skill.grantedTo} slug={skill.slug} />}
+ onSubmit={async (values) => {
+ await saveSkill.mutateAsync(values);
+ await navigate({ search: {}, to: "/skills" });
+ }}
+ slugLocked
+ submitLabel="Save changes"
+ />
+ </div>
+ );
+}
diff --git a/app/src/components/theme-provider.tsx b/app/src/components/theme-provider.tsx
new file mode 100644
index 00000000..d92a32e3
--- /dev/null
+++ b/app/src/components/theme-provider.tsx
@@ -0,0 +1,49 @@
+import {
+ createContext,
+ type ReactNode,
+ useContext,
+ useEffect,
+ useState,
+} from "react";
+import {
+ applyDarkTheme,
+ parseStoredDarkTheme,
+ THEME_STORAGE_KEY,
+} from "@/lib/theme";
+
+type ThemeContextValue = {
+ dark: boolean;
+ setDark: (dark: boolean) => void;
+};
+
+const ThemeContext = createContext<ThemeContextValue | null>(null);
+
+export function ThemeProvider({ children }: { children: ReactNode }) {
+ const [dark, setDark] = useState(() =>
+ parseStoredDarkTheme(window.localStorage.getItem(THEME_STORAGE_KEY)),
+ );
+
+ useEffect(() => {
+ applyDarkTheme(dark, {
+ setStoredValue: (key, value) => window.localStorage.setItem(key, value),
+ toggleRootClass: (name, force) =>
+ document.documentElement.classList.toggle(name, force),
+ });
+ }, [dark]);
+
+ return (
+ <ThemeContext.Provider value={{ dark, setDark }}>
+ {children}
+ </ThemeContext.Provider>
+ );
+}
+
+export function useTheme() {
+ const value = useContext(ThemeContext);
+
+ if (!value) {
+ throw new Error("useTheme must be used within ThemeProvider");
+ }
+
+ return value;
+}
diff --git a/app/src/components/ui/bubble.tsx b/app/src/components/ui/bubble.tsx
new file mode 100644
index 00000000..0b4bfe2f
--- /dev/null
+++ b/app/src/components/ui/bubble.tsx
@@ -0,0 +1,128 @@
+import * as React from "react"
+import { mergeProps } from "@base-ui/react/merge-props"
+import { useRender } from "@base-ui/react/use-render"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+
+function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="bubble-group"
+ className={cn("flex min-w-0 flex-col gap-2", className)}
+ {...props}
+ />
+ )
+}
+
+const bubbleVariants = cva(
+ "group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full",
+ {
+ variants: {
+ variant: {
+ default:
+ "*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80",
+ secondary:
+ "*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]",
+ muted:
+ "*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]",
+ tinted:
+ "*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] *:data-[slot=bubble-content]:text-foreground dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]",
+ outline:
+ "*:data-[slot=bubble-content]:border-border *:data-[slot=bubble-content]:bg-background [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30",
+ ghost:
+ "border-none *:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50",
+ destructive:
+ "*:data-[slot=bubble-content]:bg-destructive/10 *:data-[slot=bubble-content]:text-destructive dark:*:data-[slot=bubble-content]:bg-destructive/20 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+function Bubble({
+ variant = "default",
+ align = "start",
+ className,
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof bubbleVariants> & {
+ align?: "start" | "end"
+ }) {
+ return (
+ <div
+ data-slot="bubble"
+ data-variant={variant}
+ data-align={align}
+ className={cn(bubbleVariants({ variant }), className)}
+ {...props}
+ />
+ )
+}
+
+function BubbleContent({
+ className,
+ render,
+ ...props
+}: useRender.ComponentProps<"div">) {
+ return useRender({
+ defaultTagName: "div",
+ props: mergeProps<"div">(
+ {
+ className: cn(
+ "w-fit max-w-full min-w-0 overflow-hidden rounded-xl border border-transparent px-3 py-2 text-sm leading-relaxed wrap-break-word group-data-[align=end]/bubble:self-end [button]:text-left [button,a]:transition-colors [button,a]:outline-none [button,a]:focus-visible:border-ring [button,a]:focus-visible:ring-3 [button,a]:focus-visible:ring-ring/50",
+ className
+ ),
+ },
+ props
+ ),
+ render,
+ state: {
+ slot: "bubble-content",
+ },
+ })
+}
+
+const bubbleReactionsVariants = cva(
+ "absolute z-10 flex w-fit shrink-0 items-center justify-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-sm ring-3 ring-card has-[button]:p-0",
+ {
+ variants: {
+ side: {
+ top: "top-0 -translate-y-3/4",
+ bottom: "bottom-0 translate-y-3/4",
+ },
+ align: {
+ start: "left-3",
+ end: "right-3",
+ },
+ },
+ defaultVariants: {
+ side: "bottom",
+ align: "end",
+ },
+ }
+)
+
+function BubbleReactions({
+ side = "bottom",
+ align = "end",
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ align?: "start" | "end"
+ side?: "top" | "bottom"
+}) {
+ return (
+ <div
+ data-slot="bubble-reactions"
+ data-align={align}
+ data-side={side}
+ className={cn(bubbleReactionsVariants({ side, align }), className)}
+ {...props}
+ />
+ )
+}
+
+export { BubbleGroup, Bubble, BubbleContent, BubbleReactions }
diff --git a/app/src/components/ui/combobox.tsx b/app/src/components/ui/combobox.tsx
new file mode 100644
index 00000000..e8a31c6e
--- /dev/null
+++ b/app/src/components/ui/combobox.tsx
@@ -0,0 +1,297 @@
+"use client"
+
+import * as React from "react"
+import { Combobox as ComboboxPrimitive } from "@base-ui/react"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput,
+} from "@/components/ui/input-group"
+import { IconChevronDown, IconX, IconCheck } from "@tabler/icons-react"
+
+const Combobox = ComboboxPrimitive.Root
+
+function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
+ return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
+}
+
+function ComboboxTrigger({
+ className,
+ children,
+ ...props
+}: ComboboxPrimitive.Trigger.Props) {
+ return (
+ <ComboboxPrimitive.Trigger
+ data-slot="combobox-trigger"
+ className={cn("[&_svg:not([class*='size-'])]:size-4", className)}
+ {...props}
+ >
+ {children}
+ <IconChevronDown className="pointer-events-none size-4 text-muted-foreground" />
+ </ComboboxPrimitive.Trigger>
+ )
+}
+
+function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
+ return (
+ <ComboboxPrimitive.Clear
+ data-slot="combobox-clear"
+ render={<InputGroupButton variant="ghost" size="icon-xs" />}
+ className={cn(className)}
+ {...props}
+ >
+ <IconX className="pointer-events-none" />
+ </ComboboxPrimitive.Clear>
+ )
+}
+
+function ComboboxInput({
+ className,
+ children,
+ disabled = false,
+ showTrigger = true,
+ showClear = false,
+ ...props
+}: ComboboxPrimitive.Input.Props & {
+ showTrigger?: boolean
+ showClear?: boolean
+}) {
+ return (
+ <InputGroup className={cn("w-auto", className)}>
+ <ComboboxPrimitive.Input
+ render={<InputGroupInput disabled={disabled} />}
+ {...props}
+ />
+ <InputGroupAddon align="inline-end">
+ {showTrigger && (
+ <InputGroupButton
+ size="icon-xs"
+ variant="ghost"
+ render={<ComboboxTrigger />}
+ data-slot="input-group-button"
+ className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent"
+ disabled={disabled}
+ />
+ )}
+ {showClear && <ComboboxClear disabled={disabled} />}
+ </InputGroupAddon>
+ {children}
+ </InputGroup>
+ )
+}
+
+function ComboboxContent({
+ className,
+ side = "bottom",
+ sideOffset = 6,
+ align = "start",
+ alignOffset = 0,
+ anchor,
+ ...props
+}: ComboboxPrimitive.Popup.Props &
+ Pick<
+ ComboboxPrimitive.Positioner.Props,
+ "side" | "align" | "sideOffset" | "alignOffset" | "anchor"
+ >) {
+ return (
+ <ComboboxPrimitive.Portal>
+ <ComboboxPrimitive.Positioner
+ side={side}
+ sideOffset={sideOffset}
+ align={align}
+ alignOffset={alignOffset}
+ anchor={anchor}
+ className="isolate z-50"
+ >
+ <ComboboxPrimitive.Popup
+ data-slot="combobox-content"
+ data-chips={!!anchor}
+ className={cn("group/combobox-content relative max-h-(--available-height) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
+ {...props}
+ />
+ </ComboboxPrimitive.Positioner>
+ </ComboboxPrimitive.Portal>
+ )
+}
+
+function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
+ return (
+ <ComboboxPrimitive.List
+ data-slot="combobox-list"
+ className={cn(
+ "no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ComboboxItem({
+ className,
+ children,
+ ...props
+}: ComboboxPrimitive.Item.Props) {
+ return (
+ <ComboboxPrimitive.Item
+ data-slot="combobox-item"
+ className={cn(
+ "relative flex w-full cursor-default items-center gap-2 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ComboboxPrimitive.ItemIndicator
+ render={
+ <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
+ }
+ >
+ <IconCheck className="pointer-events-none" />
+ </ComboboxPrimitive.ItemIndicator>
+ </ComboboxPrimitive.Item>
+ )
+}
+
+function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
+ return (
+ <ComboboxPrimitive.Group
+ data-slot="combobox-group"
+ className={cn(className)}
+ {...props}
+ />
+ )
+}
+
+function ComboboxLabel({
+ className,
+ ...props
+}: ComboboxPrimitive.GroupLabel.Props) {
+ return (
+ <ComboboxPrimitive.GroupLabel
+ data-slot="combobox-label"
+ className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
+ {...props}
+ />
+ )
+}
+
+function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
+ return (
+ <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
+ )
+}
+
+function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
+ return (
+ <ComboboxPrimitive.Empty
+ data-slot="combobox-empty"
+ className={cn(
+ "hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ComboboxSeparator({
+ className,
+ ...props
+}: ComboboxPrimitive.Separator.Props) {
+ return (
+ <ComboboxPrimitive.Separator
+ data-slot="combobox-separator"
+ className={cn("-mx-1 my-1 h-px bg-border", className)}
+ {...props}
+ />
+ )
+}
+
+function ComboboxChips({
+ className,
+ ...props
+}: React.ComponentPropsWithRef<typeof ComboboxPrimitive.Chips> &
+ ComboboxPrimitive.Chips.Props) {
+ return (
+ <ComboboxPrimitive.Chips
+ data-slot="combobox-chips"
+ className={cn(
+ "flex min-h-8 flex-wrap items-center gap-1 rounded-lg border border-input bg-transparent bg-clip-padding px-2.5 py-1 text-sm transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ComboboxChip({
+ className,
+ children,
+ showRemove = true,
+ ...props
+}: ComboboxPrimitive.Chip.Props & {
+ showRemove?: boolean
+}) {
+ return (
+ <ComboboxPrimitive.Chip
+ data-slot="combobox-chip"
+ className={cn(
+ "flex h-[calc(--spacing(5.25))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ {showRemove && (
+ <ComboboxPrimitive.ChipRemove
+ render={<Button variant="ghost" size="icon-xs" />}
+ className="-ml-1 opacity-50 hover:opacity-100"
+ data-slot="combobox-chip-remove"
+ >
+ <IconX className="pointer-events-none" />
+ </ComboboxPrimitive.ChipRemove>
+ )}
+ </ComboboxPrimitive.Chip>
+ )
+}
+
+function ComboboxChipsInput({
+ className,
+ ...props
+}: ComboboxPrimitive.Input.Props) {
+ return (
+ <ComboboxPrimitive.Input
+ data-slot="combobox-chip-input"
+ className={cn("min-w-16 flex-1 outline-none", className)}
+ {...props}
+ />
+ )
+}
+
+function useComboboxAnchor() {
+ return React.useRef<HTMLDivElement | null>(null)
+}
+
+export {
+ Combobox,
+ ComboboxInput,
+ ComboboxContent,
+ ComboboxList,
+ ComboboxItem,
+ ComboboxGroup,
+ ComboboxLabel,
+ ComboboxCollection,
+ ComboboxEmpty,
+ ComboboxSeparator,
+ ComboboxChips,
+ ComboboxChip,
+ ComboboxChipsInput,
+ ComboboxTrigger,
+ ComboboxValue,
+ useComboboxAnchor,
+}
diff --git a/app/src/components/ui/dialog.tsx b/app/src/components/ui/dialog.tsx
new file mode 100644
index 00000000..e9858798
--- /dev/null
+++ b/app/src/components/ui/dialog.tsx
@@ -0,0 +1,157 @@
+import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
+import { IconX } from "@tabler/icons-react";
+import type * as React from "react";
+
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+/**
+ * A centred modal, for a form that is short enough to finish in one sitting.
+ *
+ * WHY THIS EXISTS ALONGSIDE `DetailPanel`. The panel is the right answer on the screens somebody
+ * lives in — writing a skill, editing an agent — where the list stays visible beside what you are
+ * editing and the work is worth a URL. Admin is not that: a credential is added once and forgotten,
+ * and giving it a route and a side panel dresses a two-field form as a place you might come back to.
+ *
+ * Built on the same Base UI dialog as `Sheet`, so focus trapping, scroll locking and the escape key
+ * behave identically across the app rather than nearly identically.
+ */
+function Dialog({ ...props }: DialogPrimitive.Root.Props) {
+ return <DialogPrimitive.Root data-slot="dialog" {...props} />;
+}
+
+function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
+}
+
+function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
+}
+
+function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
+}
+
+function DialogOverlay({ className, ...props }: DialogPrimitive.Backdrop.Props) {
+ return (
+ <DialogPrimitive.Backdrop
+ data-slot="dialog-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: DialogPrimitive.Popup.Props & { showCloseButton?: boolean }) {
+ return (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Popup
+ data-slot="dialog-content"
+ className={cn(
+ /*
+ * `max-h-[85svh]` with the body scrolling, not the popup growing: a form that is long on a
+ * laptop must not push its own submit button off the bottom of the screen, which is exactly
+ * where somebody looks for it.
+ */
+ "-translate-x-1/2 -translate-y-1/2 fixed top-1/2 left-1/2 z-50 flex max-h-[85svh] w-[calc(100%-2rem)] max-w-lg flex-col gap-4 rounded-xl border border-border bg-popover p-5 text-sm text-popover-foreground shadow-lg transition duration-150 ease-out data-ending-style:scale-[0.98] data-ending-style:opacity-0 data-starting-style:scale-[0.98] data-starting-style:opacity-0",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close
+ data-slot="dialog-close"
+ render={
+ <Button
+ variant="ghost"
+ className="absolute top-3 right-3"
+ size="icon-sm"
+ />
+ }
+ >
+ <IconX />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ )}
+ </DialogPrimitive.Popup>
+ </DialogPortal>
+ );
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="dialog-header"
+ className={cn("flex flex-col gap-1 pr-8", className)}
+ {...props}
+ />
+ );
+}
+
+/** Body scrolls, so the header and footer stay put on a short viewport. */
+function DialogBody({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="dialog-body"
+ className={cn("-mx-1 flex min-h-0 flex-1 flex-col gap-4 px-1", className)}
+ {...props}
+ />
+ );
+}
+
+function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="dialog-footer"
+ className={cn("flex flex-row items-center justify-end gap-2", className)}
+ {...props}
+ />
+ );
+}
+
+function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
+ return (
+ <DialogPrimitive.Title
+ data-slot="dialog-title"
+ className={cn("font-heading font-medium text-base text-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: DialogPrimitive.Description.Props) {
+ return (
+ <DialogPrimitive.Description
+ data-slot="dialog-description"
+ className={cn("text-muted-foreground text-sm text-pretty", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+};
diff --git a/app/src/components/ui/input-group.tsx b/app/src/components/ui/input-group.tsx
new file mode 100644
index 00000000..b38b3508
--- /dev/null
+++ b/app/src/components/ui/input-group.tsx
@@ -0,0 +1,156 @@
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+import { Textarea } from "@/components/ui/textarea"
+
+function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="input-group"
+ role="group"
+ className={cn(
+ "group/input-group relative flex h-9 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+const inputGroupAddonVariants = cva(
+ "flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ align: {
+ "inline-start":
+ "order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
+ "inline-end":
+ "order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
+ "block-start":
+ "order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
+ "block-end":
+ "order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
+ },
+ },
+ defaultVariants: {
+ align: "inline-start",
+ },
+ }
+)
+
+function InputGroupAddon({
+ className,
+ align = "inline-start",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="input-group-addon"
+ data-align={align}
+ className={cn(inputGroupAddonVariants({ align }), className)}
+ onClick={(e) => {
+ if ((e.target as HTMLElement).closest("button")) {
+ return
+ }
+ e.currentTarget.parentElement?.querySelector("input")?.focus()
+ }}
+ {...props}
+ />
+ )
+}
+
+const inputGroupButtonVariants = cva(
+ "flex items-center gap-2 text-sm shadow-none",
+ {
+ variants: {
+ size: {
+ xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
+ sm: "",
+ "icon-xs":
+ "size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
+ "icon-sm": "size-8 p-0 has-[>svg]:p-0",
+ },
+ },
+ defaultVariants: {
+ size: "xs",
+ },
+ }
+)
+
+function InputGroupButton({
+ className,
+ type = "button",
+ variant = "ghost",
+ size = "xs",
+ ...props
+}: Omit<React.ComponentProps<typeof Button>, "size" | "type"> &
+ VariantProps<typeof inputGroupButtonVariants> & {
+ type?: "button" | "submit" | "reset"
+ }) {
+ return (
+ <Button
+ type={type}
+ data-size={size}
+ variant={variant}
+ className={cn(inputGroupButtonVariants({ size }), className)}
+ {...props}
+ />
+ )
+}
+
+function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ className={cn(
+ "flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function InputGroupInput({
+ className,
+ ...props
+}: React.ComponentProps<"input">) {
+ return (
+ <Input
+ data-slot="input-group-control"
+ className={cn(
+ "flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function InputGroupTextarea({
+ className,
+ ...props
+}: React.ComponentProps<"textarea">) {
+ return (
+ <Textarea
+ data-slot="input-group-control"
+ className={cn(
+ "flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupText,
+ InputGroupInput,
+ InputGroupTextarea,
+}
diff --git a/app/src/components/ui/input.tsx b/app/src/components/ui/input.tsx
new file mode 100644
index 00000000..56407a9e
--- /dev/null
+++ b/app/src/components/ui/input.tsx
@@ -0,0 +1,20 @@
+import * as React from "react"
+import { Input as InputPrimitive } from "@base-ui/react/input"
+
+import { cn } from "@/lib/utils"
+
+function Input({ className, type, ...props }: React.ComponentProps<"input">) {
+ return (
+ <InputPrimitive
+ type={type}
+ data-slot="input"
+ className={cn(
+ "h-9 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Input }
diff --git a/app/src/components/ui/item.tsx b/app/src/components/ui/item.tsx
new file mode 100644
index 00000000..c6d9df28
--- /dev/null
+++ b/app/src/components/ui/item.tsx
@@ -0,0 +1,201 @@
+import * as React from "react";
+import { mergeProps } from "@base-ui/react/merge-props";
+import { useRender } from "@base-ui/react/use-render";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@/lib/utils";
+import { Separator } from "@/components/ui/separator";
+
+function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ role="list"
+ data-slot="item-group"
+ className={cn(
+ "group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="item-separator"
+ orientation="horizontal"
+ className={cn("my-2", className)}
+ {...props}
+ />
+ );
+}
+
+const itemVariants = cva(
+ "group/item flex w-full flex-wrap items-center rounded-lg border text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-muted",
+ {
+ variants: {
+ variant: {
+ default: "border-transparent",
+ outline: "border-border",
+ muted: "border-transparent bg-muted/50",
+ },
+ size: {
+ default: "gap-2.5 px-3 py-2.5",
+ sm: "gap-2.5 px-3 py-2.5",
+ xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+function Item({
+ className,
+ variant = "default",
+ size = "default",
+ render,
+ ...props
+}: useRender.ComponentProps<"div"> & VariantProps<typeof itemVariants>) {
+ return useRender({
+ defaultTagName: "div",
+ props: mergeProps<"div">(
+ {
+ className: cn(itemVariants({ variant, size, className })),
+ },
+ props,
+ ),
+ render,
+ state: {
+ slot: "item",
+ variant,
+ size,
+ },
+ });
+}
+
+const itemMediaVariants = cva(
+ "flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ icon: "[&_svg:not([class*='size-'])]:size-4",
+ image:
+ "size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function ItemMedia({
+ className,
+ variant = "default",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
+ return (
+ <div
+ data-slot="item-media"
+ data-variant={variant}
+ className={cn(itemMediaVariants({ variant, className }))}
+ {...props}
+ />
+ );
+}
+
+function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-content"
+ className={cn(
+ "flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-title"
+ className={cn(
+ "line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="item-description"
+ className={cn(
+ "line-clamp-2 text-left text-sm leading-normal font-normal text-muted-foreground group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-actions"
+ className={cn("flex items-center gap-2", className)}
+ {...props}
+ />
+ );
+}
+
+function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-header"
+ className={cn(
+ "flex basis-full items-center justify-between gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="item-footer"
+ className={cn(
+ "flex basis-full items-center justify-between gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Item,
+ ItemMedia,
+ ItemContent,
+ ItemActions,
+ ItemGroup,
+ ItemSeparator,
+ ItemTitle,
+ ItemDescription,
+ ItemHeader,
+ ItemFooter,
+};
diff --git a/app/src/components/ui/label.tsx b/app/src/components/ui/label.tsx
new file mode 100644
index 00000000..e5ec08fa
--- /dev/null
+++ b/app/src/components/ui/label.tsx
@@ -0,0 +1,18 @@
+import * as React from "react";
+
+import { cn } from "@/lib/utils";
+
+function Label({ className, ...props }: React.ComponentProps<"label">) {
+ return (
+ <label
+ data-slot="label"
+ className={cn(
+ "flex items-center gap-2 text-xs leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Label };
diff --git a/app/src/components/ui/separator.tsx b/app/src/components/ui/separator.tsx
new file mode 100644
index 00000000..32b4af26
--- /dev/null
+++ b/app/src/components/ui/separator.tsx
@@ -0,0 +1,23 @@
+import { Separator as SeparatorPrimitive } from "@base-ui/react/separator";
+
+import { cn } from "@/lib/utils";
+
+function Separator({
+ className,
+ orientation = "horizontal",
+ ...props
+}: SeparatorPrimitive.Props) {
+ return (
+ <SeparatorPrimitive
+ data-slot="separator"
+ orientation={orientation}
+ className={cn(
+ "shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Separator };
diff --git a/app/src/components/ui/sheet.tsx b/app/src/components/ui/sheet.tsx
new file mode 100644
index 00000000..4d14062e
--- /dev/null
+++ b/app/src/components/ui/sheet.tsx
@@ -0,0 +1,135 @@
+import * as React from "react";
+import { Dialog as SheetPrimitive } from "@base-ui/react/dialog";
+
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { IconX } from "@tabler/icons-react";
+
+function Sheet({ ...props }: SheetPrimitive.Root.Props) {
+ return <SheetPrimitive.Root data-slot="sheet" {...props} />;
+}
+
+function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
+ return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
+}
+
+function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
+ return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
+}
+
+function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
+ return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
+}
+
+function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
+ return (
+ <SheetPrimitive.Backdrop
+ data-slot="sheet-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SheetContent({
+ className,
+ children,
+ side = "right",
+ showCloseButton = true,
+ ...props
+}: SheetPrimitive.Popup.Props & {
+ side?: "top" | "right" | "bottom" | "left";
+ showCloseButton?: boolean;
+}) {
+ return (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Popup
+ data-slot="sheet-content"
+ data-side={side}
+ className={cn(
+ "fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <SheetPrimitive.Close
+ data-slot="sheet-close"
+ render={
+ <Button
+ variant="ghost"
+ className="absolute top-3 right-3"
+ size="icon-sm"
+ />
+ }
+ >
+ <IconX />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ )}
+ </SheetPrimitive.Popup>
+ </SheetPortal>
+ );
+}
+
+function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-header"
+ className={cn("flex flex-col gap-0.5 p-4", className)}
+ {...props}
+ />
+ );
+}
+
+function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ );
+}
+
+function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
+ return (
+ <SheetPrimitive.Title
+ data-slot="sheet-title"
+ className={cn(
+ "font-heading text-base font-medium text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SheetDescription({
+ className,
+ ...props
+}: SheetPrimitive.Description.Props) {
+ return (
+ <SheetPrimitive.Description
+ data-slot="sheet-description"
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+ );
+}
+
+export {
+ Sheet,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+};
diff --git a/app/src/hooks/use-mobile.ts b/app/src/hooks/use-mobile.ts
new file mode 100644
index 00000000..a93d5839
--- /dev/null
+++ b/app/src/hooks/use-mobile.ts
@@ -0,0 +1,21 @@
+import * as React from "react";
+
+const MOBILE_BREAKPOINT = 768;
+
+export function useIsMobile() {
+ const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
+ undefined,
+ );
+
+ React.useEffect(() => {
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
+ const onChange = () => {
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ };
+ mql.addEventListener("change", onChange);
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ return () => mql.removeEventListener("change", onChange);
+ }, []);
+
+ return !!isMobile;
+}
diff --git a/app/src/lib/agents/form.ts b/app/src/lib/agents/form.ts
new file mode 100644
index 00000000..fa531b38
--- /dev/null
+++ b/app/src/lib/agents/form.ts
@@ -0,0 +1,66 @@
+import { z } from "zod";
+
+/**
+ * Browser-side teammate form contract. Limits match the server parser so validation errors can be
+ * shown next to fields before submit.
+ */
+export const agentFormSchema = z.object({
+ name: z
+ .string()
+ .trim()
+ .min(1, "Name is required.")
+ .max(80, "Name must be 80 characters or fewer."),
+ title: z
+ .string()
+ .trim()
+ .min(1, "Title is required.")
+ .max(120, "Title must be 120 characters or fewer."),
+ roleDescription: z
+ .string()
+ .trim()
+ .min(1, "Role description is required.")
+ .max(1000, "Role description must be 1000 characters or fewer."),
+ visibility: z.enum(["public", "private"]),
+ /**
+ * The AG-UI endpoint this teammate runs on. Empty means the Bot in the box.
+ *
+ * Only URL shape is checked here; deployment allow/deny rules are server-side.
+ */
+ endpoint: z
+ .string()
+ .trim()
+ .refine(
+ (value) => value === "" || /^https?:\/\/\S+$/.test(value),
+ "Enter a web address starting with http:// or https://.",
+ ),
+ /**
+ * A key the agent sits behind. WRITE-ONLY: it is never sent back from the server, so this field is
+ * always empty when editing, and leaving it empty keeps whatever key is already set.
+ */
+ authValue: z.string(),
+});
+
+export type AgentFormValues = z.infer<typeof agentFormSchema>;
+
+export const emptyAgentForm: AgentFormValues = {
+ name: "",
+ title: "",
+ roleDescription: "",
+ visibility: "private",
+ endpoint: "",
+ authValue: "",
+};
+
+/** Convert form values to API input; omit an empty key so editing preserves the current credential. */
+export function agentInputFrom(values: AgentFormValues) {
+ return {
+ name: values.name,
+ title: values.title,
+ roleDescription: values.roleDescription,
+ visibility: values.visibility,
+ endpoint: values.endpoint,
+ ...(values.authValue.trim()
+ ? { auth: { header: "Authorization", value: values.authValue.trim() } }
+ : {}),
+ };
+}
diff --git a/app/src/lib/agents/mutations.ts b/app/src/lib/agents/mutations.ts
new file mode 100644
index 00000000..f71768a3
--- /dev/null
+++ b/app/src/lib/agents/mutations.ts
@@ -0,0 +1,99 @@
+import { mutationOptions, type QueryClient } from "@tanstack/react-query";
+import { type AgentProfile, type AgentVisibility, agentKeys } from "./queries";
+
+export type AgentInput = {
+ name: string;
+ title: string;
+ roleDescription: string;
+ visibility: AgentVisibility;
+ /** Where this teammate runs. Empty means the Bot in the box. */
+ endpoint?: string;
+ /** Write-only auth value; omitted when the user leaves the key field empty. */
+ auth?: { header: string; value: string };
+};
+
+async function agentRequest(
+ path: string,
+ init: { method: string; body?: AgentInput },
+): Promise<Response> {
+ const response = await fetch(path, {
+ method: init.method,
+ credentials: "include",
+ headers: init.body ? { "content-type": "application/json" } : undefined,
+ body: init.body ? JSON.stringify(init.body) : undefined,
+ });
+ if (!response.ok) {
+ // The server's message is the useful one: it names the field or the permission that failed.
+ const message = await response
+ .json()
+ .then((body: { error?: string }) => body.error)
+ .catch(() => undefined);
+ throw new Error(message ?? "Teammate operation failed");
+ }
+ return response;
+}
+
+async function agentFrom(response: Response): Promise<AgentProfile> {
+ return ((await response.json()) as { agent: AgentProfile }).agent;
+}
+
+/** Server-derived fields are invalidated instead of patched by hand. */
+function invalidateAgents(queryClient: QueryClient) {
+ return queryClient.invalidateQueries({ queryKey: agentKeys.all });
+}
+
+export function createAgentMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (input: AgentInput) =>
+ agentFrom(
+ await agentRequest("/api/agents", { method: "POST", body: input }),
+ ),
+ onSuccess: () => invalidateAgents(queryClient),
+ });
+}
+
+export function updateAgentMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (variables: { agentId: string; input: AgentInput }) =>
+ agentFrom(
+ await agentRequest(`/api/agents/${variables.agentId}`, {
+ method: "PATCH",
+ body: variables.input,
+ }),
+ ),
+ onSuccess: () => invalidateAgents(queryClient),
+ });
+}
+
+export function duplicateAgentMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (agentId: string) =>
+ agentFrom(
+ await agentRequest(`/api/agents/${agentId}/duplicate`, {
+ method: "POST",
+ }),
+ ),
+ onSuccess: () => invalidateAgents(queryClient),
+ });
+}
+
+export function setAgentHiddenMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (variables: { agentId: string; hidden: boolean }) => {
+ await agentRequest(
+ `/api/agents/${variables.agentId}/${variables.hidden ? "hide" : "unhide"}`,
+ { method: "POST" },
+ );
+ },
+ onSuccess: () => invalidateAgents(queryClient),
+ });
+}
+
+export function deleteAgentMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (agentId: string) => {
+ await agentRequest(`/api/agents/${agentId}`, { method: "DELETE" });
+ },
+ onSuccess: () => invalidateAgents(queryClient),
+ });
+}
diff --git a/app/src/lib/auth/mutations.ts b/app/src/lib/auth/mutations.ts
new file mode 100644
index 00000000..164a4e75
--- /dev/null
+++ b/app/src/lib/auth/mutations.ts
@@ -0,0 +1,19 @@
+import { mutationOptions, type QueryClient } from "@tanstack/react-query";
+import { authKeys } from "./queries";
+
+async function signOut() {
+ const response = await fetch("/api/auth/sign-out", {
+ method: "POST",
+ credentials: "include",
+ });
+ if (!response.ok) {
+ throw new Error(`Could not sign out (${response.status})`);
+ }
+}
+
+export function signOutMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: signOut,
+ onSuccess: () => queryClient.removeQueries({ queryKey: authKeys.all }),
+ });
+}
diff --git a/app/src/lib/auth/queries.ts b/app/src/lib/auth/queries.ts
new file mode 100644
index 00000000..2b1f2a8d
--- /dev/null
+++ b/app/src/lib/auth/queries.ts
@@ -0,0 +1,35 @@
+import { queryOptions } from "@tanstack/react-query";
+
+export type AuthenticatedUser = {
+ id: string;
+ email: string;
+ name?: string | null;
+ image?: string | null;
+ role: "admin" | "user";
+};
+
+export const authKeys = {
+ all: ["auth"] as const,
+ currentUser: () => [...authKeys.all, "current-user"] as const,
+};
+
+async function currentUser(): Promise<AuthenticatedUser | null> {
+ const response = await fetch("/api/me", { credentials: "include" });
+ if (response.status === 401) {
+ return null;
+ }
+ if (!response.ok) {
+ throw new Error(`Could not load the current user (${response.status})`);
+ }
+
+ const body = (await response.json()) as { user: AuthenticatedUser };
+ return body.user;
+}
+
+export function currentUserQueryOptions() {
+ return queryOptions({
+ queryKey: authKeys.currentUser(),
+ queryFn: currentUser,
+ staleTime: 60_000,
+ });
+}
diff --git a/app/src/lib/channels/mutations.ts b/app/src/lib/channels/mutations.ts
new file mode 100644
index 00000000..c48821cb
--- /dev/null
+++ b/app/src/lib/channels/mutations.ts
@@ -0,0 +1,60 @@
+import { mutationOptions, type QueryClient } from "@tanstack/react-query";
+import { type AgentChannel, channelKeys } from "./queries";
+
+/**
+ * Start a new channel with one or more teammates.
+ *
+ * Deliberately not idempotent: every call creates a channel with its own thread.
+ */
+export function createChannelMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (agentIds: string[]): Promise<AgentChannel> => {
+ const response = await fetch("/api/channels", {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentIds }),
+ });
+ if (!response.ok) {
+ const message = await response
+ .json()
+ .then((body: { error?: string }) => body.error)
+ .catch(() => undefined);
+ throw new Error(message ?? "Could not start a channel");
+ }
+ return ((await response.json()) as { channel: AgentChannel }).channel;
+ },
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: channelKeys.all }),
+ });
+}
+
+/**
+ * Report the last thing said in a channel.
+ *
+ * The client that ran the agent already has the message before platform replay can return it; the
+ * runtime exposes no run-completion hook and its run endpoint returns before the reply exists.
+ *
+ * Fire-and-forget on purpose: a failed preview update is a stale roster line, not a lost message.
+ */
+export function recordChannelActivityMutationOptions() {
+ return mutationOptions({
+ mutationFn: async (variables: {
+ channelId: string;
+ text: string;
+ agentId: string | null;
+ at: string;
+ }) => {
+ await fetch(`/api/channels/${variables.channelId}/activity`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ agentId: variables.agentId,
+ at: variables.at,
+ text: variables.text,
+ }),
+ });
+ },
+ });
+}
diff --git a/app/src/lib/channels/queries.ts b/app/src/lib/channels/queries.ts
new file mode 100644
index 00000000..b332223a
--- /dev/null
+++ b/app/src/lib/channels/queries.ts
@@ -0,0 +1,59 @@
+import { queryOptions } from "@tanstack/react-query";
+
+/**
+ * A channel as the browser sees it.
+ *
+ * `threadId` is what makes two channels with the same teammate independent conversations, and
+ * `active` is false once a linked teammate has been deleted: the transcript stays readable, but
+ * nothing more can be said in it.
+ */
+export type AgentChannel = {
+ id: string;
+ name: string;
+ agentIds: string[];
+ threadId: string;
+ active: boolean;
+};
+
+/** A channel plus the last thing said in it, which is what the roster renders. */
+export type ChannelSummary = AgentChannel & {
+ lastMessage: string | null;
+ /** ISO-8601, or null for a channel nobody has used yet. */
+ lastMessageAt: string | null;
+ lastMessageAgentId: string | null;
+ /** ISO-8601. Ordering falls back to this, so a channel just created sorts to the top. */
+ createdAt: string;
+};
+
+export const channelKeys = {
+ all: ["channels"] as const,
+ list: () => ["channels", "list"] as const,
+ detail: (channelId: string) => ["channels", "detail", channelId] as const,
+};
+
+export function channelListQueryOptions() {
+ return queryOptions({
+ queryKey: channelKeys.list(),
+ queryFn: async (): Promise<ChannelSummary[]> => {
+ const response = await fetch("/api/channels", {
+ credentials: "include",
+ });
+ if (!response.ok) throw new Error("Could not load channels");
+ return ((await response.json()) as { channels: ChannelSummary[] })
+ .channels;
+ },
+ });
+}
+
+export function channelQueryOptions(channelId: string) {
+ return queryOptions({
+ queryKey: channelKeys.detail(channelId),
+ queryFn: async (): Promise<AgentChannel> => {
+ const response = await fetch(`/api/channels/${channelId}`, {
+ credentials: "include",
+ });
+ if (!response.ok) throw new Error("Could not load this channel");
+ return ((await response.json()) as { channel: AgentChannel }).channel;
+ },
+ });
+}
diff --git a/app/src/lib/copilot/bot-thread.ts b/app/src/lib/copilot/bot-thread.ts
new file mode 100644
index 00000000..087b852d
--- /dev/null
+++ b/app/src/lib/copilot/bot-thread.ts
@@ -0,0 +1,79 @@
+import { useEffect, useState } from "react";
+
+/**
+ * The thread the direct Bot chat talks in.
+ *
+ * Two things it has to be. Minted by this deployment, so the conversation says where it came from
+ * in a project that may hold more than one. And the same one tomorrow, because a chat that takes a
+ * new thread on every load has no history to come back to.
+ *
+ * Kept per Bot: the chat is bound to one Bot at a time, and two Bots sharing a thread would read
+ * each other's conversation.
+ */
+
+const KEY = "openbot.bot-thread";
+
+function remembered(agentId: string): string | null {
+ try {
+ return window.localStorage.getItem(`${KEY}.${agentId}`);
+ } catch {
+ // Storage can be unavailable or full. A thread for this visit is better than no chat at all.
+ return null;
+ }
+}
+
+function remember(agentId: string, threadId: string): void {
+ try {
+ window.localStorage.setItem(`${KEY}.${agentId}`, threadId);
+ } catch {
+ // As above: the conversation still works, it just will not be here next time.
+ }
+}
+
+async function mint(): Promise<string | null> {
+ try {
+ const response = await fetch("/api/threads/mint", {
+ method: "POST",
+ credentials: "include",
+ });
+ if (!response.ok) return null;
+ const body = (await response.json()) as { threadId?: unknown };
+ return typeof body.threadId === "string" ? body.threadId : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * `undefined` until it is known, which is not the same as absent: rendering the chat before then
+ * would let it mint an id of its own, and that is the one this deployment would then be stuck with.
+ */
+export function useBotThread(agentId: string): string | undefined {
+ const [threadId, setThreadId] = useState<string | undefined>(undefined);
+
+ useEffect(() => {
+ let current = true;
+ setThreadId(undefined);
+
+ const existing = remembered(agentId);
+ if (existing) {
+ setThreadId(existing);
+ return;
+ }
+
+ void mint().then((minted) => {
+ if (!current) return;
+ // Falling back to one made here keeps the chat working when the deployment cannot be asked;
+ // it is simply a thread nothing can later attribute.
+ const next = minted ?? crypto.randomUUID();
+ if (minted) remember(agentId, minted);
+ setThreadId(next);
+ });
+
+ return () => {
+ current = false;
+ };
+ }, [agentId]);
+
+ return threadId;
+}
diff --git a/app/src/lib/copilot/computer-activity.ts b/app/src/lib/copilot/computer-activity.ts
new file mode 100644
index 00000000..4bd05c4e
--- /dev/null
+++ b/app/src/lib/copilot/computer-activity.ts
@@ -0,0 +1,32 @@
+/**
+ * Browser-activity epoch used by surfaces that auto-open the live screen once per run.
+ */
+
+const QUIET_GAP_MS = 10_000;
+
+type Activity = { botId: string; epoch: number };
+
+let epoch = 0;
+let lastAt = 0;
+let lastBot: string | null = null;
+const listeners = new Set<(activity: Activity) => void>();
+
+/** Called wherever a Bot's computer is reached, so auto-open surfaces share one activity source. */
+export function reportComputerActivity(botId: string): void {
+ const now = Date.now();
+ // A different Bot is always a new run, however recently the last one acted.
+ if (botId !== lastBot || now - lastAt > QUIET_GAP_MS) epoch += 1;
+ lastAt = now;
+ lastBot = botId;
+ const activity = { botId, epoch };
+ for (const listener of listeners) listener(activity);
+}
+
+export function onComputerActivity(
+ listener: (activity: Activity) => void,
+): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
diff --git a/app/src/lib/copilot/computer-tools.tsx b/app/src/lib/copilot/computer-tools.tsx
new file mode 100644
index 00000000..ce480b13
--- /dev/null
+++ b/app/src/lib/copilot/computer-tools.tsx
@@ -0,0 +1,711 @@
+import { useFrontendTool } from "@copilotkit/react-core/v2";
+import { z } from "zod";
+import { ToolLine } from "@/components/channels/tool-line";
+import { ComputerView } from "@/components/computer/computer-view";
+import {
+ type ControlState,
+ readControl,
+} from "@/components/computer/take-the-wheel";
+import { useActiveBotHolder } from "./active-bot";
+import { reportComputerActivity } from "./computer-activity";
+
+/**
+ * Frontend registrations for computer tools, including inline rendering and policy-refusal display.
+ */
+
+/** What every computer call returns to the model: either the result, or a reason it did not happen. */
+type ToolOutcome = Record<string, unknown> & { ok: boolean };
+
+/**
+ * Human-assistance wait window. Long enough for a user to return, finite so the run can unblock.
+ */
+const WAIT_FOR_PERSON_MS = 10 * 60_000;
+
+/** How often the waiting handler asks whether the person has answered yet. */
+const WAIT_POLL_MS = 1_000;
+
+/** Hold the tool call open until the human control/secret prompt is answered, cancelled, or expires. */
+async function waitForPerson(
+ botId: string,
+ done: (state: ControlState) => boolean,
+ signal: AbortSignal | undefined,
+ giveUpAfterMs = WAIT_FOR_PERSON_MS,
+): Promise<"answered" | "gave up" | "cancelled"> {
+ const deadline = Date.now() + giveUpAfterMs;
+ while (Date.now() < deadline) {
+ // Stop must actually stop, including out of a wait. The SDK aborts this when a person presses it.
+ if (signal?.aborted) return "cancelled";
+ const state = await readControl(botId).catch(() => null);
+ if (state && done(state)) return "answered";
+ await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));
+ }
+ return "gave up";
+}
+
+async function callComputer(
+ botId: string,
+ path: string,
+ init?: RequestInit,
+ signal?: AbortSignal,
+): Promise<ToolOutcome> {
+ // Announce before the call so the screen can open while the action is running.
+ reportComputerActivity(botId);
+ let response: Response;
+ try {
+ response = await fetch(`/api/computers/${botId}${path}`, {
+ credentials: "include",
+ // Abort cancels the request and prevents later actions, but cannot undo browser work already executing.
+ ...(signal ? { signal } : {}),
+ ...init,
+ });
+ } catch (error) {
+ // An abort is a stopped run, not a computer failure.
+ if (error instanceof DOMException && error.name === "AbortError") {
+ return { ok: false, reason: "Stopped.", stopped: true };
+ }
+ return {
+ ok: false,
+ reason: "The assistant's computer could not be reached.",
+ };
+ }
+
+ const body = (await response.json().catch(() => null)) as Record<
+ string,
+ unknown
+ > | null;
+
+ if (!response.ok) {
+ return {
+ ok: false,
+ reason: (body?.error as string) ?? "That did not work.",
+ // Preserve refusal/stale-ref/control distinctions for the model's next step.
+ ...(response.status === 403
+ ? { refused: true, rule: body?.rule ?? null }
+ : {}),
+ ...(response.status === 409
+ ? body?.humanHasControl === true
+ ? { humanHasControl: true }
+ : { staleRefs: true }
+ : {}),
+ };
+ }
+
+ return { ok: true, ...(body ?? {}) };
+}
+
+/** What a computer tool's render can read back out of its own result. */
+type ComputerOutcome = {
+ ok?: boolean;
+ stopped?: boolean;
+ humanHasControl?: boolean;
+ entries?: unknown[];
+ refused?: boolean;
+ reason?: string;
+ staleRefs?: boolean;
+ elements?: unknown[];
+ element?: { role?: string; name?: string };
+};
+
+/**
+ * Parse the SDK-render result string so the transcript can distinguish success, refusal, and failure.
+ */
+function outcomeOf(result: string | undefined): ComputerOutcome {
+ if (!result) return {};
+ try {
+ const parsed = JSON.parse(result) as unknown;
+ return parsed && typeof parsed === "object"
+ ? (parsed as ComputerOutcome)
+ : {};
+ } catch {
+ // Runtime stringifies thrown handlers as "Error: <message>".
+ return result.startsWith("Error:")
+ ? { ok: false, reason: result.slice("Error:".length).trim() }
+ : {};
+ }
+}
+
+/**
+ * The label of the element an action touched, as the gateway resolved it server-side.
+ *
+ * Not taken from the model's arguments: those carry only a ref. The server looked the element up in
+ * the snapshot it took itself, which is the same value it wrote to the audit trail, so the transcript
+ * and the audit row name the thing identically.
+ */
+function labelOf(result: string | undefined): string | undefined {
+ const element = (outcomeOf(result) as { element?: { name?: unknown } })
+ .element;
+ const name = element?.name;
+ return typeof name === "string" && name.trim() ? name.trim() : undefined;
+}
+
+/**
+ * A compact transcript line that distinguishes policy refusals from ordinary failures.
+ */
+function ActionLine({
+ label,
+ detail,
+ running,
+ refused,
+ failed,
+}: {
+ label: string;
+ detail?: string;
+ running?: boolean;
+ /** A policy or a boundary said no. Final: nothing the Bot does differently will help. */
+ refused?: boolean;
+ /** It was permitted and did not work. A different request might. */
+ failed?: boolean;
+}) {
+ return (
+ <ToolLine
+ detail={detail}
+ failed={failed}
+ label={label}
+ refused={refused}
+ running={running}
+ />
+ );
+}
+
+/** Whether a result is an ordinary failure rather than a refusal, so the two can render differently. */
+function didNotWork(outcome: ComputerOutcome): boolean {
+ return outcome.ok === false && outcome.refused !== true;
+}
+
+export function ComputerTools() {
+ const bot = useActiveBotHolder();
+
+ useFrontendTool({
+ name: "computer_navigate",
+ description:
+ "Open a web page on your own computer so the person can watch. Use this when asked to look " +
+ "at, visit, open or check a website. Returns the page title and its readable text, so answer " +
+ "from what comes back rather than telling the person to go and look.",
+ parameters: z.object({
+ url: z.string().describe("Full web address to open, including https://"),
+ }),
+ handler: async (
+ { url }: { url: string },
+ // Context is optional in the SDK.
+ { signal }: { signal?: AbortSignal } = {},
+ ) => {
+ const result = await callComputer(
+ bot.current,
+ "/navigate",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ url }),
+ },
+ signal,
+ );
+ return result.ok
+ ? {
+ ok: true,
+ title: result.title,
+ url: result.url,
+ text: result.text,
+ truncated: result.truncated,
+ }
+ : result;
+ },
+ render: ({ status }) => (
+ <div className="my-2">
+ <ComputerView computerId={bot.current} active={status !== "complete"} />
+ </div>
+ ),
+ });
+
+ useFrontendTool({
+ name: "computer_read",
+ description:
+ "Read the page currently open on your computer, without opening anything. Use this after you " +
+ "click something that changes the page, such as submitting a form, to find out what it now says.",
+ parameters: z.object({}),
+ handler: async () => callComputer(bot.current, "/read"),
+ render: () => null,
+ });
+
+ useFrontendTool({
+ name: "computer_snapshot",
+ description:
+ "List the things on the current page you can act on: fields, buttons, links and checkboxes, " +
+ "each with a ref, its label and its current value. Call this BEFORE clicking or typing, and " +
+ "use the refs it returns. Always send back the snapshotId it gives you. If an action reports " +
+ "that your refs are stale, the page changed: call this again and use the new refs.",
+ parameters: z.object({}),
+ handler: async () =>
+ callComputer(bot.current, "/snapshot", { method: "POST" }),
+ // Snapshot renders a count only; navigate owns the screen view.
+ render: ({ result, status }) => {
+ const outcome = outcomeOf(result);
+ const elements = Array.isArray(outcome.elements) ? outcome.elements : [];
+ return (
+ <ActionLine
+ running={status !== "complete"}
+ label="Read the page"
+ detail={
+ elements.length
+ ? `${elements.length} thing${elements.length === 1 ? "" : "s"} it can act on`
+ : undefined
+ }
+ />
+ );
+ },
+ });
+
+ useFrontendTool({
+ name: "computer_type",
+ description:
+ "Enter text into a field on the page. Give the ref of the field from your most recent " +
+ "snapshot and the snapshotId it came from. This replaces whatever the field already contains. " +
+ "Set submit to true to press Enter afterwards.",
+ parameters: z.object({
+ ref: z
+ .string()
+ .describe("Ref of the field, from your most recent snapshot"),
+ snapshotId: z.number().describe("The snapshotId that ref came from"),
+ text: z.string().describe("The text to enter"),
+ submit: z
+ .boolean()
+ .optional()
+ .describe("Press Enter after typing, to submit a single-field form"),
+ }),
+ handler: async (
+ input: {
+ ref: string;
+ snapshotId: number;
+ text: string;
+ submit?: boolean;
+ },
+ { signal }: { signal?: AbortSignal } = {},
+ ) =>
+ callComputer(
+ bot.current,
+ "/type",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ signal,
+ ),
+ render: ({ args, result, status }) => (
+ <ActionLine
+ running={status !== "complete"}
+ label="Filled in"
+ detail={
+ // Never show typed values; identify only the target field.
+ labelOf(result) ??
+ (typeof args?.ref === "string" ? args.ref : undefined)
+ }
+ refused={outcomeOf(result).refused === true}
+ failed={didNotWork(outcomeOf(result))}
+ />
+ ),
+ });
+
+ useFrontendTool({
+ name: "computer_click",
+ description:
+ "Click something on the page: a button, a link, a checkbox or a radio option. Give the ref " +
+ "from your most recent snapshot and the snapshotId it came from.",
+ parameters: z.object({
+ ref: z
+ .string()
+ .describe(
+ "Ref of the element to click, from your most recent snapshot",
+ ),
+ snapshotId: z.number().describe("The snapshotId that ref came from"),
+ }),
+ handler: async (
+ input: { ref: string; snapshotId: number },
+ { signal }: { signal?: AbortSignal } = {},
+ ) =>
+ callComputer(
+ bot.current,
+ "/click",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ signal,
+ ),
+ render: ({ args, result, status }) => {
+ const outcome = outcomeOf(result);
+ return (
+ <ActionLine
+ running={status !== "complete"}
+ label="Clicked"
+ detail={
+ // Show refusal reason instead of an internal element ref.
+ outcome.refused === true
+ ? String(outcome.reason ?? "")
+ : (labelOf(result) ??
+ (typeof args?.ref === "string" ? args.ref : undefined))
+ }
+ refused={outcome.refused === true}
+ failed={didNotWork(outcome)}
+ />
+ );
+ },
+ });
+
+ useFrontendTool({
+ name: "computer_key",
+ description:
+ "Press a key, such as Enter, Tab or Escape. Give a ref to press it while a particular field " +
+ "is focused, or omit the ref to press it on the page.",
+ parameters: z.object({
+ key: z.string().describe("Key name, such as Enter, Tab or Escape"),
+ ref: z.string().optional().describe("Optional ref to press the key on"),
+ snapshotId: z
+ .number()
+ .optional()
+ .describe("The snapshotId the ref came from, required if ref is given"),
+ }),
+ handler: async (
+ input: {
+ key: string;
+ ref?: string;
+ snapshotId?: number;
+ },
+ { signal }: { signal?: AbortSignal } = {},
+ ) =>
+ callComputer(
+ bot.current,
+ "/key",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ signal,
+ ),
+ render: ({ args, result, status }) => (
+ <ActionLine
+ running={status !== "complete"}
+ label="Pressed"
+ detail={typeof args?.key === "string" ? args.key : undefined}
+ refused={outcomeOf(result).refused === true}
+ failed={didNotWork(outcomeOf(result))}
+ />
+ ),
+ });
+
+ useFrontendTool({
+ name: "computer_request_secret",
+ description:
+ "Ask the person for ONE value you must not be told: a password, a one-time code, a card number. " +
+ "Focus the field first with computer_click, then call this with the ref of that field and a " +
+ "short label for what you need. They type it into a masked box that goes straight to the page. " +
+ "You will never see the value, and you must not ask for it any other way. Prefer this over a " +
+ "full takeover when you only need one field filled in. The value is only TYPED into the field: " +
+ "if the form needs submitting, do that yourself afterwards with computer_click.",
+ parameters: z.object({
+ label: z
+ .string()
+ .describe(
+ "What you need, in a few words, e.g. 'the code sent to your phone'",
+ ),
+ ref: z
+ .string()
+ .describe(
+ "Ref of the field it goes in, from your most recent snapshot",
+ ),
+ snapshotId: z.number().describe("The snapshotId that ref came from"),
+ }),
+ handler: async (
+ input: { label: string; ref: string; snapshotId: number },
+ { signal }: { signal?: AbortSignal } = {},
+ ) => {
+ const botId = bot.current;
+ const asked = await callComputer(
+ botId,
+ "/control/secret",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ signal,
+ );
+ if (!asked.ok) return asked;
+
+ // Completion is `secretWanted` clearing; the value never returns to the model.
+ const outcome = await waitForPerson(
+ botId,
+ (state) => state.secretWanted === undefined,
+ signal,
+ );
+ return {
+ ok: true,
+ result:
+ outcome === "answered"
+ ? `The person has entered ${input.label} into the field. It was typed straight into the page and you were not told what it is.`
+ : outcome === "cancelled"
+ ? "The request was cancelled."
+ : `Nobody entered ${input.label}. Do not ask for it another way.`,
+ };
+ },
+ // Rendered by ComputerView as a masked prompt.
+ render: () => null,
+ });
+
+ /** Self-reported model declines: audit evidence, not an enforcement control. */
+ useFrontendTool({
+ name: "report_refusal",
+ description:
+ "Record that you DECLINED something you were asked to do, because it looked unsafe, was outside " +
+ "what you are for, or you judged you should not. Call this whenever you say no to a request, in " +
+ "addition to telling the person. It changes nothing about your answer; it exists so an " +
+ "administrator can see what this Bot is being asked to do. Do not call it when you simply could " +
+ "not do something, only when you chose not to.",
+ parameters: z.object({
+ reason: z
+ .string()
+ .describe("Why you declined, in one sentence and in your own words"),
+ request: z
+ .string()
+ .optional()
+ .describe("What you were asked to do, in a few words"),
+ }),
+ handler: async (
+ input: { reason: string; request?: string },
+ { signal }: { signal?: AbortSignal } = {},
+ ) => {
+ try {
+ const response = await fetch(
+ `/api/agents/${encodeURIComponent(bot.current)}/declined`,
+ {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ ...(signal ? { signal } : {}),
+ },
+ );
+ return response.ok
+ ? "Recorded. Now tell the person what you decided and why."
+ : "That could not be recorded. Tell the person what you decided anyway.";
+ } catch {
+ // Audit bookkeeping must not prevent the Bot from answering.
+ return "That could not be recorded. Tell the person what you decided anyway.";
+ }
+ },
+ render: () => null,
+ });
+
+ useFrontendTool({
+ name: "computer_request_help",
+ description:
+ "Ask the person to take control of your computer and do something you cannot: sign in, enter a " +
+ "password or a one-time code, or clear a CAPTCHA. Say specifically what you need done. They " +
+ "will drive the browser themselves and hand it back, and you carry on in the same session. " +
+ "Use this INSTEAD of giving up, and instead of ever asking them to type a password to you.",
+ parameters: z.object({
+ reason: z
+ .string()
+ .describe(
+ "What you need the person to do, in one sentence, e.g. 'This page is asking for a code sent to your phone.'",
+ ),
+ }),
+ handler: async (
+ input: { reason: string },
+ { signal }: { signal?: AbortSignal } = {},
+ ) => {
+ const botId = bot.current;
+ const asked = await callComputer(
+ botId,
+ "/control/request",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ signal,
+ );
+ if (!asked.ok) return asked;
+
+ // Resolved when the wheel is back with the Bot and no help request remains outstanding.
+ const outcome = await waitForPerson(
+ botId,
+ (state) => state.holder === "bot" && !state.requested,
+ signal,
+ );
+ return {
+ ok: true,
+ result:
+ outcome === "answered"
+ ? "The person has finished and handed control back. Take a fresh snapshot: the page may have changed while they were driving."
+ : outcome === "cancelled"
+ ? "The request was cancelled."
+ : "Nobody took control. Say what you still need rather than trying to do it yourself.",
+ };
+ },
+ // Rendered by ComputerView as the take-the-wheel prompt.
+ render: () => null,
+ });
+
+ useFrontendTool({
+ name: "computer_list_files",
+ description:
+ "List what is in your workspace: every file and folder you have saved, with sizes. Call this " +
+ "FIRST when you are asked what files you have, or before reading a file whose exact name you " +
+ "are not sure of. Never guess a filename.",
+ parameters: z.object({
+ path: z
+ .string()
+ .optional()
+ .describe("Optional folder to list. Omit for the whole workspace."),
+ }),
+ handler: async (input: { path?: string }) =>
+ callComputer(bot.current, "/files/list", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input ?? {}),
+ }),
+ render: ({ result, status }) => {
+ const outcome = outcomeOf(result);
+ const entries = Array.isArray(outcome.entries) ? outcome.entries : [];
+ return (
+ <ActionLine
+ running={status !== "complete"}
+ label="Listed files"
+ detail={
+ outcome.refused === true || didNotWork(outcome)
+ ? String(outcome.reason ?? "")
+ : entries.length
+ ? `${entries.length} item${entries.length === 1 ? "" : "s"} in the workspace`
+ : "nothing saved yet"
+ }
+ refused={outcome.refused === true}
+ failed={didNotWork(outcome)}
+ />
+ );
+ },
+ });
+
+ useFrontendTool({
+ name: "computer_read_file",
+ description:
+ "Read a file you saved earlier in your own workspace. Paths are relative to your workspace, " +
+ "such as notes.md or reports/august.csv. Your workspace survives between conversations, so use " +
+ "this to pick up notes you made before.",
+ parameters: z.object({
+ path: z
+ .string()
+ .describe("Path relative to your workspace, such as notes.md"),
+ }),
+ handler: async (input: { path: string }) =>
+ callComputer(bot.current, "/files/read", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ render: ({ args, result, status }) => {
+ const outcome = outcomeOf(result);
+ return (
+ <ActionLine
+ running={status !== "complete"}
+ label="Read file"
+ detail={
+ outcome.refused === true
+ ? String(outcome.reason ?? "")
+ : typeof args?.path === "string"
+ ? args.path
+ : undefined
+ }
+ refused={outcome.refused === true}
+ failed={didNotWork(outcome)}
+ />
+ );
+ },
+ });
+
+ useFrontendTool({
+ name: "computer_write_file",
+ description:
+ "Save a file in your own workspace so you still have it later. Paths are relative to your " +
+ "workspace and folders are created as needed. Set append to true to add to the end of an " +
+ "existing file rather than replacing it. Text only.",
+ parameters: z.object({
+ path: z
+ .string()
+ .describe(
+ "Path relative to your workspace, such as reports/august.csv",
+ ),
+ contents: z.string().describe("The text to save"),
+ append: z
+ .boolean()
+ .optional()
+ .describe("Add to the end of the file instead of replacing it"),
+ }),
+ handler: async (input: {
+ path: string;
+ contents: string;
+ append?: boolean;
+ }) =>
+ callComputer(bot.current, "/files/write", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ render: ({ args, result, status }) => {
+ const outcome = outcomeOf(result);
+ return (
+ <ActionLine
+ running={status !== "complete"}
+ label={args?.append === true ? "Added to file" : "Saved file"}
+ // Show the path, never file contents.
+ detail={
+ outcome.refused === true
+ ? String(outcome.reason ?? "")
+ : typeof args?.path === "string"
+ ? args.path
+ : undefined
+ }
+ refused={outcome.refused === true}
+ failed={didNotWork(outcome)}
+ />
+ );
+ },
+ });
+
+ useFrontendTool({
+ name: "computer_scroll",
+ description:
+ "Scroll the page down, or up with a negative amount, to bring more of a long page into view.",
+ parameters: z.object({
+ deltaY: z
+ .number()
+ .optional()
+ .describe("Pixels to scroll; positive is down. Defaults to 600."),
+ }),
+ handler: async (
+ input: { deltaY?: number },
+ { signal }: { signal?: AbortSignal } = {},
+ ) =>
+ callComputer(
+ bot.current,
+ "/scroll",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ signal,
+ ),
+ render: ({ result, status }) => (
+ <ActionLine
+ running={status !== "complete"}
+ label="Scrolled"
+ refused={outcomeOf(result).refused === true}
+ failed={didNotWork(outcomeOf(result))}
+ />
+ ),
+ });
+
+ return null;
+}
diff --git a/app/src/lib/copilot/conversation.tsx b/app/src/lib/copilot/conversation.tsx
new file mode 100644
index 00000000..bd58740a
--- /dev/null
+++ b/app/src/lib/copilot/conversation.tsx
@@ -0,0 +1,33 @@
+import { createContext, type ReactNode, useContext, useMemo } from "react";
+
+/**
+ * Lets transcript-rendered components add a user turn back into the containing conversation.
+ */
+
+type Conversation = {
+ /** Submit a user turn from a transcript-rendered component. */
+ ask: (text: string) => void;
+};
+
+const ConversationContext = createContext<Conversation | null>(null);
+
+export function ConversationProvider({
+ ask,
+ children,
+}: {
+ ask: (text: string) => void;
+ children: ReactNode;
+}) {
+ // Keep context identity stable across unrelated composer renders.
+ const value = useMemo(() => ({ ask }), [ask]);
+ return (
+ <ConversationContext.Provider value={value}>
+ {children}
+ </ConversationContext.Provider>
+ );
+}
+
+/** The conversation this component is drawn in, if it is drawn in one. */
+export function useConversation(): Conversation | null {
+ return useContext(ConversationContext);
+}
diff --git a/app/src/lib/copilot/gallery-registry.ts b/app/src/lib/copilot/gallery-registry.ts
new file mode 100644
index 00000000..465bd116
--- /dev/null
+++ b/app/src/lib/copilot/gallery-registry.ts
@@ -0,0 +1,93 @@
+import type { useFrontendTool } from "@copilotkit/react-core/v2";
+import type { ReactElement } from "react";
+
+/**
+ * Discover gallery components from files that export `GALLERY`; deployment state owns publication,
+ * grants, and published descriptions after first announcement.
+ */
+
+/** The schema type the SDK itself accepts, so a component never needs a cast to register. */
+export type ToolParameters = Parameters<
+ typeof useFrontendTool
+>[0]["parameters"];
+
+/** Grouping for the Admin page only. Never read by the model. */
+export type GalleryKind = "chart" | "card" | "decision";
+
+export type GalleryComponent = {
+ /**
+ * The tool name the model calls, the catalogue key, and the stable fork-facing component id.
+ */
+ name: string;
+ /** What a person sees in Admin and in a refusal. */
+ title: string;
+ kind: GalleryKind;
+ /**
+ * What the model reads while deciding whether to call this. A starting value only: a deployment
+ * edits and publishes its own, and that is what a running Bot is given.
+ */
+ description: string;
+ parameters: ToolParameters;
+ Component: (props: Record<string, unknown>) => ReactElement | null;
+ /**
+ * The line the model is given once it is on screen. Ignored for a `decision`, whose result is the
+ * user's answer.
+ */
+ confirmation?: string;
+ /**
+ * The data functions this component will read, given the arguments it was called with.
+ *
+ * A component that reads nothing omits it. One that does declares it here so the grant covering
+ * that data is decided before the model is told the component is on screen.
+ */
+ reads?: (args: Record<string, unknown>) => readonly string[];
+};
+
+/**
+ * Every gallery module, loaded eagerly because the list has to exist before the first render: it
+ * decides how many hooks are registered, and a hook count that arrives late is a hook count that
+ * changed.
+ *
+ * Uses a relative pattern because `import.meta.glob` does not resolve the `@/` alias. Files without
+ * a `GALLERY` export are skipped.
+ */
+let modules: Record<string, { GALLERY?: GalleryComponent[] }> = {};
+try {
+ // Keep this call inline: Vite replaces `import.meta.glob` at build time.
+ modules = import.meta.glob<{ GALLERY?: GalleryComponent[] }>(
+ "../../components/gallery/*.tsx",
+ { eager: true },
+ );
+} catch {
+ // Outside Vite/test-runner contexts, `import.meta.glob` may be unavailable; empty gallery is the safe fallback.
+ modules = {};
+}
+
+/**
+ * Stable order is required because this list drives hook registration order.
+ */
+export const GALLERY_COMPONENTS: GalleryComponent[] = Object.values(modules)
+ .flatMap((module) => module.GALLERY ?? [])
+ .sort((left, right) => left.name.localeCompare(right.name));
+
+/** What the server is told exists. Deliberately not the schema or the renderer: it cannot use either. */
+export type GalleryManifestEntry = {
+ name: string;
+ title: string;
+ kind: GalleryKind;
+ description: string;
+};
+
+export function galleryManifest(): GalleryManifestEntry[] {
+ return GALLERY_COMPONENTS.map(({ name, title, kind, description }) => ({
+ name,
+ title,
+ kind,
+ description,
+ }));
+}
+
+/** The names this build can actually draw, for telling a catalogue row from a component. */
+export const RENDERABLE_NAMES: ReadonlySet<string> = new Set(
+ GALLERY_COMPONENTS.map((component) => component.name),
+);
diff --git a/app/src/lib/copilot/gallery-tools.tsx b/app/src/lib/copilot/gallery-tools.tsx
new file mode 100644
index 00000000..26b39a2a
--- /dev/null
+++ b/app/src/lib/copilot/gallery-tools.tsx
@@ -0,0 +1,204 @@
+import { useFrontendTool, useHumanInTheLoop } from "@copilotkit/react-core/v2";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { RefusedCard } from "@/components/gallery/refused";
+import {
+ agentComponentsQueryOptions,
+ announceGallery,
+ componentKeys,
+ decideComponent,
+ type GrantedComponent,
+} from "@/lib/components/queries";
+import { useActiveBotId } from "@/lib/copilot/active-bot";
+import {
+ GALLERY_COMPONENTS,
+ type GalleryComponent,
+ galleryManifest,
+} from "@/lib/copilot/gallery-registry";
+
+/**
+ * Register compiled gallery components once per name, scoped to the active Bot with `available`.
+ * Handlers still recheck grants at call time because a run's offered tool list is only a snapshot.
+ */
+export function GalleryTools() {
+ const queryClient = useQueryClient();
+ useEffect(() => {
+ void announceGallery(galleryManifest()).then((added) => {
+ if (added.length > 0) {
+ void queryClient.invalidateQueries({ queryKey: componentKeys.all });
+ }
+ });
+ }, [queryClient]);
+
+ // Active Bot comes from the route/channel surface currently driving the provider.
+ const grantsFor = useActiveBotId();
+ const { data: granted } = useQuery(agentComponentsQueryOptions(grantsFor));
+ const held = useMemo(
+ () =>
+ new Map(
+ (granted ?? []).map((component: GrantedComponent) => [
+ component.name,
+ component.description,
+ ]),
+ ),
+ [granted],
+ );
+
+ return (
+ <>
+ {GALLERY_COMPONENTS.map((spec) =>
+ spec.kind === "decision" ? (
+ <GrantedDecision held={held} key={spec.name} spec={spec} />
+ ) : (
+ <GrantedTool
+ grantsFor={grantsFor}
+ held={held}
+ key={spec.name}
+ spec={spec}
+ />
+ ),
+ )}
+ </>
+ );
+}
+
+function GrantedTool({
+ grantsFor,
+ spec,
+ held,
+}: {
+ grantsFor: string;
+ spec: GalleryComponent;
+ held: Map<string, string>;
+}) {
+ const description = held.get(spec.name);
+ const isHeld = description !== undefined;
+
+ /**
+ * Refusals decided by the server, keyed by the call they refused.
+ *
+ * Per-call keys preserve the original render for calls made before a grant was revoked.
+ */
+ const [refusals, setRefusals] = useState<ReadonlyMap<string, string>>(
+ new Map(),
+ );
+
+ const Component = spec.Component;
+
+ const render = useCallback(
+ (props: { toolCallId?: string; args?: Record<string, unknown> }) => {
+ const refusal = props.toolCallId
+ ? refusals.get(props.toolCallId)
+ : undefined;
+ if (refusal) {
+ return <RefusedCard reason={refusal} title={spec.title} />;
+ }
+ // Render from the polled grant snapshot so revocations show before a new call starts.
+ if (!isHeld) {
+ return (
+ <RefusedCard
+ reason={`${spec.title} is not available to this Bot at the moment. An administrator grants components per Bot, and can unpublish one for every Bot at once.`}
+ title={spec.title}
+ />
+ );
+ }
+ return <Component {...(props.args ?? {})} />;
+ },
+ [Component, isHeld, refusals, spec.title],
+ );
+
+ useFrontendTool({
+ name: spec.name,
+ // Published descriptions are model-facing runtime behavior.
+ description: description ?? spec.description,
+ parameters: spec.parameters,
+ // Keep the hook mounted and hide revoked grants from the model to preserve hook order.
+ available: isHeld,
+ handler: async (
+ args: Record<string, unknown>,
+ context: { toolCall?: { id?: string } },
+ ) => {
+ const decision = await decideComponent(
+ spec.name,
+ grantsFor,
+ spec.reads?.(args ?? {}) ?? [],
+ );
+ if (!decision.allowed) {
+ const reason = decision.reason ?? "That component is not allowed here.";
+ const id = context?.toolCall?.id;
+ if (id) {
+ setRefusals((current) => new Map(current).set(id, reason));
+ }
+ // Led with the same words the card shows, so the transcript and the card agree.
+ return `Not shown: ${spec.title}. ${reason} Nothing was displayed, so tell the person that.`;
+ }
+ return spec.confirmation ?? "It is now on screen for the person.";
+ },
+ render,
+ });
+
+ return null;
+}
+
+function GrantedDecision({
+ spec,
+ held,
+}: {
+ spec: GalleryComponent;
+ held: Map<string, string>;
+}) {
+ const description = held.get(spec.name);
+ const isHeld = description !== undefined;
+ const Component = spec.Component;
+
+ /** Stable component type so in-progress decision cards do not remount. */
+ const Render = useMemo(
+ () =>
+ function DecisionRender(props: Record<string, unknown>) {
+ if (isHeld) return <Component {...props} />;
+ return (
+ <RefusedDecision
+ respond={
+ props.respond as ((result: unknown) => Promise<void>) | undefined
+ }
+ title={spec.title}
+ />
+ );
+ },
+ [Component, isHeld, spec.title],
+ );
+
+ useHumanInTheLoop({
+ name: spec.name,
+ description: description ?? spec.description,
+ parameters: spec.parameters,
+ available: isHeld,
+ render: Render,
+ });
+
+ return null;
+}
+
+/**
+ * A decision the Bot was not allowed to ask for.
+ *
+ * Decision tools suspend the run, so a refusal must also answer the tool call.
+ */
+function RefusedDecision({
+ title,
+ respond,
+}: {
+ title: string;
+ respond?: (result: unknown) => Promise<void>;
+}) {
+ const reason = `${title} is not available to this Bot at the moment, so the person was not asked. An administrator grants components per Bot, and can unpublish one for every Bot at once.`;
+
+ useEffect(() => {
+ if (!respond) return;
+ void respond(reason).catch(() => {
+ // The run being gone is not a failure worth reporting: there is nothing left to answer.
+ });
+ }, [respond, reason]);
+
+ return <RefusedCard reason={reason} title={title} />;
+}
diff --git a/app/src/lib/copilot/plugin-tools.tsx b/app/src/lib/copilot/plugin-tools.tsx
new file mode 100644
index 00000000..3e2ae66a
--- /dev/null
+++ b/app/src/lib/copilot/plugin-tools.tsx
@@ -0,0 +1,209 @@
+import { useFrontendTool } from "@copilotkit/react-core/v2";
+import { useQuery } from "@tanstack/react-query";
+import { useRef, useState } from "react";
+import { Streamdown } from "streamdown";
+import { ToolLine } from "@/components/channels/tool-line";
+import { markdownComponents } from "@/lib/markdown";
+import * as z from "zod";
+import { useActiveBotId } from "@/lib/copilot/active-bot";
+import {
+ agentPluginsQueryOptions,
+ callPluginTool,
+ type GrantedPlugins,
+} from "@/lib/plugins/queries";
+
+/**
+ * Runtime-discovered MCP tools granted to the active Bot. Registration controls what is offered;
+ * the server still rechecks each call.
+ */
+export function PluginTools() {
+ const botId = useActiveBotId();
+ const { data } = useQuery(agentPluginsQueryOptions(botId));
+ const granted: GrantedPlugins = data ?? { tools: [], skills: [] };
+
+ /** Keep previously offered tools mounted so mid-run revocations can return explicit refusals. */
+ const seen = useRef(new Map<string, GrantedPlugins["tools"][number]>());
+ for (const tool of granted.tools) seen.current.set(tool.ref, tool);
+ const offered = [...seen.current.values()];
+
+ return (
+ <>
+ {offered.map((tool) => (
+ <PluginTool
+ botId={botId}
+ description={tool.description}
+ inputSchema={tool.inputSchema}
+ key={tool.ref}
+ name={tool.toolName}
+ toolRef={tool.ref}
+ />
+ ))}
+ </>
+ );
+}
+
+/** Convert vendor JSON Schema to SDK parameters; unreadable schemas fall back to catchall. */
+function parametersFor(inputSchema: Record<string, unknown>) {
+ try {
+ const converted = z.fromJSONSchema(inputSchema as never);
+ // Only object schemas describe tool arguments; other vendor schemas fall back to catchall.
+ if (converted instanceof z.ZodObject) return converted;
+ } catch {}
+ return z.object({}).catchall(z.unknown());
+}
+
+/**
+ * A tool result, as something worth looking at.
+ *
+ * MCP says a text part, and vendors fill it with anything from plain markdown to a JSON envelope
+ * with the markdown inside one field. Markdown is drawn as markdown, a JSON wrapper is unwrapped to
+ * the markdown it was hiding, and anything else is fenced as JSON. Nothing is discarded.
+ */
+function forDisplay(text: string): string {
+ const trimmed = text.trim();
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return text;
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ // Not JSON after all. Draw what the server sent.
+ return text;
+ }
+
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ const entries = Object.entries(parsed as Record<string, unknown>);
+ // The field carrying the answer, told apart from the ones carrying bookkeeping: Slack sends
+ // `{ results, pagination_info }`. The rest is kept below rather than dropped.
+ const markdown = entries
+ .filter(
+ ([, value]) =>
+ typeof value === "string" &&
+ (value.includes("\n#") || value.startsWith("#")),
+ )
+ .sort((a, b) => String(b[1]).length - String(a[1]).length)[0];
+
+ if (markdown) {
+ const rest = entries.filter(([key]) => key !== markdown[0]);
+ const body = String(markdown[1]);
+ if (rest.length === 0) return body;
+ return `${body}\n\n\`\`\`json\n${JSON.stringify(
+ Object.fromEntries(rest),
+ null,
+ 2,
+ )}\n\`\`\``;
+ }
+ }
+
+ return `\`\`\`json\n${JSON.stringify(parsed, null, 2)}\n\`\`\``;
+}
+
+function PluginTool({
+ name,
+ toolRef,
+ description,
+ inputSchema,
+ botId,
+}: {
+ name: string;
+ toolRef: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+ botId: string;
+}) {
+ /**
+ * Per-call render state. The SDK captures `render` at registration, so the renderer must read
+ * current results from a ref keyed by tool call id.
+ */
+ const calls = useRef(
+ new Map<
+ string,
+ {
+ result?: { text: string; isError: boolean };
+ outcome?: { refused: boolean; reason: string };
+ }
+ >(),
+ );
+ /** Bumped only to make React redraw; the data itself lives in the ref above. */
+ const [, redraw] = useState(0);
+ const touch = () => redraw((tick) => tick + 1);
+
+ const [serverId, ...rest] = toolRef.split("/");
+ const bareName = rest.join("/");
+
+ useFrontendTool({
+ name,
+ // The vendor's own description, with the server named. A model choosing between two servers that
+ // both offer "search" needs to know which is which, and vendors do not write their descriptions
+ // expecting to sit beside another vendor's.
+ description: description
+ ? `${description} (${serverId})`
+ : `${bareName} on ${serverId}.`,
+ parameters: parametersFor(inputSchema),
+ handler: async (
+ args: Record<string, unknown>,
+ // DEFAULTED, because the context argument is optional and a handler that destructures it
+ // unconditionally throws on any call that omits it.
+ context: { signal?: AbortSignal; toolCall?: { id?: string } } = {},
+ ) => {
+ const id = context.toolCall?.id ?? "";
+ const result = await callPluginTool(
+ toolRef,
+ args ?? {},
+ botId,
+ context.signal,
+ );
+
+ if (result.ok) {
+ calls.current.set(id, {
+ result: { text: result.text, isError: result.isError },
+ });
+ touch();
+ // Return MCP text to the model; vendor errors stay as tool results instead of thrown errors.
+ return result.isError
+ ? `The tool reported an error: ${result.text}`
+ : result.text;
+ }
+
+ calls.current.set(id, {
+ outcome: { refused: result.refused, reason: result.reason },
+ });
+ touch();
+ return result.reason;
+ },
+ render: ({ status, toolCallId }) => {
+ const entry = calls.current.get(toolCallId ?? "") ?? {};
+ const { result, outcome } = entry;
+
+ // Render policy refusals separately from vendor/server failures.
+ if (outcome) {
+ return (
+ <ToolLine
+ detail={outcome.reason}
+ failed={!outcome.refused}
+ label={bareName}
+ refused={outcome.refused}
+ />
+ );
+ }
+
+ return (
+ <ToolLine
+ detail={serverId}
+ failed={result?.isError}
+ label={bareName}
+ running={status !== "complete"}
+ >
+ {result ? (
+ /* The server's own words, drawn the way a Bot's prose is drawn. */
+ <Streamdown components={markdownComponents}>
+ {forDisplay(result.text)}
+ </Streamdown>
+ ) : null}
+ </ToolLine>
+ );
+ },
+ });
+
+ return null;
+}
diff --git a/app/src/lib/copilot/provider.tsx b/app/src/lib/copilot/provider.tsx
new file mode 100644
index 00000000..10963975
--- /dev/null
+++ b/app/src/lib/copilot/provider.tsx
@@ -0,0 +1,39 @@
+import { CopilotKitProvider } from "@copilotkit/react-core/v2";
+import type { ReactNode } from "react";
+import { ActiveBotProvider } from "./active-bot";
+import { ComputerTools } from "./computer-tools";
+import { GalleryTools } from "./gallery-tools";
+import { PluginTools } from "./plugin-tools";
+import { SandboxedTools } from "./sandboxed-tools";
+
+/**
+ * The CopilotKit client, wrapped once for the whole authenticated app.
+ *
+ * `credentials: "include"` is the load-bearing part. OpenBot authenticates with a Better Auth
+ * session cookie, and the runtime endpoint sits behind the same guard as every other API route, so
+ * without it every run is rejected as anonymous while the rest of the app looks signed in.
+ *
+ * The URL is relative, like every other call in the app, so the Vite dev proxy and a single-origin
+ * deployment both work without a build-time base URL to get wrong.
+ *
+ * There is no `publicApiKey`. The Intelligence key and licence token are deployment secrets held by
+ * the server; a browser never sees them (see server/src/app.ts, where /api/capabilities projects the
+ * runtime rather than returning it).
+ */
+export function CopilotProvider({ children }: { children: ReactNode }) {
+ return (
+ <CopilotKitProvider runtimeUrl="/api/copilotkit" credentials="include">
+ {/* Computer tools target the Bot declared by the mounted surface. */}
+ <ActiveBotProvider>
+ <ComputerTools />
+ {/* Gallery tools are registered once; their handlers re-read the active Bot to avoid shadowing renderers. */}
+ <GalleryTools />
+ {/* MCP tools share the same active-Bot context and server-side grant checks. */}
+ <PluginTools />
+ {/* Browser-authored components use the same component grants as the compiled gallery. */}
+ <SandboxedTools />
+ {children}
+ </ActiveBotProvider>
+ </CopilotKitProvider>
+ );
+}
diff --git a/app/src/lib/credentials/form.ts b/app/src/lib/credentials/form.ts
new file mode 100644
index 00000000..09709ac9
--- /dev/null
+++ b/app/src/lib/credentials/form.ts
@@ -0,0 +1,10 @@
+import { z } from "zod";
+
+export const credentialFormSchema = z.object({
+ kind: z.enum(["model", "connector"]),
+ provider: z.string().trim().min(1, "Provider is required."),
+ keyId: z.string().trim().min(1, "Key ID is required."),
+ plaintext: z.string().min(1, "Secret is required."),
+});
+
+export type CredentialFormValues = z.infer<typeof credentialFormSchema>;
diff --git a/app/src/lib/credentials/mutations.ts b/app/src/lib/credentials/mutations.ts
new file mode 100644
index 00000000..950651a1
--- /dev/null
+++ b/app/src/lib/credentials/mutations.ts
@@ -0,0 +1,38 @@
+import { mutationOptions, type QueryClient } from "@tanstack/react-query";
+import { credentialKeys } from "./queries";
+
+export type CredentialInput = {
+ kind: "model" | "connector";
+ provider: string;
+ keyId: string;
+ metadata: Record<string, unknown>;
+ plaintext: string;
+};
+
+async function credentialRequest(path: string, body?: CredentialInput) {
+ const response = await fetch(path, {
+ method: "POST",
+ credentials: "include",
+ headers: body ? { "content-type": "application/json" } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ if (!response.ok) throw new Error("Credential operation failed");
+}
+
+export function createCredentialMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: (input: CredentialInput) =>
+ credentialRequest("/api/admin/credentials", input),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: credentialKeys.all }),
+ });
+}
+
+export function revokeCredentialMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: (credentialId: string) =>
+ credentialRequest(`/api/admin/credentials/${credentialId}/revoke`),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: credentialKeys.all }),
+ });
+}
diff --git a/app/src/lib/credentials/queries.ts b/app/src/lib/credentials/queries.ts
new file mode 100644
index 00000000..4cc2c7eb
--- /dev/null
+++ b/app/src/lib/credentials/queries.ts
@@ -0,0 +1,29 @@
+import { queryOptions } from "@tanstack/react-query";
+
+export type CredentialStatus = {
+ id: string;
+ kind: "model" | "connector";
+ provider: string;
+ keyId: string;
+ metadata: Record<string, unknown>;
+ revokedAt: string | null;
+};
+
+export const credentialKeys = {
+ all: ["credentials"] as const,
+ list: () => [...credentialKeys.all, "list"] as const,
+};
+
+export function credentialListQueryOptions() {
+ return queryOptions({
+ queryKey: credentialKeys.list(),
+ queryFn: async (): Promise<CredentialStatus[]> => {
+ const response = await fetch("/api/admin/credentials", {
+ credentials: "include",
+ });
+ if (!response.ok) throw new Error("Could not load credentials");
+ return ((await response.json()) as { credentials: CredentialStatus[] })
+ .credentials;
+ },
+ });
+}
diff --git a/app/src/lib/markdown.tsx b/app/src/lib/markdown.tsx
new file mode 100644
index 00000000..0342968e
--- /dev/null
+++ b/app/src/lib/markdown.tsx
@@ -0,0 +1,21 @@
+import type { ComponentProps } from "react";
+
+/**
+ * Shared markdown rendering for Bot prose and tool results.
+ *
+ * Links open in a new tab with `noreferrer` because content can come from a model or remote MCP
+ * server.
+ */
+export const markdownComponents = {
+ a: ({ href, children, ...rest }: ComponentProps<"a">) => (
+ <a
+ {...rest}
+ className="underline underline-offset-2 hover:no-underline"
+ href={href}
+ rel="noreferrer noopener"
+ target="_blank"
+ >
+ {children}
+ </a>
+ ),
+};
diff --git a/app/src/lib/motion.ts b/app/src/lib/motion.ts
new file mode 100644
index 00000000..d9eda61d
--- /dev/null
+++ b/app/src/lib/motion.ts
@@ -0,0 +1,18 @@
+/**
+ * The app's motion vocabulary, in one place.
+ *
+ * These values were written out by hand in `detail-panel.tsx` and again in `app-sidebar.tsx`, and
+ * the transcript would have been a third copy. Motion that is meant to read as one hand cannot be
+ * three sets of magic numbers that happen to agree today.
+ */
+
+/** Strong ease-out. The browser's built-in curve is too weak to read as deliberate. */
+export const EASE_OUT = [0.23, 1, 0.32, 1] as const;
+
+/**
+ * How long something takes to arrive.
+ *
+ * Entrances are the one place a curve is watched closely, and anything past ~250ms starts reading
+ * as the interface thinking rather than responding.
+ */
+export const ENTRANCE_SECONDS = 0.2;
diff --git a/app/src/lib/package/queries.ts b/app/src/lib/package/queries.ts
new file mode 100644
index 00000000..630df72a
--- /dev/null
+++ b/app/src/lib/package/queries.ts
@@ -0,0 +1,16 @@
+import { queryOptions } from "@tanstack/react-query";
+
+export const packageKeys = { active: ["tenant-package", "active"] as const };
+
+export function activePackageQueryOptions() {
+ return queryOptions({
+ queryKey: packageKeys.active,
+ queryFn: async () => {
+ const response = await fetch("/api/admin/package", {
+ credentials: "include",
+ });
+ if (!response.ok) throw new Error("Could not load the active package");
+ return response.json();
+ },
+ });
+}
diff --git a/app/src/lib/sandboxed/queries.ts b/app/src/lib/sandboxed/queries.ts
new file mode 100644
index 00000000..73a8cc83
--- /dev/null
+++ b/app/src/lib/sandboxed/queries.ts
@@ -0,0 +1,76 @@
+import { queryOptions } from "@tanstack/react-query";
+
+/** A component authored in the browser, as the playground edits it. */
+export type SandboxedRecord = {
+ name: string;
+ title: string;
+ draftDescription: string;
+ draftHtml: string;
+ draftCss: string;
+ draftJsFunctions: string;
+ draftArgumentSchema: Record<string, unknown>;
+ publishedHtml: string | null;
+ publishedCss: string | null;
+ publishedJsFunctions: string | null;
+ publishedArgumentSchema: Record<string, unknown> | null;
+ sampleArguments: Record<string, unknown>;
+ revision: number;
+ published: boolean;
+ publishedAt: string | null;
+ authoredBy: string | null;
+ hasUnpublishedChanges: boolean;
+};
+
+/** What a Bot may actually draw with. The draft never appears here. */
+export type PublishedSandboxed = {
+ name: string;
+ html: string;
+ css: string;
+ jsFunctions: string;
+ /** What the model fills in. A tool with no parameters is called with no arguments. */
+ argumentSchema: Record<string, unknown>;
+};
+
+export const sandboxedKeys = {
+ all: ["sandboxed"] as const,
+ list: () => ["sandboxed", "list"] as const,
+ published: () => ["sandboxed", "published"] as const,
+};
+
+export function sandboxedListQueryOptions() {
+ return queryOptions({
+ queryKey: sandboxedKeys.list(),
+ queryFn: async (): Promise<SandboxedRecord[]> => {
+ const response = await fetch("/api/sandboxed", {
+ credentials: "include",
+ });
+ if (!response.ok) {
+ throw new Error("The playground's components could not be loaded.");
+ }
+ return (await response.json()).components ?? [];
+ },
+ });
+}
+
+/**
+ * The published source, which is what a conversation renders from.
+ *
+ * Refetched periodically so publishing takes effect in an open conversation without a reload. It is
+ * not what enforces anything: whether this Bot may use the component at all is the grant, which the
+ * server is asked about separately and at call time.
+ */
+export function publishedSandboxedQueryOptions() {
+ return queryOptions({
+ queryKey: sandboxedKeys.published(),
+ refetchInterval: 30_000,
+ queryFn: async (): Promise<PublishedSandboxed[]> => {
+ const response = await fetch("/api/sandboxed/published", {
+ credentials: "include",
+ });
+ if (!response.ok) {
+ throw new Error("The published components could not be loaded.");
+ }
+ return (await response.json()).components ?? [];
+ },
+ });
+}
diff --git a/app/src/lib/skills/form.ts b/app/src/lib/skills/form.ts
new file mode 100644
index 00000000..596243b1
--- /dev/null
+++ b/app/src/lib/skills/form.ts
@@ -0,0 +1,46 @@
+import { z } from "zod";
+
+/**
+ * The four things a person decides about a skill.
+ *
+ * THE LIMITS MATCH THE SERVER'S PARSER EXACTLY, so a form that submits is a form that will be
+ * accepted, and a rejection is shown next to the field that caused it rather than as a failed
+ * request with a sentence at the top of the page.
+ *
+ * The slug pattern is `routes.ts`'s, character for character: lower-case letters, digits and
+ * hyphens, starting and ending on an alphanumeric, 2 to 40 long. Loosening it here would only move
+ * the refusal later, to a place where it reads as the save being broken.
+ */
+export const skillFormSchema = z.object({
+ slug: z
+ .string()
+ .trim()
+ .min(1, "A command is required.")
+ .regex(
+ /^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$/,
+ "Lower-case letters, numbers and hyphens, 2 to 40 characters.",
+ ),
+ title: z
+ .string()
+ .trim()
+ .min(1, "A title is required.")
+ .max(120, "Title must be 120 characters or fewer."),
+ /** Optional on the server too, which is why there is no minimum here. */
+ summary: z
+ .string()
+ .trim()
+ .max(200, "The one-liner must be 200 characters or fewer."),
+ instructions: z
+ .string()
+ .trim()
+ .min(1, "Instructions are required — this is what the Bot follows."),
+});
+
+export type SkillFormValues = z.infer<typeof skillFormSchema>;
+
+export const emptySkillForm: SkillFormValues = {
+ slug: "",
+ title: "",
+ summary: "",
+ instructions: "",
+};
diff --git a/app/src/main.tsx b/app/src/main.tsx
new file mode 100644
index 00000000..fdcae396
--- /dev/null
+++ b/app/src/main.tsx
@@ -0,0 +1,22 @@
+import { QueryClientProvider } from "@tanstack/react-query";
+import { RouterProvider } from "@tanstack/react-router";
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { queryClient } from "./query-client";
+import { router } from "./router";
+import "@copilotkit/react-core/v2/styles.css";
+import "./styles.css";
+
+const rootElement = document.getElementById("root");
+
+if (!rootElement) {
+ throw new Error("OpenBot could not find the application root element.");
+}
+
+createRoot(rootElement).render(
+ <StrictMode>
+ <QueryClientProvider client={queryClient}>
+ <RouterProvider router={router} context={{ queryClient }} />
+ </QueryClientProvider>
+ </StrictMode>,
+);
diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.ts
new file mode 100644
index 00000000..3feb12cc
--- /dev/null
+++ b/app/src/routeTree.gen.ts
@@ -0,0 +1,540 @@
+/* eslint-disable */
+
+// @ts-nocheck
+
+// noinspection JSUnusedGlobalSymbols
+
+// This file was automatically generated by TanStack Router.
+// You should NOT make any changes in this file as it will be overwritten.
+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
+
+import { Route as rootRouteImport } from './routes/__root'
+import { Route as AuthedRouteImport } from './routes/_authed'
+import { Route as SignRouteImport } from './routes/sign'
+import { Route as AuthedAppRouteImport } from './routes/_authed/_app'
+import { Route as AuthedAdminRouteRouteImport } from './routes/_authed/admin/route'
+import { Route as AuthedSettingsRouteRouteImport } from './routes/_authed/settings/route'
+import { Route as AuthedAppIndexRouteImport } from './routes/_authed/_app/index'
+import { Route as AuthedAppBotRouteImport } from './routes/_authed/_app/bot'
+import { Route as AuthedAppSkillsRouteImport } from './routes/_authed/_app/skills'
+import { Route as AuthedAdminIndexRouteImport } from './routes/_authed/admin/index'
+import { Route as AuthedAdminAuditRouteImport } from './routes/_authed/admin/audit'
+import { Route as AuthedAdminBoundariesRouteImport } from './routes/_authed/admin/boundaries'
+import { Route as AuthedAdminComponentsRouteImport } from './routes/_authed/admin/components'
+import { Route as AuthedAdminComputersRouteImport } from './routes/_authed/admin/computers'
+import { Route as AuthedAdminConnectorsRouteImport } from './routes/_authed/admin/connectors'
+import { Route as AuthedAdminCredentialsRouteImport } from './routes/_authed/admin/credentials'
+import { Route as AuthedAdminPlaygroundRouteImport } from './routes/_authed/admin/playground'
+import { Route as AuthedAdminPluginsRouteImport } from './routes/_authed/admin/plugins'
+import { Route as AuthedSettingsIndexRouteImport } from './routes/_authed/settings/index'
+import { Route as AuthedAppAgentsIndexRouteImport } from './routes/_authed/_app/agents/index'
+import { Route as AuthedAppChannelChannelIdRouteImport } from './routes/_authed/_app/channel/$channelId'
+import { Route as AuthedAppChannelNewRouteImport } from './routes/_authed/_app/channel/new'
+import { Route as AuthedAdminConnectorsGoogleDriveRouteImport } from './routes/_authed/admin/connectors/google-drive'
+
+const AuthedRoute = AuthedRouteImport.update({
+ id: '/_authed',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const SignRoute = SignRouteImport.update({
+ id: '/sign',
+ path: '/sign',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const AuthedAppRoute = AuthedAppRouteImport.update({
+ id: '/_app',
+ getParentRoute: () => AuthedRoute,
+} as any)
+const AuthedAdminRouteRoute = AuthedAdminRouteRouteImport.update({
+ id: '/admin',
+ path: '/admin',
+ getParentRoute: () => AuthedRoute,
+} as any)
+const AuthedSettingsRouteRoute = AuthedSettingsRouteRouteImport.update({
+ id: '/settings',
+ path: '/settings',
+ getParentRoute: () => AuthedRoute,
+} as any)
+const AuthedAppIndexRoute = AuthedAppIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => AuthedAppRoute,
+} as any)
+const AuthedAppBotRoute = AuthedAppBotRouteImport.update({
+ id: '/bot',
+ path: '/bot',
+ getParentRoute: () => AuthedAppRoute,
+} as any)
+const AuthedAppSkillsRoute = AuthedAppSkillsRouteImport.update({
+ id: '/skills',
+ path: '/skills',
+ getParentRoute: () => AuthedAppRoute,
+} as any)
+const AuthedAdminIndexRoute = AuthedAdminIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminAuditRoute = AuthedAdminAuditRouteImport.update({
+ id: '/audit',
+ path: '/audit',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminBoundariesRoute = AuthedAdminBoundariesRouteImport.update({
+ id: '/boundaries',
+ path: '/boundaries',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminComponentsRoute = AuthedAdminComponentsRouteImport.update({
+ id: '/components',
+ path: '/components',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminComputersRoute = AuthedAdminComputersRouteImport.update({
+ id: '/computers',
+ path: '/computers',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminConnectorsRoute = AuthedAdminConnectorsRouteImport.update({
+ id: '/connectors',
+ path: '/connectors',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminCredentialsRoute = AuthedAdminCredentialsRouteImport.update({
+ id: '/credentials',
+ path: '/credentials',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminPlaygroundRoute = AuthedAdminPlaygroundRouteImport.update({
+ id: '/playground',
+ path: '/playground',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedAdminPluginsRoute = AuthedAdminPluginsRouteImport.update({
+ id: '/plugins',
+ path: '/plugins',
+ getParentRoute: () => AuthedAdminRouteRoute,
+} as any)
+const AuthedSettingsIndexRoute = AuthedSettingsIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => AuthedSettingsRouteRoute,
+} as any)
+const AuthedAppAgentsIndexRoute = AuthedAppAgentsIndexRouteImport.update({
+ id: '/agents/',
+ path: '/agents/',
+ getParentRoute: () => AuthedAppRoute,
+} as any)
+const AuthedAppChannelChannelIdRoute =
+ AuthedAppChannelChannelIdRouteImport.update({
+ id: '/channel/$channelId',
+ path: '/channel/$channelId',
+ getParentRoute: () => AuthedAppRoute,
+ } as any)
+const AuthedAppChannelNewRoute = AuthedAppChannelNewRouteImport.update({
+ id: '/channel/new',
+ path: '/channel/new',
+ getParentRoute: () => AuthedAppRoute,
+} as any)
+const AuthedAdminConnectorsGoogleDriveRoute =
+ AuthedAdminConnectorsGoogleDriveRouteImport.update({
+ id: '/google-drive',
+ path: '/google-drive',
+ getParentRoute: () => AuthedAdminConnectorsRoute,
+ } as any)
+
+export interface FileRoutesByFullPath {
+ '/': typeof AuthedAppIndexRoute
+ '/sign': typeof SignRoute
+ '/admin': typeof AuthedAdminRouteRouteWithChildren
+ '/settings': typeof AuthedSettingsRouteRouteWithChildren
+ '/bot': typeof AuthedAppBotRoute
+ '/skills': typeof AuthedAppSkillsRoute
+ '/admin/audit': typeof AuthedAdminAuditRoute
+ '/admin/boundaries': typeof AuthedAdminBoundariesRoute
+ '/admin/components': typeof AuthedAdminComponentsRoute
+ '/admin/computers': typeof AuthedAdminComputersRoute
+ '/admin/connectors': typeof AuthedAdminConnectorsRouteWithChildren
+ '/admin/credentials': typeof AuthedAdminCredentialsRoute
+ '/admin/playground': typeof AuthedAdminPlaygroundRoute
+ '/admin/plugins': typeof AuthedAdminPluginsRoute
+ '/admin/': typeof AuthedAdminIndexRoute
+ '/settings/': typeof AuthedSettingsIndexRoute
+ '/channel/$channelId': typeof AuthedAppChannelChannelIdRoute
+ '/channel/new': typeof AuthedAppChannelNewRoute
+ '/admin/connectors/google-drive': typeof AuthedAdminConnectorsGoogleDriveRoute
+ '/agents/': typeof AuthedAppAgentsIndexRoute
+}
+export interface FileRoutesByTo {
+ '/': typeof AuthedAppIndexRoute
+ '/sign': typeof SignRoute
+ '/bot': typeof AuthedAppBotRoute
+ '/skills': typeof AuthedAppSkillsRoute
+ '/admin/audit': typeof AuthedAdminAuditRoute
+ '/admin/boundaries': typeof AuthedAdminBoundariesRoute
+ '/admin/components': typeof AuthedAdminComponentsRoute
+ '/admin/computers': typeof AuthedAdminComputersRoute
+ '/admin/connectors': typeof AuthedAdminConnectorsRouteWithChildren
+ '/admin/credentials': typeof AuthedAdminCredentialsRoute
+ '/admin/playground': typeof AuthedAdminPlaygroundRoute
+ '/admin/plugins': typeof AuthedAdminPluginsRoute
+ '/admin': typeof AuthedAdminIndexRoute
+ '/settings': typeof AuthedSettingsIndexRoute
+ '/channel/$channelId': typeof AuthedAppChannelChannelIdRoute
+ '/channel/new': typeof AuthedAppChannelNewRoute
+ '/admin/connectors/google-drive': typeof AuthedAdminConnectorsGoogleDriveRoute
+ '/agents': typeof AuthedAppAgentsIndexRoute
+}
+export interface FileRoutesById {
+ __root__: typeof rootRouteImport
+ '/_authed': typeof AuthedRouteWithChildren
+ '/sign': typeof SignRoute
+ '/_authed/admin': typeof AuthedAdminRouteRouteWithChildren
+ '/_authed/settings': typeof AuthedSettingsRouteRouteWithChildren
+ '/_authed/_app': typeof AuthedAppRouteWithChildren
+ '/_authed/_app/bot': typeof AuthedAppBotRoute
+ '/_authed/_app/skills': typeof AuthedAppSkillsRoute
+ '/_authed/admin/audit': typeof AuthedAdminAuditRoute
+ '/_authed/admin/boundaries': typeof AuthedAdminBoundariesRoute
+ '/_authed/admin/components': typeof AuthedAdminComponentsRoute
+ '/_authed/admin/computers': typeof AuthedAdminComputersRoute
+ '/_authed/admin/connectors': typeof AuthedAdminConnectorsRouteWithChildren
+ '/_authed/admin/credentials': typeof AuthedAdminCredentialsRoute
+ '/_authed/admin/playground': typeof AuthedAdminPlaygroundRoute
+ '/_authed/admin/plugins': typeof AuthedAdminPluginsRoute
+ '/_authed/_app/': typeof AuthedAppIndexRoute
+ '/_authed/admin/': typeof AuthedAdminIndexRoute
+ '/_authed/settings/': typeof AuthedSettingsIndexRoute
+ '/_authed/_app/channel/$channelId': typeof AuthedAppChannelChannelIdRoute
+ '/_authed/_app/channel/new': typeof AuthedAppChannelNewRoute
+ '/_authed/admin/connectors/google-drive': typeof AuthedAdminConnectorsGoogleDriveRoute
+ '/_authed/_app/agents/': typeof AuthedAppAgentsIndexRoute
+}
+export interface FileRouteTypes {
+ fileRoutesByFullPath: FileRoutesByFullPath
+ fullPaths:
+ | '/'
+ | '/sign'
+ | '/admin'
+ | '/settings'
+ | '/bot'
+ | '/skills'
+ | '/admin/audit'
+ | '/admin/boundaries'
+ | '/admin/components'
+ | '/admin/computers'
+ | '/admin/connectors'
+ | '/admin/credentials'
+ | '/admin/playground'
+ | '/admin/plugins'
+ | '/admin/'
+ | '/settings/'
+ | '/channel/$channelId'
+ | '/channel/new'
+ | '/admin/connectors/google-drive'
+ | '/agents/'
+ fileRoutesByTo: FileRoutesByTo
+ to:
+ | '/'
+ | '/sign'
+ | '/bot'
+ | '/skills'
+ | '/admin/audit'
+ | '/admin/boundaries'
+ | '/admin/components'
+ | '/admin/computers'
+ | '/admin/connectors'
+ | '/admin/credentials'
+ | '/admin/playground'
+ | '/admin/plugins'
+ | '/admin'
+ | '/settings'
+ | '/channel/$channelId'
+ | '/channel/new'
+ | '/admin/connectors/google-drive'
+ | '/agents'
+ id:
+ | '__root__'
+ | '/_authed'
+ | '/sign'
+ | '/_authed/admin'
+ | '/_authed/settings'
+ | '/_authed/_app'
+ | '/_authed/_app/bot'
+ | '/_authed/_app/skills'
+ | '/_authed/admin/audit'
+ | '/_authed/admin/boundaries'
+ | '/_authed/admin/components'
+ | '/_authed/admin/computers'
+ | '/_authed/admin/connectors'
+ | '/_authed/admin/credentials'
+ | '/_authed/admin/playground'
+ | '/_authed/admin/plugins'
+ | '/_authed/_app/'
+ | '/_authed/admin/'
+ | '/_authed/settings/'
+ | '/_authed/_app/channel/$channelId'
+ | '/_authed/_app/channel/new'
+ | '/_authed/admin/connectors/google-drive'
+ | '/_authed/_app/agents/'
+ fileRoutesById: FileRoutesById
+}
+export interface RootRouteChildren {
+ AuthedRoute: typeof AuthedRouteWithChildren
+ SignRoute: typeof SignRoute
+}
+
+declare module '@tanstack/react-router' {
+ interface FileRoutesByPath {
+ '/_authed': {
+ id: '/_authed'
+ path: ''
+ fullPath: '/'
+ preLoaderRoute: typeof AuthedRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/sign': {
+ id: '/sign'
+ path: '/sign'
+ fullPath: '/sign'
+ preLoaderRoute: typeof SignRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/_authed/_app': {
+ id: '/_authed/_app'
+ path: ''
+ fullPath: '/'
+ preLoaderRoute: typeof AuthedAppRouteImport
+ parentRoute: typeof AuthedRoute
+ }
+ '/_authed/admin': {
+ id: '/_authed/admin'
+ path: '/admin'
+ fullPath: '/admin'
+ preLoaderRoute: typeof AuthedAdminRouteRouteImport
+ parentRoute: typeof AuthedRoute
+ }
+ '/_authed/settings': {
+ id: '/_authed/settings'
+ path: '/settings'
+ fullPath: '/settings'
+ preLoaderRoute: typeof AuthedSettingsRouteRouteImport
+ parentRoute: typeof AuthedRoute
+ }
+ '/_authed/_app/': {
+ id: '/_authed/_app/'
+ path: '/'
+ fullPath: '/'
+ preLoaderRoute: typeof AuthedAppIndexRouteImport
+ parentRoute: typeof AuthedAppRoute
+ }
+ '/_authed/_app/bot': {
+ id: '/_authed/_app/bot'
+ path: '/bot'
+ fullPath: '/bot'
+ preLoaderRoute: typeof AuthedAppBotRouteImport
+ parentRoute: typeof AuthedAppRoute
+ }
+ '/_authed/_app/skills': {
+ id: '/_authed/_app/skills'
+ path: '/skills'
+ fullPath: '/skills'
+ preLoaderRoute: typeof AuthedAppSkillsRouteImport
+ parentRoute: typeof AuthedAppRoute
+ }
+ '/_authed/admin/': {
+ id: '/_authed/admin/'
+ path: '/'
+ fullPath: '/admin/'
+ preLoaderRoute: typeof AuthedAdminIndexRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/audit': {
+ id: '/_authed/admin/audit'
+ path: '/audit'
+ fullPath: '/admin/audit'
+ preLoaderRoute: typeof AuthedAdminAuditRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/boundaries': {
+ id: '/_authed/admin/boundaries'
+ path: '/boundaries'
+ fullPath: '/admin/boundaries'
+ preLoaderRoute: typeof AuthedAdminBoundariesRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/components': {
+ id: '/_authed/admin/components'
+ path: '/components'
+ fullPath: '/admin/components'
+ preLoaderRoute: typeof AuthedAdminComponentsRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/computers': {
+ id: '/_authed/admin/computers'
+ path: '/computers'
+ fullPath: '/admin/computers'
+ preLoaderRoute: typeof AuthedAdminComputersRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/connectors': {
+ id: '/_authed/admin/connectors'
+ path: '/connectors'
+ fullPath: '/admin/connectors'
+ preLoaderRoute: typeof AuthedAdminConnectorsRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/credentials': {
+ id: '/_authed/admin/credentials'
+ path: '/credentials'
+ fullPath: '/admin/credentials'
+ preLoaderRoute: typeof AuthedAdminCredentialsRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/playground': {
+ id: '/_authed/admin/playground'
+ path: '/playground'
+ fullPath: '/admin/playground'
+ preLoaderRoute: typeof AuthedAdminPlaygroundRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/admin/plugins': {
+ id: '/_authed/admin/plugins'
+ path: '/plugins'
+ fullPath: '/admin/plugins'
+ preLoaderRoute: typeof AuthedAdminPluginsRouteImport
+ parentRoute: typeof AuthedAdminRouteRoute
+ }
+ '/_authed/settings/': {
+ id: '/_authed/settings/'
+ path: '/'
+ fullPath: '/settings/'
+ preLoaderRoute: typeof AuthedSettingsIndexRouteImport
+ parentRoute: typeof AuthedSettingsRouteRoute
+ }
+ '/_authed/_app/agents/': {
+ id: '/_authed/_app/agents/'
+ path: '/agents'
+ fullPath: '/agents/'
+ preLoaderRoute: typeof AuthedAppAgentsIndexRouteImport
+ parentRoute: typeof AuthedAppRoute
+ }
+ '/_authed/_app/channel/$channelId': {
+ id: '/_authed/_app/channel/$channelId'
+ path: '/channel/$channelId'
+ fullPath: '/channel/$channelId'
+ preLoaderRoute: typeof AuthedAppChannelChannelIdRouteImport
+ parentRoute: typeof AuthedAppRoute
+ }
+ '/_authed/_app/channel/new': {
+ id: '/_authed/_app/channel/new'
+ path: '/channel/new'
+ fullPath: '/channel/new'
+ preLoaderRoute: typeof AuthedAppChannelNewRouteImport
+ parentRoute: typeof AuthedAppRoute
+ }
+ '/_authed/admin/connectors/google-drive': {
+ id: '/_authed/admin/connectors/google-drive'
+ path: '/google-drive'
+ fullPath: '/admin/connectors/google-drive'
+ preLoaderRoute: typeof AuthedAdminConnectorsGoogleDriveRouteImport
+ parentRoute: typeof AuthedAdminConnectorsRoute
+ }
+ }
+}
+
+interface AuthedAdminConnectorsRouteChildren {
+ AuthedAdminConnectorsGoogleDriveRoute: typeof AuthedAdminConnectorsGoogleDriveRoute
+}
+
+const AuthedAdminConnectorsRouteChildren: AuthedAdminConnectorsRouteChildren = {
+ AuthedAdminConnectorsGoogleDriveRoute: AuthedAdminConnectorsGoogleDriveRoute,
+}
+
+const AuthedAdminConnectorsRouteWithChildren =
+ AuthedAdminConnectorsRoute._addFileChildren(
+ AuthedAdminConnectorsRouteChildren,
+ )
+
+interface AuthedAdminRouteRouteChildren {
+ AuthedAdminAuditRoute: typeof AuthedAdminAuditRoute
+ AuthedAdminBoundariesRoute: typeof AuthedAdminBoundariesRoute
+ AuthedAdminComponentsRoute: typeof AuthedAdminComponentsRoute
+ AuthedAdminComputersRoute: typeof AuthedAdminComputersRoute
+ AuthedAdminConnectorsRoute: typeof AuthedAdminConnectorsRouteWithChildren
+ AuthedAdminCredentialsRoute: typeof AuthedAdminCredentialsRoute
+ AuthedAdminPlaygroundRoute: typeof AuthedAdminPlaygroundRoute
+ AuthedAdminPluginsRoute: typeof AuthedAdminPluginsRoute
+ AuthedAdminIndexRoute: typeof AuthedAdminIndexRoute
+}
+
+const AuthedAdminRouteRouteChildren: AuthedAdminRouteRouteChildren = {
+ AuthedAdminAuditRoute: AuthedAdminAuditRoute,
+ AuthedAdminBoundariesRoute: AuthedAdminBoundariesRoute,
+ AuthedAdminComponentsRoute: AuthedAdminComponentsRoute,
+ AuthedAdminComputersRoute: AuthedAdminComputersRoute,
+ AuthedAdminConnectorsRoute: AuthedAdminConnectorsRouteWithChildren,
+ AuthedAdminCredentialsRoute: AuthedAdminCredentialsRoute,
+ AuthedAdminPlaygroundRoute: AuthedAdminPlaygroundRoute,
+ AuthedAdminPluginsRoute: AuthedAdminPluginsRoute,
+ AuthedAdminIndexRoute: AuthedAdminIndexRoute,
+}
+
+const AuthedAdminRouteRouteWithChildren =
+ AuthedAdminRouteRoute._addFileChildren(AuthedAdminRouteRouteChildren)
+
+interface AuthedSettingsRouteRouteChildren {
+ AuthedSettingsIndexRoute: typeof AuthedSettingsIndexRoute
+}
+
+const AuthedSettingsRouteRouteChildren: AuthedSettingsRouteRouteChildren = {
+ AuthedSettingsIndexRoute: AuthedSettingsIndexRoute,
+}
+
+const AuthedSettingsRouteRouteWithChildren =
+ AuthedSettingsRouteRoute._addFileChildren(AuthedSettingsRouteRouteChildren)
+
+interface AuthedAppRouteChildren {
+ AuthedAppBotRoute: typeof AuthedAppBotRoute
+ AuthedAppSkillsRoute: typeof AuthedAppSkillsRoute
+ AuthedAppIndexRoute: typeof AuthedAppIndexRoute
+ AuthedAppChannelChannelIdRoute: typeof AuthedAppChannelChannelIdRoute
+ AuthedAppChannelNewRoute: typeof AuthedAppChannelNewRoute
+ AuthedAppAgentsIndexRoute: typeof AuthedAppAgentsIndexRoute
+}
+
+const AuthedAppRouteChildren: AuthedAppRouteChildren = {
+ AuthedAppBotRoute: AuthedAppBotRoute,
+ AuthedAppSkillsRoute: AuthedAppSkillsRoute,
+ AuthedAppIndexRoute: AuthedAppIndexRoute,
+ AuthedAppChannelChannelIdRoute: AuthedAppChannelChannelIdRoute,
+ AuthedAppChannelNewRoute: AuthedAppChannelNewRoute,
+ AuthedAppAgentsIndexRoute: AuthedAppAgentsIndexRoute,
+}
+
+const AuthedAppRouteWithChildren = AuthedAppRoute._addFileChildren(
+ AuthedAppRouteChildren,
+)
+
+interface AuthedRouteChildren {
+ AuthedAdminRouteRoute: typeof AuthedAdminRouteRouteWithChildren
+ AuthedSettingsRouteRoute: typeof AuthedSettingsRouteRouteWithChildren
+ AuthedAppRoute: typeof AuthedAppRouteWithChildren
+}
+
+const AuthedRouteChildren: AuthedRouteChildren = {
+ AuthedAdminRouteRoute: AuthedAdminRouteRouteWithChildren,
+ AuthedSettingsRouteRoute: AuthedSettingsRouteRouteWithChildren,
+ AuthedAppRoute: AuthedAppRouteWithChildren,
+}
+
+const AuthedRouteWithChildren =
+ AuthedRoute._addFileChildren(AuthedRouteChildren)
+
+const rootRouteChildren: RootRouteChildren = {
+ AuthedRoute: AuthedRouteWithChildren,
+ SignRoute: SignRoute,
+}
+export const routeTree = rootRouteImport
+ ._addFileChildren(rootRouteChildren)
+ ._addFileTypes<FileRouteTypes>()
diff --git a/app/src/router-context.ts b/app/src/router-context.ts
new file mode 100644
index 00000000..1b9f9d86
--- /dev/null
+++ b/app/src/router-context.ts
@@ -0,0 +1,5 @@
+import type { QueryClient } from "@tanstack/react-query";
+
+export type RouterContext = {
+ queryClient: QueryClient;
+};
diff --git a/app/src/router.tsx b/app/src/router.tsx
new file mode 100644
index 00000000..4d7e914f
--- /dev/null
+++ b/app/src/router.tsx
@@ -0,0 +1,14 @@
+import { createRouter } from "@tanstack/react-router";
+import type { RouterContext } from "./router-context";
+import { routeTree } from "./routeTree.gen";
+
+export const router = createRouter({
+ routeTree,
+ context: {} as RouterContext,
+});
+
+declare module "@tanstack/react-router" {
+ interface Register {
+ router: typeof router;
+ }
+}
diff --git a/app/src/routes/_authed.tsx b/app/src/routes/_authed.tsx
new file mode 100644
index 00000000..f3742d54
--- /dev/null
+++ b/app/src/routes/_authed.tsx
@@ -0,0 +1,21 @@
+import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
+import { currentUserQueryOptions } from "../lib/auth/queries";
+import { CopilotProvider } from "../lib/copilot/provider";
+
+export const Route = createFileRoute("/_authed")({
+ beforeLoad: async ({ context }) => {
+ const user = await context.queryClient.ensureQueryData(
+ currentUserQueryOptions(),
+ );
+ if (!user) {
+ throw redirect({ to: "/sign" });
+ }
+ },
+ // Mounted INSIDE the authed boundary, not at the root: the runtime endpoint requires a session, so
+ // a provider above the sign-in gate would open a run for a visitor who has not signed in yet.
+ component: () => (
+ <CopilotProvider>
+ <Outlet />
+ </CopilotProvider>
+ ),
+});
diff --git a/app/src/routes/_authed/admin/boundaries.tsx b/app/src/routes/_authed/admin/boundaries.tsx
new file mode 100644
index 00000000..dd920c2d
--- /dev/null
+++ b/app/src/routes/_authed/admin/boundaries.tsx
@@ -0,0 +1,270 @@
+import { createFileRoute, Link } from "@tanstack/react-router";
+import { useCallback, useEffect, useState } from "react";
+import { PageSection, PageShell } from "@/components/layout/page-shell";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+
+/**
+ * CEL computer-action boundary editor. Rules are shown as the gateway evaluates them, and denied
+ * actions are recorded in Audit with the matching rule.
+ */
+
+type PolicyMode = "dry-run" | "enforce";
+
+type ActionPolicy = {
+ mode: PolicyMode;
+ deny: string[];
+ allow: string[];
+};
+
+/**
+ * Presets are concrete CEL rules, not a separate policy language.
+ */
+const PRESETS: { label: string; rule: string; cost?: string }[] = [
+ {
+ label: "Never submit a form",
+ // `key` exists only on keypress actions; guard it by tool name to keep other actions evaluable.
+ rule: '(intent == "activate" && contains(element.name, "submit")) || (tool.name == "computer_key" && key == "Enter")',
+ cost: "Also stops the Bot pressing Enter for anything else, because a form submits from Enter in any of its fields.",
+ },
+ {
+ label: "Never type into a password field",
+ rule: 'intent == "type" && contains(element.name, "password")',
+ cost: "A password box the page labels something else is not covered, the rule matches the label.",
+ },
+ {
+ label: "Stay off social media",
+ rule: 'intent == "navigate" && (contains(page.host, "facebook.com") || contains(page.host, "x.com"))',
+ cost: "Only the two hosts named. A link that redirects there from somewhere else is allowed.",
+ },
+];
+
+export const Route = createFileRoute("/_authed/admin/boundaries")({
+ component: BoundariesPage,
+});
+
+function BoundariesPage() {
+ const [policy, setPolicy] = useState<ActionPolicy | null>(null);
+ const [problem, setProblem] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const [saved, setSaved] = useState(false);
+ const [draft, setDraft] = useState("");
+
+ const load = useCallback(async () => {
+ try {
+ const response = await fetch("/api/computers/policy", {
+ credentials: "include",
+ });
+ if (!response.ok) {
+ setProblem("The boundary could not be read.");
+ return;
+ }
+ const body = (await response.json()) as { policy: ActionPolicy };
+ setPolicy(body.policy);
+ setProblem(null);
+ } catch {
+ setProblem("The boundary could not be reached.");
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const save = useCallback(async (next: ActionPolicy) => {
+ setSaving(true);
+ setSaved(false);
+ try {
+ const response = await fetch("/api/computers/policy", {
+ method: "PUT",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(next),
+ });
+ const body = (await response.json().catch(() => null)) as {
+ policy?: ActionPolicy;
+ error?: string;
+ } | null;
+ if (!response.ok) {
+ setProblem(body?.error ?? "The boundary could not be saved.");
+ return;
+ }
+ // Display the persisted policy in case the server normalized it.
+ if (body?.policy) setPolicy(body.policy);
+ setProblem(null);
+ setSaved(true);
+ } catch {
+ setProblem("The boundary could not be reached.");
+ } finally {
+ setSaving(false);
+ }
+ }, []);
+
+ if (problem && !policy) {
+ return (
+ <PageShell title="Boundaries">
+ <p className="mt-4 text-destructive text-sm" role="alert">
+ {problem}
+ </p>
+ </PageShell>
+ );
+ }
+
+ if (!policy) {
+ return (
+ <PageShell title="Boundaries">
+ <p className="mt-4 text-muted-foreground text-sm">
+ Loading the boundary…
+ </p>
+ </PageShell>
+ );
+ }
+
+ const addRule = (rule: string) => {
+ const trimmed = rule.trim();
+ if (!trimmed || policy.deny.includes(trimmed)) return;
+ void save({ ...policy, deny: [...policy.deny, trimmed] });
+ setDraft("");
+ };
+
+ return (
+ <PageShell
+ description={
+ <>
+ What every Bot may and may not do with its computer. Rules are checked
+ on every action before it happens, and a refusal is recorded in{" "}
+ <Link className="underline" to="/admin/audit">
+ Audit
+ </Link>{" "}
+ with the rule that refused it.
+ </>
+ }
+ title="Boundaries"
+ >
+ <PageSection title="When a rule matches">
+ <div className="mt-2 flex gap-2">
+ {(["enforce", "dry-run"] as PolicyMode[]).map((mode) => (
+ <Button
+ key={mode}
+ aria-pressed={policy.mode === mode}
+ className={policy.mode === mode ? "bg-foreground/5" : undefined}
+ disabled={saving}
+ onClick={() => void save({ ...policy, mode })}
+ size="sm"
+ variant="outline"
+ >
+ {mode === "enforce"
+ ? "Stop the action"
+ : "Record it and allow it"}
+ </Button>
+ ))}
+ </div>
+ <p className="mt-2 text-xs text-muted-foreground">
+ {policy.mode === "enforce"
+ ? "The Bot is stopped and told which rule refused it."
+ : "Nothing is stopped. Every action a rule matches is recorded as it would have been refused, which is how a rule is tried out before it is switched on."}
+ </p>
+ </PageSection>
+
+ <PageSection title="It may never">
+ {policy.deny.length === 0 ? (
+ <p className="mt-2 text-sm text-muted-foreground">
+ No rules. Every action is allowed and recorded.
+ </p>
+ ) : (
+ <ul className="mt-2 divide-y divide-border rounded-md border border-border">
+ {policy.deny.map((rule) => (
+ <li
+ className="flex items-center justify-between gap-4 px-3 py-2"
+ key={rule}
+ >
+ <code className="min-w-0 break-all font-mono text-xs">
+ {rule}
+ </code>
+ <Button
+ disabled={saving}
+ onClick={() =>
+ void save({
+ ...policy,
+ deny: policy.deny.filter((one) => one !== rule),
+ })
+ }
+ size="sm"
+ variant="ghost"
+ >
+ Remove
+ </Button>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <div className="mt-3 flex gap-2">
+ <Input
+ aria-label="A rule, written in CEL"
+ className="min-w-0 flex-1 font-mono text-xs"
+ onChange={(event) => {
+ setDraft(event.target.value);
+ setSaved(false);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") addRule(draft);
+ }}
+ placeholder='tool.name == "computer_click" && contains(element.name, "submit")'
+ value={draft}
+ />
+ <Button
+ disabled={saving || draft.trim().length === 0}
+ onClick={() => addRule(draft)}
+ size="sm"
+ >
+ Add rule
+ </Button>
+ </div>
+
+ <ul className="mt-3 space-y-2">
+ {PRESETS.map((preset) => (
+ <li className="flex items-start gap-3" key={preset.rule}>
+ <Button
+ className="shrink-0"
+ disabled={saving || policy.deny.includes(preset.rule)}
+ onClick={() => addRule(preset.rule)}
+ size="sm"
+ variant="outline"
+ >
+ {preset.label}
+ </Button>
+ {preset.cost ? (
+ <span className="pt-1 text-xs text-muted-foreground">
+ {preset.cost}
+ </span>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ </PageSection>
+
+ <PageSection title="Otherwise it may">
+ <ul className="mt-2 space-y-1">
+ {policy.allow.map((rule) => (
+ <li className="font-mono text-xs text-muted-foreground" key={rule}>
+ {rule === "true" ? "true, anything not refused above" : rule}
+ </li>
+ ))}
+ </ul>
+ </PageSection>
+
+ <p className="mt-8 text-muted-foreground text-xs">
+ {problem ? (
+ <span className="text-destructive" role="alert">
+ {problem}
+ </span>
+ ) : saved ? (
+ "Saved. It applies to the next action any Bot takes."
+ ) : (
+ "Changes apply to the next action any Bot takes, and are kept: a restart comes back up enforcing what is here."
+ )}
+ </p>
+ </PageShell>
+ );
+}
diff --git a/app/src/routes/_authed/admin/components.tsx b/app/src/routes/_authed/admin/components.tsx
new file mode 100644
index 00000000..27c40ead
--- /dev/null
+++ b/app/src/routes/_authed/admin/components.tsx
@@ -0,0 +1,382 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { createFileRoute } from "@tanstack/react-router";
+import { useState } from "react";
+import {
+ PageEmpty,
+ PageSection,
+ PageShell,
+} from "@/components/layout/page-shell";
+import { StaggerItem } from "@/components/layout/stagger";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Field, FieldLabel } from "@/components/ui/field";
+import { Textarea } from "@/components/ui/textarea";
+import { agentListQueryOptions } from "@/lib/agents/queries";
+import {
+ type ComponentRecord,
+ componentKeys,
+ componentListQueryOptions,
+ type DataFunctionSummary,
+ dataFunctionsQueryOptions,
+} from "@/lib/components/queries";
+import { RENDERABLE_NAMES } from "@/lib/copilot/gallery-registry";
+
+/**
+ * Runtime governance for compiled gallery components: publication, per-Bot grants, model-facing
+ * descriptions, and component data-function access.
+ */
+export const Route = createFileRoute("/_authed/admin/components")({
+ component: RouteComponent,
+});
+
+function RouteComponent() {
+ const queryClient = useQueryClient();
+ const { data: components, isLoading } = useQuery(componentListQueryOptions());
+ const { data: agents } = useQuery(agentListQueryOptions());
+ const { data: dataFunctions } = useQuery(dataFunctionsQueryOptions());
+
+ const invalidate = () => {
+ void queryClient.invalidateQueries({ queryKey: componentKeys.all });
+ };
+
+ const setGrant = useMutation({
+ mutationFn: async ({
+ name,
+ agentId,
+ granted,
+ }: {
+ name: string;
+ agentId: string;
+ granted: boolean;
+ }) => {
+ const response = granted
+ ? await fetch(`/api/components/${encodeURIComponent(name)}/grants`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentId }),
+ })
+ : await fetch(
+ `/api/components/${encodeURIComponent(name)}/grants/${encodeURIComponent(agentId)}`,
+ { method: "DELETE", credentials: "include" },
+ );
+ if (!response.ok) throw new Error("That change could not be saved.");
+ },
+ onSuccess: invalidate,
+ });
+
+ const setFunction = useMutation({
+ mutationFn: async ({
+ name,
+ functionName,
+ granted,
+ }: {
+ name: string;
+ functionName: string;
+ granted: boolean;
+ }) => {
+ const response = granted
+ ? await fetch(`/api/components/${encodeURIComponent(name)}/functions`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ function: functionName }),
+ })
+ : await fetch(
+ `/api/components/${encodeURIComponent(name)}/functions/${encodeURIComponent(functionName)}`,
+ { method: "DELETE", credentials: "include" },
+ );
+ if (!response.ok) throw new Error("That change could not be saved.");
+ },
+ onSuccess: invalidate,
+ });
+
+ const setPublished = useMutation({
+ mutationFn: async ({
+ name,
+ published,
+ }: {
+ name: string;
+ published: boolean;
+ }) => {
+ const response = await fetch(
+ `/api/components/${encodeURIComponent(name)}/publication`,
+ {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ published }),
+ },
+ );
+ if (!response.ok) throw new Error("That change could not be saved.");
+ },
+ onSuccess: invalidate,
+ });
+
+ const saveDraft = useMutation({
+ mutationFn: async ({
+ name,
+ description,
+ }: {
+ name: string;
+ description: string;
+ }) => {
+ const response = await fetch(
+ `/api/components/${encodeURIComponent(name)}/draft`,
+ {
+ method: "PUT",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ description }),
+ },
+ );
+ if (!response.ok) throw new Error("That draft could not be saved.");
+ },
+ onSuccess: invalidate,
+ });
+
+ const bots = agents ?? [];
+
+ return (
+ <PageShell
+ description="What each Bot may answer with. Every published component is available to every Bot; switch one off here and that Bot is never told about it. Each change and each refusal is a row in Audit."
+ title="Components"
+ >
+ {/*
+ * ONE CARD EACH, RATHER THAN A ROW EACH. Every other list in admin is `Item` rows, and these
+ * started as hand-drawn ones — but a component carries per-Bot grants and per-function grants,
+ * which is a set of switches rather than a line of text. Cramming that into a row would mean
+ * hiding it behind a menu, and which Bots hold a component is the thing this page exists to
+ * answer at a glance.
+ */}
+ <PageSection title="Published components">
+ {isLoading ? <PageEmpty>Loading…</PageEmpty> : null}
+
+ {components?.length === 0 && !isLoading ? (
+ <PageEmpty>This deployment ships no components.</PageEmpty>
+ ) : null}
+
+ <div className="mt-4 flex flex-col gap-3">
+ {(components ?? []).map((component, index) => (
+ <StaggerItem index={index} key={component.name}>
+ <ComponentRow
+ bots={bots}
+ component={component}
+ dataFunctions={dataFunctions ?? []}
+ key={component.name}
+ onSetFunction={(functionName, granted) =>
+ setFunction.mutate({
+ functionName,
+ granted,
+ name: component.name,
+ })
+ }
+ onPublish={(published) =>
+ setPublished.mutate({ name: component.name, published })
+ }
+ onSaveDraft={(description) =>
+ saveDraft.mutate({ name: component.name, description })
+ }
+ onSetGrant={(agentId, granted) =>
+ setGrant.mutate({ agentId, granted, name: component.name })
+ }
+ />
+ </StaggerItem>
+ ))}
+ </div>
+ </PageSection>
+ </PageShell>
+ );
+}
+
+function ComponentRow({
+ component,
+ bots,
+ dataFunctions,
+ onSetGrant,
+ onSetFunction,
+ onPublish,
+ onSaveDraft,
+}: {
+ component: ComponentRecord;
+ bots: { id: string; name: string }[];
+ dataFunctions: DataFunctionSummary[];
+ onSetGrant: (agentId: string, granted: boolean) => void;
+ onSetFunction: (functionName: string, granted: boolean) => void;
+ onPublish: (published: boolean) => void;
+ onSaveDraft: (description: string) => void;
+}) {
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(component.draftDescription);
+ const withheld = new Set(component.withheldFrom);
+ const heldFunctions = new Set(component.functions);
+
+ return (
+ <section
+ className="rounded-lg border border-border bg-card"
+ data-testid={`component-${component.name}`}
+ >
+ <div className="flex flex-wrap items-start justify-between gap-4 border-b border-border px-4 py-3">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <h3 className="font-medium text-sm">{component.title}</h3>
+ <code className="rounded bg-foreground/5 px-1.5 py-0.5 text-xs text-muted-foreground">
+ {component.name}
+ </code>
+ {RENDERABLE_NAMES.has(component.name) ? null : (
+ <span className="rounded-md bg-amber-500/10 px-1.5 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-400">
+ Not in this build, nothing can draw it
+ </span>
+ )}
+ {component.published ? null : (
+ <span className="rounded-md bg-amber-500/10 px-1.5 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-400">
+ Unpublished, no Bot may use it
+ </span>
+ )}
+ {component.hasUnpublishedChanges ? (
+ <span className="rounded-md bg-foreground/5 px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
+ Draft not published
+ </span>
+ ) : null}
+ </div>
+ <p className="mt-1 max-w-3xl text-sm text-muted-foreground">
+ {component.publishedDescription ??
+ "Nothing is published, so no Bot is told about this."}
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Last changed {new Date(component.updatedAt).toLocaleString()}
+ {component.updatedBy ? ` by ${component.updatedBy}` : null}
+ </p>
+ </div>
+
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ onClick={() => setEditing((open) => !open)}
+ size="sm"
+ variant="outline"
+ >
+ Edit description
+ </Button>
+ <Button
+ data-testid={`publish-${component.name}`}
+ onClick={() => onPublish(!component.published)}
+ size="sm"
+ variant={component.published ? "outline" : "default"}
+ >
+ {component.published ? "Unpublish" : "Publish"}
+ </Button>
+ </div>
+ </div>
+
+ <Dialog onOpenChange={setEditing} open={editing}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{component.title}</DialogTitle>
+ <DialogDescription>
+ The draft description is what the model reads when deciding to
+ call this. It changes nothing until it is published.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="mt-4">
+ <Field>
+ <FieldLabel htmlFor={`draft-${component.name}`}>
+ Draft description
+ </FieldLabel>
+ <Textarea
+ id={`draft-${component.name}`}
+ onChange={(event) => setDraft(event.target.value)}
+ rows={4}
+ value={draft}
+ />
+ </Field>
+ </DialogBody>
+ <DialogFooter className="mt-4">
+ <Button onClick={() => setEditing(false)} size="sm" variant="ghost">
+ Cancel
+ </Button>
+ <Button
+ onClick={() => {
+ onSaveDraft(draft);
+ setEditing(false);
+ }}
+ size="sm"
+ variant="outline"
+ >
+ Save draft
+ </Button>
+ <Button
+ onClick={() => {
+ onSaveDraft(draft);
+ onPublish(true);
+ setEditing(false);
+ }}
+ size="sm"
+ >
+ Publish
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <div className="flex flex-wrap gap-2 px-4 py-3">
+ {bots.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ There are no Bots yet.
+ </p>
+ ) : null}
+ {bots.map((bot) => {
+ const has = !withheld.has(bot.id);
+ return (
+ <Button
+ data-testid={`grant-${component.name}-${bot.id}`}
+ key={bot.id}
+ onClick={() => onSetGrant(bot.id, !has)}
+ size="sm"
+ type="button"
+ /* The fill is the state, as on the skills grants: a glance has to answer which are on. */
+ variant={has ? "default" : "outline"}
+ >
+ {bot.name}
+ </Button>
+ );
+ })}
+ </div>
+
+ {/* Data-function grants are separate from Bot component grants. */}
+ {dataFunctions.length > 0 ? (
+ <div className="border-t border-border px-4 py-3">
+ <p className="text-xs font-medium text-muted-foreground">May read</p>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {dataFunctions.map((fn) => {
+ const has = heldFunctions.has(fn.name);
+ return (
+ <Button
+ data-testid={`function-${component.name}-${fn.name}`}
+ key={fn.name}
+ onClick={() => onSetFunction(fn.name, !has)}
+ size="sm"
+ title={fn.description}
+ type="button"
+ variant={has ? "default" : "outline"}
+ >
+ {fn.name}
+ <span className="ml-2 text-muted-foreground text-xs">
+ {fn.reads}
+ </span>
+ </Button>
+ );
+ })}
+ </div>
+ </div>
+ ) : null}
+ </section>
+ );
+}
diff --git a/app/src/routes/_authed/admin/connectors/google-drive.tsx b/app/src/routes/_authed/admin/connectors/google-drive.tsx
new file mode 100644
index 00000000..f2d79ebf
--- /dev/null
+++ b/app/src/routes/_authed/admin/connectors/google-drive.tsx
@@ -0,0 +1,143 @@
+import { useForm } from "@tanstack/react-form";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { createFileRoute } from "@tanstack/react-router";
+import { z } from "zod";
+import { PageShell } from "@/components/layout/page-shell";
+import { Button } from "@/components/ui/button";
+import {
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from "@/components/ui/field";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { connectorKeys } from "@/lib/connectors/queries";
+
+export const Route = createFileRoute("/_authed/admin/connectors/google-drive")({
+ component: GoogleDriveConnectorPage,
+});
+
+function GoogleDriveConnectorPage() {
+ const queryClient = useQueryClient();
+ const setup = useMutation({
+ mutationFn: async (value: {
+ serviceAccountJson: string;
+ impersonationSubject: string;
+ }) => {
+ const response = await fetch("/api/admin/connectors/google-drive/setup", {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(value),
+ });
+ if (!response.ok) throw new Error("Could not set up Google Drive");
+ },
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: connectorKeys.all }),
+ });
+ const form = useForm({
+ defaultValues: { serviceAccountJson: "", impersonationSubject: "" },
+ validators: {
+ onSubmit: z.object({
+ serviceAccountJson: z
+ .string()
+ .trim()
+ .refine((value) => {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return Boolean(
+ parsed && typeof parsed === "object" && !Array.isArray(parsed),
+ );
+ } catch {
+ return false;
+ }
+ }, "Paste a valid service-account JSON object."),
+ impersonationSubject: z
+ .string()
+ .email("Enter the Workspace account to impersonate."),
+ }),
+ },
+ onSubmit: async ({ value }) => {
+ await setup.mutateAsync(value);
+ form.reset();
+ },
+ });
+ return (
+ /*
+ * THE FORM STAYS ON THE PAGE HERE, unlike the rest of admin. This route exists only to hold it —
+ * there is no list behind it to interrupt — so putting it in a dialog would mean navigating to a
+ * page whose only content immediately covers itself up.
+ */
+ <PageShell
+ description="Connect an organization service account with domain-wide delegation."
+ title="Google Drive"
+ >
+ <form
+ className="mt-8"
+ noValidate
+ onSubmit={(event) => {
+ event.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <FieldGroup>
+ <form.Field name="serviceAccountJson">
+ {(field) => (
+ <Field
+ data-invalid={
+ field.state.meta.isTouched && !field.state.meta.isValid
+ }
+ >
+ <FieldLabel htmlFor={field.name}>
+ Service account JSON key
+ </FieldLabel>
+ <Textarea
+ className="min-h-40 font-mono text-xs"
+ id={field.name}
+ onBlur={field.handleBlur}
+ onChange={(event) => field.handleChange(event.target.value)}
+ value={field.state.value}
+ />
+ {field.state.meta.isTouched && !field.state.meta.isValid ? (
+ <FieldError errors={field.state.meta.errors} />
+ ) : null}
+ </Field>
+ )}
+ </form.Field>
+ <form.Field name="impersonationSubject">
+ {(field) => (
+ <Field
+ data-invalid={
+ field.state.meta.isTouched && !field.state.meta.isValid
+ }
+ >
+ <FieldLabel htmlFor={field.name}>
+ Impersonation subject
+ </FieldLabel>
+ <Input
+ id={field.name}
+ onBlur={field.handleBlur}
+ onChange={(event) => field.handleChange(event.target.value)}
+ placeholder="[email protected]"
+ value={field.state.value}
+ />
+ {field.state.meta.isTouched && !field.state.meta.isValid ? (
+ <FieldError errors={field.state.meta.errors} />
+ ) : null}
+ </Field>
+ )}
+ </form.Field>
+ </FieldGroup>
+ {setup.error ? (
+ <p className="mt-4 text-destructive text-sm" role="alert">
+ Could not save the Google Drive connection.
+ </p>
+ ) : null}
+ <Button className="mt-4" disabled={setup.isPending} type="submit">
+ {setup.isPending ? "Connecting…" : "Connect Google Drive"}
+ </Button>
+ </form>
+ </PageShell>
+ );
+}
diff --git a/app/src/routes/_authed/admin/plugins.tsx b/app/src/routes/_authed/admin/plugins.tsx
new file mode 100644
index 00000000..8f1f2b32
--- /dev/null
+++ b/app/src/routes/_authed/admin/plugins.tsx
@@ -0,0 +1,756 @@
+import { IconPlus } from "@tabler/icons-react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { createFileRoute } from "@tanstack/react-router";
+import * as React from "react";
+import { useState } from "react";
+import {
+ PageEmpty,
+ PageSection,
+ PageShell,
+} from "@/components/layout/page-shell";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
+import { Input } from "@/components/ui/input";
+import { Separator } from "@/components/ui/separator";
+import { Textarea } from "@/components/ui/textarea";
+import { useBotNames } from "@/lib/agents/bot-names";
+import { agentListQueryOptions } from "@/lib/agents/queries";
+import {
+ type PluginServer,
+ type PluginSkill,
+ pluginKeys,
+ pluginsPageQueryOptions,
+} from "@/lib/plugins/queries";
+
+/**
+ * Account-wide plugin and skill installation, with separate per-Bot grants.
+ */
+export const Route = createFileRoute("/_authed/admin/plugins")({
+ component: PluginsPage,
+});
+
+function PluginsPage() {
+ const queryClient = useQueryClient();
+ const { data, isPending, isError } = useQuery(pluginsPageQueryOptions());
+ const { data: agents } = useQuery(agentListQueryOptions());
+ const nameFor = useBotNames();
+ const [tab, setTab] = useState<"catalogue" | "yours" | "skills">("catalogue");
+ const [error, setError] = useState<string | null>(null);
+
+ const refresh = () =>
+ queryClient.invalidateQueries({ queryKey: pluginKeys.all });
+
+ const post = async (path: string, body: unknown) => {
+ setError(null);
+ const response = await fetch(`/api/plugins${path}`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!response.ok) {
+ const detail = (await response.json().catch(() => null)) as {
+ error?: string;
+ } | null;
+ throw new Error(detail?.error ?? "That did not work.");
+ }
+ return response.json();
+ };
+
+ /**
+ * Store the token as a credential first; plugin server records keep only the credential id.
+ */
+ const storeToken = async (
+ serverId: string,
+ token?: string,
+ ): Promise<string | undefined> => {
+ if (!token?.trim()) return undefined;
+ const response = await fetch("/api/admin/credentials", {
+ method: "POST",
+ credentials: "include",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ kind: "mcp",
+ provider: serverId,
+ keyId: `mcp-${serverId}`,
+ plaintext: token.trim(),
+ metadata: { server: serverId },
+ }),
+ });
+ if (!response.ok) {
+ throw new Error("The token could not be stored.");
+ }
+ return (await response.json())?.credential?.id;
+ };
+
+ const mutate = useMutation({
+ mutationFn: async (action: () => Promise<unknown>) => action(),
+ onSuccess: refresh,
+ onError: (thrown: Error) => setError(thrown.message),
+ });
+
+ const bots = (agents ?? []).map((agent: { id: string }) => ({
+ id: agent.id,
+ name: nameFor(agent.id),
+ }));
+
+ return (
+ <PageShell
+ description="What this deployment can reach, and which Bots may reach it. Adding is account-wide; enabling is per Bot."
+ title="Plugins"
+ >
+ <PageSection>
+ <div className="flex flex-wrap gap-2">
+ {(
+ [
+ ["catalogue", "Catalogue"],
+ ["yours", "Yours"],
+ ["skills", "Skills"],
+ ] as const
+ ).map(([key, label]) => (
+ <Button
+ key={key}
+ onClick={() => setTab(key)}
+ size="sm"
+ type="button"
+ variant={tab === key ? "default" : "outline"}
+ >
+ {label}
+ </Button>
+ ))}
+ </div>
+
+ {error ? (
+ <p className="mt-4 text-destructive text-sm" role="alert">
+ {error}
+ </p>
+ ) : null}
+
+ <div className="mt-6">
+ {isPending ? (
+ <PageEmpty>Loading plugins…</PageEmpty>
+ ) : isError || !data ? (
+ <p className="mt-4 text-destructive text-sm" role="alert">
+ Plugins could not be loaded.
+ </p>
+ ) : tab === "catalogue" ? (
+ <Catalogue
+ added={new Set(data.servers.map((server) => server.id))}
+ items={data.catalogue}
+ onAdd={(key, instanceHost, token) =>
+ mutate.mutate(async () => {
+ const credentialId = await storeToken(key, token);
+ return post("/servers", { key, instanceHost, credentialId });
+ })
+ }
+ onAddCustom={(input) =>
+ mutate.mutate(async () => {
+ const credentialId = await storeToken(input.id, input.token);
+ return post("/servers/custom", { ...input, credentialId });
+ })
+ }
+ />
+ ) : tab === "yours" ? (
+ <Yours
+ bots={bots}
+ onGrant={(ref, agentId, held) =>
+ mutate.mutate(() =>
+ held
+ ? fetch(
+ `/api/plugins/grants?kind=mcp&ref=${encodeURIComponent(ref)}&agentId=${encodeURIComponent(agentId)}`,
+ { method: "DELETE", credentials: "include" },
+ )
+ : post("/grants", { kind: "mcp", ref, agentId }),
+ )
+ }
+ onRefresh={(id) =>
+ mutate.mutate(() => post(`/servers/${id}/refresh`, {}))
+ }
+ onRemove={(id) =>
+ mutate.mutate(() =>
+ fetch(`/api/plugins/servers/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ credentials: "include",
+ }),
+ )
+ }
+ servers={data.servers}
+ />
+ ) : (
+ <Skills
+ bots={bots}
+ onGrant={(slug, agentId, held) =>
+ mutate.mutate(() =>
+ held
+ ? fetch(
+ `/api/plugins/grants?kind=skill&ref=${encodeURIComponent(slug)}&agentId=${encodeURIComponent(agentId)}`,
+ { method: "DELETE", credentials: "include" },
+ )
+ : post("/grants", { kind: "skill", ref: slug, agentId }),
+ )
+ }
+ // Admin-authored skills are deployment-global; personal skills are created elsewhere.
+ onInstall={(input) =>
+ mutate.mutate(() => post("/skills", { ...input, global: true }))
+ }
+ onUninstall={(slug) =>
+ mutate.mutate(() =>
+ fetch(`/api/plugins/skills/${encodeURIComponent(slug)}`, {
+ method: "DELETE",
+ credentials: "include",
+ }),
+ )
+ }
+ skills={data.skills}
+ />
+ )}
+ </div>
+ </PageSection>
+ </PageShell>
+ );
+}
+
+function Catalogue({
+ items,
+ added,
+ onAdd,
+ onAddCustom,
+}: {
+ items: {
+ key: string;
+ title: string;
+ vendor: string;
+ summary: string;
+ docsUrl: string;
+ needsCredential: boolean;
+ perInstance: boolean;
+ }[];
+ added: Set<string>;
+ onAdd: (key: string, instanceHost?: string, token?: string) => void;
+ onAddCustom: (input: {
+ id: string;
+ title: string;
+ url: string;
+ token?: string;
+ }) => void;
+}) {
+ const [instanceHost, setInstanceHost] = useState<Record<string, string>>({});
+ const [token, setToken] = useState<Record<string, string>>({});
+ const [addingCustom, setAddingCustom] = useState(false);
+ const [custom, setCustom] = useState({
+ id: "",
+ title: "",
+ url: "",
+ token: "",
+ });
+
+ return (
+ <div className="space-y-6">
+ {/*
+ * ONE COLUMN, like every other list in the app. Two columns meant the eye had to choose a
+ * side and then come back for the other, on a page whose whole job is "what can this
+ * deployment reach" — a question answered by reading down a list once.
+ */}
+ <div className="flex flex-col gap-3">
+ {items.map((item) => (
+ <div
+ className="rounded-lg border border-border bg-card p-4"
+ key={item.key}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="font-medium">{item.title}</div>
+ <p className="text-sm text-muted-foreground">{item.summary}</p>
+ </div>
+ <Button
+ className="shrink-0"
+ disabled={added.has(item.key)}
+ onClick={() =>
+ onAdd(
+ item.key,
+ instanceHost[item.key] || undefined,
+ token[item.key] || undefined,
+ )
+ }
+ size="sm"
+ type="button"
+ variant="outline"
+ >
+ {added.has(item.key) ? "Added" : "Add"}
+ </Button>
+ </div>
+ {item.perInstance ? (
+ <Input
+ aria-label={`Instance host for ${item.title}`}
+ className="mt-2"
+ onChange={(event) =>
+ setInstanceHost((current) => ({
+ ...current,
+ [item.key]: event.target.value,
+ }))
+ }
+ placeholder="https://your-instance.service-now.com"
+ value={instanceHost[item.key] ?? ""}
+ />
+ ) : null}
+ {item.needsCredential ? (
+ /* Mask tokens before they are stored in the credential vault. */
+ <Input
+ aria-label={`Access token for ${item.title}`}
+ className="mt-2"
+ onChange={(event) =>
+ setToken((current) => ({
+ ...current,
+ [item.key]: event.target.value,
+ }))
+ }
+ placeholder="Access token for this server"
+ type="password"
+ value={token[item.key] ?? ""}
+ />
+ ) : null}
+ <a
+ className="mt-2 inline-block text-xs text-muted-foreground underline"
+ href={item.docsUrl}
+ rel="noreferrer"
+ target="_blank"
+ >
+ Vendor documentation
+ </a>
+ </div>
+ ))}
+ </div>
+
+ <div className="flex justify-start">
+ <Button onClick={() => setAddingCustom(true)} size="sm" variant="ghost">
+ <IconPlus />
+ Add a server by URL
+ </Button>
+ </div>
+
+ <Dialog onOpenChange={setAddingCustom} open={addingCustom}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add a server by URL</DialogTitle>
+ <DialogDescription>
+ For a server that is not in the catalogue. Nobody has reviewed it,
+ so every tool it offers is treated as one that changes something,
+ and the server is recorded as custom wherever it appears.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="mt-4">
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="custom-id">Name</FieldLabel>
+ <Input
+ id="custom-id"
+ onChange={(event) =>
+ setCustom((current) => ({
+ ...current,
+ id: event.target.value,
+ }))
+ }
+ placeholder="name (lower-case)"
+ value={custom.id}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="custom-title">Title</FieldLabel>
+ <Input
+ id="custom-title"
+ onChange={(event) =>
+ setCustom((current) => ({
+ ...current,
+ title: event.target.value,
+ }))
+ }
+ placeholder="Title"
+ value={custom.title}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="custom-url">URL</FieldLabel>
+ <Input
+ id="custom-url"
+ onChange={(event) =>
+ setCustom((current) => ({
+ ...current,
+ url: event.target.value,
+ }))
+ }
+ placeholder="https://mcp.example.com/mcp"
+ value={custom.url}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="custom-token">
+ Access token, if it needs one
+ </FieldLabel>
+ <Input
+ id="custom-token"
+ onChange={(event) =>
+ setCustom((current) => ({
+ ...current,
+ token: event.target.value,
+ }))
+ }
+ type="password"
+ value={custom.token}
+ />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter className="mt-4">
+ <Button
+ onClick={() => setAddingCustom(false)}
+ size="sm"
+ variant="ghost"
+ >
+ Cancel
+ </Button>
+ <Button
+ disabled={!(custom.id && custom.title && custom.url)}
+ onClick={() => {
+ onAddCustom(custom);
+ setCustom({ id: "", title: "", url: "", token: "" });
+ setAddingCustom(false);
+ }}
+ size="sm"
+ >
+ Add server
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+/** Plugin server summary shown in the admin grant table. */
+function Yours({
+ servers,
+ bots,
+ onGrant,
+ onRefresh,
+ onRemove,
+}: {
+ servers: PluginServer[];
+ bots: { id: string; name: string }[];
+ onGrant: (ref: string, agentId: string, held: boolean) => void;
+ onRefresh: (id: string) => void;
+ onRemove: (id: string) => void;
+}) {
+ if (servers.length === 0) {
+ return (
+ <p className="text-sm text-muted-foreground">
+ No servers added yet. The Catalogue tab is where they come from.
+ </p>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {servers.map((server) => (
+ <div
+ className="rounded-lg border border-border bg-card"
+ key={server.id}
+ >
+ <div className="flex items-start justify-between gap-3 border-border border-b px-4 py-3">
+ <div>
+ <div className="flex items-center gap-2 font-medium">
+ {server.title}
+ {server.provenance === "custom" ? (
+ <span className="rounded bg-amber-500/15 px-1.5 py-0.5 text-xs text-amber-700 dark:text-amber-500">
+ custom
+ </span>
+ ) : null}
+ </div>
+ <div className="font-mono text-muted-foreground text-xs">
+ {server.url}
+ </div>
+ {server.lastError ? (
+ <div className="mt-1 text-xs text-destructive">
+ {server.lastError}
+ </div>
+ ) : null}
+ </div>
+ <div className="flex shrink-0 gap-2">
+ <Button
+ onClick={() => onRefresh(server.id)}
+ size="sm"
+ type="button"
+ variant="outline"
+ >
+ Refresh tools
+ </Button>
+ <Button
+ onClick={() => onRemove(server.id)}
+ size="sm"
+ type="button"
+ variant="ghost"
+ >
+ Remove
+ </Button>
+ </div>
+ </div>
+
+ {/*
+ * A ROW PER TOOL, NOT A GRID OF TOOLS AGAINST BOTS. The matrix put one checkbox column per
+ * Bot, so it grew a column every time somebody made a Bot and was already scrolling
+ * sideways at four of them — and sideways is where a grant quietly goes unread. The
+ * toggles wrap under the tool they belong to instead, which is how grants are shown
+ * everywhere else in the app.
+ */}
+ {server.tools.length === 0 ? (
+ <p className="px-4 py-3 text-muted-foreground text-sm">
+ No tools listed. Refresh to ask the server again.
+ </p>
+ ) : (
+ <div className="divide-y divide-border">
+ {server.tools.map((tool) => (
+ <div className="px-4 py-3" key={tool.ref}>
+ <div className="flex flex-wrap items-baseline gap-x-2">
+ <span className="font-mono text-xs">{tool.name}</span>
+ <span
+ className={
+ tool.effect === "write"
+ ? "text-amber-600 text-xs dark:text-amber-500"
+ : "text-muted-foreground text-xs"
+ }
+ >
+ {tool.effect === "write" ? "changes things" : "reads"}
+ </span>
+ </div>
+ <p className="mt-0.5 text-muted-foreground text-xs">
+ {tool.description}
+ </p>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {bots.map((bot) => {
+ const held = tool.grantedTo.includes(bot.id);
+ return (
+ <Button
+ key={bot.id}
+ onClick={() => onGrant(tool.ref, bot.id, held)}
+ size="sm"
+ type="button"
+ variant={held ? "default" : "outline"}
+ >
+ {bot.name}
+ </Button>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/** Packaged `/` instructions installed at deployment scope and granted per Bot. */
+function Skills({
+ skills,
+ bots,
+ onInstall,
+ onUninstall,
+ onGrant,
+}: {
+ skills: PluginSkill[];
+ bots: { id: string; name: string }[];
+ onInstall: (input: {
+ slug: string;
+ title: string;
+ summary: string;
+ instructions: string;
+ }) => void;
+ onUninstall: (slug: string) => void;
+ onGrant: (slug: string, agentId: string, held: boolean) => void;
+}) {
+ const [writing, setWriting] = useState(false);
+ const [draft, setDraft] = useState({
+ slug: "",
+ title: "",
+ summary: "",
+ instructions: "",
+ });
+
+ return (
+ <div className="space-y-4">
+ <div className="flex justify-start">
+ <Button onClick={() => setWriting(true)} size="sm" variant="ghost">
+ <IconPlus />
+ Write a skill
+ </Button>
+ </div>
+
+ <Dialog onOpenChange={setWriting} open={writing}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Write a skill for the deployment</DialogTitle>
+ <DialogDescription>
+ The slug is what a person types after a slash, and the
+ instructions are added to the run when they do. Everybody here can
+ use it, and you decide which Bots have it. People write their own
+ on the Skills page.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="mt-4">
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="skill-slug">Slug</FieldLabel>
+ <Input
+ id="skill-slug"
+ onChange={(event) =>
+ setDraft((current) => ({
+ ...current,
+ slug: event.target.value,
+ }))
+ }
+ placeholder="standup-notes"
+ value={draft.slug}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="skill-title">Title</FieldLabel>
+ <Input
+ id="skill-title"
+ onChange={(event) =>
+ setDraft((current) => ({
+ ...current,
+ title: event.target.value,
+ }))
+ }
+ placeholder="Title"
+ value={draft.title}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="skill-summary">Summary</FieldLabel>
+ <Input
+ id="skill-summary"
+ onChange={(event) =>
+ setDraft((current) => ({
+ ...current,
+ summary: event.target.value,
+ }))
+ }
+ placeholder="One line"
+ value={draft.summary}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="skill-instructions">
+ Instructions
+ </FieldLabel>
+ <Textarea
+ className="h-28 font-mono text-sm"
+ id="skill-instructions"
+ onChange={(event) =>
+ setDraft((current) => ({
+ ...current,
+ instructions: event.target.value,
+ }))
+ }
+ placeholder="What the Bot should do when this skill is used."
+ value={draft.instructions}
+ />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter className="mt-4">
+ <Button onClick={() => setWriting(false)} size="sm" variant="ghost">
+ Cancel
+ </Button>
+ <Button
+ disabled={!(draft.slug && draft.title && draft.instructions)}
+ onClick={() => {
+ onInstall(draft);
+ setDraft({
+ slug: "",
+ title: "",
+ summary: "",
+ instructions: "",
+ });
+ setWriting(false);
+ }}
+ size="sm"
+ >
+ Install skill
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {skills.length === 0 ? (
+ <p className="text-muted-foreground text-sm">
+ No skills installed yet.
+ </p>
+ ) : (
+ /* Rows, for the same reason the tool grants are rows: a column per Bot does not scale. */
+ <div className="rounded-lg border border-border bg-card">
+ {skills.map((skill, index) => (
+ <React.Fragment key={skill.slug}>
+ <div className="px-4 py-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <code className="font-mono text-foreground/80 text-xs">
+ /{skill.slug}
+ </code>
+ <span className="font-medium text-sm">{skill.title}</span>
+ {skill.ownerUserId ? (
+ <span className="rounded-md bg-foreground/5 px-1.5 py-0.5 font-medium text-muted-foreground text-xs">
+ {skill.installedBy ?? "somebody"}
+ </span>
+ ) : null}
+ </div>
+ <Button
+ onClick={() => onUninstall(skill.slug)}
+ size="sm"
+ type="button"
+ variant="ghost"
+ >
+ Remove
+ </Button>
+ </div>
+ {skill.summary ? (
+ <p className="mt-0.5 text-muted-foreground text-xs">
+ {skill.summary}
+ </p>
+ ) : null}
+ <div className="mt-2 flex flex-wrap gap-2">
+ {bots.map((bot) => {
+ const held = skill.grantedTo.includes(bot.id);
+ return (
+ <Button
+ key={bot.id}
+ onClick={() => onGrant(skill.slug, bot.id, held)}
+ size="sm"
+ type="button"
+ variant={held ? "default" : "outline"}
+ >
+ {bot.name}
+ </Button>
+ );
+ })}
+ </div>
+ </div>
+ {index !== skills.length - 1 && <Separator />}
+ </React.Fragment>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/app/src/routes/_authed/admin/route.tsx b/app/src/routes/_authed/admin/route.tsx
new file mode 100644
index 00000000..d83cfe74
--- /dev/null
+++ b/app/src/routes/_authed/admin/route.tsx
@@ -0,0 +1,38 @@
+import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
+import { AdminSidebar } from "@/components/admin/admin-sidebar";
+import { SidebarProvider } from "@/components/ui/sidebar";
+import { currentUserQueryOptions } from "../../../lib/auth/queries";
+
+export const Route = createFileRoute("/_authed/admin")({
+ beforeLoad: async ({ context }) => {
+ const user = await context.queryClient.ensureQueryData(
+ currentUserQueryOptions(),
+ );
+ if (user?.role !== "admin") {
+ throw redirect({ to: "/" });
+ }
+ },
+ component: RouteComponent,
+});
+
+function RouteComponent() {
+ return (
+ <SidebarProvider
+ /*
+ * The same 340px the app and Settings use. A rail that changes width as you cross into admin
+ * makes the whole frame look like it moved.
+ */
+ style={
+ {
+ "--sidebar-width": "340px",
+ "--sidebar-width-mobile": "20rem",
+ } as React.CSSProperties
+ }
+ >
+ <AdminSidebar />
+ <main className="flex-1">
+ <Outlet />
+ </main>
+ </SidebarProvider>
+ );
+}
diff --git a/app/src/routes/sign.tsx b/app/src/routes/sign.tsx
new file mode 100644
index 00000000..8eb42d5b
--- /dev/null
+++ b/app/src/routes/sign.tsx
@@ -0,0 +1,111 @@
+import { createFileRoute, redirect } from "@tanstack/react-router";
+import { motion, useReducedMotion } from "motion/react";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { signInWithGoogle } from "@/lib/auth/client";
+import { appConfig } from "@/lib/generated/application-config";
+import { currentUserQueryOptions } from "../lib/auth/queries";
+import AgentOrb from "@/components/agents/orb/agent-orb";
+
+const EASE_OUT = [0.23, 1, 0.32, 1] as const;
+
+const ENTRANCE_SECONDS = 0.4;
+const ENTRANCE_STAGGER_SECONDS = 0.08;
+const ENTRANCE_OFFSET = "translateY(12px)";
+
+export const Route = createFileRoute("/sign")({
+ beforeLoad: async ({ context }) => {
+ const user = await context.queryClient.ensureQueryData(
+ currentUserQueryOptions(),
+ );
+ if (user) {
+ throw redirect({ to: "/" });
+ }
+ },
+ component: SignScreen,
+});
+
+function SignScreen() {
+ const [isPending, setIsPending] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ async function handleGoogleSignIn() {
+ setError(null);
+ setIsPending(true);
+
+ try {
+ await signInWithGoogle();
+ } catch (caughtError) {
+ setError(
+ caughtError instanceof Error
+ ? caughtError.message
+ : "Could not start Google sign-in.",
+ );
+ setIsPending(false);
+ }
+ }
+
+ const prefersReducedMotion = useReducedMotion();
+ const hidden = {
+ opacity: 0,
+ ...(prefersReducedMotion ? {} : { transform: ENTRANCE_OFFSET }),
+ };
+ const shown = {
+ opacity: 1,
+ ...(prefersReducedMotion ? {} : { transform: "translateY(0px)" }),
+ };
+
+ return (
+ <div className="flex flex-col h-dvh w-full items-center justify-center -mt-12">
+ <motion.div
+ animate="shown"
+ className="flex-1 flex w-full max-w-82 flex-col items-center justify-center p-4"
+ initial="hidden"
+ variants={{
+ hidden: {},
+ shown: { transition: { staggerChildren: ENTRANCE_STAGGER_SECONDS } },
+ }}
+ >
+ <motion.div
+ transition={{ duration: ENTRANCE_SECONDS, ease: EASE_OUT }}
+ variants={{ hidden, shown }}
+ className="flex items-center justify-center"
+ >
+ <AgentOrb size="56px" />
+ </motion.div>
+ <motion.h1
+ className="text-2xl font-medium tracking-tight text-center mt-8"
+ transition={{ duration: ENTRANCE_SECONDS, ease: EASE_OUT }}
+ variants={{ hidden, shown }}
+ >
+ Sign in to {appConfig.brand.productName}
+ </motion.h1>
+ <motion.div
+ className="mt-8 w-full"
+ transition={{ duration: ENTRANCE_SECONDS, ease: EASE_OUT }}
+ variants={{ hidden, shown }}
+ >
+ {appConfig.auth.providers.includes("google") ? (
+ <Button
+ className="h-10 w-full tracking-tight"
+ disabled={isPending}
+ onClick={handleGoogleSignIn}
+ size="lg"
+ >
+ {isPending ? "Opening Google…" : "Continue with Google"}
+ </Button>
+ ) : (
+ <p className="text-center text-sm text-muted-foreground">
+ No auth providers are configured.
+ </p>
+ )}
+ {error ? (
+ <p className="mt-3 text-sm text-destructive" role="alert">
+ {error}
+ </p>
+ ) : null}
+ </motion.div>
+ </motion.div>
+ </div>
+ );
+}
diff --git a/app/src/styles.css b/app/src/styles.css
new file mode 100644
index 00000000..cbb26797
--- /dev/null
+++ b/app/src/styles.css
@@ -0,0 +1,231 @@
+@import "tailwindcss";
+@import "tw-animate-css";
+@import "shadcn/tailwind.css";
+/* Composer chips/dropdown. Reads the shadcn tokens declared below, so it themes itself. */
+@import "prompt-area/tailwind.css";
+@import "@fontsource-variable/inter";
+
+/*
+ * Streamdown draws a Bot's prose, and Tailwind only ships classes it can see used. Its markup lives
+ * in a dependency, so without this the transcript renders unstyled markdown — correct HTML with none
+ * of the spacing that makes it readable. The path is relative to this file.
+ */
+@source "../node_modules/streamdown/dist/*.js";
+
+@custom-variant dark (&:is(.dark *));
+
+html {
+ font-size: 15px;
+}
+
+:root {
+ --background: oklch(0.985 0 0);
+ --foreground: oklch(0.145 0 0);
+ --card: oklch(1 0 0);
+ --card-foreground: oklch(0.145 0 0);
+ --popover: oklch(1 0 0);
+ --popover-foreground: oklch(0.145 0 0);
+ --primary: oklch(0.205 0 0);
+ --primary-foreground: oklch(0.985 0 0);
+ --secondary: oklch(0.97 0 0);
+ --secondary-foreground: oklch(0.205 0 0);
+ --muted: oklch(0.96 0 0);
+ --muted-foreground: oklch(0.5 0 0);
+ --accent: oklch(0.97 0 0);
+ --accent-foreground: oklch(0.205 0 0);
+ --destructive: oklch(0.577 0.245 27.325);
+ --border: oklch(0.922 0 0);
+ --input: oklch(0.922 0 0);
+ --ring: oklch(0.708 0 0);
+ --chart-1: oklch(0.87 0 0);
+ --chart-2: oklch(0.556 0 0);
+ --chart-3: oklch(0.439 0 0);
+ --chart-4: oklch(0.371 0 0);
+ --chart-5: oklch(0.269 0 0);
+ --radius: 0.55rem;
+ --sidebar: oklch(0.97 0 0);
+ --sidebar-foreground: oklch(0.145 0 0);
+ --sidebar-primary: oklch(0.205 0 0);
+ --sidebar-primary-foreground: oklch(0.5 0 0);
+ --sidebar-accent: oklch(0.95 0 0);
+ --sidebar-accent-foreground: oklch(0.205 0 0);
+ --sidebar-border: oklch(0.922 0 0);
+ --sidebar-ring: oklch(0.708 0 0);
+}
+
+.dark {
+ --background: oklch(0.145 0 0);
+ --foreground: oklch(0.985 0 0);
+ --card: oklch(0.205 0 0);
+ --card-foreground: oklch(0.985 0 0);
+ --popover: oklch(0.205 0 0);
+ --popover-foreground: oklch(0.985 0 0);
+ --primary: oklch(0.922 0 0);
+ --primary-foreground: oklch(0.205 0 0);
+ --secondary: oklch(0.269 0 0);
+ --secondary-foreground: oklch(0.985 0 0);
+ --muted: oklch(0.269 0 0);
+ --muted-foreground: oklch(0.708 0 0);
+ --accent: oklch(0.269 0 0);
+ --accent-foreground: oklch(0.985 0 0);
+ --destructive: oklch(0.704 0.191 22.216);
+ --border: oklch(1 0 0 / 10%);
+ --input: oklch(1 0 0 / 15%);
+ --ring: oklch(0.556 0 0);
+ --chart-1: oklch(0.87 0 0);
+ --chart-2: oklch(0.556 0 0);
+ --chart-3: oklch(0.439 0 0);
+ --chart-4: oklch(0.371 0 0);
+ --chart-5: oklch(0.269 0 0);
+ --sidebar: oklch(0.205 0 0);
+ --sidebar-foreground: oklch(0.985 0 0);
+ --sidebar-primary: oklch(0.488 0.243 264.376);
+ --sidebar-primary-foreground: oklch(0.985 0 0);
+ --sidebar-accent: oklch(0.269 0 0);
+ --sidebar-accent-foreground: oklch(0.985 0 0);
+ --sidebar-border: oklch(1 0 0 / 10%);
+ --sidebar-ring: oklch(0.556 0 0);
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ margin: 0;
+ position: relative;
+ min-width: 20rem;
+ min-height: 100vh;
+ background: var(--background);
+ color: var(--foreground);
+ font-family: Inter, ui-sans-serif, system-ui, sans-serif;
+}
+
+/*
+ * THERE IS DELIBERATELY NO `button, input, textarea, select { font: inherit }` HERE.
+ *
+ * Form controls do need it — Chrome otherwise draws them in its own ~13.3px system font — and
+ * Tailwind's Preflight already does exactly that, inside `@layer base`, where a utility can still
+ * override it. A second copy written here would sit in NO layer, and an unlayered rule outranks
+ * every layered one no matter how specific: a bare `input` selector beats `.text-sm`. That is not a
+ * specificity fight anybody wins, because layers are resolved before specificity is even consulted.
+ *
+ * One was here, and it silently disabled every `text-*` on every button, input, textarea and select
+ * in the app. Nothing looked broken; the sizes were simply never applied, and the labels — which are
+ * not in that selector list — rendered a size smaller than the fields they belonged to.
+ */
+
+@theme inline {
+ --font-heading: var(--font-sans);
+ --font-sans: "Inter Variable", sans-serif;
+ --color-sidebar-ring: var(--sidebar-ring);
+ --color-sidebar-border: var(--sidebar-border);
+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
+ --color-sidebar-accent: var(--sidebar-accent);
+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
+ --color-sidebar-primary: var(--sidebar-primary);
+ --color-sidebar-foreground: var(--sidebar-foreground);
+ --color-sidebar: var(--sidebar);
+ --color-chart-5: var(--chart-5);
+ --color-chart-4: var(--chart-4);
+ --color-chart-3: var(--chart-3);
+ --color-chart-2: var(--chart-2);
+ --color-chart-1: var(--chart-1);
+ --color-ring: var(--ring);
+ --color-input: var(--input);
+ --color-border: var(--border);
+ --color-destructive: var(--destructive);
+ --color-accent-foreground: var(--accent-foreground);
+ --color-accent: var(--accent);
+ --color-muted-foreground: var(--muted-foreground);
+ --color-muted: var(--muted);
+ --color-secondary-foreground: var(--secondary-foreground);
+ --color-secondary: var(--secondary);
+ --color-primary-foreground: var(--primary-foreground);
+ --color-primary: var(--primary);
+ --color-popover-foreground: var(--popover-foreground);
+ --color-popover: var(--popover);
+ --color-card-foreground: var(--card-foreground);
+ --color-card: var(--card);
+ --color-foreground: var(--foreground);
+ --color-background: var(--background);
+ --radius-sm: calc(var(--radius) * 0.6);
+ --radius-md: calc(var(--radius) * 0.8);
+ --radius-lg: var(--radius);
+ --radius-xl: calc(var(--radius) * 1.4);
+ --radius-2xl: calc(var(--radius) * 1.8);
+ --radius-3xl: calc(var(--radius) * 2.2);
+ --radius-4xl: calc(var(--radius) * 2.6);
+}
+
+@layer base {
+ * {
+ @apply border-border outline-ring/50;
+ }
+ body {
+ @apply bg-background text-foreground;
+ }
+ html {
+ @apply font-sans;
+ }
+
+ ::-webkit-scrollbar {
+ width: 5px;
+ }
+
+ ::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ ::-webkit-scrollbar-thumb {
+ background: var(--border);
+ border-radius: 5px;
+ }
+
+ * {
+ scrollbar-width: thin;
+ scrollbar-color: var(--border) transparent;
+ }
+}
+
+/*
+ * A tool line that is still running.
+ *
+ * A light band sweeps left to right across the words. `background-clip: text` with a transparent
+ * colour is what confines the gradient to the glyphs, and the band is built from the line's own
+ * colour so it reads the same in either theme. Only `background-position` animates, which the
+ * compositor handles without laying the text out again on every frame.
+ */
+.tool-line-running {
+ background-image: linear-gradient(
+ 100deg,
+ currentColor 40%,
+ color-mix(in oklab, currentColor 25%, transparent) 50%,
+ currentColor 60%
+ );
+ background-size: 250% 100%;
+ background-position: 100% 0;
+ background-clip: text;
+ -webkit-background-clip: text;
+ color: transparent;
+ animation: tool-line-sweep 1.6s linear infinite;
+}
+
+@keyframes tool-line-sweep {
+ to {
+ background-position: -150% 0;
+ }
+}
+
+/* Preserve running-state text without shimmer for reduced-motion users. */
+@media (prefers-reduced-motion: reduce) {
+ .tool-line-running {
+ animation: none;
+ background-image: none;
+ color: inherit;
+ }
+}
+
+.tool-line[open] .tool-line-chevron {
+ transform: rotate(90deg);
+}
diff --git a/app/tests/agents.test.ts b/app/tests/agents.test.ts
new file mode 100644
index 00000000..5c335ae6
--- /dev/null
+++ b/app/tests/agents.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, test } from "bun:test";
+import { agentFormSchema } from "@/lib/agents/form";
+import { agentKeys } from "@/lib/agents/queries";
+import { channelKeys } from "@/lib/channels/queries";
+
+describe("teammate query keys", () => {
+ test("separates the visible roster from the hidden one", () => {
+ expect(agentKeys.list()).toEqual(["agents", "list", { hidden: false }]);
+ expect(agentKeys.list(true)).toEqual(["agents", "list", { hidden: true }]);
+ // Both lists and every profile sit under one prefix, so a mutation can invalidate all of them.
+ expect(agentKeys.detail("agent_1")[0]).toBe(agentKeys.all[0]);
+ expect(channelKeys.detail("channel_1")).toEqual([
+ "channels",
+ "detail",
+ "channel_1",
+ ]);
+ });
+});
+
+describe("teammate form validation", () => {
+ test("accepts the fields a person fills in", () => {
+ expect(
+ agentFormSchema.parse({
+ name: " Expense Manager ",
+ title: "Finance Operations",
+ roleDescription: "Review receipts and prepare reimbursement reports.",
+ visibility: "private",
+ endpoint: "",
+ authValue: "",
+ }).name,
+ ).toBe("Expense Manager");
+ });
+
+ test("an endpoint is optional, and must look like a web address", () => {
+ const valid = {
+ name: "Expense Manager",
+ title: "Finance Operations",
+ roleDescription: "Review receipts.",
+ visibility: "private" as const,
+ authValue: "",
+ };
+ // Empty means the Bot in the box, which is what most people want first time.
+ expect(agentFormSchema.safeParse({ ...valid, endpoint: "" }).success).toBe(
+ true,
+ );
+ expect(
+ agentFormSchema.safeParse({
+ ...valid,
+ endpoint: "https://agents.example.com/ag-ui",
+ }).success,
+ ).toBe(true);
+ // Shape only. WHETHER an address is allowed is the server's decision, because it depends on the
+ // deployment and a check that lives in a browser is a check an attacker skips.
+ expect(
+ agentFormSchema.safeParse({ ...valid, endpoint: "not a url" }).success,
+ ).toBe(false);
+ });
+
+ test("rejects what the server would reject", () => {
+ const valid = {
+ name: "Expense Manager",
+ title: "Finance Operations",
+ roleDescription: "Review receipts.",
+ visibility: "private" as const,
+ endpoint: "",
+ authValue: "",
+ };
+
+ expect(agentFormSchema.safeParse({ ...valid, name: " " }).success).toBe(
+ false,
+ );
+ expect(
+ agentFormSchema.safeParse({ ...valid, name: "n".repeat(81) }).success,
+ ).toBe(false);
+ expect(
+ agentFormSchema.safeParse({ ...valid, title: "t".repeat(121) }).success,
+ ).toBe(false);
+ expect(
+ agentFormSchema.safeParse({
+ ...valid,
+ roleDescription: "r".repeat(1001),
+ }).success,
+ ).toBe(false);
+ expect(
+ agentFormSchema.safeParse({ ...valid, visibility: "everyone" }).success,
+ ).toBe(false);
+ });
+});
diff --git a/app/tests/auth-queries.test.ts b/app/tests/auth-queries.test.ts
new file mode 100644
index 00000000..c28e15cb
--- /dev/null
+++ b/app/tests/auth-queries.test.ts
@@ -0,0 +1,7 @@
+import { expect, test } from "bun:test";
+import { authKeys, currentUserQueryOptions } from "../src/lib/auth/queries";
+
+test("uses a stable key for the current authenticated user", () => {
+ expect(authKeys.currentUser()).toEqual(["auth", "current-user"]);
+ expect(currentUserQueryOptions().queryKey).toEqual(["auth", "current-user"]);
+});
diff --git a/app/tests/compose-state.test.ts b/app/tests/compose-state.test.ts
new file mode 100644
index 00000000..33234cda
--- /dev/null
+++ b/app/tests/compose-state.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from "bun:test";
+import {
+ addRecipient,
+ canSend,
+ MAX_RECIPIENTS,
+ removeRecipient,
+} from "../src/components/channels/compose-state";
+
+const KNOWLEDGE = { id: "knowledge", name: "Knowledge" };
+const RISK = { id: "risk-analyst", name: "Risk Analyst" };
+
+describe("addRecipient", () => {
+ test("adds to an empty list", () => {
+ expect(addRecipient([], KNOWLEDGE)).toEqual([KNOWLEDGE]);
+ });
+
+ test("replaces rather than appends once the cap is reached", () => {
+ // One teammate per channel today; a second pick replaces the first.
+ expect(addRecipient([KNOWLEDGE], RISK)).toEqual([RISK]);
+ });
+
+ test("adding the teammate already chosen is a no-op", () => {
+ expect(addRecipient([KNOWLEDGE], KNOWLEDGE)).toEqual([KNOWLEDGE]);
+ });
+});
+
+describe("removeRecipient", () => {
+ test("removes by id", () => {
+ expect(removeRecipient([KNOWLEDGE], "knowledge")).toEqual([]);
+ });
+
+ test("ignores an id that is not present", () => {
+ expect(removeRecipient([KNOWLEDGE], "nobody")).toEqual([KNOWLEDGE]);
+ });
+});
+
+describe("canSend", () => {
+ test("needs exactly one recipient and some text", () => {
+ expect(canSend([KNOWLEDGE], "hello")).toBe(true);
+ });
+
+ test("refuses with no recipient", () => {
+ expect(canSend([], "hello")).toBe(false);
+ });
+
+ test("refuses whitespace-only text", () => {
+ expect(canSend([KNOWLEDGE], " ")).toBe(false);
+ });
+
+ test("cap is one", () => {
+ expect(MAX_RECIPIENTS).toBe(1);
+ });
+});
diff --git a/app/tests/connectors.test.ts b/app/tests/connectors.test.ts
new file mode 100644
index 00000000..f7dd3af3
--- /dev/null
+++ b/app/tests/connectors.test.ts
@@ -0,0 +1,6 @@
+import { expect, test } from "bun:test";
+import { connectorKeys } from "@/lib/connectors/queries";
+
+test("uses a dedicated query namespace for the seeded connector catalog", () => {
+ expect(connectorKeys.list()).toEqual(["connectors", "list"]);
+});
diff --git a/app/tests/credential-form.test.ts b/app/tests/credential-form.test.ts
new file mode 100644
index 00000000..1991b7f1
--- /dev/null
+++ b/app/tests/credential-form.test.ts
@@ -0,0 +1,13 @@
+import { expect, test } from "bun:test";
+import { credentialFormSchema } from "@/lib/credentials/form";
+
+test("requires credential type, provider, key ID, and secret", () => {
+ expect(
+ credentialFormSchema.safeParse({
+ kind: "model",
+ provider: "",
+ keyId: "",
+ plaintext: "",
+ }).success,
+ ).toBeFalse();
+});
diff --git a/app/tests/router.test.ts b/app/tests/router.test.ts
new file mode 100644
index 00000000..70b8f6bf
--- /dev/null
+++ b/app/tests/router.test.ts
@@ -0,0 +1,12 @@
+import { expect, test } from "bun:test";
+import { router } from "../src/router";
+
+test("provides the generated index route", () => {
+ expect(router.routesByPath["/"]?.fullPath).toBe("/");
+});
+
+test("provides the protected credential administration route", () => {
+ expect(router.routesByPath["/admin/credentials"]?.fullPath).toBe(
+ "/admin/credentials",
+ );
+});
diff --git a/app/tests/transcript-messages.test.ts b/app/tests/transcript-messages.test.ts
new file mode 100644
index 00000000..2d2f55c6
--- /dev/null
+++ b/app/tests/transcript-messages.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, test } from "bun:test";
+import {
+ seedMessage,
+ stashFirstMessage,
+ takeFirstMessage,
+ transcriptMessages,
+} from "../src/components/channels/transcript-messages";
+
+/**
+ * Brand-new channel transcript seeding: show the optimistic message until stored messages arrive.
+ */
+
+const SEED = seedMessage("what is our refund policy?", "seed-1");
+const STORED = seedMessage("what is our refund policy?", "stored-1");
+
+describe("transcriptMessages", () => {
+ test("shows the seed while the agent has nothing", () => {
+ expect(transcriptMessages([], SEED)).toEqual([SEED]);
+ });
+
+ test("shows the agent's messages once it has any, and drops the seed", () => {
+ expect(transcriptMessages([STORED], SEED)).toEqual([STORED]);
+ });
+
+ test("shows nothing for an empty channel with no seed", () => {
+ expect(transcriptMessages([], null)).toEqual([]);
+ });
+
+ test("is unaffected by a seed on an established channel", () => {
+ expect(transcriptMessages([STORED], null)).toEqual([STORED]);
+ });
+});
+
+describe("seedMessage", () => {
+ test("is a user message carrying the text", () => {
+ const message = seedMessage("hello", "id-1");
+ expect(message).toEqual({ id: "id-1", role: "user", content: "hello" });
+ });
+});
+
+describe("the first-message stash", () => {
+ test("hands the message to the channel that was just created", () => {
+ stashFirstMessage("channel_a", "hello");
+ expect(takeFirstMessage("channel_a")).toBe("hello");
+ });
+
+ test("gives it up only once", () => {
+ // Take-once prevents remounts from resending the first message.
+ stashFirstMessage("channel_b", "hello");
+ takeFirstMessage("channel_b");
+ expect(takeFirstMessage("channel_b")).toBeNull();
+ });
+
+ test("has nothing for a channel that was opened normally", () => {
+ expect(takeFirstMessage("channel_never_stashed")).toBeNull();
+ });
+
+ test("keeps two channels' messages apart", () => {
+ stashFirstMessage("channel_c", "for c");
+ stashFirstMessage("channel_d", "for d");
+ expect(takeFirstMessage("channel_d")).toBe("for d");
+ expect(takeFirstMessage("channel_c")).toBe("for c");
+ });
+});
diff --git a/app/vite.config.ts b/app/vite.config.ts
new file mode 100644
index 00000000..9ec5e21a
--- /dev/null
+++ b/app/vite.config.ts
@@ -0,0 +1,26 @@
+import path from "node:path";
+import tailwindcss from "@tailwindcss/vite";
+import { tanstackRouter } from "@tanstack/router-plugin/vite";
+import react from "@vitejs/plugin-react";
+import { defineConfig } from "vite";
+
+export default defineConfig({
+ plugins: [tanstackRouter(), react(), tailwindcss()],
+ resolve: {
+ alias: {
+ "@": path.resolve(__dirname, "./src"),
+ },
+ },
+ server: {
+ port: Number.parseInt(process.env.APP_PORT ?? "3010", 10),
+ strictPort: true,
+ proxy: {
+ // `ws: true` is required for the live screen. Without it Vite answers the upgrade request with
+ // the app's HTML and the socket fails with an opaque error that looks like a server problem.
+ "/api": {
+ target: `http://localhost:${process.env.SERVER_PORT ?? "3001"}`,
+ ws: true,
+ },
+ },
+ },
+});
diff --git a/assets/architecture-dark.svg b/assets/architecture-dark.svg
new file mode 100644
index 00000000..ba83dc99
--- /dev/null
+++ b/assets/architecture-dark.svg
@@ -0,0 +1,111 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1420 852" width="1420" height="852" role="img">
+<title>OpenBot architecture</title>
+<desc>A turn goes from the app to the server, which sends it to a Bot over AG-UI. Every tool call the Bot makes returns through the gateway, which resolves the target, decides it against the configured policy, records an audit row, and only then acts, or refuses and names the rule. Allowed actions reach that Bot's own computer, one container each holding its own Chromium, logins and workspace, created by the supervisor. Every decision lands in PostgreSQL; threads and memory live in CopilotKit Intelligence.</desc>
+<rect width="1420" height="852" fill="#0f1216"/>
+<text x="64" y="56" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="26" font-weight="700" fill="#e9edf2" text-anchor="start" >OpenBot</text>
+<text x="64" y="82" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="400" fill="#98a3b0" text-anchor="start" >Every action a Bot takes is decided before it happens and recorded after.</text>
+<text x="372" y="112" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="11.5" font-weight="700" fill="#4a5361" text-anchor="start" letter-spacing="1.6" >BOTS</text>
+<path d="M372.45948094712605 127.30841256267783 C414.7755442572661 127.75903135748119, 457.83286860453444 127.65882468778416, 583.2534497483199 127.48647627032261 M371.3140529838797 126.25305205691443 C447.72572458904966 123.9519227893986, 521.8518146289691 124.77442959051916, 583.301331734899 125.43840807013089 M585.1795945325866 127.4076824894175 C581.847053746193 154.68777022492142, 584.3807238557034 180.293101147376, 581.7226641872898 219.5229846647009 M584.6959414626472 125.99034344153479 C586.2008775441483 148.55480810673907, 584.7765252946451 172.6183714543469, 584.6120601291768 216.95449549453332 M582.4079195029753 219.59986556144858 C539.6645271206439 218.16499517496968, 492.9976075144399 219.16803866177213, 370.50071936248077 218.14642846906054 M583.0778632240084 217.97157046942752 C513.369715478166 220.62198963016272, 442.9750986091751 220.1870753748219, 372.59735064701084 217.68948141927538 M370.0545847216621 219.85909935142845 C370.40988783358114 190.42915744464844, 371.2971799981453 160.60501292403785, 370.0050049165264 126.59232564475387 M371.60366226090116 217.7809959609993 C372.10964423407614 196.38327897908167, 373.1112794189602 173.91049686120823, 371.39012604309244 126.77422611610965" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="390" y="160" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#e9edf2" text-anchor="start" >agent-bot :4200</text>
+<text x="390" y="184" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >proof-of-concept AG-UI Bot</text>
+<path d="M604.7753654003266 126.8011153209389 C658.5685705694083 124.3594185872323, 709.4449551140856 123.36327777270502, 818.8914099322726 126.35842553141956 M605.5771367399276 125.36737724572752 C679.3664301281144 123.25026774481103, 752.6020563115502 123.12215808494332, 818.6802942479658 126.11360655659315 M816.2142244100571 124.2264978647232 C819.30247336092 143.21962234973907, 818.5918479031562 161.63718531131744, 819.5268792867661 216.19005148410798 M819.0730095982551 125.24631737470627 C818.1067322034836 152.7386737704277, 817.1768581647873 180.28970936536788, 817.7298718571662 217.34441727399826 M816.4182673476415 217.164418486368 C751.8307319376827 214.65393328507872, 687.0144165939447 213.82085376244598, 606.6934201704665 218.2228808325322 M817.783109710816 218.31246875807645 C761.1317898762758 214.7547609320527, 702.329790426672 214.28422255920648, 606.9569271120084 217.52542780000655 M603.9443071126938 218.84863684177398 C607.7744201186181 180.81723568439483, 606.6089606764793 145.4805855035782, 604.7424600362777 124.88841116428375 M605.181710922718 218.56795052289962 C604.5324182857514 185.13760660886766, 604.5576956142426 150.41828564405444, 604.9790272831917 127.02598694562911" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="624" y="160" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#e9edf2" text-anchor="start" >agent-langgraph :4201</text>
+<text x="624" y="184" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >LangGraph AG-UI Bot</text>
+<path d="M839.9061374464202 125.51945454854727 C917.2687686544856 128.1001170505689, 995.6132896015037 128.58872971696562, 1089.889862179768 125.00798557547179 M839.220793117005 126.90326414473529 C898.4226071404934 127.69702946847653, 957.6754931871812 126.53741045013717, 1089.8668724811935 125.32284189147505 M1087.7255521953107 124.33001983761787 C1088.1943130253076 156.99140072464945, 1089.9960092304468 184.3063765823841, 1089.873804873228 216.83503559231758 M1089.6582227140666 125.96863070428371 C1089.1201610215664 156.89218319356442, 1091.0488646157742 189.55568624436856, 1090.7836889654398 217.05005074441434 M1088.6110016661858 219.7226520476661 C1012.7272750091281 219.7210496936133, 934.8393010308669 220.149361834302, 838.3537535762667 217.38680557246659 M1090.6522105214349 217.4901317856483 C991.3425187622314 219.8864853116917, 890.4661024125554 220.45001686733917, 840.7712908044833 218.14438281684852 M839.382125300169 218.97036445736885 C838.285890841937 197.4238574564457, 838.3870133166074 177.49383605122566, 838.4411567866803 125.87924984097481 M840.2367629438638 218.08406325280666 C841.7402005732536 192.56462548673153, 840.6851090014458 167.96306796967983, 840.6045936971902 125.64235707223415" fill="none" stroke="#8b8ff5" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="858" y="160" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#8b8ff5" text-anchor="start" >your agent</text>
+<text x="858" y="184" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >any AG-UI endpoint, any framework</text>
+<text x="858" y="205" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#8b8ff5" text-anchor="start" font-style="italic" >bring your own</text>
+<path d="M63.298027720887 297.379370376289 C127.12290222325379 296.37010186649417, 191.55082946703172 295.1311413595876, 297.4038765435721 297.74717876822547 M64.66566603363925 296.5664660805724 C112.3242162041618 296.54714619175, 160.37152977972096 297.47249089731633, 295.5689448278131 295.0486315646933 M295.9449029803276 295.2117633938789 C299.22578607020375 371.00392719507215, 295.5845083755016 443.0246188282967, 297.01521052122115 493.42706986665723 M296.5299957334995 296.52405175566673 C298.56670567722324 364.90128549933434, 296.52104508609773 432.8036107957363, 295.10531864762305 491.93643941283227 M297.69664504102525 492.7352395694955 C224.9711276443222 490.88477516847996, 153.5332478905928 489.4009804780285, 63.43303564825135 490.9080976207972 M295.6022046899739 491.99013265221384 C211.5102041934872 492.82316114880143, 126.36933880875581 493.2890257798121, 63.697564484611625 491.7713455276677 M65.7992814898491 492.5167965054512 C62.78387622284889 439.72076536417006, 61.52514247345924 387.80716830492014, 61.942220866680145 297.343455517292 M64.6392383635044 491.875044721365 C64.12494536314011 439.87314400076866, 64.66594248685837 388.6631317079067, 63.21203442215919 295.21359204649923" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="82" y="332" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="18" font-weight="700" fill="#e9edf2" text-anchor="start" >you</text>
+<text x="82" y="354" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >app :3010</text>
+<text x="82" y="388" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >channels and chat</text>
+<text x="82" y="409" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >the Bot's live screen</text>
+<text x="82" y="430" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >take the wheel</text>
+<text x="82" y="451" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >/admin</text>
+<path d="M62.61822949567632 558.2329232313932 C140.5492669278654 559.4735470740345, 219.3145233572884 559.7075471963932, 294.3663793568414 559.8895392112034 M64.03002701887954 560.6700206544464 C128.76601080175504 563.4009772834773, 192.67508495743937 562.609880969618, 296.84948056865164 559.7971136221261 M295.2138950169086 559.3263611972332 C298.0993197143316 595.1830051362514, 298.64605490567686 631.3952337920666, 294.50468652844427 714.3234145343304 M296.0540162652731 559.219140997529 C296.1110535814762 618.911117759347, 296.66814405465124 680.9038666158915, 297.13905721604823 715.630875864625 M297.0798158502172 715.4356488733929 C224.63005169925074 713.3100660506027, 152.94604805536196 713.7511055650658, 62.575253519678164 715.5227113445166 M296.7724666242812 715.5834463993095 C216.57326604904515 714.3889101719773, 136.85927690794603 714.2340261806985, 64.77291417463192 715.767248457231 M65.4573829472065 717.532244604826 C63.09935324032306 657.9304899632931, 61.58220903713703 604.658929413557, 65.74403627514839 561.7750376880169 M63.45034786164761 716.5416295915842 C64.65608487710954 678.2791013389826, 63.682322078800205 641.2706654936075, 63.249078997969626 560.2923109918833" fill="none" stroke="#98a3b0" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="82" y="594" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#e9edf2" text-anchor="start" >when it needs you</text>
+<text x="82" y="622" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >it stops and asks,</text>
+<text x="82" y="644" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >you take the wheel</text>
+<text x="82" y="666" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >in its browser,</text>
+<text x="82" y="688" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >and hand it back</text>
+<path d="M372.66621589244374 296.113936231446 C472.135099323839 294.18999407969784, 573.4626744626171 293.81774314049494, 847.5364319760095 295.2817677900874 M372.24244511832126 295.9468995267602 C534.9349017423283 296.6148733090316, 698.1762702448312 296.7009495838577, 848.2497789713334 295.80987227311334 M849.1369309403922 296.56044935135645 C850.056186801107 378.3564538642972, 852.0590960553928 463.11466890126127, 848.8262762519998 599.3279800450027 M848.2609713273171 295.5274586002608 C851.0322105410625 381.47048719763814, 849.9805697025621 467.87784025456625, 848.6835504474409 600.3399499011036 M848.6640543357665 601.0064121040998 C715.9015159861755 603.3054752482482, 584.8079464264672 602.0103013666235, 372.8168763928478 599.4291859554755 M848.3734663323435 600.3746715931871 C749.184542848704 598.5892555184859, 650.1334649223106 598.9945010763978, 371.91340987297275 600.1832966287982 M371.5698358894083 599.0543529881606 C373.879922371359 492.7903756964529, 372.02787776462924 388.1307250962686, 373.06425273796907 294.5759009061038 M372.0840445313832 600.8101141179719 C369.066405300502 529.7116726961306, 369.75944933813446 460.5921184700899, 372.7269533599055 295.70492091979145" fill="none" stroke="#e9edf2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="394" y="332" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="18" font-weight="700" fill="#e9edf2" text-anchor="start" >server :3001</text>
+<text x="394" y="354" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13" font-weight="400" fill="#98a3b0" text-anchor="start" >CopilotKit runtime, auth, roles, teammates</text>
+<path d="M392.99490505291766 377.1790007470653 C519.3360949498855 374.0940089685583, 643.5004716145095 372.98248862387567, 825.3126639961062 378.20087315801743 M394.64713985393547 377.6755641991004 C558.9012461603247 383.00060959921046, 724.2774428466357 382.76585394104393, 825.3510824832397 377.3081348621009 M823.4570766448975 380.54672584533694 C826.7098966163635 436.62927570343015, 827.2525846046448 494.80909118652346, 823.5976406097412 572.5098728179931 M826.9837327957154 378.56578197479246 C827.6427371284485 436.46261138916014, 827.5880923530578 494.99518299102783, 825.4635484695434 571.3481733322144 M825.7097201331227 572.3462659663915 C719.0456922334889 573.7884970780856, 612.0911418715114 573.8587154449655, 395.1979898666237 571.1646588320311 M826.1879792775048 571.6315735545155 C739.2576037778392 569.25899671261, 651.7875863130956 569.1295028161624, 394.17050143915276 571.5799295026721 M394.91144676208495 569.2466526031494 C388.6894978355408 516.6690221786499, 391.21734207382207 465.31365737915036, 395.4074794769287 379.24183082580566 M394.23955554962157 571.5859357833863 C394.84703612899784 500.40575675964357, 394.5435632286072 428.8988199234009, 394.77288684844973 378.8210615158081" fill="none" stroke="#f0b429" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="412" y="410" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="16" font-weight="700" fill="#f0b429" text-anchor="start" >the gateway</text>
+<text x="412" y="440" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >1. resolve the target</text>
+<text x="412" y="466" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >2. decide · your CEL policy, deny before allow</text>
+<text x="412" y="492" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >3. record · an audit row, allowed or refused</text>
+<text x="412" y="518" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="13.5" font-weight="400" fill="#98a3b0" text-anchor="start" >4. act, or refuse and name the rule</text>
+<text x="412" y="554" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12" font-weight="400" fill="#4a5361" text-anchor="start" >browser · files · MCP · components</text>
+<text x="1076" y="282" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="11.5" font-weight="700" fill="#4a5361" text-anchor="start" letter-spacing="1.6" >A COMPUTER EACH</text>
+<path d="M1076.7625788604055 295.23202943289476 C1140.3169584729706 295.76059539141596, 1202.8444943100824 296.8345436675912, 1376.6369959445162 294.77395934457485 M1075.4071073434554 295.990113740448 C1161.641309680067 296.38894656675996, 1246.8642830195054 297.2259860613036, 1375.1719409092252 296.61556920945503 M1374.2633885391056 293.82817116901276 C1377.8737740792662 321.8738661073148, 1376.5540497817428 348.47884983345864, 1373.8401287324727 379.8540451876819 M1375.5280464824289 295.8317533258349 C1375.132431273794 328.5740893576294, 1376.0838425329684 359.5766064349562, 1374.8668627794832 380.9332284335047 M1374.5181193482247 379.20885255324663 C1285.5344521662269 376.81998223416207, 1190.8356217231312 377.32701176171366, 1077.074520970345 379.23730472843073 M1376.0209721610274 380.4014649525919 C1312.6469879006384 378.6272419869272, 1248.6624188429296 377.81925461733056, 1075.7931273657268 380.2687511994904 M1076.4718986041844 379.81752258464695 C1075.8256441749782 358.2047201119363, 1073.4501505293101 336.8908060364425, 1073.923518253118 296.14959624931214 M1075.4052730020135 380.53308019675313 C1075.71691927678 357.42651932574813, 1076.5423211670577 335.36698032058774, 1075.8574674423785 295.11091104783117" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="1094" y="326" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#e9edf2" text-anchor="start" >risk-analyst</text>
+<text x="1094" y="348" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >Chromium · its own logins</text>
+<text x="1094" y="366" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >/workspace · its own files</text>
+<path d="M1076.8829378630178 396.5130117344034 C1140.3475692222037 396.24523646232535, 1202.0383308866628 396.0934507807518, 1375.538895983422 397.48070335843295 M1076.240215542272 396.23306600689347 C1188.4029698675251 392.5774181733133, 1302.9415895917043 393.1280723321176, 1376.6804146069235 395.9085719989314 M1377.2247769355774 398.00745725631714 C1374.7543839206696 426.0746512413025, 1376.882908700943 456.1655756950379, 1375.9197262763978 478.30708799362185 M1375.5653512477875 395.67008194923403 C1375.3706738708495 422.0383997440338, 1375.6445218322754 449.67688355445864, 1375.0572076320648 480.56960740089414 M1376.5756606439627 479.6854735220133 C1311.6465884012441 481.2853289943392, 1247.368099751299 483.89728829675005, 1076.3746694311635 478.8249428979959 M1375.8313875772878 480.3264844579127 C1315.245997033547 480.08698949873406, 1253.2943809449819 480.2308230311712, 1076.5697021616659 480.46810477084915 M1074.662966632843 478.0623339653015 C1075.6142169475556 445.9564253807068, 1074.764421415329 414.8679972648621, 1078.2229550361633 396.0625506401062 M1075.8276528835297 479.73234086036683 C1074.3145914909364 447.44559960365297, 1075.3229121086122 415.7821493625641, 1075.222927236557 396.620635843277" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="1094" y="426" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#e9edf2" text-anchor="start" >knowledge</text>
+<text x="1094" y="448" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >Chromium · its own logins</text>
+<text x="1094" y="466" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >/workspace · its own files</text>
+<path d="M1074.439511465849 495.52421239392453 C1164.4674815573844 499.7642296831155, 1252.1221597610418 499.593763528227, 1375.8364550819122 494.69987498589956 M1076.5133221139097 495.3942301312693 C1151.9033013803664 495.3905557506075, 1226.5849989363678 494.8643998085297, 1376.337556134708 496.1595102860905 M1376.1104820668697 497.67984986901286 C1376.4202193617582 524.4391814529896, 1378.9412446379424 558.6374351561069, 1374.684690707922 577.905162101984 M1376.6655828744174 495.6509309977293 C1376.7288790668488 528.9940876454115, 1376.2341791118622 559.9980078428983, 1376.1181041032075 579.3031659334898 M1377.5027423641925 579.2342999406615 C1268.27696543833 576.9839161557857, 1163.9841974284955 576.9001258529723, 1076.244851983796 579.724100213862 M1376.2918811389504 579.7368834765592 C1300.099905557754 580.9626693569039, 1222.0236566578992 582.0253991354682, 1075.3666058023146 579.6820371308067 M1077.2311863362788 578.5956385195256 C1076.9636584423304 558.200550633669, 1078.1491002224207 541.4619629919529, 1074.96114448905 494.005630928278 M1075.077572658658 579.2098060816527 C1074.6183349195958 559.5909568756819, 1074.973360306406 539.5959571570158, 1075.498019912839 495.4192126482725" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="1094" y="526" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="15" font-weight="650" fill="#e9edf2" text-anchor="start" >your agent</text>
+<text x="1094" y="548" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >Chromium · its own logins</text>
+<text x="1094" y="566" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >/workspace · its own files</text>
+<path d="M1077.3574142853201 656.2595966941807 C1194.1999862133332 656.7320105479064, 1312.8508099436654 653.8253777967948, 1376.1171042022659 655.3335251775646 M1075.6462710070678 656.045230964574 C1135.8478064911708 657.0721983690852, 1197.5647282204031 657.0174887411071, 1376.6144162124194 656.0425126935303 M1374.266309273243 656.8149287104607 C1374.406236836791 677.9908762097359, 1375.6347185109855 701.8085107207298, 1376.9544886708259 746.5226294398308 M1375.7827475965023 657.0092307627201 C1375.2105778473617 687.7035482704639, 1373.8418600815535 720.7853230535984, 1376.990852111578 746.9222779810428 M1377.0853813000588 746.6376583345937 C1273.8570473421646 749.6109480175596, 1172.1602612787774 747.0843713779227, 1076.5430074130493 744.7435349024014 M1375.263570612992 745.783627132832 C1313.941447511542 748.6532385402439, 1251.0053212216276 749.9929601381691, 1075.6093379066492 745.9585840644982 M1076.8820784687996 747.2097674250602 C1075.5358215061426 727.3576533913613, 1074.6557826725243 702.762070119381, 1076.1196963429452 656.2621703028678 M1075.6586947858334 745.756006962061 C1075.5946337381602 716.3840447247028, 1075.2038090387582 686.0483678877354, 1076.0629785001279 655.4351796686649" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="1094" y="686" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="14.5" font-weight="650" fill="#e9edf2" text-anchor="start" >supervisor :4500</text>
+<text x="1094" y="710" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >the only process that</text>
+<text x="1094" y="728" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >creates a computer</text>
+<text x="1076" y="782" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" font-style="italic" >no Bot can read another's files</text>
+<text x="1076" y="802" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" font-style="italic" >or reuse another's sign-ins</text>
+<path d="M371.77719738941863 658.8046111064875 C417.776188965833 658.4117011528149, 468.0858579875452 657.0151969704732, 599.7057869143761 658.7018603264935 M371.1782658615275 659.4576557152258 C437.21810109504145 655.9872136278071, 504.35238132742984 656.8110725535373, 597.4351052316795 660.4399887976508 M599.3834805130958 659.1878476500511 C595.0489515401124 686.3556809544563, 599.3574945546388 710.4904454112052, 599.3446564316749 779.9106133818626 M598.0706528365612 659.5830736458302 C598.9616066992999 704.3041988909245, 599.2178851187945 750.4497687160969, 598.9248396575451 777.935109359026 M597.9866673797949 776.7276626399834 C525.1357208267116 777.3597026026896, 452.39324470423855 774.8390503212951, 373.67811312519177 776.700432292831 M598.8010006398623 778.6105373547597 C509.30977625291786 776.7332297686188, 420.6744100196916 776.5683482503597, 372.96476227909136 778.843197860217 M372.2056675553322 778.9785634398461 C369.88993355071545 740.8438836693764, 373.2377099636793 700.2691038012505, 369.8595436692238 658.632457101345 M371.6618725478649 777.0497579872608 C373.47795639111996 732.1855323851108, 373.2218446738959 686.5805169880391, 372.99138895869254 659.2364250481129" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="390" y="692" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="14.5" font-weight="650" fill="#e9edf2" text-anchor="start" >PostgreSQL :5432</text>
+<text x="390" y="718" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >the audit trail</text>
+<text x="390" y="737" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >policy, grants</text>
+<text x="390" y="756" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >credentials, encrypted</text>
+<path d="M622.3432034638697 660.7815759763811 C681.2598863875551 661.6487524956707, 737.2153987088575 662.2306085694048, 848.9228949392103 661.3572990213335 M621.3508487794204 659.9248976428028 C678.0095467088095 659.7162817255381, 733.7937468872024 658.4204990121964, 847.1432577807052 660.0704368209027 M847.0395777702331 658.2585469245911 C847.0160150228501 689.5354117393495, 847.9101709066391 717.4768273353576, 847.6376704216003 777.1889210700989 M846.9091913700104 659.4766217708587 C849.0430674993515 691.4443385601044, 850.0115901433945 721.216498708725, 849.1319468021393 777.1040860652923 M847.1600099308595 778.9045973184149 C776.3056037505262 774.2220893286756, 704.5834341253102 775.9160679548316, 623.6368516426844 778.8761569006329 M847.9145462777419 778.7994555215321 C789.707846430798 776.0533092502134, 730.5650780341078 774.7863878487858, 622.4515771264096 777.0613130753742 M621.8370814323425 779.7578206062317 C623.5139980005264 733.240727519989, 622.8942866968155 687.8444352149963, 622.4935725212097 661.8391713142395 M621.5919336795807 777.4306470394134 C621.7114059022904 749.1202331066132, 622.1790496400833 722.1361375331878, 622.3120523929596 660.3810605525971" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="640" y="692" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="14.5" font-weight="650" fill="#e9edf2" text-anchor="start" >CopilotKit Intelligence</text>
+<text x="640" y="718" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >durable threads</text>
+<text x="640" y="737" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >memory</text>
+<text x="640" y="756" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="400" fill="#98a3b0" text-anchor="start" >external service</text>
+<path d="M300.4589563369751 371.08134212493894 C322.4827579498291 370.67456152439115, 341.7028486251831 371.4913400888443, 362.7868432998657 372.91292781829833 M302.5622073173523 371.7094159126282 C322.3822106361389 372.8722309827805, 340.8900069236755 372.7094959974289, 363.176144695282 372.8805859565735" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M362.9678628921509 372.9096670150757 L353.06632849426273 376.3547240474282 L350.7515518829346 365.9711468479575" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M364.2473675441742 371.6587248325348 C360.72612594599997 372.49661110629955, 359.4484773349184 375.03055016652996, 352.68894075126656 376.6909818770944 M364.4178992509842 372.4447442579269 C361.3568441725256 373.16223622908075, 357.5450789331829 374.3659758966915, 352.1774862215043 377.4793757226525 M351.5137414664773 377.30446636981617 C352.7259723290091 374.7929712867012, 352.52782648272773 371.40237811588946, 352.102064091789 366.021968827131 M352.4162832408995 377.5075972153414 C352.49687079458624 374.74450538997775, 351.90183308830274 372.19484669472683, 352.45169311981834 367.0644621463056 M351.9116027996064 366.1489455101432 C355.56486014911656 367.27013510095117, 357.8859029989133 369.15061231784307, 363.57628142356873 371.84059708595277 M352.0922709199906 366.64978457664864 C356.5112412024035 368.738349992971, 360.632844880422 370.4800200653484, 363.9503051042557 371.9376875257492" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="334" y="358" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#98a3b0" text-anchor="middle" >a turn</text>
+<path d="M363.06768131256104 427.64463863372805 C345.60298919677734 428.0882730093002, 325.86896114349366 429.6389382925033, 302.32984561920165 427.1778844833374 M364.2176348686218 428.6527432441711 C350.26705598831177 427.86236346149445, 336.7620825767517 427.9584663667679, 301.7495898246765 427.45042695999143" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M302.92279148101807 426.8675802230835 L315.2351046874999 423.3263928196372 L314.0407382324218 432.66501152301413" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M301.92954237937926 428.52019501686095 C304.79288386502833 427.18655614896795, 308.4517605843644 425.1879104061075, 313.04280010490413 423.47188633655924 M302.12414459705354 428.233844370842 C305.4893178830789 426.50072893092255, 308.5525928473983 424.91137882332794, 314.0481626680374 423.028171341175 M314.6077485598149 422.87655064112795 C313.2775485589355 425.0211347352721, 313.37255619696845 429.1739470248059, 313.47809755208027 433.8836053009152 M313.64688933629947 422.50825980291046 C313.80491590017397 426.68348899338304, 313.93007912105344 430.64890870620667, 314.17312294142823 433.51127182541785 M314.09034984855646 433.46733395839317 C308.65362103445705 430.6942903745198, 304.9135354266112 428.9210310198945, 302.0551505947113 427.51435730934145 M314.1346832063674 433.162848851925 C311.250723403787 432.4704772499669, 308.92765499495573 431.51531593601715, 302.3494923448563 427.854978556633" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="334" y="452" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#98a3b0" text-anchor="middle" >the answer</text>
+<path d="M513.535615837574 289.7120955348015 C511.43523221319913 275.7941893339157, 512.6541069537998 260.66679826974865, 511.95747443437574 225.24842175245286 M512.6501725614071 287.6797116816044 C512.0717100945114 264.1241998374462, 512.1881668892503 240.90360620617867, 512.8325507581234 225.45764537453653" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M512.1271914958954 225.26069836616517 L516.4717190482675 239.15754984169 L507.2764307281913 237.12062204627983" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M511.8462630200386 225.10224028348924 C513.550627646963 228.90806219283047, 514.1570964391071 232.1887907036983, 516.5023272087633 238.24406513242715 M511.8151494157314 225.62744677186012 C513.4450024617086 229.82506810256982, 515.4246924327559 232.80594179374526, 516.8861921277105 237.45756763367646 M516.6424425813752 237.84094070300748 C513.4365347124357 237.79306264632856, 510.45946049657965 237.9900024957744, 507.00756885632757 237.31277637055038 M516.9963717772587 237.9199856034357 C514.665394087938 237.5342690133185, 512.0765029345126 238.00892502138757, 506.7087621733783 237.53792523972842 M507.0489624879302 237.62119640378947 C508.4444797270679 233.50497077049428, 511.2427158986141 228.94911610172284, 511.4628635907173 225.6083875155449 M506.9752967748584 237.98356071381562 C508.3435558049127 233.27965982906105, 510.72943525740004 228.18041683669213, 511.64488196730616 225.76744383454323" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="464" y="260" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#98a3b0" text-anchor="middle" >AG-UI</text>
+<path d="M691.261342382431 224.65814232826233 C690.9974284112454 237.76992988586426, 694.1827631890774 250.27571158409117, 690.6501592159271 286.23551201820374 M691.7376458406449 226.70237376689911 C691.691084428072 240.55584805011748, 692.8150063946248 254.0619346380234, 691.980505490303 288.38052241802217" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M692.6419188976288 289.2671074390411 L688.0423040649832 276.4521498844147 L698.539048073536 277.4566161319733" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M692.821620323658 288.8146432948113 C691.5225116954753 285.6028560452307, 689.439141907445 282.06427103664487, 686.6641311166228 276.4257595774651 M691.7170006406308 288.25792388558386 C689.6218874246238 283.17723843173644, 687.9333506890358 278.5805225580172, 686.3352629671039 276.58131414742473 M685.9998919722063 275.7786568250619 C689.9052072313199 275.97270721862105, 694.3973730069316 275.6641022537231, 696.733445800338 275.542785359459 M686.9388449957193 276.2395023469212 C688.7334756114781 276.1432438587372, 691.4478798138389 276.1767428271771, 697.4378097915028 276.22694129537314 M696.8579677918016 275.57033652753836 C696.8769181374319 279.4521075763257, 695.2801896451626 280.883434706799, 692.6444483113289 288.72443615674973 M697.68847971583 276.07142130227095 C695.7587153006039 279.4219475965277, 693.9825308424774 282.3836596133788, 691.8644056165218 288.35351512551307" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="762" y="260" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#98a3b0" text-anchor="middle" >a tool call</text>
+<path d="M939.6294221401215 226.23612580299377 C901.2059477994442 246.44452034330368, 861.8407785603999 261.7696726927757, 809.7884416103363 286.26497254371645 M939.6551470994949 226.00563971996309 C908.7303154594898 242.25298728322983, 876.1763555176258 256.53093857145313, 808.1555812120438 288.4606865644455" fill="none" stroke="#8b8ff5" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M808.0513820171357 287.46134915351865 L816.0754153181531 279.1837334443285 L821.1501581935993 286.64929806856145" fill="#8b8ff5" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M808.6129750943184 287.3607778429985 C811.6034839611037 284.42302766700766, 813.8365670941434 280.4076334340751, 816.7312903930165 278.76947217714326 M808.3478196847439 288.10400227189064 C810.4194820740441 285.31187835066254, 813.4256506225627 282.21102423192895, 816.7182088436105 277.94000079762475 M817.0369460381397 278.20829256200517 C818.3094872455987 280.65640456967054, 818.3916963909146 283.0056948450495, 821.5361908342514 288.22631436180086 M816.8501003078945 278.0113184754133 C817.9697993819223 281.48104331432216, 819.415628139766 285.01453633519156, 820.7130515482277 287.79011410009866 M821.641190510284 287.6902567568206 C816.8225786220888 287.5897645994946, 811.5762727008183 288.5705933894383, 808.6193693661689 288.4386743426323 M821.0707693688979 287.67134091166486 C817.9919982599058 288.0463210607311, 814.8068597961388 287.9213748519242, 807.7684854638577 288.2718258726597" fill="none" stroke="#8b8ff5" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M854.7993141115337 435.4194701420519 C909.6614246835694 408.64727548265677, 964.7751447953005 384.1619943035359, 1067.1792520846798 337.71081995706476 M855.9358530400605 436.2722291473019 C937.5556241104103 400.1695073374866, 1017.6200629721171 361.9767069724101, 1065.8468730273335 338.2595625859164" fill="none" stroke="#34d399" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1066.701243686676 338.53399953842165 L1057.3768513073546 348.59840583014653 L1052.220026735143 336.98540266619966" fill="#34d399" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1066.8558643484116 337.4279621744156 C1064.16106148945 340.0311762415441, 1062.2329667767594 342.1200625822082, 1057.3302016749008 347.55399764704873 M1066.2062844777108 338.33802357435223 C1064.4139991985471 340.7132528559796, 1062.367407960205 342.40591753845337, 1057.112523278199 347.77011045384575 M1057.9015156575708 347.384173700705 C1056.0141285920538 344.7003594587259, 1054.3956930142115 341.4921864580483, 1052.7362656911407 338.72219998559 M1057.191815714298 348.12955812780996 C1056.0731273532606 344.8664278878027, 1054.8717668424003 341.97290000888023, 1053.1247192889532 338.51809121393364 M1053.7504930389682 338.78435462104125 C1057.7107979607088 338.81512071943627, 1060.1256772299025 337.57237350184016, 1065.1344930410385 337.21358397006986 M1053.2170098174374 338.19576810227676 C1057.763295274532 338.21636091777384, 1062.097367004719 338.2055662340223, 1066.3574767231942 338.3389053034782" fill="none" stroke="#34d399" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="962" y="404" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#34d399" text-anchor="middle" >allowed</text>
+<path d="M854.8099720954895 529.3630213737488 C898.9000613212585 529.6622056875228, 939.5140763282776 528.349916258812, 971.4004048347473 528.941778087616 M856.782378911972 528.4124598026276 C889.3653441905975 527.8813306188583, 922.048065328598 527.7233884191512, 972.1837201595306 527.7558207035065" fill="none" stroke="#f87171" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M976.055222606659 517.2504460334778 C980.7192995166778 521.4918698978424, 987.7688469028473 527.3464160633088, 997.7029734611511 537.0319432258606 M976.9844622135163 518.9755086421967 C981.1551886177062 522.9660432434082, 985.3225464439391 528.5704036331177, 995.2429354190826 537.9356145381928" fill="none" stroke="#f87171" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M994.1753439903259 519.2297570228577 C990.5665754795074 522.413532705307, 981.1364471912384 531.819491071701, 974.9504263877868 540.0321648597717 M996.2589260578155 518.419736814499 C988.2719931221009 524.4775390434265, 981.8140583610534 532.0862306404114, 975.3050030231476 537.6009303569793" fill="none" stroke="#f87171" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="986" y="568" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#f87171" text-anchor="middle" >refused,</text>
+<text x="986" y="585" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#f87171" text-anchor="middle" >naming the rule</text>
+<path d="M484.5807391151786 607.6578287854791 C483.8011029495448 619.4157871589065, 482.9964200748652 631.9538984254003, 485.0042393192649 653.6361802354455 M484.7255058415234 608.0924761764705 C484.37438361124697 620.2974729202688, 483.58798717932405 632.7147735886276, 484.86746400669216 651.955067037791" fill="none" stroke="#f0b429" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M483.2399926185608 651.2836905479431 L478.9255538723411 639.4036008522035 L488.8287142016946 639.9302884742738" fill="#f0b429" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M483.6343744421005 651.4286946344375 C481.1267800451878 646.8058904295602, 479.4869578511247 643.835654713795, 478.1661544153632 639.3324130746842 M483.9916476559639 651.9540010333061 C482.19137606972333 647.995683684648, 480.41367428490696 644.4091772217809, 478.7521009538116 639.8477705142021 M479.14565602480985 639.4201850587914 C483.25449401775626 640.245970195003, 486.2215191193866 640.648206942389, 489.651910590198 640.2674289765492 M478.6358359021419 640.2099464891736 C481.1446891767963 640.3109631267564, 482.93442862002695 640.2130282569676, 489.646916213338 640.3741715512205 M489.8271814134179 639.5610655710221 C486.70383722130293 643.6690525037284, 485.94690594470023 648.4006899363209, 483.6204750585556 652.0715515375138 M489.66037427449805 640.2036627718926 C487.7422723694384 643.0497985245672, 486.6269619887687 646.0776151649009, 483.78764886140823 651.8381890368462" fill="none" stroke="#f0b429" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="466" y="634" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#f0b429" text-anchor="end" >always</text>
+<path d="M734.1900509834289 606.9510210990906 C733.3949409341811 617.578503894806, 734.3690711832046 625.8390921592712, 736.5218167304993 653.6153979301453 M735.4145257472992 608.7723478794098 C735.683249367714 623.7266811847687, 734.8413258447647 638.9714930057526, 735.2090676784516 651.305906534195" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M736.1262467384338 652.2563109397888 L728.8844886562765 640.5445562049866 L741.6845483996926 639.7028600379945" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M735.8033355093003 652.8883694314957 C732.9840294779686 648.1411157433967, 731.8383959612097 644.1379963659712, 729.941767093891 639.7120182916642 M734.7307825398445 652.3139808344841 C733.3066197299117 647.9225848375085, 731.5611870770211 643.7528234136763, 729.3617674539031 640.5193964335442 M730.3208794382797 640.384192684257 C732.5211890184993 640.0174674833047, 736.011881241047 639.7637325434472, 740.8977046353988 639.9128800617814 M729.9810015387136 640.2739138635828 C732.5551671047716 640.2588448128057, 735.5364500251277 640.0170962358633, 740.0646532974783 640.4241425679886 M740.4825121095239 640.469097301674 C737.9871870179797 645.2478047651368, 735.6241273421705 649.0686772238463, 735.1834729909897 652.3047480630875 M740.5751329376756 640.5390930125237 C738.6715435763239 643.1938560286961, 737.9060666059473 646.2039529106606, 735.1168063282967 651.9982732081413" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M734.4738057136535 606.8756037712097 L739.7705259540139 619.2656971290588 L730.654139306301 620.6913959815978" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M735.3768719434738 607.2655834245681 C737.2422511240071 612.3176822040065, 738.3857183278676 615.1100655499689, 739.7609955956995 619.4057709291458 M734.6431294655799 607.8024330115318 C737.0373863419555 612.0511232763067, 738.8225689773151 616.4740206436944, 740.373403554207 619.6003360465049 M740.3623793428582 619.7245317522915 C736.2875304820554 620.4086151620754, 732.1478182421523 620.3161780525089, 729.1104450439215 620.1545573845086 M740.0112943072055 619.643000810411 C736.2435457462348 619.8249675084759, 732.7604350862887 620.005170613105, 729.4065726480728 619.7371761407687 M729.0202716371955 620.5651405885695 C731.2850468184646 615.8648750146943, 734.5726140089304 611.188253565721, 735.7051667737961 607.6453379106522 M729.5686188504637 619.7534722617148 C732.2940294106684 615.4436331187704, 734.1606342825339 610.4200118136272, 734.6532728219032 607.8523860907554" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1226.4556588172914 647.1067694664001 C1226.4614660787581 633.2277256965638, 1227.031848769188 618.5181155204773, 1224.5386818885804 587.113443660736 M1226.6747180461884 648.1148075580597 C1226.1123440885544 636.6520590305329, 1226.343290438652 623.3334999561309, 1226.7066195964812 587.2345417499542" fill="none" stroke="#e9edf2" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1227.074082660675 587.444113445282 L1230.5010030963479 600.7278347328186 L1220.8984103939474 599.3010677650451" fill="#e9edf2" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1225.6195672941208 587.9328545045853 C1227.3865277309958 590.3322650308326, 1227.7664523150954 593.5211854859836, 1232.176382596737 600.5716980150222 M1225.7589848542214 588.3078981184959 C1227.5939428332115 590.3299217042119, 1228.5959042548177 593.924050407063, 1231.431106477028 599.4681235411643 M1230.6359814037864 599.6455276356471 C1227.178705646877 600.0213370219184, 1224.5465355559552 599.2885099307022, 1220.7471745703872 599.9169278812652 M1231.297150944469 599.9167493526844 C1227.5916588358375 599.8881056892864, 1224.6766665121647 599.5949238951871, 1221.0581011145807 599.9358697813874 M1221.2533698198736 600.3475166490554 C1222.2968688851975 596.5196384977254, 1225.3434537856078 590.4824223810056, 1225.354784731865 588.4737918519974 M1220.9636282918395 600.0242169096946 C1222.5365324620584 596.2511592016077, 1224.0541081898384 592.1468651604293, 1226.1500907349587 587.6098671889305" fill="none" stroke="#e9edf2" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
+<text x="1242" y="634" font-family='ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' font-size="12.5" font-weight="500" fill="#98a3b0" text-anchor="start" >creates one each</text>
+</svg>
\ No newline at end of file
diff --git a/biome.json b/biome.json
new file mode 100644
index 00000000..e1c542f3
--- /dev/null
+++ b/biome.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.5.8/schema.json",
+ "files": {
+ "includes": [
+ "**",
+ "!**/dist",
+ "!.",
+ "!app/src/components/ui",
+ "!app/src/lib/generated/application-config.ts",
+ "!app/src/routeTree.gen.ts"
+ ]
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "space"
+ },
+ "linter": {
+ "enabled": true
+ },
+ "css": {
+ "parser": {
+ "tailwindDirectives": true
+ }
+ }
+}
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 00000000..6ac24393
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,10 @@
+# OpenBot docs
+
+Start with the root [README](../README.md), then use these references:
+
+- [Architecture](architecture.md): services, ports, browser governance, computers, components, plugins, knowledge, and security boundaries.
+- [Configuration](configuration.md): environment variables and tenant package YAML.
+- [Development](development.md): local setup, migrations, ports, and quality checks.
+- [Teammates](teammates.md): durable Bot profiles, channels, visibility, deletion, and external AG-UI registration.
+
+Do not include credential values, customer data, transcripts, or local-only notes in public docs.
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 00000000..c6d184bc
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,153 @@
+# Architecture
+
+OpenBot combines a React app, a Hono API server, PostgreSQL, CopilotKit Intelligence, AG-UI Bot endpoints, and governed browser computers.
+
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="../assets/architecture-dark.svg">
+ <img src="../assets/architecture-light.svg" alt="A turn goes from the app to the server, which sends it to a Bot over AG-UI. Every tool call the Bot makes returns through the gateway, which resolves the target, decides it against the configured policy, records an audit row, and only then acts, or refuses and names the rule. Allowed actions reach that Bot's own computer, one container each holding its own Chromium, logins and workspace, created by the supervisor. Every decision lands in PostgreSQL; threads and memory live in CopilotKit Intelligence.">
+</picture>
+
+Regenerate it with `bun run diagram` after changing anything it shows.
+
+## Services and ports
+
+| Component | Port | Responsibility |
+| ------------------------ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| `app` | 3010 | React/Vite interface for channels, Bot chat, live screen, settings, and admin pages. |
+| `server` | 3001 | API, CopilotKit runtime, auth, roles, tenant package, teammates, channels, policy, audit, credentials, plugins, components, and connectors. |
+| `agent-computer` | 4100 | Chromium, `/workspace`, browser profile, screenshots, snapshots, and file tools. |
+| `agent-bot` | 4200 | Proof-of-concept AG-UI Bot. |
+| `agent-langgraph` | 4201 | LangGraph AG-UI Bot. |
+| `supervisor` | 4500 host / 4300 container | Creates, stops, resets, and lists per-Bot computer containers. |
+| PostgreSQL with pgvector | 5432 | Product data, audit rows, credentials, policy, grants, channels, components, connector state, and knowledge records. |
+| CopilotKit Intelligence | external | Durable threads, memory, and realtime gateway. |
+
+`scripts/start.sh` starts PostgreSQL, `agent-computer`, `agent-bot`, `agent-langgraph`, and the supervisor through Docker Compose, then starts `server` and `app` on the host.
+
+The compose file also defines optional SPIRE services. `start.sh` does not start them.
+
+## Runtime flow
+
+1. The app opens a channel or direct Bot session.
+2. The server resolves the signed-in actor and selected teammate.
+3. CopilotKit runtime sends the turn to the configured AG-UI endpoint.
+4. The surface registers available frontend tools: browser tools, MCP tools, and components granted to that Bot.
+5. Acting browser/file/MCP calls return to the server for authorization and audit.
+6. The server streams results back to the app and Intelligence thread.
+
+## Browser action governance
+
+The computer itself does not decide policy. The server gateway is the action boundary:
+
+1. resolve the target from the server-held snapshot or request subject;
+2. evaluate the current action policy;
+3. write an audit row for the decision;
+4. call the computer only when the decision forwards;
+5. write a second audit row if a forwarded action fails.
+
+Policy rules can inspect:
+
+- `tool.name`
+- `intent`
+- `bot.id`
+- `actor.id`
+- `page.url`, `page.host`
+- `element.ref`, `element.role`, `element.name`, `element.type`
+- `key`
+- `file.path`, `file.name`, `file.extension`
+- `mcp.server`, `mcp.tool`, `mcp.effect`
+
+Rules use CEL expressions plus case-insensitive `contains()` and `matches()`.
+Deny rules are evaluated before allow rules. The policy engine fails closed: a
+missing or empty policy permits nothing, a broken deny rule denies, and a broken
+allow rule does not permit. OpenBot's shipped startup default is explicit:
+`deny: []` and `allow: ["true"]`, unless `AGENT_COMPUTER_POLICY` or a saved
+administrator policy replaces it. A malformed configured policy stops server
+startup.
+
+## Computers
+
+`agent-computer` requires `COMPUTER_TOKEN` and permits only `/health` without it. Docker Compose binds it to `127.0.0.1:4100`.
+
+With `COMPUTER_SUPERVISOR_URL`, each Bot gets its own computer container, workspace volume, and browser profile. Without it, all Bots share `AGENT_COMPUTER_URL`.
+
+The supervisor exposes only ensure, stop, reset, and list operations. It holds the Docker socket, so do not expose it outside the deployment network. Set `COMPUTER_RUNTIME=runsc` to run computers under gVisor on hosts that support it.
+
+## Human control and secrets
+
+Handovers are audited as control events:
+
+- `computer.help_requested`
+- `computer.control_taken`
+- `computer.control_released`
+
+While a person controls the browser, Bot actions are refused rather than queued.
+
+Secret entry is separate from chat content. The audit trail records that a secret was requested or supplied and the character count, not the secret value.
+
+## Teammates and channels
+
+A teammate is a durable Bot profile:
+
+- `agents` stores runtime identity and endpoint/key reference.
+- `agent_profiles` stores name, title, role, owner, visibility, and deletion state.
+- `agent_preferences` stores per-user roster state.
+
+A channel is a conversation with one teammate and a CopilotKit Intelligence thread mapping. Starting a new channel creates a new thread.
+
+See [teammates.md](teammates.md).
+
+## Components
+
+Components are frontend tools a Bot can call instead of answering only in prose.
+
+Sources:
+
+- compiled React components in `app/src/components/gallery/`;
+- sandboxed components authored and published from `/admin/playground`.
+
+Governance:
+
+- compiled components are published when first seen by the app catalogue sync;
+- sandboxed components are saved as drafts and become usable only after publish;
+- every call asks the server whether the component exists, is published, and is not withheld from the Bot;
+- component data functions require a separate per-component grant.
+
+The shipped component data functions read the audit trail: `botActivity` and `recentRefusals`.
+
+## MCP and skills
+
+MCP servers and skills share the plugin grant table, but they have different ownership rules.
+
+- MCP tools are admin-governed because they can reach external systems with stored credentials.
+- Skills are reusable instructions. A person can create personal skills and attach them only to Bots they own. Administrators create deployment skills.
+
+The curated MCP catalogue contains Atlassian, Box, Slack, Salesforce, and ServiceNow. Custom MCP servers must pass URL checks; unknown tools and custom-server tools are treated as writes unless positively classified as reads.
+
+Every MCP call checks the grant first, then evaluates the same action policy engine with MCP context, then audits the result.
+
+## Tenant package and knowledge
+
+`TENANT_PACKAGE_DIR` points at the tenant package. The default is `../examples/fintech`.
+
+Required package files:
+
+- `brand.yaml`
+- `agents.yaml`
+- `channels.yaml`
+- `model.yaml`
+- `knowledge.yaml`
+
+The server validates the package at startup. Channel agent IDs must match declared agents. Knowledge sources currently support Google Drive and Microsoft OneDrive declarations.
+
+Connector credentials are stored through the credential vault and referenced by id, not stored inline in YAML.
+
+## Security boundaries
+
+- Server routes enforce auth and roles; admin pages are backed by server-side administrator checks.
+- `OPENBOT_DEV_NO_AUTH=true` is local-only and is refused with `NODE_ENV=production`.
+- `KEY_ENCRYPTION_KEY` must be a base64-encoded 32-byte value. The example key is refused with `NODE_ENV=production`.
+- Credential plaintext is encrypted at rest, never returned by APIs, and redacted from audit events.
+- Browser navigation allows `http` and `https`; cloud metadata addresses are refused under every configuration.
+- `AGENT_COMPUTER_ALLOW_PRIVATE_HOSTS=true` is for local development only.
+- Computer tokens and supervisor tokens must be long random values outside local development.
diff --git a/docs/development.md b/docs/development.md
new file mode 100644
index 00000000..91faa309
--- /dev/null
+++ b/docs/development.md
@@ -0,0 +1,97 @@
+# Development
+
+## Setup
+
+Install Docker, [Bun](https://bun.sh) 1.3+, `lsof`, `python3`, and `curl`.
+
+```sh
+cp .env.example .env
+bun install
+```
+
+Provision CopilotKit Intelligence after `.env` exists:
+
+```sh
+npx --yes copilotkit@latest login
+npx --yes copilotkit@latest project select
+npx --yes copilotkit@latest license --write
+```
+
+Put the `cpk-...` runtime key from `project select` in `.env` as
+`INTELLIGENCE_API_KEY`. `license --write` writes `COPILOTKIT_LICENSE_TOKEN`.
+Then add `OPENAI_API_KEY`.
+
+Start the stack:
+
+```sh
+bash scripts/start.sh
+```
+
+## Running services
+
+Use `bash scripts/start.sh` for the full local stack. It starts Docker services, applies migrations, starts the API server and app, and verifies health routes.
+
+Use `bun run dev` only when you want the app and API server without starting the Docker Bots and computers.
+
+| Service | Port |
+| ----------------- | -------------------------- |
+| `app` | 3010 |
+| `server` | 3001 |
+| `agent-computer` | 4100 |
+| `agent-bot` | 4200 |
+| `agent-langgraph` | 4201 |
+| `supervisor` | 4500 host / 4300 container |
+| PostgreSQL | 5432 |
+
+`start.sh` leaves existing matching services alone and reports when a port is held by another process.
+
+## Migrations
+
+After changing the Drizzle schema:
+
+```sh
+bun run --filter server db:generate
+bun run --filter server db:migrate
+```
+
+Review generated migration files before sharing them. `start.sh` applies existing migrations when it starts the stack.
+
+## Quality checks
+
+Run these before opening a pull request:
+
+```sh
+bun run format:check
+bun run lint
+bun run typecheck
+bun run test
+bun run build
+```
+
+Integration tests expect a PostgreSQL database with pgvector. Use `start.sh` or point `DATABASE_URL` at a compatible database.
+
+They write to whichever database `DATABASE_URL` names and leave their rows behind, so running
+them against a deployment you are using puts test Bots in its audit trail and its activity
+reports. Point `DATABASE_URL` at a database of their own to keep the two apart.
+
+CI uses `bun run test:ci` to verify the expected test count in addition to normal tests.
+
+`bun run test:smoke` is separate and needs a deployment that is up:
+
+```sh
+bash scripts/start.sh
+bun run test:smoke
+```
+
+It drives one journey over HTTP against the running stack, so it covers the joins the rest of the
+suite cannot reach: server to supervisor to computer, the gateway deciding before the browser acts,
+and the audit row landing. Point it elsewhere with `OPENBOT_API_URL`. Without a deployment it is
+skipped by `bun run test` and says what to start when asked for by name.
+
+## Contribution checklist
+
+- Keep changes focused.
+- Keep credentials, service-account JSON, customer data, and transcripts out of source control.
+- Put sensitive behavior on the server, not only in the browser.
+- Update [configuration](configuration.md), [architecture](architecture.md), or the root [README](../README.md) when behavior changes.
+- Run the quality checks above and include the results in the pull request.
diff --git a/examples/fintech/agents.yaml b/examples/fintech/agents.yaml
new file mode 100644
index 00000000..81161564
--- /dev/null
+++ b/examples/fintech/agents.yaml
@@ -0,0 +1,27 @@
+# An example tenant package. Every Bot here is reachable the moment the deployment starts, so the
+# surface never registers an endpoint that is unavailable by default.
+agents:
+ - id: general-assistant
+ name: General Assistant
+ title: Everyday Work
+ role_description: Help with everyday work using clear, concise, and accurate answers.
+ avatar_seed: general-assistant
+ type: built-in
+ system_prompt: You are a helpful general assistant. Give clear, concise, and accurate answers.
+ - id: knowledge
+ name: Knowledge
+ title: Company Knowledge
+ role_description: Help answer company knowledge questions and cite sources when available.
+ avatar_seed: knowledge
+ type: built-in
+ system_prompt: Answer from authorized company knowledge and cite every source.
+ # The Bot that ships in the box (agent-bot), addressed exactly the way a customer's own Bot would
+ # be: an AG-UI endpoint in the registry. Names in dollar-brace form are read from the environment,
+ # so the address belongs to the deployment. Replace it with your own service and nothing changes.
+ - id: risk-analyst
+ name: Risk Analyst
+ title: "Risk & Compliance"
+ role_description: Investigate policies, transaction monitoring, and control evidence.
+ avatar_seed: risk-analyst
+ type: remote-ag-ui
+ endpoint: ${MANAGED_AGENT_AG_UI_URL:-http://localhost:4200/ag-ui}
diff --git a/examples/fintech/brand.yaml b/examples/fintech/brand.yaml
new file mode 100644
index 00000000..89237ba1
--- /dev/null
+++ b/examples/fintech/brand.yaml
@@ -0,0 +1,3 @@
+tenant:
+ id: openbot
+ product_name: OpenBot
diff --git a/examples/fintech/knowledge.yaml b/examples/fintech/knowledge.yaml
new file mode 100644
index 00000000..fe6fef3e
--- /dev/null
+++ b/examples/fintech/knowledge.yaml
@@ -0,0 +1,5 @@
+sources:
+ - type: google-drive
+ roots: [Policies, Compliance]
+ - type: microsoft-onedrive
+ roots: [Risk, Operations]
diff --git a/examples/fintech/model.yaml b/examples/fintech/model.yaml
new file mode 100644
index 00000000..5bdce6a2
--- /dev/null
+++ b/examples/fintech/model.yaml
@@ -0,0 +1,4 @@
+model:
+ provider: openai
+ credential_secret_ref: openai-api-key
+ default_model: gpt-4.1
diff --git a/examples/langgraph-bot/bun.lock b/examples/langgraph-bot/bun.lock
new file mode 100644
index 00000000..567c0ad8
--- /dev/null
+++ b/examples/langgraph-bot/bun.lock
@@ -0,0 +1,99 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@openbot/example-langgraph-bot",
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "@langchain/core": "^0.3.66",
+ "@langchain/langgraph": "^0.4.9",
+ "@langchain/openai": "^0.6.3",
+ },
+ },
+ },
+ "packages": {
+ "@ag-ui/core": ["@ag-ui/[email protected]", "", { "dependencies": { "zod": "^3.22.4" } }, "sha512-gho1OWjNE6E3Rl7ZEZ1wr2CEpUHjLFU0FqzCZZk439TicLu+BfLCMkMokB07bMGlRmbJ60hM6LW60iOVauCx+Q=="],
+
+ "@ag-ui/encoder": ["@ag-ui/[email protected]", "", { "dependencies": { "@ag-ui/core": "0.0.57", "@ag-ui/proto": "0.0.57" } }, "sha512-ifD9NctR4xyPDR58xF9GK1bj/S8oECFkTeDfuYD8tXdbcOstIJ2TOqU2zhiCKnw7Vw+zR9Qv3TbsM9E7Gi9X3Q=="],
+
+ "@ag-ui/proto": ["@ag-ui/[email protected]", "", { "dependencies": { "@ag-ui/core": "0.0.57", "@bufbuild/protobuf": "^2.2.5", "@protobuf-ts/protoc": "^2.11.1" } }, "sha512-pPENOZt0P6ibH8sCTgq05wLYXi5t3P9B5r/1bWYehXjUxtyOdnukSlWM++SsCIwUXsQdm/b3aBgGjEeTF7RenA=="],
+
+ "@bufbuild/protobuf": ["@bufbuild/[email protected]", "", {}, "sha512-C3UGsiCwSprE2NKIIFA3hCDlpXTMCAXRZuEVp88L1GY36Y41+rYL5fryE+nOFhp4p4JPQvdV8PQ4DWgHgeTE+w=="],
+
+ "@cfworker/json-schema": ["@cfworker/[email protected]", "", {}, "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og=="],
+
+ "@langchain/core": ["@langchain/[email protected]", "", { "dependencies": { "@cfworker/json-schema": "^4.0.2", "ansi-styles": "^5.0.0", "camelcase": "6", "decamelize": "1.2.0", "js-tiktoken": "^1.0.12", "langsmith": "^0.3.67", "mustache": "^4.2.0", "p-queue": "^6.6.2", "p-retry": "4", "uuid": "^10.0.0", "zod": "^3.25.32", "zod-to-json-schema": "^3.22.3" } }, "sha512-vcJDV2vk1AlCwSh3aBm/urQ1ZrlXFFBocv11bz/NBUfLWD5/UDNMzwPdaAd2dKvNmTWa9FM2lirLU3+JCf4cRA=="],
+
+ "@langchain/langgraph": ["@langchain/[email protected]", "", { "dependencies": { "@langchain/langgraph-checkpoint": "^0.1.1", "@langchain/langgraph-sdk": "~0.1.0", "uuid": "^10.0.0", "zod": "^3.25.32" }, "peerDependencies": { "@langchain/core": ">=0.3.58 < 0.4.0", "zod-to-json-schema": "^3.x" }, "optionalPeers": ["zod-to-json-schema"] }, "sha512-+rcdTGi4Ium4X/VtIX3Zw4RhxEkYWpwUyz806V6rffjHOAMamg6/WZDxpJbrP33RV/wJG1GH12Z29oX3Pqq3Aw=="],
+
+ "@langchain/langgraph-checkpoint": ["@langchain/[email protected]", "", { "dependencies": { "uuid": "^10.0.0" }, "peerDependencies": { "@langchain/core": ">=0.2.31 <0.4.0 || ^1.0.0-alpha" } }, "sha512-h2bP0RUikQZu0Um1ZUPErQLXyhzroJqKRbRcxYRTAh49oNlsfeq4A3K4YEDRbGGuyPZI/Jiqwhks1wZwY73AZw=="],
+
+ "@langchain/langgraph-sdk": ["@langchain/[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.15", "p-queue": "^6.6.2", "p-retry": "4", "uuid": "^9.0.0" }, "peerDependencies": { "@langchain/core": ">=0.2.31 <0.4.0 || ^1.0.0-alpha", "react": "^18 || ^19", "react-dom": "^18 || ^19" }, "optionalPeers": ["@langchain/core", "react", "react-dom"] }, "sha512-9srSCb2bSvcvehMgjA2sMMwX0o1VUgPN6ghwm5Fwc9JGAKsQa6n1S4eCwy1h4abuYxwajH5n3spBw+4I2WYbgw=="],
+
+ "@langchain/openai": ["@langchain/[email protected]", "", { "dependencies": { "js-tiktoken": "^1.0.12", "openai": "5.12.2", "zod": "^3.25.32" }, "peerDependencies": { "@langchain/core": ">=0.3.68 <0.4.0" } }, "sha512-JVSzD+FL5v/2UQxKd+ikB1h4PQOtn0VlK8nqW2kPp0fshItCv4utrjBKXC/rubBnSXoRTyonBINe8QRZ6OojVQ=="],
+
+ "@protobuf-ts/protoc": ["@protobuf-ts/[email protected]", "", { "bin": { "protoc": "protoc.js" } }, "sha512-mUZJaV0daGO6HUX90o/atzQ6A7bbN2RSuHtdwo8SSF2Qoe3zHwa4IHyCN1evftTeHfLmdz+45qo47sL+5P8nyg=="],
+
+ "@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
+
+ "@types/retry": ["@types/[email protected]", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="],
+
+ "@types/uuid": ["@types/[email protected]", "", {}, "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="],
+
+ "ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
+
+ "camelcase": ["[email protected]", "", {}, "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA=="],
+
+ "chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
+
+ "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
+
+ "color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
+
+ "console-table-printer": ["[email protected]", "", { "dependencies": { "simple-wcswidth": "^1.1.2" } }, "sha512-Sc9FRJ4O9xKGNrvulNdPfK5SyBcZ6lcaRnDE4AQ/uw6IDtjHhsqyzzqcnMikjyGaiOOF2tNOKoBhbVjRvFy9Lw=="],
+
+ "decamelize": ["[email protected]", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
+
+ "eventemitter3": ["[email protected]", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="],
+
+ "has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
+
+ "js-tiktoken": ["[email protected]", "", { "dependencies": { "base64-js": "^1.5.1" } }, "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g=="],
+
+ "langsmith": ["[email protected]", "", { "dependencies": { "@types/uuid": "^10.0.0", "chalk": "^4.1.2", "console-table-printer": "^2.12.1", "p-queue": "^6.6.2", "semver": "^7.6.3", "uuid": "^10.0.0" }, "peerDependencies": { "@opentelemetry/api": "*", "@opentelemetry/exporter-trace-otlp-proto": "*", "@opentelemetry/sdk-trace-base": "*", "openai": "*" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/exporter-trace-otlp-proto", "@opentelemetry/sdk-trace-base", "openai"] }, "sha512-XXR1+9INH8YX96FKWc5tie0QixWz6tOqAsAKfcJyPkE0xPep+NDz0IQLR32q4bn10QK3LqD2HN6T3n6z1YLW7Q=="],
+
+ "mustache": ["[email protected]", "", { "bin": { "mustache": "bin/mustache" } }, "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ=="],
+
+ "openai": ["[email protected]", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-xqzHHQch5Tws5PcKR2xsZGX9xtch+JQFz5zb14dGqlshmmDAFBFEWmeIpf7wVqWV+w7Emj7jRgkNJakyKE0tYQ=="],
+
+ "p-finally": ["[email protected]", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="],
+
+ "p-queue": ["[email protected]", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="],
+
+ "p-retry": ["[email protected]", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="],
+
+ "p-timeout": ["[email protected]", "", { "dependencies": { "p-finally": "^1.0.0" } }, "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg=="],
+
+ "retry": ["[email protected]", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="],
+
+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
+ "simple-wcswidth": ["[email protected]", "", {}, "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw=="],
+
+ "supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+
+ "uuid": ["[email protected]", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+
+ "zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
+
+ "@langchain/langgraph-sdk/uuid": ["[email protected]", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
+
+ "chalk/ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
+ }
+}
diff --git a/examples/langgraph-bot/package.json b/examples/langgraph-bot/package.json
new file mode 100644
index 00000000..03e94d9d
--- /dev/null
+++ b/examples/langgraph-bot/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "@openbot/example-langgraph-bot",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "bun --env-file=../../.env --watch src/index.ts",
+ "start": "bun --env-file=../../.env src/index.ts"
+ },
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "@langchain/core": "^0.3.66",
+ "@langchain/langgraph": "^0.4.9",
+ "@langchain/openai": "^0.6.3"
+ }
+}
diff --git a/examples/langgraph-bot/src/index.ts b/examples/langgraph-bot/src/index.ts
new file mode 100644
index 00000000..6f3a1b5b
--- /dev/null
+++ b/examples/langgraph-bot/src/index.ts
@@ -0,0 +1,308 @@
+import type { BaseEvent, RunAgentInput } from "@ag-ui/core";
+import { EventEncoder } from "@ag-ui/encoder";
+import type { AIMessage, BaseMessage } from "@langchain/core/messages";
+import {
+ AIMessage as AIMessageClass,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+} from "@langchain/core/messages";
+import { Annotation, END, START, StateGraph } from "@langchain/langgraph";
+import { ChatOpenAI } from "@langchain/openai";
+import { serve } from "bun";
+
+/**
+ * A Bot written in LangGraph.
+ *
+ * This is a real LangGraph `StateGraph` with its own model client and tool loop. OpenBot knows it
+ * only as an AG-UI endpoint URL.
+ *
+ * It is an AG-UI HTTP endpoint. One POST carrying a `RunAgentInput`, and
+ * a stream of AG-UI events back. `@ag-ui/langgraph` is a client: it lets a CopilotKit
+ * runtime talk to LangGraph Platform. What a Bot has to be here is the other end, a server, so this
+ * emits the protocol directly with `@ag-ui/encoder`, the same way `agent-bot` does.
+ *
+ * Tools arrive in `input.tools` from the surface on every run, so this file never names
+ * `computer_navigate` and still drives a governed browser.
+ */
+
+const PORT = Number.parseInt(process.env.PORT ?? "4300", 10);
+const MODEL = process.env.BOT_MODEL ?? "gpt-5.5";
+
+/**
+ * The graph's state.
+ *
+ * Deliberately small. A bigger graph would prove less: the point is that a LangGraph agent works,
+ * not that LangGraph can hold state.
+ */
+const BotState = Annotation.Root({
+ messages: Annotation<BaseMessage[]>({
+ reducer: (left, right) => left.concat(right),
+ default: () => [],
+ }),
+});
+
+/** Turn the AG-UI conversation into LangChain messages. */
+function toLangChainMessages(input: RunAgentInput): BaseMessage[] {
+ const messages: BaseMessage[] = [
+ new SystemMessage(
+ "You are a Bot running on LangGraph inside OpenBot. You have a real web browser available " +
+ "through the tools you are given.\n\n" +
+ // Page contents must come from a fresh tool result, not from model memory.
+ "NEVER state what a page contains unless you have just read it with a tool in this " +
+ "conversation. You cannot know a page's contents from memory, and a plausible guess is a " +
+ "wrong answer. If you have not read it, call the tool first. Report exactly what the tool " +
+ "returned.",
+ ),
+ ];
+ // Replay the whole conversation, including tool results. Tool calls and results must come back as
+ // matched pairs so the model has evidence its action worked.
+ for (const message of input.messages ?? []) {
+ const content = typeof message.content === "string" ? message.content : "";
+ const role = message.role;
+
+ if (role === "user" && content) {
+ messages.push(new HumanMessage(content));
+ continue;
+ }
+
+ if (role === "assistant") {
+ const toolCalls = (
+ message as {
+ toolCalls?: {
+ id: string;
+ function: { name: string; arguments: string };
+ }[];
+ }
+ ).toolCalls;
+ if (toolCalls?.length) {
+ messages.push(
+ new AIMessageClass({
+ content: content ?? "",
+ tool_calls: toolCalls.map((call) => ({
+ id: call.id,
+ name: call.function.name,
+ args: safeArgs(call.function.arguments),
+ })),
+ }),
+ );
+ } else if (content) {
+ messages.push(new AIMessageClass(content));
+ }
+ continue;
+ }
+
+ if (role === "tool") {
+ const toolCallId = (message as { toolCallId?: string }).toolCallId;
+ if (toolCallId) {
+ messages.push(new ToolMessage({ content, tool_call_id: toolCallId }));
+ }
+ }
+ }
+ return messages;
+}
+
+/** Tool arguments arrive as a JSON string, and a malformed one must not kill the run. */
+function safeArgs(raw: string): Record<string, unknown> {
+ try {
+ const parsed = JSON.parse(raw || "{}");
+ return typeof parsed === "object" && parsed !== null
+ ? (parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+}
+
+/** The tools the surface granted this run, in the shape LangChain binds. */
+function toLangChainTools(input: RunAgentInput) {
+ return (input.tools ?? []).map((tool) => ({
+ type: "function" as const,
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.parameters as Record<string, unknown>,
+ },
+ }));
+}
+
+function buildGraph(input: RunAgentInput) {
+ // Stream tokens because a person is watching. With this off the model is asked for the whole answer,
+ // the graph returns once it is finished, and the surface receives a single TEXT_MESSAGE_CONTENT
+ // carrying all of it, so a six-hundred-word reply is a blank conversation for eight seconds and
+ // then a wall of text. The tokens exist the whole time; nothing was passing them on.
+ const model = new ChatOpenAI({ model: MODEL, streaming: true });
+ const tools = toLangChainTools(input);
+ const bound = tools.length > 0 ? model.bindTools(tools) : model;
+
+ return new StateGraph(BotState)
+ .addNode("think", async (state) => {
+ const reply = await bound.invoke(state.messages);
+ return { messages: [reply] };
+ })
+ .addEdge(START, "think")
+ .addEdge("think", END)
+ .compile();
+}
+
+async function runAgent(input: RunAgentInput): Promise<Response> {
+ const encoder = new EventEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const utf8 = new TextEncoder();
+ const send = (event: BaseEvent) =>
+ controller.enqueue(utf8.encode(encoder.encodeSSE(event)));
+
+ send({
+ type: "RUN_STARTED",
+ threadId: input.threadId,
+ runId: input.runId,
+ } as BaseEvent);
+
+ console.info(
+ `run ${input.runId}: ${(input.tools ?? []).length} tools granted: ${(input.tools ?? []).map((t) => t.name).join(", ") || "(none)"}`,
+ );
+
+ // A deliberate stall, for testing only. Set SLOW_MS to hold the stream open long enough to kill
+ // this process mid-run and prove the server survives a customer's agent dying under it.
+ const slowMs = Number.parseInt(process.env.SLOW_MS ?? "0", 10);
+ if (slowMs > 0)
+ await new Promise((resolve) => setTimeout(resolve, slowMs));
+
+ try {
+ const graph = buildGraph(input);
+ const messageId = `msg_${input.runId}`;
+
+ /*
+ * Tokens are forwarded as they arrive.
+ *
+ * `graph.invoke` waits for the graph to finish, so the only thing it can report is the
+ * finished answer. `streamEvents` reports what happens inside it, and `on_chat_model_stream`
+ * is one chunk of the model's output, which is what AG-UI's TEXT_MESSAGE_CONTENT is for.
+ *
+ * `TEXT_MESSAGE_START` is sent on the first chunk rather than up front: a run that produces
+ * only a tool call has no message at all, and opening one for it leaves an empty bubble above
+ * the work.
+ */
+ let started = false;
+ let last: AIMessage | undefined;
+
+ for await (const event of graph.streamEvents(
+ { messages: toLangChainMessages(input) },
+ { version: "v2" },
+ )) {
+ if (event.event === "on_chat_model_stream") {
+ const chunk = event.data?.chunk as AIMessage | undefined;
+ const delta =
+ typeof chunk?.content === "string"
+ ? chunk.content
+ : Array.isArray(chunk?.content)
+ ? chunk.content
+ .map((part) =>
+ typeof part === "string"
+ ? part
+ : ((part as { text?: string }).text ?? ""),
+ )
+ .join("")
+ : "";
+ if (!delta) continue;
+ if (!started) {
+ started = true;
+ send({
+ type: "TEXT_MESSAGE_START",
+ messageId,
+ role: "assistant",
+ } as BaseEvent);
+ }
+ send({
+ type: "TEXT_MESSAGE_CONTENT",
+ messageId,
+ delta,
+ } as BaseEvent);
+ }
+
+ // The finished message, kept for its tool calls. Streaming the text does not change where
+ // the tool loop runs, see below.
+ if (event.event === "on_chat_model_end") {
+ last = event.data?.output as AIMessage | undefined;
+ }
+ }
+
+ if (started) send({ type: "TEXT_MESSAGE_END", messageId } as BaseEvent);
+
+ // The tool loop runs on the client, exactly as it does for the Bot in the box: the call is
+ // emitted, this run ends, the surface executes it through the governed gateway and starts a
+ // new run with the result. That is why this file can drive a browser it has no access to.
+ for (const call of last?.tool_calls ?? []) {
+ const toolCallId = call.id ?? `call_${crypto.randomUUID()}`;
+ send({
+ type: "TOOL_CALL_START",
+ toolCallId,
+ toolCallName: call.name,
+ parentMessageId: messageId,
+ } as BaseEvent);
+ send({
+ type: "TOOL_CALL_ARGS",
+ toolCallId,
+ delta: JSON.stringify(call.args ?? {}),
+ } as BaseEvent);
+ send({ type: "TOOL_CALL_END", toolCallId } as BaseEvent);
+ }
+
+ send({
+ type: "RUN_FINISHED",
+ threadId: input.threadId,
+ runId: input.runId,
+ } as BaseEvent);
+ } catch (error) {
+ // Reported as a protocol event rather than a dropped connection, so the surface can say what
+ // went wrong instead of showing a Bot that stopped answering.
+ send({
+ type: "RUN_ERROR",
+ message: error instanceof Error ? error.message : "The agent failed.",
+ } as BaseEvent);
+ } finally {
+ controller.close();
+ }
+ },
+ });
+
+ return new Response(stream, {
+ headers: {
+ "content-type": encoder.getContentType(),
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ },
+ });
+}
+
+serve({
+ port: PORT,
+ idleTimeout: 120,
+ async fetch(request) {
+ const url = new URL(request.url);
+ if (url.pathname === "/health") {
+ return Response.json({ status: "ok", framework: "langgraph" });
+ }
+ // A key, when REQUIRE_KEY is set. Customer agents commonly sit behind an API key.
+ const requiredKey = process.env.REQUIRE_KEY;
+ if (
+ requiredKey &&
+ url.pathname === "/ag-ui" &&
+ request.headers.get("authorization") !== requiredKey
+ ) {
+ console.info("refused a run: wrong or missing key");
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ if (url.pathname === "/ag-ui" && request.method === "POST") {
+ const input = (await request.json()) as RunAgentInput;
+ return runAgent(input);
+ }
+ return new Response("Not found", { status: 404 });
+ },
+});
+
+console.info(
+ `langgraph-bot listening on http://localhost:${PORT}/ag-ui (model ${MODEL})`,
+);
diff --git a/examples/mastra-bot/bun.lock b/examples/mastra-bot/bun.lock
new file mode 100644
index 00000000..529511a9
--- /dev/null
+++ b/examples/mastra-bot/bun.lock
@@ -0,0 +1,582 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@openbot/example-mastra-bot",
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "@ai-sdk/openai": "^1.3.24",
+ "@mastra/core": "^0.10.5",
+ },
+ },
+ },
+ "packages": {
+ "@ag-ui/core": ["@ag-ui/[email protected]", "", { "dependencies": { "zod": "^3.22.4" } }, "sha512-gho1OWjNE6E3Rl7ZEZ1wr2CEpUHjLFU0FqzCZZk439TicLu+BfLCMkMokB07bMGlRmbJ60hM6LW60iOVauCx+Q=="],
+
+ "@ag-ui/encoder": ["@ag-ui/[email protected]", "", { "dependencies": { "@ag-ui/core": "0.0.57", "@ag-ui/proto": "0.0.57" } }, "sha512-ifD9NctR4xyPDR58xF9GK1bj/S8oECFkTeDfuYD8tXdbcOstIJ2TOqU2zhiCKnw7Vw+zR9Qv3TbsM9E7Gi9X3Q=="],
+
+ "@ag-ui/proto": ["@ag-ui/[email protected]", "", { "dependencies": { "@ag-ui/core": "0.0.57", "@bufbuild/protobuf": "^2.2.5", "@protobuf-ts/protoc": "^2.11.1" } }, "sha512-pPENOZt0P6ibH8sCTgq05wLYXi5t3P9B5r/1bWYehXjUxtyOdnukSlWM++SsCIwUXsQdm/b3aBgGjEeTF7RenA=="],
+
+ "@ai-sdk/openai": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8" }, "peerDependencies": { "zod": "^3.0.0" } }, "sha512-GYXnGJTHRTZc4gJMSmFRgEQudjqd4PUN0ZjQhPwOAYH1yOAvQoG/Ikqs+HyISRbLPCrhbZnPKCNHuRU4OfpW0Q=="],
+
+ "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="],
+
+ "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="],
+
+ "@ai-sdk/react": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider-utils": "2.2.8", "@ai-sdk/ui-utils": "1.2.11", "swr": "^2.2.5", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "zod": "^3.23.8" }, "optionalPeers": ["zod"] }, "sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g=="],
+
+ "@ai-sdk/ui-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w=="],
+
+ "@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ=="],
+
+ "@bufbuild/protobuf": ["@bufbuild/[email protected]", "", {}, "sha512-C3UGsiCwSprE2NKIIFA3hCDlpXTMCAXRZuEVp88L1GY36Y41+rYL5fryE+nOFhp4p4JPQvdV8PQ4DWgHgeTE+w=="],
+
+ "@grpc/grpc-js": ["@grpc/[email protected]", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ=="],
+
+ "@grpc/proto-loader": ["@grpc/[email protected]", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
+
+ "@js-sdsl/ordered-map": ["@js-sdsl/[email protected]", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
+
+ "@jsdevtools/ono": ["@jsdevtools/[email protected]", "", {}, "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg=="],
+
+ "@mastra/core": ["@mastra/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "^1.1.3", "@ai-sdk/provider-utils": "^2.2.8", "@ai-sdk/ui-utils": "^1.2.11", "@mastra/schema-compat": "0.10.5", "@opentelemetry/api": "^1.9.0", "@opentelemetry/auto-instrumentations-node": "^0.59.0", "@opentelemetry/core": "^2.0.1", "@opentelemetry/exporter-trace-otlp-grpc": "^0.201.1", "@opentelemetry/exporter-trace-otlp-http": "^0.201.1", "@opentelemetry/otlp-exporter-base": "^0.201.1", "@opentelemetry/otlp-transformer": "^0.201.1", "@opentelemetry/resources": "^2.0.1", "@opentelemetry/sdk-metrics": "^2.0.1", "@opentelemetry/sdk-node": "^0.201.1", "@opentelemetry/sdk-trace-base": "^2.0.1", "@opentelemetry/sdk-trace-node": "^2.0.1", "@opentelemetry/semantic-conventions": "^1.34.0", "@sindresorhus/slugify": "^2.2.1", "ai": "^4.3.16", "date-fns": "^3.6.0", "dotenv": "^16.6.1", "hono": "^4.8.4", "hono-openapi": "^0.4.8", "json-schema": "^0.4.0", "json-schema-to-zod": "^2.6.1", "pino": "^9.7.0", "pino-pretty": "^13.0.0", "radash": "^12.1.0", "sift": "^17.1.3", "xstate": "^5.19.4", "zod-to-json-schema": "^3.24.5" }, "peerDependencies": { "zod": "^3.0.0" } }, "sha512-TmNe71FyyxdjIy8J5gD/a33zsfaBiaiYYica33HPat5z8sBnn5DyTyswOaqgVJUCRcnEb98snOBphAVtN/y9VA=="],
+
+ "@mastra/schema-compat": ["@mastra/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0", "zod-from-json-schema": "^0.0.5", "zod-to-json-schema": "^3.24.5" }, "peerDependencies": { "ai": "^4.0.0", "zod": "^3.0.0" } }, "sha512-Qhz8W4Hz7b9tNoVW306NMzotVy11bya1OjiTN+pthj00HZoaH7nmK8SWBiX4drS+PyhIqA16X5AenELe2QgZag=="],
+
+ "@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="],
+
+ "@opentelemetry/api-logs": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-IxcFDP1IGMDemVFG2by/AMK+/o6EuBQ8idUq3xZ6MxgQGeumYZuX5OwR0h9HuvcUc/JPjQGfU5OHKIKYDJcXeA=="],
+
+ "@opentelemetry/auto-instrumentations-node": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/instrumentation-amqplib": "^0.48.0", "@opentelemetry/instrumentation-aws-lambda": "^0.52.0", "@opentelemetry/instrumentation-aws-sdk": "^0.53.0", "@opentelemetry/instrumentation-bunyan": "^0.47.0", "@opentelemetry/instrumentation-cassandra-driver": "^0.47.0", "@opentelemetry/instrumentation-connect": "^0.45.0", "@opentelemetry/instrumentation-cucumber": "^0.16.0", "@opentelemetry/instrumentation-dataloader": "^0.18.0", "@opentelemetry/instrumentation-dns": "^0.45.0", "@opentelemetry/instrumentation-express": "^0.50.0", "@opentelemetry/instrumentation-fastify": "^0.46.0", "@opentelemetry/instrumentation-fs": "^0.21.0", "@opentelemetry/instrumentation-generic-pool": "^0.45.0", "@opentelemetry/instrumentation-graphql": "^0.49.0", "@opentelemetry/instrumentation-grpc": "^0.201.0", "@opentelemetry/instrumentation-hapi": "^0.47.0", "@opentelemetry/instrumentation-http": "^0.201.0", "@opentelemetry/instrumentation-ioredis": "^0.49.0", "@opentelemetry/instrumentation-kafkajs": "^0.10.0", "@opentelemetry/instrumentation-knex": "^0.46.0", "@opentelemetry/instrumentation-koa": "^0.49.0", "@opentelemetry/instrumentation-lru-memoizer": "^0.46.0", "@opentelemetry/instrumentation-memcached": "^0.45.0", "@opentelemetry/instrumentation-mongodb": "^0.54.0", "@opentelemetry/instrumentation-mongoose": "^0.48.0", "@opentelemetry/instrumentation-mysql": "^0.47.0", "@opentelemetry/instrumentation-mysql2": "^0.47.0", "@opentelemetry/instrumentation-nestjs-core": "^0.47.0", "@opentelemetry/instrumentation-net": "^0.45.0", "@opentelemetry/instrumentation-oracledb": "^0.27.0", "@opentelemetry/instrumentation-pg": "^0.53.0", "@opentelemetry/instrumentation-pino": "^0.48.0", "@opentelemetry/instrumentation-redis": "^0.48.0", "@opentelemetry/instrumentation-redis-4": "^0.48.0", "@opentelemetry/instrumentation-restify": "^0.47.0", "@opentelemetry/instrumentation-router": "^0.46.0", "@opentelemetry/instrumentation-runtime-node": "^0.15.0", "@opentelemetry/instrumentation-socket.io": "^0.48.0", "@opentelemetry/instrumentation-tedious": "^0.20.0", "@opentelemetry/instrumentation-undici": "^0.12.0", "@opentelemetry/instrumentation-winston": "^0.46.0", "@opentelemetry/resource-detector-alibaba-cloud": "^0.31.1", "@opentelemetry/resource-detector-aws": "^2.1.0", "@opentelemetry/resource-detector-azure": "^0.8.0", "@opentelemetry/resource-detector-container": "^0.7.1", "@opentelemetry/resource-detector-gcp": "^0.35.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-node": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.4.1", "@opentelemetry/core": "^2.0.0" } }, "sha512-kqoEBQss8fGGGRND0ycXZrwCXa/ePFop6W+YvZF5PikA9EsH0J/F2W6zvjetKjtdjyl6AUDW8I7gslZPXLLz3Q=="],
+
+ "@opentelemetry/context-async-hooks": ["@opentelemetry/[email protected]", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-bvyMcgLEkozzSzpEEEo1OMoeQ97bxj6Qs2uN3mPrSdDvObMI1myffD/BPqcLlzZO9//d1SqQA/WPw7Cz2AiqhA=="],
+
+ "@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ=="],
+
+ "@opentelemetry/exporter-logs-otlp-grpc": ["@opentelemetry/[email protected]", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/sdk-logs": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ACV2Az9BHRcAaPMYBnYMwKHNn2JwkzzsT3cdeG6+Tokm47fFfpf2xk3sq3QvX0Gk+TXW7q6d+OfBuYfWoAud2g=="],
+
+ "@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/sdk-logs": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-flYr1tr/wlUxsVc2ZYt/seNLgp3uagyUg9MtjiHYyaMQcN4XuEuI4UjUFwXAGQjd2khmXeie5YnTmO8gzyzemw=="],
+
+ "@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ZVkutDoQYLAkWmpbmd9XKZ9NeBQS6GPxLl/NZ/uDMq+tFnmZu1p0cvZ43x5+TpFoGkjPR6QYHCxkcZBwI9M8ag=="],
+
+ "@opentelemetry/exporter-metrics-otlp-grpc": ["@opentelemetry/[email protected]", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-ywo4TpQNOLi07K7P3CaymzS8XlDGfTFmMQ4oSPsZv38/gAf3/wPVh2uL5qYAFqrVokNCmkcaeCwX3QSy0g9b/A=="],
+
+ "@opentelemetry/exporter-metrics-otlp-http": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-LMRVg2yTev28L51RLLUK3gY0avMa1RVBq7IkYNtXDBxJRcd0TGGq/0rqfk7Y4UIM9NCJhDIUFHeGg8NpSgSWcw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-proto": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-9ie2jcaUQZdIoe6B02r0rF4Gz+JsZ9mev/2pYou1N0woOUkFM8xwO6BAlORnrFVslqF/XO5WG3q5FsTbuC5iiw=="],
+
+ "@opentelemetry/exporter-prometheus": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-metrics": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-J6/4KgljApWda/2YBMHHZg6vaZ6H8BjFInO8YQW+N0al1LjGAAq3pFRCEHpU6GI7ZlkphCxKy6MUjXOZVM8KWQ=="],
+
+ "@opentelemetry/exporter-trace-otlp-grpc": ["@opentelemetry/[email protected]", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-grpc-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-0ZM5CBoZbufXckxi/SWwP5B++CjPWS6N1i+K7f+GhRxYWVGt/yh4eiV3jklZKWw/DUyMkUvUOo0GW1RxoiLoZQ=="],
+
+ "@opentelemetry/exporter-trace-otlp-http": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Nw3pIqATC/9LfSGrMiQeeMQ7/z7W2D0wKPxtXwAcr7P64JW7KSH4YSX7Ji8Ti3MmB79NQg6imdagfegJDB0rng=="],
+
+ "@opentelemetry/exporter-trace-otlp-proto": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-wMxdDDyW+lmmenYGBp0evCoKzajXqIw6SSaZtaF/uqKR9/POhC/9vudnc+kf8W49hYFyIEutPrc1hA0exe3UwQ=="],
+
+ "@opentelemetry/exporter-zipkin": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-a9eeyHIipfdxzCfc2XPrE+/TI3wmrZUDFtG2RRXHSbZZULAny7SyybSvaDvS77a7iib5MPiAvluwVvbGTsHxsw=="],
+
+ "@opentelemetry/instrumentation": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-6EOSoT2zcyBM3VryAzn35ytjRrOMeaWZyzQ/PHVfxoXp5rMf7UUgVToqxOhQffKOHtC7Dma4bHt+DuwIBBZyZA=="],
+
+ "@opentelemetry/instrumentation-amqplib": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-zXcClQX3sttvBih1CjdPbvve/If1lCHPFK41fDpJE5NYjK38dwTMOUEV0+/ulfq4iU4oEV+ReCA+ZaXAm/uYdw=="],
+
+ "@opentelemetry/instrumentation-aws-lambda": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/aws-lambda": "8.10.147" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-xGVhBxxO7OuOl72XNwt1MOgaA6d3pSKI2Y5r3OfGNkx602KzW1t2vBHzJf8s4DAJYdMd5/RJLRi1z87CBu7yyg=="],
+
+ "@opentelemetry/instrumentation-aws-sdk": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/propagation-utils": "^0.31.1", "@opentelemetry/semantic-conventions": "^1.31.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CXB2cu0qnp5lHtNZRpvz0oOZrIKiWfHOiNVGWln9KY0m9sBheEqc58x3Ptpi5lMyso67heVCGDAc9+KbLAZwTQ=="],
+
+ "@opentelemetry/instrumentation-bunyan": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "^0.201.0", "@opentelemetry/instrumentation": "^0.201.0", "@types/bunyan": "1.8.11" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Sux5us8fkBLO/z+H8P2fSu+fRIm1xTeUHlwtM/E4CNZS9W/sAYrc8djZVa2JrwNXj/tE6U5vRJVObGekIkULow=="],
+
+ "@opentelemetry/instrumentation-cassandra-driver": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-MMn/Y2ErClGe7fmzTfR3iJcbEIspAn9hxbnj8oH7bVpPHcWbPphYICkNfLqah4tKVd+zazhs1agCiHL8y/e12g=="],
+
+ "@opentelemetry/instrumentation-connect": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/connect": "3.4.38" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-OHdp71gsRnm0lVD7SEtYSJFfvq4r6QN/5lgRK+Vrife1DHy+Insm66JJZN2Frt1waIzmDNn3VLCCafTnItfVcA=="],
+
+ "@opentelemetry/instrumentation-cucumber": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-bLKOQFgKimQkD8th+y0zMD9vNBjq79BWmPd7QqOGV2atQFbb2QJnorp/Y6poTVQNiITv0GE2mmmcqbjF+Y+JQA=="],
+
+ "@opentelemetry/instrumentation-dataloader": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-egPb8OcGZP6GUU/dbB8NnVgnSIqlM0nHS8KkADq51rVaMkzBcevtinYDFYTQu9tuQ6GEwaSdiQxiQORpYaVeQw=="],
+
+ "@opentelemetry/instrumentation-dns": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-gE02Jj97aaYUdZIvp2RwWPy3DLN86k15YvPRzkMaPWZKVwsKrHcA+xVX8k3rh9o0g64PC/U2f+LXiJr14PyVLg=="],
+
+ "@opentelemetry/instrumentation-express": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-0VF7HM8hTe0B5oXqCfBljMYFeQ3WKKqs0kCTRT02/Pjnmj5bOmR62r2dstjxbxnGKoeFRUHD/QAown9gyf659A=="],
+
+ "@opentelemetry/instrumentation-fastify": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-tib8SH5RCqhYRw9Qcpep9tP6ABxyXFDljdRy2aKpklHaFAyDELr3EpEAkGdkMZtO5Y3/QhUsmzYZp1np9jkjUg=="],
+
+ "@opentelemetry/instrumentation-fs": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-p2Fn78KSSbSSIJOOTn9FbxEzNRIIsYn9KTemKhABuunVqHixIqQ3hUjChbR+RbjPNZQthDC/0GHDeihRoyLdLQ=="],
+
+ "@opentelemetry/instrumentation-generic-pool": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-+fk7tnpzkkBAQzEtyJA0zRv7aBDhr05zczyBn//iJdmDG+ZfQFuIKK4dXNnv9FUZpedW0wcHlPqbP5FIGhAsLQ=="],
+
+ "@opentelemetry/instrumentation-graphql": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-FZaOS/BmE5npzk95X3Iqfo80a6wEJlkAtk7wLUJG/VZaB8RbBjJow4g0YdtvK8GNGEQW02KiQ+VtzdPGRemlwg=="],
+
+ "@opentelemetry/instrumentation-grpc": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "0.201.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-OIkXkVnilh8E6YKz/PiQtWeERqbcbjtVppMc7A2h39eaoaKnckXxom3YXhX+/PMhfmjbUnqw6k/KvmUr9zig1Q=="],
+
+ "@opentelemetry/instrumentation-hapi": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-0BCiQl2+oAuhSzbZrgpZgRvg7PclTfb7GxuBqWmWj9XkRk6cKla18S0pBqRCtl+qluRIaZ7tyXKmdtlsXj0QIw=="],
+
+ "@opentelemetry/instrumentation-http": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/instrumentation": "0.201.1", "@opentelemetry/semantic-conventions": "^1.29.0", "forwarded-parse": "2.1.2" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-xhkL/eOntScSLS8C2/LHKZ9Z9MEyGB9Yil7lF3JV0+YBeLXHQUIw2xPD7T0qw0DnqlrN8c/gi8hb5BEXZcyHRg=="],
+
+ "@opentelemetry/instrumentation-ioredis": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/redis-common": "^0.37.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CcbA9ylntqK7/lo7NUD/I+Uj6xcIiFFk1O2RnY23MugJunqZIFufvYkdh1mdG2bvBKdIVvA2nkVVt1Igw0uw1A=="],
+
+ "@opentelemetry/instrumentation-kafkajs": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.30.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-0roBjhMaW5li1gXVqrBRjzeLPWUiym8TPQi3iXqMA3GizPzilE4hwhIVI7GxtMHAdS15TgkUce6WVYVOBFrrbg=="],
+
+ "@opentelemetry/instrumentation-knex": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-+AxDwDdLJB467mEPOQKHod/1NDzX8msUAOEiViMkM7xAJoUsHTrP6EKlbjrCKkK+X2Eqh2pTO0ibeLkhG96oNA=="],
+
+ "@opentelemetry/instrumentation-koa": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-LO2pdZ5SF2LzWZLwrPTja/sQN8Kl4Wu5QvWSFJJLLGpeVKQWC4n41qjPUAAu668w43s42xqfs9bC4hWmQe7o8g=="],
+
+ "@opentelemetry/instrumentation-lru-memoizer": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-k8wdehAJYuSYWKiIDXrXSd7+33M4qOUEhrE3ymNFOHxVjwtUWpSh6JYSFe+5pqGilhl4CqUgxCkaQ9kPy3rAOQ=="],
+
+ "@opentelemetry/instrumentation-memcached": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/memcached": "^2.2.6" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-9NjbvCBM7p+wh/sHfSGDvrtinFYqIr6qunL9nN3e86eIQh3WyE9YdnlFGRbBR+MOzTCwSzrKAvY+J0fQe91VHA=="],
+
+ "@opentelemetry/instrumentation-mongodb": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-xTECmvFNfavpNz7btxmmvkCZKdHphQSSf0J4tSw4OOT0CSTythB/IWo41mYBd6GIutkmeA12dkKPd8zAU7zzyA=="],
+
+ "@opentelemetry/instrumentation-mongoose": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-kvopwp/kb1wN8jd0HhIBx/ZxbSmwqhN7LLvl9a7fXYACYlewUtCnVJLG80kwuG+rexRZlxeDfjoacFRDQSf9XA=="],
+
+ "@opentelemetry/instrumentation-mysql": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/mysql": "2.15.26" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-QWJNDNW0JyHj3cGtQOeNBcrDeOY35yX/JnDg8jEvxzmoEABHyj0EqI8fHPdOQmdctTjKTjzbqwtuAzLYIfkdAA=="],
+
+ "@opentelemetry/instrumentation-mysql2": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.41.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-rVKuKJ6HFVTNXNo8WuC3lBL/9zQ0OZfga/2dLseg/jlQZzUlWijsA57trnA92pcYxs32HBPSfKpuA88ZAVBFpA=="],
+
+ "@opentelemetry/instrumentation-nestjs-core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.30.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-xTtWbqdvlxRfhYidLEq0XvQUGqqgT4Fom21nxJ7XYvOoUJ4KNOxFBnfGW9RcXtFHDkux6rIjNP5CiPCYMZ007g=="],
+
+ "@opentelemetry/instrumentation-net": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-kFdY4IMth8obBPXoAlpLkea7l85Joe+p7oep+BexrHQ0iX+0cvnfoYBMMSE/vAp6T1N3Nu6RDT2Wzf3mqkHxjw=="],
+
+ "@opentelemetry/instrumentation-oracledb": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/oracledb": "6.5.2" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-b/JBJroC22DqgeMUSLYyleN6ohyXbCK1YGvBsCuDdiYUmOOyyWYSKdm4D26hTwFv1TKce+Im6aGcXF1hq2WKuQ=="],
+
+ "@opentelemetry/instrumentation-pg": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@opentelemetry/sql-common": "^0.41.0", "@types/pg": "8.6.1", "@types/pg-pool": "2.0.6" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-riWbJvSviTAsjeuq8fn7Y7+CXEYf3sGR18WfLeM7GgSnptTOur1++SLTN7XogqiwP3LFFQ0GLoYe+hxVOEyEpw=="],
+
+ "@opentelemetry/instrumentation-pino": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "^0.201.0", "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-+X+GTaXFuExrmQ3XS1HH8E+4KkKQ1HPzjNGnckuW/SQVOxRGeZMwJu1s60lx4eLpQuXXRh9nJaCAqMi/As347w=="],
+
+ "@opentelemetry/instrumentation-redis": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/redis-common": "^0.37.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-bp82CqAcBNk0+nneAX2L+wbCKiNHTnTEJlppOEjxESIR8AocSKO7gnWpotTh5Bki2UULUn62MBXJmRnIzj0ikw=="],
+
+ "@opentelemetry/instrumentation-redis-4": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/redis-common": "^0.37.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-aHZGrVwOsCM5u2PQdK1/PJuIWjGjYhOKEqqaPg3Mere2C6brwp+ih1bjcGyMRBS+7KNn5OSPcsFWpcW17Bfotw=="],
+
+ "@opentelemetry/instrumentation-restify": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-A1VixeXnRAQQfWidjnNqOwqGp1K5/r6fIyCdL+1Yvde11HiruMQOf6B71D7wWJHRtNKpLhq3o8JzeNGJoBEMpA=="],
+
+ "@opentelemetry/instrumentation-router": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-p98dJcw0reSyfkhRwzx8HrhyjcKmyguIE0KCLcxBnvQFnPL7EfUR2up2M9ggceFiZO5GUo1gk+r/mP+B9VBsQw=="],
+
+ "@opentelemetry/instrumentation-runtime-node": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-K3aPMYImALNsovPUjlIHctS2oH1YESlIAQMgiHXvcUxxz6+d66pPE1a4IoGP19iFOmRDMjshgHR/0DXMOEvZKg=="],
+
+ "@opentelemetry/instrumentation-socket.io": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-bVFiRvQnAW9hT+8FZVuhhybAvopAShLGm6LYz8raNZokxEw2FzGDVXONWaAM5D2/RbCbMl7R+PLN//3SEU/k0g=="],
+
+ "@opentelemetry/instrumentation-tedious": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/instrumentation": "^0.201.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/tedious": "^4.0.14" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-8OqIj554Rh8sll9myfDaFD1cYY8XKpxK3SMzCTZGc4BqS61gU0kd7UEydZeplrkQHDgySP4nvtFfkQCaZyTS4Q=="],
+
+ "@opentelemetry/instrumentation-undici": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.7.0" } }, "sha512-SLqTWPWWwqSZVYZw3a9sdcNXsahJfimvDpYaoDd6ryvQGDlOrHVKr56gL5qD3XDVa67DmV5ZQrxRrnYUdlp3BQ=="],
+
+ "@opentelemetry/instrumentation-winston": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "^0.201.0", "@opentelemetry/instrumentation": "^0.201.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-/nvmsLSON9Ki8C32kOMAkzsCpFfpjI2Fvr51uAY8/8bwG258MUUN8fCbAOMaiaPEKiB807wsE/aym83LYiB0ng=="],
+
+ "@opentelemetry/otlp-exporter-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-transformer": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-FiS/mIWmZXyRxYGyXPHY+I/4+XrYVTD7Fz/zwOHkVPQsA1JTakAOP9fAi6trXMio0dIpzvQujLNiBqGM7ExrQw=="],
+
+ "@opentelemetry/otlp-grpc-exporter-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@grpc/grpc-js": "^1.7.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/otlp-exporter-base": "0.201.1", "@opentelemetry/otlp-transformer": "0.201.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Y0h9hiMvNtUuXUMkYNAt81hxnFuOHHSeu/RC+pXcHe7S6ac0ROlcjdabBKmYSadJxRrP4YfLahLRuNkVtZow4w=="],
+
+ "@opentelemetry/otlp-transformer": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-metrics": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "protobufjs": "^7.3.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-+q/8Yuhtu9QxCcjEAXEO8fXLjlSnrnVwfzi9jiWaMAppQp69MoagHHomQj02V2WnGjvBod5ajgkbK4IoWab50A=="],
+
+ "@opentelemetry/propagation-utils": ["@opentelemetry/[email protected]", "", { "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-pweNs/e68ptJsX7/d+gZ7qOWyoAj6EAd7f3VeLPtUxX2xELCwSy45UoX36hnZSt/TWwxUMFjLl/4nndWxQdT0w=="],
+
+ "@opentelemetry/propagator-b3": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-Hc09CaQ8Tf5AGLmf449H726uRoBNGPBL4bjr7AnnUpzWMvhdn61F78z9qb6IqB737TffBsokGAK1XykFEZ1igw=="],
+
+ "@opentelemetry/propagator-jaeger": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-7PMdPBmGVH2eQNb/AtSJizQNgeNTfh6jQFqys6lfhd6P4r+m/nTh3gKPPpaCXVdRQ+z93vfKk+4UGty390283w=="],
+
+ "@opentelemetry/redis-common": ["@opentelemetry/[email protected]", "", {}, "sha512-tJwgE6jt32bLs/9J6jhQRKU2EZnsD8qaO13aoFyXwF6s4LhpT7YFHf3Z03MqdILk6BA2BFUhoyh7k9fj9i032A=="],
+
+ "@opentelemetry/resource-detector-alibaba-cloud": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/resources": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-R/asn6dAOWMfkLeEwqHCUz0cNbb9oiHVyd11iwlypeT/p9bR1lCX5juu5g/trOwxo62dbuFcDbBdKCJd3O2Edg=="],
+
+ "@opentelemetry/resource-detector-aws": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-Veavy+khoywR+Hv065SU5jucFTGTiW1KXo39CsJ+8wqdYYz8jiRJPnQ20Kd+X9HbV2+Abb0l5CrJIdxK1ZOqBg=="],
+
+ "@opentelemetry/resource-detector-azure": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-YBsJQrt0NGT66BgdVhhTkv7/oe/rTflX/rKteptVK6HNo7z8wbeAbB4SnSNJFfF+v3XrP/ruiTxKnNzoh/ampw=="],
+
+ "@opentelemetry/resource-detector-container": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/resources": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-XUxnGuANa/EdxagipWMXKYFC7KURwed9/V0+NtYjFmwWHzV9/J4IYVGTK8cWDpyUvAQf/vE4sMa3rnS025ivXQ=="],
+
+ "@opentelemetry/resource-detector-gcp": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/semantic-conventions": "^1.27.0", "gcp-metadata": "^6.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "sha512-JYkyOUc7TZAyHy37N2aPAwFvRdET0+E5qIRjmQLPop9LQi4+N0sKf65g4xCwuY/0M721T/424G3zneJjxyiooA=="],
+
+ "@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA=="],
+
+ "@opentelemetry/sdk-logs": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-Ug8gtpssUNUnfpotB9ZhnSsPSGDu+7LngTMgKl31mmVJwLAKyl6jC8diZrMcGkSgBh0o5dbg9puvLyR25buZfw=="],
+
+ "@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/resources": "2.10.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-t6r1VSvXNtSDnPXU1FbZeetJb7yyovHmgu0wRSoftxtE0g2rSNhQZQUy69sRUCL+iioJpX8SN/S6wq6ZtvLySQ=="],
+
+ "@opentelemetry/sdk-node": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api-logs": "0.201.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/exporter-logs-otlp-grpc": "0.201.1", "@opentelemetry/exporter-logs-otlp-http": "0.201.1", "@opentelemetry/exporter-logs-otlp-proto": "0.201.1", "@opentelemetry/exporter-metrics-otlp-grpc": "0.201.1", "@opentelemetry/exporter-metrics-otlp-http": "0.201.1", "@opentelemetry/exporter-metrics-otlp-proto": "0.201.1", "@opentelemetry/exporter-prometheus": "0.201.1", "@opentelemetry/exporter-trace-otlp-grpc": "0.201.1", "@opentelemetry/exporter-trace-otlp-http": "0.201.1", "@opentelemetry/exporter-trace-otlp-proto": "0.201.1", "@opentelemetry/exporter-zipkin": "2.0.1", "@opentelemetry/instrumentation": "0.201.1", "@opentelemetry/propagator-b3": "2.0.1", "@opentelemetry/propagator-jaeger": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/sdk-logs": "0.201.1", "@opentelemetry/sdk-metrics": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1", "@opentelemetry/sdk-trace-node": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-OdkYe6ZEFbPq+YXhebuiYpPECIBrrKgFJoAQVATllKlB5RDQDTE4J84/8LwGfQqSxBiSK2u1aSaFpzgBVoBrKA=="],
+
+ "@opentelemetry/sdk-trace": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/resources": "2.10.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-MfQGq3GRmTh5fM/y+OjaO0vj6+luCB1XO2gfXCalKCfgKw0eHL++sm75DNweC6ohlp+aFvACqeE0fYayqdRaoQ=="],
+
+ "@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/resources": "2.10.0", "@opentelemetry/sdk-trace": "2.10.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-GuYQQT7QD2EeO8lcZLRQzcbOyhqAzL+6WWTKTU9mSUBYBazkEDl+VrQcXQhbB08OWM9anD1aHleVadzulpOaUQ=="],
+
+ "@opentelemetry/sdk-trace-node": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.10.0", "@opentelemetry/core": "2.10.0", "@opentelemetry/sdk-trace-base": "2.10.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-GZK/G6oZyBLGlH1pUgeDch7D91KoHd2uotUGIkWCPi9GI5T9X0p4L7nNAMDR1BQjkRYoDqo+ddfVx9t5Uhys+Q=="],
+
+ "@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
+
+ "@opentelemetry/sql-common": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0" } }, "sha512-4mhWm3Z8z+i508zQJ7r6Xi7y4mmoJpdvH0fZPFRkWrdp5fq7hhZ2HhYokEOLkfqSMgPR4Z9EyB3DBkbKGOqZiQ=="],
+
+ "@pinojs/redact": ["@pinojs/[email protected]", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="],
+
+ "@protobuf-ts/protoc": ["@protobuf-ts/[email protected]", "", { "bin": { "protoc": "protoc.js" } }, "sha512-mUZJaV0daGO6HUX90o/atzQ6A7bbN2RSuHtdwo8SSF2Qoe3zHwa4IHyCN1evftTeHfLmdz+45qo47sL+5P8nyg=="],
+
+ "@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
+
+ "@protobufjs/base64": ["@protobufjs/[email protected]", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
+
+ "@protobufjs/codegen": ["@protobufjs/[email protected]", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],
+
+ "@protobufjs/eventemitter": ["@protobufjs/[email protected]", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],
+
+ "@protobufjs/fetch": ["@protobufjs/[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],
+
+ "@protobufjs/float": ["@protobufjs/[email protected]", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
+
+ "@protobufjs/path": ["@protobufjs/[email protected]", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
+
+ "@protobufjs/pool": ["@protobufjs/[email protected]", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
+
+ "@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="],
+
+ "@sindresorhus/slugify": ["@sindresorhus/[email protected]", "", { "dependencies": { "@sindresorhus/transliterate": "^1.0.0", "escape-string-regexp": "^5.0.0" } }, "sha512-MkngSCRZ8JdSOCHRaYd+D01XhvU3Hjy6MGl06zhOk614hp9EOAp5gIkBeQg7wtmxpitU6eAL4kdiRMcJa2dlrw=="],
+
+ "@sindresorhus/transliterate": ["@sindresorhus/[email protected]", "", { "dependencies": { "escape-string-regexp": "^5.0.0" } }, "sha512-doH1gimEu3A46VX6aVxpHTeHrytJAG6HgdxntYnCFiIFHEM/ZGpG8KiZGBChchjQmG0XFIBL552kBTjVcMZXwQ=="],
+
+ "@types/aws-lambda": ["@types/[email protected]", "", {}, "sha512-nD0Z9fNIZcxYX5Mai2CTmFD7wX7UldCkW2ezCF8D1T5hdiLsnTWDGRpfRYntU6VjTdLQjOvyszru7I1c1oCQew=="],
+
+ "@types/bunyan": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-758fRH7umIMk5qt5ELmRMff4mLDlN+xyYzC+dkPTdKwbSkJFvz6xwyScrytPU0QIBbRRwbiE8/BIg8bpajerNQ=="],
+
+ "@types/connect": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="],
+
+ "@types/diff-match-patch": ["@types/[email protected]", "", {}, "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg=="],
+
+ "@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
+
+ "@types/memcached": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-AM9smvZN55Gzs2wRrqeMHVP7KE8KWgCJO/XL5yCly2xF6EKa4YlbpK+cLSAH4NG/Ah64HrlegmGqW8kYws7Vxg=="],
+
+ "@types/mysql": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-DSLCOXhkvfS5WNNPbfn2KdICAmk8lLc+/PNvnPnF7gOdMZCxopXduqv0OQ13y/yA/zXTSikZZqVgybUxOEg6YQ=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg=="],
+
+ "@types/oracledb": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-kK1eBS/Adeyis+3OlBDMeQQuasIDLUYXsi2T15ccNJ0iyUpQ4xDF7svFu3+bGVrI0CMBUclPciz+lsQR3JX3TQ=="],
+
+ "@types/pg": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-1Kc4oAGzAl7uqUStZCDvaLFqZrW9qWSjXOmBfdgyBP5La7Us6Mg4GBvRlSoaZMhQF/zSj1C8CtKMBkoiT8eL8w=="],
+
+ "@types/pg-pool": ["@types/[email protected]", "", { "dependencies": { "@types/pg": "*" } }, "sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ=="],
+
+ "@types/shimmer": ["@types/[email protected]", "", {}, "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg=="],
+
+ "@types/tedious": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw=="],
+
+ "acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
+
+ "acorn-import-attributes": ["[email protected]", "", { "peerDependencies": { "acorn": "^8" } }, "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ=="],
+
+ "agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
+
+ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8", "@ai-sdk/react": "1.2.12", "@ai-sdk/ui-utils": "1.2.11", "@opentelemetry/api": "1.9.0", "jsondiffpatch": "0.6.0" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "zod": "^3.23.8" }, "optionalPeers": ["react"] }, "sha512-dIE2bfNpqHN3r6IINp9znguYdhIOheKW2LDigAMrgt/upT3B8eBGPSCblENvaZGoq+hxaN9fSMzjWpbqloP+7Q=="],
+
+ "ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
+
+ "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
+
+ "atomic-sleep": ["[email protected]", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="],
+
+ "bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
+
+ "chalk": ["[email protected]", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
+
+ "cjs-module-lexer": ["[email protected]", "", {}, "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q=="],
+
+ "cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
+
+ "clone": ["[email protected]", "", {}, "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w=="],
+
+ "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
+
+ "color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
+
+ "colorette": ["[email protected]", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="],
+
+ "date-fns": ["[email protected]", "", {}, "sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww=="],
+
+ "dateformat": ["[email protected]", "", {}, "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA=="],
+
+ "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
+
+ "dequal": ["[email protected]", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
+
+ "diff-match-patch": ["[email protected]", "", {}, "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw=="],
+
+ "dotenv": ["[email protected]", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
+
+ "emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
+
+ "es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
+
+ "escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
+
+ "escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
+
+ "extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
+
+ "fast-copy": ["[email protected]", "", {}, "sha512-eVAiWVNPSEGIzDl5yPuLrx8fNMogScXvD9xp1Kzd41FjRIz2I3sSIcxsFeM5EzFfHAfobdvs8ZySffUopljvIA=="],
+
+ "fast-safe-stringify": ["[email protected]", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="],
+
+ "forwarded-parse": ["[email protected]", "", {}, "sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw=="],
+
+ "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
+
+ "gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="],
+
+ "gcp-metadata": ["[email protected]", "", { "dependencies": { "gaxios": "^6.1.1", "google-logging-utils": "^0.0.2", "json-bigint": "^1.0.0" } }, "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A=="],
+
+ "get-caller-file": ["[email protected]", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
+
+ "google-logging-utils": ["[email protected]", "", {}, "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ=="],
+
+ "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
+
+ "help-me": ["[email protected]", "", {}, "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
+
+ "hono-openapi": ["[email protected]", "", { "dependencies": { "json-schema-walker": "^2.0.0" }, "peerDependencies": { "@hono/arktype-validator": "^2.0.0", "@hono/effect-validator": "^1.2.0", "@hono/typebox-validator": "^0.2.0 || ^0.3.0", "@hono/valibot-validator": "^0.5.1", "@hono/zod-validator": "^0.4.1", "@sinclair/typebox": "^0.34.9", "@valibot/to-json-schema": "^1.0.0-beta.3", "arktype": "^2.0.0", "effect": "^3.11.3", "hono": "^4.6.13", "openapi-types": "^12.1.3", "valibot": "^1.0.0-beta.9", "zod": "^3.23.8", "zod-openapi": "^4.0.0" }, "optionalPeers": ["@hono/arktype-validator", "@hono/effect-validator", "@hono/typebox-validator", "@hono/valibot-validator", "@hono/zod-validator", "@sinclair/typebox", "@valibot/to-json-schema", "arktype", "effect", "hono", "valibot", "zod", "zod-openapi"] }, "sha512-LYr5xdtD49M7hEAduV1PftOMzuT8ZNvkyWfh1DThkLsIr4RkvDb12UxgIiFbwrJB6FLtFXLoOZL9x4IeDk2+VA=="],
+
+ "https-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
+
+ "import-in-the-middle": ["[email protected]", "", { "dependencies": { "acorn": "^8.14.0", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", "module-details-from-path": "^1.0.3" } }, "sha512-bpQy+CrsRmYmoPMAE/0G33iwRqwW4ouqdRg8jgbH3aKuCtOc8lxgmYXg2dMM92CRiGP660EtBcymH/eVUpCSaA=="],
+
+ "is-core-module": ["[email protected]", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA=="],
+
+ "is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
+
+ "is-stream": ["[email protected]", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
+
+ "joycon": ["[email protected]", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="],
+
+ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ=="],
+
+ "json-bigint": ["[email protected]", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],
+
+ "json-schema": ["[email protected]", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],
+
+ "json-schema-to-zod": ["[email protected]", "", { "bin": { "json-schema-to-zod": "dist/cjs/cli.js" } }, "sha512-fRr1mHgZ7hboLKBUdR428gd9dIHUFGivUqOeiDcSmyXkNZCtB1uGaZLvsjZ4GaN5pwBIs+TGIOf6s+Rp5/R/zA=="],
+
+ "json-schema-walker": ["[email protected]", "", { "dependencies": { "@apidevtools/json-schema-ref-parser": "^11.1.0", "clone": "^2.1.2" } }, "sha512-nXN2cMky0Iw7Af28w061hmxaPDaML5/bQD9nwm1lOoIKEGjHcRGxqWe4MfrkYThYAPjSUhmsp4bJNoLAyVn9Xw=="],
+
+ "jsondiffpatch": ["[email protected]", "", { "dependencies": { "@types/diff-match-patch": "^1.0.36", "chalk": "^5.3.0", "diff-match-patch": "^1.0.5" }, "bin": { "jsondiffpatch": "bin/jsondiffpatch.js" } }, "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ=="],
+
+ "lodash.camelcase": ["[email protected]", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
+
+ "long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
+
+ "minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
+
+ "module-details-from-path": ["[email protected]", "", {}, "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w=="],
+
+ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
+
+ "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],
+
+ "node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
+
+ "on-exit-leak-free": ["[email protected]", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="],
+
+ "once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
+
+ "openapi-types": ["[email protected]", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],
+
+ "path-parse": ["[email protected]", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="],
+
+ "pg-int8": ["[email protected]", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="],
+
+ "pg-protocol": ["[email protected]", "", {}, "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg=="],
+
+ "pg-types": ["[email protected]", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="],
+
+ "pino": ["[email protected]", "", { "dependencies": { "@pinojs/redact": "^0.4.0", "atomic-sleep": "^1.0.0", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^5.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^0.2.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^3.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w=="],
+
+ "pino-abstract-transport": ["[email protected]", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw=="],
+
+ "pino-pretty": ["[email protected]", "", { "dependencies": { "colorette": "^2.0.7", "dateformat": "^4.6.3", "fast-copy": "^4.0.0", "fast-safe-stringify": "^2.1.1", "help-me": "^5.0.0", "joycon": "^3.1.1", "minimist": "^1.2.6", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^3.0.0", "pump": "^3.0.0", "secure-json-parse": "^4.0.0", "sonic-boom": "^4.0.1", "strip-json-comments": "^5.0.2" }, "bin": { "pino-pretty": "bin.js" } }, "sha512-ttXRkkOz6WWC95KeY9+xxWL6AtImwbyMHrL1mSwqwW9u+vLp/WIElvHvCSDg0xO/Dzrggz1zv3rN5ovTRVowKg=="],
+
+ "pino-std-serializers": ["[email protected]", "", {}, "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="],
+
+ "postgres-array": ["[email protected]", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
+
+ "postgres-bytea": ["[email protected]", "", {}, "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ=="],
+
+ "postgres-date": ["[email protected]", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="],
+
+ "postgres-interval": ["[email protected]", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
+
+ "process-warning": ["[email protected]", "", {}, "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw=="],
+
+ "protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="],
+
+ "pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
+
+ "quick-format-unescaped": ["[email protected]", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="],
+
+ "radash": ["[email protected]", "", {}, "sha512-h36JMxKRqrAxVD8201FrCpyeNuUY9Y5zZwujr20fFO77tpUtGa6EZzfKw/3WaiBX95fq7+MpsuMLNdSnORAwSA=="],
+
+ "react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
+
+ "real-require": ["[email protected]", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="],
+
+ "require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
+
+ "require-in-the-middle": ["[email protected]", "", { "dependencies": { "debug": "^4.3.5", "module-details-from-path": "^1.0.3", "resolve": "^1.22.8" } }, "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ=="],
+
+ "resolve": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA=="],
+
+ "safe-stable-stringify": ["[email protected]", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="],
+
+ "secure-json-parse": ["[email protected]", "", {}, "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="],
+
+ "shimmer": ["[email protected]", "", {}, "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw=="],
+
+ "sift": ["[email protected]", "", {}, "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ=="],
+
+ "sonic-boom": ["[email protected]", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q=="],
+
+ "split2": ["[email protected]", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
+
+ "string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "strip-json-comments": ["[email protected]", "", {}, "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw=="],
+
+ "supports-preserve-symlinks-flag": ["[email protected]", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
+
+ "swr": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-BRw55e8r0B7SpDN20CAzoQAHl7y1yP7/Zt7oqUjMv0vSt2u2Xnkm88Ws+VypbV9BXHQVuSuyVq7zMjO16wSExw=="],
+
+ "thread-stream": ["[email protected]", "", { "dependencies": { "real-require": "^0.2.0" } }, "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw=="],
+
+ "throttleit": ["[email protected]", "", {}, "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw=="],
+
+ "tr46": ["[email protected]", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
+
+ "use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
+
+ "uuid": ["[email protected]", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
+
+ "webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
+
+ "whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
+
+ "wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
+
+ "wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
+
+ "xstate": ["[email protected]", "", {}, "sha512-ULazi1oe6wGrXl0Frb6otSlkm5HLifbbVTkMk5kkSKqz4TkxJaVpnl6jOJwKeid3ORPxYyZQgNLUSYX9q65SIA=="],
+
+ "xtend": ["[email protected]", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
+
+ "y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
+
+ "yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="],
+
+ "yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
+
+ "zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+
+ "zod-from-json-schema": ["[email protected]", "", { "dependencies": { "zod": "^3.24.2" } }, "sha512-zYEoo86M1qpA1Pq6329oSyHLS785z/mTwfr9V1Xf/ZLhuuBGaMlDGu/pDVGVUe4H4oa1EFgWZT53DP0U3oT9CQ=="],
+
+ "zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
+
+ "@opentelemetry/exporter-logs-otlp-grpc/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-logs-otlp-http/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-logs-otlp-proto/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-logs-otlp-proto/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-logs-otlp-proto/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/exporter-metrics-otlp-grpc/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-grpc/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-grpc/@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="],
+
+ "@opentelemetry/exporter-metrics-otlp-http/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-http/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-http/@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="],
+
+ "@opentelemetry/exporter-metrics-otlp-proto/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-proto/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-metrics-otlp-proto/@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="],
+
+ "@opentelemetry/exporter-prometheus/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-prometheus/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-prometheus/@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="],
+
+ "@opentelemetry/exporter-trace-otlp-grpc/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-trace-otlp-grpc/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-trace-otlp-grpc/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/exporter-trace-otlp-http/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-trace-otlp-http/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-trace-otlp-http/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/exporter-trace-otlp-proto/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-trace-otlp-proto/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-trace-otlp-proto/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/exporter-zipkin/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/exporter-zipkin/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/exporter-zipkin/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/instrumentation-http/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/otlp-exporter-base/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/otlp-grpc-exporter-base/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/otlp-transformer/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/otlp-transformer/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/otlp-transformer/@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="],
+
+ "@opentelemetry/otlp-transformer/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/propagator-b3/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/propagator-jaeger/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/sdk-logs/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/sdk-logs/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/sdk-node/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw=="],
+
+ "@opentelemetry/sdk-node/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw=="],
+
+ "@opentelemetry/sdk-node/@opentelemetry/sdk-metrics": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g=="],
+
+ "@opentelemetry/sdk-node/@opentelemetry/sdk-trace-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.1", "@opentelemetry/resources": "2.0.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ=="],
+
+ "@opentelemetry/sdk-node/@opentelemetry/sdk-trace-node": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.0.1", "@opentelemetry/core": "2.0.1", "@opentelemetry/sdk-trace-base": "2.0.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-UhdbPF19pMpBtCWYP5lHbTogLWx9N0EBxtdagvkn5YtsAnCBZzL7SjktG+ZmupRgifsHMjwUaCCaVmqGfSADmA=="],
+
+ "ai/@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
+
+ "pino-pretty/pino-abstract-transport": ["[email protected]", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg=="],
+
+ "pino-pretty/secure-json-parse": ["[email protected]", "", {}, "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA=="],
+
+ "@opentelemetry/sdk-node/@opentelemetry/sdk-trace-node/@opentelemetry/context-async-hooks": ["@opentelemetry/[email protected]", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw=="],
+ }
+}
diff --git a/examples/mastra-bot/package.json b/examples/mastra-bot/package.json
new file mode 100644
index 00000000..27be2ca1
--- /dev/null
+++ b/examples/mastra-bot/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@openbot/example-mastra-bot",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "bun --env-file=../../.env --watch src/index.ts",
+ "start": "bun --env-file=../../.env src/index.ts"
+ },
+ "dependencies": {
+ "@ag-ui/core": "0.0.57",
+ "@ag-ui/encoder": "0.0.57",
+ "@ai-sdk/openai": "^1.3.24",
+ "@mastra/core": "^0.10.5"
+ }
+}
diff --git a/server/drizzle/0000_schema.sql b/server/drizzle/0000_schema.sql
new file mode 100644
index 00000000..331b9835
--- /dev/null
+++ b/server/drizzle/0000_schema.sql
@@ -0,0 +1,406 @@
+-- The whole schema, in one migration.
+--
+-- WHY THERE IS ONLY ONE. A migration chain records how a schema was arrived at, which matters to a
+-- deployment that has to walk it and not at all to one starting from nothing. Every deployment of
+-- this starts from nothing, so the chain was collapsed into the schema it produces.
+--
+-- TWO THINGS HERE ARE NOT GENERATED from the table definitions, and must survive if this is ever
+-- regenerated: the vector extension, and the trigger that makes the audit trail append-only.
+
+CREATE EXTENSION IF NOT EXISTS vector;--> statement-breakpoint
+
+CREATE TYPE "public"."acl_effect" AS ENUM('allow', 'deny');--> statement-breakpoint
+CREATE TYPE "public"."agent_type" AS ENUM('built_in', 'remote_ag_ui');--> statement-breakpoint
+CREATE TYPE "public"."connector_type" AS ENUM('google_drive', 'onedrive');--> statement-breakpoint
+CREATE TYPE "public"."credential_kind" AS ENUM('model', 'connector', 'agent', 'mcp');--> statement-breakpoint
+CREATE TYPE "public"."role" AS ENUM('admin', 'user');--> statement-breakpoint
+CREATE TYPE "public"."sync_status" AS ENUM('pending', 'running', 'succeeded', 'failed');--> statement-breakpoint
+CREATE TYPE "public"."agent_visibility" AS ENUM('public', 'private');--> statement-breakpoint
+CREATE TABLE "accounts" (
+ "id" text PRIMARY KEY NOT NULL,
+ "account_id" text NOT NULL,
+ "provider_id" text NOT NULL,
+ "user_id" text NOT NULL,
+ "access_token" text,
+ "refresh_token" text,
+ "id_token" text,
+ "access_token_expires_at" timestamp with time zone,
+ "refresh_token_expires_at" timestamp with time zone,
+ "scope" text,
+ "password" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "agents" (
+ "id" text PRIMARY KEY NOT NULL,
+ "name" text NOT NULL,
+ "type" "agent_type" NOT NULL,
+ "configuration" jsonb NOT NULL,
+ "package_id" uuid,
+ "override" jsonb,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "audit_events" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "actor_user_id" text,
+ "event_type" text NOT NULL,
+ "target_type" text NOT NULL,
+ "target_id" text,
+ "payload" jsonb NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "channel_agents" (
+ "channel_id" text NOT NULL,
+ "agent_id" text NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "channel_agents_channel_id_agent_id_pk" PRIMARY KEY("channel_id","agent_id")
+);
+--> statement-breakpoint
+CREATE TABLE "channel_memberships" (
+ "channel_id" text NOT NULL,
+ "user_id" text NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "channel_memberships_channel_id_user_id_pk" PRIMARY KEY("channel_id","user_id")
+);
+--> statement-breakpoint
+CREATE TABLE "channels" (
+ "id" text PRIMARY KEY NOT NULL,
+ "name" text NOT NULL,
+ "description" text NOT NULL,
+ "suggested_prompts" text[] DEFAULT '{}' NOT NULL,
+ "allowed_groups" text[] DEFAULT '{}' NOT NULL,
+ "package_id" uuid,
+ "override" jsonb,
+ "last_message" text,
+ "last_message_at" timestamp with time zone,
+ "last_message_agent_id" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "chunks" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "document_id" uuid NOT NULL,
+ "position" integer NOT NULL,
+ "content" text NOT NULL,
+ "embedding" vector(1536) NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "connector_cursors" (
+ "connector_instance_id" uuid PRIMARY KEY NOT NULL,
+ "cursor" text,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "connector_instances" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "type" "connector_type" NOT NULL,
+ "credential_id" uuid,
+ "status" "sync_status" DEFAULT 'pending' NOT NULL,
+ "source_metadata" jsonb NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "credentials" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "kind" "credential_kind" NOT NULL,
+ "provider" text NOT NULL,
+ "encrypted_value" text NOT NULL,
+ "key_id" text NOT NULL,
+ "metadata" jsonb NOT NULL,
+ "revoked_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "deployment_packages" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "tenant_id" text NOT NULL,
+ "source_path" text NOT NULL,
+ "checksum" text NOT NULL,
+ "loaded_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "deployment_packages_tenant_id_unique" UNIQUE("tenant_id")
+);
+--> statement-breakpoint
+CREATE TABLE "document_acls" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "document_id" uuid NOT NULL,
+ "principal" text NOT NULL,
+ "effect" "acl_effect" NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "documents" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "connector_instance_id" uuid NOT NULL,
+ "source_id" text NOT NULL,
+ "title" text NOT NULL,
+ "canonical_url" text NOT NULL,
+ "metadata" jsonb NOT NULL,
+ "content_hash" text NOT NULL,
+ "deleted_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "intelligence_channel_mappings" (
+ "user_id" text NOT NULL,
+ "channel_id" text NOT NULL,
+ "thread_id" text NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "intelligence_channel_mappings_user_id_channel_id_pk" PRIMARY KEY("user_id","channel_id")
+);
+--> statement-breakpoint
+CREATE TABLE "sessions" (
+ "id" text PRIMARY KEY NOT NULL,
+ "user_id" text NOT NULL,
+ "token" text NOT NULL,
+ "expires_at" timestamp with time zone NOT NULL,
+ "ip_address" text,
+ "user_agent" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "sessions_token_unique" UNIQUE("token")
+);
+--> statement-breakpoint
+CREATE TABLE "sync_runs" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "connector_instance_id" uuid NOT NULL,
+ "status" "sync_status" NOT NULL,
+ "started_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "completed_at" timestamp with time zone,
+ "error" text,
+ "stats" jsonb NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "user_roles" (
+ "user_id" text NOT NULL,
+ "role" "role" NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "user_roles_user_id_role_pk" PRIMARY KEY("user_id","role")
+);
+--> statement-breakpoint
+CREATE TABLE "users" (
+ "id" text PRIMARY KEY NOT NULL,
+ "email" text NOT NULL,
+ "name" text,
+ "image" text,
+ "email_verified" boolean DEFAULT false NOT NULL,
+ "groups" text[] DEFAULT '{}' NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "users_email_unique" UNIQUE("email")
+);
+--> statement-breakpoint
+CREATE TABLE "verifications" (
+ "id" text PRIMARY KEY NOT NULL,
+ "identifier" text NOT NULL,
+ "value" text NOT NULL,
+ "expires_at" timestamp with time zone NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "webhook_subscriptions" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "connector_instance_id" uuid NOT NULL,
+ "provider_subscription_id" text NOT NULL,
+ "expires_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "action_policy" (
+ "id" text PRIMARY KEY NOT NULL,
+ "mode" text NOT NULL,
+ "deny" text[] NOT NULL,
+ "allow" text[] NOT NULL,
+ "updated_by" text,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "agent_preferences" (
+ "user_id" text NOT NULL,
+ "agent_id" text NOT NULL,
+ "hidden_at" timestamp with time zone,
+ CONSTRAINT "agent_preferences_user_id_agent_id_pk" PRIMARY KEY("user_id","agent_id")
+);
+--> statement-breakpoint
+CREATE TABLE "agent_profiles" (
+ "agent_id" text PRIMARY KEY NOT NULL,
+ "owner_user_id" text,
+ "title" text NOT NULL,
+ "role_description" text NOT NULL,
+ "avatar_seed" text NOT NULL,
+ "visibility" "agent_visibility" NOT NULL,
+ "deleted_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "component_exclusions" (
+ "component_name" text NOT NULL,
+ "agent_id" text NOT NULL,
+ "withheld_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "component_exclusions_component_name_agent_id_pk" PRIMARY KEY("component_name","agent_id")
+);
+--> statement-breakpoint
+CREATE TABLE "component_functions" (
+ "component_name" text NOT NULL,
+ "function_name" text NOT NULL,
+ "granted_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "component_functions_component_name_function_name_pk" PRIMARY KEY("component_name","function_name")
+);
+--> statement-breakpoint
+CREATE TABLE "components" (
+ "name" text PRIMARY KEY NOT NULL,
+ "title" text NOT NULL,
+ "kind" text NOT NULL,
+ "draft_description" text NOT NULL,
+ "published_description" text,
+ "published" boolean DEFAULT false NOT NULL,
+ "published_at" timestamp with time zone,
+ "updated_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "mcp_servers" (
+ "id" text PRIMARY KEY NOT NULL,
+ "title" text NOT NULL,
+ "vendor" text NOT NULL,
+ "url" text NOT NULL,
+ "provenance" text DEFAULT 'first-party' NOT NULL,
+ "credential_id" text,
+ "tools_refreshed_at" timestamp with time zone,
+ "last_error" text,
+ "added_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "mcp_tools" (
+ "server_id" text NOT NULL,
+ "name" text NOT NULL,
+ "description" text DEFAULT '' NOT NULL,
+ "input_schema" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "mcp_tools_server_id_name_pk" PRIMARY KEY("server_id","name")
+);
+--> statement-breakpoint
+CREATE TABLE "plugin_grants" (
+ "kind" text NOT NULL,
+ "ref" text NOT NULL,
+ "agent_id" text NOT NULL,
+ "granted_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "plugin_grants_kind_ref_agent_id_pk" PRIMARY KEY("kind","ref","agent_id")
+);
+--> statement-breakpoint
+CREATE TABLE "sandboxed_components" (
+ "name" text PRIMARY KEY NOT NULL,
+ "title" text NOT NULL,
+ "draft_description" text DEFAULT '' NOT NULL,
+ "draft_html" text DEFAULT '' NOT NULL,
+ "draft_css" text DEFAULT '' NOT NULL,
+ "draft_js_functions" text DEFAULT '' NOT NULL,
+ "draft_argument_schema" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "published_description" text,
+ "published_html" text,
+ "published_css" text,
+ "published_js_functions" text,
+ "published_argument_schema" jsonb,
+ "sample_arguments" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "revision" integer DEFAULT 0 NOT NULL,
+ "published" boolean DEFAULT false NOT NULL,
+ "published_at" timestamp with time zone,
+ "authored_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "skills" (
+ "id" text PRIMARY KEY NOT NULL,
+ "owner_user_id" text,
+ "slug" text NOT NULL,
+ "title" text NOT NULL,
+ "summary" text NOT NULL,
+ "instructions" text NOT NULL,
+ "origin" text DEFAULT 'yours' NOT NULL,
+ "installed_by" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agents" ADD CONSTRAINT "agents_package_id_deployment_packages_id_fk" FOREIGN KEY ("package_id") REFERENCES "public"."deployment_packages"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "channel_agents" ADD CONSTRAINT "channel_agents_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "channel_agents" ADD CONSTRAINT "channel_agents_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "channel_memberships" ADD CONSTRAINT "channel_memberships_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "channel_memberships" ADD CONSTRAINT "channel_memberships_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "channels" ADD CONSTRAINT "channels_package_id_deployment_packages_id_fk" FOREIGN KEY ("package_id") REFERENCES "public"."deployment_packages"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "channels" ADD CONSTRAINT "channels_last_message_agent_id_agents_id_fk" FOREIGN KEY ("last_message_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "chunks" ADD CONSTRAINT "chunks_document_id_documents_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."documents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "connector_cursors" ADD CONSTRAINT "connector_cursors_connector_instance_id_connector_instances_id_fk" FOREIGN KEY ("connector_instance_id") REFERENCES "public"."connector_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "connector_instances" ADD CONSTRAINT "connector_instances_credential_id_credentials_id_fk" FOREIGN KEY ("credential_id") REFERENCES "public"."credentials"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "document_acls" ADD CONSTRAINT "document_acls_document_id_documents_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."documents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "documents" ADD CONSTRAINT "documents_connector_instance_id_connector_instances_id_fk" FOREIGN KEY ("connector_instance_id") REFERENCES "public"."connector_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "intelligence_channel_mappings" ADD CONSTRAINT "intelligence_channel_mappings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "intelligence_channel_mappings" ADD CONSTRAINT "intelligence_channel_mappings_channel_id_channels_id_fk" FOREIGN KEY ("channel_id") REFERENCES "public"."channels"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "sync_runs" ADD CONSTRAINT "sync_runs_connector_instance_id_connector_instances_id_fk" FOREIGN KEY ("connector_instance_id") REFERENCES "public"."connector_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "webhook_subscriptions" ADD CONSTRAINT "webhook_subscriptions_connector_instance_id_connector_instances_id_fk" FOREIGN KEY ("connector_instance_id") REFERENCES "public"."connector_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_preferences" ADD CONSTRAINT "agent_preferences_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_preferences" ADD CONSTRAINT "agent_preferences_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_profiles" ADD CONSTRAINT "agent_profiles_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_profiles" ADD CONSTRAINT "agent_profiles_owner_user_id_users_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "component_exclusions" ADD CONSTRAINT "component_exclusions_component_name_components_name_fk" FOREIGN KEY ("component_name") REFERENCES "public"."components"("name") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "component_exclusions" ADD CONSTRAINT "component_exclusions_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "component_functions" ADD CONSTRAINT "component_functions_component_name_components_name_fk" FOREIGN KEY ("component_name") REFERENCES "public"."components"("name") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "mcp_tools" ADD CONSTRAINT "mcp_tools_server_id_mcp_servers_id_fk" FOREIGN KEY ("server_id") REFERENCES "public"."mcp_servers"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "plugin_grants" ADD CONSTRAINT "plugin_grants_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "skills" ADD CONSTRAINT "skills_owner_user_id_users_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+CREATE UNIQUE INDEX "accounts_provider_account_idx" ON "accounts" USING btree ("provider_id","account_id");--> statement-breakpoint
+CREATE INDEX "audit_events_created_at_idx" ON "audit_events" USING btree ("created_at");--> statement-breakpoint
+CREATE INDEX "channels_recent_activity_idx" ON "channels" USING btree (COALESCE("last_message_at", "created_at") DESC);--> statement-breakpoint
+CREATE UNIQUE INDEX "chunks_document_position_idx" ON "chunks" USING btree ("document_id","position");--> statement-breakpoint
+CREATE INDEX "chunks_document_idx" ON "chunks" USING btree ("document_id");--> statement-breakpoint
+CREATE UNIQUE INDEX "document_acls_document_principal_effect_idx" ON "document_acls" USING btree ("document_id","principal","effect");--> statement-breakpoint
+CREATE INDEX "document_acls_principal_idx" ON "document_acls" USING btree ("principal");--> statement-breakpoint
+CREATE UNIQUE INDEX "documents_connector_source_idx" ON "documents" USING btree ("connector_instance_id","source_id");--> statement-breakpoint
+CREATE INDEX "documents_connector_deleted_idx" ON "documents" USING btree ("connector_instance_id","deleted_at");--> statement-breakpoint
+CREATE UNIQUE INDEX "intelligence_channel_mappings_thread_idx" ON "intelligence_channel_mappings" USING btree ("thread_id");--> statement-breakpoint
+CREATE INDEX "sync_runs_connector_started_at_idx" ON "sync_runs" USING btree ("connector_instance_id","started_at");--> statement-breakpoint
+CREATE INDEX "agent_profiles_visibility_deleted_idx" ON "agent_profiles" USING btree ("visibility","deleted_at");--> statement-breakpoint
+CREATE INDEX "plugin_grants_agent_idx" ON "plugin_grants" USING btree ("agent_id");--> statement-breakpoint
+CREATE UNIQUE INDEX "skills_slug_key" ON "skills" USING btree ("slug");--> statement-breakpoint
+CREATE INDEX "skills_owner_idx" ON "skills" USING btree ("owner_user_id");
+
+-- THE AUDIT TRAIL IS APPEND-ONLY, AND THIS IS WHAT MAKES THAT TRUE. A trail anybody can edit after
+-- the fact answers no question worth asking. Enforced in the database rather than in the
+-- application, because the application is not the only thing that can reach this table.
+CREATE FUNCTION prevent_audit_event_mutation()
+RETURNS trigger
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Audit events are append-only';
+END;
+$$;--> statement-breakpoint
+
+CREATE TRIGGER audit_events_append_only
+BEFORE UPDATE OR DELETE ON audit_events
+FOR EACH ROW
+EXECUTE FUNCTION prevent_audit_event_mutation();
diff --git a/server/drizzle/meta/0000_snapshot.json b/server/drizzle/meta/0000_snapshot.json
new file mode 100644
index 00000000..649675bc
--- /dev/null
+++ b/server/drizzle/meta/0000_snapshot.json
@@ -0,0 +1,2503 @@
+{
+ "id": "084d702b-09fd-44df-a60a-22477be02359",
+ "prevId": "00000000-0000-0000-0000-000000000000",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.accounts": {
+ "name": "accounts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "accounts_provider_account_idx": {
+ "name": "accounts_provider_account_idx",
+ "columns": [
+ {
+ "expression": "provider_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "accounts_user_id_users_id_fk": {
+ "name": "accounts_user_id_users_id_fk",
+ "tableFrom": "accounts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agents": {
+ "name": "agents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "agent_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configuration": {
+ "name": "configuration",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "package_id": {
+ "name": "package_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "override": {
+ "name": "override",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agents_package_id_deployment_packages_id_fk": {
+ "name": "agents_package_id_deployment_packages_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "deployment_packages",
+ "columnsFrom": ["package_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.audit_events": {
+ "name": "audit_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_type": {
+ "name": "target_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "audit_events_created_at_idx": {
+ "name": "audit_events_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channel_agents": {
+ "name": "channel_agents",
+ "schema": "",
+ "columns": {
+ "channel_id": {
+ "name": "channel_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "channel_agents_channel_id_channels_id_fk": {
+ "name": "channel_agents_channel_id_channels_id_fk",
+ "tableFrom": "channel_agents",
+ "tableTo": "channels",
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_agents_agent_id_agents_id_fk": {
+ "name": "channel_agents_agent_id_agents_id_fk",
+ "tableFrom": "channel_agents",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "channel_agents_channel_id_agent_id_pk": {
+ "name": "channel_agents_channel_id_agent_id_pk",
+ "columns": ["channel_id", "agent_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channel_memberships": {
+ "name": "channel_memberships",
+ "schema": "",
+ "columns": {
+ "channel_id": {
+ "name": "channel_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "channel_memberships_channel_id_channels_id_fk": {
+ "name": "channel_memberships_channel_id_channels_id_fk",
+ "tableFrom": "channel_memberships",
+ "tableTo": "channels",
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_memberships_user_id_users_id_fk": {
+ "name": "channel_memberships_user_id_users_id_fk",
+ "tableFrom": "channel_memberships",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "channel_memberships_channel_id_user_id_pk": {
+ "name": "channel_memberships_channel_id_user_id_pk",
+ "columns": ["channel_id", "user_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channels": {
+ "name": "channels",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "suggested_prompts": {
+ "name": "suggested_prompts",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "allowed_groups": {
+ "name": "allowed_groups",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "package_id": {
+ "name": "package_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "override": {
+ "name": "override",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_message": {
+ "name": "last_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_message_at": {
+ "name": "last_message_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_message_agent_id": {
+ "name": "last_message_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "channels_recent_activity_idx": {
+ "name": "channels_recent_activity_idx",
+ "columns": [
+ {
+ "expression": "COALESCE(\"last_message_at\", \"created_at\") DESC",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "channels_package_id_deployment_packages_id_fk": {
+ "name": "channels_package_id_deployment_packages_id_fk",
+ "tableFrom": "channels",
+ "tableTo": "deployment_packages",
+ "columnsFrom": ["package_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "channels_last_message_agent_id_agents_id_fk": {
+ "name": "channels_last_message_agent_id_agents_id_fk",
+ "tableFrom": "channels",
+ "tableTo": "agents",
+ "columnsFrom": ["last_message_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chunks": {
+ "name": "chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "embedding": {
+ "name": "embedding",
+ "type": "vector(1536)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chunks_document_position_idx": {
+ "name": "chunks_document_position_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chunks_document_idx": {
+ "name": "chunks_document_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chunks_document_id_documents_id_fk": {
+ "name": "chunks_document_id_documents_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.connector_cursors": {
+ "name": "connector_cursors",
+ "schema": "",
+ "columns": {
+ "connector_instance_id": {
+ "name": "connector_instance_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "cursor": {
+ "name": "cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "connector_cursors_connector_instance_id_connector_instances_id_fk": {
+ "name": "connector_cursors_connector_instance_id_connector_instances_id_fk",
+ "tableFrom": "connector_cursors",
+ "tableTo": "connector_instances",
+ "columnsFrom": ["connector_instance_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.connector_instances": {
+ "name": "connector_instances",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "type": {
+ "name": "type",
+ "type": "connector_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "sync_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "source_metadata": {
+ "name": "source_metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "connector_instances_credential_id_credentials_id_fk": {
+ "name": "connector_instances_credential_id_credentials_id_fk",
+ "tableFrom": "connector_instances",
+ "tableTo": "credentials",
+ "columnsFrom": ["credential_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.credentials": {
+ "name": "credentials",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "kind": {
+ "name": "kind",
+ "type": "credential_kind",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "encrypted_value": {
+ "name": "encrypted_value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key_id": {
+ "name": "key_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.deployment_packages": {
+ "name": "deployment_packages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_path": {
+ "name": "source_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "checksum": {
+ "name": "checksum",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "loaded_at": {
+ "name": "loaded_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "deployment_packages_tenant_id_unique": {
+ "name": "deployment_packages_tenant_id_unique",
+ "nullsNotDistinct": false,
+ "columns": ["tenant_id"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_acls": {
+ "name": "document_acls",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "principal": {
+ "name": "principal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "effect": {
+ "name": "effect",
+ "type": "acl_effect",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "document_acls_document_principal_effect_idx": {
+ "name": "document_acls_document_principal_effect_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "principal",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "effect",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_acls_principal_idx": {
+ "name": "document_acls_principal_idx",
+ "columns": [
+ {
+ "expression": "principal",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_acls_document_id_documents_id_fk": {
+ "name": "document_acls_document_id_documents_id_fk",
+ "tableFrom": "document_acls",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.documents": {
+ "name": "documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "connector_instance_id": {
+ "name": "connector_instance_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "canonical_url": {
+ "name": "canonical_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "documents_connector_source_idx": {
+ "name": "documents_connector_source_idx",
+ "columns": [
+ {
+ "expression": "connector_instance_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_connector_deleted_idx": {
+ "name": "documents_connector_deleted_idx",
+ "columns": [
+ {
+ "expression": "connector_instance_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deleted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "documents_connector_instance_id_connector_instances_id_fk": {
+ "name": "documents_connector_instance_id_connector_instances_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "connector_instances",
+ "columnsFrom": ["connector_instance_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.intelligence_channel_mappings": {
+ "name": "intelligence_channel_mappings",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "channel_id": {
+ "name": "channel_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "intelligence_channel_mappings_thread_idx": {
+ "name": "intelligence_channel_mappings_thread_idx",
+ "columns": [
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "intelligence_channel_mappings_user_id_users_id_fk": {
+ "name": "intelligence_channel_mappings_user_id_users_id_fk",
+ "tableFrom": "intelligence_channel_mappings",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "intelligence_channel_mappings_channel_id_channels_id_fk": {
+ "name": "intelligence_channel_mappings_channel_id_channels_id_fk",
+ "tableFrom": "intelligence_channel_mappings",
+ "tableTo": "channels",
+ "columnsFrom": ["channel_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "intelligence_channel_mappings_user_id_channel_id_pk": {
+ "name": "intelligence_channel_mappings_user_id_channel_id_pk",
+ "columns": ["user_id", "channel_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sessions": {
+ "name": "sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sessions_user_id_users_id_fk": {
+ "name": "sessions_user_id_users_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sessions_token_unique": {
+ "name": "sessions_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sync_runs": {
+ "name": "sync_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "connector_instance_id": {
+ "name": "connector_instance_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "sync_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stats": {
+ "name": "stats",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "sync_runs_connector_started_at_idx": {
+ "name": "sync_runs_connector_started_at_idx",
+ "columns": [
+ {
+ "expression": "connector_instance_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "started_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sync_runs_connector_instance_id_connector_instances_id_fk": {
+ "name": "sync_runs_connector_instance_id_connector_instances_id_fk",
+ "tableFrom": "sync_runs",
+ "tableTo": "connector_instances",
+ "columnsFrom": ["connector_instance_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_roles": {
+ "name": "user_roles",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "role",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_roles_user_id_users_id_fk": {
+ "name": "user_roles_user_id_users_id_fk",
+ "tableFrom": "user_roles",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_roles_user_id_role_pk": {
+ "name": "user_roles_user_id_role_pk",
+ "columns": ["user_id", "role"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "groups": {
+ "name": "groups",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "nullsNotDistinct": false,
+ "columns": ["email"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verifications": {
+ "name": "verifications",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.webhook_subscriptions": {
+ "name": "webhook_subscriptions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "connector_instance_id": {
+ "name": "connector_instance_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_subscription_id": {
+ "name": "provider_subscription_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "webhook_subscriptions_connector_instance_id_connector_instances_id_fk": {
+ "name": "webhook_subscriptions_connector_instance_id_connector_instances_id_fk",
+ "tableFrom": "webhook_subscriptions",
+ "tableTo": "connector_instances",
+ "columnsFrom": ["connector_instance_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.action_policy": {
+ "name": "action_policy",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "mode": {
+ "name": "mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deny": {
+ "name": "deny",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "allow": {
+ "name": "allow",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_preferences": {
+ "name": "agent_preferences",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_preferences_user_id_users_id_fk": {
+ "name": "agent_preferences_user_id_users_id_fk",
+ "tableFrom": "agent_preferences",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_preferences_agent_id_agents_id_fk": {
+ "name": "agent_preferences_agent_id_agents_id_fk",
+ "tableFrom": "agent_preferences",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_preferences_user_id_agent_id_pk": {
+ "name": "agent_preferences_user_id_agent_id_pk",
+ "columns": ["user_id", "agent_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_profiles": {
+ "name": "agent_profiles",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role_description": {
+ "name": "role_description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "avatar_seed": {
+ "name": "avatar_seed",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "agent_visibility",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_profiles_visibility_deleted_idx": {
+ "name": "agent_profiles_visibility_deleted_idx",
+ "columns": [
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deleted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_profiles_agent_id_agents_id_fk": {
+ "name": "agent_profiles_agent_id_agents_id_fk",
+ "tableFrom": "agent_profiles",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_profiles_owner_user_id_users_id_fk": {
+ "name": "agent_profiles_owner_user_id_users_id_fk",
+ "tableFrom": "agent_profiles",
+ "tableTo": "users",
+ "columnsFrom": ["owner_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.component_exclusions": {
+ "name": "component_exclusions",
+ "schema": "",
+ "columns": {
+ "component_name": {
+ "name": "component_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "withheld_by": {
+ "name": "withheld_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "component_exclusions_component_name_components_name_fk": {
+ "name": "component_exclusions_component_name_components_name_fk",
+ "tableFrom": "component_exclusions",
+ "tableTo": "components",
+ "columnsFrom": ["component_name"],
+ "columnsTo": ["name"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "component_exclusions_agent_id_agents_id_fk": {
+ "name": "component_exclusions_agent_id_agents_id_fk",
+ "tableFrom": "component_exclusions",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "component_exclusions_component_name_agent_id_pk": {
+ "name": "component_exclusions_component_name_agent_id_pk",
+ "columns": ["component_name", "agent_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.component_functions": {
+ "name": "component_functions",
+ "schema": "",
+ "columns": {
+ "component_name": {
+ "name": "component_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "function_name": {
+ "name": "function_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "granted_by": {
+ "name": "granted_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "component_functions_component_name_components_name_fk": {
+ "name": "component_functions_component_name_components_name_fk",
+ "tableFrom": "component_functions",
+ "tableTo": "components",
+ "columnsFrom": ["component_name"],
+ "columnsTo": ["name"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "component_functions_component_name_function_name_pk": {
+ "name": "component_functions_component_name_function_name_pk",
+ "columns": ["component_name", "function_name"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.components": {
+ "name": "components",
+ "schema": "",
+ "columns": {
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "draft_description": {
+ "name": "draft_description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "published_description": {
+ "name": "published_description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published": {
+ "name": "published",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.mcp_servers": {
+ "name": "mcp_servers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "vendor": {
+ "name": "vendor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provenance": {
+ "name": "provenance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'first-party'"
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tools_refreshed_at": {
+ "name": "tools_refreshed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.mcp_tools": {
+ "name": "mcp_tools",
+ "schema": "",
+ "columns": {
+ "server_id": {
+ "name": "server_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "input_schema": {
+ "name": "input_schema",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "mcp_tools_server_id_mcp_servers_id_fk": {
+ "name": "mcp_tools_server_id_mcp_servers_id_fk",
+ "tableFrom": "mcp_tools",
+ "tableTo": "mcp_servers",
+ "columnsFrom": ["server_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "mcp_tools_server_id_name_pk": {
+ "name": "mcp_tools_server_id_name_pk",
+ "columns": ["server_id", "name"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.plugin_grants": {
+ "name": "plugin_grants",
+ "schema": "",
+ "columns": {
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ref": {
+ "name": "ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "granted_by": {
+ "name": "granted_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "plugin_grants_agent_idx": {
+ "name": "plugin_grants_agent_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "plugin_grants_agent_id_agents_id_fk": {
+ "name": "plugin_grants_agent_id_agents_id_fk",
+ "tableFrom": "plugin_grants",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "plugin_grants_kind_ref_agent_id_pk": {
+ "name": "plugin_grants_kind_ref_agent_id_pk",
+ "columns": ["kind", "ref", "agent_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sandboxed_components": {
+ "name": "sandboxed_components",
+ "schema": "",
+ "columns": {
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "draft_description": {
+ "name": "draft_description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "draft_html": {
+ "name": "draft_html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "draft_css": {
+ "name": "draft_css",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "draft_js_functions": {
+ "name": "draft_js_functions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "draft_argument_schema": {
+ "name": "draft_argument_schema",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "published_description": {
+ "name": "published_description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_html": {
+ "name": "published_html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_css": {
+ "name": "published_css",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_js_functions": {
+ "name": "published_js_functions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_argument_schema": {
+ "name": "published_argument_schema",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sample_arguments": {
+ "name": "sample_arguments",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "published": {
+ "name": "published",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authored_by": {
+ "name": "authored_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.skills": {
+ "name": "skills",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "origin": {
+ "name": "origin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'yours'"
+ },
+ "installed_by": {
+ "name": "installed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "skills_slug_key": {
+ "name": "skills_slug_key",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "skills_owner_idx": {
+ "name": "skills_owner_idx",
+ "columns": [
+ {
+ "expression": "owner_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "skills_owner_user_id_users_id_fk": {
+ "name": "skills_owner_user_id_users_id_fk",
+ "tableFrom": "skills",
+ "tableTo": "users",
+ "columnsFrom": ["owner_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.acl_effect": {
+ "name": "acl_effect",
+ "schema": "public",
+ "values": ["allow", "deny"]
+ },
+ "public.agent_type": {
+ "name": "agent_type",
+ "schema": "public",
+ "values": ["built_in", "remote_ag_ui"]
+ },
+ "public.connector_type": {
+ "name": "connector_type",
+ "schema": "public",
+ "values": ["google_drive", "onedrive"]
+ },
+ "public.credential_kind": {
+ "name": "credential_kind",
+ "schema": "public",
+ "values": ["model", "connector", "agent", "mcp"]
+ },
+ "public.role": {
+ "name": "role",
+ "schema": "public",
+ "values": ["admin", "user"]
+ },
+ "public.sync_status": {
+ "name": "sync_status",
+ "schema": "public",
+ "values": ["pending", "running", "succeeded", "failed"]
+ },
+ "public.agent_visibility": {
+ "name": "agent_visibility",
+ "schema": "public",
+ "values": ["public", "private"]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/server/package.json b/server/package.json
new file mode 100644
index 00000000..304377f7
--- /dev/null
+++ b/server/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "server",
+ "license": "MIT",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "scripts": {
+ "build": "tsc --noEmit",
+ "db:generate": "bun --env-file=../.env drizzle-kit generate --config=drizzle.config.ts",
+ "db:migrate": "bun --env-file=../.env drizzle-kit migrate --config=drizzle.config.ts",
+ "dev": "bun --env-file=../.env --watch src/index.ts",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@ag-ui/client": "0.0.57",
+ "@better-auth/drizzle-adapter": "^1.6.27",
+ "@copilotkit/runtime": "1.67.1",
+ "@modelcontextprotocol/sdk": "^1.30.0",
+ "better-auth": "^1.6.27",
+ "cel-js": "^0.8.2",
+ "drizzle-orm": "^0.45.2",
+ "hono": "^4.10.0",
+ "postgres": "^3.4.9",
+ "yaml": "^2.9.0"
+ },
+ "devDependencies": {
+ "@copilotkit/aimock": "^1.38.0",
+ "drizzle-kit": "^0.31.10",
+ "eventsource": "3.0.7"
+ }
+}
diff --git a/server/src/agents/endpoint.ts b/server/src/agents/endpoint.ts
new file mode 100644
index 00000000..e3777ed6
--- /dev/null
+++ b/server/src/agents/endpoint.ts
@@ -0,0 +1,57 @@
+import { checkNavigationTarget } from "../computer/target";
+
+/**
+ * Where an external agent lives, and whether we are willing to talk to it.
+ *
+ * Registering an agent hands us a URL that this server will POST to on every single run. That is a
+ * server-side request to an address a user chose,
+ * which is the textbook shape of SSRF: without a check, `http://169.254.169.254/` is a registrable
+ * "agent" and the runtime will happily fetch cloud credentials on a user's behalf, from inside the
+ * deployment, on a schedule.
+ *
+ * Ordering is the control. If the private-host escape hatch is consulted before the
+ * deny-list, the cloud metadata endpoint is reachable under the configuration every developer
+ * actually runs. Never-allowed hosts are refused first, ahead of any opt-in, which is why this reuses
+ * `checkNavigationTarget` rather than a second checker that would have to get the ordering right
+ * again.
+ *
+ * A developer's own agent legitimately lives at
+ * `http://localhost:4200/ag-ui`, so on a laptop the private-host opt-in is ON, which is the case where
+ * this check is weakest. That is the same trade navigation makes, and the reason the never-allowed
+ * list is checked ahead of it. In a hosted deployment the opt-in is off and a private address is
+ * refused.
+ */
+
+export type EndpointVerdict =
+ | { allowed: true; url: string }
+ | { allowed: false; reason: string };
+
+/**
+ * Check an agent endpoint before it is stored.
+ *
+ * Refused at registration rather than at run time: a URL that must never be fetched should
+ * never reach the database, because everything downstream treats a stored agent as trustworthy.
+ */
+export function checkAgentEndpoint(
+ raw: unknown,
+ options: { allowPrivateHosts?: boolean } = {},
+): EndpointVerdict {
+ if (typeof raw !== "string" || !raw.trim()) {
+ return { allowed: false, reason: "An agent needs a web address." };
+ }
+
+ const verdict = checkNavigationTarget(raw.trim(), options);
+ if (!verdict.allowed) {
+ // The navigation wording talks about "the assistant opening" a page, which is not what is
+ // happening here, so the reason is restated for the form surface.
+ return {
+ allowed: false,
+ reason: verdict.reason.replace(
+ /the assistant is never allowed to open it\.|the assistant is not allowed to open it\./,
+ "an agent may not live there.",
+ ),
+ };
+ }
+
+ return { allowed: true, url: verdict.url };
+}
diff --git a/server/src/agents/invocation.ts b/server/src/agents/invocation.ts
new file mode 100644
index 00000000..592405b6
--- /dev/null
+++ b/server/src/agents/invocation.ts
@@ -0,0 +1,20 @@
+type Agent = {
+ id: string;
+ type: "built_in" | "remote_ag_ui";
+ available: boolean;
+ reason?: string;
+};
+type Response = { text: string; citations: unknown[] };
+
+export function createAgentInvoker(ports: {
+ knowledge: (question: string) => Promise<Response>;
+ remote: (agentId: string, question: string) => Promise<Response>;
+}) {
+ return async (agent: Agent, question: string) => {
+ if (!agent.available)
+ throw new Error(agent.reason ?? "Agent is unavailable.");
+ return agent.type === "built_in"
+ ? ports.knowledge(question)
+ : ports.remote(agent.id, question);
+ };
+}
diff --git a/server/src/agents/profile-store.ts b/server/src/agents/profile-store.ts
new file mode 100644
index 00000000..8ddfcfc7
--- /dev/null
+++ b/server/src/agents/profile-store.ts
@@ -0,0 +1,408 @@
+import { and, eq, isNotNull, isNull, or } from "drizzle-orm";
+import type { CredentialStore } from "../credentials";
+import type { Database } from "../db/client";
+import {
+ agentPreferences,
+ agentProfiles,
+ agents,
+ deploymentPackages,
+} from "../db/schema";
+import { authFromConfiguration, storeAgentAuth } from "./auth-header";
+import { canManageAgent } from "./profile-policy";
+import type {
+ AgentActor,
+ AgentProfile,
+ CreateAgentInput,
+} from "./profile-types";
+
+type Transaction = Parameters<Parameters<Database["transaction"]>[0]>[0];
+type DatabaseExecutor = Pick<Database, "select"> | Pick<Transaction, "select">;
+
+/** Something that can read profiles: the pool, or a caller's open transaction. */
+export type ProfileReadExecutor = DatabaseExecutor;
+
+export type AgentProfileStore = {
+ list(actor: AgentActor, hidden?: boolean): Promise<AgentProfile[]>;
+ get(actor: AgentActor, id: string): Promise<AgentProfile | null>;
+ /**
+ * `get`, but on the caller's own transaction and holding the profile against deletion until that
+ * transaction ends.
+ *
+ * A caller that writes rows referencing an agent has to validate it here rather than through
+ * `get`. `get` borrows a second pooled connection, which deadlocks the caller's transaction once
+ * every connection is held by one, and reads an unlocked snapshot, so a deletion committing
+ * between the check and the insert leaves rows pointing at an agent that no longer runs.
+ */
+ getWithin(
+ executor: ProfileReadExecutor,
+ actor: AgentActor,
+ id: string,
+ ): Promise<AgentProfile | null>;
+ create(actor: AgentActor, input: CreateAgentInput): Promise<AgentProfile>;
+ update(
+ actor: AgentActor,
+ id: string,
+ input: CreateAgentInput,
+ ): Promise<AgentProfile>;
+ duplicate(actor: AgentActor, id: string): Promise<AgentProfile>;
+ setHidden(actor: AgentActor, id: string, hidden: boolean): Promise<void>;
+ softDelete(actor: AgentActor, id: string): Promise<void>;
+};
+
+export class AgentNotFoundError extends Error {
+ constructor(id: string) {
+ super(`Agent ${id} was not found.`);
+ this.name = "AgentNotFoundError";
+ }
+}
+
+export class AgentNotManageableError extends Error {
+ constructor(id: string) {
+ super(`Agent ${id} cannot be managed by this actor.`);
+ this.name = "AgentNotManageableError";
+ }
+}
+
+export class ProtectedAgentError extends Error {
+ constructor(id: string) {
+ super(`Agent ${id} is protected.`);
+ this.name = "ProtectedAgentError";
+ }
+}
+
+const joinedProjection = {
+ id: agents.id,
+ name: agents.name,
+ title: agentProfiles.title,
+ roleDescription: agentProfiles.roleDescription,
+ avatarSeed: agentProfiles.avatarSeed,
+ visibility: agentProfiles.visibility,
+ ownerUserId: agentProfiles.ownerUserId,
+ packageId: deploymentPackages.id,
+ hiddenAt: agentPreferences.hiddenAt,
+ deletedAt: agentProfiles.deletedAt,
+ configuration: agents.configuration,
+};
+
+function joinedProfiles(executor: DatabaseExecutor, actor: AgentActor) {
+ return executor
+ .select(joinedProjection)
+ .from(agents)
+ .innerJoin(agentProfiles, eq(agentProfiles.agentId, agents.id))
+ .leftJoin(
+ agentPreferences,
+ and(
+ eq(agentPreferences.agentId, agents.id),
+ eq(agentPreferences.userId, actor.id),
+ ),
+ )
+ .leftJoin(deploymentPackages, eq(deploymentPackages.id, agents.packageId));
+}
+
+function accessFilter(actor: AgentActor) {
+ if (actor.role === "admin") return undefined;
+
+ return or(
+ eq(agentProfiles.visibility, "public"),
+ eq(agentProfiles.ownerUserId, actor.id),
+ );
+}
+
+function mapProfile(
+ row: Awaited<
+ ReturnType<ReturnType<typeof joinedProfiles>["execute"]>
+ >[number],
+): AgentProfile {
+ return {
+ id: row.id,
+ name: row.name,
+ title: row.title,
+ roleDescription: row.roleDescription,
+ avatarSeed: row.avatarSeed,
+ visibility: row.visibility,
+ ownerUserId: row.ownerUserId,
+ systemOwned: row.packageId !== null,
+ hidden: row.hiddenAt !== null,
+ deletedAt: row.deletedAt,
+ endpoint: endpointOf(row.configuration),
+ // Whether a key is set, never which. The form needs to show "a key is set" so a person does not
+ // wipe one by saving an unrelated edit; showing the value would put a secret in a screenshot.
+ hasAuth: authFromConfiguration(row.configuration) !== null,
+ };
+}
+
+/**
+ * The AG-UI address this teammate runs on, read back out of its stored configuration.
+ *
+ * Needed so an edit does not destroy it. The edit form is the same form as create, so without the
+ * current endpoint to fill it with, saving a change of title would submit an empty endpoint and
+ * convert an external agent back into the built-in one. That failure is silent and total: the Bot
+ * keeps working, so nothing looks broken, and it is simply no longer their agent.
+ */
+function endpointOf(configuration: unknown): string | null {
+ if (!configuration || typeof configuration !== "object") return null;
+ const endpoint = (configuration as { endpoint?: unknown }).endpoint;
+ return typeof endpoint === "string" ? endpoint : null;
+}
+
+async function findAccessibleProfile(
+ executor: DatabaseExecutor,
+ actor: AgentActor,
+ id: string,
+): Promise<AgentProfile | null> {
+ const [row] = await joinedProfiles(executor, actor).where(
+ and(
+ eq(agents.id, id),
+ isNull(agentProfiles.deletedAt),
+ accessFilter(actor),
+ ),
+ );
+ return row ? mapProfile(row) : null;
+}
+
+async function lockProfileMutationRows(executor: DatabaseExecutor, id: string) {
+ await executor
+ .select({ id: agents.id })
+ .from(agents)
+ .where(eq(agents.id, id))
+ .for("update");
+ await executor
+ .select({ agentId: agentProfiles.agentId })
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, id))
+ .for("update");
+}
+
+/**
+ * Share-lock a profile so it stays readable to concurrent callers but cannot be deleted or renamed
+ * until this transaction ends. `lockProfileMutationRows` takes the exclusive counterpart, so a
+ * deletion racing a reference blocks here instead of committing underneath it.
+ */
+async function lockProfileReadRow(executor: DatabaseExecutor, id: string) {
+ await executor
+ .select({ agentId: agentProfiles.agentId })
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, id))
+ .for("share");
+}
+
+function requireManageable(actor: AgentActor, profile: AgentProfile) {
+ if (profile.systemOwned) throw new ProtectedAgentError(profile.id);
+ if (!canManageAgent(actor, profile)) {
+ throw new AgentNotManageableError(profile.id);
+ }
+}
+
+function newAgentId() {
+ return `agent_${crypto.randomUUID()}`;
+}
+
+export function createAgentProfileStore(
+ database: Database,
+ managedAgentAgUiUrl: URL,
+ /**
+ * Where a customer agent's key is kept. Optional so a deployment without a vault still runs; an
+ * agent with a key then simply cannot be created, which is better than storing it in the clear.
+ */
+ vault?: { store: CredentialStore; encryptionKey: string },
+): AgentProfileStore {
+ const managedConfiguration = {
+ endpoint: managedAgentAgUiUrl.toString(),
+ };
+
+ return {
+ async list(actor, hidden = false) {
+ const rows = await joinedProfiles(database, actor).where(
+ and(
+ isNull(agentProfiles.deletedAt),
+ accessFilter(actor),
+ hidden
+ ? isNotNull(agentPreferences.hiddenAt)
+ : isNull(agentPreferences.hiddenAt),
+ ),
+ );
+ return rows.map(mapProfile);
+ },
+
+ get(actor, id) {
+ return findAccessibleProfile(database, actor, id);
+ },
+
+ async getWithin(executor, actor, id) {
+ await lockProfileReadRow(executor, id);
+ return findAccessibleProfile(executor, actor, id);
+ },
+
+ create(actor, input) {
+ return database.transaction(async (transaction) => {
+ const id = newAgentId();
+ await transaction.insert(agents).values({
+ id,
+ name: input.name,
+ type: "remote_ag_ui",
+ // Their endpoint if they gave one, ours if they did not. Validated before it reaches here;
+ // see endpoint.ts for why a stored URL is a security decision and not a text field.
+ //
+ // The key, if there is one, goes to the vault and only its reference is stored here. See
+ // auth-header.ts for why a bearer token must not sit next to the endpoint.
+ configuration: {
+ ...(input.endpoint
+ ? { endpoint: input.endpoint }
+ : managedConfiguration),
+ ...(input.auth && vault
+ ? {
+ auth: await storeAgentAuth({
+ store: vault.store,
+ encryptionKey: vault.encryptionKey,
+ agentId: id,
+ header: input.auth.header,
+ value: input.auth.value,
+ }),
+ }
+ : {}),
+ },
+ });
+ await transaction.insert(agentProfiles).values({
+ agentId: id,
+ ownerUserId: actor.id,
+ title: input.title,
+ roleDescription: input.roleDescription,
+ avatarSeed: id,
+ visibility: input.visibility,
+ });
+
+ const profile = await findAccessibleProfile(transaction, actor, id);
+ if (!profile) throw new AgentNotFoundError(id);
+ return profile;
+ });
+ },
+
+ update(actor, id, input) {
+ return database.transaction(
+ async (transaction) => {
+ await lockProfileMutationRows(transaction, id);
+ const profile = await findAccessibleProfile(transaction, actor, id);
+ if (!profile) throw new AgentNotFoundError(id);
+ requireManageable(actor, profile);
+
+ const updatedAt = new Date();
+ /**
+ * The endpoint and the key change here too, not only at creation.
+ *
+ * The form sends both and the route validates both, so an edit that dropped them looked
+ * like it had worked: the screen reported success and the Bot kept answering at the old
+ * address, which is the worst way to move an endpoint. A key is replaced only when one is
+ * supplied, because the form cannot show what is stored and sending nothing means "leave
+ * it alone" rather than "remove it".
+ */
+ const [row] = await transaction
+ .select({ configuration: agents.configuration })
+ .from(agents)
+ .where(eq(agents.id, id))
+ .limit(1);
+ const configuration = {
+ ...((row?.configuration ?? {}) as Record<string, unknown>),
+ ...(input.endpoint ? { endpoint: input.endpoint } : {}),
+ ...(input.auth && vault
+ ? {
+ auth: await storeAgentAuth({
+ store: vault.store,
+ encryptionKey: vault.encryptionKey,
+ agentId: id,
+ header: input.auth.header,
+ value: input.auth.value,
+ }),
+ }
+ : {}),
+ };
+ await transaction
+ .update(agents)
+ .set({ name: input.name, configuration, updatedAt })
+ .where(eq(agents.id, id));
+ await transaction
+ .update(agentProfiles)
+ .set({
+ title: input.title,
+ roleDescription: input.roleDescription,
+ visibility: input.visibility,
+ updatedAt,
+ })
+ .where(eq(agentProfiles.agentId, id));
+
+ const updated = await findAccessibleProfile(transaction, actor, id);
+ if (!updated) throw new AgentNotFoundError(id);
+ return updated;
+ },
+ { isolationLevel: "read committed" },
+ );
+ },
+
+ duplicate(actor, id) {
+ return database.transaction(async (transaction) => {
+ const source = await findAccessibleProfile(transaction, actor, id);
+ if (!source) throw new AgentNotFoundError(id);
+
+ const duplicateId = newAgentId();
+ await transaction.insert(agents).values({
+ id: duplicateId,
+ name: source.name,
+ type: "remote_ag_ui",
+ configuration: managedConfiguration,
+ });
+ await transaction.insert(agentProfiles).values({
+ agentId: duplicateId,
+ ownerUserId: actor.id,
+ title: source.title,
+ roleDescription: source.roleDescription,
+ avatarSeed: source.avatarSeed,
+ visibility: "private",
+ });
+
+ const duplicate = await findAccessibleProfile(
+ transaction,
+ actor,
+ duplicateId,
+ );
+ if (!duplicate) throw new AgentNotFoundError(duplicateId);
+ return duplicate;
+ });
+ },
+
+ setHidden(actor, id, hidden) {
+ return database.transaction(async (transaction) => {
+ const profile = await findAccessibleProfile(transaction, actor, id);
+ if (!profile) throw new AgentNotFoundError(id);
+
+ await transaction
+ .insert(agentPreferences)
+ .values({
+ userId: actor.id,
+ agentId: id,
+ hiddenAt: hidden ? new Date() : null,
+ })
+ .onConflictDoUpdate({
+ target: [agentPreferences.userId, agentPreferences.agentId],
+ set: { hiddenAt: hidden ? new Date() : null },
+ });
+ });
+ },
+
+ softDelete(actor, id) {
+ return database.transaction(
+ async (transaction) => {
+ await lockProfileMutationRows(transaction, id);
+ const profile = await findAccessibleProfile(transaction, actor, id);
+ if (!profile) throw new AgentNotFoundError(id);
+ requireManageable(actor, profile);
+
+ const deletedAt = new Date();
+ await transaction
+ .update(agentProfiles)
+ .set({ deletedAt, updatedAt: deletedAt })
+ .where(eq(agentProfiles.agentId, id));
+ },
+ { isolationLevel: "read committed" },
+ );
+ },
+ };
+}
diff --git a/server/src/agents/profile-types.ts b/server/src/agents/profile-types.ts
new file mode 100644
index 00000000..7aa34f59
--- /dev/null
+++ b/server/src/agents/profile-types.ts
@@ -0,0 +1,44 @@
+export type AgentVisibility = "public" | "private";
+
+export type AgentActor = {
+ id: string;
+ role: "admin" | "user";
+};
+
+export type AgentProfile = {
+ id: string;
+ name: string;
+ title: string;
+ roleDescription: string;
+ avatarSeed: string;
+ visibility: AgentVisibility;
+ ownerUserId: string | null;
+ systemOwned: boolean;
+ hidden: boolean;
+ deletedAt: Date | null;
+ /** Where this teammate runs. Null for the Bot in the box. */
+ endpoint: string | null;
+ /** Whether a key is set for it. Never the key. */
+ hasAuth: boolean;
+};
+
+export type CreateAgentInput = Pick<
+ AgentProfile,
+ "name" | "title" | "roleDescription" | "visibility"
+> & {
+ /**
+ * The AG-UI endpoint this Bot runs on, or undefined for the one in the box.
+ *
+ * This field is the AG-UI endpoint for a customer-provided agent. Without it the Bot runs on the
+ * built-in endpoint.
+ */
+ endpoint?: string;
+ /**
+ * A key this agent sits behind, if any.
+ *
+ * Write-only. It goes to the vault and is never read back to a person: the edit form shows that a
+ * key is set, not what it is. Absent on an update means "leave whatever is there alone", which is
+ * why it is optional rather than defaulting to empty; a blank field must not drop a key.
+ */
+ auth?: { header: string; value: string };
+};
diff --git a/server/src/agents/registry.ts b/server/src/agents/registry.ts
new file mode 100644
index 00000000..5dde57b0
--- /dev/null
+++ b/server/src/agents/registry.ts
@@ -0,0 +1,50 @@
+type BuiltInAgent = {
+ id: string;
+ name: string;
+ type: "built_in";
+ credentialRef: string;
+};
+type RemoteAgent = {
+ id: string;
+ name: string;
+ type: "remote_ag_ui";
+ endpoint: string;
+};
+type SeededAgent = BuiltInAgent | RemoteAgent;
+
+export function createAgentRegistry(
+ agents: SeededAgent[],
+ activeCredentials: Set<string>,
+) {
+ return agents.map((agent) => {
+ if (agent.type === "built_in") {
+ return activeCredentials.has(agent.credentialRef)
+ ? { id: agent.id, name: agent.name, type: agent.type, available: true }
+ : {
+ id: agent.id,
+ name: agent.name,
+ type: agent.type,
+ available: false,
+ reason: "Model credential is not configured.",
+ };
+ }
+ const available = isHttpUrl(agent.endpoint);
+ return available
+ ? { id: agent.id, name: agent.name, type: agent.type, available: true }
+ : {
+ id: agent.id,
+ name: agent.name,
+ type: agent.type,
+ available: false,
+ reason: "AG-UI endpoint is invalid.",
+ };
+ });
+}
+
+function isHttpUrl(value: string) {
+ try {
+ return ["http:", "https:"].includes(new URL(value).protocol);
+ } catch {
+ return false;
+ }
+}
diff --git a/server/src/agents/runtime-agents.ts b/server/src/agents/runtime-agents.ts
new file mode 100644
index 00000000..4228b2a9
--- /dev/null
+++ b/server/src/agents/runtime-agents.ts
@@ -0,0 +1,110 @@
+import { and, eq, isNotNull, isNull, or } from "drizzle-orm";
+import { type RegisteredAgent, registeredAgentFromRow } from "../copilot";
+import type { CredentialSecretReader } from "../credentials";
+import type { Database } from "../db/client";
+import {
+ agentProfiles,
+ agents,
+ channelAgents,
+ channelMemberships,
+} from "../db/schema";
+import { agentAuthHeaders, authFromConfiguration } from "./auth-header";
+import type { AgentActor } from "./profile-types";
+
+/**
+ * Read the agents one person may run, on every request.
+ *
+ * The filtering is in the query, not in JavaScript afterwards: a private teammate must never be
+ * read into the process for an actor who cannot see it, and "we fetched it but did not show it" is
+ * the shape most accidental disclosures take.
+ */
+export function createRuntimeAgentLoader(
+ database: Database,
+ /** Resolves a customer agent's key at load time. Absent means no agent can carry one. */
+ vault?: { reader: CredentialSecretReader; encryptionKey: string },
+) {
+ return async (actor: AgentActor): Promise<RegisteredAgent[]> => {
+ const [active, tombstones] = await Promise.all([
+ selectActiveAgents(database, actor),
+ selectTombstoneAgents(database, actor),
+ ]);
+
+ // A row whose configuration cannot be understood is skipped rather than mounted as a broken
+ // agent. Tombstones are appended after, and never overwrite a live agent of the same id.
+ const registered = new Map<string, RegisteredAgent>();
+ for (const row of active) {
+ const agent = registeredAgentFromRow(row);
+ if (!agent) continue;
+ // The key is resolved per load, rather than being cached on the row: revoking a
+ // credential then takes effect on the next run rather than on the next restart.
+ if (agent.type === "remote_ag_ui" && vault) {
+ const headers = await agentAuthHeaders({
+ reader: vault.reader,
+ encryptionKey: vault.encryptionKey,
+ auth: authFromConfiguration(row.configuration),
+ });
+ if (headers) agent.headers = headers;
+ }
+ registered.set(agent.id, agent);
+ }
+ for (const row of tombstones) {
+ if (registered.has(row.id)) continue;
+ registered.set(row.id, {
+ id: row.id,
+ name: row.name,
+ type: "unavailable",
+ reason: `${row.name} has been deleted and can no longer run. Its conversations remain readable.`,
+ });
+ }
+
+ return [...registered.values()];
+ };
+}
+
+function selectActiveAgents(database: Database, actor: AgentActor) {
+ return database
+ .select({
+ id: agents.id,
+ name: agents.name,
+ type: agents.type,
+ configuration: agents.configuration,
+ title: agentProfiles.title,
+ roleDescription: agentProfiles.roleDescription,
+ })
+ .from(agents)
+ .innerJoin(agentProfiles, eq(agentProfiles.agentId, agents.id))
+ .where(
+ and(
+ isNull(agentProfiles.deletedAt),
+ actor.role === "admin"
+ ? undefined
+ : or(
+ eq(agentProfiles.visibility, "public"),
+ eq(agentProfiles.ownerUserId, actor.id),
+ ),
+ ),
+ );
+}
+
+/**
+ * Deleted teammates the caller still has history with.
+ *
+ * Registered so Intelligence can restore the thread the person is reading. Membership of a channel
+ * the agent worked in is what authorizes this, not the profile's visibility, which is why deleting
+ * a teammate leaves its conversations readable instead of erasing them.
+ */
+function selectTombstoneAgents(database: Database, actor: AgentActor) {
+ return database
+ .selectDistinct({ id: agents.id, name: agents.name })
+ .from(agents)
+ .innerJoin(agentProfiles, eq(agentProfiles.agentId, agents.id))
+ .innerJoin(channelAgents, eq(channelAgents.agentId, agents.id))
+ .innerJoin(
+ channelMemberships,
+ and(
+ eq(channelMemberships.channelId, channelAgents.channelId),
+ eq(channelMemberships.userId, actor.id),
+ ),
+ )
+ .where(isNotNull(agentProfiles.deletedAt));
+}
diff --git a/server/src/auth/roles.ts b/server/src/auth/roles.ts
new file mode 100644
index 00000000..caae861c
--- /dev/null
+++ b/server/src/auth/roles.ts
@@ -0,0 +1,14 @@
+export type OpenBotRole = "admin" | "user";
+
+export function roleForEmail(
+ email: string,
+ initialAdminEmails: readonly string[],
+): OpenBotRole {
+ const normalizedEmail = email.trim().toLowerCase();
+
+ return initialAdminEmails.some(
+ (adminEmail) => adminEmail.trim().toLowerCase() === normalizedEmail,
+ )
+ ? "admin"
+ : "user";
+}
diff --git a/server/src/channels/events.ts b/server/src/channels/events.ts
new file mode 100644
index 00000000..3bd6cd12
--- /dev/null
+++ b/server/src/channels/events.ts
@@ -0,0 +1,103 @@
+import postgres from "postgres";
+
+/**
+ * Live channel activity, from whoever ran an agent to everybody else in the channel.
+ *
+ * The person who ran it already has the reply and reports it over HTTP; this is the other direction,
+ * telling the channel's other members that something was said. It is an optimisation and never a
+ * source of truth: the roster query stays authoritative, and a client that misses events while
+ * disconnected recovers by refetching on reconnect. Nothing may be knowable only through the socket.
+ *
+ * Delivery goes through Postgres rather than an in-process list, because an in-process list is
+ * silently wrong the moment a second server instance exists: the writer is on one and the listener
+ * on the other, and the message is never delivered.
+ */
+
+export const CHANNEL_ACTIVITY_TOPIC = "channel_activity";
+
+export type ChannelActivityEvent = {
+ channelId: string;
+ /** Who may receive it. Resolved by the writer, which already had to check membership. */
+ memberIds: string[];
+ lastMessage: string | null;
+ lastMessageAt: string | null;
+ lastMessageAgentId: string | null;
+};
+
+type Send = (payload: string) => void;
+
+export type ChannelEventHub = {
+ /** Attach a connection for a person. Returns the detach. */
+ register(userId: string, send: Send): () => void;
+ /** Fan one event out to this instance's own connections. */
+ deliver(event: ChannelActivityEvent): void;
+ connectionCount(userId: string): number;
+};
+
+export function createChannelEventHub(): ChannelEventHub {
+ const connections = new Map<string, Set<Send>>();
+
+ return {
+ register(userId, send) {
+ const existing = connections.get(userId) ?? new Set<Send>();
+ existing.add(send);
+ connections.set(userId, existing);
+
+ return () => {
+ const remaining = connections.get(userId);
+ if (!remaining) return;
+ remaining.delete(send);
+ // Dropped entirely rather than left empty, so a long-lived process does not accumulate a
+ // set per person who ever connected.
+ if (remaining.size === 0) connections.delete(userId);
+ };
+ },
+
+ deliver(event) {
+ for (const userId of event.memberIds) {
+ for (const send of connections.get(userId) ?? []) {
+ try {
+ send(JSON.stringify(event));
+ } catch {
+ // A connection that cannot be written to is one that is closing. Its own close handler
+ // detaches it; failing here would deny the event to everybody after it in the set.
+ }
+ }
+ }
+ },
+
+ connectionCount(userId) {
+ return connections.get(userId)?.size ?? 0;
+ },
+ };
+}
+
+export type ChannelActivityListener = { stop: () => Promise<void> };
+
+/**
+ * Listen for activity announced by any instance, including this one.
+ *
+ * On its own connection, because `LISTEN` holds one for the life of the subscription: taken from the
+ * pool, it would be a connection the rest of the server never gets back.
+ */
+export async function startChannelActivityListener(
+ databaseUrl: string,
+ hub: ChannelEventHub,
+): Promise<ChannelActivityListener> {
+ const connection = postgres(databaseUrl, { max: 1 });
+
+ await connection.listen(CHANNEL_ACTIVITY_TOPIC, (payload) => {
+ try {
+ hub.deliver(JSON.parse(payload) as ChannelActivityEvent);
+ } catch {
+ // A payload we cannot read is not a reason to tear down the subscription: the roster query is
+ // still correct, and the next refetch shows whatever this event would have.
+ }
+ });
+
+ return {
+ stop: async () => {
+ await connection.end();
+ },
+ };
+}
diff --git a/server/src/channels/socket.ts b/server/src/channels/socket.ts
new file mode 100644
index 00000000..19470610
--- /dev/null
+++ b/server/src/channels/socket.ts
@@ -0,0 +1,13 @@
+import { createBunWebSocket } from "hono/bun";
+
+/**
+ * The one WebSocket adapter for the process.
+ *
+ * `createBunWebSocket` pairs a route-side `upgradeWebSocket` with a server-side `websocket` handler,
+ * and the two halves have to come from the same call. Bun is given the handler once, when the
+ * server starts, and it has to be the one the routes upgraded through. Calling it per route would
+ * upgrade connections into a handler nothing is listening on.
+ */
+const { upgradeWebSocket, websocket } = createBunWebSocket();
+
+export { upgradeWebSocket, websocket };
diff --git a/server/src/channels/thread-identity.ts b/server/src/channels/thread-identity.ts
new file mode 100644
index 00000000..7e76b020
--- /dev/null
+++ b/server/src/channels/thread-identity.ts
@@ -0,0 +1,89 @@
+import { createHash, randomBytes } from "node:crypto";
+
+/**
+ * Which deployment a conversation belongs to, carried by the thread's own id.
+ *
+ * Threads live in an Intelligence project, and one project can serve more than one deployment: a
+ * development copy of production shares its key, and listing a Bot's threads returns both
+ * deployments' conversations with nothing to tell them apart. The platform keeps no field a
+ * deployment can write its own name into, and lists threads by user and agent only, so the single
+ * identifier a deployment controls is the id it mints for the thread.
+ *
+ * So the id carries it: six bytes of a digest of the deployment's name lead the UUID and the rest is
+ * random. That is enough to ask whether a thread is this deployment's without having seen it before,
+ * which is what a workspace whose database is gone would need in order to take its own conversations
+ * back and leave another deployment's alone.
+ *
+ * Version 8 because RFC 9562 reserves that version for a layout the vendor decides. A version 4 UUID
+ * asserts that every bit outside the version and variant is random, and these are not.
+ *
+ * The digest is not a secret and is not meant to be one. A thread id is already visible to anyone who
+ * can list the project, and this says only that two threads came from the same deployment.
+ */
+
+/** Enough of the digest to separate deployments, and short enough to leave the id mostly random. */
+const FINGERPRINT_BYTES = 6;
+
+const UUID_V8 = 0x80;
+const VARIANT_RFC = 0x80;
+
+export type ThreadIdentity = {
+ /** A thread id belonging to this deployment. */
+ mint: () => string;
+ /**
+ * Whether this deployment minted the thread id.
+ *
+ * False for a thread minted before a deployment had a name, which is not the same as knowing it
+ * belongs to somebody else. A caller offering to take conversations back has to treat the two
+ * differently: one is certainly yours, the other is only possibly.
+ */
+ owns: (threadId: string) => boolean;
+};
+
+function fingerprintOf(deploymentId: string): Buffer {
+ return createHash("sha256")
+ .update(deploymentId)
+ .digest()
+ .subarray(0, FINGERPRINT_BYTES);
+}
+
+function format(bytes: Buffer): string {
+ const hex = bytes.toString("hex");
+ return [
+ hex.slice(0, 8),
+ hex.slice(8, 12),
+ hex.slice(12, 16),
+ hex.slice(16, 20),
+ hex.slice(20, 32),
+ ].join("-");
+}
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** The 16 bytes a UUID string stands for, or null if it is not one. */
+function bytesOf(threadId: string): Buffer | null {
+ if (!UUID.test(threadId)) return null;
+ return Buffer.from(threadId.replaceAll("-", ""), "hex");
+}
+
+export function createThreadIdentity(deploymentId: string): ThreadIdentity {
+ const fingerprint = fingerprintOf(deploymentId);
+
+ return {
+ mint() {
+ const bytes = randomBytes(16);
+ fingerprint.copy(bytes, 0);
+ // Version and variant are fixed by the format and sit outside the fingerprint's six bytes.
+ bytes[6] = (bytes[6] & 0x0f) | UUID_V8;
+ bytes[8] = (bytes[8] & 0x3f) | VARIANT_RFC;
+ return format(bytes);
+ },
+
+ owns(threadId) {
+ const bytes = bytesOf(threadId);
+ if (!bytes) return false;
+ if ((bytes[6] & 0xf0) !== UUID_V8) return false;
+ return bytes.subarray(0, FINGERPRINT_BYTES).equals(fingerprint);
+ },
+ };
+}
diff --git a/server/src/channels/thread-routes.ts b/server/src/channels/thread-routes.ts
new file mode 100644
index 00000000..7a53b1a7
--- /dev/null
+++ b/server/src/channels/thread-routes.ts
@@ -0,0 +1,28 @@
+import { Hono } from "hono";
+import type { MiddlewareHandler } from "hono";
+import type { AppVariables } from "../auth/guards";
+import type { ThreadIdentity } from "./thread-identity";
+
+/**
+ * A thread id for a conversation this deployment keeps no channel for.
+ *
+ * The direct Bot chat is CopilotKit's own component, and left to itself it generates an id in the
+ * browser that says nothing about where the conversation came from. Minting it here puts those
+ * threads in the same namespace as every channel's, so one project shared by two deployments can
+ * still tell whose conversations are whose.
+ *
+ * Behind the session guard because a thread id is the name of somewhere a conversation will be
+ * stored, and there is no reason for anybody signed out to be handed one.
+ */
+export function createThreadRoutes(
+ identity: ThreadIdentity,
+ requireUser: MiddlewareHandler<{ Variables: AppVariables }>,
+) {
+ const routes = new Hono<{ Variables: AppVariables }>();
+
+ routes.post("/mint", requireUser, (context) =>
+ context.json({ threadId: identity.mint() }),
+ );
+
+ return routes;
+}
diff --git a/server/src/components/functions.ts b/server/src/components/functions.ts
new file mode 100644
index 00000000..af98ab59
--- /dev/null
+++ b/server/src/components/functions.ts
@@ -0,0 +1,109 @@
+import { sql } from "drizzle-orm";
+import type { Database } from "../db/client";
+
+/**
+ * The data a component may fetch for itself, instead of being handed figures by a model.
+ *
+ * A component fetches its own data because a component drawn from the model's arguments alone means
+ * every number on screen is a number a model produced. For a chart of revenue that is a
+ * hallucination with axes. Here the model passes a query, which report, over how many days, and the
+ * figures come from this deployment. The model never sees them and cannot invent them.
+ *
+ * The allow-list is enforced on the server, not in the browser. A compiled React component has
+ * the whole application: it can call `fetch` itself, so a list of permitted functions held beside it
+ * is documentation, not a control. The only place a permission can be enforced is the place that
+ * holds the data. `useSandboxFunctions` is the browser-side equivalent for code running in an
+ * isolated frame, which is a different path.
+ *
+ * Arguments are checked here too, for the same reason: whatever the browser sends is a claim.
+ * Bounded rather than merely parsed, a report is a thing somebody watches load, so "how many days"
+ * has a ceiling instead of trusting a number that arrived over the wire.
+ *
+ * These read the trail directly.
+ *
+ * What these read. A fresh deployment has no connector and no documents, so the worked example reads
+ * the one dataset that is always real and always present: this deployment's own audit trail. The seam
+ * is the point, a function that reads a customer's connector is another entry in this list, and
+ * nothing above it changes.
+ */
+
+export type DataFunction = {
+ name: string;
+ /** What an administrator granting it needs to know. Never read by a model. */
+ description: string;
+ /** What it reads, in a few words, for the Admin page and for the audit row. */
+ reads: string;
+ run: (database: Database, args: Record<string, unknown>) => Promise<unknown>;
+};
+
+/** A whole number from an untrusted body, clamped into a range it is safe to run. */
+function bounded(
+ value: unknown,
+ { fallback, min, max }: { fallback: number; min: number; max: number },
+): number {
+ const parsed =
+ typeof value === "number" && Number.isFinite(value)
+ ? Math.trunc(value)
+ : Number.NaN;
+ if (Number.isNaN(parsed)) return fallback;
+ return Math.min(max, Math.max(min, parsed));
+}
+
+export const DATA_FUNCTIONS: DataFunction[] = [
+ {
+ name: "botActivity",
+ description:
+ "How many actions each Bot has taken, counted from the audit trail.",
+ reads: "the audit trail",
+ async run(database, args) {
+ const days = bounded(args.days, { fallback: 7, min: 1, max: 90 });
+ // Counted in the database rather than fetched and counted here: the trail is the one table that
+ // grows without limit, and a component asking for a chart must not pull a year of it across the
+ // wire in order to add up seven days.
+ const rows = await database.execute<{ bot: string; actions: number }>(
+ sql`select payload->>'bot' as bot, count(*)::int as actions
+ from audit_events
+ where payload->>'bot' is not null
+ and created_at > now() - make_interval(days => ${days})
+ group by 1
+ order by actions desc
+ limit 12`,
+ );
+ return { days, rows: [...rows] };
+ },
+ },
+ {
+ name: "recentRefusals",
+ description:
+ "The most recent things this deployment refused, and the reason each was refused.",
+ reads: "the audit trail",
+ async run(database, args) {
+ const limit = bounded(args.limit, { fallback: 10, min: 1, max: 50 });
+ const rows = await database.execute<{
+ at: string;
+ bot: string | null;
+ what: string;
+ reason: string | null;
+ }>(
+ sql`select created_at as at,
+ payload->>'bot' as bot,
+ event_type as what,
+ coalesce(payload->>'reason', payload->'decision'->>'rule') as reason
+ from audit_events
+ where event_type in (
+ 'computer.action_refused',
+ 'component.refused',
+ 'component.function_refused',
+ 'bot.declined'
+ )
+ order by created_at desc
+ limit ${limit}`,
+ );
+ return { rows: [...rows] };
+ },
+ },
+];
+
+export function dataFunction(name: string): DataFunction | undefined {
+ return DATA_FUNCTIONS.find((entry) => entry.name === name);
+}
diff --git a/server/src/components/routes.ts b/server/src/components/routes.ts
new file mode 100644
index 00000000..0039099f
--- /dev/null
+++ b/server/src/components/routes.ts
@@ -0,0 +1,424 @@
+import type { MiddlewareHandler } from "hono";
+import { Hono } from "hono";
+import type { AuditStore } from "../audit";
+import { recordAuditEvent } from "../audit";
+import type { AppVariables } from "../auth/guards";
+import { requireAdmin } from "../auth/guards";
+import { DATA_FUNCTIONS, dataFunction } from "./functions";
+import { ComponentNotFoundError, type ComponentStore } from "./store";
+
+/**
+ * The local development actor, which is not a row in `users`.
+ *
+ * The audit table has a foreign key to that table, so writing this id would fail the constraint and
+ * lose the row entirely. Who it was is in the payload either way.
+ */
+const DEV_ACTOR_EMAIL = "[email protected]";
+
+/**
+ * Granting, publishing and asking whether a Bot may use a component.
+ *
+ * Reading is open to any signed-in person; changing is not. Which components a Bot holds is what the
+ * surface in front of that person is built from, and what a Bot may do is not a secret from the
+ * person talking to it. Deciding it is an administrator's job.
+ *
+ * The decision endpoint is the part that matters. The app already knows what it registered, so
+ * asking again before every render looks redundant, and is not. The list of tools a run is offered
+ * is a snapshot taken when that run started, so a grant revoked one second later is still in the
+ * model's hands. Asking at call time is what makes "revoke it and watch it go" true rather than
+ * nearly true, and it is where a refusal becomes a row somebody can see.
+ */
+export function createComponentRoutes(
+ store: ComponentStore,
+ requireUser: MiddlewareHandler<{ Variables: AppVariables }>,
+ auditStore?: AuditStore,
+) {
+ const routes = new Hono<{ Variables: AppVariables }>();
+
+ const audit = async (
+ context: { var: AppVariables },
+ eventType: Parameters<typeof recordAuditEvent>[1]["eventType"],
+ targetId: string,
+ payload: Record<string, unknown>,
+ ) => {
+ if (!auditStore) return;
+ const actor = context.var.actor;
+ await recordAuditEvent(auditStore, {
+ eventType,
+ targetType: "component",
+ targetId,
+ ...(actor?.id && actor.email !== DEV_ACTOR_EMAIL
+ ? { actorUserId: actor.id }
+ : {}),
+ payload: { actor: actor?.email ?? "unknown", ...payload },
+ });
+ };
+
+ /** Everything a person needs to see the whole grant surface at once. */
+ routes.get("/", requireUser, async (context) =>
+ context.json({ components: await store.list() }),
+ );
+
+ /**
+ * A build announcing what it can draw.
+ *
+ * The build knows what exists; this deployment decides what it may do. A component is an ordinary
+ * React file, so the only thing that can truthfully enumerate them is the app that compiled them.
+ * A second list kept here would be a copy to keep in step, and the first thing to fall out of it.
+ * Drop a file in and it appears here, published, and any Bot may draw it until somebody says
+ * otherwise.
+ *
+ * Additive only, and not an administrator action: any signed-in person's browser announces it on
+ * load, and it cannot change who may use a component, its publication state or its description.
+ */
+ routes.put("/catalogue", requireUser, async (context) => {
+ const body = (await context.req.json().catch(() => null)) as {
+ components?: unknown;
+ } | null;
+ const entries = Array.isArray(body?.components) ? body.components : null;
+ if (!entries) {
+ return context.json({ error: "A list of components is required." }, 400);
+ }
+
+ const valid = entries.flatMap((entry) => {
+ if (!entry || typeof entry !== "object") return [];
+ const { name, title, kind, description } = entry as Record<
+ string,
+ unknown
+ >;
+ if (
+ typeof name !== "string" ||
+ !name ||
+ typeof title !== "string" ||
+ typeof kind !== "string" ||
+ typeof description !== "string" ||
+ !description
+ ) {
+ return [];
+ }
+ return [{ name, title, kind, description }];
+ });
+
+ const { added } = await store.syncCatalogue(valid);
+ // Only arrivals are recorded. Announcing happens on every page load, and a row per load would
+ // bury the trail it is written into.
+ for (const name of added) {
+ await audit(context, "component.published", name, {
+ note: "First seen in a build, published and available to every Bot.",
+ });
+ }
+ return context.json({ added });
+ });
+
+ /**
+ * What one Bot holds. Polled by the app, which turns it into the tools that Bot is offered.
+ *
+ * Deliberately says nothing about the components this Bot does NOT hold. A list of everything it
+ * is missing would be a list the surface could accidentally register.
+ */
+ routes.get("/for-agent/:agentId", requireUser, async (context) =>
+ context.json({
+ components: await store.listForAgent(context.req.param("agentId")),
+ }),
+ );
+
+ /**
+ * May this Bot use this component, right now?
+ *
+ * A POST because it writes: a refusal is recorded. Answering 200 with `allowed: false` rather than
+ * 403 is deliberate, the caller is the app asking a question on the Bot's behalf, and it is not
+ * itself forbidden from asking. The refusal travels in the body, where the handler turns it into
+ * something the model reads.
+ */
+ routes.post("/:name/decision", requireUser, async (context) => {
+ const name = context.req.param("name");
+ const body = (await context.req.json().catch(() => null)) as {
+ agentId?: unknown;
+ functions?: unknown;
+ } | null;
+ const agentId = typeof body?.agentId === "string" ? body.agentId : "";
+ if (!agentId) {
+ return context.json({ error: "The Bot is required." }, 400);
+ }
+ const functions = Array.isArray(body?.functions)
+ ? body.functions.filter(
+ (entry): entry is string => typeof entry === "string",
+ )
+ : [];
+
+ const decision = await store.decide(name, agentId);
+ if (!decision.allowed) {
+ await audit(context, "component.refused", name, {
+ bot: agentId,
+ reason: decision.reason,
+ });
+ return context.json({ allowed: false, reason: decision.reason });
+ }
+
+ /*
+ * The data the component will read, decided here as well.
+ *
+ * Both decisions are enforced at `/call`, but that runs while the component renders, after
+ * whoever asked for it has been answered. A caller that says which functions the component
+ * needs gets one verdict covering what it will do, rather than one covering only its name.
+ */
+ for (const functionName of functions) {
+ if (await store.mayCall(name, functionName)) continue;
+ const reason = `${name} has not been granted the function ${functionName}. An administrator grants each function to each component.`;
+ await audit(context, "component.function_refused", name, {
+ bot: agentId,
+ function: functionName,
+ reason,
+ });
+ return context.json({ allowed: false, reason });
+ }
+
+ return context.json({ allowed: true });
+ });
+
+ /** The data functions this build ships, for an administrator deciding what to grant. */
+ routes.get("/functions", requireUser, (context) =>
+ context.json({
+ functions: DATA_FUNCTIONS.map((entry) => ({
+ name: entry.name,
+ description: entry.description,
+ reads: entry.reads,
+ })),
+ }),
+ );
+
+ /**
+ * A component fetching its own data.
+ *
+ * Permission is enforced here. A compiled React component has
+ * the whole application and could call any endpoint directly, so an allow-list held beside it in
+ * the browser is documentation. The only place that can refuse is the place holding the data.
+ *
+ * Two decisions are enforced: whether this Bot may use the component at all, and whether the
+ * component may call this particular function. Passing one is not passing the other.
+ */
+ routes.post("/:name/call", requireUser, async (context) => {
+ const name = context.req.param("name");
+ const body = (await context.req.json().catch(() => null)) as {
+ function?: unknown;
+ args?: unknown;
+ agentId?: unknown;
+ } | null;
+ const functionName =
+ typeof body?.function === "string" ? body.function : "";
+ const agentId = typeof body?.agentId === "string" ? body.agentId : "";
+ if (!functionName || !agentId) {
+ return context.json(
+ { error: "The function and the Bot are both required." },
+ 400,
+ );
+ }
+
+ const refuse = async (reason: string) => {
+ await audit(context, "component.function_refused", name, {
+ bot: agentId,
+ function: functionName,
+ reason,
+ });
+ return context.json({ allowed: false, reason });
+ };
+
+ // The component itself, first. A component this Bot may not use may not read on its behalf.
+ const decision = await store.decide(name, agentId);
+ if (!decision.allowed) return refuse(decision.reason);
+
+ const fn = dataFunction(functionName);
+ if (!fn) {
+ // Named separately from a refusal so an administrator is not sent looking for a grant to give
+ // for something this build does not have.
+ return refuse(
+ `There is no data function called ${functionName} in this deployment.`,
+ );
+ }
+
+ if (!(await store.mayCall(name, functionName))) {
+ return refuse(
+ `${name} has not been granted the function ${functionName}. An administrator grants each function to each component.`,
+ );
+ }
+
+ try {
+ const data = await store.callFunction(
+ functionName,
+ (body?.args ?? {}) as Record<string, unknown>,
+ );
+ await audit(context, "component.function_called", name, {
+ bot: agentId,
+ function: functionName,
+ reads: fn.reads,
+ });
+ return context.json({ allowed: true, data });
+ } catch (error) {
+ // A function that threw is not a refusal and must not read as one: nothing was forbidden, the
+ // read failed. Recorded as its own thing so a broken query is not filed as a policy event.
+ await audit(context, "component.function_failed", name, {
+ bot: agentId,
+ function: functionName,
+ failure: error instanceof Error ? error.message : "The read failed.",
+ });
+ return context.json(
+ { allowed: true, error: "That data could not be read." },
+ 502,
+ );
+ }
+ });
+
+ routes.post("/:name/functions", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const name = context.req.param("name");
+ const body = (await context.req.json().catch(() => null)) as {
+ function?: unknown;
+ } | null;
+ const functionName =
+ typeof body?.function === "string" ? body.function : "";
+ if (!functionName || !dataFunction(functionName)) {
+ return context.json(
+ { error: "A function this deployment ships is required." },
+ 400,
+ );
+ }
+
+ try {
+ await store.grantFunction(name, functionName, context.var.actor.email);
+ } catch (error) {
+ if (error instanceof ComponentNotFoundError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+
+ await audit(context, "component.function_granted", name, {
+ function: functionName,
+ });
+ return context.json({ granted: true });
+ });
+
+ routes.delete("/:name/functions/:function", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const name = context.req.param("name");
+ const functionName = context.req.param("function");
+ await store.revokeFunction(name, functionName);
+ await audit(context, "component.function_revoked", name, {
+ function: functionName,
+ });
+ return context.json({ revoked: true });
+ });
+
+ routes.post("/:name/grants", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const name = context.req.param("name");
+ const body = (await context.req.json().catch(() => null)) as {
+ agentId?: unknown;
+ } | null;
+ const agentId = typeof body?.agentId === "string" ? body.agentId : "";
+ if (!agentId) {
+ return context.json({ error: "The Bot is required." }, 400);
+ }
+
+ try {
+ await store.grant(name, agentId);
+ } catch (error) {
+ if (error instanceof ComponentNotFoundError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+
+ await audit(context, "component.granted", name, { bot: agentId });
+ return context.json({ granted: true });
+ });
+
+ routes.delete("/:name/grants/:agentId", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const name = context.req.param("name");
+ const agentId = context.req.param("agentId");
+ try {
+ await store.revoke(name, agentId, context.var.actor.email);
+ } catch (error) {
+ if (error instanceof ComponentNotFoundError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+ await audit(context, "component.revoked", name, { bot: agentId });
+ return context.json({ revoked: true });
+ });
+
+ routes.post("/:name/publication", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const name = context.req.param("name");
+ const body = (await context.req.json().catch(() => null)) as {
+ published?: unknown;
+ } | null;
+ const published = body?.published !== false;
+
+ try {
+ if (published) {
+ await store.publish(name, context.var.actor.email);
+ } else {
+ await store.unpublish(name, context.var.actor.email);
+ }
+ } catch (error) {
+ if (error instanceof ComponentNotFoundError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+
+ await audit(
+ context,
+ published ? "component.published" : "component.unpublished",
+ name,
+ {},
+ );
+ return context.json({ published });
+ });
+
+ /**
+ * Edit the draft. Changes nothing a model can see until it is published, which is the point of
+ * having a draft at all.
+ */
+ routes.put("/:name/draft", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const name = context.req.param("name");
+ const body = (await context.req.json().catch(() => null)) as {
+ description?: unknown;
+ } | null;
+ const description =
+ typeof body?.description === "string" ? body.description.trim() : "";
+ if (!description) {
+ return context.json({ error: "A description is required." }, 400);
+ }
+
+ try {
+ await store.saveDraft(name, description, context.var.actor.email);
+ } catch (error) {
+ if (error instanceof ComponentNotFoundError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+
+ await audit(context, "component.draft_saved", name, {});
+ return context.json({ saved: true });
+ });
+
+ return routes;
+}
diff --git a/server/src/components/sandboxed-routes.ts b/server/src/components/sandboxed-routes.ts
new file mode 100644
index 00000000..b297aad3
--- /dev/null
+++ b/server/src/components/sandboxed-routes.ts
@@ -0,0 +1,118 @@
+import type { MiddlewareHandler } from "hono";
+import { Hono } from "hono";
+import type { AppVariables } from "../auth/guards";
+import { requireAdmin } from "../auth/guards";
+import {
+ SandboxedNameRefusedError,
+ SandboxedNotFoundError,
+ type SandboxedStore,
+} from "./sandboxed";
+
+/**
+ * The playground's endpoints, and the one the app renders from.
+ *
+ * Mounted apart from `/api/components` rather than inside it. Those routes end in `/:name/...`, so a
+ * `/sandboxed` path would sit one registration-order mistake away from being swallowed by the
+ * parameter route, and the failure would look like a component called "sandboxed". A separate mount
+ * cannot be shadowed by accident.
+ *
+ * Governance still lives next door. Granting, publishing a description and asking whether a Bot
+ * may use one of these all go through the component routes unchanged, because a sandboxed component
+ * writes a `components` row like any other. What is here is only what is different: the source.
+ */
+export function createSandboxedRoutes(
+ store: SandboxedStore,
+ requireUser: MiddlewareHandler<{ Variables: AppVariables }>,
+) {
+ const routes = new Hono<{ Variables: AppVariables }>();
+
+ const actorEmail = (context: { var: AppVariables }) =>
+ context.var.actor?.email ?? "unknown";
+
+ /** Everything the playground edits. Admin-only: this is the source of what Bots draw. */
+ routes.get("/", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ return context.json({ components: await store.list() });
+ });
+
+ /**
+ * The published source, for the app to render from.
+ *
+ * Open to any signed-in person, unlike the list above. This is what a Bot draws with in a
+ * conversation the person is already in; the draft is an administrator's working copy and is not
+ * theirs to read.
+ */
+ routes.get("/published", requireUser, async (context) =>
+ context.json({ components: await store.published() }),
+ );
+
+ routes.post("/", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const body = (await context.req.json().catch(() => null)) as {
+ slug?: string;
+ title?: string;
+ description?: string;
+ html?: string;
+ css?: string;
+ jsFunctions?: string;
+ argumentSchema?: Record<string, unknown>;
+ sampleArguments?: Record<string, unknown>;
+ } | null;
+
+ if (!body?.slug || !body.title) {
+ return context.json({ error: "A name and a title are required." }, 400);
+ }
+
+ try {
+ const component = await store.save({
+ slug: body.slug,
+ title: body.title,
+ description: body.description ?? "",
+ html: body.html ?? "",
+ css: body.css ?? "",
+ jsFunctions: body.jsFunctions ?? "",
+ argumentSchema: body.argumentSchema ?? {},
+ sampleArguments: body.sampleArguments ?? {},
+ by: actorEmail(context),
+ });
+ return context.json({ component });
+ } catch (error) {
+ if (error instanceof SandboxedNameRefusedError) {
+ return context.json({ error: error.message }, 400);
+ }
+ throw error;
+ }
+ });
+
+ routes.post("/:name/publish", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ try {
+ const component = await store.publish(
+ context.req.param("name"),
+ actorEmail(context),
+ );
+ return context.json({ component });
+ } catch (error) {
+ if (error instanceof SandboxedNotFoundError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+ });
+
+ routes.delete("/:name", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ await store.remove(context.req.param("name"), actorEmail(context));
+ return context.json({ ok: true });
+ });
+
+ return routes;
+}
diff --git a/server/src/components/sandboxed.ts b/server/src/components/sandboxed.ts
new file mode 100644
index 00000000..784426f1
--- /dev/null
+++ b/server/src/components/sandboxed.ts
@@ -0,0 +1,323 @@
+import { asc, eq } from "drizzle-orm";
+import { type AuditStore, recordAuditEvent } from "../audit";
+import type { Database } from "../db/client";
+import { components, sandboxedComponents } from "../db/schema";
+
+/**
+ * Components authored in a browser rather than compiled into the build.
+ *
+ * This exists alongside the React path rather than instead of it. A registered React component is
+ * what a customer's own front-end engineers write: it inherits their design system, their component
+ * library and their review process, and it is the right primary path. It also costs a deployment.
+ * That is fine for engineers and wrong for lightweight edits: a solutions engineer wanting one
+ * temporary card, an analyst changing a column heading, and anything a model
+ * produces, which cannot be a file in the repository by definition.
+ *
+ * The governance is the same governance. Saving one writes a row in `components` too, so the grant
+ * grid, the published description and the per-Bot decision all work on it unchanged. An operator
+ * deciding what a Bot may answer with should never have to know which of the two kinds they are
+ * looking at, and two grant surfaces would be two things to keep in step.
+ *
+ * The source has its own publish gate. Publishing without a rebuild is
+ * the entire point of this table and it is also what puts an editor one keystroke from changing what
+ * every Bot draws in production. A draft absorbs that: edited freely, previewed against sample
+ * arguments, and reaching nobody until somebody publishes it.
+ */
+
+export type SandboxedRecord = {
+ name: string;
+ title: string;
+ draftDescription: string;
+ draftHtml: string;
+ draftCss: string;
+ draftJsFunctions: string;
+ draftArgumentSchema: Record<string, unknown>;
+ publishedHtml: string | null;
+ publishedCss: string | null;
+ publishedJsFunctions: string | null;
+ publishedArgumentSchema: Record<string, unknown> | null;
+ sampleArguments: Record<string, unknown>;
+ revision: number;
+ published: boolean;
+ publishedAt: string | null;
+ authoredBy: string | null;
+ hasUnpublishedChanges: boolean;
+};
+
+/** What a Bot may actually draw with: the published source, or nothing at all. */
+export type PublishedSandboxed = {
+ name: string;
+ html: string;
+ css: string;
+ jsFunctions: string;
+ /**
+ * The arguments this component takes, as the author described them.
+ *
+ * Without this the tool advertises no parameters, and a model told a tool takes nothing calls it
+ * with nothing.
+ */
+ argumentSchema: Record<string, unknown>;
+};
+
+export class SandboxedNotFoundError extends Error {
+ constructor(name: string) {
+ super(`No component is called ${name}.`);
+ this.name = "SandboxedNotFoundError";
+ }
+}
+
+export class SandboxedNameRefusedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SandboxedNameRefusedError";
+ }
+}
+
+const iso = (value: Date | string | null): string | null =>
+ value === null ? null : value instanceof Date ? value.toISOString() : value;
+
+/**
+ * The one place a sandboxed component's name is decided.
+ *
+ * Namespaced so it can never collide with a compiled one. Both kinds share the `components` table
+ * and both are tool names the model calls, so a playground save that happened to pick `showBarChart`
+ * would quietly take over the renderer for a component the build ships. The prefix makes that
+ * impossible rather than unlikely, and it also tells a reader of the audit trail which kind drew
+ * something without having to look it up.
+ */
+export const SANDBOXED_PREFIX = "custom_";
+
+export function sandboxedNameFor(slug: string): string {
+ return `${SANDBOXED_PREFIX}${slug}`;
+}
+
+export function createSandboxedStore(
+ database: Database,
+ auditStore: AuditStore,
+) {
+ async function requireRow(name: string) {
+ const [row] = await database
+ .select()
+ .from(sandboxedComponents)
+ .where(eq(sandboxedComponents.name, name))
+ .limit(1);
+ if (!row) throw new SandboxedNotFoundError(name);
+ return row;
+ }
+
+ const toRecord = (
+ row: typeof sandboxedComponents.$inferSelect,
+ ): SandboxedRecord => ({
+ name: row.name,
+ title: row.title,
+ draftDescription: row.draftDescription,
+ draftHtml: row.draftHtml,
+ draftCss: row.draftCss,
+ draftJsFunctions: row.draftJsFunctions,
+ draftArgumentSchema: row.draftArgumentSchema as Record<string, unknown>,
+ publishedHtml: row.publishedHtml,
+ publishedCss: row.publishedCss,
+ publishedJsFunctions: row.publishedJsFunctions,
+ publishedArgumentSchema: row.publishedArgumentSchema as Record<
+ string,
+ unknown
+ > | null,
+ sampleArguments: row.sampleArguments as Record<string, unknown>,
+ revision: row.revision,
+ published: row.published,
+ publishedAt: iso(row.publishedAt),
+ authoredBy: row.authoredBy,
+ hasUnpublishedChanges:
+ row.published &&
+ (row.draftHtml !== row.publishedHtml ||
+ row.draftCss !== row.publishedCss ||
+ row.draftJsFunctions !== row.publishedJsFunctions),
+ });
+
+ return {
+ async list(): Promise<SandboxedRecord[]> {
+ const rows = await database
+ .select()
+ .from(sandboxedComponents)
+ .orderBy(asc(sandboxedComponents.title));
+ return rows.map(toRecord);
+ },
+
+ /**
+ * Save a draft.
+ *
+ * The `components` row is written at the same time, unpublished, so the new component appears in
+ * the grid straight away and no Bot can draw it yet. Publishing is the decision that hands it to
+ * every Bot, so it happens after somebody has looked at it rather than the moment it is saved.
+ */
+ async save(input: {
+ slug: string;
+ title: string;
+ description: string;
+ html: string;
+ css: string;
+ jsFunctions: string;
+ argumentSchema: Record<string, unknown>;
+ sampleArguments: Record<string, unknown>;
+ by: string;
+ }): Promise<SandboxedRecord> {
+ if (!/^[a-z0-9][a-z0-9_]{0,38}[a-z0-9]$/.test(input.slug)) {
+ throw new SandboxedNameRefusedError(
+ "A name is lower-case letters, numbers and underscores.",
+ );
+ }
+ const name = sandboxedNameFor(input.slug);
+
+ await database
+ .insert(sandboxedComponents)
+ .values({
+ name,
+ title: input.title,
+ draftDescription: input.description,
+ draftHtml: input.html,
+ draftCss: input.css,
+ draftJsFunctions: input.jsFunctions,
+ draftArgumentSchema: input.argumentSchema,
+ sampleArguments: input.sampleArguments,
+ authoredBy: input.by,
+ })
+ .onConflictDoUpdate({
+ target: sandboxedComponents.name,
+ set: {
+ title: input.title,
+ draftDescription: input.description,
+ draftHtml: input.html,
+ draftCss: input.css,
+ draftJsFunctions: input.jsFunctions,
+ draftArgumentSchema: input.argumentSchema,
+ sampleArguments: input.sampleArguments,
+ authoredBy: input.by,
+ updatedAt: new Date(),
+ },
+ });
+
+ // The governance row. `published` is left alone on conflict: an administrator publishing a
+ // description is their decision, and a save must not quietly undo or advance it.
+ await database
+ .insert(components)
+ .values({
+ name,
+ title: input.title,
+ kind: "sandboxed",
+ draftDescription: input.description,
+ publishedDescription: null,
+ published: false,
+ updatedBy: input.by,
+ })
+ .onConflictDoUpdate({
+ target: components.name,
+ set: {
+ title: input.title,
+ draftDescription: input.description,
+ updatedBy: input.by,
+ updatedAt: new Date(),
+ },
+ });
+
+ await recordAuditEvent(auditStore, {
+ eventType: "component.draft_saved",
+ targetType: "component",
+ targetId: name,
+ payload: { actor: input.by, kind: "sandboxed" },
+ });
+
+ return toRecord(await requireRow(name));
+ },
+
+ /**
+ * Publish: the source and the description, in one act.
+ *
+ * One button because it is one decision. Publishing the wording without the markup would offer
+ * the model a component that draws the previous version, and publishing the markup without the
+ * wording would leave a component no model is told about. Either half on its own is a state
+ * nobody wants and both would be reachable if this were two endpoints.
+ */
+ async publish(name: string, by: string): Promise<SandboxedRecord> {
+ const row = await requireRow(name);
+
+ await database
+ .update(sandboxedComponents)
+ .set({
+ publishedDescription: row.draftDescription,
+ publishedHtml: row.draftHtml,
+ publishedCss: row.draftCss,
+ publishedJsFunctions: row.draftJsFunctions,
+ publishedArgumentSchema: row.draftArgumentSchema,
+ published: true,
+ publishedAt: new Date(),
+ revision: row.revision + 1,
+ updatedAt: new Date(),
+ })
+ .where(eq(sandboxedComponents.name, name));
+
+ await database
+ .update(components)
+ .set({
+ publishedDescription: row.draftDescription,
+ published: true,
+ publishedAt: new Date(),
+ updatedBy: by,
+ updatedAt: new Date(),
+ })
+ .where(eq(components.name, name));
+
+ await recordAuditEvent(auditStore, {
+ eventType: "component.published",
+ targetType: "component",
+ targetId: name,
+ payload: { actor: by, kind: "sandboxed", revision: row.revision + 1 },
+ });
+
+ return toRecord(await requireRow(name));
+ },
+
+ async remove(name: string, by: string): Promise<void> {
+ // Delete both rows; a governance row pointing at a component with no source is the visible
+ // "catalogue disagrees with the build" state.
+ await database
+ .delete(sandboxedComponents)
+ .where(eq(sandboxedComponents.name, name));
+ await database.delete(components).where(eq(components.name, name));
+
+ await recordAuditEvent(auditStore, {
+ eventType: "component.unpublished",
+ targetType: "component",
+ targetId: name,
+ payload: { actor: by, kind: "sandboxed", change: "deleted" },
+ });
+ },
+
+ /**
+ * The published source for every sandboxed component, which is what the app renders from.
+ *
+ * Published only, and null is not a fallback. A component that has never been published has no
+ * published source, so it is absent from this list and the app has nothing to draw. A draft
+ * quietly rendering in production is the one outcome the draft column exists to prevent.
+ */
+ async published(): Promise<PublishedSandboxed[]> {
+ const rows = await database
+ .select()
+ .from(sandboxedComponents)
+ .where(eq(sandboxedComponents.published, true));
+ return rows
+ .filter((row) => row.publishedHtml !== null)
+ .map((row) => ({
+ name: row.name,
+ html: row.publishedHtml ?? "",
+ css: row.publishedCss ?? "",
+ jsFunctions: row.publishedJsFunctions ?? "",
+ argumentSchema: (row.publishedArgumentSchema ?? {}) as Record<
+ string,
+ unknown
+ >,
+ }));
+ },
+ };
+}
+
+export type SandboxedStore = ReturnType<typeof createSandboxedStore>;
diff --git a/server/src/computer/policy-store.ts b/server/src/computer/policy-store.ts
new file mode 100644
index 00000000..053ddd15
--- /dev/null
+++ b/server/src/computer/policy-store.ts
@@ -0,0 +1,168 @@
+/**
+ * The policy the gateway is currently enforcing, and the ability to change it while running.
+ *
+ * It survives a restart. A rule held only in memory vanishes the next time the process comes up, and
+ * the trail shows it being added without showing that it stopped applying. A reader would believe a
+ * boundary held at a moment when it did not, and a form going through after a restart is
+ * indistinguishable from a rule that never applied.
+ *
+ * Memory is the cache, and the table is the record. The gateway asks for the policy on every single
+ * action, so `get` stays synchronous and reads from memory; the write goes through to the database
+ * and the memory copy is only updated once it has. A store that answered from the database on every
+ * click would put a query on the path of every keystroke a Bot makes.
+ *
+ * Without a database it still works in memory. Tests that only care about decision logic do not need
+ * Postgres.
+ */
+import { eq } from "drizzle-orm";
+import type { Database } from "../db/client";
+import { actionPolicy } from "../db/schema";
+import type { ActionPolicy } from "./policy";
+
+/** There is one boundary per deployment, so there is one row. */
+const CURRENT = "current";
+
+/**
+ * What a deployment allows when it has not said otherwise.
+ *
+ * Permissive, and written down rather than implied. The policy engine is fail-closed: an absent
+ * policy denies, and a broken rule denies. This default is a separate decision, and it is deliberately
+ * an explicit `allow` rather than a special "unconfigured" case, because a Bot that can look at a page
+ * and touch nothing is not a product, and the first thing a person does is ask it to fill something in.
+ *
+ * Out of the box, OpenBot lets a Bot act, records every action and gives an administrator somewhere
+ * to write the first restriction.
+ */
+export const DEFAULT_ACTION_POLICY: ActionPolicy = {
+ mode: "enforce",
+ deny: [],
+ allow: ["true"],
+};
+
+export type PolicyStore = {
+ /** Synchronous on purpose: this is asked on every action. */
+ get: () => ActionPolicy;
+ /** Persisted before the in-memory copy changes, so a reported success is a saved rule. */
+ set: (policy: ActionPolicy, by?: string) => Promise<void>;
+ /** Back to what configuration says, forgetting the saved one. */
+ reset: () => Promise<void>;
+ /** Read the saved policy at boot. Returns where the live policy came from. */
+ load: () => Promise<"the database" | "configuration">;
+};
+
+export function createPolicyStore(
+ initial: ActionPolicy,
+ /** Absent keeps everything in memory, which is what a test without a database wants. */
+ database?: Database,
+): PolicyStore {
+ const configured = clone(initial);
+ let current = clone(initial);
+
+ return {
+ get: () => current,
+
+ set: async (policy, by) => {
+ const next = clone(policy);
+ if (database) {
+ // Written before it is enforced. If the write fails this throws and the caller reports a
+ // failure, which is the honest outcome: an administrator who is told a rule was saved must
+ // not be enforcing a rule that will disappear at the next restart.
+ await database
+ .insert(actionPolicy)
+ .values({
+ id: CURRENT,
+ mode: next.mode,
+ deny: next.deny,
+ allow: next.allow,
+ updatedBy: by ?? null,
+ updatedAt: new Date(),
+ })
+ .onConflictDoUpdate({
+ target: actionPolicy.id,
+ set: {
+ mode: next.mode,
+ deny: next.deny,
+ allow: next.allow,
+ updatedBy: by ?? null,
+ updatedAt: new Date(),
+ },
+ });
+ }
+ current = next;
+ },
+
+ reset: async () => {
+ // The saved policy is removed rather than overwritten with the configured one, so "reset" means
+ // this deployment has no boundary of its own again, and changing what configuration says then
+ // changes what it enforces, which is what an operator expects of a reset.
+ if (database) {
+ await database.delete(actionPolicy).where(eq(actionPolicy.id, CURRENT));
+ }
+ current = clone(configured);
+ },
+
+ load: async () => {
+ if (!database) return "configuration";
+ const [row] = await database
+ .select()
+ .from(actionPolicy)
+ .where(eq(actionPolicy.id, CURRENT))
+ .limit(1);
+ if (!row) return "configuration";
+
+ current = {
+ mode: row.mode as ActionPolicy["mode"],
+ deny: [...row.deny],
+ allow: [...row.allow],
+ };
+ return "the database";
+ },
+ };
+}
+
+function clone(policy: ActionPolicy): ActionPolicy {
+ return {
+ mode: policy.mode,
+ deny: [...policy.deny],
+ allow: [...policy.allow],
+ };
+}
+
+/**
+ * Validate a policy that arrived over HTTP.
+ *
+ * Rejects rather than coerces. A policy is the thing standing between a Bot and somebody's live
+ * website, and "we accepted your rule but not in the shape you wrote it" is the one behaviour that
+ * must never happen here: an operator would believe a restriction is in force when it is not.
+ *
+ * Expressions are NOT validated for correctness on the way in, only for being strings. Whether a rule
+ * is meaningful is the policy engine's business, it fails closed there, and pre-validating here would
+ * mean two parsers to keep in agreement.
+ */
+export function parseActionPolicy(
+ input: unknown,
+): { ok: true; policy: ActionPolicy } | { ok: false; error: string } {
+ if (!input || typeof input !== "object") {
+ return { ok: false, error: "A policy must be an object." };
+ }
+ const candidate = input as Record<string, unknown>;
+
+ const mode = candidate.mode;
+ if (mode !== "enforce" && mode !== "dry-run") {
+ return {
+ ok: false,
+ error: 'mode must be "enforce" or "dry-run".',
+ };
+ }
+
+ const lists: Record<"deny" | "allow", string[]> = { deny: [], allow: [] };
+ for (const key of ["deny", "allow"] as const) {
+ const value = candidate[key] ?? [];
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
+ return { ok: false, error: `${key} must be a list of expressions.` };
+ }
+ lists[key] = value as string[];
+ }
+
+ return { ok: true, policy: { mode, deny: lists.deny, allow: lists.allow } };
+}
diff --git a/server/src/computer/policy.ts b/server/src/computer/policy.ts
new file mode 100644
index 00000000..7b18ceeb
--- /dev/null
+++ b/server/src/computer/policy.ts
@@ -0,0 +1,284 @@
+/**
+ * Whether a Bot may take one particular action on one particular page.
+ *
+ * Mirrors the policy engine in CopilotKit's enterprise agent gateway rather than being re-derived, so
+ * a rule written here means the same thing there. Kept from it: CEL expressions, `dry-run` vs
+ * `enforce`, default-deny, and fail-closed evaluation. Added here: a `deny` list, because an
+ * allow-only policy can only forbid one thing by withdrawing permission from everything.
+ *
+ * CEL instead of a rule table. The boundary a company wants is a sentence: "never click anything
+ * that says Submit on a page outside our own domain". A table of columns can express the shapes we
+ * thought of; an expression language can express the one they thought of. This is also the language
+ * the enterprise gateway already speaks, so a rule written here means the same thing there.
+ *
+ * Precedence: deny beats allow. A rule that removes permission must never be
+ * defeated by a broader rule that grants it, or a company cannot reason about what it has forbidden.
+ */
+import { evaluate } from "cel-js";
+
+export type PolicyMode = "dry-run" | "enforce";
+
+export type ActionPolicy = {
+ /**
+ * `enforce` blocks. `dry-run` decides and records, and lets everything through.
+ *
+ * Dry-run exists so an operator can write a rule against real traffic and read the audit trail
+ * before it starts refusing anybody's work. A governance feature nobody dares switch on is not a
+ * governance feature.
+ */
+ mode: PolicyMode;
+ /** Evaluated first. Any expression true means refused, whatever `allow` says. */
+ deny: string[];
+ /** Any expression true means permitted. Empty means nothing is permitted. */
+ allow: string[];
+};
+
+/**
+ * The attributes a rule can be written against.
+ *
+ * `element` is resolved by the gateway from the snapshot the server itself fetched, never from what
+ * the caller claimed it was clicking. A policy that decides on an attacker-supplied label is
+ * decoration: the whole point is that "do not click Submit" cannot be evaded by calling it something
+ * else in the request.
+ */
+export type PolicyContext = {
+ tool: { name: string };
+ bot: { id: string };
+ page: { url: string; host: string };
+ actor: { id: string };
+ element?: {
+ ref: string;
+ role: string;
+ name: string;
+ type?: string;
+ };
+ /**
+ * The key a `computer_key` call is about to press.
+ *
+ * Without this, a rule about clicking is bypassed. An agent that meets a deny rule on
+ * clicking "Submit order" will press Enter in the form instead, and the order goes through: the
+ * click is refused and audited, the keypress is allowed, because nothing in the context could tell
+ * one keypress from another.
+ *
+ * A form has two doors and the policy could only see one. Now a rule can say
+ * `tool.name == "computer_key" && key == "Enter"`, and an operator blocking a submit button knows
+ * to block both routes, which the deny example in `.env.example` now does.
+ */
+ key?: string;
+ /**
+ * What the action does, rather than which tool was called.
+ *
+ * `tool.name` describes mechanism. An operator thinks in effects, "do not activate anything called
+ * submit", and mechanism is a poor proxy for effect: a button is activated by a click OR by Enter
+ * OR by Space, so a rule naming `computer_click` covers only one activation path.
+ *
+ * `activate`, a click, or Enter or Space, which are the gestures that press a thing.
+ * `type`, text going into a field, including any other keypress.
+ * `navigate`, opening a page.
+ * `read`, looking at the page or listing what is on it.
+ * `write_file` / `read_file` / `list_files`, the workspace.
+ *
+ * It still cannot see whether a keypress will submit a form. A browser submits
+ * from Enter in any field of it, and the element a keypress names is the field, not the form. The
+ * gateway would need to know the page's structure at decision time, which it does not, refs are
+ * held off-DOM by Playwright and the policy runs before the action reaches the browser. So a rule
+ * that must stop a submission still has to refuse Enter outright, and the preset says so.
+ */
+ intent?:
+ | "activate"
+ | "type"
+ | "navigate"
+ | "read"
+ | "read_file"
+ | "write_file"
+ | "list_files"
+ // A tool on somebody else's MCP server. Split by effect for the same reason as the browser
+ // intents: an operator thinks "nothing may change anything in Jira", not "nothing may call
+ // editJiraIssue, transitionJiraIssue, addCommentToJiraIssue and the six others".
+ | "read_tool"
+ | "write_tool";
+ /**
+ * The file a `computer_read_file` or `computer_write_file` call is aimed at.
+ *
+ * The path is as the Bot asked for it, relative to its workspace. Containment is not policy: a path
+ * that tries to escape is refused by the computer itself and is not negotiable. A rule here is about
+ * which files inside the workspace a given Bot may touch.
+ *
+ * `name` and `extension` are split out because the rules people actually want are "nothing called
+ * *.env" and "nothing under credentials/", and making them write string surgery in CEL to express
+ * that would guarantee subtly wrong rules.
+ */
+ file?: {
+ path: string;
+ name: string;
+ /** Without the dot, and lower-case. Empty for a file with no extension. */
+ extension: string;
+ };
+ /**
+ * The MCP server and tool a call is aimed at.
+ *
+ * Split out rather than left in `tool.name`. The offered tool name is `mcp__jira__editJiraIssue`,
+ * and asking an operator to write string surgery against that to say "nothing may write to Jira"
+ * would guarantee rules that are subtly wrong the first time a vendor renames something. Server,
+ * tool and effect are three plain fields instead.
+ *
+ * `effect` is decided by the server's own advertised catalogue crossed with a reviewed list of
+ * which of its tools change things, and it fails closed: anything not positively known to be a
+ * read is a write.
+ */
+ mcp?: {
+ server: string;
+ tool: string;
+ effect: "read" | "write";
+ };
+};
+
+export type PolicyDecision = {
+ allowed: boolean;
+ mode: PolicyMode;
+ /** Which expression decided it, so the audit row can say why and an operator can find the rule. */
+ matched: string | null;
+ /** Which list that expression came from. `default` means nothing matched and the floor applied. */
+ source: "deny" | "allow" | "default";
+ /** True when the action should actually be carried out. False for a refusal in `enforce`. */
+ forward: boolean;
+ /** Why, in words that go in front of a person. */
+ reason: string;
+};
+
+/**
+ * String helpers, registered as CEL globals.
+ *
+ * cel-js 0.8.2 implements no string methods at all: `element.name.contains("Submit")` raises
+ * "Unknown method: contains", as do `startsWith`, `endsWith` and `matches`. These globals make
+ * substring rules enforceable with the installed CEL version.
+ *
+ * Both are case-insensitive. A rule saying "never click submit" also catches a button labelled
+ * "SUBMIT".
+ */
+const POLICY_FUNCTIONS: Record<string, (...args: never[]) => unknown> = {
+ contains: ((haystack: unknown, needle: unknown) =>
+ String(haystack).toLowerCase().includes(String(needle).toLowerCase())) as (
+ ...args: never[]
+ ) => unknown,
+ matches: ((value: unknown, pattern: unknown) => {
+ try {
+ return new RegExp(String(pattern), "i").test(String(value));
+ } catch {
+ // An unparseable regex is a broken rule, not a match. The caller treats a thrown expression as
+ // fail-closed, so returning false here would quietly weaken a deny rule; throw instead.
+ throw new Error(`not a valid pattern: ${String(pattern)}`);
+ }
+ }) as (...args: never[]) => unknown,
+};
+
+/**
+ * Evaluate one expression. Never throws.
+ *
+ * `onError` decides what a broken expression means, because the safe answer differs by list: a broken
+ * `allow` must not permit, and a broken `deny` must not stop denying. Both are logged loudly, because
+ * a policy that silently misbehaves is worse than one that visibly refuses.
+ */
+function matches(
+ expression: string,
+ context: PolicyContext,
+ onError: boolean,
+): boolean {
+ try {
+ return (
+ evaluate(
+ expression,
+ context as unknown as Record<string, unknown>,
+ POLICY_FUNCTIONS as Record<string, CallableFunction>,
+ ) === true
+ );
+ } catch (error) {
+ console.error(
+ JSON.stringify({
+ type: "computer-policy-expression-error",
+ expression,
+ error: String(error),
+ treatedAs: onError,
+ }),
+ );
+ return onError;
+ }
+}
+
+/**
+ * Decide whether this action may run.
+ *
+ * An absent policy denies. An unconfigured deployment is one that has not said what its Bots may do,
+ * and the safe reading of silence is "nothing", not "anything". The shipped configuration therefore
+ * states its permissions explicitly rather than relying on a default, so that what a Bot may do is
+ * always something somebody wrote down.
+ */
+export function evaluateActionPolicy(
+ policy: ActionPolicy | null | undefined,
+ context: PolicyContext,
+): PolicyDecision {
+ const mode: PolicyMode = policy?.mode ?? "enforce";
+ const deny = policy?.deny ?? [];
+ const allow = policy?.allow ?? [];
+
+ // Deny first, and a broken deny expression still denies. One typo in a rule therefore blocks the
+ // action rather than admitting it: the failure is loud, immediate and safe, and the alternative is
+ // a deployment that believes it has forbidden something it has not.
+ for (const expression of deny) {
+ if (matches(expression, context, true)) {
+ return {
+ allowed: false,
+ mode,
+ matched: expression,
+ source: "deny",
+ // dry-run records the refusal and lets the work continue, which is what makes it safe to
+ // switch on against live traffic.
+ forward: mode === "dry-run",
+ reason: describeRefusal(context, expression),
+ };
+ }
+ }
+
+ for (const expression of allow) {
+ if (matches(expression, context, false)) {
+ return {
+ allowed: true,
+ mode,
+ matched: expression,
+ source: "allow",
+ forward: true,
+ reason: "Permitted by policy.",
+ };
+ }
+ }
+
+ return {
+ allowed: false,
+ mode,
+ matched: null,
+ source: "default",
+ forward: mode === "dry-run",
+ reason:
+ "No rule in this deployment's policy permits that action, so it was refused. " +
+ "An administrator can add one.",
+ };
+}
+
+/** A refusal a person can act on: what was refused, and on what. */
+function describeRefusal(context: PolicyContext, expression: string): string {
+ // A file refusal must not be phrased as happening "on <host>": the workspace has nothing to do with
+ // whatever page the browser happens to be showing, and saying so sends somebody to the wrong place.
+ if (context.file) {
+ return (
+ `This deployment's policy does not allow that: the file ${context.file.path} ` +
+ `is blocked by the rule \`${expression}\`.`
+ );
+ }
+ const what = context.element?.name
+ ? `“${context.element.name}”`
+ : `a ${context.tool.name.replace("computer_", "")} action`;
+ return (
+ `This deployment's policy does not allow that: ${what} on ${context.page.host} ` +
+ `is blocked by the rule \`${expression}\`.`
+ );
+}
diff --git a/server/src/computer/routes.ts b/server/src/computer/routes.ts
new file mode 100644
index 00000000..3ce1c285
--- /dev/null
+++ b/server/src/computer/routes.ts
@@ -0,0 +1,515 @@
+import type { Context, MiddlewareHandler } from "hono";
+import { Hono } from "hono";
+import type { AppVariables } from "../auth/guards";
+import { requireAdmin } from "../auth/guards";
+import {
+ type ComputerClient,
+ ComputerUnavailableError,
+ ElementNotFoundError,
+ NavigationRefusedError,
+ StaleSnapshotError,
+ WorkspaceRefusedError,
+ WorkspaceRequestError,
+} from "./client";
+import {
+ type ActionActor,
+ ActionRefusedError,
+ type ComputerGateway,
+} from "./gateway";
+import { type PolicyStore, parseActionPolicy } from "./policy-store";
+
+/**
+ * The Bot computer's surface, behind the same session guard as every other API route.
+ *
+ * The computer has token authentication but no user/session identity. These server routes require a
+ * session guard because `COMPUTER_TOKEN` proves the caller is an internal service, not which user is
+ * asking to drive the browser.
+ *
+ * Read-only calls go to the client; acting calls go to the gateway. That split is the governance
+ * boundary: every acting route in this file passes through a policy decision and audit row before it
+ * reaches the computer.
+ */
+export function createComputerRoutes(
+ client: ComputerClient,
+ gateway: ComputerGateway,
+ policyStore: PolicyStore,
+ requireUser: MiddlewareHandler<{ Variables: AppVariables }>,
+) {
+ const routes = new Hono<{ Variables: AppVariables }>();
+
+ routes.get("/:botId/status", requireUser, async (context) =>
+ context.json(await client.status(context.req.param("botId"))),
+ );
+
+ routes.get("/:botId/screenshot", requireUser, async (context) => {
+ try {
+ return context.json(
+ await client.forBot(context.req.param("botId")).screenshot(),
+ );
+ } catch (error) {
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ routes.get("/:botId/read", requireUser, async (context) => {
+ try {
+ return context.json(await gateway.read(context.req.param("botId")));
+ } catch (error) {
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ routes.post("/:botId/navigate", requireUser, async (context) => {
+ const body = (await context.req.json().catch(() => null)) as {
+ url?: unknown;
+ } | null;
+ if (typeof body?.url !== "string" || !body.url.trim()) {
+ return context.json({ error: "A web address is required." }, 400);
+ }
+
+ try {
+ return context.json(
+ await gateway.navigate(
+ context.req.param("botId") ?? "default",
+ context.req.param("botId") ?? "default",
+ {
+ id: context.var.actor.id,
+ ...(context.var.actor.email === DEV_ACTOR_EMAIL
+ ? {}
+ : { userId: context.var.actor.id }),
+ },
+ body.url.trim(),
+ ),
+ );
+ } catch (error) {
+ if (error instanceof ActionRefusedError) {
+ return context.json({ error: error.message, rule: error.rule }, 403);
+ }
+ // A refusal is the rules working, not a fault, so it is a 403 with the reason a person reads.
+ // Collapsing it into the same 5xx as an unreachable computer would send somebody looking for
+ // an outage that is not happening.
+ if (error instanceof NavigationRefusedError) {
+ return context.json({ error: error.message }, 403);
+ }
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ routes.post("/:botId/snapshot", requireUser, async (context) => {
+ try {
+ return context.json(await gateway.snapshot(context.req.param("botId")));
+ } catch (error) {
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ /**
+ * The acting routes.
+ *
+ * Each one hands the gateway the computer id, the Bot, the actor and the input, and does no checking
+ * of its own beyond the shape of the request. Where a decision gets made is a single place.
+ */
+ routes.post("/:botId/click", requireUser, (context) =>
+ act(context, (botId, actor, body, signal) => {
+ const ref = asRef(body);
+ if (!ref) return badRef;
+ return gateway.click(botId, botId, actor, ref, signal);
+ }),
+ );
+
+ routes.post("/:botId/type", requireUser, (context) =>
+ act(context, (botId, actor, body, signal) => {
+ const ref = asRef(body);
+ if (!ref) return badRef;
+ if (typeof body?.text !== "string") {
+ return { error: "The text to enter is required." };
+ }
+ return gateway.type(
+ botId,
+ botId,
+ actor,
+ {
+ ...ref,
+ text: body.text,
+ submit: body?.submit === true,
+ },
+ signal,
+ );
+ }),
+ );
+
+ routes.post("/:botId/key", requireUser, (context) =>
+ act(context, (botId, actor, body, signal) => {
+ if (typeof body?.key !== "string" || !body.key) {
+ return { error: "A key name is required, such as Enter or Tab." };
+ }
+ const ref = asRef(body);
+ return gateway.key(
+ botId,
+ botId,
+ actor,
+ {
+ key: body.key,
+ ...(ref ?? {}),
+ },
+ signal,
+ );
+ }),
+ );
+
+ routes.post("/:botId/scroll", requireUser, (context) =>
+ act(context, (botId, actor, body) =>
+ gateway.scroll(botId, botId, actor, {
+ ...(typeof body?.deltaY === "number" ? { deltaY: body.deltaY } : {}),
+ }),
+ ),
+ );
+
+ /**
+ * Who has the wheel. Polled by the surface next to the screen, so the person sees the Bot ask for
+ * help without reloading anything.
+ */
+ routes.get("/:botId/control", requireUser, async (context) => {
+ try {
+ return context.json(await gateway.control(context.req.param("botId")));
+ } catch (error) {
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ routes.post("/:botId/control/request", requireUser, (context) =>
+ act(context, (botId, actor, body) =>
+ gateway.requestHelp(
+ botId,
+ botId,
+ actor,
+ typeof body?.reason === "string" && body.reason.trim()
+ ? body.reason.trim()
+ : "The assistant needs a person to continue.",
+ ),
+ ),
+ );
+
+ /**
+ * The computers, for the admin surface.
+ *
+ * Not per-Bot in the path the way the acting routes are: this asks the computer what it holds, and
+ * it holds a list. `:botId` is still there because every route under this router has it and the
+ * gateway wants somebody to attribute the call to.
+ */
+ routes.get("/:botId/computers", requireUser, async (context) => {
+ try {
+ return context.json(await gateway.computers());
+ } catch (error) {
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ /** Stop the browser, keep the logins. */
+ routes.post("/:botId/computers/stop", requireUser, (context) =>
+ act(context, (botId, actor) => gateway.stopComputer(botId, botId, actor)),
+ );
+
+ /** Delete the profile. Every login goes with it, which is the point and also the danger. */
+ routes.post("/:botId/computers/reset", requireUser, (context) =>
+ act(context, (botId, actor) => gateway.resetComputer(botId, botId, actor)),
+ );
+
+ routes.post("/:botId/control/take", requireUser, (context) =>
+ act(context, (botId, actor) => gateway.takeControl(botId, botId, actor)),
+ );
+
+ routes.post("/:botId/control/release", requireUser, (context) =>
+ act(context, (botId, actor) => gateway.releaseControl(botId, botId, actor)),
+ );
+
+ /** The Bot asking for a value it must not be told. */
+ routes.post("/:botId/control/secret", requireUser, (context) =>
+ act(context, (botId, actor, body) => {
+ if (typeof body?.ref !== "string" || !body.ref) {
+ return {
+ error:
+ "Say which field the value goes in, using a ref from your snapshot.",
+ };
+ }
+ if (typeof body?.snapshotId !== "number") {
+ return { error: "The snapshotId the ref came from is required." };
+ }
+ return gateway.requestSecret(botId, botId, actor, {
+ label:
+ typeof body?.label === "string" && body.label.trim()
+ ? body.label.trim()
+ : "the value this page is asking for",
+ ref: body.ref,
+ snapshotId: body.snapshotId,
+ });
+ }),
+ );
+
+ /**
+ * A person supplying it.
+ *
+ * The value is read from the body, passed straight through, and referred to nowhere else. Its own
+ * route rather than a `kind` on the input route below, so that grepping for where a secret can enter
+ * this server returns exactly one place.
+ */
+ routes.post("/:botId/human/secret", requireUser, (context) =>
+ act(context, (botId, actor, body) => {
+ if (typeof body?.text !== "string" || !body.text) {
+ return { error: "A value is required." };
+ }
+ return gateway.supplySecret(botId, botId, actor, body.text);
+ }),
+ );
+
+ /**
+ * A person's own mouse and keyboard.
+ *
+ * Not through the policy gateway, and not audited per keystroke, see the note on `humanInput` in
+ * client.ts. The takeover is the audited event; what the person typed during it is deliberately
+ * unrecorded, because the reason a takeover exists is to let them enter the thing nothing else
+ * should keep.
+ */
+ routes.post("/:botId/human/:kind", requireUser, async (context) => {
+ const kind = context.req.param("kind");
+ if (
+ kind !== "click" &&
+ kind !== "type" &&
+ kind !== "key" &&
+ kind !== "scroll"
+ ) {
+ return context.json({ error: "Unknown input." }, 400);
+ }
+ const body = (await context.req.json().catch(() => null)) as Record<
+ string,
+ unknown
+ > | null;
+ try {
+ return context.json(
+ await gateway.humanInput(context.req.param("botId"), {
+ kind,
+ ...(body ?? {}),
+ } as Parameters<typeof gateway.humanInput>[1]),
+ );
+ } catch (error) {
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+ });
+
+ /** The Bot's files. Through the gateway, like every other acting call. */
+ routes.post("/:botId/files/list", requireUser, (context) =>
+ act(context, (botId, actor, body) =>
+ gateway.listFiles(botId, botId, actor, {
+ ...(typeof body?.path === "string" && body.path.trim()
+ ? { path: body.path.trim() }
+ : {}),
+ }),
+ ),
+ );
+
+ routes.post("/:botId/files/read", requireUser, (context) =>
+ act(context, (botId, actor, body) => {
+ if (typeof body?.path !== "string" || !body.path.trim()) {
+ return { error: "A file path is required." };
+ }
+ return gateway.readFile(botId, botId, actor, { path: body.path.trim() });
+ }),
+ );
+
+ routes.post("/:botId/files/write", requireUser, (context) =>
+ act(context, (botId, actor, body) => {
+ if (typeof body?.path !== "string" || !body.path.trim()) {
+ return { error: "A file path is required." };
+ }
+ if (typeof body?.contents !== "string") {
+ return { error: "The contents to write are required." };
+ }
+ return gateway.writeFile(botId, botId, actor, {
+ path: body.path.trim(),
+ contents: body.contents,
+ append: body.append === true,
+ });
+ }),
+ );
+
+ /**
+ * The policy, readable and writable by an administrator.
+ *
+ * Here rather than in the admin routes file, because this directory owns the computer and `app.ts`
+ * takes one appended line per mount. The storage underneath is durable, so administrator rules
+ * remain active after a restart.
+ */
+ routes.get("/policy", requireUser, (context) => {
+ const denied = requireAdmin(context);
+ return denied ?? context.json({ policy: policyStore.get() });
+ });
+
+ routes.put("/policy", requireUser, async (context) => {
+ const denied = requireAdmin(context);
+ if (denied) return denied;
+
+ const parsed = parseActionPolicy(
+ await context.req.json().catch(() => null),
+ );
+ if (!parsed.ok) {
+ return context.json({ error: parsed.error }, 400);
+ }
+ try {
+ await policyStore.set(parsed.policy, context.var.actor.email);
+ } catch {
+ /*
+ * Saved, or said so. A boundary that is enforced now and gone after the next restart is worse
+ * than one that was never set, so a policy that could not be written is reported as a failure
+ * rather than quietly held in memory. Nothing changes: the previous policy is still in force.
+ */
+ return context.json(
+ {
+ error:
+ "That rule could not be saved, so it has not been applied. The previous boundary is still in force.",
+ },
+ 503,
+ );
+ }
+ // Echoed back so a caller can see exactly what is now in force rather than assuming its request
+ // was stored verbatim.
+ return context.json({ policy: policyStore.get() });
+ });
+
+ return routes;
+}
+
+type ComputerContext = Context<{ Variables: AppVariables }>;
+
+/** A request that was rejected before any decision was needed, because it was not a valid action. */
+type BadRequest = { error: string };
+
+const badRef: BadRequest = {
+ error:
+ "A ref and the snapshotId it came from are both required. Take a snapshot first.",
+};
+
+/**
+ * Shared plumbing for acting routes that use this helper: resolve who is asking, run, and map
+ * failures onto statuses.
+ *
+ * One place, so a new acting route cannot accidentally report a policy refusal as a server error, and
+ * so the actor is derived the same way every time.
+ */
+async function act(
+ context: ComputerContext,
+ handler: (
+ botId: string,
+ actor: ActionActor,
+ body: Record<string, unknown> | null,
+ /**
+ * The person's Stop, as an abort.
+ *
+ * The surface aborts its request when Stop is pressed; Bun exposes that here, and every acting
+ * route passes it on so the abort reaches the Playwright call mid-click. Without it, Stop ended
+ * the run in the transcript while the click carried on landing on a live page, harmless most of
+ * the time, and not harmless on a Confirm button, which is exactly when Stop gets pressed.
+ */
+ signal: AbortSignal,
+ ) => Promise<unknown> | BadRequest,
+) {
+ // Always present on these routes, which all declare `:botId`. The fallback exists because this
+ // helper is typed against a generic context that cannot know that, and a thrown "undefined bot"
+ // would be a worse outcome than naming the one shared computer.
+ const botId = context.req.param("botId") ?? "default";
+ const record = context.var.actor;
+ const body = (await context.req.json().catch(() => null)) as Record<
+ string,
+ unknown
+ > | null;
+
+ try {
+ const result = await handler(
+ botId,
+ {
+ id: record.id,
+ // Only a real users row may go in the audit table's foreign key column. The local development
+ // actor is not one, so writing it there fails the constraint and loses the row entirely. Who
+ // it was is recorded in the payload regardless. See gateway.ts.
+ ...(record.email === DEV_ACTOR_EMAIL ? {} : { userId: record.id }),
+ },
+ body,
+ context.req.raw.signal,
+ );
+ if (isBadRequest(result)) {
+ return context.json(result, 400);
+ }
+ return context.json(result as Record<string, unknown>);
+ } catch (error) {
+ // A policy refusal is the product working. 403 with the rule that refused it, so the surface can
+ // tell the person which boundary they met rather than reporting a malfunction.
+ if (error instanceof ActionRefusedError) {
+ return context.json({ error: error.message, rule: error.rule }, 403);
+ }
+ // The computer refused the path itself, which is a different thing from the policy refusing this
+ // Bot. Same status, no rule attached, because there is no rule to go and edit.
+ if (error instanceof WorkspaceRefusedError) {
+ return context.json({ error: error.message }, 403);
+ }
+ // A 400, deliberately, NOT a 403. The surface treats 403 as "a boundary refused you" and renders
+ // it as Blocked, so returning it for "there is no file at notes.md" told both the person and the
+ // model that a policy had intervened when none had.
+ if (error instanceof WorkspaceRequestError) {
+ return context.json({ error: error.message }, 400);
+ }
+ return context.json({ error: describe(error) }, statusFor(error));
+ }
+}
+
+/**
+ * The local actor's address, matched to decide whether the id is a real users row.
+ *
+ * Compared against rather than imported from `auth/dev-actor` because the computer must not depend on the
+ * authentication module's internals; this is the one fact about it that matters here.
+ */
+const DEV_ACTOR_EMAIL = "[email protected]";
+
+function isBadRequest(value: unknown): value is BadRequest {
+ return (
+ !!value &&
+ typeof value === "object" &&
+ "error" in value &&
+ !("action" in value)
+ );
+}
+
+function asRef(
+ body: Record<string, unknown> | null,
+): { ref: string; snapshotId: number } | undefined {
+ if (typeof body?.ref !== "string" || !body.ref) return undefined;
+ if (typeof body?.snapshotId !== "number") return undefined;
+ return { ref: body.ref, snapshotId: body.snapshotId };
+}
+
+function describe(error: unknown): string {
+ return error instanceof Error ? error.message : "Something went wrong.";
+}
+
+/**
+ * Which HTTP status a failure deserves.
+ *
+ * Three genuinely different conditions that read identically if they all become 500: the computer is
+ * not running (an operator fixes it), the refs are stale (the model fixes it by snapshotting again),
+ * and everything else. Navigation established this; the acting routes follow it.
+ */
+function statusFor(error: unknown): 409 | 500 | 503 {
+ if (error instanceof StaleSnapshotError) return 409;
+ // The same answer as a stale snapshot, because it is the same instruction: the refs are wrong, take
+ // another snapshot. Not 503, which says the computer is unavailable and sends an operator hunting a
+ // container that is running perfectly.
+ if (error instanceof ElementNotFoundError) return 409;
+ // A person holding the wheel, or a person driving before taking it. Nothing is broken; the caller
+ // has to wait or take control first, and 409 is how both of those are already reported.
+ if (
+ error instanceof ComputerUnavailableError &&
+ /control/i.test(error.message)
+ ) {
+ return 409;
+ }
+ if (error instanceof ComputerUnavailableError) return 503;
+ return 500;
+}
diff --git a/server/src/computer/schema.ts b/server/src/computer/schema.ts
new file mode 100644
index 00000000..659e8d7a
--- /dev/null
+++ b/server/src/computer/schema.ts
@@ -0,0 +1,328 @@
+/**
+ * The computer-use contract.
+ *
+ * One place that says what a tool call looks like, so neither the surface nor the computer has to
+ * read the other's code to find out. Changing a name or a parameter here is a breaking change for
+ * both sides: add, do not repurpose.
+ *
+ * The read-only tools sit alongside the acting ones, and every acting tool goes through the gateway,
+ * so each is policy checked and written to the audit trail before it runs. Names are never
+ * repurposed: this file only ever grows.
+ */
+
+/**
+ * Every tool the computer exposes.
+ *
+ * Ordered read-only first, then acting. `COMPUTER_ACTING_TOOLS` below is what the gateway uses to
+ * decide which calls need a policy decision, so add acting tools to both lists.
+ */
+export const COMPUTER_TOOLS = [
+ "computer_navigate",
+ "computer_screenshot",
+ "computer_read",
+ "computer_snapshot",
+ "computer_click",
+ "computer_type",
+ "computer_key",
+ "computer_scroll",
+ "computer_read_file",
+ "computer_write_file",
+ "computer_list_files",
+] as const;
+
+/**
+ * The tools that change something, or reach something that needs deciding on.
+ *
+ * These are the calls the gateway must decide on. Reading a PAGE a Bot has already been allowed to
+ * open is not a new decision; clicking "Confirm payment" on it is.
+ *
+ * Both file tools are here, including the read. That differs from `computer_read`, which
+ * is ungoverned, and it is deliberate: a page was already permitted when it was opened, whereas the
+ * workspace accumulates whatever a Bot has put in it across every task it has ever run, so "which
+ * files may this Bot read" is a question a deployment genuinely needs to be able to answer. The build
+ * doc says both file tools go through the gateway, and this is why that is right.
+ */
+export const COMPUTER_ACTING_TOOLS = [
+ // Navigation is governed too, and not only guarded. The client's target guard refuses a forbidden
+ // address on its own, which stops the request and writes nothing. That leaves the trail silent
+ // about an attempt to reach the cloud metadata endpoint, the single most security-relevant thing a
+ // Bot can try, while ticking a radio button is recorded. Governing it puts both in the trail.
+ "computer_navigate",
+ "computer_click",
+ "computer_type",
+ "computer_key",
+ "computer_scroll",
+ "computer_read_file",
+ "computer_write_file",
+ "computer_list_files",
+] as const;
+
+export type ComputerActingToolName = (typeof COMPUTER_ACTING_TOOLS)[number];
+
+export function isActingTool(name: string): name is ComputerActingToolName {
+ return (COMPUTER_ACTING_TOOLS as readonly string[]).includes(name);
+}
+
+export type ComputerToolName = (typeof COMPUTER_TOOLS)[number];
+
+export type NavigateInput = { url: string };
+export type NavigateResult = {
+ url: string;
+ title: string;
+ /**
+ * The readable text of the page, truncated.
+ *
+ * Navigation returns content because a Bot that can open a page but not read it can only answer
+ * "I opened it, go and look yourself", which is worse than not having the tool: the person asked
+ * a question and got homework. The screenshot is for the human to watch; this is what the Bot
+ * reads. They are not interchangeable, and a picture is not something a model should be made to
+ * squint at to answer "what is the top story".
+ */
+ text: string;
+ /** True when the page was longer than the extract, so the Bot can say so rather than guess. */
+ truncated: boolean;
+ /** Wall-clock ms the navigation took, for the progress line in the transcript. */
+ elapsedMs: number;
+};
+
+export type ScreenshotResult = {
+ /** PNG, base64. The transcript renders it; nothing else interprets it. */
+ base64: string;
+ width: number;
+ height: number;
+ capturedAt: string;
+ /**
+ * The page this is a picture of, or `about:blank` for a browser that has not been sent anywhere.
+ *
+ * Optional because it was added after the first computers shipped, and an agent-computer that has
+ * not been redeployed does not send it. Treat a missing value as "some page", never as blank: the
+ * failure that matters is a real screenshot being hidden behind a placeholder.
+ */
+ url?: string;
+};
+
+/** The current page as text, without opening anything. Same shape as a navigation, minus the trip. */
+export type ReadResult = Omit<NavigateResult, "elapsedMs">;
+
+/**
+ * One thing on the page a Bot can act on.
+ *
+ * This is the accessibility-tree view, not the pixels: a Bot fills in a form by reading a list of
+ * labelled fields and naming one, which is why form-filling needs no vision model. See the build
+ * doc's open decision 2 (accessibility tree first, pixels as fallback).
+ */
+export type SnapshotElement = {
+ /** Opaque handle, valid only for the snapshot that produced it. Never construct one. */
+ ref: string;
+ /** ARIA role where the page declares one, otherwise the tag name. */
+ role: string;
+ /** What a person reads as this control's label, resolved the way a screen reader resolves it. */
+ name: string;
+ /** Current contents, for form controls. Lets a Bot tell an empty field from a filled one. */
+ value?: string;
+ /** An `input`'s type, so a Bot does not try to type into a checkbox. */
+ type?: string;
+ disabled?: boolean;
+ checked?: boolean;
+};
+
+export type SnapshotResult = {
+ /**
+ * Which snapshot these refs belong to. Must be sent back with every action.
+ *
+ * This field makes refs from superseded snapshots refusals instead of actions.
+ * A page that re-rendered between the snapshot and the click has moved its controls, and the
+ * failure mode without this check is not an error, it is clicking the wrong button.
+ */
+ snapshotId: number;
+ url: string;
+ title: string;
+ elements: SnapshotElement[];
+ /** True when the page had more interactive elements than the snapshot describes. */
+ truncated: boolean;
+};
+
+/** Common to every acting call: which element, and which snapshot the ref came from. */
+export type ActionTarget = { ref: string; snapshotId: number };
+
+export type ClickInput = ActionTarget;
+export type TypeInput = ActionTarget & {
+ text: string;
+ /** Press Enter afterwards. How a Bot submits a single-field form without hunting for the button. */
+ submit?: boolean;
+};
+export type KeyInput = Partial<ActionTarget> & { key: string };
+export type ScrollInput = { deltaY?: number };
+
+/**
+ * What an action reports back.
+ *
+ * Typed text is absent. This value is read by the model and written to the
+ * audit trail, and the contents of a form field is exactly where a password, a card number or a
+ * one-time code lives. The caller already knows what it sent, so echoing it buys nothing and puts a
+ * secret into two places that keep it. `characters` is enough to confirm the field was filled.
+ */
+export type ActionResult = {
+ action: "click" | "type" | "key" | "scroll";
+ ref?: string;
+ /**
+ * The label of the element acted on, as the gateway resolved it.
+ *
+ * The ref is an internal handle, so the response carries the readable element label.
+ */
+ element?: { role: string; name: string };
+ /** For `type`: how much was entered, never what. */
+ characters?: number;
+ submitted?: boolean;
+ key?: string;
+ deltaY?: number;
+ /** Where the page ended up, which is how a Bot notices that its click navigated. */
+ url: string;
+ elapsedMs: number;
+};
+
+/** Absent path means the whole workspace. */
+export type ListFilesInput = { path?: string };
+
+/** One thing in the workspace. Folders included, so a Bot can see the shape, not just the leaves. */
+export type WorkspaceEntry = {
+ /** Relative to the workspace root, which is the only form a request may use. */
+ path: string;
+ kind: "file" | "folder";
+ bytes?: number;
+};
+
+export type ListFilesResult = {
+ path: string;
+ entries: WorkspaceEntry[];
+ /** True when there was more in the workspace than the listing describes. */
+ truncated: boolean;
+};
+
+export type ReadFileInput = { path: string };
+export type ReadFileResult = {
+ path: string;
+ text: string;
+ /** True when the file was longer than the extract, so the Bot can say so rather than guess. */
+ truncated: boolean;
+ /** The file's real size, even when the text was cut. */
+ bytes: number;
+};
+
+export type WriteFileInput = {
+ path: string;
+ contents: string;
+ /** Add to the end instead of replacing, for a Bot keeping a running log. */
+ append?: boolean;
+};
+
+/**
+ * What a write reports back.
+ *
+ * The contents are not echoed, for the same reason typed text is not: a Bot may well be saving
+ * something it was told in confidence, and a value repeated into the transcript and the audit trail
+ * now lives in three places instead of one.
+ */
+export type WriteFileResult = {
+ path: string;
+ bytes: number;
+ appended: boolean;
+};
+
+/**
+ * Who is driving the computer.
+ *
+ * The expand overlay is where control lands. One browser, two possible drivers, never at once: while a person holds the wheel every acting call from the Bot
+ * is refused rather than queued, because a queued click arrives after the person has moved on.
+ */
+export type ControlHolder = "bot" | "human";
+
+export type ControlState = {
+ holder: ControlHolder;
+ /** ISO timestamp of the last handover, so the surface can say how long this has been going on. */
+ since: string;
+ /** Why the Bot asked for help, in its own words. Shown to the person being handed the wheel. */
+ reason?: string;
+ /** The Bot has asked and nobody has taken over yet. */
+ requested: boolean;
+};
+
+/**
+ * A value the Bot needs and must not be told: a password, a one-time code.
+ *
+ * `label` is what the person is asked for, and it is the only part of this that is ever stored or
+ * recorded. `ref` names the field it goes in, because a secret typed into whatever happens to have
+ * focus goes nowhere when nothing does, and reports success while doing it.
+ */
+export type SecretRequest = { label: string; ref: string; snapshotId: number };
+
+/**
+ * What supplying a secret reports back.
+ *
+ * `characters` and nothing else. The value is not returned, not logged and not audited: the point of
+ * the whole mechanism is that it exists in one place, the page it was typed into.
+ */
+/**
+ * One Bot's computer, as the admin surface lists it.
+ *
+ * A Bot that has a profile has a computer, whether or not a browser is running for it this second.
+ * That distinction is the point of the page: "not running" is the normal resting state of a computer
+ * nobody is using, and it is not a fault.
+ */
+export type ComputerProfile = {
+ botId: string;
+ running: boolean;
+ startedAt: string | null;
+ /**
+ * The host its traffic leaves through, or null for direct.
+ *
+ * Host only. A proxy is usually handed out as a URL with credentials in it, and this field is
+ * read by people and rendered in a browser.
+ */
+ egress: string | null;
+};
+
+export type SecretResult = {
+ supplied: boolean;
+ characters: number;
+ url: string;
+};
+
+/** What a person did with their mouse or keyboard. Coordinates are viewport pixels. */
+export type HumanInput =
+ | { kind: "click"; x: number; y: number }
+ | { kind: "type"; text: string }
+ | { kind: "key"; key: string }
+ | { kind: "scroll"; deltaY?: number };
+
+/**
+ * What a person's input reports back.
+ *
+ * Never the text. A takeover exists so a person can type the thing the Bot must not have, a password,
+ * a one-time code. That value goes from their keyboard to the browser and stops; it is not returned
+ * here, not written to the audit trail, and not on any path the model can read.
+ */
+export type HumanInputResult = {
+ action: "human_click" | "human_type" | "human_key" | "human_scroll";
+ characters?: number;
+ key?: string;
+ deltaY?: number;
+ url: string;
+};
+
+/** Lifecycle states a Bot's computer can be in, as the UI must render them. */
+export const COMPUTER_STATES = [
+ "absent",
+ "starting",
+ "ready",
+ "unreachable",
+] as const;
+
+export type ComputerState = (typeof COMPUTER_STATES)[number];
+
+export type ComputerStatus = {
+ botId: string;
+ state: ComputerState;
+ /** Set when state is "unreachable", in words a person can act on. */
+ reason?: string;
+};
diff --git a/server/src/connectors.ts b/server/src/connectors.ts
new file mode 100644
index 00000000..7ad7f7fa
--- /dev/null
+++ b/server/src/connectors.ts
@@ -0,0 +1,124 @@
+export type ConnectorStatus = {
+ id: string;
+ type: "google_drive" | "onedrive";
+ name: string;
+ roots: string[];
+ configured: boolean;
+};
+
+export type ConnectorAdminService = {
+ list: () => Promise<ConnectorStatus[]>;
+ configureGoogleDrive?: (input: {
+ serviceAccountJson: string;
+ impersonationSubject: string;
+ actorUserId: string;
+ }) => Promise<ConnectorStatus>;
+};
+
+type KnowledgeSource = {
+ type: "google-drive" | "microsoft-onedrive";
+ roots: string[];
+};
+
+export function createConnectorCatalogService(
+ sources: KnowledgeSource[],
+): ConnectorAdminService {
+ return {
+ list: async () =>
+ sources.map((source) =>
+ source.type === "google-drive"
+ ? {
+ id: "google-drive",
+ type: "google_drive",
+ name: "Google Drive",
+ roots: source.roots,
+ configured: false,
+ }
+ : {
+ id: "microsoft-onedrive",
+ type: "onedrive",
+ name: "Microsoft OneDrive",
+ roots: source.roots,
+ configured: false,
+ },
+ ),
+ };
+}
+
+export function createConnectorAdminService(
+ sources: KnowledgeSource[],
+ database: Database,
+ credentials: CredentialAdminService,
+): ConnectorAdminService {
+ const catalog = createConnectorCatalogService(sources);
+ return {
+ /**
+ * The catalogue, with each entry told whether this deployment has configured it.
+ *
+ * `knowledge.yaml` says what a deployment may connect to rather than what it has, so whether a
+ * connector is configured is read from the instances table instead.
+ */
+ list: async () => {
+ const configured = new Set(
+ (
+ await database
+ .select({ type: connectorInstances.type })
+ .from(connectorInstances)
+ ).map((row) => row.type),
+ );
+ return (await catalog.list()).map((connector) => ({
+ ...connector,
+ configured: configured.has(connector.type),
+ }));
+ },
+ configureGoogleDrive: async (input) => {
+ const source = sources.find((item) => item.type === "google-drive");
+ if (!source)
+ throw new Error("Google Drive is not enabled by knowledge.yaml");
+ const credential = await credentials.create({
+ kind: "connector",
+ provider: "google_drive",
+ keyId: input.impersonationSubject,
+ metadata: {},
+ plaintext: input.serviceAccountJson,
+ actorUserId: input.actorUserId,
+ });
+ const sourceMetadata = {
+ roots: source.roots,
+ impersonationSubject: input.impersonationSubject,
+ };
+ const [existing] = await database
+ .select({ id: connectorInstances.id })
+ .from(connectorInstances)
+ .where(eq(connectorInstances.type, "google_drive"));
+ if (existing) {
+ await database
+ .update(connectorInstances)
+ .set({
+ credentialId: credential.id,
+ sourceMetadata,
+ updatedAt: new Date(),
+ })
+ .where(eq(connectorInstances.id, existing.id));
+ } else {
+ await database.insert(connectorInstances).values({
+ type: "google_drive",
+ credentialId: credential.id,
+ sourceMetadata,
+ });
+ }
+ return {
+ id: "google-drive",
+ type: "google_drive",
+ name: "Google Drive",
+ roots: source.roots,
+ configured: true,
+ };
+ },
+ };
+}
+
+import { eq } from "drizzle-orm";
+import type { CredentialAdminService } from "./credentials";
+import type { Database } from "./db/client";
+import { connectorInstances } from "./db/schema";
diff --git a/server/src/copilot.ts b/server/src/copilot.ts
new file mode 100644
index 00000000..c555edaf
--- /dev/null
+++ b/server/src/copilot.ts
@@ -0,0 +1,352 @@
+import { AbstractAgent, HttpAgent } from "@ag-ui/client";
+import type { BuiltInAgentConfiguration } from "@copilotkit/runtime/v2";
+import {
+ BuiltInAgent,
+ CopilotKitIntelligence,
+ CopilotRuntime,
+} from "@copilotkit/runtime/v2";
+import { createCopilotHonoHandler } from "@copilotkit/runtime/v2/hono";
+import type { AgentActor } from "./agents/profile-types";
+import type { DeploymentConfig } from "./config";
+
+/**
+ * The CopilotKit runtime, always in Intelligence mode.
+ *
+ * Package-declared built-in Bots run as CopilotKit `BuiltInAgent` instances. External Bots are
+ * reached over AG-UI as `HttpAgent` instances, so anything that speaks the protocol remains a Bot
+ * with no framework adapter here: LangGraph, Pydantic-AI, CrewAI, Mastra, ADK, or a hand-written
+ * server.
+ *
+ * There is no SSE branch. Intelligence is a requirement of the product, not a tier: it owns
+ * durable threads, memory and learning, and a deployment without it silently forgets every
+ * conversation. config.ts refuses to boot without the full contract, so by the time this runs the
+ * settings are present and this file has one mode.
+ */
+
+/** Resolve the signed-in person for a request. Threads and memory are scoped to whoever this returns. */
+export type IdentifyUser = (
+ request: Request,
+) => Promise<{ id: string; name: string }>;
+
+type RegisteredBuiltInAgent = {
+ id: string;
+ name: string;
+ type: "built_in";
+ systemPrompt: string;
+};
+
+type RegisteredRemoteAgent = {
+ id: string;
+ name: string;
+ type: "remote_ag_ui";
+ endpoint: string;
+ standingMessage: StandingRoleMessage;
+ /** The key this agent sits behind, resolved from the vault at load time. Never logged. */
+ headers?: Record<string, string>;
+};
+
+/**
+ * A teammate the caller may see but may not run: its profile was deleted while a channel it worked
+ * in still exists. It is registered so Intelligence can restore that thread and the person can read
+ * what was said; every run is refused here, without contacting the endpoint.
+ */
+type RegisteredUnavailableAgent = {
+ id: string;
+ name: string;
+ type: "unavailable";
+ reason: string;
+};
+
+export type RegisteredAgent =
+ | RegisteredBuiltInAgent
+ | RegisteredRemoteAgent
+ | RegisteredUnavailableAgent;
+
+type AgentRunInput = Parameters<AbstractAgent["run"]>[0];
+type AgentMessage = AgentRunInput["messages"][number];
+export type StandingRoleMessage = Extract<AgentMessage, { role: "system" }>;
+
+/** The durable part of a teammate: who it is and what its standing job is. */
+export type AgentStandingProfile = {
+ id: string;
+ name: string;
+ title: string;
+ roleDescription: string;
+};
+
+/**
+ * The teammate's job, as one system message.
+ *
+ * It is an ordinary AG-UI system message rather than `forwardedProps` or framework-specific state
+ * because the endpoint on the other side may be LangGraph, Mastra, ADK or a hand-written server, and
+ * a system message is the only thing all of them already understand. The id is derived from the
+ * agent so a run can recognise a copy of it and refuse to send a second.
+ */
+export function standingRoleMessage(
+ profile: AgentStandingProfile,
+): StandingRoleMessage {
+ return {
+ id: `standing-role:${profile.id}`,
+ role: "system",
+ content: [
+ `You are ${profile.name}, ${profile.title}.`,
+ profile.roleDescription,
+ "This standing role applies in every channel. Treat channel messages as task-specific instructions within it.",
+ ].join("\n\n"),
+ };
+}
+
+export type RuntimeModel = {
+ provider: "openai";
+ defaultModel: string;
+};
+
+type RuntimeAgentRow = {
+ id: string;
+ name: string;
+ type: "built_in" | "remote_ag_ui";
+ configuration: unknown;
+ title: string;
+ roleDescription: string;
+};
+
+export function registeredAgentFromRow(
+ row: RuntimeAgentRow,
+): RegisteredAgent | null {
+ if (!isPlainObject(row.configuration)) {
+ return null;
+ }
+ const configuration = row.configuration;
+ if (row.type === "built_in") {
+ const systemPrompt = configuration?.systemPrompt;
+ const trimmedSystemPrompt =
+ typeof systemPrompt === "string" ? systemPrompt.trim() : "";
+ return trimmedSystemPrompt.length > 0
+ ? {
+ id: row.id,
+ name: row.name,
+ type: "built_in",
+ systemPrompt: trimmedSystemPrompt,
+ }
+ : null;
+ }
+
+ const endpoint = configuration?.endpoint;
+ return typeof endpoint === "string" && isHttpUrl(endpoint)
+ ? {
+ id: row.id,
+ name: row.name,
+ type: "remote_ag_ui",
+ endpoint,
+ standingMessage: standingRoleMessage(row),
+ }
+ : null;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return false;
+ }
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+function isHttpUrl(value: string) {
+ try {
+ return ["http:", "https:"].includes(new URL(value).protocol);
+ } catch {
+ return false;
+ }
+}
+
+export function builtInAgentConfiguration(
+ agent: RegisteredBuiltInAgent,
+ model: RuntimeModel,
+ apiKey: string | null,
+): BuiltInAgentConfiguration {
+ if (!apiKey) {
+ return {
+ type: "custom",
+ // biome-ignore lint/correctness/useYield: this agent must fail when iteration starts.
+ factory: async function* () {
+ throw new Error(
+ `Model credential is not configured for ${agent.name}. Add the package credential or set OPENAI_API_KEY.`,
+ );
+ },
+ };
+ }
+
+ return {
+ model: `${model.provider}/${model.defaultModel}`,
+ prompt: agent.systemPrompt,
+ apiKey,
+ };
+}
+
+/**
+ * Build the built-in and remote AG-UI agent map the runtime serves.
+ *
+ * Keyed by the registry id, which is what the browser sends as the agent name, so the two cannot
+ * drift apart without the lookup failing loudly rather than silently running the wrong Bot.
+ */
+export function buildAgents(
+ agents: RegisteredAgent[],
+ model: RuntimeModel,
+ apiKey: string | null,
+): Record<string, AbstractAgent> {
+ return Object.fromEntries(
+ agents.map((agent) => [agent.id, buildAgent(agent, model, apiKey)]),
+ );
+}
+
+function buildAgent(
+ agent: RegisteredAgent,
+ model: RuntimeModel,
+ apiKey: string | null,
+): AbstractAgent {
+ if (agent.type === "built_in") {
+ return new BuiltInAgent(builtInAgentConfiguration(agent, model, apiKey));
+ }
+ if (agent.type === "unavailable") {
+ return new UnavailableAgent(agent);
+ }
+ return remoteAgentWithStandingRole(agent);
+}
+
+/**
+ * A remote AG-UI agent that states its standing role on every run.
+ *
+ * This is standard AG-UI middleware rather than a request transformation on one provider's client,
+ * so the same teammate works against any endpoint that speaks the protocol. Any copy of the standing
+ * message already in the conversation is dropped: the endpoint must receive exactly one, first,
+ * however many times the thread has been replayed.
+ */
+function remoteAgentWithStandingRole(agent: RegisteredRemoteAgent) {
+ const remote = new HttpAgent({
+ url: agent.endpoint,
+ agentId: agent.id,
+ // The customer's own key, if their agent sits behind one. `HttpAgentConfig` is
+ // `{ url, headers?, fetch? }`, verified against @ag-ui/client 0.0.57.
+ ...(agent.headers ? { headers: agent.headers } : {}),
+ });
+ remote.use((input, next) =>
+ next.run({
+ ...input,
+ messages: [
+ agent.standingMessage,
+ ...input.messages.filter(
+ (message) => message.id !== agent.standingMessage.id,
+ ),
+ ],
+ }),
+ );
+ return remote;
+}
+
+class UnavailableAgent extends AbstractAgent {
+ private readonly reason: string;
+
+ constructor(agent: RegisteredUnavailableAgent) {
+ super({ agentId: agent.id, description: agent.name });
+ this.reason = agent.reason;
+ }
+
+ // Refused here rather than at the endpoint: a deleted teammate has no endpoint worth contacting,
+ // and the person is owed the reason rather than a transport error.
+ run(): never {
+ throw new Error(this.reason);
+ }
+}
+
+export async function resolveRuntimeAgents(
+ loadAgents: () => Promise<RegisteredAgent[]>,
+ model: RuntimeModel,
+ resolveModelApiKey: () => Promise<string | null>,
+): Promise<Record<string, AbstractAgent>> {
+ const registered = await loadAgents();
+ if (registered.length === 0) {
+ throw new Error(
+ "No agents are registered. Add one to the tenant package or the agents table.",
+ );
+ }
+
+ const apiKey = registered.some((agent) => agent.type === "built_in")
+ ? await resolveModelApiKey()
+ : null;
+ return buildAgents(registered, model, apiKey);
+}
+
+/** Who is asking. Agent visibility is decided per person, so a run has to know this first. */
+export type IdentifyActor = (request: Request) => Promise<AgentActor>;
+
+/** Loads exactly the agents one person may see, already carrying their standing roles. */
+export type LoadAgentsForActor = (
+ actor: AgentActor,
+) => Promise<RegisteredAgent[]>;
+
+/**
+ * Build the runtime's per-request agent factory.
+ *
+ * Resolution is per request, not per boot, because who may run a teammate is a property of the
+ * person asking: a private teammate must be absent for everybody else, and a role edited a moment
+ * ago must apply to the next run without a restart. Both fall out of rebuilding the map here.
+ */
+export function createRequestAgents(
+ identifyActor: IdentifyActor,
+ loadAgents: LoadAgentsForActor,
+ model: RuntimeModel,
+ resolveModelApiKey: () => Promise<string | null>,
+) {
+ return async ({ request }: { request: Request }) => {
+ const actor = await identifyActor(request);
+ return resolveRuntimeAgents(
+ () => loadAgents(actor),
+ model,
+ resolveModelApiKey,
+ );
+ };
+}
+
+/**
+ * Mount the CopilotKit endpoint onto the host Hono app.
+ *
+ * `agents` is a factory rather than a fixed map so a Bot registered while the server is running is
+ * reachable on the next request. Resolving once at boot would mean every new Bot needed a restart,
+ * which is not a property you can explain to somebody who just created one.
+ */
+export function mountCopilotRuntime(
+ config: DeploymentConfig,
+ model: RuntimeModel,
+ loadAgents: LoadAgentsForActor,
+ resolveModelApiKey: () => Promise<string | null>,
+ identifyUser: IdentifyUser,
+ identifyActor: IdentifyActor,
+ basePath = "/api/copilotkit",
+) {
+ const { intelligence } = config.runtime;
+
+ const runtime = new CopilotRuntime({
+ // `mode` is inferred from the presence of `intelligence`; passing it is a type error.
+ //
+ // identifyUser is NOT optional in practice. Threads and memory are scoped to the user it
+ // returns, so omitting it puts every person in the deployment in the same thread space and one
+ // person's conversations become another's.
+ identifyUser,
+ intelligence: new CopilotKitIntelligence({
+ apiUrl: intelligence.apiUrl,
+ wsUrl: intelligence.gatewayWsUrl,
+ apiKey: intelligence.apiKey,
+ }),
+ licenseToken: intelligence.licenseToken,
+ // `identifyUser` is the Intelligence projection of the same person `identifyActor` returns:
+ // one resolver decides both whose threads these are and whose teammates exist.
+ agents: createRequestAgents(
+ identifyActor,
+ loadAgents,
+ model,
+ resolveModelApiKey,
+ ) as never,
+ });
+
+ return createCopilotHonoHandler({ runtime, basePath });
+}
diff --git a/server/src/credentials.ts b/server/src/credentials.ts
new file mode 100644
index 00000000..ddd6c599
--- /dev/null
+++ b/server/src/credentials.ts
@@ -0,0 +1,358 @@
+import { and, desc, eq, isNull } from "drizzle-orm";
+import { type AuditStore, recordAuditEvent } from "./audit";
+import type { Database } from "./db/client";
+import { credentials } from "./db/schema";
+
+type CredentialEnvelope = {
+ version: 1;
+ iv: string;
+ ciphertext: string;
+};
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+export type CredentialKind = "model" | "connector" | "agent" | "mcp";
+
+export type CredentialStatus = {
+ id: string;
+ kind: CredentialKind;
+ provider: string;
+ keyId: string;
+ metadata: Record<string, unknown>;
+ revokedAt: Date | null;
+};
+
+type StoredCredential = {
+ id: string;
+ revokedAt: Date | null;
+};
+
+export type CredentialStore = {
+ create: (value: {
+ kind: CredentialKind;
+ provider: string;
+ keyId: string;
+ metadata: Record<string, unknown>;
+ encryptedValue: string;
+ }) => Promise<StoredCredential>;
+ revoke: (id: string) => Promise<Date>;
+};
+
+export type CredentialSecretReader = {
+ readSecret: (id: string) => Promise<{
+ encryptedValue: string;
+ revokedAt: Date | null;
+ } | null>;
+};
+
+export type CredentialStatusReader = {
+ list: () => Promise<CredentialStatus[]>;
+};
+
+export type ModelCredentialSecretReader = {
+ readModelSecret: (input: {
+ provider: "openai";
+ keyId: string;
+ }) => Promise<{ encryptedValue: string } | null>;
+};
+
+type CredentialService = {
+ encryptionKey: string;
+ store: CredentialStore;
+ auditStore: AuditStore;
+};
+
+async function aesKey(encodedKey: string) {
+ return crypto.subtle.importKey(
+ "raw",
+ Buffer.from(encodedKey, "base64"),
+ { name: "AES-GCM" },
+ false,
+ ["encrypt", "decrypt"],
+ );
+}
+
+function parseEnvelope(value: string): CredentialEnvelope {
+ try {
+ const envelope = JSON.parse(value) as CredentialEnvelope;
+ if (
+ envelope.version !== 1 ||
+ typeof envelope.iv !== "string" ||
+ typeof envelope.ciphertext !== "string"
+ ) {
+ throw new Error("invalid envelope");
+ }
+ return envelope;
+ } catch {
+ throw new Error("Credential envelope is invalid");
+ }
+}
+
+export async function encryptSecret(encodedKey: string, plaintext: string) {
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const ciphertext = await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv },
+ await aesKey(encodedKey),
+ encoder.encode(plaintext),
+ );
+
+ return JSON.stringify({
+ version: 1,
+ iv: Buffer.from(iv).toString("base64"),
+ ciphertext: Buffer.from(ciphertext).toString("base64"),
+ } satisfies CredentialEnvelope);
+}
+
+export async function decryptSecret(encodedKey: string, value: string) {
+ const envelope = parseEnvelope(value);
+ const plaintext = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: Buffer.from(envelope.iv, "base64") },
+ await aesKey(encodedKey),
+ Buffer.from(envelope.ciphertext, "base64"),
+ );
+
+ return decoder.decode(plaintext);
+}
+
+export async function decryptCredentialForUse(
+ encodedKey: string,
+ reader: CredentialSecretReader,
+ credentialId: string,
+) {
+ const credential = await reader.readSecret(credentialId);
+ if (!credential) {
+ throw new Error("Credential was not found");
+ }
+ if (credential.revokedAt) {
+ throw new Error("Credential is revoked");
+ }
+
+ return decryptSecret(encodedKey, credential.encryptedValue);
+}
+
+export async function resolveModelApiKey(input: {
+ encryptionKey: string;
+ reader: ModelCredentialSecretReader;
+ provider: "openai";
+ keyId: string;
+ environment: Record<string, string | undefined>;
+}) {
+ const stored = await input.reader.readModelSecret({
+ provider: input.provider,
+ keyId: input.keyId,
+ });
+ if (stored) {
+ return decryptSecret(input.encryptionKey, stored.encryptedValue);
+ }
+
+ const environmentKey = input.environment.OPENAI_API_KEY?.trim();
+ return environmentKey || null;
+}
+
+export function createCredentialStore(
+ database: Database,
+): CredentialStore &
+ CredentialSecretReader &
+ CredentialStatusReader &
+ ModelCredentialSecretReader {
+ return {
+ create: async (value) => {
+ const [credential] = await database
+ .insert(credentials)
+ .values(value)
+ .returning({ id: credentials.id, revokedAt: credentials.revokedAt });
+
+ if (!credential) {
+ throw new Error("Credential could not be stored");
+ }
+ return credential;
+ },
+ revoke: async (id) => {
+ const revokedAt = new Date();
+ const [credential] = await database
+ .update(credentials)
+ .set({ revokedAt, updatedAt: revokedAt })
+ .where(eq(credentials.id, id))
+ .returning({ revokedAt: credentials.revokedAt });
+
+ if (!credential?.revokedAt) {
+ throw new Error("Credential was not found");
+ }
+ return credential.revokedAt;
+ },
+ readSecret: async (id) => {
+ const [credential] = await database
+ .select({
+ encryptedValue: credentials.encryptedValue,
+ revokedAt: credentials.revokedAt,
+ })
+ .from(credentials)
+ .where(eq(credentials.id, id));
+
+ return credential ?? null;
+ },
+ readModelSecret: async ({ provider, keyId }) => {
+ const [credential] = await database
+ .select({ encryptedValue: credentials.encryptedValue })
+ .from(credentials)
+ .where(
+ and(
+ eq(credentials.kind, "model"),
+ eq(credentials.provider, provider),
+ eq(credentials.keyId, keyId),
+ isNull(credentials.revokedAt),
+ ),
+ )
+ .orderBy(
+ desc(credentials.createdAt),
+ // UUID descending selects the lexicographically greatest ID on a timestamp tie.
+ desc(credentials.id),
+ )
+ .limit(1);
+
+ return credential ?? null;
+ },
+ list: async () => {
+ const records = await database
+ .select({
+ id: credentials.id,
+ kind: credentials.kind,
+ provider: credentials.provider,
+ keyId: credentials.keyId,
+ metadata: credentials.metadata,
+ revokedAt: credentials.revokedAt,
+ })
+ .from(credentials)
+ .orderBy(credentials.createdAt);
+
+ return records.map((credential) => ({
+ ...credential,
+ metadata: credential.metadata as Record<string, unknown>,
+ }));
+ },
+ };
+}
+
+export type CredentialInput = {
+ kind: CredentialKind;
+ provider: string;
+ keyId: string;
+ metadata: Record<string, unknown>;
+ plaintext: string;
+ actorUserId?: string;
+};
+
+export type CredentialAdminService = CredentialStatusReader & {
+ create: (input: CredentialInput) => Promise<CredentialStatus>;
+ rotate: (
+ input: CredentialInput & { previousCredentialId: string },
+ ) => Promise<CredentialStatus>;
+ revoke: (
+ credentialId: string,
+ actorUserId?: string,
+ ) => Promise<{
+ id: string;
+ revokedAt: Date;
+ }>;
+};
+
+async function persistCredential(
+ service: CredentialService,
+ input: CredentialInput,
+): Promise<CredentialStatus> {
+ const stored = await service.store.create({
+ kind: input.kind,
+ provider: input.provider,
+ keyId: input.keyId,
+ metadata: input.metadata,
+ encryptedValue: await encryptSecret(service.encryptionKey, input.plaintext),
+ });
+
+ return {
+ id: stored.id,
+ kind: input.kind,
+ provider: input.provider,
+ keyId: input.keyId,
+ metadata: input.metadata,
+ revokedAt: stored.revokedAt,
+ };
+}
+
+export async function createCredential(
+ service: CredentialService,
+ input: CredentialInput,
+): Promise<CredentialStatus> {
+ const credential = await persistCredential(service, input);
+
+ await recordAuditEvent(service.auditStore, {
+ eventType: "credential.created",
+ targetType: "credential",
+ targetId: credential.id,
+ actorUserId: input.actorUserId,
+ payload: {
+ kind: input.kind,
+ provider: input.provider,
+ keyId: input.keyId,
+ },
+ });
+
+ return credential;
+}
+
+export async function rotateCredential(
+ service: CredentialService,
+ input: CredentialInput & { previousCredentialId: string },
+) {
+ const credential = await persistCredential(service, input);
+ await service.store.revoke(input.previousCredentialId);
+
+ await recordAuditEvent(service.auditStore, {
+ eventType: "credential.rotated",
+ targetType: "credential",
+ targetId: credential.id,
+ actorUserId: input.actorUserId,
+ payload: {
+ previousCredentialId: input.previousCredentialId,
+ kind: input.kind,
+ provider: input.provider,
+ keyId: input.keyId,
+ },
+ });
+
+ return credential;
+}
+
+export async function revokeCredential(
+ service: CredentialService,
+ credentialId: string,
+ actorUserId?: string,
+) {
+ const revokedAt = await service.store.revoke(credentialId);
+
+ await recordAuditEvent(service.auditStore, {
+ eventType: "credential.revoked",
+ targetType: "credential",
+ targetId: credentialId,
+ actorUserId,
+ payload: {},
+ });
+
+ return { id: credentialId, revokedAt };
+}
+
+export function createCredentialAdminService(
+ encryptionKey: string,
+ store: CredentialStore & CredentialStatusReader,
+ auditStore: AuditStore,
+): CredentialAdminService {
+ const service = { encryptionKey, store, auditStore };
+
+ return {
+ list: store.list,
+ create: (input) => createCredential(service, input),
+ rotate: (input) => rotateCredential(service, input),
+ revoke: (credentialId, actorUserId) =>
+ revokeCredential(service, credentialId, actorUserId),
+ };
+}
diff --git a/server/src/db/client.ts b/server/src/db/client.ts
new file mode 100644
index 00000000..d197dc0e
--- /dev/null
+++ b/server/src/db/client.ts
@@ -0,0 +1,23 @@
+import { SQL } from "bun";
+import { drizzle } from "drizzle-orm/bun-sql";
+import * as schema from "./schema";
+
+/**
+ * `max` is exposed so tests can pin the pool to a single connection. Code that opens a transaction
+ * and then reads on a second connection deadlocks once every pooled connection is inside such a
+ * transaction; a pool of one turns that from a load-dependent production hang into an immediate,
+ * reproducible failure.
+ */
+export function createDatabase(
+ databaseUrl: string,
+ options: { max?: number } = {},
+) {
+ const client =
+ options.max === undefined
+ ? new SQL(databaseUrl)
+ : new SQL(databaseUrl, { max: options.max });
+
+ return drizzle({ client, schema });
+}
+
+export type Database = ReturnType<typeof createDatabase>;
diff --git a/server/src/db/schema/components.ts b/server/src/db/schema/components.ts
new file mode 100644
index 00000000..667bb125
--- /dev/null
+++ b/server/src/db/schema/components.ts
@@ -0,0 +1,107 @@
+import {
+ boolean,
+ pgTable,
+ primaryKey,
+ text,
+ timestamp,
+} from "drizzle-orm/pg-core";
+import { agents } from "./core";
+
+const createdAt = () =>
+ timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
+const updatedAt = () =>
+ timestamp("updated_at", { withTimezone: true }).notNull().defaultNow();
+
+/**
+ * A component a Bot may answer with, and the state that governs it.
+ *
+ * The code owns the component; this table owns its governance. The React file and its schema are
+ * compiled into the app and cannot be edited from here. What lives in a row is everything a
+ * deployment decides at runtime: whether it is published at all, what the model is told about it, and
+ * who last changed that. A fork that deletes `RecordCard` leaves a row with nothing to draw it, which
+ * the Admin page reports rather than hiding, a catalogue that silently disagrees with the build is
+ * worse than one that says so.
+ *
+ * `name` is the primary key and a contract. It is the tool name the model calls, the key the
+ * app maps to a renderer, and the thing a customer's fork keeps when it replaces the component. A
+ * surrogate id would let two rows claim one name and would break that mapping silently.
+ */
+export const components = pgTable("components", {
+ name: text("name").primaryKey(),
+ title: text("title").notNull(),
+ /** Grouping for the Admin page only: chart, card, decision. Never read by the model. */
+ kind: text("kind").notNull(),
+
+ /**
+ * The draft and the published description, which is the only version pair a compiled component can
+ * have.
+ *
+ * The description is not decoration: it is what the model reads while deciding whether to call
+ * this component at all, so changing it changes behaviour. That makes it exactly the thing that
+ * should not take effect the moment somebody types it. A draft is edited freely and changes
+ * nothing; publishing promotes it and the next run sees it.
+ */
+ draftDescription: text("draft_description").notNull(),
+ /** Null until first published. Null means the model is never offered this component. */
+ publishedDescription: text("published_description"),
+
+ published: boolean("published").notNull().default(false),
+ publishedAt: timestamp("published_at", { withTimezone: true }),
+ /** Who last changed anything about this component. An email, because that is what a reader knows. */
+ updatedBy: text("updated_by"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
+/**
+ * One Bot held back from one component. A published component is available to every Bot; a row here
+ * is the exception.
+ *
+ * Open by default because a component is a way of answering, not a way of reaching anything. What a
+ * component may READ is {@link componentFunctions}, which is strict: no row, no call.
+ */
+export const componentExclusions = pgTable(
+ "component_exclusions",
+ {
+ componentName: text("component_name")
+ .notNull()
+ .references(() => components.name, { onDelete: "cascade" }),
+ agentId: text("agent_id")
+ .notNull()
+ .references(() => agents.id, { onDelete: "cascade" }),
+ /** An email. Who decided this Bot should not answer with this. */
+ withheldBy: text("withheld_by"),
+ withheldAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (table) => [primaryKey({ columns: [table.componentName, table.agentId] })],
+);
+
+/**
+ * The functions one component may call. A row is the permission.
+ *
+ * Same shape as a grant, for the same reason. Absence is the refusal, so a component nobody has
+ * granted anything can call nothing, including a component somebody added this morning, and one
+ * whose grants were lost. There is no "denied" row to forget to write.
+ *
+ * Keyed on the component, not the Bot. A component only renders for a Bot that
+ * holds it, so the Bot is already gated one level up; adding it here would be a second lock on the
+ * same door and a second place for the two to disagree. Which Bot was on screen is recorded on every
+ * call, because that is a fact about the call rather than about the permission.
+ */
+export const componentFunctions = pgTable(
+ "component_functions",
+ {
+ componentName: text("component_name")
+ .notNull()
+ .references(() => components.name, { onDelete: "cascade" }),
+ /** The name of a function this build ships. Not a foreign key: functions live in code. */
+ functionName: text("function_name").notNull(),
+ grantedBy: text("granted_by"),
+ grantedAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (table) => [
+ primaryKey({ columns: [table.componentName, table.functionName] }),
+ ],
+);
diff --git a/server/src/db/schema/json.ts b/server/src/db/schema/json.ts
new file mode 100644
index 00000000..71c55385
--- /dev/null
+++ b/server/src/db/schema/json.ts
@@ -0,0 +1,29 @@
+import { customType } from "drizzle-orm/pg-core";
+
+/**
+ * A `jsonb` column that actually stores JSON.
+ *
+ * Drizzle's ordinary `jsonb()` serialises the value in `mapToDriverValue`, and Bun's `SQL` driver
+ * serialises it again on the way to Postgres. Objects that need SQL JSON operators use this custom
+ * type so they are stored as JSON objects. The same insert through both paths:
+ *
+ * drizzle jsonb() jsonb_typeof = "string" payload->>'bot' = NULL
+ * this type jsonb_typeof = "object" payload->>'bot' = "y"
+ *
+ * Application reads can still render double-encoded values as objects. SQL consumers require stored
+ * JSON objects so fields such as `payload->>'bot'` stay queryable.
+ *
+ * Serialize once. The driver already knows how to send an object to a `jsonb`
+ * parameter, so this hands it the object and stays out of the way. Reads are unchanged: both paths
+ * return an object, which is why this can be swapped in without touching a single call site.
+ *
+ * Use this everywhere instead of `jsonb` from `drizzle-orm/pg-core`.
+ */
+export const jsonb = customType<{
+ data: Record<string, unknown>;
+ driverData: unknown;
+}>({
+ dataType: () => "jsonb",
+ // Straight through. The double `JSON.stringify` is the whole bug.
+ toDriver: (value) => value,
+});
diff --git a/server/src/db/schema/plugins.ts b/server/src/db/schema/plugins.ts
new file mode 100644
index 00000000..482d058c
--- /dev/null
+++ b/server/src/db/schema/plugins.ts
@@ -0,0 +1,236 @@
+import {
+ boolean,
+ index,
+ integer,
+ pgTable,
+ primaryKey,
+ text,
+ timestamp,
+ uniqueIndex,
+} from "drizzle-orm/pg-core";
+import { agents, users } from "./core";
+import { jsonb } from "./json";
+
+const createdAt = () =>
+ timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
+const updatedAt = () =>
+ timestamp("updated_at", { withTimezone: true }).notNull().defaultNow();
+
+/**
+ * Schema owned by Plugins: MCP servers a deployment has added, the tools they offer, packaged
+ * skills, and which Bots may use any of it.
+ *
+ * One surface for both. A tool from an MCP server and a
+ * packaged skill are different things to build and the same thing to govern: somebody adds it once
+ * for the deployment, and then decides which Bots may use it. Two tables with two grant surfaces
+ * would give an operator two places to look and two ways to be wrong about what a Bot can reach.
+ */
+
+/**
+ * An MCP server this deployment has added.
+ *
+ * Account-wide, not per-Bot. Adding a server is an administrative act with a
+ * credential behind it; which Bots may use its tools is a separate decision, recorded in
+ * {@link pluginGrants}. Conflating them would mean adding a server to a second Bot re-entered the
+ * credential, and a deployment would end up with the same vendor authorised several times over with
+ * no single place to revoke it.
+ *
+ * `id` is the slug and a contract: it prefixes every tool name the model is offered, so a tool
+ * from two servers can never collide, and a rule written against `mcp.server == "atlassian"` keeps
+ * meaning the same thing after somebody renames the display title.
+ */
+export const mcpServers = pgTable("mcp_servers", {
+ id: text("id").primaryKey(),
+ title: text("title").notNull(),
+ /** The vendor this server is maintained by, which is what the first-party rule is checked against. */
+ vendor: text("vendor").notNull(),
+ url: text("url").notNull(),
+ /**
+ * `first-party` for a curated entry, `custom` for one an administrator added by URL.
+ *
+ * Recorded because the two are not the same risk. A curated entry has reviewed source provenance
+ * and a pinned host. A custom one is a URL somebody typed, and every surface that lists it says so.
+ * Storing which it is means the Plugins page, the audit trail and anybody reading the database
+ * later all agree about how a server got here, rather than inferring it from whether the host
+ * happens to still be in this build's catalogue.
+ */
+ provenance: text("provenance").notNull().default("first-party"),
+ /**
+ * The vault row holding this server's credential, or null for a server that needs none.
+ *
+ * A pointer rather than the secret: the vault owns encryption, rotation and revocation, and a
+ * second copy of a token here would be a second thing to remember to revoke.
+ */
+ credentialId: text("credential_id"),
+ /** What the deployment last heard back from it. `null` until the first successful listing. */
+ toolsRefreshedAt: timestamp("tools_refreshed_at", { withTimezone: true }),
+ /** The last failure, kept so the Plugins page can say why a server has no tools. */
+ lastError: text("last_error"),
+ addedBy: text("added_by"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
+/**
+ * A tool one server says it offers, as of the last listing.
+ *
+ * A cache of what the server said, never a source of truth about what it will accept. The row exists
+ * so the Plugins page and the `@` menu can show a list without a network call per render, and so a
+ * grant can name a tool that is not reachable this second. Every actual call re-reads the server.
+ *
+ * Rows are replaced wholesale on each refresh rather than merged, so a tool a vendor withdrew stops
+ * being offered instead of lingering as a name the model will call and the server will reject.
+ */
+export const mcpTools = pgTable(
+ "mcp_tools",
+ {
+ serverId: text("server_id")
+ .notNull()
+ .references(() => mcpServers.id, { onDelete: "cascade" }),
+ name: text("name").notNull(),
+ description: text("description").notNull().default(""),
+ /** The tool's own JSON Schema, passed to the model unchanged. */
+ inputSchema: jsonb("input_schema").notNull().default({}),
+ createdAt: createdAt(),
+ },
+ (table) => [primaryKey({ columns: [table.serverId, table.name] })],
+);
+
+/**
+ * A packaged skill: a named instruction a person invokes with `/` and a Bot follows.
+ *
+ * Not a tool, and the difference matters. A tool is something a Bot calls; a skill is something a
+ * Bot is told. Writing one adds no capability at all: it can only ask a Bot to use what that Bot was
+ * already granted, and every one of those calls is still decided, policy-checked and audited. The
+ * firewall is at the tool call, not at the prose, which is why anybody may write a skill while
+ * adding an MCP server stays an administrator's decision.
+ */
+export const skills = pgTable(
+ "skills",
+ {
+ id: text("id").primaryKey(),
+ /**
+ * Whose skill this is. Null means the deployment's: written by an administrator, or shipped,
+ * and offered to everybody.
+ *
+ * A person's own skill is theirs alone. They may write one freely and put it on a Bot they own,
+ * and nobody else sees it in their `/` menu or their list.
+ */
+ ownerUserId: text("owner_user_id").references(() => users.id, {
+ onDelete: "cascade",
+ }),
+ /**
+ * What a person types after `/`, and unique across the deployment rather than per person.
+ *
+ * The `/` namespace is shared because Bots are shared: two different behaviours answering to
+ * `/standup` in one deployment is confusing wherever the second one came from. First to take a
+ * name keeps it, and the refusal says so.
+ */
+ slug: text("slug").notNull(),
+ title: text("title").notNull(),
+ /** One line, shown in the catalogue and in the `/` menu. */
+ summary: text("summary").notNull(),
+ /** The instruction itself, prepended to the run when the skill is invoked. */
+ instructions: text("instructions").notNull(),
+ /** Where it came from: `catalogue` for one we ship, `yours` for one somebody wrote here. */
+ origin: text("origin").notNull().default("yours"),
+ installedBy: text("installed_by"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (table) => [
+ uniqueIndex("skills_slug_key").on(table.slug),
+ index("skills_owner_idx").on(table.ownerUserId),
+ ],
+);
+
+/**
+ * One Bot's hold on one plugin, whether that plugin is an MCP tool or a skill. A row is the grant.
+ *
+ * Absence is the refusal, the same shape component grants use and for the same reason. A Bot
+ * created before a server was added, a deployment that lost this table, a tool nobody ever enabled:
+ * all of them land on "not granted", which is a refusal. An `enabled` boolean would make a missing
+ * row undefined behaviour, and undefined behaviour in a grant table resolves to "allowed" the first
+ * time somebody is in a hurry.
+ *
+ * One table for both kinds. `kind` says which, and `ref` names it: `<serverId>/<toolName>` for an
+ * MCP tool, the slug for a skill. A second table would mean two code paths asking the same question
+ * and two chances for them to disagree.
+ */
+export const pluginGrants = pgTable(
+ "plugin_grants",
+ {
+ kind: text("kind").notNull(),
+ ref: text("ref").notNull(),
+ agentId: text("agent_id")
+ .notNull()
+ .references(() => agents.id, { onDelete: "cascade" }),
+ grantedBy: text("granted_by"),
+ grantedAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (table) => [
+ primaryKey({ columns: [table.kind, table.ref, table.agentId] }),
+ index("plugin_grants_agent_idx").on(table.agentId),
+ ],
+);
+
+/**
+ * A component authored in the browser rather than compiled into the build.
+ *
+ * This is not a column on `components`. That table governs components the build ships: its rows
+ * describe something the code already owns, and a fork that deletes the React file leaves a row the
+ * Admin page reports as missing. A sandboxed component has no React file and never will, so the
+ * source is the row. Putting the source on the same table would mean every compiled component
+ * carried three permanently empty columns, and "is this row backed by code" would become a question
+ * about whether a text field happened to be blank.
+ *
+ * The two share the grant surface and the publish gate, because an operator deciding what a Bot may
+ * answer with should not have to know which of the two they are looking at.
+ */
+export const sandboxedComponents = pgTable("sandboxed_components", {
+ /** The tool name the model calls. Namespaced on save so it can never collide with a compiled one. */
+ name: text("name").primaryKey(),
+ title: text("title").notNull(),
+
+ /**
+ * The draft, which is what the playground edits, and the published copy, which is the only version
+ * that ever renders or reaches a model.
+ *
+ * Separate columns rather than one live body. Publishing without a rebuild is the whole point of
+ * this table, and it is also what makes an editor one keystroke away from changing what every Bot
+ * draws in production. A draft absorbs that: it is edited freely, previewed against sample
+ * arguments, and changes nothing until somebody publishes it. Same reason the catalogue splits a compiled
+ * component's description, and the same fail-closed property: null published means no model is
+ * ever offered this component, so a half-written draft cannot be called.
+ */
+ draftDescription: text("draft_description").notNull().default(""),
+ draftHtml: text("draft_html").notNull().default(""),
+ draftCss: text("draft_css").notNull().default(""),
+ /**
+ * Functions the body may call, as source. Runs inside `@jetbrains/websandbox`, so it reaches
+ * neither the page, the session nor the network except through what the host hands it.
+ */
+ draftJsFunctions: text("draft_js_functions").notNull().default(""),
+ /**
+ * The arguments this component takes, as JSON Schema. This is what the model fills in, so it is
+ * the difference between a component a model can use and one it will call wrongly forever.
+ */
+ draftArgumentSchema: jsonb("draft_argument_schema").notNull().default({}),
+
+ publishedDescription: text("published_description"),
+ publishedHtml: text("published_html"),
+ publishedCss: text("published_css"),
+ publishedJsFunctions: text("published_js_functions"),
+ publishedArgumentSchema: jsonb("published_argument_schema"),
+
+ /** Sample arguments the playground previews against, kept so the next editor sees what it draws. */
+ sampleArguments: jsonb("sample_arguments").notNull().default({}),
+ /** Bumped on every publish, so a reader can tell which version of a component drew something. */
+ revision: integer("revision").notNull().default(0),
+ published: boolean("published").notNull().default(false),
+ publishedAt: timestamp("published_at", { withTimezone: true }),
+ authoredBy: text("authored_by"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
diff --git a/server/src/db/schema/teammate.ts b/server/src/db/schema/teammate.ts
new file mode 100644
index 00000000..13f8ea74
--- /dev/null
+++ b/server/src/db/schema/teammate.ts
@@ -0,0 +1,64 @@
+/**
+ * Teammate tables: bots, skills, routines, bot-to-bot handoff.
+ *
+ * Split by owner so two people can add tables all day without touching the same lines. Add tables
+ * here; never edit core.ts or computer.ts to do it.
+ */
+import {
+ index,
+ pgEnum,
+ pgTable,
+ primaryKey,
+ text,
+ timestamp,
+} from "drizzle-orm/pg-core";
+import { agents, users } from "./core";
+
+const createdAt = () =>
+ timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
+const updatedAt = () =>
+ timestamp("updated_at", { withTimezone: true }).notNull().defaultNow();
+
+export const agentVisibility = pgEnum("agent_visibility", [
+ "public",
+ "private",
+]);
+
+export const agentProfiles = pgTable(
+ "agent_profiles",
+ {
+ agentId: text("agent_id")
+ .primaryKey()
+ .references(() => agents.id, { onDelete: "cascade" }),
+ ownerUserId: text("owner_user_id").references(() => users.id, {
+ onDelete: "set null",
+ }),
+ title: text("title").notNull(),
+ roleDescription: text("role_description").notNull(),
+ avatarSeed: text("avatar_seed").notNull(),
+ visibility: agentVisibility("visibility").notNull(),
+ deletedAt: timestamp("deleted_at", { withTimezone: true }),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (table) => [
+ index("agent_profiles_visibility_deleted_idx").on(
+ table.visibility,
+ table.deletedAt,
+ ),
+ ],
+);
+
+export const agentPreferences = pgTable(
+ "agent_preferences",
+ {
+ userId: text("user_id")
+ .notNull()
+ .references(() => users.id, { onDelete: "cascade" }),
+ agentId: text("agent_id")
+ .notNull()
+ .references(() => agents.id, { onDelete: "cascade" }),
+ hiddenAt: timestamp("hidden_at", { withTimezone: true }),
+ },
+ (table) => [primaryKey({ columns: [table.userId, table.agentId] })],
+);
diff --git a/server/src/knowledge/acl.ts b/server/src/knowledge/acl.ts
new file mode 100644
index 00000000..d9dc3e97
--- /dev/null
+++ b/server/src/knowledge/acl.ts
@@ -0,0 +1,22 @@
+import type { KnowledgeAclEntry, KnowledgeActor } from "./types";
+
+export function canRead(
+ actor: KnowledgeActor,
+ entries: KnowledgeAclEntry[],
+): boolean {
+ let allowed = false;
+
+ for (const entry of entries) {
+ if (!matchesPrincipal(actor, entry.principal)) continue;
+ if (entry.effect === "deny") return false;
+ allowed = true;
+ }
+
+ return allowed;
+}
+
+function matchesPrincipal(actor: KnowledgeActor, principal: string): boolean {
+ if (principal === `user:${actor.userId}`) return true;
+ if (!principal.startsWith("group:")) return false;
+ return actor.groups.includes(principal.slice("group:".length));
+}
diff --git a/server/src/knowledge/repository.ts b/server/src/knowledge/repository.ts
new file mode 100644
index 00000000..883cf9e3
--- /dev/null
+++ b/server/src/knowledge/repository.ts
@@ -0,0 +1,57 @@
+import { canRead } from "./acl";
+import type { KnowledgeAclEntry, KnowledgeActor } from "./types";
+
+type SourceChange = {
+ connectorInstanceId: string;
+ sourceId: string;
+ title: string;
+ canonicalUrl: string;
+ contentHash: string;
+ chunks: { position: number; content: string }[];
+ acls: KnowledgeAclEntry[];
+};
+
+type Citation = {
+ documentId: string;
+ title: string;
+ canonicalUrl: string;
+ chunkId: string;
+ content: string;
+};
+
+export class InMemoryKnowledgeRepository {
+ #sources = new Map<string, SourceChange>();
+ #deleted = new Set<string>();
+
+ apply(change: SourceChange) {
+ const key = sourceKey(change.connectorInstanceId, change.sourceId);
+ this.#sources.set(key, structuredClone(change));
+ this.#deleted.delete(key);
+ }
+
+ delete(connectorInstanceId: string, sourceId: string) {
+ this.#deleted.add(sourceKey(connectorInstanceId, sourceId));
+ }
+
+ documents(): SourceChange[] {
+ return [...this.#sources.values()].map((source) => structuredClone(source));
+ }
+
+ search(actor: KnowledgeActor): Citation[] {
+ return [...this.#sources.entries()].flatMap(([key, source]) => {
+ if (this.#deleted.has(key) || !canRead(actor, source.acls)) return [];
+ const documentId = key;
+ return source.chunks.map((chunk) => ({
+ documentId,
+ title: source.title,
+ canonicalUrl: source.canonicalUrl,
+ chunkId: `${documentId}:${chunk.position}`,
+ content: chunk.content,
+ }));
+ });
+ }
+}
+
+function sourceKey(connectorInstanceId: string, sourceId: string) {
+ return `${connectorInstanceId}:${sourceId}`;
+}
diff --git a/server/src/knowledge/types.ts b/server/src/knowledge/types.ts
new file mode 100644
index 00000000..5ef9b202
--- /dev/null
+++ b/server/src/knowledge/types.ts
@@ -0,0 +1,9 @@
+export type KnowledgeActor = {
+ userId: string;
+ groups: string[];
+};
+
+export type KnowledgeAclEntry = {
+ principal: string;
+ effect: "allow" | "deny";
+};
diff --git a/server/src/plugins/mcp.ts b/server/src/plugins/mcp.ts
new file mode 100644
index 00000000..4ebc7844
--- /dev/null
+++ b/server/src/plugins/mcp.ts
@@ -0,0 +1,148 @@
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
+
+/**
+ * The only place in this deployment that speaks MCP to somebody else's server.
+ *
+ * One door. Every call out is a credential leaving the building and a result coming back
+ * that a model will read, so both directions want a single place to be careful in. A second client
+ * somewhere else would be a second place to forget the timeout, the credential handling or the size
+ * cap, and nothing about the second one would look wrong in review.
+ *
+ * No connection is kept. A client is built, used and closed for every listing and every call.
+ * Streamable HTTP makes that cheap, and a pooled session would mean one Bot's request could arrive
+ * on a session another Bot's credential opened, which is a whole class of bug we simply decline to
+ * have.
+ */
+
+/** How long a server gets before we give up on it, for a listing and for a call. */
+const LIST_TIMEOUT_MS = 15_000;
+const CALL_TIMEOUT_MS = 60_000;
+
+/**
+ * The most result text a call may return.
+ *
+ * A tool result goes straight into a model's context, so an unbounded one is somebody else's server
+ * deciding how much of our context window to spend, and a truncation the model can see is far better
+ * than a run that fails or a bill nobody expected. Truncated visibly, never silently.
+ */
+const MAX_RESULT_CHARS = 20_000;
+
+export type McpTool = {
+ name: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+};
+
+export class McpServerError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "McpServerError";
+ }
+}
+
+type Connection = {
+ url: string;
+ /** The bearer token for this server, already decrypted. Absent for a server that needs none. */
+ token?: string;
+};
+
+/**
+ * Build, use and close a client.
+ *
+ * The `finally` closes the transport whatever happened, because a thrown error is the case where a
+ * leaked connection is most likely and least noticed.
+ */
+async function withClient<T>(
+ connection: Connection,
+ use: (client: Client) => Promise<T>,
+): Promise<T> {
+ const transport = new StreamableHTTPClientTransport(new URL(connection.url), {
+ requestInit: connection.token
+ ? { headers: { Authorization: `Bearer ${connection.token}` } }
+ : undefined,
+ });
+ const client = new Client({ name: "openbot", version: "1.0.0" });
+
+ try {
+ await client.connect(transport);
+ return await use(client);
+ } catch (error) {
+ // Rewrapped so a caller never has to care whether the failure came from the transport, the
+ // handshake or the call, and so the message that reaches an audit row and an admin page is one
+ // sentence rather than a stack.
+ throw new McpServerError(
+ error instanceof Error ? error.message : String(error),
+ );
+ } finally {
+ await client.close().catch(() => {
+ // A server that will not say goodbye is not a failure of the work that just succeeded.
+ });
+ }
+}
+
+/** What this server says it offers, right now. */
+export async function listTools(connection: Connection): Promise<McpTool[]> {
+ return withClient(connection, async (client) => {
+ const result = await client.listTools(undefined, {
+ timeout: LIST_TIMEOUT_MS,
+ });
+ return result.tools.map((tool) => ({
+ name: tool.name,
+ description: tool.description ?? "",
+ inputSchema: (tool.inputSchema ?? {}) as Record<string, unknown>,
+ }));
+ });
+}
+
+export type McpCallResult = {
+ /** The result as text, which is what a model reads. Truncated visibly if it was enormous. */
+ text: string;
+ /** True when the server itself reported the call as an error rather than failing to answer. */
+ isError: boolean;
+ truncated: boolean;
+};
+
+/**
+ * Call one tool.
+ *
+ * Whether the call was permitted is not decided here. This function's only job is to speak the
+ * protocol; the grant and the policy are settled before anything reaches it. Keeping the two apart
+ * means the permission check cannot be accidentally satisfied by a code path that also happens to
+ * make the call.
+ */
+export async function callTool(
+ connection: Connection,
+ toolName: string,
+ args: Record<string, unknown>,
+): Promise<McpCallResult> {
+ return withClient(connection, async (client) => {
+ const result = await client.callTool(
+ { name: toolName, arguments: args },
+ undefined,
+ { timeout: CALL_TIMEOUT_MS },
+ );
+
+ const parts = Array.isArray(result.content) ? result.content : [];
+ const text = parts
+ .map((part) => {
+ const item = part as { type?: string; text?: string };
+ if (item.type === "text" && typeof item.text === "string") {
+ return item.text;
+ }
+ // A non-text part is named rather than dropped. A model told "[image]" can say the tool
+ // returned an image; a model handed nothing concludes the tool returned nothing.
+ return `[${item.type ?? "unknown"}]`;
+ })
+ .join("\n");
+
+ const truncated = text.length > MAX_RESULT_CHARS;
+ return {
+ text: truncated
+ ? `${text.slice(0, MAX_RESULT_CHARS)}\n\n[truncated: the tool returned ${text.length} characters]`
+ : text,
+ isError: result.isError === true,
+ truncated,
+ };
+ });
+}
diff --git a/server/src/plugins/routes.ts b/server/src/plugins/routes.ts
new file mode 100644
index 00000000..59c6c2a3
--- /dev/null
+++ b/server/src/plugins/routes.ts
@@ -0,0 +1,387 @@
+import type { MiddlewareHandler } from "hono";
+import { Hono } from "hono";
+import type { AppVariables } from "../auth/guards";
+import { requireAdmin } from "../auth/guards";
+import { CATALOGUE } from "./catalogue";
+import {
+ CatalogueEntryUnknownError,
+ CustomServerRefusedError,
+ PluginRefusedError,
+ type PluginStore,
+} from "./store";
+
+/**
+ * The Plugins surface: what this deployment has added, and which Bots may use it.
+ *
+ * What a Bot can reach is an administrator's; what it is told is not. Adding an MCP server stores a
+ * credential and opens a path into another company's system, and enabling one on a Bot is the same
+ * decision one step later, so both are an administrator's. A skill only ever asks for tools the Bot
+ * already holds, and every one of those calls is still decided, policy-checked and audited, so
+ * anybody may write one for themselves and put it on a Bot they own.
+ *
+ * Reading is open to any signed-in person either way: what a Bot can reach is not a secret from the
+ * person talking to it.
+ *
+ * The call endpoint asks again. The list of tools a run was offered is a snapshot taken when the run
+ * started, so a grant revoked a second later is still in the model's hands. Deciding at call time is
+ * what makes revocation immediate rather than nearly immediate, and it is where a refusal becomes a
+ * row somebody can read.
+ */
+export function createPluginRoutes(
+ store: PluginStore,
+ requireUser: MiddlewareHandler<{ Variables: AppVariables }>,
+) {
+ const routes = new Hono<{ Variables: AppVariables }>();
+
+ const actorEmail = (context: { var: AppVariables }) =>
+ context.var.actor?.email ?? "unknown";
+
+ const skillActor = (context: { var: AppVariables }) => ({
+ id: context.var.actor.id,
+ isAdmin: context.var.actor.role === "admin",
+ });
+
+ /**
+ * May this person write, edit or delete this skill?
+ *
+ * An administrator may touch anything. Everybody else may touch their own and nothing else, which
+ * includes not editing a deployment skill an administrator wrote for everyone.
+ */
+ async function skillRefusal(
+ context: { var: AppVariables },
+ slug: string,
+ ): Promise<string | null> {
+ const actor = skillActor(context);
+ if (actor.isAdmin) return null;
+ const owner = await store.skillOwner(slug);
+ if (owner === undefined) return null; // A new skill. Ownership is decided on the way in.
+ if (owner === null) {
+ return `${slug} belongs to this deployment. An administrator looks after it.`;
+ }
+ return owner === actor.id ? null : `${slug} is somebody else's skill.`;
+ }
+
+ /** Everything the Plugins page draws: the catalogue, what is added, and the skills. */
+ routes.get("/", requireUser, async (context) =>
+ context.json({
+ catalogue: CATALOGUE.map((entry) => ({
+ key: entry.key,
+ title: entry.title,
+ vendor: entry.vendor,
+ summary: entry.summary,
+ docsUrl: entry.docsUrl,
+ needsCredential: entry.needsCredential,
+ perInstance: entry.host === null,
+ })),
+ servers: await store.listServers(),
+ // Scoped: the deployment's skills plus this person's own. An administrator sees them all.
+ skills: await store.listSkills(skillActor(context)),
+ }),
+ );
+
+ /** Add a curated server. The URL comes from the catalogue, never from the request. */
+ routes.post("/servers", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const body = (await context.req.json().catch(() => null)) as {
+ key?: string;
+ instanceHost?: string;
+ credentialId?: string;
+ } | null;
+ if (!body?.key) {
+ return context.json({ error: "A catalogue key is required." }, 400);
+ }
+
+ try {
+ const server = await store.addServer({
+ key: body.key,
+ instanceHost: body.instanceHost,
+ credentialId: body.credentialId,
+ by: actorEmail(context),
+ });
+ return context.json({ server });
+ } catch (error) {
+ if (error instanceof CatalogueEntryUnknownError) {
+ return context.json({ error: error.message }, 400);
+ }
+ throw error;
+ }
+ });
+
+ /**
+ * Add a server by URL.
+ *
+ * Its own endpoint rather than a flag on the one above, so that "an administrator pointed this
+ * deployment at an address of their own" is a distinct act in the code, in the audit trail and in
+ * anything that reads either.
+ */
+ routes.post("/servers/custom", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ const body = (await context.req.json().catch(() => null)) as {
+ id?: string;
+ title?: string;
+ url?: string;
+ credentialId?: string;
+ } | null;
+ if (!body?.id || !body.title || !body.url) {
+ return context.json(
+ { error: "A name, a title and a URL are required." },
+ 400,
+ );
+ }
+
+ try {
+ const server = await store.addCustomServer({
+ id: body.id,
+ title: body.title,
+ url: body.url,
+ credentialId: body.credentialId,
+ by: actorEmail(context),
+ });
+ return context.json({ server });
+ } catch (error) {
+ if (
+ error instanceof CustomServerRefusedError ||
+ error instanceof CatalogueEntryUnknownError
+ ) {
+ return context.json({ error: error.message }, 400);
+ }
+ throw error;
+ }
+ });
+
+ routes.delete("/servers/:id", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ await store.removeServer(context.req.param("id"), actorEmail(context));
+ return context.json({ ok: true });
+ });
+
+ /** Ask a server what it offers now. Reported rather than thrown, so the page can say what broke. */
+ routes.post("/servers/:id/refresh", requireUser, async (context) => {
+ const forbidden = requireAdmin(context);
+ if (forbidden) return forbidden;
+
+ try {
+ const result = await store.refreshTools(context.req.param("id"));
+ const servers = await store.listServers();
+ return context.json({
+ tools: result.tools,
+ server: servers.find((server) => server.id === context.req.param("id")),
+ });
+ } catch (error) {
+ if (error instanceof CatalogueEntryUnknownError) {
+ return context.json({ error: error.message }, 404);
+ }
+ throw error;
+ }
+ });
+
+ /**
+ * Write a skill.
+ *
+ * Not admin-only. A skill is an instruction, not a capability: it can only ask a
+ * Bot to use tools that Bot was already granted, and every one of those calls is still decided,
+ * policy-checked and audited. Adding an MCP server is the opposite, and stays an administrator's.
+ *
+ * A person's skill is their own. `global` writes one for the whole deployment, which an
+ * administrator may do and nobody else.
+ */
+ routes.post("/skills", requireUser, async (context) => {
+ const body = (await context.req.json().catch(() => null)) as {
+ slug?: string;
+ title?: string;
+ summary?: string;
+ instructions?: string;
+ global?: boolean;
+ } | null;
+ if (!body?.slug || !body.title || !body.instructions) {
+ return context.json(
+ { error: "A slug, a title and instructions are required." },
+ 400,
+ );
+ }
+ if (!/^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$/.test(body.slug)) {
+ return context.json(
+ { error: "A slug is lower-case letters, numbers and hyphens." },
+ 400,
+ );
+ }
+
+ const actor = skillActor(context);
+ if (body.global && !actor.isAdmin) {
+ return context.json(
+ { error: "Only an administrator writes a skill for the deployment." },
+ 403,
+ );
+ }
+
+ // Editing an existing slug, which is what a repeated save is, needs the right to edit that
+ // skill. Without this, saving over somebody else's name would silently take it.
+ const refusal = await skillRefusal(context, body.slug);
+ if (refusal) return context.json({ error: refusal }, 403);
+
+ await store.installSkill({
+ slug: body.slug,
+ title: body.title,
+ summary: body.summary ?? "",
+ instructions: body.instructions,
+ ownerUserId: body.global ? null : actor.id,
+ by: actorEmail(context),
+ });
+ return context.json({ skills: await store.listSkills(actor) });
+ });
+
+ routes.delete("/skills/:slug", requireUser, async (context) => {
+ const slug = context.req.param("slug");
+ const refusal = await skillRefusal(context, slug);
+ if (refusal) return context.json({ error: refusal }, 403);
+
+ await store.uninstallSkill(slug, actorEmail(context));
+ return context.json({ ok: true });
+ });
+
+ /**
+ * Grant and revoke, for both kinds, through one pair of endpoints.
+ *
+ * The store keeps one grant table because the question is the same either way; the API says the
+ * same thing, so a reader is never left wondering whether skills are governed differently.
+ */
+
+ /**
+ * May this person put this on that Bot?
+ *
+ * MCP is an administrator's, always: it reaches another company's system with a stored credential.
+ * A skill is an instruction, so somebody may put their own skill on a Bot they own, and neither
+ * half alone is enough. Both are checked here rather than in the store, because this is the only
+ * place that knows who is asking.
+ */
+ async function enablementRefusal(
+ context: { var: AppVariables },
+ kind: "mcp" | "skill",
+ ref: string,
+ agentId: string,
+ ): Promise<string | null> {
+ const actor = skillActor(context);
+ if (actor.isAdmin) return null;
+ if (kind === "mcp") {
+ return "An administrator decides which Bots may reach a tool.";
+ }
+
+ const owner = await store.skillOwner(ref);
+ if (owner === undefined) return `There is no skill called ${ref}.`;
+ if (owner !== actor.id) {
+ return owner === null
+ ? `${ref} belongs to this deployment. An administrator decides which Bots use it.`
+ : `${ref} is somebody else's skill.`;
+ }
+
+ const botOwner = await store.agentOwner(agentId);
+ if (botOwner === undefined) return "There is no such Bot.";
+ if (botOwner !== actor.id) {
+ // Including the shared Bots this deployment publishes, which have no owner at all: a skill
+ // one person wrote would otherwise change how a Bot answers everybody.
+ return "You can only put your own skills on Bots you own.";
+ }
+ return null;
+ }
+
+ routes.post("/grants", requireUser, async (context) => {
+ const body = (await context.req.json().catch(() => null)) as {
+ kind?: "mcp" | "skill";
+ ref?: string;
+ agentId?: string;
+ } | null;
+ if (!body?.kind || !body.ref || !body.agentId) {
+ return context.json(
+ { error: "A kind, a ref and a Bot are required." },
+ 400,
+ );
+ }
+ const refusal = await enablementRefusal(
+ context,
+ body.kind,
+ body.ref,
+ body.agentId,
+ );
+ if (refusal) return context.json({ error: refusal }, 403);
+
+ await store.grant(body.kind, body.ref, body.agentId, actorEmail(context));
+ return context.json({ ok: true });
+ });
+
+ routes.delete("/grants", requireUser, async (context) => {
+ const kind = context.req.query("kind");
+ const ref = context.req.query("ref");
+ const agentId = context.req.query("agentId");
+ if ((kind !== "mcp" && kind !== "skill") || !ref || !agentId) {
+ return context.json(
+ { error: "A kind, a ref and a Bot are required." },
+ 400,
+ );
+ }
+ const refusal = await enablementRefusal(context, kind, ref, agentId);
+ if (refusal) return context.json({ error: refusal }, 403);
+
+ await store.revoke(kind, ref, agentId, actorEmail(context));
+ return context.json({ ok: true });
+ });
+
+ /** What one Bot holds. The runtime reads this to decide what to offer a model. */
+ routes.get("/for/:agentId", requireUser, async (context) =>
+ context.json(await store.listForAgent(context.req.param("agentId"))),
+ );
+
+ /**
+ * Call a tool, as a Bot.
+ *
+ * The grant, the policy and the audit row all happen inside the store, so this endpoint cannot
+ * accidentally satisfy one of them and skip another. A refusal comes back as 403 with the reason
+ * the model and the person are both shown, which is the same sentence written to the trail.
+ */
+ routes.post("/call", requireUser, async (context) => {
+ const body = (await context.req.json().catch(() => null)) as {
+ ref?: string;
+ args?: Record<string, unknown>;
+ agentId?: string;
+ } | null;
+ if (!body?.ref || !body.agentId) {
+ return context.json({ error: "A tool and a Bot are required." }, 400);
+ }
+
+ try {
+ const result = await store.callTool({
+ ref: body.ref,
+ args: body.args ?? {},
+ botId: body.agentId,
+ actorId: actorEmail(context),
+ });
+ return context.json(result);
+ } catch (error) {
+ if (error instanceof PluginRefusedError) {
+ return context.json({ error: error.message, rule: error.rule }, 403);
+ }
+ if (error instanceof CatalogueEntryUnknownError) {
+ return context.json({ error: error.message }, 404);
+ }
+ // A server that failed is not a refusal, and saying so matters: one means the deployment
+ // decided against it, the other means somebody else's software did not answer.
+ return context.json(
+ {
+ error:
+ error instanceof Error
+ ? error.message
+ : "The server did not answer.",
+ failed: true,
+ },
+ 502,
+ );
+ }
+ });
+
+ return routes;
+}
diff --git a/server/tests/agent-connection-live.test.ts b/server/tests/agent-connection-live.test.ts
new file mode 100644
index 00000000..8427a2e9
--- /dev/null
+++ b/server/tests/agent-connection-live.test.ts
@@ -0,0 +1,74 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { AGUIMock } from "@copilotkit/aimock/agui";
+import { testAgentConnection } from "../src/agents/connection-test";
+
+/**
+ * The connection test, against something that really speaks AG-UI.
+ *
+ * Uses a real AG-UI mock rather than a stubbed fetch. The other tests for this hand it a function that returns a hand-written
+ * SSE body, which proves the parsing and nothing about the protocol: every one of them would still
+ * pass if AG-UI changed its wire format underneath us, or if we had misread it in the first place.
+ * The whole promise is that somebody else's agent works if it speaks this protocol, so the
+ * test that matters is one where an implementation we did not write answers.
+ *
+ * `@copilotkit/aimock` is ours, which is the point: it is the org's deterministic backend for
+ * exactly this, it tracks the protocol as the protocol moves, and using it here means OpenBot finds
+ * out about a drift in the same week as everything else that depends on it rather than in a
+ * customer's integration.
+ *
+ * Deterministic and offline. No key, no network, no spend, and the same answer on every run, so
+ * this belongs in CI, which is where an agent-facing contract most needs watching.
+ */
+
+describe("registering an agent that really answers", () => {
+ const mock = new AGUIMock();
+ let url = "";
+
+ beforeAll(async () => {
+ // The events a well-behaved agent sends for a trivial run: it starts, says something, finishes.
+ mock.onRun(/.*/, [
+ { type: "RUN_STARTED", threadId: "t", runId: "r" },
+ { type: "TEXT_MESSAGE_START", messageId: "m", role: "assistant" },
+ { type: "TEXT_MESSAGE_CONTENT", messageId: "m", delta: "ready" },
+ { type: "TEXT_MESSAGE_END", messageId: "m" },
+ { type: "RUN_FINISHED", threadId: "t", runId: "r" },
+ ] as never);
+ url = await mock.start();
+ });
+
+ afterAll(async () => {
+ await mock.stop?.();
+ });
+
+ test("an agent speaking real AG-UI is reported as working, with what it sent", async () => {
+ const result = await testAgentConnection(url, { allowPrivateHosts: true });
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ // The events are shown to the person registering it, so that they can see it really answered
+ // rather than being told it did.
+ expect(result.events).toContain("RUN_STARTED");
+ expect(result.events).toContain("RUN_FINISHED");
+ });
+
+ test("the address is still checked before anything is dialled", async () => {
+ // Same guard as registration: the button must not become a way to probe the internal network,
+ // and a live server on the other end does not change that.
+ const result = await testAgentConnection("http://169.254.169.254/", {
+ allowPrivateHosts: true,
+ });
+ expect(result.ok).toBe(false);
+ });
+
+ test("a port with nothing on it reports the direction of the connection", async () => {
+ // The server dials the agent, so localhost must be tested from the server side.
+ const dead = await testAgentConnection("http://127.0.0.1:9/", {
+ allowPrivateHosts: true,
+ timeoutMs: 2_000,
+ });
+ expect(dead.ok).toBe(false);
+ if (!dead.ok) {
+ expect(dead.reason).toMatch(/reachable from|did not answer/);
+ }
+ });
+});
diff --git a/server/tests/agent-invocation.test.ts b/server/tests/agent-invocation.test.ts
new file mode 100644
index 00000000..b2f6a8db
--- /dev/null
+++ b/server/tests/agent-invocation.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from "bun:test";
+import { createAgentInvoker } from "../src/agents/invocation";
+
+test("invokes the selected available built-in agent", async () => {
+ const invoke = createAgentInvoker({
+ knowledge: async () => ({ text: "Answer", citations: [] }),
+ remote: async () => ({ text: "unused", citations: [] }),
+ });
+ await expect(
+ invoke({ id: "knowledge", type: "built_in", available: true }, "question"),
+ ).resolves.toEqual({ text: "Answer", citations: [] });
+});
+
+test("rejects unavailable agents before invocation", async () => {
+ const invoke = createAgentInvoker({
+ knowledge: async () => ({ text: "unused", citations: [] }),
+ remote: async () => ({ text: "unused", citations: [] }),
+ });
+ await expect(
+ invoke(
+ {
+ id: "knowledge",
+ type: "built_in",
+ available: false,
+ reason: "Model credential is not configured.",
+ },
+ "question",
+ ),
+ ).rejects.toThrow("Model credential is not configured.");
+});
diff --git a/server/tests/agent-profile-policy.test.ts b/server/tests/agent-profile-policy.test.ts
new file mode 100644
index 00000000..437f5b7d
--- /dev/null
+++ b/server/tests/agent-profile-policy.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, test } from "bun:test";
+import {
+ canAccessAgent,
+ canManageAgent,
+ canRunAgent,
+} from "../src/agents/profile-policy";
+import type { AgentActor, AgentProfile } from "../src/agents/profile-types";
+
+const creator: AgentActor = { id: "user-1", role: "user" };
+const otherUser: AgentActor = { id: "user-2", role: "user" };
+const admin: AgentActor = { id: "admin-1", role: "admin" };
+
+function profile(overrides: Partial<AgentProfile> = {}): AgentProfile {
+ return {
+ id: "agent-1",
+ name: "Researcher",
+ title: "Research Assistant",
+ roleDescription: "Finds and summarizes information.",
+ avatarSeed: "researcher",
+ visibility: "private",
+ ownerUserId: creator.id,
+ systemOwned: false,
+ hidden: false,
+ deletedAt: null,
+ ...overrides,
+ };
+}
+
+describe("agent profile permissions", () => {
+ test("allows every actor to access and run an active public profile", () => {
+ const agent = profile({ visibility: "public", hidden: true });
+
+ for (const actor of [creator, otherUser, admin]) {
+ expect(canAccessAgent(actor, agent)).toBe(true);
+ expect(canRunAgent(actor, agent)).toBe(true);
+ }
+ });
+
+ test("limits active private profile access and runs to its creator and admins", () => {
+ const agent = profile({ visibility: "private" });
+
+ expect(canAccessAgent(creator, agent)).toBe(true);
+ expect(canAccessAgent(otherUser, agent)).toBe(false);
+ expect(canAccessAgent(admin, agent)).toBe(true);
+ expect(canRunAgent(creator, agent)).toBe(true);
+ expect(canRunAgent(otherUser, agent)).toBe(false);
+ expect(canRunAgent(admin, agent)).toBe(true);
+ });
+
+ test("allows only the creator and admins to manage active user profiles", () => {
+ for (const visibility of ["public", "private"] as const) {
+ const agent = profile({ visibility });
+
+ expect(canManageAgent(creator, agent)).toBe(true);
+ expect(canManageAgent(otherUser, agent)).toBe(false);
+ expect(canManageAgent(admin, agent)).toBe(true);
+ }
+ });
+
+ test("allows all actors to access and run a system public profile but nobody to manage it", () => {
+ const agent = profile({
+ visibility: "public",
+ ownerUserId: null,
+ systemOwned: true,
+ });
+
+ for (const actor of [creator, otherUser, admin]) {
+ expect(canAccessAgent(actor, agent)).toBe(true);
+ expect(canRunAgent(actor, agent)).toBe(true);
+ expect(canManageAgent(actor, agent)).toBe(false);
+ }
+ });
+
+ test("denies every permission for deleted profiles", () => {
+ const agent = profile({
+ visibility: "public",
+ deletedAt: new Date("2026-08-14T00:00:00.000Z"),
+ });
+
+ for (const actor of [creator, otherUser, admin]) {
+ expect(canAccessAgent(actor, agent)).toBe(false);
+ expect(canManageAgent(actor, agent)).toBe(false);
+ expect(canRunAgent(actor, agent)).toBe(false);
+ }
+ });
+
+ test("exports canRunAgent as the canAccessAgent alias", () => {
+ expect(canRunAgent).toBe(canAccessAgent);
+ });
+});
diff --git a/server/tests/audit.test.ts b/server/tests/audit.test.ts
new file mode 100644
index 00000000..30b61b2a
--- /dev/null
+++ b/server/tests/audit.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, test } from "bun:test";
+import { readFile } from "node:fs/promises";
+import { createApp } from "../src/app";
+import {
+ auditEventTypes,
+ recordAuditEvent,
+ redactAuditPayload,
+} from "../src/audit";
+import { loadConfig } from "../src/config";
+import { testEnvironment } from "./support/environment";
+
+const config = loadConfig({
+ ...testEnvironment(),
+});
+
+const adminAuth = {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => ({
+ user: { id: "admin", email: "[email protected]" },
+ }),
+ },
+};
+
+const memberAuth = {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => ({
+ user: { id: "member", email: "[email protected]" },
+ }),
+ },
+};
+
+describe("audit payload redaction", () => {
+ test("defines the v1 audit event taxonomy", () => {
+ expect(auditEventTypes).toEqual(
+ expect.arrayContaining([
+ "configuration.changed",
+ "credential.created",
+ "credential.rotated",
+ "credential.revoked",
+ "connector.sync_succeeded",
+ "connector.sync_failed",
+ "knowledge.searched",
+ "agent.invoked",
+ "mcp.call_succeeded",
+ "mcp.call_rejected",
+ ]),
+ );
+ });
+
+ test("removes secret values and document content recursively", () => {
+ expect(
+ redactAuditPayload({
+ connector: "google_drive",
+ accessToken: "sensitive-token",
+ nested: {
+ content: "full document body",
+ resultCategory: "succeeded",
+ },
+ }),
+ ).toEqual({
+ connector: "google_drive",
+ accessToken: "[REDACTED]",
+ nested: {
+ content: "[REDACTED]",
+ resultCategory: "succeeded",
+ },
+ });
+ });
+
+ test("writes only the redacted payload to the audit store", async () => {
+ const writes: unknown[] = [];
+
+ await recordAuditEvent(
+ {
+ insert: async (event) => {
+ writes.push(event);
+ },
+ },
+ {
+ eventType: "credential.created",
+ targetType: "credential",
+ targetId: "credential-1",
+ payload: { apiKey: "plaintext-key", provider: "openai" },
+ },
+ );
+
+ expect(writes).toEqual([
+ {
+ eventType: "credential.created",
+ targetType: "credential",
+ targetId: "credential-1",
+ payload: { apiKey: "[REDACTED]", provider: "openai" },
+ },
+ ]);
+ });
+});
+
+describe("audit event immutability", () => {
+ test("installs a database trigger that rejects updates and deletes", async () => {
+ const migration = await readFile(
+ new URL("../drizzle/0000_schema.sql", import.meta.url),
+ "utf8",
+ );
+
+ expect(migration).toContain("CREATE FUNCTION prevent_audit_event_mutation");
+ expect(migration).toContain("BEFORE UPDATE OR DELETE ON audit_events");
+ expect(migration).toContain("Audit events are append-only");
+ });
+});
+
+describe("admin audit API", () => {
+ test("returns a filtered audit page to an administrator", async () => {
+ const queries: unknown[] = [];
+ const app = createApp(
+ config,
+ adminAuth,
+ { rolesForUser: async () => ["admin"] },
+ {
+ list: async (query) => {
+ queries.push(query);
+ return {
+ events: [
+ {
+ id: "event-1",
+ eventType: "connector.sync_succeeded",
+ targetType: "connector",
+ targetId: "drive-1",
+ actorUserId: "admin",
+ payload: { itemCount: 3 },
+ createdAt: "2026-08-13T12:00:00.000Z",
+ },
+ ],
+ nextCursor: "next-page",
+ };
+ },
+ },
+ );
+
+ const response = await app.request(
+ "http://openbot.local/api/admin/audit-events?eventType=connector.sync_succeeded&limit=10",
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ events: [
+ {
+ id: "event-1",
+ eventType: "connector.sync_succeeded",
+ targetType: "connector",
+ targetId: "drive-1",
+ actorUserId: "admin",
+ payload: { itemCount: 3 },
+ createdAt: "2026-08-13T12:00:00.000Z",
+ },
+ ],
+ nextCursor: "next-page",
+ });
+ expect(queries).toEqual([
+ { eventType: "connector.sync_succeeded", limit: 10 },
+ ]);
+ });
+
+ test("denies a non-admin caller", async () => {
+ const app = createApp(
+ config,
+ memberAuth,
+ { rolesForUser: async () => ["user"] },
+ { list: async () => ({ events: [] }) },
+ );
+
+ const response = await app.request(
+ "http://openbot.local/api/admin/audit-events",
+ );
+
+ expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toEqual({
+ error: "Administrator access required.",
+ });
+ });
+});
diff --git a/server/tests/channel-activity.integration.test.ts b/server/tests/channel-activity.integration.test.ts
new file mode 100644
index 00000000..e9d7a00f
--- /dev/null
+++ b/server/tests/channel-activity.integration.test.ts
@@ -0,0 +1,235 @@
+import { afterAll, afterEach, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import {
+ AgentNotFoundError,
+ createAgentProfileStore,
+} from "../src/agents/profile-store";
+import type { AgentActor } from "../src/agents/profile-types";
+import {
+ ChannelNotFoundError,
+ createChannelStore,
+} from "../src/channels/routes";
+import { createThreadIdentity } from "../src/channels/thread-identity";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import {
+ agentProfiles,
+ agents,
+ channels,
+ intelligenceChannelMappings,
+ users,
+} from "../src/db/schema";
+
+const databaseUrl =
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot";
+const database = createDatabase(databaseUrl, TEST_POOL);
+const profileStore = createAgentProfileStore(
+ database,
+ new URL("https://managed.example.test/ag-ui"),
+);
+const store = createChannelStore(
+ database,
+ profileStore,
+ createThreadIdentity("test-deployment"),
+);
+
+const testPrefix = `channel-activity-${randomUUID()}`;
+const createdUserIds: string[] = [];
+const createdAgentIds: string[] = [];
+const createdChannelIds: string[] = [];
+
+afterEach(async () => {
+ for (const channelId of createdChannelIds.splice(0)) {
+ await database
+ .delete(intelligenceChannelMappings)
+ .where(eq(intelligenceChannelMappings.channelId, channelId));
+ await database.delete(channels).where(eq(channels.id, channelId));
+ }
+ for (const agentId of createdAgentIds.splice(0)) {
+ await database
+ .delete(agentProfiles)
+ .where(eq(agentProfiles.agentId, agentId));
+ await database.delete(agents).where(eq(agents.id, agentId));
+ }
+ for (const userId of createdUserIds.splice(0)) {
+ await database.delete(users).where(eq(users.id, userId));
+ }
+});
+
+afterAll(async () => {
+ await database.$client.close();
+});
+
+async function createUser(): Promise<AgentActor> {
+ const id = `${testPrefix}-user-${randomUUID()}`;
+ await database.insert(users).values({
+ id,
+ email: `${id}@example.test`,
+ name: "Channel Activity Test User",
+ });
+ createdUserIds.push(id);
+ return { id, role: "user" };
+}
+
+async function createAgent(owner: AgentActor, name = "Expense Manager") {
+ const profile = await profileStore.create(owner, {
+ name,
+ title: "Finance Operations",
+ roleDescription: "Review receipts.",
+ visibility: "private",
+ });
+ createdAgentIds.push(profile.id);
+ return profile.id;
+}
+
+async function createChannel(owner: AgentActor, agentIds: string[]) {
+ const channel = await store.create(owner, agentIds);
+ createdChannelIds.push(channel.id);
+ return channel;
+}
+
+/**
+ * The roster reads the last thing said from our own row rather than from the Intelligence platform,
+ * so it stays one indexed query however long the conversations get. What is stored is whatever the
+ * client that ran the agent reported, which is why each of these guards exists.
+ */
+describe("channel activity", () => {
+ test("records the last message and returns it on the roster", async () => {
+ const owner = await createUser();
+ const agentId = await createAgent(owner);
+ const channel = await createChannel(owner, [agentId]);
+ const at = new Date();
+
+ await store.recordActivity(owner, channel.id, {
+ agentId,
+ at,
+ text: "Categorized three expenses.",
+ });
+
+ expect(await store.list(owner)).toEqual([
+ {
+ ...channel,
+ lastMessage: "Categorized three expenses.",
+ lastMessageAgentId: agentId,
+ lastMessageAt: at,
+ createdAt: expect.any(Date),
+ },
+ ]);
+ });
+
+ test("keeps a person's roster to the channels they belong to", async () => {
+ const owner = await createUser();
+ const otherUser = await createUser();
+ const agentId = await createAgent(owner);
+ const channel = await createChannel(owner, [agentId]);
+
+ expect(await store.list(otherUser)).toEqual([]);
+ await expect(
+ store.recordActivity(otherUser, channel.id, {
+ agentId: null,
+ at: new Date(),
+ text: "Not mine.",
+ }),
+ ).rejects.toBeInstanceOf(ChannelNotFoundError);
+ });
+
+ test("ignores a report older than what is already stored", async () => {
+ const owner = await createUser();
+ const agentId = await createAgent(owner);
+ const channel = await createChannel(owner, [agentId]);
+ const newest = new Date();
+ const older = new Date(newest.getTime() - 60_000);
+
+ await store.recordActivity(owner, channel.id, {
+ agentId,
+ at: newest,
+ text: "The reply.",
+ });
+ // A person's message and the agent's reply are two separate reports. A slow one must not
+ // overwrite a newer one that already landed.
+ await store.recordActivity(owner, channel.id, {
+ agentId: null,
+ at: older,
+ text: "The question.",
+ });
+
+ expect((await store.list(owner))[0]?.lastMessage).toBe("The reply.");
+ });
+
+ test("stores at most 200 code points, without control characters", async () => {
+ const owner = await createUser();
+ const agentId = await createAgent(owner);
+ const channel = await createChannel(owner, [agentId]);
+
+ await store.recordActivity(owner, channel.id, {
+ agentId,
+ at: new Date(),
+ // A terminal escape and a newline: a preview is rendered as text, not replayed as control.
+ text: `line one\nline two \u001b[31m ${"x".repeat(400)}`,
+ });
+
+ const stored = (await store.list(owner))[0]?.lastMessage ?? "";
+ expect(Array.from(stored).length).toBeLessThanOrEqual(200);
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: asserting they were removed.
+ expect(stored).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/);
+ expect(stored.startsWith("line one line two")).toBe(true);
+ });
+
+ test("refuses an agent that is not in the channel", async () => {
+ const owner = await createUser();
+ const agentId = await createAgent(owner);
+ const strangerId = await createAgent(owner, "Stranger");
+ const channel = await createChannel(owner, [agentId]);
+
+ await expect(
+ store.recordActivity(owner, channel.id, {
+ agentId: strangerId,
+ at: new Date(),
+ text: "Not from this channel.",
+ }),
+ ).rejects.toBeInstanceOf(AgentNotFoundError);
+ });
+
+ test("puts a channel just created above one that has already been used", async () => {
+ const owner = await createUser();
+ const agentId = await createAgent(owner);
+ const used = await createChannel(owner, [agentId]);
+ await store.recordActivity(owner, used.id, {
+ agentId,
+ // A minute back, not `now`. The activity time comes from this process and `created_at` comes
+ // from Postgres, so two events written in the same instant are ordered by whichever clock is
+ // marginally ahead. The property under test is the ordering rule, not the tie-break.
+ at: new Date(Date.now() - 60_000),
+ text: "Said something a minute ago.",
+ });
+
+ // Starting a conversation is the most recent thing this person did, and it is the one they are
+ // about to type in. Sorting it under every channel that has a message would bury it.
+ const fresh = await createChannel(owner, [agentId]);
+
+ expect((await store.list(owner)).map((channel) => channel.id)).toEqual([
+ fresh.id,
+ used.id,
+ ]);
+ });
+
+ test("sorts by recency and leaves silent channels below, not absent", async () => {
+ const owner = await createUser();
+ const agentId = await createAgent(owner);
+ const quiet = await createChannel(owner, [agentId]);
+ const busy = await createChannel(owner, [agentId]);
+
+ await store.recordActivity(owner, busy.id, {
+ agentId,
+ at: new Date(),
+ text: "Said something.",
+ });
+
+ expect((await store.list(owner)).map((channel) => channel.id)).toEqual([
+ busy.id,
+ quiet.id,
+ ]);
+ });
+});
diff --git a/server/tests/channel-routes.test.ts b/server/tests/channel-routes.test.ts
new file mode 100644
index 00000000..baaf7cf1
--- /dev/null
+++ b/server/tests/channel-routes.test.ts
@@ -0,0 +1,825 @@
+import { afterAll, afterEach, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import type { MiddlewareHandler } from "hono";
+import { Hono } from "hono";
+import {
+ AgentNotFoundError,
+ createAgentProfileStore,
+} from "../src/agents/profile-store";
+import type { AgentActor } from "../src/agents/profile-types";
+import { createApp } from "../src/app";
+import type { AppVariables } from "../src/auth/guards";
+import {
+ type AgentChannel,
+ ChannelNotFoundError,
+ type ChannelStore,
+ createChannelRoutes,
+ createChannelStore,
+ parseChannelInput,
+} from "../src/channels/routes";
+import { createThreadIdentity } from "../src/channels/thread-identity";
+import { loadConfig } from "../src/config";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import {
+ agentProfiles,
+ agents,
+ channelAgents,
+ channelMemberships,
+ channels,
+ intelligenceChannelMappings,
+ users,
+} from "../src/db/schema";
+import { testEnvironment } from "./support/environment";
+
+const actor = {
+ id: "user-1",
+ email: "[email protected]",
+ role: "user",
+} as const;
+
+function channel(overrides: Partial<AgentChannel> = {}): AgentChannel {
+ return {
+ id: "channel-1",
+ name: "Assistant channel",
+ agentIds: ["agent-1", "agent-2"],
+ threadId: "thread-1",
+ active: true,
+ ...overrides,
+ };
+}
+
+type StoreCall = [method: keyof ChannelStore, ...arguments_: unknown[]];
+
+function fakeStore(
+ overrides: Partial<ChannelStore> = {},
+): ChannelStore & { calls: StoreCall[] } {
+ const calls: StoreCall[] = [];
+ const base: ChannelStore = {
+ async create(receivedActor, agentIds) {
+ calls.push(["create", receivedActor, agentIds]);
+ return channel({ agentIds });
+ },
+ async get(receivedActor, id) {
+ calls.push(["get", receivedActor, id]);
+ return channel({ id });
+ },
+ };
+
+ return Object.assign(base, overrides, { calls });
+}
+
+const requireUser: MiddlewareHandler<{ Variables: AppVariables }> = async (
+ context,
+ next,
+) => {
+ context.set("actor", actor);
+ await next();
+};
+
+function appFor(
+ store: ChannelStore,
+ middleware: MiddlewareHandler<{ Variables: AppVariables }> = requireUser,
+) {
+ const app = new Hono<{ Variables: AppVariables }>();
+ app.route("/", createChannelRoutes(store, middleware));
+ return app;
+}
+
+async function json(response: Response) {
+ return response.json();
+}
+
+describe("channel input parser", () => {
+ test.each([[null], [[]], ["input"], [42], [true]])(
+ "rejects a non-object root: %p",
+ (input) => {
+ expect(parseChannelInput(input)).toEqual({
+ ok: false,
+ error: "Channel input must be a JSON object.",
+ });
+ },
+ );
+
+ test.each([
+ [undefined, "Agent IDs must be a non-empty array."],
+ [null, "Agent IDs must be a non-empty array."],
+ ["agent-1", "Agent IDs must be a non-empty array."],
+ [{}, "Agent IDs must be a non-empty array."],
+ [[], "Agent IDs must be a non-empty array."],
+ ])("rejects invalid agentIds: %p", (agentIds, error) => {
+ expect(parseChannelInput({ agentIds })).toEqual({ ok: false, error });
+ });
+
+ test.each([
+ [[""], "Agent IDs must be non-empty strings."],
+ [[" "], "Agent IDs must be non-empty strings."],
+ [[1], "Agent IDs must be non-empty strings."],
+ [[false], "Agent IDs must be non-empty strings."],
+ [[null], "Agent IDs must be non-empty strings."],
+ [[{}], "Agent IDs must be non-empty strings."],
+ [["agent-1", " agent-1 "], "Agent IDs must be unique."],
+ ])("rejects invalid agent ID members: %p", (agentIds, error) => {
+ expect(parseChannelInput({ agentIds })).toEqual({ ok: false, error });
+ });
+
+ test("trims, sorts, and whitelists channel input", () => {
+ expect(
+ parseChannelInput({
+ agentIds: [" agent-2 ", "agent-1"],
+ id: "forged-channel",
+ name: "forged name",
+ threadId: "forged-thread",
+ active: false,
+ }),
+ ).toEqual({ ok: true, value: { agentIds: ["agent-1", "agent-2"] } });
+ });
+});
+
+describe("channel routes", () => {
+ test("attaches authentication middleware to every route before calling the store", async () => {
+ const store = fakeStore();
+ const denied: MiddlewareHandler<{ Variables: AppVariables }> = (context) =>
+ Promise.resolve(context.json({ error: "denied" }, 401));
+ const app = appFor(store, denied);
+
+ const created = await app.request("http://openbot.test/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentIds: ["agent-1"] }),
+ });
+ const fetched = await app.request("http://openbot.test/channel-1");
+
+ expect(created.status).toBe(401);
+ expect(fetched.status).toBe(401);
+ expect(store.calls).toEqual([]);
+ });
+
+ test("uses the authenticated context actor and canonical agent IDs", async () => {
+ const store = fakeStore();
+ const app = appFor(store);
+
+ const created = await app.request("http://openbot.test/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentIds: [" agent-2 ", "agent-1"] }),
+ });
+ const fetched = await app.request("http://openbot.test/channel-1");
+
+ expect(created.status).toBe(201);
+ expect(fetched.status).toBe(200);
+ expect(store.calls).toEqual([
+ ["create", actor, ["agent-1", "agent-2"]],
+ ["get", actor, "channel-1"],
+ ]);
+ });
+
+ test("returns only the channel DTO for create and get", async () => {
+ const store = fakeStore({
+ async create(_actor, agentIds) {
+ return Object.assign(channel({ agentIds }), { ownerUserId: "user-1" });
+ },
+ async get() {
+ return Object.assign(channel(), { internalState: "hidden" });
+ },
+ });
+ const app = appFor(store);
+
+ const created = await app.request("http://openbot.test/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentIds: ["agent-1"] }),
+ });
+ const fetched = await app.request("http://openbot.test/channel-1");
+
+ expect(created.status).toBe(201);
+ expect(await json(created)).toEqual({
+ channel: {
+ id: "channel-1",
+ name: "Assistant channel",
+ agentIds: ["agent-1"],
+ threadId: "thread-1",
+ active: true,
+ },
+ });
+ expect(fetched.status).toBe(200);
+ expect(await json(fetched)).toEqual({ channel: channel() });
+ });
+
+ test.each([
+ ["{", "Channel input must be a JSON object."],
+ [JSON.stringify([]), "Channel input must be a JSON object."],
+ [JSON.stringify({ agentIds: [] }), "Agent IDs must be a non-empty array."],
+ ])(
+ "returns safe validation errors for malformed POST bodies",
+ async (body, error) => {
+ const store = fakeStore();
+ const response = await appFor(store).request("http://openbot.test/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body,
+ });
+
+ expect(response.status).toBe(400);
+ expect(await json(response)).toEqual({ error });
+ expect(store.calls).toEqual([]);
+ },
+ );
+
+ test("returns 404 when get returns null", async () => {
+ const store = fakeStore({ get: async () => null });
+
+ const response = await appFor(store).request("http://openbot.test/missing");
+
+ expect(response.status).toBe(404);
+ expect(await json(response)).toEqual({ error: "Channel not found." });
+ });
+
+ test.each([
+ ["create", new AgentNotFoundError("agent-1"), 404, "Agent not found."],
+ ["get", new ChannelNotFoundError("channel-1"), 404, "Channel not found."],
+ ] as const)(
+ "maps known store errors from %s",
+ async (method, error, status, message) => {
+ const store = fakeStore({
+ ...(method === "create"
+ ? {
+ create: async () => {
+ throw error;
+ },
+ }
+ : {
+ get: async () => {
+ throw error;
+ },
+ }),
+ });
+ const app = appFor(store);
+ const response =
+ method === "create"
+ ? await app.request("http://openbot.test/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentIds: ["agent-1"] }),
+ })
+ : await app.request("http://openbot.test/channel-1");
+
+ expect(response.status).toBe(status);
+ expect(await json(response)).toEqual({ error: message });
+ },
+ );
+
+ test("rethrows unexpected errors to the outer Hono error handler", async () => {
+ const store = fakeStore({
+ create: async () => {
+ throw new Error("database disconnected");
+ },
+ });
+ const app = appFor(store);
+ app.onError((error, context) =>
+ context.json({ sentinel: error.message }, 599),
+ );
+
+ const response = await app.request("http://openbot.test/", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ agentIds: ["agent-1"] }),
+ });
+
+ expect(response.status).toBe(599);
+ expect(await json(response)).toEqual({ sentinel: "database disconnected" });
+ });
+});
+
+describe("channel route composition", () => {
+ test("mounts the store behind createApp authentication with the derived actor", async () => {
+ const store = fakeStore();
+ let session: {
+ user: { id: string; email: string; name: string; image: string };
+ } | null = null;
+ const app = createApp(
+ loadConfig(testEnvironment()),
+ {
+ handler: () => new Response(null, { status: 204 }),
+ api: { getSession: async () => session },
+ },
+ { rolesForUser: async () => ["user"] },
+ // Positions 4-12, ending at agentProfileStore. the computer gateway and policy store were added
+ // ahead of these, so the run of placeholders grew with them.
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ store,
+ );
+
+ const unauthenticated = await app.request(
+ "http://openbot.test/api/channels/channel-1",
+ );
+ expect(unauthenticated.status).toBe(401);
+ expect(store.calls).toEqual([]);
+
+ session = {
+ user: {
+ id: actor.id,
+ email: actor.email,
+ name: "OpenBot Member",
+ image: "https://example.test/member.png",
+ },
+ };
+ const authenticated = await app.request(
+ "http://openbot.test/api/channels/channel-1",
+ );
+
+ expect(authenticated.status).toBe(200);
+ expect(store.calls).toEqual([
+ [
+ "get",
+ {
+ ...actor,
+ name: "OpenBot Member",
+ image: "https://example.test/member.png",
+ },
+ "channel-1",
+ ],
+ ]);
+ });
+
+ test("leaves channel routes unmounted when createApp has no store", async () => {
+ const app = createApp(loadConfig(testEnvironment()));
+
+ const response = await app.request(
+ "http://openbot.test/api/channels/channel-1",
+ );
+
+ expect(response.status).toBe(404);
+ });
+});
+
+const databaseUrl =
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot";
+const database = createDatabase(databaseUrl, TEST_POOL);
+const profileStore = createAgentProfileStore(
+ database,
+ new URL("https://managed.example.test/ag-ui"),
+);
+const persistentStore = createChannelStore(
+ database,
+ profileStore,
+ createThreadIdentity("test-deployment"),
+);
+const testPrefix = `channel-store-${randomUUID()}`;
+const createdUserIds: string[] = [];
+const createdAgentIds: string[] = [];
+const createdChannelIds: string[] = [];
+
+afterEach(async () => {
+ for (const channelId of createdChannelIds.splice(0)) {
+ await database
+ .delete(intelligenceChannelMappings)
+ .where(eq(intelligenceChannelMappings.channelId, channelId));
+ await database.delete(channels).where(eq(channels.id, channelId));
+ }
+ for (const agentId of createdAgentIds.splice(0)) {
+ await database
+ .delete(agentProfiles)
+ .where(eq(agentProfiles.agentId, agentId));
+ await database.delete(agents).where(eq(agents.id, agentId));
+ }
+ for (const userId of createdUserIds.splice(0)) {
+ await database.delete(users).where(eq(users.id, userId));
+ }
+});
+
+afterAll(async () => {
+ await database.$client.close();
+});
+
+function persistentId(kind: string) {
+ return `${testPrefix}-${kind}-${randomUUID()}`;
+}
+
+async function createPersistentUser(): Promise<AgentActor> {
+ const userId = persistentId("user");
+ await database.insert(users).values({
+ id: userId,
+ email: `${userId}@example.test`,
+ name: "Channel Store Test User",
+ });
+ createdUserIds.push(userId);
+ return { id: userId, role: "user" };
+}
+
+async function createPersistentAgent(options: {
+ id?: string;
+ name: string;
+ owner: AgentActor;
+ visibility?: "public" | "private";
+}) {
+ const agentId = options.id ?? persistentId("agent");
+ await database.insert(agents).values({
+ id: agentId,
+ name: options.name,
+ type: "remote_ag_ui",
+ configuration: { endpoint: "https://agent.example.test/ag-ui" },
+ });
+ createdAgentIds.push(agentId);
+ await database.insert(agentProfiles).values({
+ agentId,
+ ownerUserId: options.owner.id,
+ title: `${options.name} title`,
+ roleDescription: `${options.name} role description`,
+ avatarSeed: agentId,
+ visibility: options.visibility ?? "private",
+ });
+ return agentId;
+}
+
+async function persistedChannel(channelId: string) {
+ const [channelRow] = await database
+ .select()
+ .from(channels)
+ .where(eq(channels.id, channelId));
+ const memberships = await database
+ .select()
+ .from(channelMemberships)
+ .where(eq(channelMemberships.channelId, channelId));
+ const linkedAgents = await database
+ .select()
+ .from(channelAgents)
+ .where(eq(channelAgents.channelId, channelId));
+ const mappings = await database
+ .select()
+ .from(intelligenceChannelMappings)
+ .where(eq(intelligenceChannelMappings.channelId, channelId));
+ return { channelRow, memberships, linkedAgents, mappings };
+}
+
+async function channelTableSnapshot() {
+ return {
+ channels: (await database.select({ id: channels.id }).from(channels))
+ .map(({ id }) => id)
+ .sort(),
+ memberships: (
+ await database
+ .select({
+ channelId: channelMemberships.channelId,
+ userId: channelMemberships.userId,
+ })
+ .from(channelMemberships)
+ )
+ .map(({ channelId, userId }) => `${channelId}:${userId}`)
+ .sort(),
+ agents: (
+ await database
+ .select({
+ agentId: channelAgents.agentId,
+ channelId: channelAgents.channelId,
+ })
+ .from(channelAgents)
+ )
+ .map(({ agentId, channelId }) => `${channelId}:${agentId}`)
+ .sort(),
+ mappings: (
+ await database
+ .select({
+ channelId: intelligenceChannelMappings.channelId,
+ threadId: intelligenceChannelMappings.threadId,
+ userId: intelligenceChannelMappings.userId,
+ })
+ .from(intelligenceChannelMappings)
+ )
+ .map(
+ ({ channelId, threadId, userId }) =>
+ `${channelId}:${threadId}:${userId}`,
+ )
+ .sort(),
+ };
+}
+
+describe("channel store integration", () => {
+ test("reads the creator's persisted channel exactly", async () => {
+ const actor = await createPersistentUser();
+ const agentId = await createPersistentAgent({
+ name: "Historical agent",
+ owner: actor,
+ });
+ const created = await persistentStore.create(actor, [agentId]);
+ createdChannelIds.push(created.id);
+
+ expect(await persistentStore.get(actor, created.id)).toEqual(created);
+ });
+
+ test("does not expose a member's channel to another user through public agents", async () => {
+ const creator = await createPersistentUser();
+ const otherUser = await createPersistentUser();
+ const agentId = await createPersistentAgent({
+ name: "Public historical agent",
+ owner: creator,
+ visibility: "public",
+ });
+ const created = await persistentStore.create(creator, [agentId]);
+ createdChannelIds.push(created.id);
+ const otherUserMiddleware: MiddlewareHandler<{
+ Variables: AppVariables;
+ }> = async (context, next) => {
+ context.set("actor", otherUser);
+ await next();
+ };
+
+ expect(await persistentStore.get(otherUser, created.id)).toBeNull();
+ const response = await appFor(persistentStore, otherUserMiddleware).request(
+ `http://openbot.test/${created.id}`,
+ );
+ expect(response.status).toBe(404);
+ expect(await json(response)).toEqual({ error: "Channel not found." });
+ });
+
+ test("reads linked agent IDs in lexicographic order", async () => {
+ const actor = await createPersistentUser();
+ const agentIdBase = persistentId("ordered-agent");
+ const laterAgentId = await createPersistentAgent({
+ id: `${agentIdBase}-zulu`,
+ name: "Zulu",
+ owner: actor,
+ });
+ const earlierAgentId = await createPersistentAgent({
+ id: `${agentIdBase}-alpha`,
+ name: "Alpha",
+ owner: actor,
+ });
+ const created = await persistentStore.create(actor, [
+ laterAgentId,
+ earlierAgentId,
+ ]);
+ createdChannelIds.push(created.id);
+
+ expect((await persistentStore.get(actor, created.id))?.agentIds).toEqual(
+ [earlierAgentId, laterAgentId].sort(),
+ );
+ });
+
+ test("keeps a historical channel readable but inactive after a linked profile is deleted", async () => {
+ const actor = await createPersistentUser();
+ const activeAgentId = await createPersistentAgent({
+ name: "Active historical agent",
+ owner: actor,
+ });
+ const deletedAgentId = await createPersistentAgent({
+ name: "Deleted historical agent",
+ owner: actor,
+ });
+ const created = await persistentStore.create(
+ actor,
+ [activeAgentId, deletedAgentId].sort(),
+ );
+ createdChannelIds.push(created.id);
+ await profileStore.softDelete(actor, deletedAgentId);
+
+ expect(await persistentStore.get(actor, created.id)).toEqual({
+ ...created,
+ active: false,
+ });
+ });
+
+ test("returns null when the member's channel mapping is missing", async () => {
+ const actor = await createPersistentUser();
+ const agentId = await createPersistentAgent({
+ name: "Unmapped historical agent",
+ owner: actor,
+ });
+ const created = await persistentStore.create(actor, [agentId]);
+ createdChannelIds.push(created.id);
+ await database
+ .delete(intelligenceChannelMappings)
+ .where(eq(intelligenceChannelMappings.channelId, created.id));
+
+ expect(await persistentStore.get(actor, created.id)).toBeNull();
+ });
+
+ test("creates independent persisted channels for repeated agent selections", async () => {
+ const actor = await createPersistentUser();
+ const agentId = await createPersistentAgent({
+ name: "Solo Agent",
+ owner: actor,
+ });
+
+ const first = await persistentStore.create(actor, [agentId]);
+ createdChannelIds.push(first.id);
+ const second = await persistentStore.create(actor, [agentId]);
+ createdChannelIds.push(second.id);
+
+ expect(first).toMatchObject({
+ name: "Solo Agent",
+ agentIds: [agentId],
+ active: true,
+ });
+ expect(second).toMatchObject({
+ name: "Solo Agent",
+ agentIds: [agentId],
+ active: true,
+ });
+ expect(first.id).toMatch(/^channel_[0-9a-f-]{36}$/);
+ expect(second.id).toMatch(/^channel_[0-9a-f-]{36}$/);
+ expect(first.id).not.toBe(second.id);
+ expect(first.threadId).toMatch(/^[0-9a-f-]{36}$/);
+ expect(second.threadId).toMatch(/^[0-9a-f-]{36}$/);
+ expect(first.threadId).not.toBe(second.threadId);
+
+ for (const created of [first, second]) {
+ const persisted = await persistedChannel(created.id);
+ expect(persisted.channelRow).toMatchObject({
+ id: created.id,
+ name: "Solo Agent",
+ description: "Private agent channel.",
+ suggestedPrompts: [],
+ allowedGroups: [],
+ packageId: null,
+ override: null,
+ });
+ expect(persisted.memberships).toHaveLength(1);
+ expect(persisted.memberships[0]).toMatchObject({
+ channelId: created.id,
+ userId: actor.id,
+ });
+ expect(persisted.linkedAgents).toHaveLength(1);
+ expect(persisted.linkedAgents[0]).toMatchObject({
+ channelId: created.id,
+ agentId,
+ });
+ expect(persisted.mappings).toHaveLength(1);
+ expect(persisted.mappings[0]).toMatchObject({
+ userId: actor.id,
+ channelId: created.id,
+ threadId: created.threadId,
+ });
+ }
+ });
+
+ test("persists every canonical agent and derives its name in canonical order", async () => {
+ const actor = await createPersistentUser();
+ const firstId = await createPersistentAgent({
+ id: persistentId("agent-a"),
+ name: "Zulu",
+ owner: actor,
+ });
+ const secondId = await createPersistentAgent({
+ id: persistentId("agent-b"),
+ name: "Alpha",
+ owner: actor,
+ });
+ const canonicalAgentIds = [firstId, secondId].sort();
+
+ const created = await persistentStore.create(actor, canonicalAgentIds);
+ createdChannelIds.push(created.id);
+
+ expect(created).toEqual({
+ id: created.id,
+ name: "Zulu, Alpha",
+ agentIds: canonicalAgentIds,
+ threadId: created.threadId,
+ active: true,
+ });
+ const persisted = await persistedChannel(created.id);
+ expect(persisted.channelRow?.name).toBe("Zulu, Alpha");
+ expect(persisted.linkedAgents.map(({ agentId }) => agentId).sort()).toEqual(
+ canonicalAgentIds,
+ );
+ });
+
+ test("truncates derived names to 120 Unicode code points with an ellipsis", async () => {
+ const actor = await createPersistentUser();
+ const longName = "😀".repeat(121);
+ const agentId = await createPersistentAgent({
+ name: longName,
+ owner: actor,
+ });
+
+ const created = await persistentStore.create(actor, [agentId]);
+ createdChannelIds.push(created.id);
+
+ expect(Array.from(created.name)).toHaveLength(120);
+ expect(created.name).toBe(`${"😀".repeat(119)}…`);
+ expect((await persistedChannel(created.id)).channelRow?.name).toBe(
+ created.name,
+ );
+ });
+
+ test.each(["inaccessible private", "soft-deleted"] as const)(
+ "rejects an %s agent and leaves every channel table unchanged",
+ async (scenario) => {
+ const actor = await createPersistentUser();
+ const owner =
+ scenario === "inaccessible private"
+ ? await createPersistentUser()
+ : actor;
+ const accessibleAgentId = await createPersistentAgent({
+ name: "Accessible agent",
+ owner: actor,
+ });
+ const agentId = await createPersistentAgent({
+ name: `${scenario} agent`,
+ owner,
+ });
+ if (scenario === "soft-deleted") {
+ await profileStore.softDelete(actor, agentId);
+ }
+ const before = await channelTableSnapshot();
+
+ await expect(
+ persistentStore.create(actor, [accessibleAgentId, agentId].sort()),
+ ).rejects.toBeInstanceOf(AgentNotFoundError);
+
+ expect(await channelTableSnapshot()).toEqual(before);
+ },
+ );
+});
+
+/**
+ * Channel creation validates each selected agent through the profile store while its own
+ * transaction is open. If that read runs on a second pooled connection it is both a deadlock (the
+ * transaction holds a connection while waiting for one) and a time-of-check race (the read sees a
+ * different snapshot and takes no lock, so a concurrent deletion lands between check and insert).
+ */
+describe("channel store concurrency", () => {
+ test("creates a channel without borrowing a second connection", async () => {
+ const singleConnection = createDatabase(databaseUrl, { max: 1 });
+ const store = createChannelStore(
+ singleConnection,
+ createAgentProfileStore(
+ singleConnection,
+ new URL("https://managed.example.test/ag-ui"),
+ ),
+ createThreadIdentity("test-deployment"),
+ );
+ const owner = await createPersistentUser();
+ const agentId = await createPersistentAgent({
+ name: "Single connection agent",
+ owner,
+ });
+
+ try {
+ const created = await store.create(owner, [agentId]);
+ createdChannelIds.push(created.id);
+
+ expect(created.agentIds).toEqual([agentId]);
+ } finally {
+ await singleConnection.$client.close();
+ }
+ });
+
+ test("refuses an agent whose deletion commits mid-creation", async () => {
+ const owner = await createPersistentUser();
+ const agentId = await createPersistentAgent({
+ name: "Concurrently deleted agent",
+ owner,
+ });
+
+ let markDeleted: () => void = () => {};
+ let releaseDeletion: () => void = () => {};
+ const deletionApplied = new Promise<void>((resolve) => {
+ markDeleted = resolve;
+ });
+ const deletionHeld = new Promise<void>((resolve) => {
+ releaseDeletion = resolve;
+ });
+ const deletion = database.transaction(async (transaction) => {
+ await transaction
+ .update(agentProfiles)
+ .set({ deletedAt: new Date() })
+ .where(eq(agentProfiles.agentId, agentId));
+ markDeleted();
+ await deletionHeld;
+ });
+
+ await deletionApplied;
+ const creation = persistentStore.create(owner, [agentId]);
+ // Long enough for a correct implementation to reach the row lock and block on it.
+ await Bun.sleep(250);
+ releaseDeletion();
+ await deletion;
+
+ const outcome = await creation.then(
+ (created) => {
+ createdChannelIds.push(created.id);
+ return created;
+ },
+ (error: unknown) => error,
+ );
+
+ expect(outcome).toBeInstanceOf(AgentNotFoundError);
+ expect(
+ await database
+ .select({ channelId: channelAgents.channelId })
+ .from(channelAgents)
+ .where(eq(channelAgents.agentId, agentId)),
+ ).toEqual([]);
+ });
+});
diff --git a/server/tests/computer-client.test.ts b/server/tests/computer-client.test.ts
new file mode 100644
index 00000000..462a7b5c
--- /dev/null
+++ b/server/tests/computer-client.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, test } from "bun:test";
+import {
+ createComputerClient,
+ ElementNotFoundError,
+ NavigationRefusedError,
+} from "../src/computer/client";
+
+function clientWith(
+ handler: (url: string, init?: RequestInit) => Promise<Response> | Response,
+ allowPrivateHosts = false,
+) {
+ return createComputerClient({
+ baseUrl: "http://agent-computer:4100",
+ allowPrivateHosts,
+ fetchImpl: ((url: string, init?: RequestInit) =>
+ Promise.resolve(handler(url, init))) as unknown as typeof fetch,
+ });
+}
+
+const ok = (body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+
+describe("computer client", () => {
+ test("navigates and returns where it landed", async () => {
+ const seen: string[] = [];
+ const client = clientWith((url, init) => {
+ seen.push(url);
+ expect(JSON.parse(String(init?.body))).toEqual({
+ url: "https://example.com/",
+ });
+ return ok({
+ url: "https://example.com/",
+ title: "Example",
+ elapsedMs: 12,
+ });
+ });
+
+ await expect(client.navigate("https://example.com/")).resolves.toEqual({
+ url: "https://example.com/",
+ title: "Example",
+ elapsedMs: 12,
+ });
+ expect(seen).toEqual(["http://agent-computer:4100/navigate"]);
+ });
+
+ // The refusal happens before anything leaves. A guard that only inspects the response has
+ // already let the request reach the internal service it was meant to protect.
+ test("refuses an internal address without calling the computer", async () => {
+ let called = false;
+ const client = clientWith(() => {
+ called = true;
+ return ok({});
+ });
+
+ await expect(client.navigate("http://169.254.169.254/")).rejects.toThrow(
+ NavigationRefusedError,
+ );
+ expect(called).toBe(false);
+ });
+
+ // The opt-in every laptop sets must not be a way to reach the cloud credential endpoint. The
+ // earlier test above passes with the opt-in OFF, which is what let this through unnoticed.
+ test("refuses cloud metadata even when private hosts are allowed", async () => {
+ let called = false;
+ const client = clientWith(() => {
+ called = true;
+ return ok({});
+ }, true);
+
+ for (const target of [
+ "http://169.254.169.254/latest/meta-data/",
+ "http://metadata.google.internal/computeMetadata/v1/",
+ ]) {
+ await expect(client.navigate(target)).rejects.toThrow(
+ NavigationRefusedError,
+ );
+ }
+ expect(called).toBe(false);
+ });
+
+ test("allows an internal address when the deployment opted in", async () => {
+ const client = clientWith(
+ () => ok({ url: "http://localhost:3000/", title: "Local", elapsedMs: 3 }),
+ true,
+ );
+
+ await expect(
+ client.navigate("http://localhost:3000/"),
+ ).resolves.toMatchObject({ title: "Local" });
+ });
+
+ // Two different failures that read identically to a person unless we separate them: the computer
+ // being absent is an operator problem, a page failing to load is not.
+ test("reports an absent computer distinctly from a failed page", async () => {
+ const missing = clientWith(() => {
+ throw new Error("connect ECONNREFUSED");
+ });
+ await expect(missing.navigate("https://example.com")).rejects.toThrow(
+ "The assistant's computer is not running.",
+ );
+
+ const badPage = clientWith(
+ () =>
+ new Response(JSON.stringify({ error: "net::ERR_NAME_NOT_RESOLVED" }), {
+ status: 502,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ await expect(badPage.navigate("https://nope.example")).rejects.toThrow(
+ "net::ERR_NAME_NOT_RESOLVED",
+ );
+ });
+
+ test("status reports unreachable rather than throwing", async () => {
+ const client = clientWith(() => {
+ throw new Error("down");
+ });
+
+ await expect(client.status("bot-1")).resolves.toEqual({
+ botId: "bot-1",
+ state: "unreachable",
+ reason: "The assistant's computer is not running.",
+ });
+ });
+
+ test("screenshot returns the png a transcript can render", async () => {
+ const client = clientWith(() =>
+ ok({
+ base64: "aGVsbG8=",
+ width: 1280,
+ height: 800,
+ capturedAt: "2026-08-14T00:00:00.000Z",
+ }),
+ );
+
+ await expect(client.screenshot()).resolves.toMatchObject({
+ base64: "aGVsbG8=",
+ width: 1280,
+ });
+ });
+
+ test("surfaces a timeout as the computer not responding", async () => {
+ const client = clientWith(() => {
+ const error = new Error("timed out");
+ error.name = "TimeoutError";
+ throw error;
+ });
+
+ await expect(client.status("bot-1")).resolves.toMatchObject({
+ state: "unreachable",
+ reason: "The assistant's computer did not respond in time.",
+ });
+ });
+});
+
+/**
+ * A ref that is not on the page.
+ *
+ * Reported as a stale snapshot, not as computer unavailability. A model can recover by taking a
+ * fresh snapshot.
+ */
+describe("acting on an element that is not there", () => {
+ const playwrightTimeout = {
+ error:
+ "click: Timeout 10000ms exceeded.\nCall log:\n - waiting for locator('aria-ref=e5')\n",
+ };
+
+ const timingOut = () =>
+ clientWith(
+ () =>
+ new Response(JSON.stringify(playwrightTimeout), {
+ status: 500,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+
+ test("is its own condition, not an unavailable computer", async () => {
+ expect(
+ timingOut().click({ ref: "e5", snapshotId: 1 }),
+ ).rejects.toBeInstanceOf(ElementNotFoundError);
+ });
+
+ test("says what to do next, and drops the call log", async () => {
+ try {
+ await timingOut().click({ ref: "e5", snapshotId: 1 });
+ throw new Error("should have refused");
+ } catch (error) {
+ const message = (error as Error).message;
+ // The instruction, naming the ref that failed.
+ expect(message).toContain("e5");
+ expect(message).toContain("fresh snapshot");
+ // Not several lines of Playwright internals, which are noise to a model and to a person.
+ expect(message).not.toContain("Call log");
+ expect(message).not.toContain("Timeout");
+ }
+ });
+});
+
+/**
+ * Stop has to travel.
+ *
+ * Pressing Stop aborts the surface's request. That abort is only useful if it reaches the browser: a
+ * click already running in Chromium otherwise lands anyway, which is harmless most of the time and
+ * not harmless on a Confirm button, precisely the moment somebody presses Stop.
+ */
+describe("the caller's Stop", () => {
+ test("is passed to the request, so it can reach the browser", async () => {
+ let seen: AbortSignal | undefined;
+ const client = clientWith((_url, init) => {
+ seen = init?.signal ?? undefined;
+ return ok({ action: "click" });
+ });
+
+ const stop = new AbortController();
+ await client.click({ ref: "e1", snapshotId: 1 }, stop.signal);
+
+ expect(seen).toBeDefined();
+ // Not the caller's signal itself: it is combined with the timeout, because a computer that stops
+ // answering must still end the request even when nobody pressed anything.
+ expect(seen?.aborted).toBe(false);
+ stop.abort();
+ expect(seen?.aborted).toBe(true);
+ });
+
+ test("a request that was already stopped never reaches the computer", async () => {
+ let called = false;
+ const client = clientWith(() => {
+ called = true;
+ return ok({ action: "click" });
+ });
+
+ const stop = new AbortController();
+ stop.abort();
+
+ expect(
+ client.click({ ref: "e1", snapshotId: 1 }, stop.signal),
+ ).rejects.toBeDefined();
+ expect(called).toBe(false);
+ });
+
+ test("without one, the timeout still applies", async () => {
+ let seen: AbortSignal | undefined;
+ const client = clientWith((_url, init) => {
+ seen = init?.signal ?? undefined;
+ return ok({ action: "click" });
+ });
+
+ await client.click({ ref: "e1", snapshotId: 1 });
+
+ // A caller that passes nothing must not end up with an unbounded request.
+ expect(seen).toBeDefined();
+ });
+});
diff --git a/server/tests/connector-admin.integration.test.ts b/server/tests/connector-admin.integration.test.ts
new file mode 100644
index 00000000..317756e6
--- /dev/null
+++ b/server/tests/connector-admin.integration.test.ts
@@ -0,0 +1,109 @@
+import { afterAll, beforeAll, expect, test } from "bun:test";
+import { eq } from "drizzle-orm";
+import { createConnectorAdminService } from "../src/connectors";
+import type { CredentialAdminService } from "../src/credentials";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import {
+ connectorInstances,
+ credentials as credentialRows,
+} from "../src/db/schema";
+
+/**
+ * What the Connectors page reports about a connector that has been set up.
+ *
+ * The catalogue is built from `knowledge.yaml`, which says what a deployment may connect to rather
+ * than what it has, so the listing has to read the instances as well.
+ */
+
+const database = createDatabase(
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot",
+ TEST_POOL,
+);
+
+const sources = [
+ { type: "google-drive" as const, roots: ["Policies"] },
+ { type: "microsoft-onedrive" as const, roots: ["Operations"] },
+];
+
+/**
+ * No vault: what is under test is what the listing reports, not how a secret is kept. The row is
+ * still written, because a connector instance references the credential it was set up with.
+ */
+const issued: string[] = [];
+const credentials = {
+ create: async () => {
+ const [row] = await database
+ .insert(credentialRows)
+ .values({
+ kind: "connector",
+ provider: "google_drive",
+ encryptedValue: "{}",
+ keyId: "[email protected]",
+ metadata: {},
+ })
+ .returning({ id: credentialRows.id });
+ issued.push(row.id);
+ return {
+ id: row.id,
+ kind: "connector" as const,
+ provider: "google_drive",
+ keyId: "[email protected]",
+ metadata: {},
+ revokedAt: null,
+ };
+ },
+} as unknown as CredentialAdminService;
+
+const service = createConnectorAdminService(sources, database, credentials);
+
+async function removeGoogleDriveInstance() {
+ await database
+ .delete(connectorInstances)
+ .where(eq(connectorInstances.type, "google_drive"));
+}
+
+let alreadyConfigured = false;
+
+beforeAll(async () => {
+ alreadyConfigured =
+ (
+ await database
+ .select({ id: connectorInstances.id })
+ .from(connectorInstances)
+ .where(eq(connectorInstances.type, "google_drive"))
+ ).length > 0;
+});
+
+afterAll(async () => {
+ if (!alreadyConfigured) await removeGoogleDriveInstance();
+ for (const id of issued) {
+ await database.delete(credentialRows).where(eq(credentialRows.id, id));
+ }
+});
+
+test("a connector reads as configured once it has been set up", async () => {
+ if (alreadyConfigured) await removeGoogleDriveInstance();
+
+ const before = await service.list();
+ expect(before.map((connector) => connector.configured)).toEqual([
+ false,
+ false,
+ ]);
+
+ await service.configureGoogleDrive?.({
+ serviceAccountJson: JSON.stringify({ type: "service_account" }),
+ impersonationSubject: "[email protected]",
+ actorUserId: "admin",
+ });
+
+ const after = await service.list();
+ // Only the one that was set up, so the listing reports the deployment rather than the catalogue.
+ expect(
+ after.map((connector) => [connector.type, connector.configured]),
+ ).toEqual([
+ ["google_drive", true],
+ ["onedrive", false],
+ ]);
+});
diff --git a/server/tests/copilot.test.ts b/server/tests/copilot.test.ts
new file mode 100644
index 00000000..8369571d
--- /dev/null
+++ b/server/tests/copilot.test.ts
@@ -0,0 +1,427 @@
+import { describe, expect, spyOn, test } from "bun:test";
+import { HttpAgent } from "@ag-ui/client";
+import { BuiltInAgent } from "@copilotkit/runtime/v2";
+import {
+ buildAgents,
+ builtInAgentConfiguration,
+ createRequestAgents,
+ registeredAgentFromRow,
+ resolveRuntimeAgents,
+ standingRoleMessage,
+} from "../src/copilot";
+
+// Every agent row now joins its profile, so the row a teammate is built from always names it.
+const assistantRow = {
+ id: "general-assistant",
+ name: "General Assistant",
+ type: "built_in" as const,
+ title: "Everyday Work",
+ roleDescription: "Help with everyday work.",
+};
+const riskRow = {
+ id: "risk",
+ name: "Risk",
+ type: "remote_ag_ui" as const,
+ title: "Risk & Compliance",
+ roleDescription: "Investigate policies and controls.",
+};
+
+describe("registered Copilot agents", () => {
+ test("normalizes built-in and remote rows", () => {
+ expect(
+ registeredAgentFromRow({
+ ...assistantRow,
+ configuration: { systemPrompt: "Be helpful." },
+ }),
+ ).toEqual({
+ id: "general-assistant",
+ name: "General Assistant",
+ type: "built_in",
+ systemPrompt: "Be helpful.",
+ });
+ expect(
+ registeredAgentFromRow({
+ ...riskRow,
+ configuration: { endpoint: "http://risk.internal/ag-ui" },
+ }),
+ ).toEqual({
+ id: "risk",
+ name: "Risk",
+ type: "remote_ag_ui",
+ endpoint: "http://risk.internal/ag-ui",
+ standingMessage: standingRoleMessage(riskRow),
+ });
+ });
+
+ test("rejects malformed agent configurations", () => {
+ const rows = [
+ { ...assistantRow, configuration: {} },
+ { ...assistantRow, configuration: null },
+ { ...assistantRow, configuration: [] },
+ { ...assistantRow, configuration: { systemPrompt: " " } },
+ { ...riskRow, configuration: { endpoint: "" } },
+ { ...riskRow, configuration: { endpoint: "not a URL" } },
+ { ...riskRow, configuration: { endpoint: "ftp://risk.internal/ag-ui" } },
+ ] as const;
+
+ for (const row of rows) {
+ expect(registeredAgentFromRow(row)).toBeNull();
+ }
+ });
+
+ test("trims built-in prompts and preserves valid remote endpoint strings", () => {
+ expect(
+ registeredAgentFromRow({
+ ...assistantRow,
+ configuration: { systemPrompt: " Be helpful. " },
+ }),
+ ).toMatchObject({ systemPrompt: "Be helpful." });
+ expect(
+ registeredAgentFromRow({
+ ...riskRow,
+ configuration: { endpoint: "https://risk.internal:443/ag-ui" },
+ }),
+ ).toMatchObject({ endpoint: "https://risk.internal:443/ag-ui" });
+ });
+
+ test("configures an OpenAI built-in agent", () => {
+ expect(
+ builtInAgentConfiguration(
+ {
+ id: "general-assistant",
+ name: "General Assistant",
+ type: "built_in",
+ systemPrompt: "Be helpful.",
+ },
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ "openai-secret",
+ ),
+ ).toEqual({
+ model: "openai/gpt-4.1",
+ prompt: "Be helpful.",
+ apiKey: "openai-secret",
+ });
+ });
+
+ test("fails an unavailable built-in agent through the AG-UI lifecycle", async () => {
+ const agents = buildAgents(
+ [
+ {
+ id: "general-assistant",
+ name: "General Assistant",
+ type: "built_in",
+ systemPrompt: "Be helpful.",
+ },
+ ],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ null,
+ );
+ const agent = agents["general-assistant"];
+ if (!agent) {
+ throw new Error("Expected the built-in agent");
+ }
+ let lifecycleError: Error | undefined;
+ const consoleError = spyOn(console, "error").mockImplementation(() => {});
+
+ try {
+ await expect(
+ agent.runAgent(undefined, {
+ onRunFailed: ({ error }) => {
+ lifecycleError = error;
+ },
+ }),
+ ).rejects.toThrow("Add the package credential or set OPENAI_API_KEY");
+ } finally {
+ consoleError.mockRestore();
+ }
+ expect(lifecycleError?.message).toContain(
+ "Add the package credential or set OPENAI_API_KEY",
+ );
+ });
+
+ test("constructs built-in and remote agents together", () => {
+ const agents = buildAgents(
+ [
+ {
+ id: "general-assistant",
+ name: "General Assistant",
+ type: "built_in",
+ systemPrompt: "Be helpful.",
+ },
+ {
+ id: "risk",
+ name: "Risk",
+ type: "remote_ag_ui",
+ endpoint: "http://risk.internal/ag-ui",
+ },
+ ],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ "openai-secret",
+ );
+
+ expect(agents["general-assistant"]).toBeInstanceOf(BuiltInAgent);
+ expect(agents.risk).toBeInstanceOf(HttpAgent);
+ });
+
+ test("resolves fresh built-in agents and credentials for every request", async () => {
+ const registered = [
+ {
+ id: "general-assistant",
+ name: "General Assistant",
+ type: "built_in" as const,
+ systemPrompt: "Be helpful.",
+ },
+ ];
+ let resolutionCount = 0;
+ const resolveModelApiKey = async () => {
+ resolutionCount += 1;
+ return resolutionCount === 1 ? "first-secret" : null;
+ };
+
+ const first = await resolveRuntimeAgents(
+ async () => registered,
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ resolveModelApiKey,
+ );
+ const second = await resolveRuntimeAgents(
+ async () => registered,
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ resolveModelApiKey,
+ );
+
+ expect(first["general-assistant"]).not.toBe(second["general-assistant"]);
+ expect(resolutionCount).toBe(2);
+ const consoleError = spyOn(console, "error").mockImplementation(() => {});
+ try {
+ await expect(second["general-assistant"]?.runAgent()).rejects.toThrow(
+ "Add the package credential or set OPENAI_API_KEY",
+ );
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
+
+ test("does not resolve model credentials for remote-only agents", async () => {
+ let resolverInvoked = false;
+ const agents = await resolveRuntimeAgents(
+ async () => [
+ {
+ id: "risk",
+ name: "Risk",
+ type: "remote_ag_ui",
+ endpoint: "http://risk.internal/ag-ui",
+ },
+ ],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ async () => {
+ resolverInvoked = true;
+ throw new Error("corrupt model credential");
+ },
+ );
+
+ expect(agents.risk).toBeInstanceOf(HttpAgent);
+ expect(resolverInvoked).toBe(false);
+ });
+});
+
+/**
+ * A teammate's job is durable: it lives on the profile, not in the conversation. Every run of a
+ * remote agent therefore carries a standing role message the person never has to retype, and the
+ * runtime resolves which agents exist per request so one person's private teammate is not another's.
+ */
+describe("standing agent roles", () => {
+ const profile = {
+ id: "agent_expense",
+ name: "Expense Manager",
+ title: "Finance Operations",
+ roleDescription:
+ "Review receipts, categorize expenses, and prepare reimbursement reports.",
+ };
+
+ test("builds a stable, framework-neutral standing role message", () => {
+ expect(standingRoleMessage(profile)).toEqual({
+ id: "standing-role:agent_expense",
+ role: "system",
+ content: [
+ "You are Expense Manager, Finance Operations.",
+ "Review receipts, categorize expenses, and prepare reimbursement reports.",
+ "This standing role applies in every channel. Treat channel messages as task-specific instructions within it.",
+ ].join("\n\n"),
+ });
+ });
+
+ test("sends one standing role message ahead of the conversation", async () => {
+ await using endpoint = fakeAgUiEndpoint();
+ const agents = buildAgents(
+ [remoteAgent(endpoint.url)],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ null,
+ );
+
+ const agent = agents.agent_expense;
+ // A replayed thread already carries the standing message; it must not produce a second copy.
+ agent?.setMessages([
+ standingRoleMessage(profile),
+ userMessage("Sort these."),
+ ]);
+ const result = await agent?.runAgent();
+
+ const sent = endpoint.requests.at(-1);
+ expect(sent?.messages).toEqual([
+ standingRoleMessage(profile),
+ userMessage("Sort these."),
+ ]);
+ expect(result?.newMessages?.at(-1)?.content).toBe("Categorized.");
+ });
+
+ test("keeps the standing role out of forwarded props and agent state", async () => {
+ await using endpoint = fakeAgUiEndpoint();
+ const agents = buildAgents(
+ [remoteAgent(endpoint.url)],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ null,
+ );
+
+ const agent = agents.agent_expense;
+ agent?.setMessages([userMessage("Sort these.")]);
+ await agent?.runAgent();
+
+ const sent = endpoint.requests.at(-1);
+ expect(JSON.stringify(sent?.forwardedProps ?? {})).not.toContain(
+ "standing-role",
+ );
+ expect(JSON.stringify(sent?.state ?? {})).not.toContain("standing-role");
+ });
+
+ test("resolves a deleted teammate as a tombstone that never reaches its endpoint", async () => {
+ await using endpoint = fakeAgUiEndpoint();
+ const agents = buildAgents(
+ [
+ {
+ id: "agent_expense",
+ name: "Expense Manager",
+ type: "unavailable",
+ reason: "Expense Manager has been deleted.",
+ },
+ ],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ null,
+ );
+
+ const consoleError = spyOn(console, "error").mockImplementation(() => {});
+ try {
+ await expect(agents.agent_expense?.runAgent()).rejects.toThrow(
+ "Expense Manager has been deleted.",
+ );
+ } finally {
+ consoleError.mockRestore();
+ }
+ // A tombstone exists so Intelligence can restore the thread, not so it can run.
+ expect(agents.agent_expense).toBeDefined();
+ expect(endpoint.requests).toEqual([]);
+ });
+
+ test("resolves agents per request from the requesting actor", async () => {
+ const seen: { request?: Request; actors: unknown[] } = { actors: [] };
+ const factory = createRequestAgents(
+ async (request) => {
+ seen.request = request;
+ return { id: "user-7", role: "user" as const };
+ },
+ async (actor) => {
+ seen.actors.push(actor);
+ return [remoteAgent("http://teammate.internal/ag-ui")];
+ },
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ async () => null,
+ );
+
+ const request = new Request("http://openbot.test/api/copilotkit");
+ const resolved = await factory({ request });
+
+ expect(seen.request).toBe(request);
+ expect(seen.actors).toEqual([{ id: "user-7", role: "user" }]);
+ expect(resolved.agent_expense).toBeInstanceOf(HttpAgent);
+ });
+
+ test("rebuilds each agent from the loader so an edited role applies to the next run", async () => {
+ let roleDescription = "Review receipts.";
+ const factory = createRequestAgents(
+ async () => ({ id: "user-7", role: "user" as const }),
+ async () => [
+ remoteAgent("http://teammate.internal/ag-ui", { roleDescription }),
+ ],
+ { provider: "openai", defaultModel: "gpt-4.1" },
+ async () => null,
+ );
+ const request = new Request("http://openbot.test/api/copilotkit");
+
+ const before = await factory({ request });
+ roleDescription = "Reconcile corporate card statements.";
+ const after = await factory({ request });
+
+ expect(before.agent_expense).not.toBe(after.agent_expense);
+ expect(standingRoleMessage({ ...profile, roleDescription }).content).toBe(
+ [
+ "You are Expense Manager, Finance Operations.",
+ "Reconcile corporate card statements.",
+ "This standing role applies in every channel. Treat channel messages as task-specific instructions within it.",
+ ].join("\n\n"),
+ );
+ });
+
+ function remoteAgent(
+ endpoint: string,
+ overrides: Partial<typeof profile> = {},
+ ) {
+ const resolved = { ...profile, ...overrides };
+ return {
+ id: resolved.id,
+ name: resolved.name,
+ type: "remote_ag_ui" as const,
+ endpoint,
+ standingMessage: standingRoleMessage(resolved),
+ };
+ }
+});
+
+function userMessage(content: string) {
+ return { id: `user-${content}`, role: "user" as const, content };
+}
+
+/**
+ * An AG-UI server that records what it was sent and answers with a complete run, so the standing
+ * role can be asserted on the wire rather than on the object that was supposed to send it.
+ */
+function fakeAgUiEndpoint() {
+ const requests: Record<string, unknown>[] = [];
+ const server = Bun.serve({
+ port: 0,
+ fetch: async (request) => {
+ const input = (await request.json()) as Record<string, unknown>;
+ requests.push(input);
+ const { threadId, runId } = input as { threadId: string; runId: string };
+ const events = [
+ { type: "RUN_STARTED", threadId, runId },
+ { type: "TEXT_MESSAGE_START", messageId: "reply-1", role: "assistant" },
+ {
+ type: "TEXT_MESSAGE_CONTENT",
+ messageId: "reply-1",
+ delta: "Categorized.",
+ },
+ { type: "TEXT_MESSAGE_END", messageId: "reply-1" },
+ { type: "RUN_FINISHED", threadId, runId },
+ ];
+ return new Response(
+ events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""),
+ { headers: { "content-type": "text/event-stream" } },
+ );
+ },
+ });
+
+ return {
+ requests,
+ url: `http://localhost:${server.port}/ag-ui`,
+ [Symbol.asyncDispose]: () => server.stop(true),
+ };
+}
diff --git a/server/tests/credentials.test.ts b/server/tests/credentials.test.ts
new file mode 100644
index 00000000..de7acd1a
--- /dev/null
+++ b/server/tests/credentials.test.ts
@@ -0,0 +1,483 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { createApp } from "../src/app";
+import { loadConfig } from "../src/config";
+import {
+ createCredential,
+ createCredentialStore,
+ decryptCredentialForUse,
+ decryptSecret,
+ encryptSecret,
+ resolveModelApiKey,
+ revokeCredential,
+ rotateCredential,
+} from "../src/credentials";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import { credentials } from "../src/db/schema";
+import { testEnvironment } from "./support/environment";
+
+const key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
+const config = loadConfig(testEnvironment({ KEY_ENCRYPTION_KEY: key }));
+const database = createDatabase(
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot",
+ TEST_POOL,
+);
+const credentialIds: string[] = [];
+
+afterEach(async () => {
+ for (const credentialId of credentialIds.splice(0)) {
+ await database.delete(credentials).where(eq(credentials.id, credentialId));
+ }
+});
+
+describe("credential encryption", () => {
+ test("stores a versioned AES-GCM envelope and restores it only server-side", async () => {
+ const envelope = await encryptSecret(key, "openai-secret-value");
+
+ expect(JSON.parse(envelope)).toEqual({
+ version: 1,
+ iv: expect.any(String),
+ ciphertext: expect.any(String),
+ });
+ await expect(decryptSecret(key, envelope)).resolves.toBe(
+ "openai-secret-value",
+ );
+ });
+
+ test("creates a write-only credential and audits safe metadata", async () => {
+ const stored: unknown[] = [];
+ const audited: unknown[] = [];
+
+ const credential = await createCredential(
+ {
+ encryptionKey: key,
+ store: {
+ create: async (value) => {
+ stored.push(value);
+ return { id: "credential-1", revokedAt: null };
+ },
+ revoke: async () => new Date(),
+ },
+ auditStore: {
+ insert: async (event) => {
+ audited.push(event);
+ },
+ },
+ },
+ {
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ plaintext: "openai-secret-value",
+ actorUserId: "admin",
+ },
+ );
+
+ expect(credential).toEqual({
+ id: "credential-1",
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ revokedAt: null,
+ });
+ expect(JSON.stringify(stored)).not.toContain("openai-secret-value");
+ expect(audited).toEqual([
+ {
+ eventType: "credential.created",
+ targetType: "credential",
+ targetId: "credential-1",
+ actorUserId: "admin",
+ payload: {
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ },
+ },
+ ]);
+ });
+
+ test("rotates then revokes credentials without returning plaintext", async () => {
+ const revoked: string[] = [];
+ const audited: unknown[] = [];
+ const service = {
+ encryptionKey: key,
+ store: {
+ create: async () => ({ id: "credential-new", revokedAt: null }),
+ revoke: async (id: string) => {
+ revoked.push(id);
+ return new Date("2026-08-13T12:00:00.000Z");
+ },
+ },
+ auditStore: {
+ insert: async (event: unknown) => {
+ audited.push(event);
+ },
+ },
+ };
+
+ await rotateCredential(service, {
+ previousCredentialId: "credential-old",
+ kind: "model",
+ provider: "openai",
+ keyId: "secondary",
+ metadata: { label: "Rotated OpenAI" },
+ plaintext: "new-openai-secret",
+ actorUserId: "admin",
+ });
+ await revokeCredential(service, "credential-new", "admin");
+
+ expect(revoked).toEqual(["credential-old", "credential-new"]);
+ expect(JSON.stringify(audited)).not.toContain("new-openai-secret");
+ expect(
+ audited.map((event) => (event as { eventType: string }).eventType),
+ ).toEqual(["credential.rotated", "credential.revoked"]);
+ });
+
+ test("decrypts only an active credential for server-side use", async () => {
+ const encryptedValue = await encryptSecret(key, "connector-secret");
+
+ await expect(
+ decryptCredentialForUse(
+ key,
+ { readSecret: async () => ({ encryptedValue, revokedAt: null }) },
+ "credential-1",
+ ),
+ ).resolves.toBe("connector-secret");
+ await expect(
+ decryptCredentialForUse(
+ key,
+ { readSecret: async () => ({ encryptedValue, revokedAt: new Date() }) },
+ "credential-1",
+ ),
+ ).rejects.toThrow("Credential is revoked");
+ });
+});
+
+describe("model credential resolution", () => {
+ test("prefers a stored model credential over the environment", async () => {
+ const encryptedValue = await encryptSecret(key, "stored-openai-key");
+
+ await expect(
+ resolveModelApiKey({
+ encryptionKey: key,
+ reader: {
+ readModelSecret: async () => ({ encryptedValue }),
+ },
+ provider: "openai",
+ keyId: "openai-api-key",
+ environment: { OPENAI_API_KEY: "environment-openai-key" },
+ }),
+ ).resolves.toBe("stored-openai-key");
+ });
+
+ test("uses OPENAI_API_KEY when no stored credential exists", async () => {
+ await expect(
+ resolveModelApiKey({
+ encryptionKey: key,
+ reader: { readModelSecret: async () => null },
+ provider: "openai",
+ keyId: "openai-api-key",
+ environment: { OPENAI_API_KEY: " environment-openai-key " },
+ }),
+ ).resolves.toBe("environment-openai-key");
+ });
+
+ test("returns null when neither credential source is configured", async () => {
+ await expect(
+ resolveModelApiKey({
+ encryptionKey: key,
+ reader: { readModelSecret: async () => null },
+ provider: "openai",
+ keyId: "openai-api-key",
+ environment: {},
+ }),
+ ).resolves.toBeNull();
+ });
+
+ test("rejects corrupt stored ciphertext instead of falling back to the environment", async () => {
+ await expect(
+ resolveModelApiKey({
+ encryptionKey: key,
+ reader: {
+ readModelSecret: async () => ({ encryptedValue: "corrupt" }),
+ },
+ provider: "openai",
+ keyId: "openai-api-key",
+ environment: { OPENAI_API_KEY: "environment-openai-key" },
+ }),
+ ).rejects.toThrow("Credential envelope is invalid");
+ });
+});
+
+describe("model credential store lookup", () => {
+ test("selects the newest active matching model credential with id as the timestamp tie-breaker", async () => {
+ const matchingOldId = randomUUID();
+ const matchingLowerId = "00000000-0000-4000-8000-000000000001";
+ const matchingHigherId = "00000000-0000-4000-8000-000000000002";
+ const ignoredIds = [randomUUID(), randomUUID(), randomUUID(), randomUUID()];
+ const allIds = [
+ matchingOldId,
+ matchingLowerId,
+ matchingHigherId,
+ ...ignoredIds,
+ ];
+ credentialIds.push(...allIds);
+
+ await database.insert(credentials).values([
+ {
+ id: matchingOldId,
+ kind: "model",
+ provider: "openai",
+ keyId: "openai-api-key",
+ encryptedValue: "old-matching-value",
+ metadata: {},
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ },
+ {
+ id: matchingLowerId,
+ kind: "model",
+ provider: "openai",
+ keyId: "openai-api-key",
+ encryptedValue: "lower-id-value",
+ metadata: {},
+ createdAt: new Date("2026-02-01T00:00:00.000Z"),
+ },
+ {
+ id: matchingHigherId,
+ kind: "model",
+ provider: "openai",
+ keyId: "openai-api-key",
+ encryptedValue: "higher-id-value",
+ metadata: {},
+ createdAt: new Date("2026-02-01T00:00:00.000Z"),
+ },
+ {
+ id: ignoredIds[0]!,
+ kind: "connector",
+ provider: "openai",
+ keyId: "openai-api-key",
+ encryptedValue: "wrong-kind-value",
+ metadata: {},
+ createdAt: new Date("2026-03-01T00:00:00.000Z"),
+ },
+ {
+ id: ignoredIds[1]!,
+ kind: "model",
+ provider: "other",
+ keyId: "openai-api-key",
+ encryptedValue: "wrong-provider-value",
+ metadata: {},
+ createdAt: new Date("2026-03-01T00:00:00.000Z"),
+ },
+ {
+ id: ignoredIds[2]!,
+ kind: "model",
+ provider: "openai",
+ keyId: "other-api-key",
+ encryptedValue: "wrong-key-value",
+ metadata: {},
+ createdAt: new Date("2026-03-01T00:00:00.000Z"),
+ },
+ {
+ id: ignoredIds[3]!,
+ kind: "model",
+ provider: "openai",
+ keyId: "openai-api-key",
+ encryptedValue: "revoked-value",
+ metadata: {},
+ revokedAt: new Date("2026-03-01T00:00:00.000Z"),
+ createdAt: new Date("2026-03-01T00:00:00.000Z"),
+ },
+ ]);
+
+ await expect(
+ createCredentialStore(database).readModelSecret({
+ provider: "openai",
+ keyId: "openai-api-key",
+ }),
+ ).resolves.toEqual({ encryptedValue: "higher-id-value" });
+ });
+});
+
+describe("admin credential API", () => {
+ test("returns only credential status and metadata", async () => {
+ const app = createApp(
+ config,
+ {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => ({
+ user: { id: "admin", email: "[email protected]" },
+ }),
+ },
+ },
+ { rolesForUser: async () => ["admin"] },
+ undefined,
+ {
+ list: async () => [
+ {
+ id: "credential-1",
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ revokedAt: null,
+ },
+ ],
+ },
+ );
+
+ const response = await app.request(
+ "http://openbot.local/api/admin/credentials",
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ credentials: [
+ {
+ id: "credential-1",
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ revokedAt: null,
+ },
+ ],
+ });
+ });
+
+ test("accepts plaintext only on credential creation and returns safe status", async () => {
+ const created: unknown[] = [];
+ const app = createApp(
+ config,
+ {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => ({
+ user: { id: "admin", email: "[email protected]" },
+ }),
+ },
+ },
+ { rolesForUser: async () => ["admin"] },
+ undefined,
+ {
+ list: async () => [],
+ create: async (input) => {
+ created.push(input);
+ return {
+ id: "credential-1",
+ kind: input.kind,
+ provider: input.provider,
+ keyId: input.keyId,
+ metadata: input.metadata,
+ revokedAt: null,
+ };
+ },
+ },
+ );
+
+ const response = await app.request(
+ "http://openbot.local/api/admin/credentials",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ plaintext: "openai-secret-value",
+ }),
+ },
+ );
+
+ expect(response.status).toBe(201);
+ await expect(response.json()).resolves.toEqual({
+ credential: {
+ id: "credential-1",
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ revokedAt: null,
+ },
+ });
+ expect(created).toEqual([
+ {
+ kind: "model",
+ provider: "openai",
+ keyId: "primary",
+ metadata: { label: "Production OpenAI" },
+ plaintext: "openai-secret-value",
+ actorUserId: "admin",
+ },
+ ]);
+ });
+
+ test("rotates and revokes through write-only administrator operations", async () => {
+ const calls: string[] = [];
+ const app = createApp(
+ config,
+ {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => ({
+ user: { id: "admin", email: "[email protected]" },
+ }),
+ },
+ },
+ { rolesForUser: async () => ["admin"] },
+ undefined,
+ {
+ list: async () => [],
+ create: async () => {
+ throw new Error("not used");
+ },
+ rotate: async (input) => {
+ calls.push(`rotate:${input.previousCredentialId}`);
+ return {
+ id: "credential-new",
+ kind: input.kind,
+ provider: input.provider,
+ keyId: input.keyId,
+ metadata: input.metadata,
+ revokedAt: null,
+ };
+ },
+ revoke: async (id) => {
+ calls.push(`revoke:${id}`);
+ return { id, revokedAt: new Date("2026-08-13T12:00:00.000Z") };
+ },
+ },
+ );
+
+ const rotate = await app.request(
+ "http://openbot.local/api/admin/credentials/credential-old/rotate",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ kind: "model",
+ provider: "openai",
+ keyId: "secondary",
+ metadata: {},
+ plaintext: "rotated-secret",
+ }),
+ },
+ );
+ const revoke = await app.request(
+ "http://openbot.local/api/admin/credentials/credential-new/revoke",
+ { method: "POST" },
+ );
+
+ expect(rotate.status).toBe(200);
+ expect(revoke.status).toBe(200);
+ expect(calls).toEqual(["rotate:credential-old", "revoke:credential-new"]);
+ expect(await rotate.text()).not.toContain("rotated-secret");
+ });
+});
diff --git a/server/tests/database.test.ts b/server/tests/database.test.ts
new file mode 100644
index 00000000..ee55ca9d
--- /dev/null
+++ b/server/tests/database.test.ts
@@ -0,0 +1,12 @@
+import { expect, test } from "bun:test";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+
+test("creates a typed database boundary without opening a query", () => {
+ const database = createDatabase(
+ "postgres://openbot:openbot@localhost:5432/openbot",
+ TEST_POOL,
+ );
+
+ expect(database.query.users).toBeDefined();
+});
diff --git a/server/tests/guards.test.ts b/server/tests/guards.test.ts
new file mode 100644
index 00000000..d4130d03
--- /dev/null
+++ b/server/tests/guards.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, test } from "bun:test";
+import { createApp } from "../src/app";
+import { loadConfig } from "../src/config";
+import { testEnvironment } from "./support/environment";
+
+const config = loadConfig({
+ ...testEnvironment(),
+});
+
+const noSessionAuth = {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => null,
+ },
+};
+
+function authenticatedAs(
+ userId: string,
+ email = "[email protected]",
+ name = "OpenBot Member",
+ image = "https://example.test/member.png",
+) {
+ return {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => ({ user: { id: userId, email, name, image } }),
+ },
+ };
+}
+
+describe("server authorization", () => {
+ test("returns 401 when a protected route has no session", async () => {
+ const app = createApp(config, noSessionAuth, {
+ rolesForUser: async () => [],
+ });
+
+ const response = await app.request("http://openbot.local/api/me");
+
+ expect(response.status).toBe(401);
+ await expect(response.json()).resolves.toEqual({
+ error: "Authentication required.",
+ });
+ });
+
+ test("denies a signed-in user from an administrator route", async () => {
+ const app = createApp(config, authenticatedAs("member"), {
+ rolesForUser: async () => ["user"],
+ });
+
+ const response = await app.request("http://openbot.local/api/admin/status");
+
+ expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toEqual({
+ error: "Administrator access required.",
+ });
+ });
+
+ test("returns the authenticated user actor", async () => {
+ const app = createApp(config, authenticatedAs("member"), {
+ rolesForUser: async () => ["user"],
+ });
+
+ const response = await app.request("http://openbot.local/api/me");
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ user: {
+ id: "member",
+ email: "[email protected]",
+ name: "OpenBot Member",
+ image: "https://example.test/member.png",
+ role: "user",
+ },
+ });
+ });
+
+ test("allows an administrator to reach an administrator route", async () => {
+ const app = createApp(config, authenticatedAs("admin"), {
+ rolesForUser: async () => ["admin"],
+ });
+
+ const response = await app.request("http://openbot.local/api/admin/status");
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ status: "ok" });
+ });
+});
diff --git a/server/tests/health.test.ts b/server/tests/health.test.ts
new file mode 100644
index 00000000..e4702100
--- /dev/null
+++ b/server/tests/health.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test } from "bun:test";
+import { createApp } from "../src/app";
+import { loadConfig } from "../src/config";
+import { testEnvironment } from "./support/environment";
+
+const app = createApp(
+ loadConfig({
+ ...testEnvironment(),
+ }),
+);
+
+describe("health endpoint", () => {
+ test("reports the server as healthy", async () => {
+ const response = await app.request("http://openbot.local/health");
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ status: "ok" });
+ });
+});
+
+describe("runtime capabilities", () => {
+ test("reports the Intelligence runtime without exposing configuration secrets", async () => {
+ const response = await app.request("http://openbot.local/api/capabilities");
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ mode: "intelligence",
+ durableHistory: true,
+ });
+ });
+
+ // The runtime object holds the Intelligence API key and licence token. This endpoint has no
+ // authentication, so a projection bug here publishes deployment secrets to anyone who asks.
+ test("never serves the Intelligence credentials", async () => {
+ const response = await app.request("http://openbot.local/api/capabilities");
+ const body = await response.text();
+ const parsed = (await new Response(body).json()) as Record<string, unknown>;
+
+ expect(body).not.toContain("tenant-api-key");
+ expect(body).not.toContain("license-token");
+ // The settings object itself must not be projected, whatever it happens to hold today.
+ expect(Object.keys(parsed)).toEqual(["mode", "durableHistory"]);
+ });
+});
+
+describe("authentication availability", () => {
+ test("fails loudly when Google authentication has not been configured", async () => {
+ const response = await app.request(
+ "http://openbot.local/api/auth/sign-in/social",
+ { method: "POST" },
+ );
+
+ expect(response.status).toBe(503);
+ await expect(response.json()).resolves.toEqual({
+ error: "Google authentication is not configured.",
+ });
+ });
+
+ test("forwards auth requests to the configured Better Auth handler", async () => {
+ const authenticatedApp = createApp(
+ loadConfig({
+ ...testEnvironment(),
+ }),
+ {
+ handler: () => new Response("mounted", { status: 204 }),
+ },
+ );
+
+ const response = await authenticatedApp.request(
+ "http://openbot.local/api/auth/callback/google",
+ );
+
+ expect(response.status).toBe(204);
+ });
+
+ test("forwards logout requests to Better Auth", async () => {
+ const authenticatedApp = createApp(
+ loadConfig({
+ ...testEnvironment(),
+ }),
+ {
+ handler: () => new Response(null, { status: 204 }),
+ api: {
+ getSession: async () => null,
+ },
+ },
+ );
+
+ const response = await authenticatedApp.request(
+ "http://openbot.local/api/auth/sign-out",
+ { method: "POST" },
+ );
+
+ expect(response.status).toBe(204);
+ });
+});
diff --git a/server/tests/jsonb-encoding.integration.test.ts b/server/tests/jsonb-encoding.integration.test.ts
new file mode 100644
index 00000000..1ec02261
--- /dev/null
+++ b/server/tests/jsonb-encoding.integration.test.ts
@@ -0,0 +1,85 @@
+import { afterAll, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { eq, sql } from "drizzle-orm";
+import { createAuditStore, recordAuditEvent } from "../src/audit";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import { agents } from "../src/db/schema";
+
+/**
+ * A jsonb column must hold JSON, not a string that looks like it.
+ *
+ * Drizzle's `jsonb()` serialises the value and Bun's SQL driver serialises it again, so this codebase
+ * uses a custom type for objects that must stay queryable with JSON operators. The audit trail depends
+ * on `payload->>'bot'` and related SQL reads returning fields from an object, not from a JSON string.
+ *
+ * These assertions are deliberately made in SQL, against a real database, on the shape of the stored
+ * value rather than on what comes back through the application.
+ */
+
+const database = createDatabase(
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot",
+ TEST_POOL,
+);
+const suite = randomUUID().slice(0, 8);
+const agentId = `agent_jsonb_${suite}`;
+
+afterAll(async () => {
+ await database.delete(agents).where(eq(agents.id, agentId));
+});
+
+describe("what a jsonb column actually stores", () => {
+ test("an object written through the schema is stored as an object", async () => {
+ await database.insert(agents).values({
+ id: agentId,
+ name: agentId,
+ type: "remote_ag_ui",
+ configuration: {
+ endpoint: "https://example.test/ag-ui",
+ nested: { a: 1 },
+ },
+ });
+
+ const [row] = await database.execute<{ shape: string; endpoint: string }>(
+ sql`select jsonb_typeof(configuration) as shape,
+ configuration->>'endpoint' as endpoint
+ from agents where id = ${agentId}`,
+ );
+
+ expect(row?.shape).toBe("object");
+ // The SQL-queryability property: a key is reachable through JSON operators.
+ expect(row?.endpoint).toBe("https://example.test/ag-ui");
+ });
+
+ test("an audit payload is queryable by its own fields", async () => {
+ const store = createAuditStore(database);
+ const marker = `bot_${suite}`;
+ await recordAuditEvent(store, {
+ eventType: "component.function_called",
+ targetType: "component",
+ targetId: `test_${suite}`,
+ payload: { bot: marker, function: "botActivity" },
+ });
+
+ const [row] = await database.execute<{ shape: string; bot: string }>(
+ sql`select jsonb_typeof(payload) as shape, payload->>'bot' as bot
+ from audit_events where target_id = ${`test_${suite}`}`,
+ );
+
+ expect(row?.shape).toBe("object");
+ expect(row?.bot).toBe(marker);
+ // Left in place: the trail is append-only, so a test cannot tidy up after itself. One row.
+ });
+
+ test("the whole trail is objects, not strings", async () => {
+ // A deployment that has run the migration has no string-shaped payloads left. Written as a sweep
+ // rather than a single row because the failure this guards against is partial by nature: a new
+ // column added with drizzle's `jsonb` would pass every test above and fail only here.
+ const [row] = await database.execute<{ strings: number }>(
+ sql`select count(*)::int as strings from audit_events
+ where jsonb_typeof(payload) <> 'object'`,
+ );
+ expect(row?.strings).toBe(0);
+ });
+});
diff --git a/server/tests/knowledge-agent.test.ts b/server/tests/knowledge-agent.test.ts
new file mode 100644
index 00000000..53d188a4
--- /dev/null
+++ b/server/tests/knowledge-agent.test.ts
@@ -0,0 +1,37 @@
+import { expect, test } from "bun:test";
+import { createKnowledgeAgent } from "../src/agents/knowledge-agent";
+
+test("returns authorized knowledge citations to the model port", async () => {
+ const agent = createKnowledgeAgent({
+ available: true,
+ search: async () => [
+ {
+ title: "Policy",
+ canonicalUrl: "https://example.test/policy",
+ content: "Use MFA.",
+ },
+ ],
+ complete: async ({ context }) => `Answer: ${context[0]?.content}`,
+ });
+ await expect(agent.respond("What is required?")).resolves.toEqual({
+ text: "Answer: Use MFA.",
+ citations: [
+ {
+ title: "Policy",
+ canonicalUrl: "https://example.test/policy",
+ content: "Use MFA.",
+ },
+ ],
+ });
+});
+
+test("refuses to run when its model credential is unavailable", async () => {
+ const agent = createKnowledgeAgent({
+ available: false,
+ search: async () => [],
+ complete: async () => "unused",
+ });
+ await expect(agent.respond("question")).rejects.toThrow(
+ "Model credential is not configured.",
+ );
+});
diff --git a/server/tests/knowledge-repository.test.ts b/server/tests/knowledge-repository.test.ts
new file mode 100644
index 00000000..d3863a1c
--- /dev/null
+++ b/server/tests/knowledge-repository.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from "bun:test";
+import { InMemoryKnowledgeRepository } from "../src/knowledge/repository";
+
+const change = {
+ connectorInstanceId: "connector-1",
+ sourceId: "source-1",
+ title: "Finance policy",
+ canonicalUrl: "https://example.test/policy",
+ contentHash: "hash-1",
+ chunks: [{ position: 0, content: "finance content" }],
+ acls: [{ principal: "group:finance", effect: "allow" as const }],
+};
+
+describe("knowledge repository", () => {
+ test("replaces source content idempotently", () => {
+ const repository = new InMemoryKnowledgeRepository();
+ repository.apply(change);
+ repository.apply({
+ ...change,
+ contentHash: "hash-2",
+ chunks: [{ position: 0, content: "updated" }],
+ });
+
+ expect(repository.documents()).toEqual([
+ {
+ ...change,
+ contentHash: "hash-2",
+ chunks: [{ position: 0, content: "updated" }],
+ },
+ ]);
+ });
+
+ test("returns citations only to authorized actors and hides deleted sources", () => {
+ const repository = new InMemoryKnowledgeRepository();
+ repository.apply(change);
+ expect(repository.search({ userId: "u1", groups: ["finance"] })).toEqual([
+ {
+ documentId: "connector-1:source-1",
+ title: "Finance policy",
+ canonicalUrl: "https://example.test/policy",
+ chunkId: "connector-1:source-1:0",
+ content: "finance content",
+ },
+ ]);
+ expect(repository.search({ userId: "u2", groups: [] })).toEqual([]);
+ repository.delete("connector-1", "source-1");
+ expect(repository.search({ userId: "u1", groups: ["finance"] })).toEqual(
+ [],
+ );
+ });
+});
diff --git a/server/tests/plugin-catalogue.test.ts b/server/tests/plugin-catalogue.test.ts
new file mode 100644
index 00000000..7efca89e
--- /dev/null
+++ b/server/tests/plugin-catalogue.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, test } from "bun:test";
+import {
+ CATALOGUE,
+ catalogueEntry,
+ classifyTool,
+ customUrlRefusal,
+ hostAdmissible,
+ resolveServerUrl,
+} from "../src/plugins/catalogue";
+
+/**
+ * The catalogue decides two things that are worth being sure about: which addresses this deployment
+ * will talk to at all, and which of a server's tools change something.
+ *
+ * Both fail closed, and both are tested for that rather than for the happy path. An admissibility
+ * check that accepts one address too many is a request-forgery primitive; an effect classifier that
+ * calls a write a read is a governance surface that quietly stops covering the thing it exists for.
+ */
+
+describe("which servers this deployment will talk to", () => {
+ test("a pinned host matches only itself", () => {
+ const atlassian = catalogueEntry("atlassian");
+ expect(atlassian).not.toBeNull();
+ expect(hostAdmissible(atlassian!, "https://mcp.atlassian.com")).toBe(true);
+ // A prefix, a suffix and a lookalike are each refused. The suffix case is the one that matters:
+ // a check written with endsWith rather than equality would accept it.
+ expect(
+ hostAdmissible(atlassian!, "https://mcp.atlassian.com.evil.test"),
+ ).toBe(false);
+ expect(
+ hostAdmissible(atlassian!, "https://evil.test/mcp.atlassian.com"),
+ ).toBe(false);
+ expect(hostAdmissible(atlassian!, "http://mcp.atlassian.com")).toBe(false);
+ });
+
+ test("a per-instance vendor accepts its own instances and nothing else", () => {
+ const servicenow = catalogueEntry("servicenow");
+ expect(servicenow).not.toBeNull();
+ expect(hostAdmissible(servicenow!, "https://acme.service-now.com")).toBe(
+ true,
+ );
+ expect(
+ hostAdmissible(servicenow!, "https://acme-dev1.service-now.com"),
+ ).toBe(true);
+ // Anchored at both ends, so neither a prefix nor a suffix gets in.
+ expect(
+ hostAdmissible(servicenow!, "https://acme.service-now.com.evil.test"),
+ ).toBe(false);
+ expect(
+ hostAdmissible(servicenow!, "https://evil.test#acme.service-now.com"),
+ ).toBe(false);
+ // A subdomain of an instance is not an instance.
+ expect(hostAdmissible(servicenow!, "https://a.b.service-now.com")).toBe(
+ false,
+ );
+ });
+
+ test("a server not in the catalogue resolves to nothing", () => {
+ expect(resolveServerUrl("not-a-vendor")).toBeNull();
+ expect(catalogueEntry("not-a-vendor")).toBeNull();
+ });
+
+ test("the path is the catalogue's, never the caller's", () => {
+ // A per-instance vendor is the only case where a caller supplies any part of the address, and
+ // even then the path is fixed, so an admissible host cannot reach another endpoint.
+ const resolved = resolveServerUrl(
+ "servicenow",
+ "https://acme.service-now.com",
+ );
+ expect(resolved?.url).toBe(
+ "https://acme.service-now.com/sncapps/mcp-server",
+ );
+ });
+
+ test("a per-instance vendor with no instance supplied resolves to nothing", () => {
+ expect(resolveServerUrl("servicenow")).toBeNull();
+ });
+
+ test("every catalogue entry pins a host or an anchored pattern", () => {
+ for (const entry of CATALOGUE) {
+ if (entry.host === null) {
+ expect(entry.hostPattern).toBeDefined();
+ // Anchored at both ends or the pattern is decoration.
+ expect(entry.hostPattern?.startsWith("^")).toBe(true);
+ expect(entry.hostPattern?.endsWith("$")).toBe(true);
+ } else {
+ expect(entry.host.startsWith("https://")).toBe(true);
+ }
+ }
+ });
+});
+
+describe("what a tool does", () => {
+ const atlassian = catalogueEntry("atlassian")!;
+
+ test("a named write is a write", () => {
+ expect(classifyTool(atlassian, "createJiraIssue", true)).toBe("write");
+ });
+
+ test("an advertised tool that is not a named write is a read", () => {
+ expect(classifyTool(atlassian, "searchJiraIssues", true)).toBe("read");
+ });
+
+ test("a tool the server never advertised is a write", () => {
+ // The only thing that produced this name was a model, so nothing has vouched for it.
+ expect(classifyTool(atlassian, "searchJiraIssues", false)).toBe("write");
+ });
+
+ test("every tool on a server nobody reviewed is a write", () => {
+ expect(classifyTool(null, "anything_at_all", true)).toBe("write");
+ });
+
+ test("a tool that edits rather than creates is still a write", () => {
+ // The naming does not carry it: "update" and "create" both change somebody else's system, and a
+ // list built by reading verbs off tool names lets the edits through.
+ const slack = catalogueEntry("slack")!;
+ expect(classifyTool(slack, "slack_update_canvas", true)).toBe("write");
+ expect(classifyTool(slack, "slack_create_canvas", true)).toBe("write");
+ expect(classifyTool(slack, "slack_read_canvas", true)).toBe("read");
+ });
+});
+
+describe("a URL an administrator typed", () => {
+ test("an ordinary vendor URL is accepted", () => {
+ expect(customUrlRefusal("https://mcp.example.com/mcp")).toBeNull();
+ });
+
+ test("plaintext is refused", () => {
+ expect(customUrlRefusal("http://mcp.example.com")).toContain("https");
+ });
+
+ test("an address literal is refused", () => {
+ // The cloud metadata endpoint, which is the reason this check exists.
+ expect(
+ customUrlRefusal("https://169.254.169.254/latest/meta-data/"),
+ ).toContain("hostname");
+ expect(customUrlRefusal("https://127.0.0.1/mcp")).toContain("hostname");
+ expect(customUrlRefusal("https://[::1]/mcp")).toContain("hostname");
+ });
+
+ test("names that only resolve inside the network are refused", () => {
+ expect(customUrlRefusal("https://localhost/mcp")).not.toBeNull();
+ expect(customUrlRefusal("https://database/mcp")).not.toBeNull();
+ expect(customUrlRefusal("https://vault.internal/mcp")).not.toBeNull();
+ expect(customUrlRefusal("https://printer.local/mcp")).not.toBeNull();
+ });
+
+ test("nonsense is refused rather than thrown", () => {
+ expect(customUrlRefusal("not a url")).toBe("That is not a URL.");
+ });
+});
diff --git a/server/tests/plugin-store.integration.test.ts b/server/tests/plugin-store.integration.test.ts
new file mode 100644
index 00000000..3349ab8e
--- /dev/null
+++ b/server/tests/plugin-store.integration.test.ts
@@ -0,0 +1,306 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { and, eq, sql } from "drizzle-orm";
+import { createAuditStore } from "../src/audit";
+import type { ActionPolicy } from "../src/computer/policy";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import {
+ agents,
+ auditEvents,
+ mcpServers,
+ mcpTools,
+ pluginGrants,
+} from "../src/db/schema";
+import { createPluginStore, PluginRefusedError } from "../src/plugins/store";
+
+/**
+ * The two questions a tool call has to pass, and the row each answer leaves behind.
+ *
+ * The refusals are the property under test. A call that succeeds proves the plumbing works; a call
+ * that is refused proves the governance does. Both refusals here stop before any network call, which
+ * is itself the property being asserted: a tool a Bot was never given must not reach the vault or
+ * the vendor, so there is nothing to stub.
+ */
+
+const database = createDatabase(
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot",
+ TEST_POOL,
+);
+
+const suite = randomUUID().slice(0, 8);
+const holderId = `agent_plugin_holder_${suite}`;
+const strangerId = `agent_plugin_stranger_${suite}`;
+const serverId = `atlassian`;
+const toolName = "searchJiraIssues";
+const ref = `${serverId}/${toolName}`;
+
+let policy: ActionPolicy = { mode: "enforce", deny: [], allow: ["true"] };
+
+/**
+ * Whether this deployment already had the server before the test ran.
+ *
+ * The id is a real catalogue key rather than a suite-scoped one, because what is under test includes
+ * the vendor's own read/write classification. On a database somebody is using, that key is their
+ * configured server, so it is removed only when the test is what created it.
+ */
+let serverWasAlreadyConfigured = false;
+
+const store = createPluginStore({
+ database,
+ auditStore: createAuditStore(database),
+ credentials: {
+ // No credential is ever read in these tests, because every call is refused before the vault.
+ readSecret: async () => null,
+ },
+ encryptionKey: "x".repeat(44),
+ policy: () => policy,
+});
+
+async function auditRowsFor(targetId: string) {
+ return database
+ .select({
+ eventType: auditEvents.eventType,
+ payload: auditEvents.payload,
+ })
+ .from(auditEvents)
+ .where(
+ and(
+ eq(auditEvents.targetType, "mcp_tool"),
+ eq(auditEvents.targetId, targetId),
+ ),
+ );
+}
+
+beforeAll(async () => {
+ for (const id of [holderId, strangerId]) {
+ await database
+ .insert(agents)
+ .values({
+ id,
+ name: id,
+ type: "remote_ag_ui",
+ configuration: {},
+ })
+ .onConflictDoNothing();
+ }
+
+ serverWasAlreadyConfigured =
+ (
+ await database
+ .select({ id: mcpServers.id })
+ .from(mcpServers)
+ .where(eq(mcpServers.id, serverId))
+ ).length > 0;
+
+ // The server row is written directly rather than through addServer, so the test needs no vendor
+ // to be reachable. What is under test is the decision, not the listing.
+ await database
+ .insert(mcpServers)
+ .values({
+ id: serverId,
+ title: "Atlassian",
+ vendor: "Atlassian",
+ url: "https://mcp.atlassian.com/v1/mcp/authv2",
+ provenance: "first-party",
+ })
+ .onConflictDoNothing();
+ await database
+ .insert(mcpTools)
+ .values({ serverId, name: toolName, description: "Search issues." })
+ .onConflictDoNothing();
+});
+
+afterAll(async () => {
+ await database.delete(pluginGrants).where(eq(pluginGrants.ref, ref));
+ // A server row is deployment configuration, so it belongs to the deployment rather than here.
+ if (!serverWasAlreadyConfigured) {
+ await database.delete(mcpTools).where(eq(mcpTools.serverId, serverId));
+ await database.delete(mcpServers).where(eq(mcpServers.id, serverId));
+ }
+ await database.delete(agents).where(eq(agents.id, holderId));
+ await database.delete(agents).where(eq(agents.id, strangerId));
+});
+
+describe("a grant is the permission", () => {
+ test("a Bot that was never granted a tool is refused, and the refusal is recorded", async () => {
+ await expect(
+ store.callTool({
+ ref,
+ args: {},
+ botId: strangerId,
+ actorId: "[email protected]",
+ }),
+ ).rejects.toBeInstanceOf(PluginRefusedError);
+
+ const rows = await auditRowsFor(ref);
+ const rejected = rows.filter(
+ (row) =>
+ row.eventType === "mcp.call_rejected" &&
+ (row.payload as { bot?: string }).bot === strangerId,
+ );
+ expect(rejected.length).toBeGreaterThan(0);
+ expect((rejected[0].payload as { refusal?: string }).refusal).toBe(
+ "not_granted",
+ );
+ });
+
+ test("granting lets the same Bot past the grant check", async () => {
+ await store.grant("mcp", ref, holderId, "[email protected]");
+ const decision = await store.decide("mcp", ref, holderId);
+ expect(decision.allowed).toBe(true);
+ });
+
+ test("revoking takes it away again", async () => {
+ await store.grant("mcp", ref, holderId, "[email protected]");
+ await store.revoke("mcp", ref, holderId, "[email protected]");
+ const decision = await store.decide("mcp", ref, holderId);
+ expect(decision.allowed).toBe(false);
+ });
+
+ test("a Bot is offered exactly what it holds", async () => {
+ await store.grant("mcp", ref, holderId, "[email protected]");
+ const held = await store.listForAgent(holderId);
+ expect(held.tools.map((tool) => tool.ref)).toEqual([ref]);
+ // The name the model is offered, which may not contain a slash.
+ expect(held.tools[0].toolName).toBe("mcp__atlassian__searchJiraIssues");
+
+ const nothing = await store.listForAgent(strangerId);
+ expect(nothing.tools).toEqual([]);
+ expect(nothing.skills).toEqual([]);
+ });
+});
+
+describe("the policy is asked as well as the grant", () => {
+ test("a granted tool is still refused by a deny rule, and the rule is named", async () => {
+ await store.grant("mcp", ref, holderId, "[email protected]");
+ policy = {
+ mode: "enforce",
+ deny: ['mcp.server == "atlassian"'],
+ allow: ["true"],
+ };
+
+ let thrown: unknown;
+ try {
+ await store.callTool({
+ ref,
+ args: {},
+ botId: holderId,
+ actorId: "[email protected]",
+ });
+ } catch (error) {
+ thrown = error;
+ } finally {
+ policy = { mode: "enforce", deny: [], allow: ["true"] };
+ }
+
+ expect(thrown).toBeInstanceOf(PluginRefusedError);
+ // The rule that decided it, so an operator reading the refusal knows what to edit.
+ expect((thrown as PluginRefusedError).rule).toBe(
+ 'mcp.server == "atlassian"',
+ );
+
+ const rows = await auditRowsFor(ref);
+ const refusedByPolicy = rows.filter(
+ (row) =>
+ row.eventType === "mcp.call_rejected" &&
+ (row.payload as { decision?: { rule?: string } }).decision?.rule ===
+ 'mcp.server == "atlassian"',
+ );
+ expect(refusedByPolicy.length).toBeGreaterThan(0);
+ });
+
+ test("a rule can speak about effect rather than about tool names", async () => {
+ await store.grant("mcp", ref, holderId, "[email protected]");
+ // `searchJiraIssues` is advertised and is not in the vendor's write list, so it is a read and
+ // this deny rule must NOT catch it. The assertion is that the call gets past the policy, which
+ // it proves by failing at the network instead of as a refusal.
+ policy = {
+ mode: "enforce",
+ deny: ['intent == "write_tool"'],
+ allow: ["true"],
+ };
+
+ let thrown: unknown;
+ try {
+ await store.callTool({
+ ref,
+ args: {},
+ botId: holderId,
+ actorId: "[email protected]",
+ });
+ } catch (error) {
+ thrown = error;
+ } finally {
+ policy = { mode: "enforce", deny: [], allow: ["true"] };
+ }
+
+ expect(thrown).not.toBeInstanceOf(PluginRefusedError);
+ });
+});
+
+describe("a boundary written about the browser does not refuse tool calls", () => {
+ test("an unguarded rule about a page element does not refuse a tool call", async () => {
+ await store.grant("mcp", ref, holderId, "[email protected]");
+ /**
+ * This engine treats an expression it cannot evaluate as a MATCH, which is right for a browser
+ * action on an element the server could not resolve and catastrophic for a tool call: with
+ * `element` absent from the context, ANY deny rule naming it is unevaluable, so it matches, so
+ * every MCP call is refused for a reason about a submit button.
+ *
+ * The preset in `.env.example` happens to survive that, because it guards each clause with
+ * `tool.name == "computer_click"` and CEL short-circuits before ever reaching `element`. That is
+ * luck, not design, and a rule an operator writes by hand has no such guard. So the rule under
+ * test is the unguarded one.
+ */
+ policy = {
+ mode: "enforce",
+ deny: ['contains(element.name, "submit")'],
+ allow: ["true"],
+ };
+
+ let thrown: unknown;
+ try {
+ await store.callTool({
+ ref,
+ args: {},
+ botId: holderId,
+ actorId: "[email protected]",
+ });
+ } catch (error) {
+ thrown = error;
+ } finally {
+ policy = { mode: "enforce", deny: [], allow: ["true"] };
+ }
+
+ // Not a refusal. It gets as far as the network, which is where this test stops caring.
+ expect(thrown).not.toBeInstanceOf(PluginRefusedError);
+ });
+});
+
+describe("the trail can be read by a second reader", () => {
+ test("a refusal names the bot, the server and the tool in queryable JSON", async () => {
+ const [row] = await database
+ .select({
+ bot: sql<string>`payload ->> 'bot'`,
+ server: sql<string>`payload ->> 'server'`,
+ tool: sql<string>`payload ->> 'tool'`,
+ })
+ .from(auditEvents)
+ .where(
+ and(
+ eq(auditEvents.targetType, "mcp_tool"),
+ eq(auditEvents.eventType, "mcp.call_rejected"),
+ eq(auditEvents.targetId, ref),
+ ),
+ )
+ .limit(1);
+
+ // Asserted in SQL rather than through the application, because the stored payload shape is the
+ // property under test.
+ expect(row?.server).toBe(serverId);
+ expect(row?.tool).toBe(toolName);
+ expect(row?.bot).toBeTruthy();
+ });
+});
diff --git a/server/tests/runtime-agents.integration.test.ts b/server/tests/runtime-agents.integration.test.ts
new file mode 100644
index 00000000..bff85340
--- /dev/null
+++ b/server/tests/runtime-agents.integration.test.ts
@@ -0,0 +1,186 @@
+import { afterAll, afterEach, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { createAgentProfileStore } from "../src/agents/profile-store";
+import type { AgentActor } from "../src/agents/profile-types";
+import { createRuntimeAgentLoader } from "../src/agents/runtime-agents";
+import { createChannelStore } from "../src/channels/routes";
+import { createThreadIdentity } from "../src/channels/thread-identity";
+import { standingRoleMessage } from "../src/copilot";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import {
+ agentProfiles,
+ agents,
+ channels,
+ intelligenceChannelMappings,
+ users,
+} from "../src/db/schema";
+
+const databaseUrl =
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot";
+const database = createDatabase(databaseUrl, TEST_POOL);
+const managedEndpoint = new URL("https://managed.example.test/ag-ui");
+const profileStore = createAgentProfileStore(database, managedEndpoint);
+const channelStore = createChannelStore(
+ database,
+ profileStore,
+ createThreadIdentity("test-deployment"),
+);
+const loadAgents = createRuntimeAgentLoader(database);
+
+const testPrefix = `runtime-agents-${randomUUID()}`;
+const createdUserIds: string[] = [];
+const createdAgentIds: string[] = [];
+const createdChannelIds: string[] = [];
+
+afterEach(async () => {
+ for (const channelId of createdChannelIds.splice(0)) {
+ await database
+ .delete(intelligenceChannelMappings)
+ .where(eq(intelligenceChannelMappings.channelId, channelId));
+ await database.delete(channels).where(eq(channels.id, channelId));
+ }
+ for (const agentId of createdAgentIds.splice(0)) {
+ await database
+ .delete(agentProfiles)
+ .where(eq(agentProfiles.agentId, agentId));
+ await database.delete(agents).where(eq(agents.id, agentId));
+ }
+ for (const userId of createdUserIds.splice(0)) {
+ await database.delete(users).where(eq(users.id, userId));
+ }
+});
+
+afterAll(async () => {
+ await database.$client.close();
+});
+
+async function createUser(role: AgentActor["role"] = "user") {
+ const id = `${testPrefix}-user-${randomUUID()}`;
+ await database.insert(users).values({
+ id,
+ email: `${id}@example.test`,
+ name: "Runtime Agents Test User",
+ });
+ createdUserIds.push(id);
+ return { id, role } satisfies AgentActor;
+}
+
+async function createTeammate(
+ owner: AgentActor,
+ overrides: { name?: string; visibility?: "public" | "private" } = {},
+) {
+ const profile = await profileStore.create(owner, {
+ name: overrides.name ?? "Expense Manager",
+ title: "Finance Operations",
+ roleDescription:
+ "Review receipts, categorize expenses, and prepare reimbursement reports.",
+ visibility: overrides.visibility ?? "private",
+ });
+ createdAgentIds.push(profile.id);
+ return profile;
+}
+
+function idsOf(loaded: Awaited<ReturnType<typeof loadAgents>>) {
+ return loaded.map((agent) => agent.id);
+}
+
+/**
+ * Which teammates exist is a per-person question, answered on every request. These assertions are
+ * against the database rather than a fake, because the whole point of resolving here is that the
+ * filtering happens in the query and not in JavaScript after every row has already been read.
+ */
+describe("runtime agent loading", () => {
+ test("carries the owner's teammate with its standing role and managed endpoint", async () => {
+ const owner = await createUser();
+ const profile = await createTeammate(owner);
+
+ const loaded = await loadAgents(owner);
+
+ expect(loaded).toContainEqual({
+ id: profile.id,
+ name: "Expense Manager",
+ type: "remote_ag_ui",
+ endpoint: managedEndpoint.toString(),
+ standingMessage: standingRoleMessage({
+ id: profile.id,
+ name: "Expense Manager",
+ title: "Finance Operations",
+ roleDescription:
+ "Review receipts, categorize expenses, and prepare reimbursement reports.",
+ }),
+ });
+ });
+
+ test("hides a private teammate from everybody but its owner and administrators", async () => {
+ const owner = await createUser();
+ const otherUser = await createUser();
+ const administrator = await createUser("admin");
+ const profile = await createTeammate(owner);
+
+ expect(idsOf(await loadAgents(owner))).toContain(profile.id);
+ expect(idsOf(await loadAgents(otherUser))).not.toContain(profile.id);
+ expect(idsOf(await loadAgents(administrator))).toContain(profile.id);
+ });
+
+ test("shares a public teammate with everybody", async () => {
+ const owner = await createUser();
+ const otherUser = await createUser();
+ const profile = await createTeammate(owner, {
+ name: "Company Helper",
+ visibility: "public",
+ });
+
+ expect(idsOf(await loadAgents(otherUser))).toContain(profile.id);
+ });
+
+ test("drops a deleted teammate that has no history to restore", async () => {
+ const owner = await createUser();
+ const profile = await createTeammate(owner);
+
+ await profileStore.softDelete(owner, profile.id);
+
+ expect(idsOf(await loadAgents(owner))).not.toContain(profile.id);
+ });
+
+ test("keeps a deleted teammate as a tombstone for a channel member", async () => {
+ const owner = await createUser();
+ const otherUser = await createUser();
+ const profile = await createTeammate(owner);
+ const channel = await channelStore.create(owner, [profile.id]);
+ createdChannelIds.push(channel.id);
+
+ await profileStore.softDelete(owner, profile.id);
+
+ expect(await loadAgents(owner)).toContainEqual({
+ id: profile.id,
+ name: "Expense Manager",
+ type: "unavailable",
+ reason:
+ "Expense Manager has been deleted and can no longer run. Its conversations remain readable.",
+ });
+ // Somebody with no channel of their own gets no tombstone: history is what authorizes it.
+ expect(idsOf(await loadAgents(otherUser))).not.toContain(profile.id);
+ });
+
+ test("applies an edited role to the next load without a restart", async () => {
+ const owner = await createUser();
+ const profile = await createTeammate(owner);
+
+ await profileStore.update(owner, profile.id, {
+ name: "Expense Manager",
+ title: "Finance Operations",
+ roleDescription: "Reconcile corporate card statements.",
+ visibility: "private",
+ });
+
+ const reloaded = (await loadAgents(owner)).find(
+ (agent) => agent.id === profile.id,
+ );
+ expect(
+ reloaded?.type === "remote_ag_ui" && reloaded.standingMessage.content,
+ ).toContain("Reconcile corporate card statements.");
+ });
+});
diff --git a/server/tests/schema.test.ts b/server/tests/schema.test.ts
new file mode 100644
index 00000000..b95cd00b
--- /dev/null
+++ b/server/tests/schema.test.ts
@@ -0,0 +1,310 @@
+import { describe, expect, test } from "bun:test";
+import { readFile } from "node:fs/promises";
+import { getTableName } from "drizzle-orm";
+import { getTableConfig } from "drizzle-orm/pg-core";
+import {
+ accounts,
+ agentPreferences,
+ agentProfiles,
+ agents,
+ agentVisibility,
+ auditEvents,
+ channelAgents,
+ channelMemberships,
+ channels,
+ chunks,
+ connectorCursors,
+ connectorInstances,
+ credentials,
+ documentAcls,
+ documents,
+ intelligenceChannelMappings,
+ sessions,
+ syncRuns,
+ userRoles,
+ users,
+ verifications,
+} from "../src/db/schema";
+
+describe("OpenBot database schema", () => {
+ test("defines the core runtime records", () => {
+ expect(
+ [
+ users,
+ sessions,
+ accounts,
+ verifications,
+ userRoles,
+ agents,
+ channels,
+ channelMemberships,
+ channelAgents,
+ credentials,
+ connectorInstances,
+ connectorCursors,
+ syncRuns,
+ documents,
+ chunks,
+ documentAcls,
+ auditEvents,
+ intelligenceChannelMappings,
+ ].map(getTableName),
+ ).toEqual([
+ "users",
+ "sessions",
+ "accounts",
+ "verifications",
+ "user_roles",
+ "agents",
+ "channels",
+ "channel_memberships",
+ "channel_agents",
+ "credentials",
+ "connector_instances",
+ "connector_cursors",
+ "sync_runs",
+ "documents",
+ "chunks",
+ "document_acls",
+ "audit_events",
+ "intelligence_channel_mappings",
+ ]);
+ });
+
+ test("keeps document embeddings and ACLs separate from document metadata", () => {
+ expect(Object.keys(documents)).toEqual(
+ expect.arrayContaining([
+ "id",
+ "connectorInstanceId",
+ "sourceId",
+ "canonicalUrl",
+ ]),
+ );
+ expect(Object.keys(chunks)).toEqual(
+ expect.arrayContaining(["documentId", "embedding"]),
+ );
+ expect(Object.keys(documentAcls)).toEqual(
+ expect.arrayContaining(["documentId", "principal", "effect"]),
+ );
+ });
+
+ test("includes Better Auth's verified Google identity records", () => {
+ expect(Object.keys(users)).toContain("emailVerified");
+ expect(Object.keys(sessions)).toEqual(
+ expect.arrayContaining(["ipAddress", "userAgent"]),
+ );
+ expect(Object.keys(accounts)).toEqual(
+ expect.arrayContaining(["userId", "providerId", "accountId"]),
+ );
+ });
+
+ test("defines the exact agent profile and roster preference contracts", () => {
+ expect([agentProfiles, agentPreferences].map(getTableName)).toEqual([
+ "agent_profiles",
+ "agent_preferences",
+ ]);
+ expect(agentVisibility.enumName).toBe("agent_visibility");
+ expect(agentVisibility.enumValues).toEqual(["public", "private"]);
+
+ const profileConfig = getTableConfig(agentProfiles);
+ const preferenceConfig = getTableConfig(agentPreferences);
+
+ expect(
+ profileConfig.columns.map((column) => ({
+ name: column.name,
+ notNull: column.notNull,
+ hasDefault: column.hasDefault,
+ primary: column.primary,
+ })),
+ ).toEqual([
+ { name: "agent_id", notNull: true, hasDefault: false, primary: true },
+ {
+ name: "owner_user_id",
+ notNull: false,
+ hasDefault: false,
+ primary: false,
+ },
+ { name: "title", notNull: true, hasDefault: false, primary: false },
+ {
+ name: "role_description",
+ notNull: true,
+ hasDefault: false,
+ primary: false,
+ },
+ {
+ name: "avatar_seed",
+ notNull: true,
+ hasDefault: false,
+ primary: false,
+ },
+ {
+ name: "visibility",
+ notNull: true,
+ hasDefault: false,
+ primary: false,
+ },
+ {
+ name: "deleted_at",
+ notNull: false,
+ hasDefault: false,
+ primary: false,
+ },
+ {
+ name: "created_at",
+ notNull: true,
+ hasDefault: true,
+ primary: false,
+ },
+ {
+ name: "updated_at",
+ notNull: true,
+ hasDefault: true,
+ primary: false,
+ },
+ ]);
+
+ expect(
+ preferenceConfig.columns.map((column) => ({
+ name: column.name,
+ sqlType: column.getSQLType(),
+ notNull: column.notNull,
+ hasDefault: column.hasDefault,
+ primary: column.primary,
+ })),
+ ).toEqual([
+ {
+ name: "user_id",
+ sqlType: "text",
+ notNull: true,
+ hasDefault: false,
+ primary: false,
+ },
+ {
+ name: "agent_id",
+ sqlType: "text",
+ notNull: true,
+ hasDefault: false,
+ primary: false,
+ },
+ {
+ name: "hidden_at",
+ sqlType: "timestamp with time zone",
+ notNull: false,
+ hasDefault: false,
+ primary: false,
+ },
+ ]);
+
+ expect(
+ [...profileConfig.foreignKeys, ...preferenceConfig.foreignKeys].map(
+ (foreignKey) => {
+ const reference = foreignKey.reference();
+ return {
+ sourceColumns: reference.columns.map((column) => column.name),
+ targetTable: getTableName(reference.foreignTable),
+ targetColumns: reference.foreignColumns.map(
+ (column) => column.name,
+ ),
+ onDelete: foreignKey.onDelete,
+ onUpdate: foreignKey.onUpdate,
+ };
+ },
+ ),
+ ).toEqual([
+ {
+ sourceColumns: ["agent_id"],
+ targetTable: "agents",
+ targetColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ },
+ {
+ sourceColumns: ["owner_user_id"],
+ targetTable: "users",
+ targetColumns: ["id"],
+ onDelete: "set null",
+ onUpdate: "no action",
+ },
+ {
+ sourceColumns: ["user_id"],
+ targetTable: "users",
+ targetColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ },
+ {
+ sourceColumns: ["agent_id"],
+ targetTable: "agents",
+ targetColumns: ["id"],
+ onDelete: "cascade",
+ onUpdate: "no action",
+ },
+ ]);
+
+ expect(
+ preferenceConfig.primaryKeys.map((primaryKey) => ({
+ name: primaryKey.getName(),
+ columns: primaryKey.columns.map((column) => column.name),
+ })),
+ ).toEqual([
+ {
+ name: "agent_preferences_user_id_agent_id_pk",
+ columns: ["user_id", "agent_id"],
+ },
+ ]);
+
+ expect(
+ profileConfig.indexes.map((index) => ({
+ name: index.config.name,
+ columns: index.config.columns.map((column) =>
+ "name" in column ? column.name : undefined,
+ ),
+ unique: index.config.unique,
+ method: index.config.method,
+ })),
+ ).toEqual([
+ {
+ name: "agent_profiles_visibility_deleted_idx",
+ columns: ["visibility", "deleted_at"],
+ unique: false,
+ method: "btree",
+ },
+ ]);
+ });
+
+ test("keeps the agent profile migration aligned with the schema", async () => {
+ const migration = await readFile(
+ new URL("../drizzle/0000_schema.sql", import.meta.url),
+ "utf8",
+ );
+ const normalizedMigration = migration.replace(/\s+/g, " ").trim();
+
+ expect(normalizedMigration).toContain(
+ `CREATE TYPE "public"."agent_visibility" AS ENUM('public', 'private')`,
+ );
+ expect(normalizedMigration).toContain(
+ `"agent_id" text PRIMARY KEY NOT NULL, "owner_user_id" text, "title" text NOT NULL, "role_description" text NOT NULL, "avatar_seed" text NOT NULL, "visibility" "agent_visibility" NOT NULL, "deleted_at" timestamp with time zone, "created_at" timestamp with time zone DEFAULT now() NOT NULL, "updated_at" timestamp with time zone DEFAULT now() NOT NULL`,
+ );
+ expect(normalizedMigration).toContain(
+ `CREATE TABLE "agent_preferences" ( "user_id" text NOT NULL, "agent_id" text NOT NULL, "hidden_at" timestamp with time zone,`,
+ );
+ expect(normalizedMigration).toContain(
+ `CONSTRAINT "agent_preferences_user_id_agent_id_pk" PRIMARY KEY("user_id","agent_id")`,
+ );
+ expect(normalizedMigration).toContain(
+ `ALTER TABLE "agent_profiles" ADD CONSTRAINT "agent_profiles_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action`,
+ );
+ expect(normalizedMigration).toContain(
+ `ALTER TABLE "agent_profiles" ADD CONSTRAINT "agent_profiles_owner_user_id_users_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action`,
+ );
+ expect(normalizedMigration).toContain(
+ `ALTER TABLE "agent_preferences" ADD CONSTRAINT "agent_preferences_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action`,
+ );
+ expect(normalizedMigration).toContain(
+ `ALTER TABLE "agent_preferences" ADD CONSTRAINT "agent_preferences_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action`,
+ );
+ expect(normalizedMigration).toContain(
+ `CREATE INDEX "agent_profiles_visibility_deleted_idx" ON "agent_profiles" USING btree ("visibility","deleted_at")`,
+ );
+ });
+});
diff --git a/server/tests/tenant-package.test.ts b/server/tests/tenant-package.test.ts
new file mode 100644
index 00000000..98a257d2
--- /dev/null
+++ b/server/tests/tenant-package.test.ts
@@ -0,0 +1,618 @@
+import { afterAll, afterEach, describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { createDatabase } from "../src/db/client";
+import { TEST_POOL } from "./support/database";
+import {
+ agentProfiles,
+ agents,
+ deploymentPackages,
+ users,
+} from "../src/db/schema";
+import {
+ createApplicationConfiguration,
+ expandEnvironment,
+ type LoadedTenantPackage,
+ loadTenantPackage,
+ synchronizeTenantPackage,
+ validateTenantPackage,
+ validateThemeCss,
+} from "../src/tenant-package";
+
+const database = createDatabase(
+ process.env.DATABASE_URL ??
+ "postgres://openbot:openbot@localhost:5432/openbot",
+ TEST_POOL,
+);
+const createdAgentIds: string[] = [];
+const createdPackageIds: string[] = [];
+const createdTenantIds: string[] = [];
+const createdUserIds: string[] = [];
+
+afterEach(async () => {
+ for (const agentId of createdAgentIds.splice(0)) {
+ await database.delete(agents).where(eq(agents.id, agentId));
+ }
+ for (const packageId of createdPackageIds.splice(0)) {
+ await database
+ .delete(deploymentPackages)
+ .where(eq(deploymentPackages.id, packageId));
+ }
+ for (const tenantId of createdTenantIds.splice(0)) {
+ await database
+ .delete(deploymentPackages)
+ .where(eq(deploymentPackages.tenantId, tenantId));
+ }
+ for (const userId of createdUserIds.splice(0)) {
+ await database.delete(users).where(eq(users.id, userId));
+ }
+});
+
+afterAll(async () => {
+ await database.$client.close();
+});
+
+function packageAgent(
+ overrides: Partial<LoadedTenantPackage["agents"][number]> = {},
+): LoadedTenantPackage["agents"][number] {
+ return {
+ id: randomUUID(),
+ name: "Package Assistant",
+ title: "Everyday Work",
+ roleDescription: "Help with everyday work.",
+ type: "built_in",
+ configuration: { systemPrompt: "Be helpful." },
+ ...overrides,
+ };
+}
+
+function loadedPackage(
+ agent: LoadedTenantPackage["agents"][number] = packageAgent(),
+): LoadedTenantPackage {
+ const tenantId = randomUUID();
+ createdTenantIds.push(tenantId);
+ return {
+ tenantId,
+ productName: "Package Test",
+ stylesheet: null,
+ agents: [agent],
+ channels: [],
+ model: {
+ provider: "openai",
+ credentialSecretRef: "openai-key",
+ defaultModel: "gpt-4.1",
+ },
+ knowledgeSources: [],
+ themeCss: "",
+ sourcePath: `/test/${randomUUID()}`,
+ checksum: randomUUID(),
+ };
+}
+
+async function createUser() {
+ const userId = randomUUID();
+ await database.insert(users).values({
+ id: userId,
+ email: `${userId}@example.test`,
+ });
+ createdUserIds.push(userId);
+ return userId;
+}
+
+async function createPackage(tenantId: string) {
+ const [deploymentPackage] = await database
+ .insert(deploymentPackages)
+ .values({
+ tenantId,
+ sourcePath: `/old/${randomUUID()}`,
+ checksum: randomUUID(),
+ })
+ .returning();
+ if (!deploymentPackage) throw new Error("Expected deployment package.");
+ createdPackageIds.push(deploymentPackage.id);
+ return deploymentPackage;
+}
+
+describe("tenant theme validation", () => {
+ test("accepts approved variables in root and dark blocks", () => {
+ expect(() =>
+ validateThemeCss(`
+ :root { --primary: oklch(0.32 0.09 250); }
+ .dark { --primary: oklch(0.87 0.03 250); }
+ `),
+ ).not.toThrow();
+ });
+
+ test("rejects imports, selectors, and unsupported variables", () => {
+ expect(() =>
+ validateThemeCss('@import "https://example.com/theme.css";'),
+ ).toThrow("must not contain imports or URLs");
+ expect(() => validateThemeCss("body { color: red; }")).toThrow(
+ "only define :root and .dark blocks",
+ );
+ expect(() => validateThemeCss(":root { --made-up: red; }")).toThrow(
+ "is not an approved theme variable",
+ );
+ });
+});
+
+describe("tenant YAML validation", () => {
+ test("rejects an agent without a title", () => {
+ expect(() =>
+ validateTenantPackage({
+ brand: "tenant: { id: fintech, product_name: Ledgerline }",
+ agents:
+ "agents: [{ id: knowledge, name: Knowledge, role_description: Answer company questions., type: built-in, system_prompt: Answer from knowledge. }]",
+ channels: "channels: []",
+ model:
+ "model: { provider: openai, credential_secret_ref: openai-key, default_model: gpt-4.1 }",
+ knowledge: "sources: []",
+ themeCss: "",
+ }),
+ ).toThrow("agent.title must be a non-empty string");
+ });
+
+ test("rejects an agent without a role description", () => {
+ expect(() =>
+ validateTenantPackage({
+ brand: "tenant: { id: fintech, product_name: Ledgerline }",
+ agents:
+ "agents: [{ id: knowledge, name: Knowledge, title: Company Knowledge, type: built-in, system_prompt: Answer from knowledge. }]",
+ channels: "channels: []",
+ model:
+ "model: { provider: openai, credential_secret_ref: openai-key, default_model: gpt-4.1 }",
+ knowledge: "sources: []",
+ themeCss: "",
+ }),
+ ).toThrow("agent.role_description must be a non-empty string");
+ });
+
+ test("parses an explicit avatar seed and leaves an omitted seed undefined", () => {
+ const tenantPackage = validateTenantPackage({
+ brand: "tenant: { id: fintech, product_name: Ledgerline }",
+ agents: `agents:
+ - id: knowledge
+ name: Knowledge
+ title: Company Knowledge
+ role_description: Answer company questions.
+ avatar_seed: knowledge
+ type: built-in
+ system_prompt: Answer from knowledge.
+ - id: risk
+ name: Risk
+ title: Risk & Compliance
+ role_description: Investigate policies and controls.
+ type: remote-ag-ui
+ endpoint: http://risk.internal/ag-ui`,
+ channels: "channels: []",
+ model:
+ "model: { provider: openai, credential_secret_ref: openai-key, default_model: gpt-4.1 }",
+ knowledge: "sources: []",
+ themeCss: "",
+ });
+
+ expect(tenantPackage.agents[0]?.avatarSeed).toBe("knowledge");
+ expect(tenantPackage.agents[1]?.avatarSeed).toBeUndefined();
+ });
+
+ test("rejects an empty optional avatar seed", () => {
+ expect(() =>
+ validateTenantPackage({
+ brand: "tenant: { id: fintech, product_name: Ledgerline }",
+ agents:
+ "agents: [{ id: knowledge, name: Knowledge, title: Company Knowledge, role_description: Answer company questions., avatar_seed: '', type: built-in, system_prompt: Answer from knowledge. }]",
+ channels: "channels: []",
+ model:
+ "model: { provider: openai, credential_secret_ref: openai-key, default_model: gpt-4.1 }",
+ knowledge: "sources: []",
+ themeCss: "",
+ }),
+ ).toThrow("agent.avatar_seed must be a non-empty string");
+ });
+
+ test("creates a browser-safe application configuration", () => {
+ const configuration = createApplicationConfiguration(
+ validateTenantPackage({
+ brand:
+ "tenant: { id: fintech, product_name: Ledgerline }\nskin: { stylesheet: theme.css }",
+ agents: "agents: []",
+ channels: "channels: []",
+ model:
+ "model: { provider: openai, credential_secret_ref: openai-key, default_model: gpt-4.1 }",
+ knowledge: "sources: []",
+ themeCss: ":root { --primary: oklch(0.32 0.09 250); }",
+ }),
+ ["google"],
+ );
+
+ expect(configuration).toEqual({
+ brand: {
+ tenantId: "fintech",
+ productName: "Ledgerline",
+ },
+ auth: { providers: ["google"] },
+ });
+ });
+
+ test("loads the mounted fintech package without a theme file", async () => {
+ const tenantPackage = await loadTenantPackage(
+ new URL("../../examples/fintech", import.meta.url).pathname,
+ );
+
+ expect(tenantPackage.tenantId).toBe("openbot");
+ expect(tenantPackage.stylesheet).toBeNull();
+ expect(tenantPackage.themeCss).toBe("");
+ expect(tenantPackage.checksum).toMatch(/^[a-f0-9]{64}$/);
+ expect(tenantPackage.agents).toContainEqual({
+ id: "general-assistant",
+ name: "General Assistant",
+ title: "Everyday Work",
+ roleDescription:
+ "Help with everyday work using clear, concise, and accurate answers.",
+ avatarSeed: "general-assistant",
+ type: "built_in",
+ configuration: {
+ systemPrompt:
+ "You are a helpful general assistant. Give clear, concise, and accurate answers.",
+ },
+ });
+ expect(tenantPackage.channels).toContainEqual({
+ id: "general-assistant",
+ name: "General Assistant",
+ description: "Ask for help with everyday work.",
+ permittedAgents: ["general-assistant"],
+ allowedGroups: ["all"],
+ });
+ });
+
+ test("accepts the complete fintech package and normalizes agent types", () => {
+ const tenantPackage = validateTenantPackage({
+ brand: `tenant:\n id: fintech\n product_name: Ledgerline\nskin:\n stylesheet: theme.css`,
+ agents: `agents:\n - id: knowledge\n name: Knowledge\n title: Company Knowledge\n role_description: Answer company questions.\n type: built-in\n system_prompt: Answer from knowledge.\n - id: risk\n name: Risk\n title: Risk & Compliance\n role_description: Investigate policies and controls.\n type: remote-ag-ui\n endpoint: http://risk.internal/ag-ui`,
+ channels: `channels:\n - id: company\n name: Company\n description: Knowledge channel\n permitted_agents: [knowledge, risk]\n allowed_groups: [all]`,
+ model: `model:\n provider: openai\n credential_secret_ref: openai-key\n default_model: gpt-4.1`,
+ knowledge: `sources:\n - type: google-drive\n roots: [Policies]`,
+ themeCss: ":root { --primary: black; }",
+ });
+
+ expect(tenantPackage.agents[0]?.type).toBe("built_in");
+ expect(tenantPackage.agents[1]?.type).toBe("remote_ag_ui");
+ });
+
+ test("rejects a channel that refers to an unknown agent", () => {
+ expect(() =>
+ validateTenantPackage({
+ brand:
+ "tenant: { id: fintech, product_name: Ledgerline }\nskin: { stylesheet: theme.css }",
+ agents: "agents: []",
+ channels:
+ "channels: [{ id: company, name: Company, description: Test, permitted_agents: [missing], allowed_groups: [all] }]",
+ model:
+ "model: { provider: openai, credential_secret_ref: openai-key, default_model: gpt-4.1 }",
+ knowledge: "sources: []",
+ themeCss: ":root { --primary: black; }",
+ }),
+ ).toThrow('references unknown agent "missing"');
+ });
+});
+
+describe("tenant package agent profile synchronization", () => {
+ test("creates a public ownerless profile for a canonical package agent", async () => {
+ const agent = packageAgent();
+ const tenantPackage = loadedPackage(agent);
+
+ const deploymentPackage = await synchronizeTenantPackage(
+ database,
+ tenantPackage,
+ );
+ createdAgentIds.push(agent.id);
+ createdPackageIds.push(deploymentPackage.id);
+
+ const [canonical] = await database
+ .select()
+ .from(agents)
+ .where(eq(agents.id, agent.id));
+ const [profile] = await database
+ .select()
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, agent.id));
+
+ expect(canonical).toMatchObject({
+ id: agent.id,
+ name: agent.name,
+ packageId: deploymentPackage.id,
+ });
+ expect(profile).toMatchObject({
+ agentId: agent.id,
+ ownerUserId: null,
+ title: agent.title,
+ roleDescription: agent.roleDescription,
+ avatarSeed: agent.id,
+ visibility: "public",
+ deletedAt: null,
+ });
+ });
+
+ test("resynchronizes and undeletes an existing package profile", async () => {
+ const agent = packageAgent({ avatarSeed: "old-avatar" });
+ const tenantPackage = loadedPackage(agent);
+ const deploymentPackage = await synchronizeTenantPackage(
+ database,
+ tenantPackage,
+ );
+ createdAgentIds.push(agent.id);
+ createdPackageIds.push(deploymentPackage.id);
+ const oldUpdatedAt = new Date("2000-01-01T00:00:00.000Z");
+ await database
+ .update(agentProfiles)
+ .set({
+ visibility: "private",
+ deletedAt: new Date("2001-01-01T00:00:00.000Z"),
+ updatedAt: oldUpdatedAt,
+ })
+ .where(eq(agentProfiles.agentId, agent.id));
+
+ const updatedAgent = {
+ ...agent,
+ name: "Updated Package Assistant",
+ title: "Updated Work",
+ roleDescription: "Handle updated package work.",
+ avatarSeed: "updated-avatar",
+ };
+ await synchronizeTenantPackage(database, {
+ ...tenantPackage,
+ agents: [updatedAgent],
+ checksum: randomUUID(),
+ });
+
+ const [canonical] = await database
+ .select()
+ .from(agents)
+ .where(eq(agents.id, agent.id));
+ const [profile] = await database
+ .select()
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, agent.id));
+ expect(canonical?.name).toBe(updatedAgent.name);
+ expect(profile).toMatchObject({
+ ownerUserId: null,
+ title: updatedAgent.title,
+ roleDescription: updatedAgent.roleDescription,
+ avatarSeed: updatedAgent.avatarSeed,
+ visibility: "public",
+ deletedAt: null,
+ });
+ expect(profile?.updatedAt.getTime()).toBeGreaterThan(
+ oldUpdatedAt.getTime(),
+ );
+ });
+
+ test("rejects a user-created canonical and profile collision without changing them", async () => {
+ const ownerUserId = await createUser();
+ const agent = packageAgent();
+ const tenantPackage = loadedPackage(agent);
+ await database.insert(agents).values({
+ id: agent.id,
+ name: "User Agent",
+ type: "built_in",
+ configuration: { systemPrompt: "User-owned prompt." },
+ });
+ createdAgentIds.push(agent.id);
+ await database.insert(agentProfiles).values({
+ agentId: agent.id,
+ ownerUserId,
+ title: "User Title",
+ roleDescription: "User role.",
+ avatarSeed: "user-avatar",
+ visibility: "private",
+ });
+
+ await expect(
+ synchronizeTenantPackage(database, tenantPackage),
+ ).rejects.toThrow("user-created agent");
+
+ const [canonical] = await database
+ .select()
+ .from(agents)
+ .where(eq(agents.id, agent.id));
+ const [profile] = await database
+ .select()
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, agent.id));
+ expect(canonical).toMatchObject({
+ name: "User Agent",
+ packageId: null,
+ configuration: { systemPrompt: "User-owned prompt." },
+ });
+ expect(profile).toMatchObject({
+ ownerUserId,
+ title: "User Title",
+ roleDescription: "User role.",
+ avatarSeed: "user-avatar",
+ visibility: "private",
+ });
+ const synchronizedPackages = await database
+ .select()
+ .from(deploymentPackages)
+ .where(eq(deploymentPackages.tenantId, tenantPackage.tenantId));
+ expect(synchronizedPackages).toHaveLength(0);
+ });
+
+ test("rejects a user-owned profile collision and rolls back canonical changes", async () => {
+ const ownerUserId = await createUser();
+ const agent = packageAgent();
+ const tenantPackage = loadedPackage(agent);
+ const deploymentPackage = await createPackage(tenantPackage.tenantId);
+ await database.insert(agents).values({
+ id: agent.id,
+ name: "Original Package Agent",
+ type: "built_in",
+ configuration: { systemPrompt: "Original package prompt." },
+ packageId: deploymentPackage.id,
+ });
+ createdAgentIds.push(agent.id);
+ await database.insert(agentProfiles).values({
+ agentId: agent.id,
+ ownerUserId,
+ title: "User Title",
+ roleDescription: "User role.",
+ avatarSeed: "user-avatar",
+ visibility: "private",
+ });
+
+ await expect(
+ synchronizeTenantPackage(database, tenantPackage),
+ ).rejects.toThrow("user-owned profile");
+
+ const [canonical] = await database
+ .select()
+ .from(agents)
+ .where(eq(agents.id, agent.id));
+ const [profile] = await database
+ .select()
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, agent.id));
+ const [unchangedPackage] = await database
+ .select()
+ .from(deploymentPackages)
+ .where(eq(deploymentPackages.id, deploymentPackage.id));
+ expect(canonical).toMatchObject({
+ name: "Original Package Agent",
+ configuration: { systemPrompt: "Original package prompt." },
+ packageId: deploymentPackage.id,
+ });
+ expect(profile).toMatchObject({
+ ownerUserId,
+ title: "User Title",
+ roleDescription: "User role.",
+ avatarSeed: "user-avatar",
+ visibility: "private",
+ });
+ expect(unchangedPackage).toMatchObject({
+ sourcePath: deploymentPackage.sourcePath,
+ checksum: deploymentPackage.checksum,
+ });
+ });
+
+ test("rejects a cross-package agent collision and rolls back both packages", async () => {
+ const packageAAgent = packageAgent({
+ name: "Package A Agent",
+ title: "Package A Title",
+ roleDescription: "Package A role.",
+ avatarSeed: "package-a-avatar",
+ });
+ const packageA = loadedPackage(packageAAgent);
+ const packageARow = await synchronizeTenantPackage(database, packageA);
+ createdAgentIds.push(packageAAgent.id);
+ createdPackageIds.push(packageARow.id);
+
+ const packageB = loadedPackage({
+ ...packageAAgent,
+ name: "Package B Agent",
+ title: "Package B Title",
+ roleDescription: "Package B role.",
+ avatarSeed: "package-b-avatar",
+ configuration: { systemPrompt: "Package B prompt." },
+ });
+ const packageBRow = await createPackage(packageB.tenantId);
+
+ const snapshot = async () => {
+ const [canonical] = await database
+ .select()
+ .from(agents)
+ .where(eq(agents.id, packageAAgent.id));
+ const [profile] = await database
+ .select()
+ .from(agentProfiles)
+ .where(eq(agentProfiles.agentId, packageAAgent.id));
+ const [persistedPackageA] = await database
+ .select()
+ .from(deploymentPackages)
+ .where(eq(deploymentPackages.id, packageARow.id));
+ const [persistedPackageB] = await database
+ .select()
+ .from(deploymentPackages)
+ .where(eq(deploymentPackages.id, packageBRow.id));
+ return {
+ canonical,
+ profile,
+ packageA: persistedPackageA,
+ packageB: persistedPackageB,
+ };
+ };
+ const before = await snapshot();
+
+ const outcome = await synchronizeTenantPackage(database, packageB).then(
+ () => ({ status: "fulfilled" as const }),
+ (error: unknown) => ({
+ status: "rejected" as const,
+ message: error instanceof Error ? error.message : String(error),
+ }),
+ );
+ const after = await snapshot();
+
+ expect(outcome).toEqual({
+ status: "rejected",
+ message: `Tenant package agent "${packageAAgent.id}" collides with a user-created agent`,
+ });
+ expect(after).toEqual(before);
+ });
+});
+
+/**
+ * `${NAME}` in a package file.
+ *
+ * The addresses of the services a package points at belong to the environment rather than to the
+ * package, so the same package has to work against a local stack and a deployed one. A name with no
+ * value and no default is an error: substituting nothing would point a Bot at an address nobody
+ * meant.
+ */
+describe("expanding a package file against the environment", () => {
+ const file = "agents.yaml";
+
+ test("takes the value from the environment", () => {
+ expect(
+ expandEnvironment("endpoint: ${AG_UI_URL}", file, {
+ AG_UI_URL: "https://bots.example.test/ag-ui",
+ }),
+ ).toBe("endpoint: https://bots.example.test/ag-ui");
+ });
+
+ test("falls back to the default when the name is not set", () => {
+ expect(
+ expandEnvironment(
+ "endpoint: ${AG_UI_URL:-http://localhost:4200}",
+ file,
+ {},
+ ),
+ ).toBe("endpoint: http://localhost:4200");
+ });
+
+ test("prefers the environment over the default", () => {
+ expect(
+ expandEnvironment("endpoint: ${AG_UI_URL:-http://localhost:4200}", file, {
+ AG_UI_URL: "https://bots.example.test",
+ }),
+ ).toBe("endpoint: https://bots.example.test");
+ });
+
+ test("treats an empty value as unset", () => {
+ expect(
+ expandEnvironment("endpoint: ${AG_UI_URL:-http://localhost:4200}", file, {
+ AG_UI_URL: "",
+ }),
+ ).toBe("endpoint: http://localhost:4200");
+ });
+
+ test("an empty default is allowed and is not an error", () => {
+ expect(expandEnvironment("suffix: ${NOTHING:-}", file, {})).toBe(
+ "suffix: ",
+ );
+ });
+
+ test("refuses a name with neither a value nor a default", () => {
+ expect(() => expandEnvironment("endpoint: ${AG_UI_URL}", file, {})).toThrow(
+ /agents\.yaml refers to \$\{AG_UI_URL\}/,
+ );
+ });
+});
diff --git a/server/tests/thread-identity.test.ts b/server/tests/thread-identity.test.ts
new file mode 100644
index 00000000..cfb5b4a3
--- /dev/null
+++ b/server/tests/thread-identity.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from "bun:test";
+import { createThreadIdentity } from "../src/channels/thread-identity";
+
+/**
+ * The thread id as the only place a deployment can write its own name.
+ *
+ * The platform accepts a client-generated id and nothing else a deployment controls, so these are
+ * the properties the id has to hold on its own: it is a UUID the platform will take, it says which
+ * deployment minted it, and it says that to a deployment that has never seen the thread before.
+ */
+
+const here = createThreadIdentity("openbot-production");
+const elsewhere = createThreadIdentity("openbot-staging");
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+describe("a thread id carries the deployment that minted it", () => {
+ test("it is a well-formed UUID, which is all the platform accepts", () => {
+ // A prefixed id is refused by the platform with a validation error, so the tag has to fit inside
+ // the format rather than sit beside it.
+ expect(here.mint()).toMatch(UUID);
+ });
+
+ test("it declares the custom layout rather than claiming to be random", () => {
+ // Version 8: RFC 9562 reserves it for a vendor-defined layout, which is what this is.
+ expect(here.mint()[14]).toBe("8");
+ });
+
+ test("a deployment recognises its own", () => {
+ for (let attempt = 0; attempt < 50; attempt++) {
+ expect(here.owns(here.mint())).toBe(true);
+ }
+ });
+
+ test("and does not claim another deployment's", () => {
+ for (let attempt = 0; attempt < 50; attempt++) {
+ expect(here.owns(elsewhere.mint())).toBe(false);
+ expect(elsewhere.owns(here.mint())).toBe(false);
+ }
+ });
+
+ test("the same name recognises threads minted by another process", () => {
+ // Nothing is remembered between runs: a deployment that restarts, or a second copy of the same
+ // deployment, has to reach the same answer from the name alone.
+ expect(createThreadIdentity("openbot-production").owns(here.mint())).toBe(
+ true,
+ );
+ });
+
+ test("ids differ, so the tag has not eaten the randomness", () => {
+ const minted = new Set(Array.from({ length: 1000 }, () => here.mint()));
+ expect(minted.size).toBe(1000);
+ });
+
+ test("a thread minted before deployments had names is not claimed", () => {
+ // A plain version 4 id. Unknown provenance rather than somebody else's, which is a distinction
+ // its caller has to make, not this.
+ expect(here.owns(crypto.randomUUID())).toBe(false);
+ });
+
+ test("anything that is not a UUID is refused rather than parsed", () => {
+ for (const value of [
+ "",
+ "not-a-uuid",
+ "openbot-connection-test-123",
+ "377529b0-9a52-4fe3-bfaa-b99a3886710",
+ "377529b0-9a52-4fe3-bfaa-b99a3886710e-extra",
+ "zzzzzzzz-9a52-4fe3-bfaa-b99a3886710e",
+ ]) {
+ expect(here.owns(value)).toBe(false);
+ }
+ });
+});
diff --git a/server/tsconfig.json b/server/tsconfig.json
new file mode 100644
index 00000000..4bd6962d
--- /dev/null
+++ b/server/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../tsconfig.base.json",
+ "include": ["src"]
+}
diff --git a/shared/bot-prompt.ts b/shared/bot-prompt.ts
new file mode 100644
index 00000000..8e924902
--- /dev/null
+++ b/shared/bot-prompt.ts
@@ -0,0 +1,56 @@
+/**
+ * What a Bot in this box knows about its own hands.
+ *
+ * Shared by `agent-bot` and `agent-langgraph` so the implementations differ by framework, not by
+ * instructions or available computer behavior.
+ */
+/**
+ * The order of operations that makes the computer tools usable.
+ *
+ * The prompt requires snapshot-first computer use. Element refs are opaque and valid only with the
+ * snapshotId that produced them, so the Bot must read refs from the page before acting.
+ */
+export const SYSTEM_PROMPT = [
+ "You are a Bot with your own computer, a real web browser the person can watch you use.",
+ "When you are asked to look at, open, visit, check or read a web page, call computer_navigate.",
+ "Never claim you cannot browse: opening a page is something you can actually do.",
+ "Opening a page returns its title and its readable text. Answer from that text.",
+ "Never tell the person to go and look at the page themselves: you have already read it.",
+ "",
+ "You can also ACT on a page: fill in forms, click buttons, tick boxes and follow links.",
+ "The order matters. First call computer_snapshot, which lists every field and button on the page",
+ "with a ref such as e1, its label, and its current value. Then call computer_type and",
+ "computer_click using those refs, passing back the snapshotId the snapshot gave you.",
+ "Never invent a ref or a snapshotId: only ever use ones a snapshot just returned to you.",
+ "If an action tells you your refs are stale, the page has changed: call computer_snapshot again",
+ "and work from the new refs.",
+ "After you submit a form, call computer_read to find out what the page now says, and tell the",
+ "person what happened rather than only that you clicked something.",
+ "",
+ "You also have a workspace: your own folder of files that survives between conversations.",
+ "Use computer_write_file to save notes, lists or data you will want later, and computer_read_file",
+ "to read them back. Paths are relative to your workspace, such as notes.md, and you cannot reach",
+ "anything outside it.",
+ "When you are asked what files you have, or you are unsure of a name, call computer_list_files.",
+ "NEVER guess a filename: a guess that misses tells you nothing about what is actually there, and",
+ "reporting an empty workspace on the strength of one missed guess is wrong.",
+ "'There is no file at X' means that file does not exist. It is NOT a policy restriction and you",
+ "must not describe it as one. List the workspace and work from what is really in it.",
+ "",
+ "Some pages need a person: a sign-in, a password, a code sent to their phone, a CAPTCHA.",
+ "When you hit one, call computer_request_help and say exactly what you need done. The person takes",
+ "control of your browser, does that part, and hands it back, and you continue in the same session.",
+ "NEVER ask the person to tell you a password or a code. You do not need it and must not have it.",
+ "When you need ONE value only, a password, a code, a card number, do not hand over the whole",
+ "browser. Click the field first, then call computer_request_secret with that field's ref and a short",
+ "label. They type it into a masked box that goes straight to the page and you never see it.",
+ "Use a full takeover for anything more involved than one field.",
+ "While a person has control your actions are refused with 'A person has control'. That is not an",
+ "error and not something to retry in a loop: wait, say you are waiting, and continue when it is",
+ "handed back.",
+ "",
+ "Some actions are refused by this deployment's policy. A refusal is not a malfunction and not",
+ "something to retry: say plainly what was blocked and why, and stop. Do not try another route to",
+ "the same thing.",
+ "Say what you found or did in plain language, briefly.",
+].join(" ");
diff --git a/spire/agent.conf b/spire/agent.conf
new file mode 100644
index 00000000..bd36dc78
--- /dev/null
+++ b/spire/agent.conf
@@ -0,0 +1,34 @@
+# The agent every computer asks for its identity.
+#
+# The Docker attestor identifies the calling container and selects on labels. The Unix attestor needs
+# a shared PID namespace, which does not hold when each Bot runs in its own runtime-created container.
+agent {
+ data_dir = "/opt/spire/data/agent"
+ log_level = "INFO"
+ trust_domain = "openbot.local"
+ server_address = "spire-server"
+ server_port = "8081"
+
+ # Local bootstrap only. A real deployment provisions the trust bundle through a hardware attestor
+ # (x509pop, TPM, or a cloud instance identity document) rather than trusting first contact.
+ insecure_bootstrap = true
+
+ socket_path = "/tmp/spire-agent/public/api.sock"
+}
+
+plugins {
+ NodeAttestor "join_token" {
+ plugin_data {}
+ }
+
+ KeyManager "memory" {
+ plugin_data {}
+ }
+
+ # Selects on the labels the supervisor sets when it creates a computer.
+ WorkloadAttestor "docker" {
+ plugin_data {
+ docker_socket_path = "unix:///var/run/docker.sock"
+ }
+ }
+}
diff --git a/supervisor/Dockerfile b/supervisor/Dockerfile
new file mode 100644
index 00000000..e45689f0
--- /dev/null
+++ b/supervisor/Dockerfile
@@ -0,0 +1,21 @@
+# The container supervisor. The only thing in this deployment that holds the Docker socket.
+#
+# A small image with a two-package dependency tree, because this process is the one
+# whose compromise costs the host. Everything it needs is an HTTP server and a Docker client.
+# The SPIRE CLI, taken from the official image at a pinned version rather than downloaded at build
+# time. It is how entries are registered; without it identity is simply unavailable, which the
+# supervisor reports and carries on from.
+FROM ghcr.io/spiffe/spire-server:1.15.1 AS spire
+
+FROM oven/bun:1.3.14-alpine
+
+WORKDIR /app
+COPY supervisor/package.json ./
+RUN bun install
+
+COPY --from=spire /opt/spire/bin/spire-server /usr/local/bin/spire-server
+
+COPY supervisor/src ./src
+
+EXPOSE 4300
+CMD ["bun", "src/index.ts"]
diff --git a/supervisor/bun.lock b/supervisor/bun.lock
new file mode 100644
index 00000000..c9773176
--- /dev/null
+++ b/supervisor/bun.lock
@@ -0,0 +1,164 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "@openbot/supervisor",
+ "dependencies": {
+ "dockerode": "5.0.1",
+ "hono": "^4.10.0",
+ },
+ "devDependencies": {
+ "@types/dockerode": "4.0.1",
+ "typescript": "^5.9.3",
+ },
+ },
+ },
+ "packages": {
+ "@balena/dockerignore": ["@balena/[email protected]", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="],
+
+ "@grpc/grpc-js": ["@grpc/[email protected]", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ=="],
+
+ "@grpc/proto-loader": ["@grpc/[email protected]", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.2.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ=="],
+
+ "@js-sdsl/ordered-map": ["@js-sdsl/[email protected]", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
+
+ "@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
+
+ "@protobufjs/base64": ["@protobufjs/[email protected]", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
+
+ "@protobufjs/codegen": ["@protobufjs/[email protected]", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],
+
+ "@protobufjs/eventemitter": ["@protobufjs/[email protected]", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],
+
+ "@protobufjs/fetch": ["@protobufjs/[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],
+
+ "@protobufjs/float": ["@protobufjs/[email protected]", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
+
+ "@protobufjs/path": ["@protobufjs/[email protected]", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
+
+ "@protobufjs/pool": ["@protobufjs/[email protected]", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
+
+ "@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="],
+
+ "@types/docker-modem": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "@types/ssh2": "*" } }, "sha512-yKpAGEuKRSS8wwx0joknWxsmLha78wNMe9R2S3UNsVOkZded8UqOrV8KoeDXoXsjndxwyF3eIhyClGbO1SEhEg=="],
+
+ "@types/dockerode": ["@types/[email protected]", "", { "dependencies": { "@types/docker-modem": "*", "@types/node": "*", "@types/ssh2": "*" } }, "sha512-cmUpB+dPN955PxBEuXE3f6lKO1hHiIGYJA46IVF3BJpNsZGvtBDcRnlrHYHtOH/B6vtDOyl2kZ2ShAu3mgc27Q=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg=="],
+
+ "@types/ssh2": ["@types/[email protected]", "", { "dependencies": { "@types/node": "^18.11.18" } }, "sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ=="],
+
+ "ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
+
+ "asn1": ["[email protected]", "", { "dependencies": { "safer-buffer": "~2.1.0" } }, "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ=="],
+
+ "base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
+
+ "bcrypt-pbkdf": ["[email protected]", "", { "dependencies": { "tweetnacl": "^0.14.3" } }, "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w=="],
+
+ "bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
+
+ "buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
+
+ "buildcheck": ["[email protected]", "", {}, "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA=="],
+
+ "chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
+
+ "cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
+
+ "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
+
+ "color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
+
+ "cpu-features": ["[email protected]", "", { "dependencies": { "buildcheck": "~0.0.6", "nan": "^2.19.0" } }, "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA=="],
+
+ "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
+
+ "docker-modem": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "readable-stream": "^3.5.0", "split-ca": "^1.0.1", "ssh2": "^1.15.0" } }, "sha512-XJgGhoR/CLpqshm4d3L7rzH6t8NgDFUIIpztYlLHIApeJjMZKYJMz2zxPsYxnejq5h3ELYSw/RBsi3t5h7gNTA=="],
+
+ "dockerode": ["[email protected]", "", { "dependencies": { "@balena/dockerignore": "^1.0.2", "@grpc/grpc-js": "^1.11.1", "@grpc/proto-loader": "^0.7.13", "docker-modem": "^5.0.7", "protobufjs": "^7.3.2", "tar-fs": "^2.1.4" } }, "sha512-avsq/xk4YPIrn0CgleX5bjT9Y8IT1p9PxrNQ++RBQ2WEyFfHCTDsT9kmyxz+H/axnjAwg8wJWEIuPGOUuNupiA=="],
+
+ "emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
+
+ "escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
+
+ "fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
+
+ "get-caller-file": ["[email protected]", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
+
+ "hono": ["[email protected]", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
+
+ "ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
+
+ "inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
+
+ "is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
+
+ "lodash.camelcase": ["[email protected]", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
+
+ "long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
+
+ "mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
+
+ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
+
+ "nan": ["[email protected]", "", {}, "sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ=="],
+
+ "once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
+
+ "protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="],
+
+ "pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
+
+ "readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
+
+ "require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
+
+ "safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
+
+ "safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
+
+ "split-ca": ["[email protected]", "", {}, "sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ=="],
+
+ "ssh2": ["[email protected]", "", { "dependencies": { "asn1": "^0.2.6", "bcrypt-pbkdf": "^1.0.2" }, "optionalDependencies": { "cpu-features": "~0.0.10", "nan": "^2.23.0" } }, "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ=="],
+
+ "string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
+ "string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
+
+ "strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw=="],
+
+ "tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
+
+ "tweetnacl": ["[email protected]", "", {}, "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
+
+ "util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
+
+ "wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
+
+ "wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
+
+ "y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
+
+ "yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="],
+
+ "yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
+
+ "@grpc/grpc-js/@grpc/proto-loader": ["@grpc/[email protected]", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
+
+ "@types/ssh2/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="],
+
+ "@types/ssh2/@types/node/undici-types": ["[email protected]", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
+ }
+}
diff --git a/supervisor/src/identity.ts b/supervisor/src/identity.ts
new file mode 100644
index 00000000..28d755e1
--- /dev/null
+++ b/supervisor/src/identity.ts
@@ -0,0 +1,97 @@
+import type { ComputerNames } from "./names";
+import { BOT_LABEL, NAMESPACE, NAMESPACE_LABEL } from "./names";
+
+/**
+ * A SPIFFE identity for each Bot's computer.
+ *
+ * An SVID makes the Bot's identity something a workload holds and can be challenged on, rather than
+ * a name supplied in a header.
+ *
+ * The computer is issued nothing at build time and carries no
+ * secret. It asks the local SPIRE agent, and the agent decides what it is by inspecting the calling
+ * container and matching the label the supervisor set. So identity follows from the same fact that
+ * created the container, and an unregistered container gets nothing.
+ *
+ * Registered here because the supervisor knows when a computer has come into existence.
+ */
+
+const SPIFFE_ENABLED = process.env.SPIRE_SOCKET !== undefined;
+
+/** The parent every workload entry hangs from: the agent that attested the node. */
+const AGENT_SPIFFE_ID =
+ process.env.SPIRE_AGENT_ID ??
+ "spiffe://openbot.local/spire/agent/join_token/openbot";
+
+const TRUST_DOMAIN = process.env.SPIRE_TRUST_DOMAIN ?? "openbot.local";
+
+export function spiffeIdFor(botId: string): string {
+ return `spiffe://${TRUST_DOMAIN}/bot/${botId}`;
+}
+
+export type EntryResult =
+ | { registered: true; spiffeId: string }
+ | { registered: false; reason: string };
+
+/**
+ * Give this Bot's computer an identity, if SPIRE is part of this deployment.
+ *
+ * Not fatal when it fails. A computer without an SVID still works; it simply cannot prove which Bot
+ * it is. Refusing to start one would turn an identity outage into an outage of the product, which is
+ * the wrong trade for a deployment that may not run SPIRE at all. It is reported instead, so the
+ * difference between "no identity configured" and "identity broken" stays visible.
+ */
+export async function registerEntry(
+ names: ComputerNames,
+): Promise<EntryResult> {
+ if (!SPIFFE_ENABLED) {
+ return { registered: false, reason: "SPIRE is not configured." };
+ }
+
+ const spiffeId = spiffeIdFor(names.botId);
+ const selectors = [
+ `docker:label:${BOT_LABEL}:${names.botId}`,
+ `docker:label:${NAMESPACE_LABEL}:${NAMESPACE}`,
+ ];
+
+ try {
+ // The SPIRE CLI rather than a hand-rolled registration client: it is the supported surface for
+ // this, ships in the same image as the server, and its entry semantics are already idempotent.
+ const process_ = Bun.spawn(
+ [
+ "spire-server",
+ "entry",
+ "create",
+ "-socketPath",
+ process.env.SPIRE_SOCKET ?? "/tmp/spire-server/private/api.sock",
+ "-spiffeID",
+ spiffeId,
+ "-parentID",
+ AGENT_SPIFFE_ID,
+ ...selectors.flatMap((selector) => ["-selector", selector]),
+ ],
+ { stdout: "pipe", stderr: "pipe" },
+ );
+
+ const [status, stderr] = await Promise.all([
+ process_.exited,
+ new Response(process_.stderr).text(),
+ ]);
+
+ // Already registered is success for a restarted supervisor.
+ if (status !== 0 && !stderr.includes("similar entry already exists")) {
+ return {
+ registered: false,
+ reason: stderr.trim().slice(0, 200) || `spire-server exited ${status}`,
+ };
+ }
+
+ return { registered: true, spiffeId };
+ } catch (error) {
+ // Identity registration must not stop a computer being created. A missing binary, unreachable
+ // socket or starting server is reported in the response instead.
+ return {
+ registered: false,
+ reason: error instanceof Error ? error.message : String(error),
+ };
+ }
+}
diff --git a/supervisor/src/names.ts b/supervisor/src/names.ts
new file mode 100644
index 00000000..46ad78a3
--- /dev/null
+++ b/supervisor/src/names.ts
@@ -0,0 +1,94 @@
+/**
+ * What a Bot id is allowed to be, and what it becomes.
+ *
+ * This is a security boundary. Every id that arrives here is turned into a container name, two volume
+ * names and a label filter. The supervisor only accepts plain Bot identifiers, so callers cannot
+ * name an existing container, database volume, API server resource, or host tool through this API.
+ *
+ * So an id must be a plain identifier and nothing else: letters, digits, hyphen and underscore. No
+ * slashes (which would let a name escape into another path segment on the socket API), no dots (which
+ * Docker allows in names but which invite `..` reasoning), no colons (image tags), no whitespace.
+ *
+ * Names are derived rather than accepted. A caller says which Bot; it never says which container.
+ */
+
+/** Long enough for a uuid-shaped agent id, short enough to stay inside Docker's own name limits. */
+const MAX_BOT_ID = 64;
+
+const ALLOWED = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
+
+/**
+ * The deployment a computer belongs to.
+ *
+ * Container and volume names are global to a Docker host, so two OpenBot deployments sharing a host
+ * would otherwise derive the same names for the same Bot id and each would treat the other's
+ * containers as its own. The namespace is part of every derived name, and is held to the same
+ * character rules for the same reason.
+ */
+export const DEFAULT_NAMESPACE = "openbot";
+
+export const NAMESPACE = (() => {
+ const configured = process.env.COMPUTER_NAMESPACE?.trim();
+ if (!configured) return DEFAULT_NAMESPACE;
+ if (!ALLOWED.test(configured) || configured.length > MAX_BOT_ID) {
+ throw new Error(
+ "COMPUTER_NAMESPACE may contain only letters, digits, hyphen and underscore, and must start with a letter or digit.",
+ );
+ }
+ return configured;
+})();
+
+/**
+ * Everything the supervisor is permitted to create for one Bot, and nothing it is not.
+ *
+ * `label` is what makes stop and reset safe: the supervisor only ever acts on containers carrying it,
+ * so even a correct-looking name for something it did not create will not match.
+ */
+export type ComputerNames = {
+ botId: string;
+ container: string;
+ profileVolume: string;
+ workspaceVolume: string;
+};
+
+export type NameResult =
+ | { ok: true; names: ComputerNames }
+ | { ok: false; reason: string };
+
+/** The label every container and volume the supervisor owns carries. */
+export const OWNER_LABEL = "openbot.supervisor";
+
+/** The label holding the Bot a container belongs to, so a listing can report it without parsing names. */
+export const BOT_LABEL = "openbot.bot-id";
+
+/** The label holding the deployment a container belongs to. */
+export const NAMESPACE_LABEL = "openbot.namespace";
+
+export function namesFor(botId: unknown): NameResult {
+ if (typeof botId !== "string" || botId.length === 0) {
+ return { ok: false, reason: "A bot id is required." };
+ }
+ if (botId.length > MAX_BOT_ID) {
+ return {
+ ok: false,
+ reason: `A bot id may be at most ${MAX_BOT_ID} characters.`,
+ };
+ }
+ if (!ALLOWED.test(botId)) {
+ return {
+ ok: false,
+ reason:
+ "A bot id may contain only letters, digits, hyphen and underscore, and must start with a letter or digit.",
+ };
+ }
+
+ return {
+ ok: true,
+ names: {
+ botId,
+ container: `${NAMESPACE}-computer-${botId}`,
+ profileVolume: `${NAMESPACE}-profile-${botId}`,
+ workspaceVolume: `${NAMESPACE}-workspace-${botId}`,
+ },
+ };
+}
diff --git a/supervisor/tsconfig.json b/supervisor/tsconfig.json
new file mode 100644
index 00000000..1172f877
--- /dev/null
+++ b/supervisor/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../tsconfig.base.json",
+ "compilerOptions": {
+ "types": ["bun"]
+ },
+ "include": ["src"]
+}
diff --git a/tests/compose.test.ts b/tests/compose.test.ts
new file mode 100644
index 00000000..9c507047
--- /dev/null
+++ b/tests/compose.test.ts
@@ -0,0 +1,64 @@
+import { expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+test("provides PostgreSQL with pgvector for local development", () => {
+ const compose = readFileSync(
+ join(import.meta.dir, "..", "docker-compose.yml"),
+ "utf8",
+ );
+
+ expect(compose).toContain("postgres:");
+ expect(compose).toContain("pgvector/pgvector:");
+ expect(compose).toContain("${POSTGRES_PORT:-5432}:5432");
+});
+
+/**
+ * Every published port is settable, and defaults to the number the documentation gives.
+ *
+ * `scripts/start.sh` reads these same names to decide where to look for each service.
+ */
+test("publishes every service on a settable port with the documented default", () => {
+ const compose = readFileSync(
+ join(import.meta.dir, "..", "docker-compose.yml"),
+ "utf8",
+ );
+
+ const published = [
+ ["POSTGRES_PORT", "5432", "5432"],
+ ["COMPUTER_PORT", "4100", "4100"],
+ ["SUPERVISOR_PORT", "4500", "4300"],
+ ["BOT_PORT", "4200", "4200"],
+ ["LANGGRAPH_PORT", "4201", "4201"],
+ ] as const;
+
+ for (const [name, host, container] of published) {
+ expect(compose).toContain(`\${${name}:-${host}}:${container}`);
+ }
+});
+
+test("enables pgvector before creating vector columns", () => {
+ const migration = readFileSync(
+ join(import.meta.dir, "..", "server", "drizzle", "0000_schema.sql"),
+ "utf8",
+ );
+
+ // The order is the property, not the first line. A `vector` column cannot be created before the
+ // extension that defines the type, and a generated migration has no reason to put them in that
+ // order on its own.
+ const extension = migration.indexOf("CREATE EXTENSION IF NOT EXISTS vector;");
+ const firstVectorColumn = migration.search(/"embedding" vector\(/);
+ expect(extension).toBeGreaterThanOrEqual(0);
+ expect(firstVectorColumn).toBeGreaterThan(extension);
+});
+
+test("runs migrations after PostgreSQL becomes healthy", () => {
+ const compose = readFileSync(
+ join(import.meta.dir, "..", "docker-compose.yml"),
+ "utf8",
+ );
+
+ expect(compose).toContain("migrate:");
+ expect(compose).toContain("condition: service_healthy");
+ expect(compose).toContain('"drizzle-kit", "migrate"');
+});
diff --git a/tests/workspace.test.ts b/tests/workspace.test.ts
new file mode 100644
index 00000000..aacea898
--- /dev/null
+++ b/tests/workspace.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from "bun:test";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+const repositoryRoot = join(import.meta.dir, "..");
+
+function packageManifest(path: string) {
+ return JSON.parse(
+ readFileSync(join(repositoryRoot, path, "package.json"), "utf8"),
+ ) as {
+ name: string;
+ };
+}
+
+describe("OpenBot workspace", () => {
+ test("defines the app, server, and worker packages", () => {
+ const rootManifest = JSON.parse(
+ readFileSync(join(repositoryRoot, "package.json"), "utf8"),
+ ) as { workspaces: string[] };
+
+ expect(rootManifest.workspaces).toEqual(["app", "server", "worker"]);
+
+ for (const packageName of rootManifest.workspaces) {
+ expect(existsSync(join(repositoryRoot, packageName))).toBe(true);
+ expect(packageManifest(packageName).name).toBe(packageName);
+ }
+ });
+});
diff --git a/worker/package.json b/worker/package.json
new file mode 100644
index 00000000..8a136363
--- /dev/null
+++ b/worker/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "worker",
+ "license": "MIT",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "scripts": {
+ "build": "tsc --noEmit",
+ "dev": "bun --watch src/index.ts",
+ "typecheck": "tsc --noEmit"
+ }
+}
diff --git a/worker/src/index.ts b/worker/src/index.ts
new file mode 100644
index 00000000..aad40e41
--- /dev/null
+++ b/worker/src/index.ts
@@ -0,0 +1,3 @@
+import { workerStatus } from "./status";
+
+console.info(`OpenBot worker status: ${workerStatus().status}`);
diff --git a/worker/tests/status.test.ts b/worker/tests/status.test.ts
new file mode 100644
index 00000000..bcb031f9
--- /dev/null
+++ b/worker/tests/status.test.ts
@@ -0,0 +1,8 @@
+import { describe, expect, test } from "bun:test";
+import { workerStatus } from "../src/status";
+
+describe("worker status", () => {
+ test("starts idle before connector jobs are configured", () => {
+ expect(workerStatus()).toEqual({ status: "idle" });
+ });
+});