Skip to content

The open-source app everyone uses to manage agents at work

feat(connections): add experimental task-pinned AI routing (#14967)

Dotta0e0b63e5a551
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index e700f79f56..41d7435d3a 100644
--- a/doc/SPEC-implementation.md
+++ b/doc/SPEC-implementation.md
@@ -1907,6 +1907,14 @@ unavailable. Preserve current ownership and newer-work fences. See
- GitHub.com, manual refresh only. No upstream editing, polling, webhook sync, commits,
or pull-request creation in this milestone.
+### Experimental AI connection routing
+
+Opt-in plugin routers may represent a pool as an AI runtime binding. Core keeps
+company and credential authorization, atomically records task/agent affinity and
+a pool cursor, and persists concrete native recovery evidence. The full contract
+is in [AI-CONNECTION-ROUTERS.md](connections/AI-CONNECTION-ROUTERS.md). Disabled
+routing cannot allocate new tasks; already admitted native runs remain recoverable.
+
### Connection instructions
Connections can store optional, versioned agent instructions independently of
diff --git a/doc/SPEC.md b/doc/SPEC.md
index d2003e1080..25e05ab058 100644
--- a/doc/SPEC.md
+++ b/doc/SPEC.md
@@ -686,3 +686,10 @@ requirements, and advisory warnings for missing or external references. New
upstream skills require reviewed selection; removed or deselected skills remain
installed. Editing starts with an independent copy. Write-back and PR publication
are a later milestone; exact path and commit provenance provide their base.
+
+### Experimental connection routing
+
+A virtual AI connection can rotate new task/agent allocations through an
+authorized pool while preserving session affinity. Admission, credentials and
+durable recovery remain host responsibilities; policy can be supplied by an
+opt-in plugin. See [the experimental contract](connections/AI-CONNECTION-ROUTERS.md).
diff --git a/doc/connections/AI-CONNECTION-ROUTERS.md b/doc/connections/AI-CONNECTION-ROUTERS.md
new file mode 100644
index 0000000000..06f092c556
--- /dev/null
+++ b/doc/connections/AI-CONNECTION-ROUTERS.md
@@ -0,0 +1,133 @@
+# Experimental AI connection routers
+
+AI routers are virtual, company-scoped connections owned by a capability-gated
+plugin (`ai.connections.route`). The instance flag `enableAiConnectionRouters`
+defaults to false. Pools also default to disabled. The host must implement this
+contract; the plugin's minimum version alone does not establish compatibility.
+Routing has no visible enable control in Experimental settings on either
+self-hosted or Cloud instances, even after an operator enables it. Self-hosted
+operators can set `enableAiConnectionRouters` through the instance-admin
+`PATCH /api/instance/settings/experimental` API. Cloud operators use the existing
+fleet or per-stack managed feature configuration. Installing a plugin does not
+enable routing; enabling routing does not enable individual pools.
+
+The host authorizes members using the ordinary company, user, sharing, install,
+health and harness checks. Saving a binding or changing its harness requires
+at least one usable member for that agent. New-agent creation installs only
+members authorized by the ordinary personal-owner or shared-install policy,
+in the same transaction as the agent. Pool membership cannot install a
+restricted shared connection. It sends authorized metadata and sanitized usage
+observations to `onRouteAiConnection`. The plugin proposes an opaque member ID;
+it cannot receive credentials or expand authorization. Pure round robin does
+not probe usage. Usage-aware selection has a shared 15-second probe budget,
+60-second freshness cache and ordinary grant/secret freshness invalidation.
+Concurrent starts share an in-flight probe for the same grant and credential
+freshness. Each caller retains its selection deadline.
+
+One cursor spans all agents in a pool. An allocation transaction locks the
+cursor, checks config and cursor revisions, rechecks authorization, and writes
+the task pin and cursor advance together. Pins use company, pool, agent and the
+existing task key (including `__heartbeat__`). Wakes without a task key retain
+the original run ID as an affinity key in retry context. Conflicts retry at most
+20 times; contention beyond that returns an actionable conflict.
+
+Pins snapshot the concrete binding and member profile. Removing or editing a
+member affects future allocations. Composer changes can change a supported
+model or effort, with a note on fallback, but never the account or harness.
+Session reset and compaction retain the pin. Revocation requires operator repair.
+Authentication repair uses the failed run’s durable concrete allocation and
+current member permissions; reconnect-and-continue preserves the agent’s pool
+binding. Changing the agent’s pool invalidates the old repair card.
+A pre-existing managed session can adopt its saved account when it is an
+eligible member; otherwise the operator must explicitly reset the session.
+
+Credential `ai_session_epoch` changes on reconnect or manual rotation. Only
+verified runtime refresh write-back preserves it. Session fingerprints use the
+secret ID and epoch while authentication failure attribution still uses the
+token generation. A reconnect that replaces an indexed legacy secret changes
+the session identity even when both secret epochs are zero.
+Adopting a valid account preserves a session only when the complete effective
+configuration matches a prior fingerprint. Core can bridge binding-only agent
+revisions (up to 20) and unchanged legacy token identities at epoch zero. Changes
+to other settings, explicit resets, and credential replacement retain their
+existing reset behavior; no fingerprint category is exempted.
+Native recovery retains concrete routing evidence and can finish after the
+router flag or plugin is disabled or uninstalled; it revalidates underlying
+account access and never makes a new allocation.
+
+The private Cloud plugin owns round-robin and quota policy. Its manifest declares
+`aiConnectionRouter: { name, description }` alongside `ai.connections.route`.
+Core adds that connector to the regular catalog and hosts its setup and account
+management using authenticated, company-scoped pool APIs. No separate plugin
+page or sidebar entry is needed. New allocations over
+the chosen threshold wait; known exhaustion defers pinned turns. The deferred
+run schedules `ai_connection_pool_wait` without spending the failure retry
+budget, and the UI labels that retry as **Pool exhausted**.
+
+Operators choose **Connectors → AI connection pool → Add connection pool**,
+select existing accounts, arrange their order, and create a paused connection.
+The normal account page supports rename, member changes, enabling, and removal.
+**Used by** lists the company’s non-terminated agents configured to use the pool,
+with their avatars and links to their profiles. Paused agents remain listed.
+Optional usage and runtime defaults live under **Advanced**. Creating another
+account opens the normal catalog in a new tab so the pool draft stays intact.
+The catalog marks experimental-disabled or unavailable plugins as unavailable.
+
+Deletion uses
+`DELETE /api/companies/:companyId/ai-connection-pools/:poolId` with the current
+`expectedRevision`. Core disables and archives the virtual connection, retaining
+its task pins, cursor and run records. It rejects stale edits and new allocations;
+already admitted runs keep their concrete recovery evidence. Cleanup remains
+available when experimental routing or the plugin is disabled. The catalog captures the reviewed pool revision before showing its removal
+confirmation and uses the pool endpoint. Ordinary connection update and removal
+endpoints reject pools so they cannot bypass configuration revisions. Non-managers
+see the permission requirement without making a denied management request.
+
+Configuration and committed selection are recorded in activity records. Runs
+record the selected member/profile and override notes in the local run log and
+recovery context. These records stay in the instance database.
+
+Tests: `cd server && pnpm exec vitest run src/__tests__/ai-connection-router.test.ts`
+plus the existing AI connection, retry accounting, run-dispatch and UI suites.
+
+## UI review in Storybook
+
+Run `pnpm --filter @paperclipai/ui storybook` from Core, then open
+**AI Connections / Connection pools**. The 16 stories use production components
+for pool selection, legacy-session adoption, unavailable/read-only selections,
+mixed-provider composer models and effort, mobile composer settings, usage waits,
+run selections and override notes, and scheduled retries.
+`AllCoreSurfaces` provides an overview; individual stories expose the expanded
+menus and adoption dialog. Run `pnpm --filter @paperclipai/ui build-storybook`
+to build the preview.
+
+Pool configuration stories belong to the private Cloud plugin's own Storybook
+in `extensions/plugin-connection-pool/storybook/`. Both previews use fictional
+accounts; they do not call live providers or mutate a Paperclip instance.
+Core also owns **Connectors / Pool host** stories for the generic native
+extension. The overview links to Cloud's **In Connectors** preview on port 6010;
+its stories mount these same production routes, header, sidebar and tokens.
+**Full Setup And Management** exercises the complete catalog-to-pool journey.
+Both previews include **Operator Setup Required** for a manually disabled host.
+
+## Full-app browser acceptance
+
+Install the compatible plugin into an isolated, loopback `local_trusted` instance,
+enable the experimental flag, and use a company named for an E2E or test drive
+with two saved, authorized AI accounts. Run:
+
+```sh
+PAPERCLIP_CONNECTION_POOL_E2E=1 \
+AI_CONNECTIONS_TEST_URL=http://127.0.0.1:3100 \
+AI_CONNECTIONS_TEST_COMPANY_ID=<test-company-id> \
+pnpm exec playwright test --config tests/ai-connections-app/playwright.config.ts connection-pools.spec.ts
+```
+
+These opt-in tests exercise the shipped app, installed plugin and database without
+mocking browser routes or pool APIs. They cover catalog navigation, setup, ordering,
+paused defaults, rename, member changes, refresh persistence, stale edits and
+removal. They verify that an operator-enabled host still offers no Experimental
+control for routing. With a test agent already bound to a saved pool, they also verify
+the **Used by** list, avatars and profile links. Cleanup archives only the test's own pool and verifies that existing
+accounts and pools remain intact. This suite does not execute agents or probe
+live usage; provider and restart acceptance remain separate gated test drives.
diff --git a/packages/db/src/connections-v3-schema-core-migration.test.ts b/packages/db/src/connections-v3-schema-core-migration.test.ts
index 4072d63c42..88ec7ceed6 100644
--- a/packages/db/src/connections-v3-schema-core-migration.test.ts
+++ b/packages/db/src/connections-v3-schema-core-migration.test.ts
@@ -38,6 +38,11 @@ describeEmbeddedPostgres("connections v3 schema core migration", () => {
await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`;
// AI defaults arrive in 0273/0277 and depend on the composite grant key
// from 0232. Rewind those tables before recreating the 0182 grant schema.
+ // Router pins/cursors depend on pools, whose composite connection FK also
+ // arrives after 0182. Rewind these empty fixture tables in dependency order.
+ await sql`DROP TABLE IF EXISTS "ai_connection_task_pins"`;
+ await sql`DROP TABLE IF EXISTS "ai_connection_router_cursors"`;
+ await sql`DROP TABLE IF EXISTS "ai_connection_pools"`;
await sql`DROP TABLE IF EXISTS "ai_provider_defaults"`;
await sql`DROP TABLE IF EXISTS "ai_connection_defaults"`;
await sql`DROP TABLE IF EXISTS "connection_grant_delegations"`;
diff --git a/packages/db/src/migrations/0299_absent_ser_duncan.sql b/packages/db/src/migrations/0299_absent_ser_duncan.sql
new file mode 100644
index 0000000000..5f15b95940
--- /dev/null
+++ b/packages/db/src/migrations/0299_absent_ser_duncan.sql
@@ -0,0 +1,64 @@
+CREATE TABLE IF NOT EXISTS "ai_connection_pools" (
+ "id" uuid PRIMARY KEY NOT NULL,
+ "company_id" uuid NOT NULL,
+ "plugin_key" text NOT NULL,
+ "config" jsonb NOT NULL,
+ "revision" integer DEFAULT 1 NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "ai_connection_pools_company_id_uq" UNIQUE("company_id","id")
+);
+--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "ai_connection_router_cursors" (
+ "pool_id" uuid PRIMARY KEY NOT NULL,
+ "company_id" uuid NOT NULL,
+ "last_member_id" text,
+ "version" integer DEFAULT 0 NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "ai_connection_task_pins" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "pool_id" uuid NOT NULL,
+ "agent_id" uuid NOT NULL,
+ "task_key" text NOT NULL,
+ "selection" jsonb NOT NULL,
+ "member" jsonb NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "company_secrets" ADD COLUMN IF NOT EXISTS "ai_session_epoch" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_pools" ADD CONSTRAINT "ai_connection_pools_id_tool_connections_id_fk" FOREIGN KEY ("id") REFERENCES "public"."tool_connections"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_pools" ADD CONSTRAINT "ai_connection_pools_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_pools" ADD CONSTRAINT "ai_connection_pools_company_connection_fk" FOREIGN KEY ("company_id","id") REFERENCES "public"."tool_connections"("company_id","id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_router_cursors" ADD CONSTRAINT "ai_connection_router_cursors_pool_id_ai_connection_pools_id_fk" FOREIGN KEY ("pool_id") REFERENCES "public"."ai_connection_pools"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_router_cursors" ADD CONSTRAINT "ai_connection_router_cursors_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_router_cursors" ADD CONSTRAINT "ai_connection_router_cursors_company_pool_fk" FOREIGN KEY ("company_id","pool_id") REFERENCES "public"."ai_connection_pools"("company_id","id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_task_pins" ADD CONSTRAINT "ai_connection_task_pins_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_task_pins" ADD CONSTRAINT "ai_connection_task_pins_pool_id_ai_connection_pools_id_fk" FOREIGN KEY ("pool_id") REFERENCES "public"."ai_connection_pools"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_task_pins" ADD CONSTRAINT "ai_connection_task_pins_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_task_pins" ADD CONSTRAINT "ai_connection_task_pins_company_pool_fk" FOREIGN KEY ("company_id","pool_id") REFERENCES "public"."ai_connection_pools"("company_id","id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+DO $$ BEGIN
+ALTER TABLE "ai_connection_task_pins" ADD CONSTRAINT "ai_connection_task_pins_company_agent_fk" FOREIGN KEY ("company_id","agent_id") REFERENCES "public"."agents"("company_id","id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "ai_connection_task_pins_affinity_uq" ON "ai_connection_task_pins" USING btree ("company_id","pool_id","agent_id","task_key");
\ No newline at end of file
diff --git a/packages/db/src/migrations/meta/0294_snapshot.json b/packages/db/src/migrations/meta/0299_snapshot.json
similarity index 98%
rename from packages/db/src/migrations/meta/0294_snapshot.json
rename to packages/db/src/migrations/meta/0299_snapshot.json
index c5115c1974..8129db0a20 100644
--- a/packages/db/src/migrations/meta/0294_snapshot.json
+++ b/packages/db/src/migrations/meta/0299_snapshot.json
@@ -1,6 +1,6 @@
{
- "id": "66a0b3c9-91bb-46b8-a868-a6facedbc14b",
- "prevId": "d0c40f4e-c2c5-4efd-bc15-c6ae5632047d",
+ "id": "0eac674e-f69a-4f25-b800-3be01b8fd28d",
+ "prevId": "792dfb38-10bf-4147-a541-5c52ce0e80b6",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -2903,6 +2903,362 @@
},
"isRLSEnabled": false
},
+ "public.ai_connection_pools": {
+ "name": "ai_connection_pools",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plugin_key": {
+ "name": "plugin_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "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": {
+ "ai_connection_pools_id_tool_connections_id_fk": {
+ "name": "ai_connection_pools_id_tool_connections_id_fk",
+ "tableFrom": "ai_connection_pools",
+ "tableTo": "tool_connections",
+ "columnsFrom": [
+ "id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_pools_company_id_companies_id_fk": {
+ "name": "ai_connection_pools_company_id_companies_id_fk",
+ "tableFrom": "ai_connection_pools",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_pools_company_connection_fk": {
+ "name": "ai_connection_pools_company_connection_fk",
+ "tableFrom": "ai_connection_pools",
+ "tableTo": "tool_connections",
+ "columnsFrom": [
+ "company_id",
+ "id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "ai_connection_pools_company_id_uq": {
+ "name": "ai_connection_pools_company_id_uq",
+ "nullsNotDistinct": false,
+ "columns": [
+ "company_id",
+ "id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_connection_router_cursors": {
+ "name": "ai_connection_router_cursors",
+ "schema": "",
+ "columns": {
+ "pool_id": {
+ "name": "pool_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_member_id": {
+ "name": "last_member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "ai_connection_router_cursors_pool_id_ai_connection_pools_id_fk": {
+ "name": "ai_connection_router_cursors_pool_id_ai_connection_pools_id_fk",
+ "tableFrom": "ai_connection_router_cursors",
+ "tableTo": "ai_connection_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_router_cursors_company_id_companies_id_fk": {
+ "name": "ai_connection_router_cursors_company_id_companies_id_fk",
+ "tableFrom": "ai_connection_router_cursors",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_router_cursors_company_pool_fk": {
+ "name": "ai_connection_router_cursors_company_pool_fk",
+ "tableFrom": "ai_connection_router_cursors",
+ "tableTo": "ai_connection_pools",
+ "columnsFrom": [
+ "company_id",
+ "pool_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_connection_task_pins": {
+ "name": "ai_connection_task_pins",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pool_id": {
+ "name": "pool_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_key": {
+ "name": "task_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "selection": {
+ "name": "selection",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "member": {
+ "name": "member",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ai_connection_task_pins_affinity_uq": {
+ "name": "ai_connection_task_pins_affinity_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "pool_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "task_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_connection_task_pins_company_id_companies_id_fk": {
+ "name": "ai_connection_task_pins_company_id_companies_id_fk",
+ "tableFrom": "ai_connection_task_pins",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_task_pins_pool_id_ai_connection_pools_id_fk": {
+ "name": "ai_connection_task_pins_pool_id_ai_connection_pools_id_fk",
+ "tableFrom": "ai_connection_task_pins",
+ "tableTo": "ai_connection_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_task_pins_agent_id_agents_id_fk": {
+ "name": "ai_connection_task_pins_agent_id_agents_id_fk",
+ "tableFrom": "ai_connection_task_pins",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_task_pins_company_pool_fk": {
+ "name": "ai_connection_task_pins_company_pool_fk",
+ "tableFrom": "ai_connection_task_pins",
+ "tableTo": "ai_connection_pools",
+ "columnsFrom": [
+ "company_id",
+ "pool_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_connection_task_pins_company_agent_fk": {
+ "name": "ai_connection_task_pins_company_agent_fk",
+ "tableFrom": "ai_connection_task_pins",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "company_id",
+ "agent_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
"public.ai_provider_defaults": {
"name": "ai_provider_defaults",
"schema": "",
@@ -12347,6 +12703,13 @@
"primaryKey": false,
"notNull": false
},
+ "ai_session_epoch": {
+ "name": "ai_session_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
"latest_version": {
"name": "latest_version",
"type": "integer",
@@ -38918,6 +39281,140 @@
},
"isRLSEnabled": false
},
+ "public.resource_lifecycle_events": {
+ "name": "resource_lifecycle_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint",
+ "primaryKey": true,
+ "notNull": true,
+ "identity": {
+ "type": "always",
+ "name": "resource_lifecycle_events_id_seq",
+ "schema": "public",
+ "increment": "1",
+ "startWith": "1",
+ "minValue": "1",
+ "maxValue": "9223372036854775807",
+ "cache": "1",
+ "cycle": false
+ }
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "resource_lifecycle_events_creation_idx": {
+ "name": "resource_lifecycle_events_creation_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"resource_lifecycle_events\".\"action\" = 'create'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_lifecycle_events_company_idx": {
+ "name": "resource_lifecycle_events_company_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "resource_lifecycle_events_company_id_companies_id_fk": {
+ "name": "resource_lifecycle_events_company_id_companies_id_fk",
+ "tableFrom": "resource_lifecycle_events",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "resource_lifecycle_events_resource_type_check": {
+ "name": "resource_lifecycle_events_resource_type_check",
+ "value": "\"resource_lifecycle_events\".\"resource_type\" IN ('agent', 'project')"
+ },
+ "resource_lifecycle_events_action_check": {
+ "name": "resource_lifecycle_events_action_check",
+ "value": "\"resource_lifecycle_events\".\"action\" = 'create' OR (\"resource_lifecycle_events\".\"resource_type\" = 'agent' AND \"resource_lifecycle_events\".\"action\" IN ('pause', 'resume', 'terminate'))"
+ }
+ },
+ "isRLSEnabled": false
+ },
"public.routine_documents": {
"name": "routine_documents",
"schema": "",
@@ -44497,6 +44994,298 @@
"checkConstraints": {},
"isRLSEnabled": false
},
+ "public.tool_connection_app_snapshots": {
+ "name": "tool_connection_app_snapshots",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_key": {
+ "name": "credential_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "toolkit": {
+ "name": "toolkit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accounts": {
+ "name": "accounts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "error_at": {
+ "name": "error_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "tool_connection_app_snapshots_owner_toolkit_uq": {
+ "name": "tool_connection_app_snapshots_owner_toolkit_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "connection_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "toolkit",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tool_connection_app_snapshots_company_id_companies_id_fk": {
+ "name": "tool_connection_app_snapshots_company_id_companies_id_fk",
+ "tableFrom": "tool_connection_app_snapshots",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tool_connection_app_snapshots_company_connection_fk": {
+ "name": "tool_connection_app_snapshots_company_connection_fk",
+ "tableFrom": "tool_connection_app_snapshots",
+ "tableTo": "tool_connections",
+ "columnsFrom": [
+ "company_id",
+ "connection_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tool_connection_app_syncs": {
+ "name": "tool_connection_app_syncs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_key": {
+ "name": "credential_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lease_id": {
+ "name": "lease_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "checked": {
+ "name": "checked",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "total": {
+ "name": "total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "failed": {
+ "name": "failed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_completed_at": {
+ "name": "last_completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tool_connection_app_syncs_owner_key_uq": {
+ "name": "tool_connection_app_syncs_owner_key_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "connection_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "credential_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tool_connection_app_syncs_company_id_companies_id_fk": {
+ "name": "tool_connection_app_syncs_company_id_companies_id_fk",
+ "tableFrom": "tool_connection_app_syncs",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tool_connection_app_syncs_company_connection_fk": {
+ "name": "tool_connection_app_syncs_company_connection_fk",
+ "tableFrom": "tool_connection_app_syncs",
+ "tableTo": "tool_connections",
+ "columnsFrom": [
+ "company_id",
+ "connection_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
"public.tool_connection_installs": {
"name": "tool_connection_installs",
"schema": "",
@@ -44790,6 +45579,12 @@
"notNull": true,
"default": false
},
+ "agent_instructions": {
+ "name": "agent_instructions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
"config": {
"name": "config",
"type": "jsonb",
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index 3a30520242..e411db2742 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -2080,6 +2080,13 @@
"when": 1791241297512,
"tag": "0298_connection_agent_instructions",
"breakpoints": true
+ },
+ {
+ "idx": 299,
+ "version": "7",
+ "when": 1791248126600,
+ "tag": "0299_absent_ser_duncan",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/ai_connection_routing.ts b/packages/db/src/schema/ai_connection_routing.ts
new file mode 100644
index 0000000000..524e432aa1
--- /dev/null
+++ b/packages/db/src/schema/ai_connection_routing.ts
@@ -0,0 +1,38 @@
+import { foreignKey, integer, jsonb, pgTable, text, timestamp, unique, uniqueIndex, uuid } from "drizzle-orm/pg-core";
+import type { AiConnectionPoolConfig, AiConnectionRouterSelection } from "@paperclipai/shared";
+import { companies } from "./companies.js";
+import { agents } from "./agents.js";
+import { toolConnections } from "./tool_access.js";
+
+export const aiConnectionPools = pgTable("ai_connection_pools", {
+ id: uuid("id").primaryKey().references(() => toolConnections.id, { onDelete: "cascade" }),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ pluginKey: text("plugin_key").notNull(),
+ config: jsonb("config").$type<AiConnectionPoolConfig>().notNull(),
+ revision: integer("revision").notNull().default(1),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
+}, (table) => [
+ unique("ai_connection_pools_company_id_uq").on(table.companyId, table.id),
+ foreignKey({ columns: [table.companyId, table.id], foreignColumns: [toolConnections.companyId, toolConnections.id], name: "ai_connection_pools_company_connection_fk" }).onDelete("cascade"),
+]);
+export const aiConnectionRouterCursors = pgTable("ai_connection_router_cursors", {
+ poolId: uuid("pool_id").primaryKey().references(() => aiConnectionPools.id, { onDelete: "cascade" }),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ lastMemberId: text("last_member_id"),
+ version: integer("version").notNull().default(0),
+}, (table) => [foreignKey({ columns: [table.companyId, table.poolId], foreignColumns: [aiConnectionPools.companyId, aiConnectionPools.id], name: "ai_connection_router_cursors_company_pool_fk" }).onDelete("cascade")]);
+export const aiConnectionTaskPins = pgTable("ai_connection_task_pins", {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ poolId: uuid("pool_id").notNull().references(() => aiConnectionPools.id, { onDelete: "cascade" }),
+ agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }),
+ taskKey: text("task_key").notNull(),
+ selection: jsonb("selection").$type<AiConnectionRouterSelection>().notNull(),
+ member: jsonb("member").$type<AiConnectionPoolConfig["members"][number]>().notNull(),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+}, (table) => [
+ uniqueIndex("ai_connection_task_pins_affinity_uq").on(table.companyId, table.poolId, table.agentId, table.taskKey),
+ foreignKey({ columns: [table.companyId, table.poolId], foreignColumns: [aiConnectionPools.companyId, aiConnectionPools.id], name: "ai_connection_task_pins_company_pool_fk" }).onDelete("cascade"),
+ foreignKey({ columns: [table.companyId, table.agentId], foreignColumns: [agents.companyId, agents.id], name: "ai_connection_task_pins_company_agent_fk" }).onDelete("cascade"),
+]);
diff --git a/packages/db/src/schema/company_secrets.ts b/packages/db/src/schema/company_secrets.ts
index 9ca340d224..6d3a9ddc29 100644
--- a/packages/db/src/schema/company_secrets.ts
+++ b/packages/db/src/schema/company_secrets.ts
@@ -21,6 +21,7 @@ export const companySecrets = pgTable(
externalRef: text("external_ref"),
providerConfigId: uuid("provider_config_id").references(() => companySecretProviderConfigs.id, { onDelete: "set null" }),
providerMetadata: jsonb("provider_metadata").$type<Record<string, unknown>>(),
+ aiSessionEpoch: integer("ai_session_epoch").notNull().default(0),
latestVersion: integer("latest_version").notNull().default(1),
description: text("description"),
lastResolvedAt: timestamp("last_resolved_at", { withTimezone: true }),
diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts
index ce1ebff078..874d13ebff 100644
--- a/packages/db/src/schema/index.ts
+++ b/packages/db/src/schema/index.ts
@@ -219,5 +219,7 @@ export { browserUseSettings, browserUseSessions, browserUseRuns, browserUseBrows
export * from "./company_skill_sources.js";
+
+export * from "./ai_connection_routing.js";
export { toolConnectionAppSnapshots } from "./tool_connection_app_snapshots.js";
export { toolConnectionAppSyncs } from "./tool_connection_app_syncs.js";
diff --git a/packages/plugins/sdk/src/define-plugin.ts b/packages/plugins/sdk/src/define-plugin.ts
index ef5c5dc6f9..947a67cbb5 100644
--- a/packages/plugins/sdk/src/define-plugin.ts
+++ b/packages/plugins/sdk/src/define-plugin.ts
@@ -1,3 +1,4 @@
+import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
/**
* `definePlugin` — the top-level helper for authoring a Paperclip plugin.
*
@@ -345,6 +346,9 @@ export interface PluginDefinition {
*
* Requires `external.objects.read`.
*/
+ /** Propose a member from host-authorized candidates. Requires ai.connections.route. */
+ onRouteAiConnection?(params: AiConnectionRouterRequest): Promise<AiConnectionRouterResult>;
+
onResolveExternalObject?(
params: ResolveExternalObjectParams,
): Promise<PluginExternalObjectResolveResult>;
diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts
index 788247f39a..57f8628117 100644
--- a/packages/plugins/sdk/src/index.ts
+++ b/packages/plugins/sdk/src/index.ts
@@ -451,3 +451,5 @@ export {
export { PluginEnvironmentCreationCleanupError, environmentCreationCleanupErrorData, readEnvironmentCreationCleanupError } from "./environment-creation-cleanup.js";
export type { PluginEnvironmentCreationCleanup } from "./environment-creation-cleanup.js";
+
+export type { AiConnectionPool, AiConnectionPoolConfig, AiConnectionPoolMember, AiConnectionRouterRequest, AiConnectionRouterResult, AiConnectionRouterSelection } from "@paperclipai/shared";
diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts
index 5476c10bec..9c08a45c42 100644
--- a/packages/plugins/sdk/src/protocol.ts
+++ b/packages/plugins/sdk/src/protocol.ts
@@ -1,3 +1,4 @@
+import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
/**
* JSON-RPC 2.0 message types and protocol helpers for the host ↔ worker IPC
* channel.
@@ -1350,6 +1351,7 @@ export interface HostToWorkerMethods {
params: DetectExternalObjectsParams,
result: DetectExternalObjectsResult,
];
+ routeAiConnection: [params: AiConnectionRouterRequest, result: AiConnectionRouterResult];
resolveExternalObject: [
params: ResolveExternalObjectParams,
result: PluginExternalObjectResolveResult,
@@ -1478,6 +1480,7 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[]
"performAction",
"executeTool",
"detectExternalObjects",
+ "routeAiConnection",
"resolveExternalObject",
"refreshExternalObjects",
"environmentValidateConfig",
diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts
index 78d8308a29..0f0d4eb4cf 100644
--- a/packages/plugins/sdk/src/worker-rpc-host.ts
+++ b/packages/plugins/sdk/src/worker-rpc-host.ts
@@ -1,3 +1,4 @@
+import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
import { environmentCreationCleanupErrorData } from "./environment-creation-cleanup.js";
/**
* Worker-side RPC host — runs inside the child process spawned by the host.
@@ -1620,6 +1621,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
return handleExecuteTool(params as ExecuteToolParams);
case "detectExternalObjects":
return handleDetectExternalObjects(params as DetectExternalObjectsParams);
+ case "routeAiConnection":
+ if (!plugin.definition.onRouteAiConnection) throw methodNotImplemented("routeAiConnection");
+ return plugin.definition.onRouteAiConnection(params as AiConnectionRouterRequest);
case "resolveExternalObject":
return handleResolveExternalObject(params as ResolveExternalObjectParams);
case "refreshExternalObjects":
@@ -1736,6 +1740,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
if (plugin.definition.onShutdown) supportedMethods.push("shutdown");
if (plugin.definition.onApiRequest) supportedMethods.push("handleApiRequest");
if (plugin.definition.onDetectExternalObjects) supportedMethods.push("detectExternalObjects");
+ if (plugin.definition.onRouteAiConnection) supportedMethods.push("routeAiConnection");
if (plugin.definition.onResolveExternalObject) supportedMethods.push("resolveExternalObject");
if (plugin.definition.onRefreshExternalObjects) supportedMethods.push("refreshExternalObjects");
if (plugin.definition.onEnvironmentValidateConfig) supportedMethods.push("environmentValidateConfig");
diff --git a/packages/plugins/sdk/tests/worker-rpc-host.test.ts b/packages/plugins/sdk/tests/worker-rpc-host.test.ts
index b504a70362..cce6a3ae1a 100644
--- a/packages/plugins/sdk/tests/worker-rpc-host.test.ts
+++ b/packages/plugins/sdk/tests/worker-rpc-host.test.ts
@@ -1115,3 +1115,25 @@ describe("worker duplex channel dispatch", () => {
}
});
});
+
+
+describe("AI connection router RPC", () => {
+ it("advertises and calls only an implemented routing hook", async () => {
+ const input = new PassThrough(), output = new PassThrough();
+ const reader = createInterface({ input: output });
+ const request = { companyId: "company", taskKey: "task", candidates: [], memberOrder: [] };
+ let received: unknown;
+ const plugin = definePlugin({ async setup() {}, onRouteAiConnection(params) { received = params; return { kind: "selected", memberId: "authorized-member" }; } });
+ const worker = startWorkerRpcHost({ plugin, stdin: input, stdout: output });
+ let sequence = 0;
+ const pending = new Map<string, (value: unknown) => void>();
+ reader.on("line", line => { const response = parseMessage(line); if (isJsonRpcResponse(response)) { pending.get(String(response.id))?.(response); pending.delete(String(response.id)); } });
+ const call = (method: string, params: unknown) => new Promise<JsonRpcResponse>(resolve => { const id = String(++sequence); pending.set(id, value => resolve(value as JsonRpcResponse)); input.write(serializeMessage(createRequest(method, params, id))); });
+ try {
+ const initialized = await call("initialize", { manifest: { id: "fixture.router", apiVersion: 1, version: "1.0.0", displayName: "Router", description: "Fixture", author: "Tests", categories: ["connector"], capabilities: ["ai.connections.route"], entrypoints: {} }, config: {}, databaseNamespace: null });
+ expect((initialized as { result: { supportedMethods: string[] } }).result.supportedMethods).toContain("routeAiConnection");
+ expect((await call("routeAiConnection", request) as { result: unknown }).result).toEqual({ kind: "selected", memberId: "authorized-member" });
+ expect(received).toEqual(request);
+ } finally { worker.stop(); reader.close(); input.destroy(); output.destroy(); }
+ });
+});
diff --git a/packages/shared/src/ai-connection-router.ts b/packages/shared/src/ai-connection-router.ts
new file mode 100644
index 0000000000..9fbd89c385
--- /dev/null
+++ b/packages/shared/src/ai-connection-router.ts
@@ -0,0 +1,96 @@
+import { z } from "zod";
+import { aiConnectionBindingSchema, type AiConnectionBinding } from "./ai-connections.js";
+import type { AiConnectionUsage } from "./ai-connection-usage.js";
+
+export const aiConnectionRouterBindingSchema = z.object({
+ mode: z.literal("router"),
+ connectionId: z.string().uuid(),
+}).strict();
+export const aiRuntimeConnectionBindingSchema = z.union([aiConnectionBindingSchema, aiConnectionRouterBindingSchema]);
+export type AiRuntimeConnectionBinding = z.infer<typeof aiRuntimeConnectionBindingSchema>;
+
+export const aiConnectionPoolMemberSchema = z.object({
+ id: z.string().uuid(),
+ binding: aiConnectionBindingSchema.refine((v) => v.mode !== "responsible_user", "Select an explicit account grant"),
+ profile: z.object({
+ provider: z.enum(["codex", "acpx", "opencode"]),
+ acpxAgent: z.enum(["claude", "grok"]).optional(),
+ model: z.string().trim().min(1).max(256),
+ effort: z.string().trim().min(1).max(32).optional(),
+ }).strict(),
+}).strict();
+export const aiConnectionPoolConfigSchema = z.object({
+ name: z.string().trim().min(1).max(160),
+ enabled: z.boolean().default(false),
+ mode: z.enum(["round_robin", "usage_aware"]).default("round_robin"),
+ thresholdPercent: z.number().int().min(1).max(100).default(90),
+ members: z.array(aiConnectionPoolMemberSchema).min(1).max(100),
+}).strict().superRefine((v, ctx) => {
+ const ids = new Set<string>();
+ const grants = new Set<string>();
+ const connections = new Set<string>();
+ for (const [index, member] of v.members.entries()) {
+ const grant = `${member.binding.connectionId}:${member.binding.grantId}`;
+ if (ids.has(member.id) || grants.has(grant) || connections.has(member.binding.connectionId)) ctx.addIssue({ code: "custom", path: ["members", index], message: "Duplicate pool member" });
+ ids.add(member.id); grants.add(grant); connections.add(member.binding.connectionId);
+ if (member.profile.provider === "acpx" && !member.profile.acpxAgent) ctx.addIssue({ code: "custom", path: ["members", index, "profile"], message: "Choose an ACP harness" });
+ }
+});
+export type AiConnectionPoolMember = z.infer<typeof aiConnectionPoolMemberSchema>;
+export type AiConnectionPoolConfig = z.infer<typeof aiConnectionPoolConfigSchema>;
+export interface AiConnectionPool extends AiConnectionPoolConfig {
+ id: string;
+ companyId: string;
+ pluginKey: string;
+ revision: number;
+}
+/** Host-authorized metadata only. No credentials or raw provider responses. */
+export interface AiConnectionRouterRequest {
+ companyId: string;
+ pool: AiConnectionPool;
+ agentId: string;
+ taskKey: string;
+ lastMemberId: string | null;
+ cursorVersion: number;
+ /** Opaque IDs preserve order without exposing unauthorized account metadata. */
+ memberOrder: string[];
+ pinnedMemberId?: string;
+ candidates: Array<{ member: AiConnectionPoolMember; runtimeConfig: Record<string, unknown>; notes: string[]; usage?: AiConnectionUsage }>;
+ now: string;
+}
+export type AiConnectionRouterResult =
+ | { kind: "selected"; memberId: string; skipped?: Record<string, string> }
+ | { kind: "exhausted"; retryAt: string; skipped: Record<string, string> }
+ | { kind: "unavailable"; skipped: Record<string, string> };
+export interface AiConnectionPoolSaveInput {
+ companyId: string;
+ id?: string;
+ expectedRevision?: number;
+ config: AiConnectionPoolConfig;
+}
+export interface AiConnectionRouterSelection {
+ poolId: string;
+ memberId: string;
+ binding: AiConnectionBinding;
+ runtimeConfig: Record<string, unknown>;
+ notes: string[];
+}
+
+/** Stable, collision-free catalog identity across plugin reinstallations. */
+export function aiConnectionRouterSlug(pluginKey: string): string {
+ return `ai-router-${Array.from(pluginKey, character => character.charCodeAt(0).toString(16).padStart(2, "0")).join("")}`;
+}
+
+export function aiConnectionRouterAppDefinition(pluginKey: string, descriptor: { name: string; description: string }, availability = { available: true } as { available: boolean; reason?: string }): import("./types/app-definition.js").AppDefinition {
+ return {
+ schemaVersion: 1, slug: aiConnectionRouterSlug(pluginKey), ...descriptor,
+ categories: ["ai"], branding: { logoUrl: "/brands/apps/connection-pool.svg" }, urlPatterns: [],
+ aiConnectionRouter: { pluginKey }, availability,
+ methods: [],
+ };
+}
+
+export function aiConnectionRouterPluginKey(connection: { config?: Record<string, unknown> | null }): string | null {
+ const router = connection.config?.aiRouter;
+ return router && typeof router === "object" && "pluginKey" in router && typeof router.pluginKey === "string" ? router.pluginKey : null;
+}
diff --git a/packages/shared/src/ai-connections.ts b/packages/shared/src/ai-connections.ts
index 5917642775..898a5f246e 100644
--- a/packages/shared/src/ai-connections.ts
+++ b/packages/shared/src/ai-connections.ts
@@ -176,6 +176,7 @@ export interface AiManagedConnectionSummary {
}
export interface AiConnectionList {
currentUserId: string;
+ pools?: import("./ai-connection-router.js").AiConnectionPool[];
canManageConnections: boolean;
connections: AiManagedConnectionSummary[];
}
diff --git a/packages/shared/src/app-definitions.test.ts b/packages/shared/src/app-definitions.test.ts
index 0970e05d06..4a050a35b0 100644
--- a/packages/shared/src/app-definitions.test.ts
+++ b/packages/shared/src/app-definitions.test.ts
@@ -25,7 +25,8 @@ import {
SELF_SERVE_MCP_CANDIDATES,
SELF_SERVE_MCP_RESEARCH,
} from "./self-serve-mcp-research.js";
-import { appDefinitionsSchema } from "./validators/app-definition.js";
+import { aiConnectionRouterAppDefinition } from "./ai-connection-router.js";
+import { appDefinitionSchema, appDefinitionsSchema } from "./validators/app-definition.js";
const googleScope = (scope: string) =>
`https://www.googleapis.com/auth/${scope}`;
@@ -1140,3 +1141,12 @@ describe("tool method permission review", () => {
.toEqual(["read-mcp", "read-repos", "contribute-repos", "jobs"]);
});
});
+
+it("validates native pool catalog entries without inventing an authentication method", () => {
+ const entry = aiConnectionRouterAppDefinition("example.pool", { name: "AI connection pool", description: "Use saved connections" });
+ expect(appDefinitionSchema.parse(entry)).toEqual(entry);
+ expect(entry.methods).toEqual([]);
+ expect(appDefinitionSchema.safeParse({ ...entry, aiConnectionRouter: undefined }).success).toBe(false);
+ expect(appDefinitionSchema.safeParse({ ...entry, methods: APP_STORE_DEFINITIONS[0]!.methods }).success).toBe(false);
+ expect(appDefinitionSchema.safeParse({ ...entry, categories: ["developer"] }).success).toBe(false);
+});
diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts
index 61a2b2b5ba..3e83f26313 100644
--- a/packages/shared/src/constants.ts
+++ b/packages/shared/src/constants.ts
@@ -1320,6 +1320,7 @@ export type PluginCategory = (typeof PLUGIN_CATEGORIES)[number];
* @see PLUGIN_SPEC.md §15 — Capability Model
*/
export const PLUGIN_CAPABILITIES = [
+ "ai.connections.route",
// Data Read
"companies.read",
"projects.read",
diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.ts
index 457172b2fa..9f6f23e1a3 100644
--- a/packages/shared/src/feature-catalog.ts
+++ b/packages/shared/src/feature-catalog.ts
@@ -50,6 +50,11 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalog
cloudDefault: false,
selfHostedDefault: false,
},
+ enableAiConnectionRouters: {
+ title: "AI connection routers",
+ description: "Allow experimental plugin connections to choose task-pinned accounts and harnesses.",
+ tier: "managed", cloudDefault: false, selfHostedDefault: false,
+ },
enableNativeRunner: {
title: "Paperclip Runner",
description:
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 5486a3c58f..00f7a8d8e2 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -2789,6 +2789,7 @@ export { EXECUTION_RECONCILIATION_CAUSES, requiresExecutionReconciliation } from
export * from "./agent-appearance.js";
export * from "./ai-connections.js";
+export * from "./ai-connection-router.js";
export * from "./ai-connection-usage.js";
export * from "./types/email.js";
export * from "./validators/email.js";
@@ -2820,6 +2821,8 @@ export * from "./browser-use.js";
export * from "./types/skill-source.js";
export * from "./validators/skill-source.js";
export * from "./github-skill-repository.js";
+
+export { aiConnectionRouterSlug, aiConnectionRouterAppDefinition, aiConnectionRouterPluginKey } from "./ai-connection-router.js";
export { isAppAggregator, aggregatorManagementUrl, aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema, type AggregatorAppSnapshot, type AggregatorAppsResponse, type ArcadeDiscoverySetupInput } from "./aggregator-apps.js";
export * from "./connection-instructions.js";
diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.ts
index 443e61f217..2cbde14d9c 100644
--- a/packages/shared/src/types/agent.ts
+++ b/packages/shared/src/types/agent.ts
@@ -25,7 +25,7 @@ export interface AgentPermissions extends Record<string, unknown> {
}
export type AgentRuntimeConfig = Record<string, unknown> & {
- aiConnection?: import("../ai-connections.js").AiConnectionBinding;
+ aiConnection?: import("../ai-connection-router.js").AiRuntimeConnectionBinding;
};
export type AgentInstructionsBundleMode = "managed" | "external";
diff --git a/packages/shared/src/types/app-definition.ts b/packages/shared/src/types/app-definition.ts
index dc04bbabd7..2e8d2d5c43 100644
--- a/packages/shared/src/types/app-definition.ts
+++ b/packages/shared/src/types/app-definition.ts
@@ -3,7 +3,7 @@ export type AppCategory = "ai"|"analytics"|"commerce"|"communication"|"content"|
export type OAuthRedirectConstraints = "https-or-loopback-http";
export interface FieldDef { key:string; label:string; type:"text"|"password"|"textarea"|"datetime"|"select"|"checkbox"; required?:boolean; advanced?:boolean; hidden?:boolean; placeholder?:string; helperMd?:string; secret?:boolean; prefix?:string; defaultValue?:string|boolean; validation?:{pattern?:string;maxLength?:number}; options?:Array<{value:string;label:string}>; transport?:{location:"query"|"header";name:string;format?:"string"|"csv"|"boolean";omitFalse?:boolean} }
export interface ConnectionMethodDef { ai?: import("../ai-connections.js").AiConnectionMetadata; key:string; label?:string; purpose?:ToolConnectionPurpose; provider?:"slack"|"github"|"discord"|"microsoft-teams"|"telegram"|"agentmail"|"imessage-photon"; transport:ToolConnectionTransport; auth:"oauth"|"api_key"|"none"; oauthStrategy?:"paperclip_cloud_connector"|"paperclip_id_connector"; connectorProfile?:string; oauthClientSecretRequired?:boolean; capabilityProfile?:{key:string;label:string;description?:string}; grantKinds?:ConnectionGrantKind[]; ownershipModes:ToolConnectionOwnership[]; whenToUse:string; defaults?:{serverUrl?:string;serverUrlTemplate?:string;discoveryUrl?:string|null;serviceHost?:string;templateKey?:string;authorizationEndpoint?:string;tokenEndpoint?:string;metadataUrl?:string;scopesHint?:string[];oauthAuthorizationParams?:{access_type?:"offline";prompt?:"consent"};toolArgumentDefaults?:Record<string,unknown>}; tenantFields?:FieldDef[]; extensionFields?:FieldDef[]; configRequirements?:{atLeastOneOf?:string[]}; credentialFields?:FieldDef[]; keyPlacement?:{location:"header"|"query"|"body_json"|"env";name:string;prefix?:string|null}; credentialSources?:{vercelConnect?:{services:string[];principalModes:VercelConnectPrincipalMode[];scopes:string[];header:{name:string;prefix?:string|null}}}; guidanceMd:string; consoleLinks?:{register?:string;keys?:string;settings?:string;docs?:string}; warnings?:string[]; variants?:Array<{key:string;label:string;whenToUse:string;tenantFields?:FieldDef[]}>; riskTier:"S1"|"S2"|"S3"|"S4"; requiredResourceFilters?:string[] }
-export interface AppDefinition { agentInstructions?: import("../connection-instructions.js").ConnectionInstructionTemplate; schemaVersion:1; slug:string; name:string; description:string; categories:AppCategory[]; featured?:boolean; branding:{logoUrl:string;darkLogoUrl?:string;backgroundColor?:string;accentColor?:string}; urlPatterns:string[]; docsUrl?:string; setupPrerequisite?:{title:string;description:string;steps?:string[];actionLabel:string;actionUrl:string}; redirectConstraints?:OAuthRedirectConstraints; methods:ConnectionMethodDef[]; suggestable?:boolean; availability?:{available:boolean;reason?:string;robotEmail?:string}; ownershipAvailability?:Partial<Record<ToolConnectionOwnership,boolean>> }
+export interface AppDefinition { aiConnectionRouter?: { pluginKey: string }; agentInstructions?: import("../connection-instructions.js").ConnectionInstructionTemplate; schemaVersion:1; slug:string; name:string; description:string; categories:AppCategory[]; featured?:boolean; branding:{logoUrl:string;darkLogoUrl?:string;backgroundColor?:string;accentColor?:string}; urlPatterns:string[]; docsUrl?:string; setupPrerequisite?:{title:string;description:string;steps?:string[];actionLabel:string;actionUrl:string}; redirectConstraints?:OAuthRedirectConstraints; methods:ConnectionMethodDef[]; suggestable?:boolean; availability?:{available:boolean;reason?:string;robotEmail?:string}; ownershipAvailability?:Partial<Record<ToolConnectionOwnership,boolean>> }
export type SelfServeMcpAuthMode =
| "dcr"
diff --git a/packages/shared/src/types/instance.ts b/packages/shared/src/types/instance.ts
index 1bb6278d67..c9a6e61c67 100644
--- a/packages/shared/src/types/instance.ts
+++ b/packages/shared/src/types/instance.ts
@@ -46,6 +46,7 @@ export interface InstanceExperimentalSettings {
* Existing native runs ignore later flag changes so they remain recoverable.
*/
enableNativeRunner: boolean;
+ enableAiConnectionRouters: boolean;
/**
* Hide the local environment and run all agents in the platform-managed
* sandbox environment. Run selection refuses local while this is on.
diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts
index 68662753a3..42643d3b00 100644
--- a/packages/shared/src/types/plugin.ts
+++ b/packages/shared/src/types/plugin.ts
@@ -687,6 +687,8 @@ export interface PaperclipPluginManifestV1 {
minimumPaperclipVersion?: PluginMinimumHostVersion;
/** Capabilities this plugin requires from the host. Enforced at runtime. */
capabilities: PluginCapability[];
+ /** Opt into the native pooled-connection catalog, setup, and management UI. */
+ aiConnectionRouter?: { name: string; description: string };
/** Entrypoint paths relative to the package root. */
entrypoints: {
/** Path to the worker entrypoint (required). */
diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts
index 9c2ec1d061..9f023c2b59 100644
--- a/packages/shared/src/validators/agent.ts
+++ b/packages/shared/src/validators/agent.ts
@@ -1,5 +1,5 @@
import { agentAppearanceSchema } from "../agent-appearance.js";
-import { aiConnectionBindingSchema } from "../ai-connections.js";
+import { aiRuntimeConnectionBindingSchema as aiConnectionBindingSchema } from "../ai-connection-router.js";
import { z } from "zod";
import {
AGENT_ICON_NAMES,
diff --git a/packages/shared/src/validators/app-definition.ts b/packages/shared/src/validators/app-definition.ts
index 6cf59f19f9..5e48887fe6 100644
--- a/packages/shared/src/validators/app-definition.ts
+++ b/packages/shared/src/validators/app-definition.ts
@@ -8,5 +8,12 @@ const appBrandAssetUrlSchema=z.string().refine((value)=>{
},{message:"Brand assets must be HTTPS URLs or local /brands/apps SVG/PNG paths"});
const field=z.object({key:z.string().min(1),label:z.string().min(1),type:z.enum(["text","password","textarea","datetime","select","checkbox"]),required:z.boolean().optional(),advanced:z.boolean().optional(),hidden:z.boolean().optional(),placeholder:z.string().optional(),helperMd:z.string().optional(),secret:z.boolean().optional(),prefix:z.string().optional(),defaultValue:z.union([z.string(),z.boolean()]).optional(),validation:z.object({pattern:z.string().optional(),maxLength:z.number().int().positive().optional()}).optional(),options:z.array(z.object({value:z.string(),label:z.string()})).optional(),transport:z.object({location:z.enum(["query","header"]),name:z.string().min(1),format:z.enum(["string","csv","boolean"]).optional(),omitFalse:z.boolean().optional()}).optional()}).superRefine((v,c)=>{if(v.required&&v.type!=="checkbox"&&!v.placeholder)c.addIssue({code:"custom",message:"Required fields need placeholders",path:["placeholder"]});if(v.type==="select"&&(!v.options||v.options.length===0))c.addIssue({code:"custom",message:"Select fields need options",path:["options"]});if(v.hidden&&v.defaultValue===undefined)c.addIssue({code:"custom",message:"Hidden fields need defaults",path:["defaultValue"]})});
export const connectionMethodDefSchema=z.object({key:z.string().min(1),label:z.string().min(1).optional(),purpose:z.union([toolConnectionPurposeSchema,z.literal("ai")]).optional(),provider:z.enum(["slack","github","discord","microsoft-teams","telegram","agentmail","imessage-photon"]).optional(),transport:z.union([toolConnectionTransportSchema,z.literal("runtime_auth")]),ai:aiConnectionMetadataSchema.optional(),auth:z.enum(["oauth","api_key","none"]),oauthStrategy:z.enum(["paperclip_cloud_connector","paperclip_id_connector"]).optional(),connectorProfile:z.string().regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/).optional(),oauthClientSecretRequired:z.boolean().optional(),capabilityProfile:z.object({key:z.string().min(1),label:z.string().min(1),description:z.string().min(1).optional()}).optional(),grantKinds:z.array(connectionGrantKindSchema).min(1).optional(),ownershipModes:z.array(toolConnectionOwnershipSchema).min(1),whenToUse:z.string().min(1),defaults:z.object({serverUrl:z.string().url().optional(),serverUrlTemplate:z.string().regex(/^https:\/\//).optional(),discoveryUrl:z.string().url().nullable().optional(),serviceHost:z.string().optional(),templateKey:z.string().optional(),authorizationEndpoint:z.string().url().optional(),tokenEndpoint:z.string().url().optional(),metadataUrl:z.string().url().optional(),scopesHint:z.array(z.string()).optional(),oauthAuthorizationParams:z.object({access_type:z.literal("offline").optional(),prompt:z.literal("consent").optional()}).optional(),toolArgumentDefaults:z.record(z.string(),z.unknown()).optional()}).optional(),tenantFields:z.array(field).optional(),extensionFields:z.array(field).optional(),configRequirements:z.object({atLeastOneOf:z.array(z.string().min(1)).min(1).optional()}).optional(),credentialFields:z.array(field).optional(),keyPlacement:z.object({location:z.enum(["header","query","body_json","env"]),name:z.string().min(1),prefix:z.string().nullable().optional()}).optional(),credentialSources:z.object({vercelConnect:z.object({services:z.array(z.string().min(1)).min(1),principalModes:z.array(z.enum(["app","user"])).min(1),scopes:z.array(z.string().min(1)).min(1),header:z.object({name:z.string().min(1),prefix:z.string().nullable().optional()})}).optional()}).optional(),guidanceMd:z.string().min(1),consoleLinks:z.object({register:z.string().url().optional(),keys:z.string().url().optional(),settings:z.string().url().optional(),docs:z.string().url().optional()}).optional(),warnings:z.array(z.string()).optional(),variants:z.array(z.object({key:z.string(),label:z.string(),whenToUse:z.string(),tenantFields:z.array(field).optional()})).optional(),riskTier:z.enum(["S1","S2","S3","S4"]),requiredResourceFilters:z.array(z.string()).optional()}).superRefine((v,c)=>{if((v.transport==="runtime_auth")!==Boolean(v.ai))c.addIssue({code:"custom",message:"Runtime authentication requires AI metadata and AI metadata requires runtime_auth",path:["ai"]});if(v.ai&&!AI_CONNECTION_CAPABILITIES[v.ai.provider].methods[v.ai.method])c.addIssue({code:"custom",message:"Unsupported AI sign-in method",path:["ai","method"]});if(v.ai&&v.auth!==(v.ai.method==="subscription"?"oauth":"api_key"))c.addIssue({code:"custom",message:"AI sign-in method must match authentication",path:["auth"]});const purpose=v.purpose??"tool";if((purpose==="ai")!==(v.transport==="runtime_auth"))c.addIssue({code:"custom",message:"AI methods require runtime_auth and runtime_auth requires AI purpose",path:["purpose"]});if(v.transport==="chat_sdk"&&purpose!=="channel")c.addIssue({code:"custom",message:"Chat SDK methods must be channel connections",path:["purpose"]});if(purpose==="channel"&&v.transport!=="chat_sdk"&&!(v.provider==="agentmail"&&v.transport==="rest_api"))c.addIssue({code:"custom",message:"Channel connections must use the Chat SDK transport",path:["transport"]});if(purpose==="channel"&&!v.provider)c.addIssue({code:"custom",message:"Channel connections require a chat provider",path:["provider"]});if(v.auth==="api_key"&&!v.keyPlacement&&purpose!=="channel")c.addIssue({code:"custom",message:"API-key tool methods require keyPlacement",path:["keyPlacement"]});if(v.oauthStrategy&&v.auth!=="oauth")c.addIssue({code:"custom",message:"OAuth strategies require OAuth auth",path:["oauthStrategy"]});if(v.oauthStrategy&&!v.connectorProfile)c.addIssue({code:"custom",message:"Paperclip Cloud connector methods require connectorProfile",path:["connectorProfile"]});if(v.connectorProfile&&!v.oauthStrategy)c.addIssue({code:"custom",message:"connectorProfile requires a Paperclip Cloud OAuth strategy",path:["connectorProfile"]});if(v.credentialSources?.vercelConnect&&(v.transport!=="mcp_remote"||v.auth==="none"))c.addIssue({code:"custom",message:"Vercel Connect requires an authenticated remote MCP method",path:["credentialSources","vercelConnect"]});const keys=new Set([...(v.tenantFields??[]),...(v.extensionFields??[])].map((entry)=>entry.key));for(const key of v.configRequirements?.atLeastOneOf??[])if(!keys.has(key))c.addIssue({code:"custom",message:"Config requirement references an unknown field",path:["configRequirements","atLeastOneOf"]});if(v.defaults?.serverUrl&&v.defaults.serverUrlTemplate)c.addIssue({code:"custom",message:"Use either serverUrl or serverUrlTemplate",path:["defaults"]});for(const placeholder of v.defaults?.serverUrlTemplate?.matchAll(/\{([a-zA-Z0-9_-]+)\}/g)??[])if(!keys.has(placeholder[1]))c.addIssue({code:"custom",message:"Server URL template references an unknown field",path:["defaults","serverUrlTemplate"]})});
-export const appDefinitionSchema=z.object({agentInstructions:connectionInstructionTemplateSchema.optional(),schemaVersion:z.literal(1),slug:z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),name:z.string().min(1),description:z.string().min(1),categories:z.array(z.enum(["ai","analytics","commerce","communication","content","data","developer","productivity","other"])).min(1),featured:z.boolean().optional(),branding:z.object({logoUrl:appBrandAssetUrlSchema,darkLogoUrl:appBrandAssetUrlSchema.optional(),backgroundColor:z.string().optional(),accentColor:z.string().optional()}),urlPatterns:z.array(z.string()),docsUrl:z.string().url().optional(),setupPrerequisite:z.object({title:z.string().min(1),description:z.string().min(1),steps:z.array(z.string().min(1)).min(1).optional(),actionLabel:z.string().min(1),actionUrl:z.string().url()} ).optional(),redirectConstraints:z.enum(["https-or-loopback-http"]).optional(),methods:z.array(connectionMethodDefSchema).min(1),suggestable:z.boolean().optional(),availability:z.object({available:z.boolean(),reason:z.string().optional(),robotEmail:z.string().optional()}).optional(),ownershipAvailability:z.object({platform_shared:z.boolean().optional(),platform_provisioned:z.boolean().optional(),customer:z.boolean().optional(),dcr:z.boolean().optional()}).optional()});
+export const appDefinitionSchema=z.object({agentInstructions:connectionInstructionTemplateSchema.optional(),aiConnectionRouter:z.object({pluginKey:z.string().min(1)}).optional(),schemaVersion:z.literal(1),slug:z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),name:z.string().min(1),description:z.string().min(1),categories:z.array(z.enum(["ai","analytics","commerce","communication","content","data","developer","productivity","other"])).min(1),featured:z.boolean().optional(),branding:z.object({logoUrl:appBrandAssetUrlSchema,darkLogoUrl:appBrandAssetUrlSchema.optional(),backgroundColor:z.string().optional(),accentColor:z.string().optional()}),urlPatterns:z.array(z.string()),docsUrl:z.string().url().optional(),setupPrerequisite:z.object({title:z.string().min(1),description:z.string().min(1),steps:z.array(z.string().min(1)).min(1).optional(),actionLabel:z.string().min(1),actionUrl:z.string().url()} ).optional(),redirectConstraints:z.enum(["https-or-loopback-http"]).optional(),methods:z.array(connectionMethodDefSchema),suggestable:z.boolean().optional(),availability:z.object({available:z.boolean(),reason:z.string().optional(),robotEmail:z.string().optional()}).optional(),ownershipAvailability:z.object({platform_shared:z.boolean().optional(),platform_provisioned:z.boolean().optional(),customer:z.boolean().optional(),dcr:z.boolean().optional()}).optional()}).superRefine((value, ctx) => {
+ if (value.aiConnectionRouter) {
+ if (value.methods.length !== 0) ctx.addIssue({ code: "custom", message: "Pooled connectors use existing connections, not authentication methods", path: ["methods"] });
+ if (!value.categories.includes("ai")) ctx.addIssue({ code: "custom", message: "Pooled connectors must use the AI category", path: ["categories"] });
+ } else if (value.methods.length === 0) {
+ ctx.addIssue({ code: "custom", message: "Connectors require at least one connection method", path: ["methods"] });
+ }
+});
export const appDefinitionsSchema=z.array(appDefinitionSchema).superRefine((v,c)=>{const s=new Set<string>();v.forEach((a,i)=>{if(s.has(a.slug))c.addIssue({code:"custom",message:"Duplicate slug",path:[i,"slug"]});s.add(a.slug)})});
diff --git a/packages/shared/src/validators/instance.ts b/packages/shared/src/validators/instance.ts
index d4c2235af7..90970097a1 100644
--- a/packages/shared/src/validators/instance.ts
+++ b/packages/shared/src/validators/instance.ts
@@ -41,6 +41,7 @@ export const patchInstanceGeneralSettingsSchema = z
export const instanceExperimentalSettingsSchema = z.object({
enableEnvironments: z.boolean().default(false),
enableNativeRunner: z.boolean().default(true),
+ enableAiConnectionRouters: z.boolean().default(false),
enableManagedSandboxOnly: z.boolean().default(false),
enableIsolatedWorkspaces: z.boolean().default(false),
enableIsolatedWorkspacesByDefault: z.boolean().default(false),
diff --git a/packages/shared/src/validators/plugin.test.ts b/packages/shared/src/validators/plugin.test.ts
index 043a048b1e..3c3b46cc9b 100644
--- a/packages/shared/src/validators/plugin.test.ts
+++ b/packages/shared/src/validators/plugin.test.ts
@@ -33,6 +33,11 @@ describe("plugin capability constants", () => {
});
describe("plugin manifest validators", () => {
+ it("requires routing authority for native pooled connector declarations without a custom UI bundle", () => {
+ const manifest = { id: "example.pool", apiVersion: 1, version: "0.1.0", displayName: "Pool", description: "Pool", author: "Tests", categories: ["connector"], entrypoints: { worker: "worker.js" }, aiConnectionRouter: { name: "AI connection pool", description: "Use saved connections" } };
+ expect(pluginManifestV1Schema.safeParse({ ...manifest, capabilities: ["ui.page.register"] }).success).toBe(false);
+ expect(pluginManifestV1Schema.parse({ ...manifest, capabilities: ["ai.connections.route"] }).aiConnectionRouter).toEqual(manifest.aiConnectionRouter);
+ });
it("accepts existing-style plugins that do not request access or authorization capabilities", () => {
const parsed = pluginManifestV1Schema.parse({
id: "paperclip.compat-dashboard",
diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts
index 55a915a069..0024977164 100644
--- a/packages/shared/src/validators/plugin.ts
+++ b/packages/shared/src/validators/plugin.ts
@@ -782,6 +782,7 @@ export const pluginManifestV1Schema = z.object({
"minimumPaperclipVersion must follow semver (e.g. 1.0.0)",
).optional(),
capabilities: z.array(z.enum(PLUGIN_CAPABILITIES)).min(1),
+ aiConnectionRouter: z.object({ name: z.string().trim().min(1).max(100), description: z.string().trim().min(1).max(500) }).strict().optional(),
entrypoints: z.object({
worker: z.string().min(1),
ui: z.string().min(1).optional(),
@@ -835,6 +836,10 @@ export const pluginManifestV1Schema = z.object({
// declare every capability it needs up-front; silently having more features
// than capabilities would cause runtime rejections.
+ if (manifest.aiConnectionRouter && !manifest.capabilities.includes("ai.connections.route")) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "ai.connections.route is required for aiConnectionRouter", path: ["capabilities"] });
+ }
+
// tools require agent.tools.register (PLUGIN_SPEC.md §11)
if (manifest.tools && manifest.tools.length > 0) {
if (!manifest.capabilities.includes("agent.tools.register")) {
diff --git a/server/src/__tests__/agent-hire-ai-connections.test.ts b/server/src/__tests__/agent-hire-ai-connections.test.ts
index d4f28de63d..8fb798e261 100644
--- a/server/src/__tests__/agent-hire-ai-connections.test.ts
+++ b/server/src/__tests__/agent-hire-ai-connections.test.ts
@@ -6,8 +6,8 @@ import express from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-import { agents, companies, companyMemberships, createDb, heartbeatRuns, issues, principalPermissionGrants, toolConnectionInstalls } from "@paperclipai/db";
-import { type AiConnectionBinding } from "@paperclipai/shared";
+import { activityLog, agents, companies, companyMemberships, createDb, heartbeatRuns, issues, plugins, principalPermissionGrants, toolConnectionInstalls } from "@paperclipai/db";
+import { type AiConnectionBinding, type AiConnectionPoolMember, type PaperclipPluginManifestV1 } from "@paperclipai/shared";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { agentRoutes } from "../routes/agents.js";
import { errorHandler } from "../middleware/index.js";
@@ -16,6 +16,9 @@ import { heartbeatService } from "../services/heartbeat.js";
import { getServerAdapter, registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
import { prepareManagedAiRuntime } from "../services/ai-connection-runtime.js";
import { secretService } from "../services/secrets.js";
+import { aiConnectionRouterService } from "../services/ai-connection-router.js";
+import { instanceSettingsService } from "../services/instance-settings.js";
+import { toolAccessService } from "../services/tool-access.js";
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
@@ -67,7 +70,144 @@ function hired(response: request.Response) {
return response.body.agent ?? response.body;
}
+async function poolFixture(f: Awaited<ReturnType<typeof fixture>>, extraMembers: AiConnectionPoolMember[] = []) {
+ await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true });
+ const pluginKey = `fixture.pool-${f.companyId}`;
+ const manifest: PaperclipPluginManifestV1 = { id: pluginKey, apiVersion: 1, version: "0.1.0", displayName: "Pool fixture", description: "Fixture", author: "Tests", categories: ["connector"], capabilities: ["ai.connections.route"], aiConnectionRouter: { name: "AI connection pool", description: "Fixture" }, entrypoints: { worker: "worker.js" } };
+ await db.insert(plugins).values({ pluginKey, packageName: pluginKey, version: "0.1.0", manifestJson: manifest, status: "ready" });
+ const member: AiConnectionPoolMember = { id: randomUUID(), binding: { ...f.account, provider: "openai", method: "api_key", mode: "delegated" }, profile: { provider: "codex", model: "gpt-5.6-sol" } };
+ const pool = await aiConnectionRouterService(db).save(pluginKey, { companyId: f.companyId, config: { name: "Fixture pool", enabled: true, mode: "round_robin", thresholdPercent: 90, members: [member, ...extraMembers] } }, f.userId);
+ return { pool, binding: { mode: "router", connectionId: pool.id } as const, member };
+}
+
describe("agent-created hires use managed AI connections", () => {
+ it.each(["agent-hires", "agents"])("%s inherits a manager's pool without copying legacy credentials", async (endpoint) => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ const secret = await secretService(db).create(f.companyId, {
+ name: "Stale manager credential", provider: "local_encrypted", value: "fixture-legacy-key",
+ });
+ await db.update(agents).set({
+ runtimeConfig: { aiConnection: p.binding },
+ adapterConfig: { env: { OPENAI_API_KEY: { type: "secret_ref", secretId: secret.id } } },
+ }).where(eq(agents.id, f.agentId));
+ const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/${endpoint}`).send({
+ name: "Inherited pool teammate", role: "engineer", adapterType: f.adapterType,
+ }));
+ expect(agent.runtimeConfig.aiConnection).toEqual(p.binding);
+ expect(agent.adapterConfig.env?.OPENAI_API_KEY).toBeUndefined();
+ const installs = await db.select().from(toolConnectionInstalls).where(and(eq(toolConnectionInstalls.companyId, f.companyId), eq(toolConnectionInstalls.targetType, "agent"), eq(toolConnectionInstalls.targetId, agent.id)));
+ expect(installs.map(i => i.connectionId).sort()).toEqual([p.pool.id, f.account.connectionId].sort());
+ });
+
+ it("keeps an inherited pool when copying the caller's native runtime settings", async () => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-5.6-sol", lifecycleMode: "per_turn" }, runtimeConfig: { aiConnection: p.binding } }).where(eq(agents.id, f.agentId));
+ const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({
+ name: "Native pool teammate", role: "engineer", adapterType: "paperclip_runner", inheritRuntimeFrom: "caller",
+ }));
+ expect(agent.runtimeConfig.aiConnection).toEqual(p.binding);
+ expect(agent.adapterConfig).toMatchObject({ provider: "codex", model: "gpt-5.6-sol", lifecycleMode: "per_turn" });
+ });
+
+ it("rejects an inherited pool with no compatible harness instead of dropping its binding", async () => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ await db.update(agents).set({ runtimeConfig: { aiConnection: p.binding } }).where(eq(agents.id, f.agentId));
+ const response = await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Incompatible teammate", role: "engineer", adapterType: "claude_local" });
+ expect(response.status, JSON.stringify(response.body)).toBe(422);
+ expect(response.body.error).toContain("no compatible harness");
+ expect(await db.select().from(agents).where(eq(agents.companyId, f.companyId))).toHaveLength(1);
+ });
+
+ it.each(["OPENAI_API_KEY", "ANTHROPIC_API_KEY"])("pool inheritance honors only the child's own provider auth override (%s)", async (key) => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ await db.update(agents).set({ runtimeConfig: { aiConnection: p.binding } }).where(eq(agents.id, f.agentId));
+ const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Explicit auth teammate", role: "engineer", adapterType: f.adapterType, adapterConfig: { env: { [key]: "fixture-explicit-key" } } }));
+ expect(agent.runtimeConfig.aiConnection).toEqual(key === "OPENAI_API_KEY" ? undefined : p.binding);
+ expect(agent.adapterConfig.env[key]).toEqual({ type: "plain", value: "fixture-explicit-key" });
+ });
+
+ it.each([
+ ["opencode_local", {}, "PAPERCLIP_OPENCODE_PROVIDERS"],
+ ["opencode_local", { model: "anthropic/claude-sonnet-5" }, "OPENCODE_AUTH_JSON"],
+ ["paperclip_runner", { provider: "opencode", model: "anthropic/claude-sonnet-5" }, "OPENCODE_CONFIG_CONTENT"],
+ ] as const)("%s hires with %j keep explicit %s auth outside the managed OpenRouter model catalog", async (adapterType, config, key) => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ await db.update(agents).set({ runtimeConfig: { aiConnection: p.binding } }).where(eq(agents.id, f.agentId));
+ const provider = { npm: "@ai-sdk/anthropic", options: { apiKey: "fixture-explicit-key" }, models: { "claude-sonnet-5": { name: "Claude fixture" } } };
+ const value = JSON.stringify(key === "PAPERCLIP_OPENCODE_PROVIDERS" ? { anthropic: provider }
+ : key === "OPENCODE_CONFIG_CONTENT" ? { provider: { anthropic: provider } }
+ : { anthropic: { type: "api", key: "fixture-explicit-key" } });
+ const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({
+ name: "Independent OpenCode teammate", role: "engineer", adapterType, adapterConfig: { ...config, env: { [key]: value } },
+ }));
+ expect(agent.runtimeConfig.aiConnection).toBeUndefined();
+ expect(agent.adapterConfig.env[key]).toEqual({ type: "plain", value });
+ expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.targetId, agent.id))).toEqual([]);
+ });
+
+ it.each(["agent-hires", "agents"])("%s installs authorized pool members atomically with the new agent", async (endpoint) => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/${endpoint}`).send({ name: "Pool teammate", role: "engineer", adapterType: f.adapterType, reportsTo: f.agentId, runtimeConfig: { aiConnection: p.binding } }));
+ expect(agent.runtimeConfig.aiConnection).toEqual(p.binding);
+ const installs = await db.select().from(toolConnectionInstalls).where(and(eq(toolConnectionInstalls.companyId, f.companyId), eq(toolConnectionInstalls.targetType, "agent"), eq(toolConnectionInstalls.targetId, agent.id)));
+ expect(installs.map(i => i.connectionId).sort()).toEqual([p.pool.id, f.account.connectionId].sort());
+ const [creation] = await db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.entityId, agent.id), eq(activityLog.action, endpoint === "agent-hires" ? "agent.hire_created" : "agent.created")));
+ expect(creation.details).toMatchObject({ aiConnectionPoolId: p.pool.id, aiConnectionMemberInstallIds: [f.account.connectionId] });
+ const runtime = await prepareManagedAiRuntime(db, { companyId: f.companyId, agentId: agent.id, responsibleUserId: f.userId, adapterType: f.adapterType, binding: p.member.binding, config: {} });
+ try { expect(runtime.attribution.connectionId).toBe(f.account.connectionId); } finally { await runtime.cleanup(); }
+ });
+
+ it("rejects a saved pool binding when no member is installed for that agent", async () => {
+ const f = await fixture("openai");
+ const p = await poolFixture(f);
+ await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", principalId: f.userId, permissionKey: "agents:configure" });
+ await db.delete(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.account.connectionId));
+ const response = await request(f.app).patch(`/api/agents/${f.agentId}`).send({ runtimeConfig: { aiConnection: p.binding } });
+ expect(response.status, JSON.stringify(response.body)).toBe(422);
+ expect(response.body.details).toMatchObject({ code: "ai_connection_pool_no_eligible_member" });
+ const [saved] = await db.select().from(agents).where(eq(agents.id, f.agentId));
+ expect(saved.runtimeConfig.aiConnection).toEqual(f.binding);
+ });
+
+ it("does not install a restricted shared connection through pool membership", async () => {
+ const f = await fixture("openai");
+ const otherOwner = `other-${f.companyId}`;
+ await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: otherOwner, membershipRole: "member", status: "active" });
+ const account = await aiConnectionService(db).save(f.companyId, otherOwner, { provider: "openai", method: "api_key", ownership: "shared", name: "Shared credential, restricted installation", apiKey: "fixture", agentIds: [f.agentId], allAgents: false }, "fixture");
+ await toolAccessService(db).replaceConnectionGrantMembers(account.connectionId, account.grantId, [f.userId], { userId: otherOwner });
+ const member: AiConnectionPoolMember = { id: randomUUID(), binding: { ...account, provider: "openai", method: "api_key", mode: "shared" }, profile: { provider: "codex", model: "gpt-5.6-sol" } };
+ const p = await poolFixture(f, [member]);
+ const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agents`).send({ name: "Restricted pool teammate", role: "engineer", adapterType: f.adapterType, runtimeConfig: { aiConnection: p.binding } }));
+ const input = { companyId: f.companyId, userId: f.userId, adapterType: f.adapterType, binding: member.binding };
+ expect((await aiConnectionService(db).select({ ...input, agentId: f.agentId })).connection.id).toBe(account.connectionId);
+ await expect(aiConnectionService(db).select({ ...input, agentId: agent.id })).rejects.toThrow("not permitted for this agent");
+ const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.connectionId));
+ expect(installs.map(i => i.targetId)).toEqual([f.agentId]);
+ });
+
+ it.each([false, true])("rechecks an unchanged pool when the agent harness changes (compatible member: %s)", async (compatible) => {
+ const f = await fixture("openai");
+ const extra: AiConnectionPoolMember[] = [];
+ if (compatible) {
+ const account = await aiConnectionService(db).save(f.companyId, f.userId, { provider: "anthropic", method: "api_key", ownership: "personal", name: "Claude fixture", apiKey: "fixture", allAgents: true, agentIds: [] }, "fixture");
+ extra.push({ id: randomUUID(), binding: { ...account, provider: "anthropic", method: "api_key", mode: "delegated" }, profile: { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-5" } });
+ }
+ const p = await poolFixture(f, extra);
+ await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", principalId: f.userId, permissionKey: "agents:configure" });
+ await db.update(agents).set({ runtimeConfig: { aiConnection: p.binding } }).where(eq(agents.id, f.agentId));
+ const response = await request(f.app).patch(`/api/agents/${f.agentId}`).send({ adapterType: "claude_local", adapterConfig: { model: "claude-sonnet-5" } });
+ expect(response.status, JSON.stringify(response.body)).toBe(compatible ? 200 : 422);
+ const [saved] = await db.select().from(agents).where(eq(agents.id, f.agentId));
+ expect(saved.adapterType).toBe(compatible ? "claude_local" : "codex_local");
+ expect(saved.runtimeConfig.aiConnection).toEqual(p.binding);
+ });
+
for (const operation of ["test", "save"] as const) {
it.each([401, 403, 429, 503, null])(`${operation} changes API-key health only for a provider rejection (status: %s)`, async (status) => {
const f = await fixture("anthropic", "api_key");
diff --git a/server/src/__tests__/ai-connection-router.test.ts b/server/src/__tests__/ai-connection-router.test.ts
new file mode 100644
index 0000000000..b2e13a92e8
--- /dev/null
+++ b/server/src/__tests__/ai-connection-router.test.ts
@@ -0,0 +1,404 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { and, eq } from "drizzle-orm";
+import { createDb, companies, agents, companyMemberships, connectionGrants, plugins, aiConnectionRouterCursors, aiConnectionTaskPins, toolConnections, companySecrets, heartbeatRuns, issues } from "@paperclipai/db";
+import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
+import type { AiConnectionPoolMember, AiConnectionRouterRequest, AiConnectionRouterResult, PaperclipPluginManifestV1 } from "@paperclipai/shared";
+import { aiConnectionRouterService, AiConnectionPoolExhausted, poolMemberRuntimeConfig, applyAiConnectionRouterTaskSettings } from "../services/ai-connection-router.js";
+import { aiConnectionSessionCompatibilityInputs } from "../services/ai-connection-session.js";
+import { projectPaperclipRunnerTaskConfig, resolvePaperclipRunnerNativeProviderInput } from "../services/native-runtime/provider-profile.js";
+import { aiConnectionService } from "../services/ai-connections.js";
+import { instanceSettingsService } from "../services/instance-settings.js";
+import { managedAiSessionFingerprintConfig, prepareManagedAiRuntime } from "../services/ai-connection-runtime.js";
+import { secretService } from "../services/secrets.js";
+import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
+import express from "express";
+import request from "supertest";
+import { toolAccessRoutes } from "../routes/tool-access.js";
+import { aiConnectionRoutes } from "../routes/ai-connections.js";
+import { errorHandler } from "../middleware/index.js";
+import { heartbeatService, buildEffectiveRunSessionConfigMetadata, resolveTaskSessionConfigFreshness } from "../services/heartbeat.js";
+import { connectionIntentService } from "../services/connection-intents.js";
+import { legacyExecutionNeedsReconciliation } from "../services/legacy-execution-recovery.js";
+import { getServerAdapter, registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
+
+let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
+let db: ReturnType<typeof createDb>;
+let home: string;
+const companyId = randomUUID(), otherCompanyId = randomUUID(), agentId = randomUUID(), secondAgentId = randomUUID(), pluginId = randomUUID();
+const pluginKey = "fixture.ai-router";
+const manifest: PaperclipPluginManifestV1 = { id: pluginKey, apiVersion: 1, version: "0.1.0", displayName: "Fixture router", description: "Fixture", author: "Tests", categories: ["connector"], capabilities: ["ai.connections.route"], aiConnectionRouter: { name: "AI connection pool", description: "Use saved connections" }, entrypoints: { worker: "worker.js" } };
+let members: AiConnectionPoolMember[];
+const proposal = vi.fn(async (_id: string, _method: string, request: AiConnectionRouterRequest): Promise<AiConnectionRouterResult> => {
+ const next = (request.memberOrder.indexOf(request.lastMemberId ?? "") + 1) % request.memberOrder.length;
+ const order = request.pinnedMemberId ? [request.pinnedMemberId] : [...request.memberOrder.slice(next), ...request.memberOrder.slice(0, next)];
+ const selected = order.find(id => request.candidates.some(candidate => candidate.member.id === id));
+ return selected ? { kind: "selected", memberId: selected } : { kind: "unavailable", skipped: {} };
+});
+const worker = { isRunning: () => true, call: proposal } as unknown as PluginWorkerManager;
+const defaultProposal = proposal.getMockImplementation()!;
+const service = () => aiConnectionRouterService(db, worker);
+const resolve = (poolId: string, taskKey: string, extra = {}) => service().resolve({ companyId, poolId, agentId, userId: "alice", adapterType: "paperclip_runner", taskKey, ...extra });
+const makePool = async (config = {}) => service().save(pluginKey, { companyId, config: { name: randomUUID(), enabled: true, mode: "round_robin", thresholdPercent: 90, members, ...config } }, "alice");
+beforeAll(async () => {
+ home = await mkdtemp(path.join(os.tmpdir(), "paperclip-router-tests-"));
+ vi.stubEnv("PAPERCLIP_HOME", home); vi.stubEnv("PAPERCLIP_INSTANCE_ID", "router-fixture");
+ database = await startEmbeddedPostgresTestDatabase("paperclip-router-db-"); db = createDb(database.connectionString);
+ await db.insert(companies).values([{ id: companyId, name: "Router fixture", issuePrefix: "RTF" }, { id: otherCompanyId, name: "Other", issuePrefix: "RTO" }]);
+ await db.insert(agents).values([agentId, secondAgentId].map(id => ({ id, companyId, name: "Router agent", adapterType: "paperclip_runner" })));
+ await db.insert(companyMemberships).values(["alice", "bob"].map(principalId => ({ companyId, principalId, principalType: "user", status: "active", membershipRole: "member" })));
+ await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: pluginKey, version: "0.1.0", manifestJson: manifest, status: "ready" });
+ const accounts = aiConnectionService(db);
+ const codex = await accounts.save(companyId, "alice", { provider: "openai", method: "api_key", ownership: "personal", name: "Codex", apiKey: "fixture", agentIds: [], allAgents: true }, "fixture-codex");
+ const claude = await accounts.save(companyId, "alice", { provider: "anthropic", method: "subscription", ownership: "personal", name: "Claude", loginSessionId: "fixture", agentIds: [], allAgents: true }, "fixture-claude");
+ members = [
+ { id: randomUUID(), binding: { mode: "delegated", provider: "openai", method: "api_key", ...codex }, profile: { provider: "codex", model: "gpt-5.6-sol", effort: "low" } },
+ { id: randomUUID(), binding: { mode: "delegated", provider: "anthropic", method: "subscription", ...claude }, profile: { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-5" } },
+ ];
+}, 90000);
+afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
+
+describe("durable, authorized connection routing", () => {
+ it("defaults off and does not expose selectable pools before opt-in", async () => {
+ expect((await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters).toBe(false);
+ expect((await service().catalog())[0]?.availability).toEqual({ available: false, reason: "Ask your instance operator to enable AI connection routing." });
+ await expect(makePool()).rejects.toThrow("instance operator");
+ expect(await service().selectable(companyId, "alice")).toEqual([]);
+ await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true });
+ });
+ it("registers native connectors only for declared installed routers", async () => {
+ const entry = (await service().catalog())[0]!;
+ expect(entry.name).toBe("AI connection pool");
+ expect(entry.aiConnectionRouter).toEqual({ pluginKey });
+ expect(entry.availability?.available).toBe(true);
+ await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, pluginId));
+ try {
+ expect((await service().catalog())[0]?.availability?.available).toBe(false);
+ await db.update(plugins).set({ status: "uninstalled" }).where(eq(plugins.id, pluginId));
+ expect(await service().catalog()).toEqual([]);
+ } finally { await db.update(plugins).set({ status: "ready" }).where(eq(plugins.id, pluginId)); }
+ });
+ it("native connector removal retains durable pins and ordinary updates cannot bypass pool revisions", async () => {
+ const pool = await makePool(); const selected = await resolve(pool.id, "catalog-removal");
+ const app = express(); app.use(express.json());
+ app.use((req, _res, next) => { req.actor = { type: "board", userId: "alice", source: "local_implicit", companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: "owner" }] } as typeof req.actor; next(); });
+ app.use("/api", toolAccessRoutes(db)); app.use("/api", aiConnectionRoutes(db)); app.use(errorHandler);
+ expect((await request(app).patch(`/api/tool-connections/${pool.id}`).send({ name: "Bypass" })).status).toBe(400);
+ expect((await request(app).delete(`/api/tool-connections/${pool.id}`)).status).toBe(400);
+ expect((await request(app).delete(`/api/companies/${companyId}/ai-connection-pools/${pool.id}`).send({ expectedRevision: pool.revision + 1 })).status).toBe(409);
+ expect((await request(app).delete(`/api/companies/${companyId}/ai-connection-pools/${pool.id}`).send({ expectedRevision: pool.revision })).status).toBe(200);
+ expect((await service().list(companyId)).some(row => row.id === pool.id)).toBe(false);
+ expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(1);
+ expect(await resolve(pool.id, "catalog-removal", { persisted: selected })).toEqual(selected);
+ expect((await db.select().from(toolConnections).where(eq(toolConnections.id, members[0]!.binding.connectionId)))[0]?.status).toBe("active");
+ });
+ it("requires company connection management authority on pool configuration routes", async () => {
+ const app = express(); app.use(express.json());
+ let actor = { type: "board", userId: "alice", source: "session", companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: "owner" }] };
+ app.use((req, _res, next) => { req.actor = actor as typeof req.actor; next(); }); app.use("/api", aiConnectionRoutes(db)); app.use(errorHandler);
+ const pool = await makePool(); const url = `/api/companies/${companyId}/ai-connection-pools`;
+ expect((await request(app).get(url)).status).toBe(200);
+ expect((await request(app).get(`/api/companies/${otherCompanyId}/ai-connection-pools`)).status).toBe(403);
+ expect((await request(app).delete(`/api/companies/${otherCompanyId}/ai-connection-pools/${pool.id}`).send({ expectedRevision: pool.revision })).status).toBe(403);
+ actor = { ...actor, memberships: [{ companyId, status: "active", membershipRole: "viewer" }] };
+ expect((await request(app).get(url)).status).toBe(403);
+ expect((await request(app).post(url).send({ pluginKey, config: pool })).status).toBe(403);
+ expect((await request(app).get(`${url}/${pool.id}/inspection`)).status).toBe(403);
+ expect((await request(app).delete(`${url}/${pool.id}`).send({ expectedRevision: pool.revision })).status).toBe(403);
+ actor = { type: "agent", agentId, companyId, source: "agent_jwt" } as unknown as typeof actor;
+ expect((await request(app).get(url)).status).toBe(403);
+ expect((await request(app).delete(`${url}/${pool.id}`).send({ expectedRevision: pool.revision })).status).toBe(403);
+ actor = { type: "board", userId: "alice", source: "session", companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: "owner" }] };
+ expect((await request(app).delete(`${url}/${pool.id}`).send({ expectedRevision: pool.revision + 1 })).status).toBe(409);
+ expect((await request(app).delete(`${url}/${pool.id}`).send({ expectedRevision: pool.revision })).status).toBe(200);
+ expect((await request(app).get(url)).body.some((entry: { id: string }) => entry.id === pool.id)).toBe(false);
+ });
+ it("deletes pools without erasing pins, cursors, or admitted recovery evidence", async () => {
+ const pool = await makePool(); const selected = await resolve(pool.id, "retained");
+ await expect(service().remove(otherCompanyId, pool.id, pool.revision, "alice")).rejects.toThrow("not found");
+ await expect(service().remove(companyId, pool.id, pool.revision + 1, "alice")).rejects.toThrow("reload before deleting");
+ await service().remove(companyId, pool.id, pool.revision, "alice");
+ expect((await service().list(companyId)).some(entry => entry.id === pool.id)).toBe(false);
+ expect((await service().selectable(companyId, "alice")).some(entry => entry.id === pool.id)).toBe(false);
+ expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(1);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(1);
+ await expect(resolve(pool.id, "new")).rejects.toThrow("choose another AI connection");
+ expect(await resolve(pool.id, "retained", { persisted: selected })).toEqual(selected);
+ const { name, enabled, mode, thresholdPercent, members: savedMembers } = pool;
+ await expect(service().save(pluginKey, { companyId, id: pool.id, expectedRevision: pool.revision + 1, config: { name, enabled, mode, thresholdPercent, members: savedMembers } }, "alice")).rejects.toThrow("not found");
+ });
+ it("does not commit a selection when its pool is deleted during a proposal", async () => {
+ const pool = await makePool();
+ proposal.mockImplementationOnce(async () => { await service().remove(companyId, pool.id, pool.revision, "alice"); return { kind: "selected", memberId: members[0]!.id }; });
+ await expect(resolve(pool.id, "deleted-during-selection")).rejects.toThrow("choose another AI connection");
+ expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(0);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(0);
+ });
+ it("allows cleanup while experimental routing and its plugin are disabled", async () => {
+ const pool = await makePool();
+ await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: false });
+ await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, pluginId));
+ try { await expect(service().remove(companyId, pool.id, pool.revision, "alice")).resolves.toEqual({ ok: true }); }
+ finally { await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true }); await db.update(plugins).set({ status: "ready" }).where(eq(plugins.id, pluginId)); }
+ });
+ it("rotates new tasks across qualified backends and retains pins on turns, resets and service restart", async () => {
+ const pool = await makePool();
+ expect((await resolve(pool.id, "one")).memberId).toBe(members[0]!.id);
+ expect((await resolve(pool.id, "two")).memberId).toBe(members[1]!.id);
+ expect((await resolve(pool.id, "one", { overrides: { model: "claude-sonnet-5", modelReasoningEffort: "high" } })).memberId).toBe(members[0]!.id);
+ expect((await aiConnectionRouterService(db, worker).resolve({ companyId, poolId: pool.id, agentId, userId: "alice", adapterType: "paperclip_runner", taskKey: "one" })).memberId).toBe(members[0]!.id);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(2);
+ });
+ it("commits one allocation for duplicate starts and serializes concurrent tasks", async () => {
+ const pool = await makePool();
+ const same = await Promise.all(Array.from({ length: 8 }, () => resolve(pool.id, "duplicate")));
+ expect(new Set(same.map(s => s.memberId)).size).toBe(1);
+ const many = await Promise.all(Array.from({ length: 8 }, (_, n) => resolve(pool.id, `concurrent-${n}`)));
+ expect(many.filter(s => s.memberId === members[0]!.id)).toHaveLength(4);
+ const pins = await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id)); expect(pins).toHaveLength(9);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(9);
+ });
+ it("rolls back both pin and cursor on a failure during commit", async () => {
+ const pool = await makePool();
+ await db.execute(`CREATE FUNCTION fixture_router_crash() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture commit crash'; END $$`);
+ await db.execute(`CREATE TRIGGER fixture_router_crash BEFORE UPDATE ON ai_connection_router_cursors FOR EACH ROW EXECUTE FUNCTION fixture_router_crash()`);
+ try { await expect(resolve(pool.id, "crash")).rejects.toThrow(); } finally { await db.execute(`DROP TRIGGER fixture_router_crash ON ai_connection_router_cursors`); await db.execute(`DROP FUNCTION fixture_router_crash()`); }
+ expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(0);
+ const selected = await resolve(pool.id, "crash"); expect(selected.memberId).toBe(members[0]!.id);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(1);
+ });
+ it("rechecks config revisions after a proposal and preserves removed member snapshots", async () => {
+ const pool = await makePool(); const old = await resolve(pool.id, "existing");
+ const saved = await service().save(pluginKey, { companyId, id: pool.id, expectedRevision: pool.revision, config: { name: "Edited", enabled: true, mode: "round_robin", thresholdPercent: 90, members: [members[1]!] } }, "alice");
+ await expect(service().save(pluginKey, { companyId, id: pool.id, expectedRevision: pool.revision, config: saved }, "alice")).rejects.toThrow();
+ expect((await resolve(pool.id, "existing")).binding).toEqual(old.binding);
+ expect((await resolve(pool.id, "future")).memberId).toBe(members[1]!.id);
+ });
+ it("keeps account and harness pinned through independent composer fallback", async () => {
+ const pool = await makePool();
+ const first = await resolve(pool.id, "composer");
+ const changed = await resolve(pool.id, "composer", { overrides: { model: "claude-sonnet-5", modelReasoningEffort: "high" } });
+ expect(changed.binding).toEqual(first.binding); expect(changed.runtimeConfig).toMatchObject({ provider: "codex", model: "gpt-5.6-sol", modelReasoningEffort: "high" }); expect(changed.notes).toHaveLength(1);
+ const claude = poolMemberRuntimeConfig(members[1]!, "paperclip_runner", { model: "gpt-5.6-sol", modelReasoningEffort: "ultra" });
+ expect(claude.config).toMatchObject({ provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-5" }); expect(claude.notes).toHaveLength(2);
+ const overrides = applyAiConnectionRouterTaskSettings({ model: "claude-sonnet-5", effort: "invalid", cwd: "/fixture" }, changed);
+ const native = resolvePaperclipRunnerNativeProviderInput({ backend: "codex_app_server", adapterConfig: projectPaperclipRunnerTaskConfig("codex_app_server", changed.runtimeConfig, overrides) });
+ expect(native).toMatchObject({ provider: "codex", model: "gpt-5.6-sol", codexReasoningEffort: "high" });
+ expect(overrides).toMatchObject({ cwd: "/fixture" }); expect(overrides).not.toHaveProperty("effort");
+ });
+ it("retries a changed config proposal without advancing the abandoned selection", async () => {
+ const pool = await makePool();
+ proposal.mockImplementationOnce(async () => {
+ await service().save(pluginKey, { companyId, id: pool.id, expectedRevision: pool.revision, config: { name: pool.name, enabled: true, mode: pool.mode, thresholdPercent: pool.thresholdPercent, members: [members[1]!] } }, "alice");
+ return { kind: "selected", memberId: members[0]!.id };
+ });
+ expect((await resolve(pool.id, "revision-conflict")).memberId).toBe(members[1]!.id);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(1);
+ });
+ it("fails closed when the experimental flag changes during a proposal", async () => {
+ const pool = await makePool();
+ proposal.mockImplementationOnce(async () => { await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: false }); return { kind: "selected", memberId: members[0]!.id }; });
+ try { await expect(resolve(pool.id, "disabled-in-flight")).rejects.toThrow("disabled during allocation"); expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(0); }
+ finally { await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true }); }
+ });
+ it("uses only compatible legacy members and makes reassignment an independent pin", async () => {
+ const pool = await makePool();
+ expect((await resolve(pool.id, "legacy", { adapterType: "claude_local" })).memberId).toBe(members[1]!.id);
+ expect((await resolve(pool.id, "legacy", { agentId: secondAgentId, adapterType: "codex_local" })).memberId).toBe(members[0]!.id);
+ const pins = await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id)); expect(pins).toHaveLength(2);
+ });
+ it("adopts a valid existing account and requires explicit reset for an unrelated session", async () => {
+ const pool = await makePool();
+ expect((await resolve(pool.id, "adopt", { requireExisting: true, existingGrantId: members[1]!.binding.grantId })).memberId).toBe(members[1]!.id);
+ await expect(resolve(pool.id, "foreign-session", { requireExisting: true, existingGrantId: randomUUID() })).rejects.toThrow("Reset");
+ expect((await resolve(pool.id, "foreign-session")).memberId).toBe(members[0]!.id);
+ });
+ it("rejects cross-company access and unauthorized plugin proposals", async () => {
+ const pool = await makePool();
+ await expect(resolve(pool.id, "foreign", { companyId: otherCompanyId })).rejects.toThrow();
+ proposal.mockResolvedValueOnce({ kind: "selected", memberId: randomUUID() });
+ await expect(resolve(pool.id, "bad-proposal")).rejects.toThrow("unauthorized");
+ expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(0);
+ });
+ it("does not grant members to another responsible user or move revoked pins", async () => {
+ const pool = await makePool(); const selected = await resolve(pool.id, "revoke");
+ await expect(resolve(pool.id, "revoke", { userId: "bob" })).rejects.toThrow();
+ await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, selected.binding.mode === "responsible_user" ? "" : selected.binding.grantId));
+ try { await expect(resolve(pool.id, "revoke")).rejects.toThrow(); expect((await resolve(pool.id, "new")).memberId).toBe(members[1]!.id); }
+ finally { await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, members[0]!.binding.grantId)); }
+ });
+ it("never probes pure rotation, caches authorized observations, and invalidates on credential change", async () => {
+ const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(JSON.stringify({ five_hour: { utilization: 12 } })));
+ try {
+ const pure = await makePool(); await resolve(pure.id, "pure"); expect(spy).not.toHaveBeenCalled();
+ const aware = await makePool({ mode: "usage_aware", members: [members[1]!] }); await resolve(aware.id, "aware"); expect(spy).toHaveBeenCalledTimes(1); await resolve(aware.id, "aware"); expect(spy).toHaveBeenCalledTimes(1);
+ expect((await service().inspect(companyId, aware.id, "alice"))[members[1]!.id]?.checkedAt).not.toBeNull();
+ const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, members[1]!.binding.grantId)); const ref = grant!.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")!;
+ await secretService(db).rotate(ref.secretId, { value: "fixture-refreshed", preserveAiSessionEpoch: true }, { userId: "alice" });
+ expect((await service().inspect(companyId, aware.id, "alice"))[members[1]!.id]?.checkedAt).toBeNull();
+ await resolve(aware.id, "aware"); expect(spy).toHaveBeenCalledTimes(2);
+ proposal.mockResolvedValueOnce({ kind: "exhausted", retryAt: new Date(Date.now() + 60_000).toISOString(), skipped: {} });
+ await expect(resolve(aware.id, "aware")).rejects.toBeInstanceOf(AiConnectionPoolExhausted);
+ const pins = await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, aware.id)); expect(pins).toHaveLength(1);
+ } finally { spy.mockRestore(); }
+ });
+ it("shares an in-flight usage observation across concurrent allocations", async () => {
+ const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, members[1]!.binding.grantId));
+ const ref = grant!.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")!;
+ await secretService(db).rotate(ref.secretId, { value: "fixture-shared-probe", preserveAiSessionEpoch: true }, { userId: "alice" });
+ const fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async () => {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ return new Response(JSON.stringify({ five_hour: { utilization: 12 } }));
+ });
+ try {
+ const pool = await makePool({ mode: "usage_aware", members: [members[1]!] });
+ await Promise.all(Array.from({ length: 6 }, (_, index) => resolve(pool.id, `shared-probe-${index}`)));
+ expect(fetch).toHaveBeenCalledTimes(1);
+ } finally { fetch.mockRestore(); }
+ });
+ it("expires a usage observation at a reported reset", async () => {
+ const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, members[1]!.binding.grantId));
+ const ref = grant!.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")!;
+ await secretService(db).rotate(ref.secretId, { value: "fixture-reset-cache", preserveAiSessionEpoch: true }, { userId: "alice" });
+ const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(JSON.stringify({ five_hour: { utilization: 12, resets_at: new Date(Date.now() + 200).toISOString() } })));
+ try {
+ const pool = await makePool({ mode: "usage_aware", members: [members[1]!] }); await resolve(pool.id, "reset-cache"); expect(spy).toHaveBeenCalledTimes(1);
+ await new Promise(resolve => setTimeout(resolve, 250)); await resolve(pool.id, "reset-cache"); expect(spy).toHaveBeenCalledTimes(2);
+ } finally { spy.mockRestore(); }
+ });
+ it("treats unfinished probes as unknown within the shared selection budget", async () => {
+ const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, members[1]!.binding.grantId));
+ const ref = grant!.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")!;
+ await secretService(db).rotate(ref.secretId, { value: "fixture-slow-probe", preserveAiSessionEpoch: true }, { userId: "alice" });
+ const spy = vi.spyOn(globalThis, "fetch").mockImplementation(() => new Promise<Response>(() => {}));
+ try { const pool = await makePool({ mode: "usage_aware", members: [members[1]!] }); const start = Date.now(); expect((await resolve(pool.id, "slow-probe")).memberId).toBe(members[1]!.id); expect(Date.now() - start).toBeLessThan(20_000); expect(proposal.mock.calls.at(-1)?.[2].candidates[0]?.usage).toBeUndefined(); }
+ finally { spy.mockRestore(); }
+ }, 25_000);
+ it("persists run-key affinity before policy calls and reuses it across allocation recovery", async () => {
+ await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true, enableWorktreeRunExecution: true });
+ const pool = await makePool({ members: [members[1]!] });
+ const [agent] = await db.insert(agents).values({ companyId, name: "Run-key fixture", adapterType: "claude_local", adapterConfig: { cwd: home, engine: "cli" }, runtimeConfig: { aiConnection: { mode: "router", connectionId: pool.id }, heartbeat: { enabled: false } } }).returning();
+ let affinity: string | undefined;
+ const execute = vi.fn(); registerServerAdapter({ ...getServerAdapter("claude_local"), execute });
+ const heartbeat = heartbeatService(db, { pluginWorkerManager: worker, runtimeEnv: {} });
+ proposal.mockImplementationOnce(async (_id, _method, request) => {
+ const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agent!.id), eq(heartbeatRuns.status, "running")));
+ expect(run?.contextSnapshot?.aiRouterTaskKey).toBe(run?.id);
+ expect(request.taskKey).toBe(run?.id);
+ affinity = run!.id;
+ throw new Error("fixture policy interruption");
+ });
+ try {
+ const run = await heartbeat.wakeup(agent!.id, { source: "on_demand", reason: "manual", triggerDetail: "manual", contextSnapshot: { responsibleUserId: "alice", wakeReason: "manual" } });
+ expect(run).not.toBeNull();
+ await expect.poll(async () => (await heartbeat.getRun(run!.id))?.status, { timeout: 20_000 }).toBe("failed");
+ expect(affinity).toBe(run!.id);
+ expect((await heartbeat.getRun(run!.id))?.contextSnapshot?.aiRouterTaskKey).toBe(affinity);
+ expect(execute).not.toHaveBeenCalled();
+ const input = { agentId: agent!.id, adapterType: "claude_local" };
+ const committed = await resolve(pool.id, affinity!, input);
+ expect(await aiConnectionRouterService(db, worker).resolve({ companyId, poolId: pool.id, agentId: agent!.id, userId: "alice", adapterType: "claude_local", taskKey: affinity! })).toEqual(committed);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(1);
+ expect(await db.select().from(aiConnectionTaskPins).where(eq(aiConnectionTaskPins.poolId, pool.id))).toHaveLength(1);
+ } finally { proposal.mockReset(); proposal.mockImplementation(defaultProposal); unregisterServerAdapter("claude_local"); await heartbeat.drainActiveRunExecutions(); }
+ }, 30_000);
+ it("defers a pinned task before provider work and schedules a retry with its affinity intact", async () => {
+ await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true, enableWorktreeRunExecution: true });
+ const pool = await makePool({ members: [members[1]!] });
+ const [agent] = await db.insert(agents).values({ companyId, name: "Quota fixture", adapterType: "claude_local", adapterConfig: { cwd: home, engine: "cli" }, runtimeConfig: { aiConnection: { mode: "router", connectionId: pool.id }, heartbeat: { enabled: false } } }).returning();
+ const [issue] = await db.insert(issues).values({ companyId, title: "Quota fixture", status: "todo", assigneeAgentId: agent!.id, responsibleUserId: "alice", createdByUserId: "alice" }).returning();
+ const pinned = await resolve(pool.id, issue!.id, { agentId: agent!.id, adapterType: "claude_local" });
+ await service().save(pluginKey, { companyId, id: pool.id, expectedRevision: pool.revision, config: { name: pool.name, enabled: true, mode: "usage_aware", thresholdPercent: 90, members: [members[1]!] } }, "alice");
+ const execute = vi.fn(); registerServerAdapter({ ...getServerAdapter("claude_local"), execute });
+ const fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(JSON.stringify({ five_hour: { utilization: 100 } })));
+ proposal.mockResolvedValueOnce({ kind: "exhausted", retryAt: new Date(Date.now() + 60_000).toISOString(), skipped: { [members[1]!.id]: "Exhausted" } });
+ const heartbeat = heartbeatService(db, { pluginWorkerManager: worker, runtimeEnv: {} });
+ try {
+ const run = await heartbeat.wakeup(agent!.id, { source: "assignment", reason: "issue_assigned", payload: { issueId: issue!.id }, contextSnapshot: { issueId: issue!.id, wakeReason: "issue_assigned", responsibleUserId: "alice" }, triggerDetail: "system" });
+ expect(run).not.toBeNull();
+ await expect.poll(async () => (await heartbeat.getRun(run!.id))?.status, { timeout: 20_000 }).toBe("cancelled");
+ const cancelled = await heartbeat.getRun(run!.id); expect(cancelled?.errorCode).toBe("ai_connection_pool_exhausted");
+ expect(legacyExecutionNeedsReconciliation(cancelled!)).toBe(false);
+ expect(legacyExecutionNeedsReconciliation({ ...cancelled!, resultJson: { executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: true } } })).toBe(true);
+ await expect.poll(async () => (await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agent!.id), eq(heartbeatRuns.scheduledRetryReason, "ai_connection_pool_wait")))).length, { timeout: 5000 }).toBe(1);
+ const [retry] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agent!.id), eq(heartbeatRuns.scheduledRetryReason, "ai_connection_pool_wait")));
+ expect(retry?.contextSnapshot?.aiRouterTaskKey).toBe(issue!.id); expect(retry?.contextSnapshot?.executionRetryAccounting).toMatchObject({ failureRetries: 0 }); expect(execute).not.toHaveBeenCalled();
+ const [pin] = await db.select().from(aiConnectionTaskPins).where(and(eq(aiConnectionTaskPins.poolId, pool.id), eq(aiConnectionTaskPins.agentId, agent!.id))); expect(pin?.selection).toEqual(pinned);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(eq(aiConnectionRouterCursors.poolId, pool.id)); expect(cursor?.version).toBe(1);
+ await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(eq(heartbeatRuns.agentId, agent!.id));
+ } finally { fetch.mockRestore(); proposal.mockReset(); proposal.mockImplementation(defaultProposal); unregisterServerAdapter("claude_local"); await heartbeat.drainActiveRunExecutions(); }
+ }, 30_000);
+ it("repairs the failed pool account without replacing the pool or adopting the configured provider", async () => {
+ const pool = await makePool({ members: [members[1]!] });
+ const [agent] = await db.insert(agents).values({ companyId, name: "Pool repair", adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-5.6-sol" }, runtimeConfig: { aiConnection: { mode: "router", connectionId: pool.id } } }).returning();
+ const [issue] = await db.insert(issues).values({ companyId, title: "Pool repair", status: "in_progress", assigneeAgentId: agent!.id, responsibleUserId: "alice", createdByUserId: "alice" }).returning();
+ const selection = await resolve(pool.id, issue!.id, { agentId: agent!.id });
+ const runtime = await prepareManagedAiRuntime(db, { companyId, agentId: agent!.id, responsibleUserId: "alice", adapterType: "paperclip_runner", config: selection.runtimeConfig, binding: selection.binding });
+ const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent!.id, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: "alice", startedAt: new Date(), contextSnapshot: { issueId: issue!.id, aiRouterTaskKey: issue!.id, aiRouterSelection: selection, aiConnection: { ...runtime!.attribution, identity: runtime!.identity } } }).returning();
+ try {
+ const intents = connectionIntentService(db);
+ const card = await intents.requestForRunAuthFailure(run!.id);
+ expect(card?.service).toBe("anthropic"); expect(card?.state).toBe("needs_user_action");
+ const options = await intents.setupOptions(card!.interactionId!);
+ expect(options.aiConnection).toEqual(selection.binding); expect(options.aiConnectionRequiresAdoption).toBeUndefined();
+ const [failedGrant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, members[1]!.binding.grantId)); expect(failedGrant?.status).toBe("needs_reauthorization");
+ await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, members[1]!.binding.grantId));
+ await db.update(toolConnections).set({ healthStatus: "ok" }).where(eq(toolConnections.id, members[1]!.binding.connectionId));
+ expect(await intents.complete(card!.interactionId!, members[1]!.binding.connectionId, "alice")).toMatchObject({ status: "accepted" });
+ const [savedAgent] = await db.select().from(agents).where(eq(agents.id, agent!.id)); expect(savedAgent?.runtimeConfig.aiConnection).toEqual({ mode: "router", connectionId: pool.id });
+ expect((await resolve(pool.id, issue!.id, { agentId: agent!.id })).binding).toEqual(selection.binding);
+ await db.update(agents).set({ runtimeConfig: { aiConnection: { mode: "router", connectionId: randomUUID() } } }).where(eq(agents.id, agent!.id));
+ await expect(intents.setupOptions(card!.interactionId!)).rejects.toThrow("configuration changed");
+ } finally {
+ await runtime?.cleanup();
+ await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, members[1]!.binding.grantId));
+ await db.update(toolConnections).set({ healthStatus: "ok" }).where(eq(toolConnections.id, members[1]!.binding.connectionId));
+ }
+ });
+ it("rejects disabled routing but recovers server-owned native evidence after disable/uninstall", async () => {
+ const pool = await makePool(); const selected = await resolve(pool.id, "recovery");
+ await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: false });
+ try { await expect(resolve(pool.id, "recovery")).rejects.toMatchObject({ status: 422, details: { code: "ai_connection_router_disabled" } }); expect(await resolve(pool.id, "recovery", { persisted: selected })).toEqual(selected); }
+ finally { await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true }); }
+ await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, pluginId));
+ try { await expect(resolve(pool.id, "new")).rejects.toThrow("plugin"); expect(await resolve(pool.id, "recovery", { persisted: selected })).toEqual(selected); await db.delete(toolConnections).where(eq(toolConnections.id, pool.id)); expect(await resolve(pool.id, "recovery", { persisted: selected })).toEqual(selected); }
+ finally { await db.update(plugins).set({ status: "ready" }).where(eq(plugins.id, pluginId)); }
+ });
+ it("resumes a responsible-user session through a delegated pool using real managed account configurations", async () => {
+ await aiConnectionService(db).setDefault(companyId, "alice", members[0]!.binding.grantId!);
+ const pool = await makePool({ members: [members[0]!] });
+ const selected = await resolve(pool.id, "managed-mode-adoption", { requireExisting: true, existingGrantId: members[0]!.binding.grantId });
+ const directBinding = { mode: "responsible_user" as const, provider: "openai" as const, method: "api_key" as const };
+ const prepare = { companyId, agentId, responsibleUserId: "alice", adapterType: "paperclip_runner", config: selected.runtimeConfig };
+ const before = await prepareManagedAiRuntime(db, { ...prepare, binding: directBinding });
+ const after = await prepareManagedAiRuntime(db, { ...prepare, binding: selected.binding });
+ try {
+ expect(before.config.managedAiConnection.mode).toBe("responsible_user");
+ expect(after.config.managedAiConnection.mode).toBe("delegated");
+ expect(after.sessionIdentity).toBe(before.sessionIdentity);
+ const common = { adapterType: "paperclip_runner", issueOverrides: null, workspaceConfig: {}, environment: {}, environmentEnv: null, projectEnv: null, routineEnv: null, runtimeSkills: [], agentConfigRevision: null };
+ const previous = await buildEffectiveRunSessionConfigMetadata({ ...common, effectiveAdapterConfig: before.config, managedAiHome: before.home, agentRuntimeConfig: { aiConnection: directBinding } });
+ const currentInput = { ...common, effectiveAdapterConfig: after.config, managedAiHome: after.home, agentRuntimeConfig: { aiConnection: { mode: "router", connectionId: pool.id } } };
+ const current = await buildEffectiveRunSessionConfigMetadata(currentInput);
+ const alternatives = aiConnectionSessionCompatibilityInputs({ ...currentInput, originalIssueOverrides: null, binding: selected.binding, router: true, storedIdentity: before.sessionIdentity, sessionIdentity: after.sessionIdentity, credentialIdentity: after.identity, revisions: [] });
+ const compatibleConfigMetadata = await Promise.all(alternatives.map(candidate => buildEffectiveRunSessionConfigMetadata({ ...currentInput, ...candidate })));
+ expect(resolveTaskSessionConfigFreshness({ hasTaskSession: true, configuredModel: String(selected.runtimeConfig.model), taskSessionParams: { __paperclipConfiguredModel: selected.runtimeConfig.model, __paperclipConfigFingerprint: previous.fingerprint, __paperclipConfigFingerprintVersion: previous.version, __paperclipConfigCategoryFingerprints: previous.categoryFingerprints }, configMetadata: current, compatibleConfigMetadata }).reset).toBe(false);
+ } finally { await before.cleanup(); await after.cleanup(); }
+ });
+ it("keeps session identity and fingerprints stable on authenticated refresh, but changes them on manual replacement", async () => {
+ const input = { companyId, agentId, responsibleUserId: "alice", adapterType: "paperclip_runner", binding: members[0]!.binding, config: { provider: "codex", model: "gpt-5.6-sol" } };
+ const first = await prepareManagedAiRuntime(db, input);
+ const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, members[0]!.binding.grantId)); const ref = grant!.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")!;
+ try {
+ await secretService(db).rotate(ref.secretId, { value: "fixture-new-token", preserveAiSessionEpoch: true }, { userId: "alice" });
+ const refreshed = await prepareManagedAiRuntime(db, input);
+ try { expect(refreshed.identity).not.toBe(first.identity); expect(refreshed.sessionIdentity).toBe(first.sessionIdentity); expect(managedAiSessionFingerprintConfig(refreshed.config, refreshed.home)).toEqual(managedAiSessionFingerprintConfig(first.config, first.home)); } finally { await refreshed.cleanup(); }
+ await secretService(db).rotate(ref.secretId, { value: "fixture-replacement" }, { userId: "alice" });
+ const replaced = await prepareManagedAiRuntime(db, input); try { expect(replaced.sessionIdentity).not.toBe(first.sessionIdentity); } finally { await replaced.cleanup(); }
+ const [secret] = await db.select().from(companySecrets).where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.id, ref.secretId))); expect(secret!.aiSessionEpoch).toBeGreaterThan(0);
+ } finally { await first.cleanup(); }
+ });
+});
diff --git a/server/src/__tests__/ai-connection-session.test.ts b/server/src/__tests__/ai-connection-session.test.ts
new file mode 100644
index 0000000000..81bed1e2c4
--- /dev/null
+++ b/server/src/__tests__/ai-connection-session.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from "vitest";
+import { aiConnectionSessionCompatibilityInputs, managedAiSessionIdentityCompatible, aiConnectionOnlyConfigRevision, aiConnectionRevisionMetadata } from "../services/ai-connection-session.js";
+import { buildEffectiveRunSessionConfigMetadata, resolveTaskSessionConfigFreshness } from "../services/heartbeat.js";
+
+const binding = { mode: "shared" as const, provider: "openai" as const, method: "subscription" as const, connectionId: "account", grantId: "grant" };
+const pool = { mode: "router", connectionId: "pool" };
+const sessionIdentity = "grant:alice:0", credentialIdentity = "grant:alice:token";
+const config = { provider: "codex", model: "gpt-5.6-sol", env: { OPENAI_API_KEY: "fixture-token" }, managedAiConnection: { ...binding, identity: credentialIdentity, sessionIdentity } };
+const base = { adapterType: "paperclip_runner", effectiveAdapterConfig: config, agentRuntimeConfig: { aiConnection: pool }, agentConfigRevision: null as unknown, issueOverrides: null as unknown, workspaceConfig: {}, environment: {}, environmentEnv: null, projectEnv: null, routineEnv: null, runtimeSkills: [] };
+type MetadataInput = Parameters<typeof buildEffectiveRunSessionConfigMetadata>[0];
+type CompatibilityInput = Parameters<typeof aiConnectionSessionCompatibilityInputs>[0];
+const revision = (id: string, beforeBinding: unknown, afterBinding: unknown, extra = {}) => ({
+ id, changedKeys: ["runtimeConfig"], createdAt: new Date(`2026-10-02T00:00:0${id.slice(-1)}Z`),
+ beforeConfig: { name: "Agent", runtimeConfig: { aiConnection: beforeBinding }, adapterConfig: { model: "gpt-5.6-sol" } },
+ afterConfig: { name: "Agent", runtimeConfig: { aiConnection: afterBinding }, adapterConfig: { model: "gpt-5.6-sol" }, ...extra },
+});
+
+async function decision(previous: Partial<MetadataInput>, next: Partial<MetadataInput> = {}, compatibility: Partial<CompatibilityInput> = {}, wakeResetReason?: string) {
+ const before = await buildEffectiveRunSessionConfigMetadata({ ...base, ...previous });
+ const afterInput = { ...base, ...next };
+ const after = await buildEffectiveRunSessionConfigMetadata(afterInput);
+ const candidates = aiConnectionSessionCompatibilityInputs({ ...afterInput, originalIssueOverrides: null, binding, router: true, storedIdentity: sessionIdentity, sessionIdentity, credentialIdentity, revisions: [], ...compatibility });
+ const alternatives = await Promise.all(candidates.map(candidate => buildEffectiveRunSessionConfigMetadata({ ...afterInput, ...candidate })));
+ return resolveTaskSessionConfigFreshness({ hasTaskSession: true, configuredModel: String(afterInput.effectiveAdapterConfig.model), taskSessionParams: { __paperclipConfiguredModel: "gpt-5.6-sol", __paperclipConfigFingerprint: before.fingerprint, __paperclipConfigFingerprintVersion: before.version, __paperclipConfigCategoryFingerprints: before.categoryFingerprints }, configMetadata: after, compatibleConfigMetadata: alternatives, wakeResetReason });
+}
+
+describe("AI pool session adoption", () => {
+ it.each([binding, { ...binding, mode: "delegated" }, { mode: "responsible_user", provider: "openai", method: "api_key" }])("preserves the exact existing configuration through a compatible binding change: %j", async aiConnection => {
+ expect((await decision({ agentRuntimeConfig: { aiConnection }, effectiveAdapterConfig: { ...config, managedAiConnection: { ...config.managedAiConnection, mode: aiConnection.mode } } })).reset).toBe(false);
+ });
+ it("bridges only account-binding edits in revision history", async () => {
+ const first = revision("revision-1", null, binding);
+ const adoption = revision("revision-2", binding, pool);
+ expect(aiConnectionOnlyConfigRevision(adoption)).toBe(true);
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(adoption) }, { revisions: [adoption, first] })).reset).toBe(false);
+ });
+ it("handles consecutive binding edits without erasing another configuration revision", async () => {
+ const first = revision("revision-1", null, binding);
+ const adoption = revision("revision-2", binding, { mode: "router", connectionId: "previous-pool" });
+ const switchPool = revision("revision-3", { mode: "router", connectionId: "previous-pool" }, pool);
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(switchPool) }, { revisions: [switchPool, adoption, first] })).reset).toBe(false);
+ });
+ it("retains resets when the same edit also changes unrelated configuration", async () => {
+ const first = revision("revision-1", null, binding);
+ const edit = revision("revision-2", binding, pool, { name: "Renamed agent" });
+ expect(aiConnectionOnlyConfigRevision(edit)).toBe(false);
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(edit) }, { revisions: [edit, first] })).reset).toBe(true);
+ });
+ it("does not bridge a stale revision over a newer runtime settings change", async () => {
+ const first = revision("revision-1", null, binding);
+ const adoption = revision("revision-2", binding, pool);
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentRuntimeConfig: { aiConnection: pool, heartbeat: { enabled: false } }, agentConfigRevision: aiConnectionRevisionMetadata(adoption) }, { revisions: [adoption, first] })).reset).toBe(true);
+ });
+ it.each([
+ { effectiveAdapterConfig: { ...config, model: "gpt-5.6-terra" } },
+ { effectiveAdapterConfig: { ...config, provider: "acpx", acpxAgent: "codex" } },
+ { effectiveAdapterConfig: { ...config, env: { ...config.env, OTHER: "changed" } } },
+ { agentRuntimeConfig: { aiConnection: pool, heartbeat: { maxConcurrentRuns: 2 } } },
+ { workspaceConfig: { effectiveMode: "isolated_workspace" } },
+ ])("preserves normal resets for effective settings changes: %j", async next => {
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding } }, next)).reset).toBe(true);
+ });
+ it("preserves an explicit session reset even when a compatibility fingerprint matches", async () => {
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding } }, {}, {}, "explicit session reset")).reset).toBe(true);
+ });
+ it("migrates a legacy token fingerprint only for the unchanged credential at epoch zero", async () => {
+ const managed = { ...config.managedAiConnection } as Record<string, unknown>; delete managed.sessionIdentity;
+ expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, effectiveAdapterConfig: { ...config, managedAiConnection: managed } }, {}, { storedIdentity: credentialIdentity })).reset).toBe(false);
+ });
+ it("does not treat a changed token or a manual replacement of the same bytes as legacy-compatible", () => {
+ expect(managedAiSessionIdentityCompatible("grant:alice:old-token", sessionIdentity, credentialIdentity)).toBe(false);
+ expect(managedAiSessionIdentityCompatible(credentialIdentity, "grant:alice:1", credentialIdentity)).toBe(false);
+ expect(managedAiSessionIdentityCompatible(sessionIdentity, "grant:alice:1", credentialIdentity)).toBe(false);
+ expect(managedAiSessionIdentityCompatible(sessionIdentity, sessionIdentity, "grant:alice:refreshed-token")).toBe(true);
+ });
+ it("rejects compatibility candidates for a different account or responsible user", () => {
+ const input = { ...base, originalIssueOverrides: null, binding, router: true, sessionIdentity, credentialIdentity, revisions: [] };
+ expect(aiConnectionSessionCompatibilityInputs({ ...input, storedIdentity: "other-grant:alice:0" })).toEqual([]);
+ expect(aiConnectionSessionCompatibilityInputs({ ...input, storedIdentity: "grant:bob:0" })).toEqual([]);
+ });
+});
diff --git a/server/src/__tests__/ai-legacy-compatibility.test.ts b/server/src/__tests__/ai-legacy-compatibility.test.ts
index bc41cd3181..ee9a3e05a6 100644
--- a/server/src/__tests__/ai-legacy-compatibility.test.ts
+++ b/server/src/__tests__/ai-legacy-compatibility.test.ts
@@ -4,11 +4,11 @@ import { mkdtemp, readFile, writeFile, mkdir, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { eq, sql } from "drizzle-orm";
-import { createDb, companies, agents, companyMemberships, adapterAuthSessions, environments, connectionGrants, toolConnections, activityLog } from "@paperclipai/db";
+import { createDb, companies, agents, companyMemberships, adapterAuthSessions, environments, connectionGrants, toolConnections, activityLog, companySecrets } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
import { secretService } from "../services/secrets.js";
import { aiConnectionService } from "../services/ai-connections.js";
-import { prepareManagedAiRuntime } from "../services/ai-connection-runtime.js";
+import { prepareManagedAiRuntime, managedAiSessionFingerprintConfig } from "../services/ai-connection-runtime.js";
import { localAiLoginService } from "../services/local-ai-login.js";
import { readVerifiedLocalAiCredential } from "../services/local-ai-credentials.js";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
@@ -39,12 +39,25 @@ it("reconnect detaches an indexed credential without changing unadopted legacy a
const migration = await readFile(new URL("../../../packages/db/src/migrations/0276_hard_mandroid.sql", import.meta.url), "utf8");
await db.execute(sql.raw(migration.slice(migration.indexOf("DO $$", migration.indexOf("-- Only declared")))));
const connection = (await service.list(companyId, owner)).find(c => c.name === secret.name)!;
+ const input = { companyId, agentId, responsibleUserId: owner, adapterType: "claude_local", binding: { provider: "anthropic", method: "api_key", mode: "delegated", connectionId: connection.id, grantId: connection.grantId } as const, config: {}, allowLegacyValidation: true };
+ const before = await prepareManagedAiRuntime(db, input);
+ await before.cleanup();
const resolve = () => vault.resolveUserSecretValue(companyId, { definitionId: definition.id, responsibleUserId: owner, required: true, version: "latest" }, { companyId, responsibleUserId: owner, actorType: "system" });
expect((await resolve())?.value).toBe("fixture-original");
await service.save(companyId, owner, { provider: "anthropic", method: "api_key", name: connection.name, ownership: "personal", agentIds: [], allAgents: true, connectionId: connection.id, apiKey: "fixture-new-account" }, "fixture-new-account");
expect((await resolve())?.value).toBe("fixture-original");
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, connection.grantId));
expect(grant.credentialSecretRefs[0].secretId).not.toBe(secret.id);
+ const [oldSecret] = await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id));
+ const [newSecret] = await db.select().from(companySecrets).where(eq(companySecrets.id, grant.credentialSecretRefs[0].secretId));
+ expect(oldSecret.aiSessionEpoch).toBe(0);
+ expect(newSecret.aiSessionEpoch).toBe(0);
+ const after = await prepareManagedAiRuntime(db, input);
+ try {
+ expect(after.attribution.grantId).toBe(before.attribution.grantId);
+ expect(after.sessionIdentity).not.toBe(before.sessionIdentity);
+ expect(managedAiSessionFingerprintConfig(after.config, after.home)).not.toEqual(managedAiSessionFingerprintConfig(before.config, before.home));
+ } finally { await after.cleanup(); }
const selected = await service.select({ companyId, agentId, userId: owner, adapterType: "claude_local", binding: { provider: "anthropic", method: "api_key", mode: "responsible_user" } });
expect(await service.credential(selected)).toBe("fixture-new-account");
await service.save(companyId, owner, { provider: "anthropic", method: "api_key", name: connection.name, ownership: "personal", agentIds: [], allAgents: true, connectionId: connection.id, apiKey: "fixture-second" }, "fixture-second");
diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.ts
index 32ce6a2c01..86ed463b3c 100644
--- a/server/src/__tests__/instance-settings-service.test.ts
+++ b/server/src/__tests__/instance-settings-service.test.ts
@@ -20,6 +20,7 @@ describe("instance settings service", () => {
expect(normalizeExperimentalSettings({
enableEnvironments: true,
enableNativeRunner: false,
+ enableAiConnectionRouters: false,
enableManagedSandboxOnly: false,
enableIsolatedWorkspaces: true,
enableIssuePlanDecompositions: true,
@@ -35,6 +36,7 @@ describe("instance settings service", () => {
})).toEqual({
enableEnvironments: true,
enableNativeRunner: false,
+ enableAiConnectionRouters: false,
enableManagedSandboxOnly: false,
enableIsolatedWorkspaces: true,
enableIsolatedWorkspacesByDefault: false,
diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts
index 729b5f4af4..9263c0ba75 100644
--- a/server/src/__tests__/openapi-routes.test.ts
+++ b/server/src/__tests__/openapi-routes.test.ts
@@ -227,6 +227,22 @@ function loadSpecRoutes() {
}
describe("openapi routes", () => {
+ it("documents board-only pool management with revision-checked deletion", () => {
+ const { spec } = loadSpecRoutes();
+ const pools = spec.paths["/api/companies/{companyId}/ai-connection-pools"];
+ const remove = spec.paths["/api/companies/{companyId}/ai-connection-pools/{poolId}"].delete;
+ const inspection = spec.paths["/api/companies/{companyId}/ai-connection-pools/{poolId}/inspection"].get;
+ for (const operation of [pools.get, pools.post, remove, inspection]) {
+ expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
+ }
+ expect(remove.requestBody.required).toBe(true);
+ expect(remove.requestBody.content["application/json"].schema).toMatchObject({
+ required: ["expectedRevision"], additionalProperties: false,
+ properties: { expectedRevision: { type: "integer", minimum: 0, exclusiveMinimum: true } },
+ });
+ expect(Object.keys(remove.responses)).toEqual(expect.arrayContaining(["200", "400", "401", "403", "404", "409"]));
+ });
+
it("documents personal board-only announcements and private responses", () => {
const { spec } = loadSpecRoutes();
const current = spec.paths["/api/announcements/current"].get;
diff --git a/server/src/app.ts b/server/src/app.ts
index d7107c260c..c99839e4fa 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -897,7 +897,7 @@ export async function createApp(
lifecycleManager: lifecycle,
instanceInfo: {
instanceId: opts.instanceId ?? "default",
- hostVersion: opts.hostVersion ?? "0.0.0",
+ hostVersion: opts.hostVersion ?? serverVersion,
deploymentMode: opts.deploymentMode,
deploymentExposure: opts.deploymentExposure,
},
diff --git a/server/src/modules/run-dispatch/adapters/postgres.ts b/server/src/modules/run-dispatch/adapters/postgres.ts
index b882b09bac..adaf1a97ce 100644
--- a/server/src/modules/run-dispatch/adapters/postgres.ts
+++ b/server/src/modules/run-dispatch/adapters/postgres.ts
@@ -127,7 +127,7 @@ function readNonEmptyString(value: unknown): string | null {
function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind {
if (retryReason === MAX_TURN_CONTINUATION_RETRY_REASON) return "max_turn_continuation";
if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair";
- if (retryReason === "ai_connection_busy") return "ai_connection_wait";
+ if ((retryReason === "ai_connection_busy" || retryReason === "ai_connection_pool_wait")) return "ai_connection_wait";
if (retryReason === "native_safe_replacement") return "native_safe_replacement";
return "other";
}
diff --git a/server/src/modules/run-dispatch/domain/wake-context.test.ts b/server/src/modules/run-dispatch/domain/wake-context.test.ts
index 223ee6fb8b..ac6b84eb68 100644
--- a/server/src/modules/run-dispatch/domain/wake-context.test.ts
+++ b/server/src/modules/run-dispatch/domain/wake-context.test.ts
@@ -91,3 +91,8 @@ describe("wake context", () => {
},
);
});
+
+ it("preserves non-assignee pool wait authority", () => {
+ expect(isNonAssigneeWorkspaceBusyRetry("ai_connection_pool_wait", { aiConnectionBusyDeferredWhileAssignee: false })).toBe(true);
+ expect(isNonAssigneeWorkspaceBusyRetry("ai_connection_pool_wait", { aiConnectionBusyDeferredWhileAssignee: true })).toBe(false);
+ });
diff --git a/server/src/modules/run-dispatch/domain/wake-context.ts b/server/src/modules/run-dispatch/domain/wake-context.ts
index b0dd653959..2100b357d9 100644
--- a/server/src/modules/run-dispatch/domain/wake-context.ts
+++ b/server/src/modules/run-dispatch/domain/wake-context.ts
@@ -17,6 +17,7 @@ function readNonEmptyString(value: unknown): string | null {
export const MAX_TURN_CONTINUATION_RETRY_REASON = "max_turns_continuation";
export const WORKSPACE_BUSY_RETRY_REASON = "workspace_busy";
+export const AI_CONNECTION_POOL_WAIT_RETRY_REASON = "ai_connection_pool_wait";
export const AI_CONNECTION_BUSY_RETRY_REASON = "ai_connection_busy";
export const INTERACTION_CONTINUATION_INFRA_RETRY_REASON = "interaction_continuation_infra_retry";
export const INTERACTION_CONTINUATION_INFRA_WAKE_REASON = "interaction_continuation_infra_retry";
@@ -41,7 +42,7 @@ export function isNonAssigneeWorkspaceBusyRetry(
return (
(retryReason === WORKSPACE_BUSY_RETRY_REASON &&
contextSnapshot.workspaceBusyDeferredWhileAssignee === false) ||
- (retryReason === AI_CONNECTION_BUSY_RETRY_REASON &&
+ ((retryReason === AI_CONNECTION_BUSY_RETRY_REASON || retryReason === AI_CONNECTION_POOL_WAIT_RETRY_REASON) &&
contextSnapshot.aiConnectionBusyDeferredWhileAssignee === false)
);
}
diff --git a/server/src/modules/run-dispatch/index.ts b/server/src/modules/run-dispatch/index.ts
index d6fda59345..d29b078323 100644
--- a/server/src/modules/run-dispatch/index.ts
+++ b/server/src/modules/run-dispatch/index.ts
@@ -13,6 +13,7 @@ export {
MAX_TURN_CONTINUATION_RETRY_REASON,
WORKSPACE_BUSY_RETRY_REASON,
AI_CONNECTION_BUSY_RETRY_REASON,
+ AI_CONNECTION_POOL_WAIT_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
WAKE_COMMENT_IDS_KEY,
diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts
index 11fdc1ab3c..93ab497d32 100644
--- a/server/src/routes/agents.ts
+++ b/server/src/routes/agents.ts
@@ -1,3 +1,4 @@
+import { aiConnectionRouterService, poolMemberRuntimeConfig } from "../services/ai-connection-router.js";
import { connectionIntentService } from "../services/connection-intents.js";
import { completeConnectionIntentSchema } from "@paperclipai/shared";
import { agentFileStore, agentFileTokenFromHash } from "../services/agent-file-store.js";
@@ -5,7 +6,7 @@ import { pipeline } from "node:stream/promises";
import { resolveAgentAppearance, agentAvatarUrl } from "@paperclipai/shared";
import { listOpenRouterModels } from "../services/openrouter-models.js";
import { prepareManagedAiRuntime, assertManagedAiProjectAuth, stripAiAuthBindings } from "../services/ai-connection-runtime.js";
-import { ADAPTER_AUTH_MISSING_CHECK_CODE, AI_CONNECTION_CAPABILITIES, aiConnectionBindingSchema, type AiConnectionBinding } from "@paperclipai/shared";
+import { ADAPTER_AUTH_MISSING_CHECK_CODE, AI_CONNECTION_CAPABILITIES, aiConnectionBindingSchema, type AiConnectionBinding, aiRuntimeConnectionBindingSchema, type AiRuntimeConnectionBinding } from "@paperclipai/shared";
import { toolConnections } from "@paperclipai/db";
import { aiConnectionService } from "../services/ai-connections.js";
import { defaultAiConnectionForHire } from "../services/agent-ai-connection-default.js";
@@ -2599,7 +2600,7 @@ export function agentRoutes(
const parent = await svc.getById(req.actor.agentId);
if (!parent || parent.companyId !== companyId || parent.adapterType !== adapterType) return noInheritance;
// Managed parents must not pass stale legacy credential references to hires.
- if (aiConnectionBindingSchema.safeParse(parent.runtimeConfig.aiConnection).success) return noInheritance;
+ if (aiRuntimeConnectionBindingSchema.safeParse(parent.runtimeConfig.aiConnection).success) return noInheritance;
const parentEnv = asRecord(asRecord(parent.adapterConfig)?.env);
if (!parentEnv) return noInheritance;
@@ -3241,6 +3242,21 @@ export function agentRoutes(
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
const type = assertKnownAdapterType(req.params.type as string);
+ const poolId = asNonEmptyString(req.query.poolId);
+ if (poolId) {
+ const pool = (await aiConnectionRouterService(db).selectable(companyId, getActorInfo(req).actorId)).find(pool => pool.id === poolId);
+ if (!pool) throw unprocessable("Enable an accessible AI connection pool");
+ const catalog = new Map<string, { id: string; label: string }>();
+ for (const member of pool.members) {
+ const memberAdapter = member.binding.provider === "openai" ? "codex_local" : member.binding.provider === "anthropic" ? "claude_local" : member.binding.provider === "xai" ? "grok_local" : "opencode_local";
+ const models = [{ id: member.profile.model, label: member.profile.model }, ...await listAdapterModels(memberAdapter)];
+ for (const model of models) {
+ try { poolMemberRuntimeConfig({ ...member, profile: { ...member.profile, model: model.id } }, type); catalog.set(model.id, model); } catch { /* Only qualified profiles belong in the pool catalog. */ }
+ }
+ }
+ res.json([...catalog.values()]);
+ return;
+ }
const refresh = typeof req.query.refresh === "string"
? ["1", "true", "yes"].includes(req.query.refresh.toLowerCase())
: false;
@@ -3379,7 +3395,33 @@ export function agentRoutes(
return result;
}
- async function validateManagedAgentBinding(req: Request, companyId: string, agentId: string, adapterType: string, config: Record<string, unknown>, binding: AiConnectionBinding, environmentId: string | null | undefined, test: boolean, newAgent = false) {
+ async function validateManagedAgentBinding(req: Request, companyId: string, agentId: string, adapterType: string, config: Record<string, unknown>, binding: AiRuntimeConnectionBinding, environmentId: string | null | undefined, test: boolean, newAgent = false) {
+ if (binding.mode === "router") {
+ const settings = await import("../services/instance-settings.js");
+ if (!(await settings.instanceSettingsService(db).getExperimental()).enableAiConnectionRouters) throw unprocessable("Ask your instance operator to enable AI connection routing.");
+ const pool = (await aiConnectionRouterService(db).selectable(companyId, responsibleUserForAiRequest(req) ?? "")).find((p) => p.id === binding.connectionId && p.enabled);
+ if (!pool) throw unprocessable("Enable the selected connection pool");
+ const userId = responsibleUserForAiRequest(req);
+ const memberConnectionIds = new Set<string>();
+ let compatible = false;
+ for (const member of pool.members) {
+ let runtime: ReturnType<typeof poolMemberRuntimeConfig>;
+ try { runtime = poolMemberRuntimeConfig(member, adapterType); } catch { continue; }
+ compatible = true;
+ const allowUninstalledShared = newAgent && await canInstallSharedAiConnectionForNewAgent(db, req, companyId, member.binding);
+ try {
+ const selection = await aiConnectionService(db).select({ companyId, agentId, userId, adapterType, binding: member.binding,
+ model: runtime.config.model, runnerProvider: runtime.config.provider, acpxAgent: runtime.config.acpxAgent,
+ allowUninstalledPersonal: newAgent, allowUninstalledShared });
+ memberConnectionIds.add(selection.connection.id);
+ } catch (error) {
+ if (!(error instanceof HttpError && [403, 422].includes(error.status))) throw error;
+ }
+ }
+ if (!compatible) throw unprocessable("This pool has no compatible harness");
+ if (!memberConnectionIds.size) throw unprocessable("Install or repair a compatible pool member for this agent.", { code: "ai_connection_pool_no_eligible_member" });
+ return { connectionId: pool.id, ...(newAgent ? { memberConnectionIds: [...memberConnectionIds] } : {}) };
+ }
const userId = responsibleUserForAiRequest(req);
const allowUninstalledShared = newAgent && await canInstallSharedAiConnectionForNewAgent(db, req, companyId, binding);
const selection = await aiConnectionService(db).select({ companyId, agentId, userId, adapterType, model: config.model, runnerProvider: config.provider, acpxAgent: config.acpxAgent, binding, allowUninstalledPersonal: newAgent, allowUninstalledShared, allowLegacyValidation: test }).catch((error: unknown) => {
@@ -3409,7 +3451,7 @@ export function agentRoutes(
if (selection.connection.config.aiLegacyAdoption === true) await db.update(toolConnections).set({ healthStatus: "ok", config: { ...selection.connection.config, aiLegacyAdoption: false }, updatedAt: new Date() }).where(eq(toolConnections.id, selection.connection.id));
} finally { try { await managed?.cleanup(); } finally { await target.release("released"); } }
}
- return selection.connection.id;
+ return { connectionId: selection.connection.id };
}
router.post(
@@ -3422,7 +3464,8 @@ export function agentRoutes(
const adapter = requireServerAdapter(type);
- const aiBinding = req.body.aiConnection ? aiConnectionBindingSchema.parse(req.body.aiConnection) : undefined;
+ const requestedBinding = req.body.aiConnection ? aiRuntimeConnectionBindingSchema.parse(req.body.aiConnection) : undefined;
+ const aiBinding = requestedBinding?.mode === "router" ? undefined : requestedBinding;
if (aiBinding && req.body.testCredentials && Object.keys(req.body.testCredentials).length) throw unprocessable("A managed connection test cannot override its credentials");
const inputAdapterConfig = aiBinding ? { ...req.body.adapterConfig, env: stripAiAuthBindings(req.body.adapterConfig?.env) } : (req.body?.adapterConfig ?? {}) as Record<string, unknown>;
const savedAgentId = typeof req.body.agentId === "string" ? req.body.agentId : null;
@@ -3434,6 +3477,12 @@ export function agentRoutes(
if (savedAgent.companyId !== companyId) throw notFound("Agent not found");
await assertCanUpdateAgent(req, savedAgent);
}
+ const poolBinding = requestedBinding ?? (savedAgent?.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(savedAgent.runtimeConfig.aiConnection) : undefined);
+ if (poolBinding?.mode === "router") {
+ await validateManagedAgentBinding(req, companyId, savedAgentId ?? "", type, req.body.adapterConfig ?? {}, poolBinding, req.body.environmentId, false, !savedAgentId);
+ res.json({ adapterType: type, status: "warn", testedAt: new Date().toISOString(), checks: [{ code: "ai_connection_pool_task_test_required", level: "warn", message: "Pool configuration is available. Run a task to verify the selected account and harness; this preview does not allocate a task or contact a provider." }] });
+ return;
+ }
const requestedEnvironmentId = await resolveAdapterTestEnvironmentId(
companyId,
// Omission tests the saved selection. Explicit null tests a prospective
@@ -4632,8 +4681,8 @@ export function agentRoutes(
const requiresApproval = company.requireBoardApprovalForNewAgents;
const status = requiresApproval ? "pending_approval" : "idle";
- const managedHireBinding = normalizedHireInput.runtimeConfig?.aiConnection ? aiConnectionBindingSchema.parse(normalizedHireInput.runtimeConfig.aiConnection) : undefined;
- const managedHireConnectionId = managedHireBinding ? await validateManagedAgentBinding(req, companyId, hiredAgentId, normalizedHireInput.adapterType, normalizedHireInput.adapterConfig, managedHireBinding, normalizedHireInput.defaultEnvironmentId, false, true) : undefined;
+ const managedHireBinding = normalizedHireInput.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(normalizedHireInput.runtimeConfig.aiConnection) : undefined;
+ const managedHireConnection = managedHireBinding ? await validateManagedAgentBinding(req, companyId, hiredAgentId, normalizedHireInput.adapterType, normalizedHireInput.adapterConfig, managedHireBinding, normalizedHireInput.defaultEnvironmentId, false, true) : undefined;
const createdAgent = await svc.create(
companyId,
{
@@ -4644,7 +4693,7 @@ export function agentRoutes(
lastHeartbeatAt: null,
},
{
- aiConnectionInstall: managedHireConnectionId ? { connectionId: managedHireConnectionId, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
+ aiConnectionInstall: managedHireConnection ? { ...managedHireConnection, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
claudeLogin: {
storedSessionId: hireStoredSessionId ?? null,
ownerUserId: req.actor.type === "agent" ? null : (req.actor.userId ?? null),
@@ -4755,6 +4804,7 @@ export function agentRoutes(
issueIds: sourceIssueIds,
desiredSkills: desiredSkillAssignment.desiredSkills,
hireFingerprint: requestFingerprint,
+ ...(managedHireConnection?.memberConnectionIds ? { aiConnectionPoolId: managedHireConnection.connectionId, aiConnectionMemberInstallIds: managedHireConnection.memberConnectionIds } : {}),
},
});
const telemetryClient = getTelemetryClient();
@@ -4881,8 +4931,8 @@ export function agentRoutes(
allowedSandboxProviders: allowedSandboxProvidersForAgent(createInput.adapterType),
});
- const managedBinding = normalizedRuntimeConfig.aiConnection ? aiConnectionBindingSchema.parse(normalizedRuntimeConfig.aiConnection) : undefined;
- const managedConnectionId = managedBinding ? await validateManagedAgentBinding(req, companyId, agentId, createInput.adapterType, normalizedAdapterConfig, managedBinding, createInput.defaultEnvironmentId, false, true) : undefined;
+ const managedBinding = normalizedRuntimeConfig.aiConnection ? aiRuntimeConnectionBindingSchema.parse(normalizedRuntimeConfig.aiConnection) : undefined;
+ const managedConnection = managedBinding ? await validateManagedAgentBinding(req, companyId, agentId, createInput.adapterType, normalizedAdapterConfig, managedBinding, createInput.defaultEnvironmentId, false, true) : undefined;
const createdAgent = await svc.create(
companyId,
{
@@ -4895,7 +4945,7 @@ export function agentRoutes(
lastHeartbeatAt: null,
},
{
- aiConnectionInstall: managedConnectionId ? { connectionId: managedConnectionId, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
+ aiConnectionInstall: managedConnection ? { ...managedConnection, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
claudeLogin: {
storedSessionId: createStoredSessionId ?? null,
ownerUserId: req.actor.type === "agent" ? null : (req.actor.userId ?? null),
@@ -4932,6 +4982,7 @@ export function agentRoutes(
name: agent.name,
role: agent.role,
desiredSkills: desiredSkillAssignment.desiredSkills,
+ ...(managedConnection?.memberConnectionIds ? { aiConnectionPoolId: managedConnection.connectionId, aiConnectionMemberInstallIds: managedConnection.memberConnectionIds } : {}),
},
});
const telemetryClient = getTelemetryClient();
@@ -5410,8 +5461,8 @@ export function agentRoutes(
if (!setup.aiConnectionRequiresAdoption || !setup.aiConnection) throw conflict("The agent’s AI configuration changed. Reload the task and try again.");
// Probe in the agent's execution environment without installing access.
// The binding, install, audit, and card resolution commit together below.
- const validatedConnectionId = await validateManagedAgentBinding(req, agent.companyId, agent.id, agent.adapterType, agent.adapterConfig, setup.aiConnection, agent.defaultEnvironmentId, true, true);
- if (validatedConnectionId !== connectionId) throw conflict("This is no longer the selected account. Reload the task and try again.");
+ const validatedConnection = await validateManagedAgentBinding(req, agent.companyId, agent.id, agent.adapterType, agent.adapterConfig, setup.aiConnection, agent.defaultEnvironmentId, true, true);
+ if (validatedConnection?.connectionId !== connectionId) throw conflict("This is no longer the selected account. Reload the task and try again.");
res.json(await intents.complete(interactionId, connectionId, userId, {
validatedAdoption: { agentUpdatedAt: agent.updatedAt, binding: setup.aiConnection },
}));
@@ -5560,13 +5611,13 @@ export function agentRoutes(
});
}
if (existing.runtimeConfig.aiConnection && requestedRuntimeConfig && !requestedRuntimeConfig.aiConnection) requestedRuntimeConfig.aiConnection = existing.runtimeConfig.aiConnection;
- const nextAiBinding = aiConnectionBindingSchema.safeParse(requestedRuntimeConfig?.aiConnection ?? existing.runtimeConfig.aiConnection).data;
+ const nextAiBinding = aiRuntimeConnectionBindingSchema.safeParse(requestedRuntimeConfig?.aiConnection ?? existing.runtimeConfig.aiConnection).data;
if (nextAiBinding) {
await assertCanUpdateAgent(req, existing);
const changed = JSON.stringify(nextAiBinding) !== JSON.stringify(existing.runtimeConfig.aiConnection);
const aiConfig = (patchData.adapterConfig ?? existing.adapterConfig) as Record<string, unknown>;
- if (!isAiConnectionCompatible(nextAiBinding, requestedAdapterType, aiConfig.model, aiConfig.provider, aiConfig.acpxAgent)) throw unprocessable("Select an AI connection compatible with the new harness and model");
- if (changed) await validateManagedAgentBinding(req, existing.companyId, existing.id, requestedAdapterType, aiConfig, nextAiBinding, (patchData.defaultEnvironmentId !== undefined ? patchData.defaultEnvironmentId : existing.defaultEnvironmentId) as string | null, true);
+ if (nextAiBinding.mode !== "router" && !isAiConnectionCompatible(nextAiBinding, requestedAdapterType, aiConfig.model, aiConfig.provider, aiConfig.acpxAgent)) throw unprocessable("Select an AI connection compatible with the new harness and model");
+ if (changed || (nextAiBinding.mode === "router" && requestedAdapterType !== existing.adapterType)) await validateManagedAgentBinding(req, existing.companyId, existing.id, requestedAdapterType, aiConfig, nextAiBinding, (patchData.defaultEnvironmentId !== undefined ? patchData.defaultEnvironmentId : existing.defaultEnvironmentId) as string | null, true);
}
if (requestedRuntimeConfig) patchData.runtimeConfig = requestedRuntimeConfig;
if (touchesAdapterConfiguration || Object.prototype.hasOwnProperty.call(patchData, "defaultEnvironmentId")) {
diff --git a/server/src/routes/ai-connections.ts b/server/src/routes/ai-connections.ts
index 335ed8067b..adcb505e5a 100644
--- a/server/src/routes/ai-connections.ts
+++ b/server/src/routes/ai-connections.ts
@@ -22,11 +22,13 @@ import {
type AiProvider,
type AiConnectionBinding,
type AiConnectionList,
+ aiConnectionPoolConfigSchema,
} from "@paperclipai/shared";
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { accessService } from "../services/access.js";
import { logActivity } from "../services/activity-log.js";
+import { aiConnectionRouterService } from "../services/ai-connection-router.js";
import { aiConnectionService } from "../services/ai-connections.js";
import { validate } from "../middleware/validate.js";
@@ -173,6 +175,36 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
const router = Router();
const service = aiConnectionService(db);
const localLogin = localAiLoginService(db);
+ const pools = aiConnectionRouterService(db);
+ router.get("/companies/:companyId/ai-connection-pools", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertBoard(req); assertCompanyAccess(req, companyId);
+ if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
+ res.setHeader("Cache-Control", "no-store");
+ res.json(await pools.list(companyId));
+ });
+ router.get("/companies/:companyId/ai-connection-pools/:poolId/inspection", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertBoard(req); assertCompanyAccess(req, companyId);
+ if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
+ res.setHeader("Cache-Control", "no-store");
+ res.json(await pools.inspect(companyId, z.string().uuid().parse(req.params.poolId), getActorInfo(req).actorId));
+ });
+ router.post("/companies/:companyId/ai-connection-pools", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertBoard(req); assertCompanyAccess(req, companyId);
+ if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
+ const body = z.object({ pluginKey: z.string().min(1).max(160), id: z.string().uuid().optional(), expectedRevision: z.number().int().positive().optional(), config: aiConnectionPoolConfigSchema }).strict().parse(req.body);
+ res.json(await pools.save(body.pluginKey, { ...body, companyId }, getActorInfo(req).actorId));
+ });
+ router.delete("/companies/:companyId/ai-connection-pools/:poolId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertBoard(req); assertCompanyAccess(req, companyId);
+ if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
+ const poolId = z.string().uuid().parse(req.params.poolId);
+ const { expectedRevision } = z.object({ expectedRevision: z.number().int().positive() }).strict().parse(req.body);
+ res.json(await pools.remove(companyId, poolId, expectedRevision, getActorInfo(req).actorId));
+ });
function assertLocalOperator(req: Request) {
assertBoard(req);
assertCompanyAccess(req, req.params.companyId as string);
@@ -216,6 +248,7 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
throw unprocessable("Invalid agent ID");
res.json({
currentUserId,
+ pools: await pools.selectable(companyId, currentUserId),
canManageConnections: await canManageAiConnections(db, req, companyId),
connections: await service.list(
companyId,
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index be92ac52f4..f915180cc8 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -7,6 +7,7 @@ import { Router } from "express";
import { z } from "zod";
import {
createAiConnectionSchema,
+ aiConnectionPoolConfigSchema,
aiConnectionLoginIntentSchema,
localAiConnectionSchema,
localAiLoginStartSchema,
@@ -1353,6 +1354,10 @@ const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/companies/{companyId}/ai-connections/{connectionId}/active-runs",
"GET /api/companies/{companyId}/ai-connections/{connectionId}/usage",
"GET /api/companies/{companyId}/ai-connections/login/{sessionId}",
+ "GET /api/companies/{companyId}/ai-connection-pools",
+ "POST /api/companies/{companyId}/ai-connection-pools",
+ "DELETE /api/companies/{companyId}/ai-connection-pools/{poolId}",
+ "GET /api/companies/{companyId}/ai-connection-pools/{poolId}/inspection",
"GET /api/companies/{companyId}/project-repositories",
"PUT /api/projects/{id}/repositories",
@@ -10384,6 +10389,40 @@ registerCurrentRoute({
// --- AI runtime connections -------------------------------------------------
+registerCurrentRoute({
+ method: "get",
+ path: "/api/companies/{companyId}/ai-connection-pools",
+ tags: ["ai-connections"],
+ summary: "List company AI connection pools for connection managers",
+ responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
+});
+
+registerCurrentRoute({
+ method: "post",
+ path: "/api/companies/{companyId}/ai-connection-pools",
+ tags: ["ai-connections"],
+ summary: "Create or revise an experimental plugin-owned connection pool",
+ body: z.object({ pluginKey: z.string().min(1), id: z.string().uuid().optional(), expectedRevision: z.number().int().positive().optional(), config: aiConnectionPoolConfigSchema }).strict(),
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 422: r.unprocessable },
+});
+
+registerCurrentRoute({
+ method: "delete",
+ path: "/api/companies/{companyId}/ai-connection-pools/{poolId}",
+ tags: ["ai-connections"],
+ summary: "Delete a connection pool while retaining task and run records",
+ body: z.object({ expectedRevision: z.number().int().positive() }).strict(),
+ responses: { 200: r.ok(z.object({ ok: z.literal(true) })), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
+});
+
+registerCurrentRoute({
+ method: "get",
+ path: "/api/companies/{companyId}/ai-connection-pools/{poolId}/inspection",
+ tags: ["ai-connections"],
+ summary: "Inspect authorized pool members and fresh cached usage without probing",
+ responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
+});
+
registerCurrentRoute({
method: "get",
path: "/api/companies/{companyId}/ai-connections/{connectionId}/usage",
diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts
index 59cfce69e0..f9ca1f6103 100644
--- a/server/src/routes/tool-access.ts
+++ b/server/src/routes/tool-access.ts
@@ -1,3 +1,5 @@
+import { aiConnectionRouterPluginKey } from "@paperclipai/shared";
+import { aiConnectionRouterService } from "../services/ai-connection-router.js";
import { composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSchema, composioAppAccountSchema } from "@paperclipai/shared";
import { aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema } from "@paperclipai/shared/aggregator-apps";
import { Router, type Request, type Response } from "express";
@@ -856,9 +858,9 @@ function connectorEnrollmentPrincipal(req: Request): string {
: "Vercel Connect setup is disabled on this Paperclip instance.",
},
},
- apps: APP_STORE_DEFINITIONS.filter((app) => (enableMemoryConnectors || !isMemoryConnectorId(app.slug))).map((app) =>
+ apps: [...APP_STORE_DEFINITIONS.filter((app) => (enableMemoryConnectors || !isMemoryConnectorId(app.slug))).map((app) =>
appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles)
- ),
+ ), ...await aiConnectionRouterService(db).catalog()],
});
});
@@ -2148,6 +2150,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
const existing = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!existing) return;
await assertToolConnectionConfigureAccess(req, existing);
+ if (aiConnectionRouterPluginKey(existing)) throw badRequest("Update this connection pool through its pool settings.");
const connection = await svc.updateConnection(existing.id, req.body);
const lifecycleChanges = classifyConnectionUpdate(
{ enabled: existing.enabled, config: existing.config },
@@ -2194,6 +2197,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
const existing = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!existing) return;
await assertToolConnectionConfigureAccess(req, existing);
+ if (aiConnectionRouterPluginKey(existing)) throw badRequest("Remove this connection pool through its revision-checked pool settings.");
const applicationBefore = await svc.getApplication(existing.applicationId);
const { connection, removal } = await svc.archiveConnection(
existing.id,
diff --git a/server/src/services/agent-ai-connection-default.ts b/server/src/services/agent-ai-connection-default.ts
index fc0224f124..c403cef41f 100644
--- a/server/src/services/agent-ai-connection-default.ts
+++ b/server/src/services/agent-ai-connection-default.ts
@@ -1,8 +1,9 @@
import {
AI_PROVIDERS,
- aiConnectionBindingSchema,
+ aiRuntimeConnectionBindingSchema,
isAiConnectionCompatible,
type AiConnectionBinding,
+ type AiRuntimeConnectionBinding,
type AiProvider,
} from "@paperclipai/shared";
@@ -20,15 +21,29 @@ export function defaultAiConnectionForHire(
adapterType: string,
config: Record<string, unknown>,
managerBinding: unknown,
-): AiConnectionBinding | undefined {
+): AiRuntimeConnectionBinding | undefined {
const compatible = (binding: AiConnectionBinding) =>
isAiConnectionCompatible(binding, adapterType, config.model, config.provider, config.acpxAgent);
- const inherited = aiConnectionBindingSchema.safeParse(managerBinding);
+ const inherited = aiRuntimeConnectionBindingSchema.safeParse(managerBinding);
// Unmanaged parents keep their existing login and credential-reference paths.
if (!inherited.success) return undefined;
const env = config.env && typeof config.env === "object" ? config.env as Record<string, unknown> : {};
+ const hasChildAuth = (provider: AiProvider) =>
+ PROVIDER_AUTH_ENV_KEYS[provider].some((key) => env[key] !== undefined);
const withChildAuthPrecedence = (binding: AiConnectionBinding) =>
- PROVIDER_AUTH_ENV_KEYS[binding.provider].some((key) => env[key] !== undefined) ? undefined : binding;
+ hasChildAuth(binding.provider) ? undefined : binding;
+ if (inherited.data.mode === "router") {
+ // The host validates pool membership, access and harness compatibility for
+ // the new agent. Never silently replace an incompatible pool with local auth.
+ // OpenCode also supports explicitly configured providers whose models are
+ // outside the managed OpenRouter catalog. Their auth still takes precedence.
+ const childProvider = adapterType === "opencode_local"
+ || (adapterType === "paperclip_runner" && config.provider === "opencode")
+ ? "openrouter"
+ : AI_PROVIDERS.find((provider) =>
+ compatible({ provider, method: "api_key", mode: "responsible_user" }));
+ return childProvider && hasChildAuth(childProvider) ? undefined : inherited.data;
+ }
if (inherited.data.mode !== "delegated" && compatible(inherited.data)) {
return withChildAuthPrecedence(inherited.data);
}
diff --git a/server/src/services/agents.ts b/server/src/services/agents.ts
index 93c437da8d..3640a90d4e 100644
--- a/server/src/services/agents.ts
+++ b/server/src/services/agents.ts
@@ -127,7 +127,7 @@ interface UpdateAgentOptions {
}
interface CreateAgentOptions {
- aiConnectionInstall?: { connectionId: string; createdByUserId: string | null };
+ aiConnectionInstall?: { connectionId: string; memberConnectionIds?: string[]; createdByUserId: string | null };
allowBuiltInAgentMetadata?: boolean;
claudeLogin?: ClaudeLoginContext;
}
@@ -945,11 +945,13 @@ export function agentService(db: Db) {
.returning()
.then((rows) => rows[0]);
if (options?.aiConnectionInstall) {
- await tx.insert(toolConnectionInstalls).values({
- companyId, connectionId: options.aiConnectionInstall.connectionId,
- targetType: "agent", targetId: created.id,
- createdByUserId: options.aiConnectionInstall.createdByUserId,
- }).onConflictDoNothing();
+ const install = options.aiConnectionInstall;
+ const connectionIds = [...new Set([install.connectionId, ...(install.memberConnectionIds ?? [])])];
+ await tx.insert(toolConnectionInstalls).values(connectionIds.map(connectionId => ({
+ companyId, connectionId,
+ targetType: "agent" as const, targetId: created.id,
+ createdByUserId: install.createdByUserId,
+ }))).onConflictDoNothing();
}
await syncAgentSecretBindings(created, txDb);
if (created.status !== "pending_approval" && created.status !== "terminated") {
diff --git a/server/src/services/ai-connection-router.ts b/server/src/services/ai-connection-router.ts
new file mode 100644
index 0000000000..4208bcd775
--- /dev/null
+++ b/server/src/services/ai-connection-router.ts
@@ -0,0 +1,283 @@
+import { randomUUID } from "node:crypto";
+import { and, eq, ne, sql } from "drizzle-orm";
+import { aiConnectionPools, aiConnectionRouterCursors, aiConnectionTaskPins, companySecrets, connectionGrants, instanceSettings, plugins, toolApplications, toolConnections, toolConnectionInstalls, type Db } from "@paperclipai/db";
+import { aiConnectionRouterAppDefinition, aiConnectionRouterSlug, aiConnectionPoolConfigSchema, isAiConnectionCompatible, type AiConnectionPool, type AiConnectionPoolMember, type AiConnectionRouterRequest, type AiConnectionRouterSelection, type AiConnectionPoolSaveInput, type AiConnectionUsage } from "@paperclipai/shared";
+import { isCodexLocalKnownModel, codexLocalReasoningEffortsForModel } from "@paperclipai/adapter-codex-local";
+import { models as claudeModels, claudeLocalReasoningEffortsForModel } from "@paperclipai/adapter-claude-local";
+import { models as grokModels, grokLocalReasoningEffortsForModel } from "@paperclipai/adapter-grok-local";
+import { aiConnectionService } from "./ai-connections.js";
+import { instanceSettingsService } from "./instance-settings.js";
+import { logActivity } from "./activity-log.js";
+import { forbidden, notFound, conflict, unprocessable } from "../errors.js";
+import type { PluginWorkerManager } from "./plugin-worker-manager.js";
+import { resolvePaperclipRunnerProviderProfile, resolvePaperclipRunnerNativeProviderInput } from "./native-runtime/provider-profile.js";
+
+const usageCache = new Map<string, { expires: number; value: AiConnectionUsage }>();
+const usageInFlight = new Map<string, Promise<AiConnectionUsage | undefined>>();
+const routedRuntimeKeys = new Set(["provider", "acpxAgent", "model", "modelReasoningEffort", "reasoningEffort", "effort", "variant"]);
+export function applyAiConnectionRouterTaskSettings(config: Record<string, unknown>, selection: AiConnectionRouterSelection) {
+ return { ...Object.fromEntries(Object.entries(config).filter(([key]) => !routedRuntimeKeys.has(key))), ...selection.runtimeConfig };
+}
+export class AiConnectionPoolExhausted extends Error {
+ readonly code = "ai_connection_pool_exhausted";
+ constructor(readonly retryAt: string, readonly poolId: string) { super("All eligible pool accounts are over their usage limit. Waiting for usage to reset."); }
+}
+
+/** Routing can override provider/model only, never environment, permissions, or instructions. */
+export function poolMemberRuntimeConfig(member: AiConnectionPoolMember, adapterType: string, overrides: Record<string, unknown> = {}) {
+ const notes: string[] = [];
+ const provider = member.binding.provider;
+ const profile = member.profile;
+ const expected = provider === "openai" ? profile.provider === "codex"
+ : provider === "anthropic" ? profile.provider === "acpx" && profile.acpxAgent === "claude"
+ : provider === "xai" ? profile.provider === "acpx" && profile.acpxAgent === "grok"
+ : profile.provider === "opencode";
+ if (!expected) throw unprocessable("Pool member harness does not match its account");
+ const supportsModel = (value: string) => provider === "openai" ? isCodexLocalKnownModel(value)
+ : provider === "anthropic" ? claudeModels.some((m) => m.id === value)
+ : provider === "xai" ? grokModels.some((m) => m.id === value) : value.startsWith("openrouter/");
+ const config: Record<string, unknown> = { provider: profile.provider, ...(profile.acpxAgent ? { acpxAgent: profile.acpxAgent } : {}), model: profile.model };
+ const validate = () => {
+ if (!isAiConnectionCompatible(member.binding, adapterType, config.model, config.provider, config.acpxAgent)) throw unprocessable("Pool member is incompatible with this harness");
+ if (adapterType === "paperclip_runner") {
+ const resolved = resolvePaperclipRunnerProviderProfile(config);
+ resolvePaperclipRunnerNativeProviderInput({ backend: resolved.backend, adapterConfig: config });
+ }
+ };
+ validate();
+ if (typeof overrides.model === "string" && overrides.model !== profile.model) {
+ if (supportsModel(overrides.model)) {
+ config.model = overrides.model;
+ try { validate(); } catch { config.model = profile.model; notes.push("Model override is unavailable for this member; using its default."); }
+ } else notes.push("Model override is unavailable for this member; using its default.");
+ }
+ const model = String(config.model);
+ const efforts = provider === "openai" ? codexLocalReasoningEffortsForModel(model)
+ : provider === "anthropic" ? claudeLocalReasoningEffortsForModel(model)
+ : provider === "xai" ? grokLocalReasoningEffortsForModel(model) : [];
+ // ACPX currently has no qualified effort override; keep that host limitation explicit.
+ const effortKey = adapterType === "paperclip_runner" ? profile.provider === "codex" ? "modelReasoningEffort" : null
+ : provider === "anthropic" ? "effort" : provider === "xai" ? "reasoningEffort" : provider === "openai" ? "modelReasoningEffort" : "variant";
+ const requested = overrides.modelReasoningEffort ?? overrides.reasoningEffort ?? overrides.effort ?? overrides.variant;
+ const effort = typeof requested === "string" && efforts.includes(requested) && effortKey ? requested
+ : profile.effort && efforts.includes(profile.effort) && effortKey ? profile.effort : null;
+ if (requested && requested !== effort) notes.push("Effort override is unavailable for this member; using its default.");
+ if (effort && effortKey) config[effortKey] = effort;
+ validate();
+ return { config, notes };
+}
+
+export function aiConnectionRouterService(db: Db, workerManager?: PluginWorkerManager) {
+ async function owner(pluginKey: string) {
+ const [plugin] = await db.select().from(plugins).where(eq(plugins.pluginKey, pluginKey));
+ if (!plugin || plugin.status !== "ready" || !plugin.manifestJson.capabilities.includes("ai.connections.route")) throw unprocessable("Enable a compatible AI connection router plugin");
+ return plugin;
+ }
+ async function enabled() {
+ if (!(await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters) throw unprocessable("Ask your instance operator to enable AI connection routing.", { code: "ai_connection_router_disabled" });
+ }
+ async function catalog() {
+ const experimental = (await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters;
+ const installed = await db.select().from(plugins);
+ return installed.filter(plugin => plugin.status !== "uninstalled" && plugin.manifestJson.aiConnectionRouter && plugin.manifestJson.capabilities.includes("ai.connections.route"))
+ .map(plugin => aiConnectionRouterAppDefinition(plugin.pluginKey, plugin.manifestJson.aiConnectionRouter!, {
+ available: experimental && plugin.status === "ready",
+ ...(!experimental ? { reason: "Ask your instance operator to enable AI connection routing." }
+ : plugin.status !== "ready" ? { reason: "Enable the connection pool plugin in Plugins." } : {}),
+ }));
+ }
+ async function list(companyId: string) {
+ const rows = await db.select({ pool: aiConnectionPools }).from(aiConnectionPools)
+ .innerJoin(toolConnections, and(eq(toolConnections.id, aiConnectionPools.id), eq(toolConnections.companyId, aiConnectionPools.companyId)))
+ .where(and(eq(aiConnectionPools.companyId, companyId), ne(toolConnections.status, "archived")));
+ return rows.map(({ pool: row }): AiConnectionPool => ({ ...row.config, id: row.id, companyId, pluginKey: row.pluginKey, revision: row.revision }));
+ }
+ async function selectable(companyId: string, userId: string) {
+ if (!(await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters) return [];
+ const accounts = await aiConnectionService(db).list(companyId, userId);
+ const result: AiConnectionPool[] = [];
+ for (const pool of await list(companyId)) {
+ if (!pool.enabled) continue;
+ try { await owner(pool.pluginKey); } catch { continue; }
+ const members = pool.members.filter(member => accounts.some(account => account.id === member.binding.connectionId && account.grantId === member.binding.grantId));
+ if (members.length) result.push({ ...pool, members });
+ }
+ return result;
+ }
+ async function inspect(companyId: string, poolId: string, userId: string) {
+ const pool = (await list(companyId)).find(pool => pool.id === poolId);
+ if (!pool) throw notFound("Connection pool not found");
+ const visible = await aiConnectionService(db).list(companyId, userId);
+ const result: Record<string, { reason: string; checkedAt: string | null; usage?: AiConnectionUsage }> = {};
+ for (const member of pool.members) {
+ const account = visible.find(account => account.id === member.binding.connectionId && account.grantId === member.binding.grantId);
+ const key = account ? await usageCacheKey(member, companyId) : null;
+ const cached = key ? usageCache.get(key) : undefined;
+ const observation = cached && cached.expires > Date.now() ? cached.value : undefined;
+ result[member.id] = { reason: account?.status === "connected" ? "Eligible if agent access permits" : account?.status ?? "Not permitted", checkedAt: account && observation ? observation.checkedAt : null, ...(account && observation ? { usage: observation } : {}) };
+ }
+ return result;
+ }
+ async function save(pluginKey: string, input: AiConnectionPoolSaveInput, userId: string) {
+ await enabled();
+ const plugin = await owner(pluginKey);
+ const config = aiConnectionPoolConfigSchema.parse(input.config);
+ const visible = await aiConnectionService(db).list(input.companyId, userId);
+ for (const member of config.members) {
+ if (!visible.some((v) => v.id === member.binding.connectionId && v.grantId === member.binding.grantId)) throw forbidden("Choose an account you may use in this company");
+ poolMemberRuntimeConfig(member, "paperclip_runner");
+ }
+ const id = input.id ?? randomUUID();
+ await db.transaction(async (tx) => {
+ if (input.id) {
+ const [row] = await tx.select().from(aiConnectionPools).where(and(eq(aiConnectionPools.id, id), eq(aiConnectionPools.companyId, input.companyId), eq(aiConnectionPools.pluginKey, pluginKey))).for("update");
+ if (!row) throw notFound("Connection pool not found");
+ const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, id), eq(toolConnections.companyId, input.companyId)));
+ if (!connection || connection.status === "archived") throw notFound("Connection pool not found");
+ if (input.expectedRevision !== row.revision) throw conflict("Pool changed; reload before saving");
+ await tx.update(aiConnectionPools).set({ config, revision: row.revision + 1, updatedAt: new Date() }).where(eq(aiConnectionPools.id, id));
+ await tx.update(toolConnections).set({ name: config.name, enabled: config.enabled, updatedAt: new Date() }).where(and(eq(toolConnections.id, id), eq(toolConnections.companyId, input.companyId)));
+ } else {
+ const key = `plugin:${pluginKey}:ai-router`;
+ await tx.insert(toolApplications).values({ companyId: input.companyId, applicationKey: key, name: plugin.manifestJson.aiConnectionRouter?.name ?? plugin.manifestJson.displayName, metadata: { sourceTemplateKey: aiConnectionRouterSlug(pluginKey) }, type: "paperclip_plugin", pluginId: plugin.id }).onConflictDoNothing();
+ const [application] = await tx.select().from(toolApplications).where(and(eq(toolApplications.companyId, input.companyId), eq(toolApplications.applicationKey, key)));
+ if (!application) throw new Error("Router application could not be created");
+ await tx.insert(toolConnections).values({ id, companyId: input.companyId, applicationId: application.id, name: config.name, uid: id, connectionPurpose: "ai", transport: "runtime_auth", enabled: config.enabled, status: "active", healthStatus: "ok", config: { aiRouter: { pluginKey }, sourceTemplateKey: aiConnectionRouterSlug(pluginKey) }, createdByUserId: userId });
+ await tx.insert(aiConnectionPools).values({ id, companyId: input.companyId, pluginKey, config });
+ await tx.insert(aiConnectionRouterCursors).values({ poolId: id, companyId: input.companyId });
+ await tx.insert(toolConnectionInstalls).values({ companyId: input.companyId, connectionId: id, targetType: "company", targetId: input.companyId, createdByUserId: userId });
+ }
+ await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "user", actorId: userId, action: "ai_connection.pool_saved", entityType: "tool_connection", entityId: id, details: { enabled: config.enabled, memberCount: config.members.length, mode: config.mode } });
+ });
+ return (await list(input.companyId)).find((p) => p.id === id)!;
+ }
+ async function remove(companyId: string, poolId: string, expectedRevision: number, userId: string) {
+ // Archive the virtual connection; cascading deletion would erase task pins.
+ // Cleanup remains available when the experimental flag or plugin is off.
+ await db.transaction(async tx => {
+ const [row] = await tx.select().from(aiConnectionPools).where(and(eq(aiConnectionPools.id, poolId), eq(aiConnectionPools.companyId, companyId))).for("update");
+ if (!row) throw notFound("Connection pool not found");
+ const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, poolId), eq(toolConnections.companyId, companyId)));
+ if (!connection || connection.status === "archived") throw notFound("Connection pool not found");
+ if (row.revision !== expectedRevision) throw conflict("Pool changed; reload before deleting");
+ await tx.update(aiConnectionPools).set({ config: { ...row.config, enabled: false }, revision: row.revision + 1, updatedAt: new Date() }).where(eq(aiConnectionPools.id, poolId));
+ await tx.update(toolConnections).set({ status: "archived", enabled: false, updatedAt: new Date() }).where(and(eq(toolConnections.id, poolId), eq(toolConnections.companyId, companyId)));
+ await logActivity(tx as unknown as Db, { companyId, actorType: "user", actorId: userId, action: "ai_connection.pool_deleted", entityType: "tool_connection", entityId: poolId, details: { retainedTaskPins: true } });
+ });
+ return { ok: true };
+ }
+ async function usageCacheKey(member: AiConnectionPoolMember, companyId: string) {
+ const [grant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, companyId), eq(connectionGrants.id, member.binding.grantId)));
+ if (!grant) return null;
+ const ref = grant.credentialSecretRefs.find((r) => r.configPath === "ai.credential");
+ const [secret] = ref ? await db.select({ version: companySecrets.latestVersion }).from(companySecrets).where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.id, ref.secretId))) : [];
+ return `${companyId}:${grant.id}:${ref?.secretId}:${secret?.version}:${grant.updatedAt.toISOString()}`;
+ }
+ async function probe(member: AiConnectionPoolMember, companyId: string, userId: string, deadline: number) {
+ const key = await usageCacheKey(member, companyId);
+ if (!key) return undefined;
+ const cached = usageCache.get(key);
+ if (cached && cached.expires > Date.now()) return cached.value;
+ let pending = usageInFlight.get(key);
+ if (!pending) {
+ let probeTimer: ReturnType<typeof setTimeout> | undefined;
+ pending = Promise.race([
+ aiConnectionService(db).probeUsage(companyId, userId, member.binding.connectionId, member.binding.grantId).catch(() => undefined),
+ new Promise<undefined>(resolve => { probeTimer = setTimeout(() => resolve(undefined), 15_000); }),
+ ]).then(value => {
+ if (value) {
+ const resets = value.limits.map(v => Date.parse(v.resetsAt ?? "")).filter(v => Number.isFinite(v) && v > Date.now());
+ if (usageCache.size > 1000) usageCache.clear();
+ usageCache.set(key, { value, expires: Math.min(Date.now() + 60_000, ...resets) });
+ }
+ return value;
+ }).finally(() => { if (probeTimer) clearTimeout(probeTimer); usageInFlight.delete(key); });
+ usageInFlight.set(key, pending);
+ }
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ pending,
+ new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), Math.max(0, deadline - Date.now())); }),
+ ]);
+ } finally { if (timer) clearTimeout(timer); }
+ }
+
+ async function resolve(input: { companyId: string; poolId: string; agentId: string; userId: string | null; adapterType: string; taskKey: string; overrides?: Record<string, unknown>; existingGrantId?: string; requireExisting?: boolean; persisted?: AiConnectionRouterSelection }) {
+ const pinWhere = and(eq(aiConnectionTaskPins.companyId, input.companyId), eq(aiConnectionTaskPins.poolId, input.poolId), eq(aiConnectionTaskPins.agentId, input.agentId), eq(aiConnectionTaskPins.taskKey, input.taskKey));
+ const validateSelection = async (selection: AiConnectionRouterSelection, client = db) => aiConnectionService(client).select({ companyId: input.companyId, agentId: input.agentId, userId: input.userId, adapterType: input.adapterType, binding: selection.binding, model: selection.runtimeConfig.model, runnerProvider: selection.runtimeConfig.provider, acpxAgent: selection.runtimeConfig.acpxAgent });
+ if (input.persisted) {
+ if (input.persisted.poolId !== input.poolId) throw unprocessable("Persisted pool selection does not match this run");
+ const [pin] = await db.select().from(aiConnectionTaskPins).where(pinWhere);
+ // Uninstall can remove the virtual connection. Server-owned native recovery
+ // evidence still authorizes the original concrete selection, never a new one.
+ if (pin && (pin.selection.memberId !== input.persisted.memberId || JSON.stringify(pin.selection.binding) !== JSON.stringify(input.persisted.binding))) throw unprocessable("Persisted pool allocation is inconsistent");
+ await validateSelection(input.persisted);
+ return input.persisted;
+ }
+ await enabled();
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const [record] = await db.select({ pool: aiConnectionPools, connectionStatus: toolConnections.status }).from(aiConnectionPools)
+ .innerJoin(toolConnections, and(eq(toolConnections.id, aiConnectionPools.id), eq(toolConnections.companyId, aiConnectionPools.companyId)))
+ .where(and(eq(aiConnectionPools.id, input.poolId), eq(aiConnectionPools.companyId, input.companyId)));
+ if (!record || record.connectionStatus === "archived") throw unprocessable("This connection pool is unavailable; choose another AI connection");
+ const row = record.pool;
+ if (!row.config.enabled) throw unprocessable("Enable the selected connection pool");
+ const plugin = await owner(row.pluginKey);
+ if (!workerManager?.isRunning(plugin.id)) throw unprocessable("The connection router worker is unavailable; retry when it is ready");
+ const [pin] = await db.select().from(aiConnectionTaskPins).where(pinWhere);
+ const [cursor] = await db.select().from(aiConnectionRouterCursors).where(and(eq(aiConnectionRouterCursors.poolId, row.id), eq(aiConnectionRouterCursors.companyId, input.companyId)));
+ if (!cursor) throw unprocessable("The connection pool cursor is unavailable");
+ const pool: AiConnectionPool = { ...row.config, id: row.id, companyId: row.companyId, pluginKey: row.pluginKey, revision: row.revision };
+ const deadline = Date.now() + 15_000;
+ const candidates: AiConnectionRouterRequest["candidates"] = [];
+ for (const member of pin ? [pin.member] : pool.members) {
+ try {
+ const effective = poolMemberRuntimeConfig(member, input.adapterType, input.overrides);
+ const selection: AiConnectionRouterSelection = { poolId: row.id, memberId: member.id, binding: member.binding, runtimeConfig: effective.config, notes: effective.notes };
+ await validateSelection(selection);
+ candidates.push({ member, runtimeConfig: effective.config, notes: effective.notes });
+ } catch (error) { if (pin) throw error; }
+ }
+ if (!pin && input.requireExisting) {
+ const existing = candidates.find((candidate) => candidate.member.binding.grantId === input.existingGrantId);
+ if (!existing) throw unprocessable("Reset this task session before adopting the connection pool");
+ candidates.splice(0, candidates.length, existing);
+ }
+ if (pool.mode === "usage_aware" && input.userId) {
+ // At most four provider calls at once; the shared deadline bounds the whole pool.
+ for (let i = 0; i < candidates.length && Date.now() < deadline; i += 4) await Promise.all(candidates.slice(i, i + 4).map(async (candidate) => { candidate.usage = await probe(candidate.member, input.companyId, input.userId!, deadline); }));
+ }
+ const authorizedPool = { ...pool, members: candidates.map((candidate) => candidate.member) };
+ const result = await workerManager.call(plugin.id, "routeAiConnection", { companyId: input.companyId, pool: authorizedPool, memberOrder: pool.members.map((member) => member.id), agentId: input.agentId, taskKey: input.taskKey, lastMemberId: cursor.lastMemberId, cursorVersion: cursor.version, ...(pin ? { pinnedMemberId: pin.member.id } : {}), candidates, now: new Date().toISOString() }, 5000);
+ if (result.kind === "exhausted") {
+ const retry = Date.parse(result.retryAt);
+ throw new AiConnectionPoolExhausted(new Date(Number.isFinite(retry) ? Math.max(Date.now() + 1000, retry) : Date.now() + 60_000).toISOString(), pool.id);
+ }
+ if (result.kind !== "selected") throw unprocessable("No pool account is permitted and compatible for this task");
+ const candidate = candidates.find((v) => v.member.id === result.memberId);
+ if (!candidate || (pin && candidate.member.id !== pin.member.id)) throw unprocessable("The router returned an unauthorized member");
+ const selected: AiConnectionRouterSelection = { poolId: row.id, memberId: candidate.member.id, binding: candidate.member.binding, runtimeConfig: candidate.runtimeConfig, notes: candidate.notes };
+ if (pin) return selected;
+ const committed = await db.transaction(async (tx) => {
+ const [locked] = await tx.select().from(aiConnectionRouterCursors).where(and(eq(aiConnectionRouterCursors.poolId, row.id), eq(aiConnectionRouterCursors.companyId, input.companyId))).for("update");
+ const [existing] = await tx.select().from(aiConnectionTaskPins).where(pinWhere);
+ if (existing) return { retry: true };
+ const [current] = await tx.select().from(aiConnectionPools).where(and(eq(aiConnectionPools.id, row.id), eq(aiConnectionPools.companyId, input.companyId))).for("share");
+ if (!locked || locked.version !== cursor.version || !current || current.revision !== row.revision) return { retry: true };
+ const [currentPlugin] = await tx.select().from(plugins).where(eq(plugins.id, plugin.id)).for("share");
+ if (currentPlugin?.status !== "ready") throw unprocessable("The router plugin was disabled during allocation");
+ await tx.select({ id: instanceSettings.id }).from(instanceSettings).where(eq(instanceSettings.singletonKey, "default")).for("share");
+ if (!(await instanceSettingsService(tx as unknown as Db).getExperimental()).enableAiConnectionRouters) throw unprocessable("AI connection routers were disabled during allocation");
+ await validateSelection(selected, tx as unknown as Db);
+ await tx.insert(aiConnectionTaskPins).values({ companyId: input.companyId, poolId: row.id, agentId: input.agentId, taskKey: input.taskKey, selection: selected, member: candidate.member });
+ await tx.update(aiConnectionRouterCursors).set({ lastMemberId: candidate.member.id, version: sql`${aiConnectionRouterCursors.version} + 1` }).where(eq(aiConnectionRouterCursors.poolId, row.id));
+ await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "system", actorId: "system", agentId: input.agentId, action: "ai_connection.pool_selected", entityType: "tool_connection", entityId: row.id, details: { memberId: candidate.member.id, connectionId: candidate.member.binding.connectionId, taskKey: input.taskKey } });
+ return { retry: false };
+ });
+ if (!committed.retry) return selected;
+ }
+ throw conflict("Concurrent pool selections changed the cursor; retry this task");
+ }
+ return { catalog, list, selectable, inspect, save, remove, resolve };
+}
diff --git a/server/src/services/ai-connection-runtime.ts b/server/src/services/ai-connection-runtime.ts
index 534f5cf023..ea691f5f3d 100644
--- a/server/src/services/ai-connection-runtime.ts
+++ b/server/src/services/ai-connection-runtime.ts
@@ -189,7 +189,13 @@ export function managedAiSessionFingerprintConfig(
for (const [key, value] of Object.entries(managedAiHomeEnvironment(managedHome))) {
if (env[key] === value) env[key] = stable[key];
}
- return { ...config, env };
+ const managed = config.managedAiConnection as Record<string, unknown> | undefined;
+ if (managed?.sessionIdentity) {
+ for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "OPENROUTER_API_KEY", "XAI_API_KEY", "GROK_API_KEY", "OPENCODE_AUTH_JSON", "OPENCODE_CONFIG_CONTENT"]) {
+ if (env[key]) env[key] = "<managed-ai-credential>";
+ }
+ }
+ return { ...config, env, ...(managed?.sessionIdentity ? { managedAiConnection: { ...managed, identity: managed.sessionIdentity } } : {}) };
}
export async function prepareManagedAiRuntime(
@@ -251,7 +257,14 @@ export async function prepareManagedAiRuntime(
throw unprocessable(
"The selected default changed. Retry this execution.",
);
+ const credentialRef = selection.grant.credentialSecretRefs.find((ref) => ref.configPath === "ai.credential");
+ if (!credentialRef) throw unprocessable("The selected AI credential is unavailable");
+ const readFreshness = async () => (await db.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion })
+ .from(companySecrets).where(and(eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, credentialRef.secretId))).limit(1))[0];
+ const freshness = await readFreshness();
const value = await service.credential(selection);
+ const afterRead = await readFreshness();
+ if (!freshness || freshness.version !== afterRead?.version || freshness.epoch !== afterRead.epoch) throw unprocessable("The AI credential changed during preparation; retry this execution");
home = await mkdtemp(
path.join(
os.tmpdir(),
@@ -298,11 +311,13 @@ export async function prepareManagedAiRuntime(
.digest("hex")
.slice(0, 16);
const identity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${generation}`;
+ const sessionIdentity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${credentialRef.secretId}:${freshness.epoch}`;
return {
+ sessionIdentity,
config: {
...input.config,
env,
- managedAiConnection: { ...selection.attribution, identity },
+ managedAiConnection: { ...selection.attribution, identity, sessionIdentity },
},
attribution: selection.attribution,
accountName: selection.connection.name,
@@ -367,7 +382,7 @@ export async function prepareManagedAiRuntime(
if (decision !== 10) return;
await secretService(tx).rotate(
ref.secretId,
- { value: refreshed },
+ { value: refreshed, preserveAiSessionEpoch: true },
{ userId: grant.subjectUserId },
);
await tx
diff --git a/server/src/services/ai-connection-session.ts b/server/src/services/ai-connection-session.ts
new file mode 100644
index 0000000000..1b0c4fc583
--- /dev/null
+++ b/server/src/services/ai-connection-session.ts
@@ -0,0 +1,103 @@
+import { isDeepStrictEqual } from "node:util";
+import type { AiConnectionBinding } from "@paperclipai/shared";
+
+type ConfigRevision = {
+ id: string;
+ changedKeys: string[];
+ createdAt: Date;
+ beforeConfig: Record<string, unknown>;
+ afterConfig: Record<string, unknown>;
+};
+
+function record(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown> : {};
+}
+
+export function managedAiSessionIdentityCompatible(
+ stored: unknown,
+ sessionIdentity: string,
+ credentialIdentity: string,
+): boolean {
+ // Legacy token identities can migrate only before any manual replacement.
+ // Replacing even the same credential bytes increments the epoch.
+ return stored === sessionIdentity || (sessionIdentity.endsWith(":0") && stored === credentialIdentity);
+}
+
+export function aiConnectionOnlyConfigRevision(revision: ConfigRevision): boolean {
+ const withoutBinding = (snapshot: Record<string, unknown>) => {
+ const runtimeConfig = { ...record(snapshot.runtimeConfig) };
+ delete runtimeConfig.aiConnection;
+ return { ...snapshot, runtimeConfig };
+ };
+ return !isDeepStrictEqual(record(revision.beforeConfig.runtimeConfig).aiConnection, record(revision.afterConfig.runtimeConfig).aiConnection)
+ && isDeepStrictEqual(withoutBinding(revision.beforeConfig), withoutBinding(revision.afterConfig));
+}
+
+export function aiConnectionRevisionMetadata(revision: ConfigRevision | undefined) {
+ return revision ? { id: revision.id, changedKeys: revision.changedKeys, configRevisionAt: revision.createdAt.toISOString() } : null;
+}
+
+/** Exact alternative fingerprints, never a category-level exemption. The caller
+ * has already authorized the selected account and prepared its credential. */
+export function aiConnectionSessionCompatibilityInputs(input: {
+ effectiveAdapterConfig: Record<string, unknown>;
+ agentRuntimeConfig: unknown;
+ agentConfigRevision: unknown;
+ issueOverrides: unknown;
+ originalIssueOverrides: unknown;
+ binding: AiConnectionBinding;
+ router: boolean;
+ storedIdentity: unknown;
+ sessionIdentity: string;
+ credentialIdentity: string;
+ revisions: readonly ConfigRevision[];
+}) {
+ if (!managedAiSessionIdentityCompatible(input.storedIdentity, input.sessionIdentity, input.credentialIdentity)) return [];
+ const configs = [input.effectiveAdapterConfig];
+ if (input.storedIdentity === input.credentialIdentity && input.sessionIdentity.endsWith(":0")) {
+ const managed = { ...record(input.effectiveAdapterConfig.managedAiConnection) };
+ delete managed.sessionIdentity;
+ managed.identity = input.credentialIdentity;
+ configs.push({ ...input.effectiveAdapterConfig, managedAiConnection: managed });
+ }
+ const variants = [{ agentRuntimeConfig: input.agentRuntimeConfig, agentConfigRevision: input.agentConfigRevision }];
+ if (input.router) {
+ // Also support bindings saved before revision history was introduced, and
+ // responsible-user defaults that resolve to this same authorized grant.
+ const bindings = [input.binding, ...("grantId" in input.binding ? [
+ { ...input.binding, mode: "shared" }, { ...input.binding, mode: "delegated" },
+ ] : []), ...(["subscription", "api_key"] as const).map(method => ({ mode: "responsible_user", provider: input.binding.provider, method }))];
+ for (const binding of bindings) {
+ variants.push({ agentRuntimeConfig: { ...record(input.agentRuntimeConfig), aiConnection: binding }, agentConfigRevision: input.agentConfigRevision });
+ }
+ let expectedRuntimeConfig = record(input.agentRuntimeConfig);
+ for (let index = 0; index < Math.min(20, input.revisions.length); index++) {
+ const revision = input.revisions[index]!;
+ if (index === 0 && revision.id !== record(input.agentConfigRevision).id) break;
+ if (!isDeepStrictEqual(record(revision.afterConfig.runtimeConfig), expectedRuntimeConfig)) break;
+ if (!aiConnectionOnlyConfigRevision(revision)) break;
+ // An incomplete bounded history is not sufficient to waive a revision.
+ const previous = input.revisions[index + 1];
+ if (!previous && input.revisions.length >= 21) break;
+ variants.push({ agentRuntimeConfig: record(revision.beforeConfig.runtimeConfig), agentConfigRevision: aiConnectionRevisionMetadata(previous) });
+ expectedRuntimeConfig = record(revision.beforeConfig.runtimeConfig);
+ }
+ }
+ const overrides = input.router && !isDeepStrictEqual(input.issueOverrides, input.originalIssueOverrides)
+ ? [input.issueOverrides, input.originalIssueOverrides] : [input.issueOverrides];
+ return variants.flatMap(variant => {
+ const previousMode = record(record(variant.agentRuntimeConfig).aiConnection).mode;
+ const modes = input.router
+ ? ["responsible_user", "shared", "delegated"].includes(String(previousMode))
+ ? [previousMode] : ["responsible_user", "shared", "delegated"]
+ : [record(input.effectiveAdapterConfig.managedAiConnection).mode];
+ return configs.flatMap(config => modes.flatMap(mode => overrides.map(issueOverrides => ({
+ ...variant,
+ // Binding mode is also recorded in the managed account attribution.
+ // Keep grant, user, credential epoch, and every other setting unchanged.
+ effectiveAdapterConfig: { ...config, managedAiConnection: { ...record(config.managedAiConnection), mode } },
+ issueOverrides,
+ }))));
+ });
+}
diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts
index a3d2bf640c..7cfdbeb155 100644
--- a/server/src/services/ai-connections.ts
+++ b/server/src/services/ai-connections.ts
@@ -383,7 +383,7 @@ export function aiConnectionService(db: Db) {
!installs.length &&
!(
(input.allowUninstalledPersonal &&
- binding.mode === "responsible_user" && grant.subjectUserId === userId) ||
+ grant.kind === "user" && grant.subjectUserId === userId) ||
(input.allowUninstalledShared && binding.mode === "shared" && grant.kind === "organization")
)
)
diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts
index d369ad33cc..175a2228d8 100644
--- a/server/src/services/connection-intents.ts
+++ b/server/src/services/connection-intents.ts
@@ -5,12 +5,13 @@ import { agentService } from "./agents.js";
import { createHash } from "node:crypto";
import { logActivity } from "./activity-log.js";
import { aiConnectionService } from "./ai-connections.js";
-import { aiConnectionBindingSchema } from "@paperclipai/shared";
+import { aiConnectionBindingSchema, aiConnectionRouterBindingSchema } from "@paperclipai/shared";
import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js";
import { and, eq, desc, isNull, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
+ aiConnectionTaskPins,
companies,
toolConnections,
toolCatalogEntries,
@@ -234,11 +235,26 @@ export function connectionIntentService(db: Db) {
};
}
- async function managedAgent(companyId: string, agentId: string, serviceSlug: string, fallback?: AiConnectionBinding) {
- const [agent] = await db.select().from(agents).where(and(eq(agents.companyId, companyId), eq(agents.id, agentId)));
- const saved = aiConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data;
- const binding = saved ?? fallback;
- return agent && binding?.provider === serviceSlug ? { agent, binding, requiresAdoption: !saved } : null;
+ async function managedAgent(companyId: string, agentId: string, serviceSlug: string, options: { fallback?: AiConnectionBinding; sourceRunId?: string | null } = {}, client = db) {
+ const [agent] = await client.select().from(agents).where(and(eq(agents.companyId, companyId), eq(agents.id, agentId)));
+ if (!agent) return null;
+ const router = aiConnectionRouterBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data;
+ if (router) {
+ // Repair the durable task allocation, without adopting a personal default
+ // or replacing the agent's pool. A changed pool invalidates the old card.
+ if (!options.sourceRunId) return null;
+ const [source] = await client.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.id, options.sourceRunId)));
+ const taskKey = text(source?.contextSnapshot?.aiRouterTaskKey);
+ const evidence = record(source?.contextSnapshot?.aiRouterSelection);
+ if (!source || !isAiAuthenticationFailure(source.errorCode) || source.status !== "failed" || evidence?.poolId !== router.connectionId || !taskKey) return null;
+ const [pin] = await client.select().from(aiConnectionTaskPins).where(and(eq(aiConnectionTaskPins.companyId, companyId), eq(aiConnectionTaskPins.poolId, router.connectionId), eq(aiConnectionTaskPins.agentId, agentId), eq(aiConnectionTaskPins.taskKey, taskKey)));
+ const binding = pin?.selection.binding;
+ if (!pin || binding?.provider !== serviceSlug || JSON.stringify(evidence.binding) !== JSON.stringify(binding)) return null;
+ return { agent, binding, adapterConfig: { ...agent.adapterConfig, ...pin.selection.runtimeConfig }, requiresAdoption: false };
+ }
+ const saved = aiConnectionBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data;
+ const binding = saved ?? options.fallback;
+ return binding?.provider === serviceSlug ? { agent, binding, adapterConfig: agent.adapterConfig, requiresAdoption: !saved } : null;
}
async function usableConnectionForAgent(input: {
@@ -247,12 +263,13 @@ export function connectionIntentService(db: Db) {
responsibleUserId: string;
serviceSlug: string;
purpose?: "ai" | "channel";
+ sourceRunId?: string | null;
inventory?: Awaited<ReturnType<typeof connectionInventory>>;
}) {
- const managed = input.purpose === "ai" ? await managedAgent(input.companyId, input.agentId, input.serviceSlug) : null;
+ const managed = input.purpose === "ai" ? await managedAgent(input.companyId, input.agentId, input.serviceSlug, { sourceRunId: input.sourceRunId }) : null;
if (managed) {
try {
- const selected = await aiConnectionService(db).select({ companyId: input.companyId, agentId: input.agentId, userId: input.responsibleUserId, adapterType: managed.agent.adapterType, model: managed.agent.adapterConfig.model, runnerProvider: managed.agent.adapterConfig.provider, acpxAgent: managed.agent.adapterConfig.acpxAgent, binding: managed.binding });
+ const selected = await aiConnectionService(db).select({ companyId: input.companyId, agentId: input.agentId, userId: input.responsibleUserId, adapterType: managed.agent.adapterType, model: managed.adapterConfig.model, runnerProvider: managed.adapterConfig.provider, acpxAgent: managed.adapterConfig.acpxAgent, binding: managed.binding });
return access.getConnection(selected.connection.id, input.companyId);
} catch (error) { if ([403, 404, 422].includes((error as { status?: number }).status ?? 0)) return null; throw error; }
}
@@ -732,6 +749,7 @@ export function connectionIntentService(db: Db) {
responsibleUserId: context.run.responsibleUserId!,
serviceSlug: app.slug,
purpose: options.purpose,
+ sourceRunId: context.run.id,
});
if (ready && !accessRequest && (!options.connectionId || ready.id === options.connectionId)) {
return {
@@ -829,7 +847,7 @@ export function connectionIntentService(db: Db) {
readyConnectionId: inboxes.find(inbox => inbox.id === interactionId)?.connectionId ?? null },
};
}
- let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null;
+ let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug, { sourceRunId: loaded.interaction.sourceRunId }) : null;
if (payload.purpose === "ai" && !managed) {
const [source] = await db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, loaded.interaction.sourceRunId!), eq(heartbeatRuns.companyId, loaded.issue.companyId),
@@ -837,21 +855,21 @@ export function connectionIntentService(db: Db) {
));
const [agent] = await db.select().from(agents).where(and(eq(agents.id, payload.requestingAgentId), eq(agents.companyId, loaded.issue.companyId)));
if (source?.status === "failed" && isAiAuthenticationFailure(source.errorCode) && !source.contextSnapshot?.aiConnection && agent && !agent.runtimeConfig.aiConnection) {
- managed = await managedAgent(loaded.issue.companyId, agent.id, app.slug, aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig));
+ managed = await managedAgent(loaded.issue.companyId, agent.id, app.slug, { fallback: aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig) });
}
}
if (payload.purpose === "ai" && !managed) throw conflict("The agent’s AI configuration changed. Start a new execution.");
const inventory = await connectionInventory(loaded.issue.companyId);
let usableAiConnection = managed ? await usableConnectionForAgent({
companyId: loaded.issue.companyId, agentId: payload.requestingAgentId,
- responsibleUserId: loaded.interaction.addresseeUserId!, serviceSlug: app.slug, purpose: "ai",
+ responsibleUserId: loaded.interaction.addresseeUserId!, serviceSlug: app.slug, purpose: "ai", sourceRunId: loaded.interaction.sourceRunId,
}) : null;
if (managed?.requiresAdoption) {
try {
const selected = await aiConnectionService(db).select({
companyId: loaded.issue.companyId, agentId: managed.agent.id, userId: loaded.interaction.addresseeUserId!,
- adapterType: managed.agent.adapterType, model: managed.agent.adapterConfig.model,
- runnerProvider: managed.agent.adapterConfig.provider, acpxAgent: managed.agent.adapterConfig.acpxAgent,
+ adapterType: managed.agent.adapterType, model: managed.adapterConfig.model,
+ runnerProvider: managed.adapterConfig.provider, acpxAgent: managed.adapterConfig.acpxAgent,
binding: managed.binding, allowUninstalledPersonal: true,
});
usableAiConnection = await access.getConnection(selected.connection.id, loaded.issue.companyId);
@@ -1010,19 +1028,19 @@ export function connectionIntentService(db: Db) {
action: "agent.updated", entityType: "agent", entityId: agent.id,
details: { connectionIntentId: interactionId, aiConnectionAdopted: true },
});
- managed = { agent: updated, binding, requiresAdoption: false };
+ managed = { agent: updated, binding, adapterConfig: updated.adapterConfig, requiresAdoption: false };
} else {
- managed = await managedAgent(loaded.issue.companyId, payload.requestingAgentId, payload.serviceSlug);
+ managed = await managedAgent(loaded.issue.companyId, payload.requestingAgentId, payload.serviceSlug, { sourceRunId: loaded.interaction.sourceRunId }, txDb);
}
if (!managed) throw conflict("Configure the agent’s AI connection before using this account");
const service = aiConnectionService(txDb);
if (managed.binding.mode === "responsible_user") {
- const selected = await service.select({ companyId: loaded.issue.companyId, agentId: payload.requestingAgentId, userId, adapterType: managed.agent.adapterType, model: managed.agent.adapterConfig.model, runnerProvider: managed.agent.adapterConfig.provider, acpxAgent: managed.agent.adapterConfig.acpxAgent, binding: managed.binding, allowUninstalledPersonal: true });
+ const selected = await service.select({ companyId: loaded.issue.companyId, agentId: payload.requestingAgentId, userId, adapterType: managed.agent.adapterType, model: managed.adapterConfig.model, runnerProvider: managed.adapterConfig.provider, acpxAgent: managed.adapterConfig.acpxAgent, binding: managed.binding, allowUninstalledPersonal: true });
if (selected.connection.id !== selectedConnection.id) throw conflict("Choose this account as your personal default in Connections first");
const installs = await txAccess.listConnectionInstalls(selectedConnection.id, loaded.issue.companyId);
await txAccess.putConnectionInstalls(selectedConnection.id, { installs: [...installs, { targetType: "agent", targetId: payload.requestingAgentId }] }, { actorType: "user", actorId: userId });
}
- const selected = await service.select({ companyId: loaded.issue.companyId, agentId: payload.requestingAgentId, userId, adapterType: managed.agent.adapterType, model: managed.agent.adapterConfig.model, runnerProvider: managed.agent.adapterConfig.provider, acpxAgent: managed.agent.adapterConfig.acpxAgent, binding: managed.binding });
+ const selected = await service.select({ companyId: loaded.issue.companyId, agentId: payload.requestingAgentId, userId, adapterType: managed.agent.adapterType, model: managed.adapterConfig.model, runnerProvider: managed.adapterConfig.provider, acpxAgent: managed.adapterConfig.acpxAgent, binding: managed.binding });
if (selected.connection.id !== selectedConnection.id) throw conflict("This is not the account selected for the agent");
return txInteractions.resolveConnectionIntent(loaded.issue, interactionId, { version: 1, outcome: "connected", connectionId: selected.connection.id }, { userId });
}
@@ -1157,11 +1175,14 @@ export function connectionIntentService(db: Db) {
const [agent] = await db.select().from(agents).where(and(eq(agents.id, run.agentId), eq(agents.companyId, run.companyId)));
if (!agent) return null;
const saved = aiConnectionBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data;
- const binding = saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig);
+ const router = aiConnectionRouterBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data;
+ const selected = router ? record(run.contextSnapshot?.aiRouterSelection) : null;
+ const managed = router && selected ? await managedAgent(run.companyId, run.agentId, String(record(selected.binding)?.provider), { sourceRunId: run.id }) : null;
+ const binding = router ? managed?.binding : saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig);
if (!binding) return null;
const attribution = record(run.contextSnapshot?.aiConnection);
if (attribution && attribution.provider !== binding.provider) return null;
- if (saved && attribution && typeof attribution.identity === "string" && typeof attribution.connectionId === "string" && typeof attribution.grantId === "string") {
+ if ((saved || managed) && attribution && typeof attribution.identity === "string" && typeof attribution.connectionId === "string" && typeof attribution.grantId === "string") {
await aiConnectionService(db).markAuthenticationFailed({ companyId: run.companyId, runId: run.id, agentId: run.agentId,
runStartedAt: run.startedAt ?? run.createdAt,
attribution: attribution as unknown as AiConnectionAttribution & { identity: string } });
diff --git a/server/src/services/execution-recovery-attempt.test.ts b/server/src/services/execution-recovery-attempt.test.ts
index 2673e2b33c..c434e7b60a 100644
--- a/server/src/services/execution-recovery-attempt.test.ts
+++ b/server/src/services/execution-recovery-attempt.test.ts
@@ -27,7 +27,7 @@ describe("failure attempts across resource waits", () => {
});
describe("persisted independent accounting", () => {
- it.each(["max_turns_continuation", "issue_disposition_repair", "workspace_busy", "ai_connection_busy"])("%s cannot erase prior infrastructure debits or spend more", scheduledRetryReason => {
+ it.each(["max_turns_continuation", "issue_disposition_repair", "workspace_busy", "ai_connection_busy", "ai_connection_pool_wait"])("%s cannot erase prior infrastructure debits or spend more", scheduledRetryReason => {
expect(executionFailureRetryCount({ scheduledRetryReason, scheduledRetryAttempt: 20,
contextSnapshot: { executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 1 } },
})).toBe(2);
diff --git a/server/src/services/execution-recovery-attempt.ts b/server/src/services/execution-recovery-attempt.ts
index 689137d9d9..dec0d847cf 100644
--- a/server/src/services/execution-recovery-attempt.ts
+++ b/server/src/services/execution-recovery-attempt.ts
@@ -28,7 +28,7 @@ function savedAccounting(run: RetryRun): ExecutionRetryAccounting | null {
function historicalFailureCount(run: RetryRun): number {
if (run.scheduledRetryReason === "max_turns_continuation" || run.scheduledRetryReason === "issue_disposition_repair") return 0;
- if (run.scheduledRetryReason === "ai_connection_busy") {
+ if (run.scheduledRetryReason === "ai_connection_busy" || run.scheduledRetryReason === "ai_connection_pool_wait") {
const saved = count(run.contextSnapshot?.failureRetriesBeforeAiConnectionWait);
if (saved !== null) return saved;
}
@@ -42,7 +42,7 @@ function historicalFailureCount(run: RetryRun): number {
export function executionRetryAccounting(run: RetryRun): ExecutionRetryAccounting {
const saved = savedAccounting(run);
- const nonFailureLane = ["max_turns_continuation", "issue_disposition_repair", "workspace_busy", "ai_connection_busy"].includes(run.scheduledRetryReason ?? "");
+ const nonFailureLane = ["max_turns_continuation", "issue_disposition_repair", "workspace_busy", "ai_connection_busy", "ai_connection_pool_wait"].includes(run.scheduledRetryReason ?? "");
return {
version: 1,
failureRetries: Math.max(saved?.failureRetries ?? 0, saved && nonFailureLane ? 0 : historicalFailureCount(run)),
@@ -57,7 +57,7 @@ export function executionFailureRetryCount(run: RetryRun): number {
}
export function executionRetryAttemptCount(run: RetryRun, reason: string): number {
- if (reason === "workspace_busy" || reason === "ai_connection_busy") {
+ if (reason === "workspace_busy" || reason === "ai_connection_busy" || reason === "ai_connection_pool_wait") {
return run.scheduledRetryReason === reason ? count(run.scheduledRetryAttempt) ?? 0 : 0;
}
const accounting = executionRetryAccounting(run);
@@ -67,6 +67,6 @@ export function executionRetryAttemptCount(run: RetryRun, reason: string): numbe
export function accountingForScheduledRetry(run: RetryRun, reason: string, attempt: number): ExecutionRetryAccounting {
const accounting = executionRetryAccounting(run);
if (reason === "max_turns_continuation") accounting.maxTurnContinuations = attempt;
- else if (reason !== "workspace_busy" && reason !== "ai_connection_busy") accounting.failureRetries = attempt;
+ else if (reason !== "workspace_busy" && reason !== "ai_connection_busy" && reason !== "ai_connection_pool_wait") accounting.failureRetries = attempt;
return accounting;
}
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index f6186b718f..9e8617e2fc 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -39,7 +39,9 @@ import { admitExplicitNativeContinuation, admitExplicitContinuationRetry, undeli
import { canRetryStoppedRun, isCancelledNativeStartup } from "./cancelled-native-startup.js";
import { connectionIntentService } from "./connection-intents.js";
import { managedAiSessionFingerprintConfig, prepareManagedAiRuntime, assertManagedAiProjectAuth, stripAiAuthBindings, isAiConnectionBusy, AI_AUTH_ENV_KEYS } from "./ai-connection-runtime.js";
-import { aiConnectionBindingSchema } from "@paperclipai/shared";
+import { aiConnectionBindingSchema, aiRuntimeConnectionBindingSchema, type AiConnectionRouterSelection } from "@paperclipai/shared";
+import { aiConnectionRouterService, AiConnectionPoolExhausted, applyAiConnectionRouterTaskSettings } from "./ai-connection-router.js";
+import { aiConnectionSessionCompatibilityInputs, managedAiSessionIdentityCompatible } from "./ai-connection-session.js";
import { executionBlockerPredicate, getExecutionBlocker } from "./execution-blocker.js";
import { CONVERSATION_CONTINUATION_POLICY, claimedAdapterType, runUsedConversationAdapter, hasConversationContinuationPolicy, isConversationAdapter } from "./conversation-continuation.js";
import { recordExecutionWait } from "./execution-wait.js";
@@ -539,6 +541,7 @@ import {
MAX_TURN_CONTINUATION_RETRY_REASON,
WORKSPACE_BUSY_RETRY_REASON,
AI_CONNECTION_BUSY_RETRY_REASON,
+ AI_CONNECTION_POOL_WAIT_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
WAKE_COMMENT_IDS_KEY,
@@ -6975,6 +6978,7 @@ export function resolveTaskSessionConfigFreshness(input: {
configuredModel: string | null;
taskSessionParams: Record<string, unknown> | null | undefined;
configMetadata: EffectiveRunSessionConfigMetadata | null;
+ compatibleConfigMetadata?: readonly EffectiveRunSessionConfigMetadata[];
wakeResetReason?: string | null;
preserveLegacySessionWithoutConfigMetadata?: boolean;
}): TaskSessionConfigFreshnessDecision {
@@ -7022,7 +7026,8 @@ export function resolveTaskSessionConfigFreshness(input: {
);
} else if (
storedConfig &&
- storedConfig.fingerprint !== input.configMetadata.fingerprint
+ storedConfig.fingerprint !== input.configMetadata.fingerprint &&
+ !input.compatibleConfigMetadata?.some(candidate => candidate.version === storedConfig.version && candidate.fingerprint === storedConfig.fingerprint)
) {
changedCategories = changedEffectiveRunSessionConfigCategories({
previous: storedConfig.categoryFingerprints,
@@ -15582,7 +15587,7 @@ export function heartbeatService(
const requiresIssueGate =
isTransientWorkspaceGitScanCode(run.errorCode) ||
hasConversationContinuationPolicy(run.resultJson) ||
- retryReason === AI_CONNECTION_BUSY_RETRY_REASON ||
+ (retryReason === AI_CONNECTION_BUSY_RETRY_REASON || retryReason === AI_CONNECTION_POOL_WAIT_RETRY_REASON) ||
retryReason === MAX_TURN_CONTINUATION_RETRY_REASON ||
retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON;
if (requiresIssueGate) {
@@ -15652,7 +15657,7 @@ export function heartbeatService(
executionFailureRetryCount(run),
}
: {}),
- ...(retryReason === AI_CONNECTION_BUSY_RETRY_REASON
+ ...((retryReason === AI_CONNECTION_BUSY_RETRY_REASON || retryReason === AI_CONNECTION_POOL_WAIT_RETRY_REASON)
? { failureRetriesBeforeAiConnectionWait: executionFailureRetryCount(run) }
: {}),
...(shouldQuarantineWorkspaceForRetry
@@ -15979,7 +15984,7 @@ export function heartbeatService(
}
if (
- retryReason === AI_CONNECTION_BUSY_RETRY_REASON && issueId &&
+ (retryReason === AI_CONNECTION_BUSY_RETRY_REASON || retryReason === AI_CONNECTION_POOL_WAIT_RETRY_REASON) && issueId &&
!isNonAssigneeWorkspaceBusyRetry(retryReason, contextSnapshot)
) {
// The issue row is locked above. Recheck after the preflight gate so
@@ -20519,7 +20524,7 @@ export function heartbeatService(
let readFailureReportSecrets: () => string[] = () => [];
try {
- const agent = await getAgent(run.agentId);
+ let agent = await getAgent(run.agentId);
if (!agent) {
await setRunStatus(runId, "failed", {
error: "Agent not found",
@@ -20770,7 +20775,7 @@ export function heartbeatService(
: row;
})
: null;
- const issueAssigneeOverrides =
+ let issueAssigneeOverrides =
issueContext && issueContext.assigneeAgentId === agent.id
? parseIssueAssigneeAdapterOverrides(
issueContext.assigneeAdapterOverrides,
@@ -20976,7 +20981,7 @@ export function heartbeatService(
// durable for authorization and operation-time credential resolution.
context.executionPolicy = retainedTrust.executionPolicy;
}
- const config = parseObject(agent.adapterConfig);
+ let config = parseObject(agent.adapterConfig);
const taskSession = taskKey
? await getTaskSession(
agent.companyId,
@@ -20985,6 +20990,53 @@ export function heartbeatService(
taskKey,
)
: null;
+ const routerHasPersistedInput = Object.keys(parseObject(parseObject(run.runnerProfileJson).nativeExecutionInput)).length > 0;
+ const persistedRouterPoolId = routerHasPersistedInput ? readNonEmptyString(parseObject(context.aiRouterSelection).poolId) : null;
+ const requestedAiBinding = persistedRouterPoolId ? { mode: "router" as const, connectionId: persistedRouterPoolId } : agent.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined;
+ let aiBinding = requestedAiBinding?.mode === "router" ? undefined : requestedAiBinding;
+ const originalAiIssueOverrides = issueAssigneeOverrides;
+ if (requestedAiBinding?.mode === "router") {
+ try {
+ const routerTaskKey = readNonEmptyString(context.aiRouterTaskKey) ?? taskKey ?? run.id;
+ // A retry must retain the original run-key affinity even if the host
+ // crashes after committing a pin but before recording its selection.
+ if (routerTaskKey !== run.contextSnapshot?.aiRouterTaskKey) {
+ await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiRouterTaskKey: routerTaskKey })}::jsonb` }).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, agent.companyId)));
+ }
+ context.aiRouterTaskKey = routerTaskKey;
+ const savedIdentity = taskSession?.sessionParamsJson?.paperclipAiCredentialIdentity;
+ const selection = await aiConnectionRouterService(db, options.pluginWorkerManager).resolve({
+ companyId: agent.companyId, poolId: requestedAiBinding.connectionId, agentId: agent.id,
+ userId: responsibleUserId, adapterType: agent.adapterType, taskKey: String(context.aiRouterTaskKey),
+ overrides: issueAssigneeOverrides?.adapterConfig ?? {},
+ existingGrantId: typeof savedIdentity === "string" ? savedIdentity.split(":")[0] : undefined,
+ requireExisting: Boolean(taskSession?.sessionDisplayId) && !shouldResetTaskSessionForWake(context),
+ persisted: routerHasPersistedInput ? context.aiRouterSelection as AiConnectionRouterSelection | undefined : undefined,
+ });
+ aiBinding = selection.binding;
+ // Provider-specific fields from the configured harness must not leak into the selected member.
+ config = applyAiConnectionRouterTaskSettings(config, selection);
+ if (issueAssigneeOverrides) issueAssigneeOverrides = { ...issueAssigneeOverrides, adapterConfig: applyAiConnectionRouterTaskSettings(issueAssigneeOverrides.adapterConfig ?? {}, selection) };
+ agent = { ...agent, adapterConfig: config };
+ context.aiRouterSelection = selection;
+ await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiRouterTaskKey: context.aiRouterTaskKey, aiRouterSelection: selection })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
+ await appendRunEvent(run, { eventType: "lifecycle", stream: "system", level: "info", message: "Using task-pinned pool account", payload: { poolId: selection.poolId, memberId: selection.memberId, provider: aiBinding.provider, model: config.model, notes: selection.notes } });
+ } catch (error) {
+ if (error instanceof AiConnectionPoolExhausted && !routerHasPersistedInput) {
+ const now = new Date();
+ context.aiConnectionBusyDeferredWhileAssignee = issueContext?.assigneeAgentId === agent.id;
+ const cancelled = await setRunStatusIfRunning(run.id, "cancelled", { error: error.message, errorCode: error.code, finishedAt: now, resultJson: { executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: false }, retryAt: error.retryAt }, contextSnapshot: context });
+ if (cancelled.updated) {
+ await setWakeupStatus(run.wakeupRequestId, "cancelled", { finishedAt: now, error: error.message });
+ const retry = await scheduleBoundedRetryForRun(cancelled.run ?? run, agent, { now, retryReason: AI_CONNECTION_POOL_WAIT_RETRY_REASON, wakeReason: "ai_connection_pool_retry", maxAttempts: (run.scheduledRetryAttempt ?? 0) + 1, delayMs: Math.max(1000, Date.parse(error.retryAt) - Date.now()) });
+ if (retry.outcome !== "scheduled") await releaseIssueExecutionAndPromote(cancelled.run ?? run);
+ await finalizeAgentStatus(run.agentId, "cancelled");
+ }
+ return;
+ }
+ throw new ConfigurationIncompleteFailure(error instanceof Error ? error.message : "Configure this connection pool", { configurationIncomplete: { reason: "ai_connection_unavailable", companyId: agent.companyId, agentId: agent.id, responsibleUserId, actionUrl: `/agents/${agent.id}/runtime`, fingerprint: `ai-router:${requestedAiBinding.connectionId}` } });
+ }
+ }
if (isConversation(issueContext)) {
delete context.resumeSessionParams;
delete context.resumeSessionDisplayId;
@@ -21649,7 +21701,8 @@ export function heartbeatService(
});
const mergedConfig = {
...workspaceManagedConfig,
- ...(issueAssigneeOverrides?.adapterConfig ?? {}),
+ ...Object.fromEntries(Object.entries(issueAssigneeOverrides?.adapterConfig ?? {}).filter(([key]) => requestedAiBinding?.mode !== "router" || !["provider", "acpxAgent", "model", "modelReasoningEffort", "reasoningEffort", "effort", "variant"].includes(key))),
+ ...(requestedAiBinding?.mode === "router" ? parseObject(parseObject(context.aiRouterSelection).runtimeConfig) : {}),
// The base below is already task-owned. Keep directory transport while
// preserving isolated mode and the mandatory sandbox preflight.
...(useIsolatedTaskDirectory ? { workspaceStrategy: { type: "project_primary" } } : {}),
@@ -21686,7 +21739,7 @@ export function heartbeatService(
["local", "ssh"].includes(
selectedEnvironmentForConfig?.driver ?? "local",
);
- const aiBinding = agent.runtimeConfig?.aiConnection ? aiConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined;
+
const { resolvedConfig, secretKeys, secretManifest } =
await resolveExecutionRunAdapterConfig({
managedAiCredentials: Boolean(aiBinding),
@@ -21736,13 +21789,18 @@ export function heartbeatService(
fingerprint: `ai:${agent.id}:${responsibleUserId}:${JSON.stringify(aiBinding)}` },
});
}
- if (persistedNativeExecutionInput && parseObject(run.contextSnapshot?.aiConnection).identity !== managedAiRuntime.identity) {
+ const savedAiAccount = parseObject(run.contextSnapshot?.aiConnection);
+ if (persistedNativeExecutionInput && !managedAiSessionIdentityCompatible(
+ savedAiAccount.sessionIdentity ?? savedAiAccount.identity,
+ managedAiRuntime.sessionIdentity,
+ managedAiRuntime.identity,
+ )) {
throw new ConfigurationIncompleteFailure("The AI account changed while this native run was suspended. Start a new execution.", { configurationIncomplete: { reason: "ai_connection_changed", actionUrl: `/agents/${agent.id}/runtime` } });
}
Object.assign(resolvedConfig, managedAiRuntime.config);
for (const key of AI_AUTH_ENV_KEYS) secretKeys.add(key);
- context.aiConnection = { ...managedAiRuntime.attribution, identity: managedAiRuntime.identity };
- await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiConnection: context.aiConnection })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
+ context.aiConnection = { ...managedAiRuntime.attribution, accountName: managedAiRuntime.accountName, identity: managedAiRuntime.identity, sessionIdentity: managedAiRuntime.sessionIdentity };
+ await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiConnection: context.aiConnection, ...(context.aiRouterTaskKey ? { aiRouterTaskKey: context.aiRouterTaskKey } : {}), ...(context.aiRouterSelection ? { aiRouterSelection: context.aiRouterSelection } : {}) })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
}
if (secretManifest.length > 0) {
context.paperclipSecrets = {
@@ -21811,8 +21869,7 @@ export function heartbeatService(
agent.companyId,
agent.id,
);
- const sessionConfigMetadata =
- await buildEffectiveRunSessionConfigMetadata({
+ const sessionConfigMetadataInput = {
adapterType: agent.adapterType,
effectiveAdapterConfig: runtimeConfig,
managedAiHome: managedAiRuntime?.home,
@@ -21876,7 +21933,24 @@ export function heartbeatService(
latestAgentConfigRevision.createdAt.toISOString(),
}
: null,
+ };
+ const sessionConfigMetadata = await buildEffectiveRunSessionConfigMetadata(sessionConfigMetadataInput);
+ let compatibleConfigMetadata: EffectiveRunSessionConfigMetadata[] = [];
+ if (managedAiRuntime && aiBinding && taskSession &&
+ readConfigFingerprintFromSessionParams(taskSession.sessionParamsJson)?.fingerprint !== sessionConfigMetadata.fingerprint) {
+ const revisions = requestedAiBinding?.mode === "router"
+ ? await db.select().from(agentConfigRevisions).where(and(eq(agentConfigRevisions.companyId, agent.companyId), eq(agentConfigRevisions.agentId, agent.id))).orderBy(desc(agentConfigRevisions.createdAt), desc(agentConfigRevisions.id)).limit(21)
+ : [];
+ const candidates = aiConnectionSessionCompatibilityInputs({
+ effectiveAdapterConfig: runtimeConfig, agentRuntimeConfig: agent.runtimeConfig,
+ agentConfigRevision: sessionConfigMetadataInput.agentConfigRevision,
+ issueOverrides: issueAssigneeOverrides, originalIssueOverrides: originalAiIssueOverrides,
+ binding: aiBinding, router: requestedAiBinding?.mode === "router",
+ storedIdentity: taskSession.sessionParamsJson?.paperclipAiCredentialIdentity,
+ sessionIdentity: managedAiRuntime.sessionIdentity, credentialIdentity: managedAiRuntime.identity, revisions,
});
+ compatibleConfigMetadata = await Promise.all(candidates.map(candidate => buildEffectiveRunSessionConfigMetadata({ ...sessionConfigMetadataInput, ...candidate })));
+ }
const configuredModel =
readConfiguredModelFromAdapterConfig(runtimeConfig);
if (context.refreshTools === true && agent.adapterType !== "paperclip_runner") {
@@ -21891,6 +21965,7 @@ export function heartbeatService(
taskSessionParams:
taskSession?.sessionParamsJson ?? taskSessionDecodedParams,
configMetadata: sessionConfigMetadata,
+ compatibleConfigMetadata,
wakeResetReason: wakeSessionResetReason,
preserveLegacySessionWithoutConfigMetadata:
acceptedPlanContinuationWake && !acceptedPlanWakeRoutingDecision,
@@ -23140,12 +23215,13 @@ export function heartbeatService(
delete context.paperclipPreviousSessionId;
}
- const taskSessionCredentialCompatible = isTaskSessionCredentialCompatible(
- taskSession?.sessionParamsJson,
- managedAiRuntime?.identity,
+ const taskSessionCredentialCompatible = !managedAiRuntime || managedAiSessionIdentityCompatible(
+ taskSession?.sessionParamsJson?.paperclipAiCredentialIdentity,
+ managedAiRuntime.sessionIdentity,
+ managedAiRuntime.identity,
);
if (managedAiRuntime) {
- sessionConfigMetadata.aiCredentialIdentity = managedAiRuntime.identity;
+ sessionConfigMetadata.aiCredentialIdentity = managedAiRuntime.sessionIdentity;
if (!taskSessionCredentialCompatible) {
runtimeSessionIdForAdapter = null;
runtimeSessionParamsForAdapter = null;
diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts
index 1191d7afab..18d85bdbd1 100644
--- a/server/src/services/instance-settings.ts
+++ b/server/src/services/instance-settings.ts
@@ -223,6 +223,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
return {
enableEnvironments: parsed.data.enableEnvironments ?? false,
enableNativeRunner: parsed.data.enableNativeRunner ?? true,
+ enableAiConnectionRouters: parsed.data.enableAiConnectionRouters ?? false,
enableManagedSandboxOnly: parsed.data.enableManagedSandboxOnly ?? false,
enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false,
enableIsolatedWorkspacesByDefault: parsed.data.enableIsolatedWorkspacesByDefault ?? false,
@@ -269,6 +270,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
return {
enableEnvironments: false,
enableNativeRunner: true,
+ enableAiConnectionRouters: false,
enableManagedSandboxOnly: false,
enableIsolatedWorkspaces: false,
enableIsolatedWorkspacesByDefault: false,
diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts
index 6ab86f7ee4..64c4c7f2db 100644
--- a/server/src/services/legacy-execution-recovery.ts
+++ b/server/src/services/legacy-execution-recovery.ts
@@ -39,7 +39,7 @@ export function legacyExecutionNeedsReconciliation(
&& (run.resultJson?.executionCancellation as Record<string, unknown> | undefined)?.state === "acknowledged") return false;
// Waiting for a subscription or workspace precedes provider execution. It is
// a resource wait, not a failed provider attempt or permission to replay work.
- if (run.status === "cancelled" && run.errorCode === "ai_connection_busy" &&
+ if (run.status === "cancelled" && (run.errorCode === "ai_connection_busy" || run.errorCode === "ai_connection_pool_exhausted") &&
evidence?.kind === "ai_connection_wait" && evidence.providerWorkStarted === false) return false;
if (run.status === "cancelled" && run.errorCode === "workspace_busy" &&
evidence?.kind === "workspace_wait" && evidence.providerWorkStarted === false) return false;
diff --git a/server/src/services/secrets.ts b/server/src/services/secrets.ts
index 143275d094..6549cf69e0 100644
--- a/server/src/services/secrets.ts
+++ b/server/src/services/secrets.ts
@@ -2397,6 +2397,8 @@ export function secretService(db: Db | DbTransaction) {
// update matches the latest version, so a concurrent rotation between the
// read and the write cannot pass. A mismatch throws a 409 conflict.
expectedLatestVersion?: number;
+ /** Internal authenticated refresh write-back only; never accepted by HTTP schemas. */
+ preserveAiSessionEpoch?: boolean;
},
actor?: { userId?: string | null; agentId?: string | null },
) {
@@ -2534,6 +2536,7 @@ export function secretService(db: Db | DbTransaction) {
.update(companySecrets)
.set({
latestVersion: nextVersion,
+ aiSessionEpoch: input.preserveAiSessionEpoch ? secret.aiSessionEpoch : sql`${companySecrets.aiSessionEpoch} + 1`,
externalRef: prepared.externalRef,
providerConfigId,
lastRotatedAt: new Date(),
@@ -4589,6 +4592,8 @@ export function secretService(db: Db | DbTransaction) {
providerVersionRef?: string | null;
providerConfigId?: string | null;
expectedLatestVersion?: number;
+ /** Internal authenticated refresh write-back only; never accepted by HTTP schemas. */
+ preserveAiSessionEpoch?: boolean;
},
actor?: { userId?: string | null; agentId?: string | null },
) => {
diff --git a/tests/ai-connections-app/connection-pools.spec.ts b/tests/ai-connections-app/connection-pools.spec.ts
new file mode 100644
index 0000000000..e90135ce17
--- /dev/null
+++ b/tests/ai-connections-app/connection-pools.spec.ts
@@ -0,0 +1,159 @@
+import { expect, test, type APIRequestContext } from "@playwright/test";
+import type { AiConnectionList, AiConnectionPool, AppDefinition } from "@paperclipai/shared";
+
+// Exercise the full shipped app and an installed router, with real persistence.
+// No browser routes, credentials, providers, or pool APIs are mocked. Opt in
+// only against a loopback test-drive company with existing saved accounts.
+const companyId = process.env.AI_CONNECTIONS_TEST_COMPANY_ID;
+test.skip(process.env.PAPERCLIP_CONNECTION_POOL_E2E !== "1" || !companyId, "Opt in with an isolated connection-pool test drive");
+let prefix: string;
+let connector: AppDefinition;
+let accounts: AiConnectionList["connections"];
+const poolsPath = `/api/companies/${companyId}/ai-connection-pools`;
+async function listPools(request: APIRequestContext): Promise<AiConnectionPool[]> {
+ const response = await request.get(poolsPath);
+ expect(response.ok()).toBe(true);
+ return response.json();
+}
+
+test.beforeAll(async ({ request }, testInfo) => {
+ const origin = new URL(testInfo.project.use.baseURL!);
+ expect(origin.protocol).toBe("http:");
+ expect(["127.0.0.1", "[::1]"]).toContain(origin.hostname);
+ const health = await (await request.get("/api/health")).json();
+ expect(health).toMatchObject({ status: "ok", bootstrapStatus: "ready", deploymentMode: "local_trusted" });
+ const company = await (await request.get(`/api/companies/${companyId}`)).json();
+ expect(company.name).toMatch(/test drive|e2e/i);
+ prefix = company.issuePrefix;
+ const gallery = await (await request.get(`/api/companies/${companyId}/tools/gallery`)).json();
+ connector = gallery.apps.find((app: AppDefinition) => app.aiConnectionRouter && app.availability?.available);
+ expect(connector, "Install and enable a router plugin, then opt in to the instance flag").toBeTruthy();
+ const list: AiConnectionList = await (await request.get(`/api/companies/${companyId}/ai-connections`)).json();
+ expect(list.canManageConnections).toBe(true);
+ accounts = list.connections.filter((account, index, all) => account.status === "connected" && all.findIndex(candidate => candidate.id === account.id) === index).slice(0, 2);
+ expect(accounts, "Use two pre-existing authorized accounts").toHaveLength(2);
+});
+
+test("operator-enabled routing has no experimental settings control", async ({ page, request }) => {
+ const response = await request.get("/api/instance/settings/experimental");
+ expect(response.ok()).toBe(true);
+ expect(await response.json()).toMatchObject({ enableAiConnectionRouters: true });
+ await page.goto(`/${prefix}/company/settings/instance/experimental`);
+ await expect(page.getByRole("heading", { name: "Experimental", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Experimental features", exact: true })).toBeVisible();
+ await expect(page.getByText("AI connection routers", { exact: true })).toHaveCount(0);
+ await expect(page.getByRole("switch", { name: "Toggle AI connection routers experimental setting", exact: true })).toHaveCount(0);
+});
+
+test("native catalog setup, account edits, conflicts and removal persist through the full app", async ({ page, request }) => {
+ test.setTimeout(90_000);
+ const originalPools = await listPools(request);
+ const originalAccountIds = (await (await request.get(`/api/companies/${companyId}/ai-connections`)).json()).connections.map((account: { id: string }) => account.id).sort();
+ let poolId: string | undefined;
+ try {
+ await page.goto(`/${prefix}/dashboard`);
+ await page.getByRole("link", { name: "Connectors", exact: true }).click();
+ await page.getByRole("button", { name: `Add connection pool ${connector.name}`, exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Add a connection pool", exact: true })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Continue", exact: true })).toBeDisabled();
+ await expect(page.getByRole("link", { name: "Connect a new account", exact: true })).toHaveAttribute("target", "_blank");
+ for (const account of accounts) await page.getByRole("checkbox", { name: account.name, exact: true }).check();
+ await page.getByRole("button", { name: "Continue", exact: true }).click();
+ await page.getByRole("button", { name: `Move ${accounts[1]!.name} up`, exact: true }).click();
+ await page.getByRole("button", { name: "Back", exact: true }).click();
+ for (const account of accounts) await expect(page.getByRole("checkbox", { name: account.name, exact: true })).toBeChecked();
+ await page.getByRole("button", { name: "Continue", exact: true }).click();
+ await expect(page.getByRole("list", { name: "Connection order" }).getByRole("listitem").first()).toContainText(accounts[1]!.name);
+ await page.getByRole("button", { name: "Create pool", exact: true }).click();
+ await expect(page).toHaveURL(/\/apps\/[a-f0-9-]+\/permissions$/);
+ poolId = new URL(page.url()).pathname.split("/").at(-2)!;
+ const saved = async () => (await listPools(request)).find(pool => pool.id === poolId)!;
+ expect(await saved()).toMatchObject({ enabled: false, mode: "round_robin", thresholdPercent: 90 });
+ expect((await saved()).members.map(member => member.binding.connectionId)).toEqual([accounts[1]!.id, accounts[0]!.id]);
+ await expect(page.getByRole("link", { name: "Settings", exact: true })).toBeVisible();
+ await expect(page.getByRole("link", { name: "Review", exact: true })).toHaveCount(0);
+ await expect(page.getByRole("checkbox", { name: "Enable this pool", exact: true })).not.toBeChecked();
+ await expect(page.getByRole("region", { name: "Used by", exact: true })).toContainText("No agents yet.");
+
+ const name = `Pool E2E ${Date.now()}`;
+ await page.getByRole("button", { name: "Rename app", exact: true }).click();
+ await page.getByRole("textbox", { name: "App name", exact: true }).fill(name);
+ await page.getByRole("button", { name: "Save", exact: true }).click();
+ await expect(page.getByRole("heading", { name, level: 1 })).toBeVisible();
+ await page.getByRole("button", { name: `Remove ${accounts[0]!.name}`, exact: true }).click();
+ await page.getByRole("button", { name: "Save changes", exact: true }).click();
+ await expect.poll(async () => (await saved()).members.length).toBe(1);
+ await page.reload();
+ await expect(page.getByRole("list", { name: "Connection order" }).getByRole("listitem")).toHaveCount(1);
+ await page.getByRole("button", { name: "Add connections", exact: true }).click();
+ const picker = page.getByRole("dialog", { name: "Add connections", exact: true });
+ await picker.getByRole("checkbox", { name: accounts[0]!.name, exact: true }).check();
+ await picker.getByRole("button", { name: "Done", exact: true }).click();
+ await page.getByRole("checkbox", { name: "Enable this pool", exact: true }).check();
+ await page.getByRole("button", { name: "Save changes", exact: true }).click();
+ await expect.poll(async () => (await saved()).enabled).toBe(true);
+ await page.reload();
+ await expect(page.getByRole("heading", { name, level: 1 })).toBeVisible();
+ await expect(page.getByRole("checkbox", { name: "Enable this pool", exact: true })).toBeChecked();
+ await expect(page.getByRole("list", { name: "Connection order" }).getByRole("listitem")).toHaveCount(2);
+
+ // Two real pages keep their reviewed revisions. A stale save must not
+ // overwrite a newer edit, and refreshing must recover the latest version.
+ const other = await page.context().newPage();
+ await other.goto(page.url());
+ await expect(other.getByRole("heading", { name, level: 1 })).toBeVisible();
+ await page.getByRole("checkbox", { name: "Enable this pool", exact: true }).uncheck();
+ await page.getByRole("button", { name: "Save changes", exact: true }).click();
+ await expect.poll(async () => (await saved()).enabled).toBe(false);
+ await other.getByRole("button", { name: "Save changes", exact: true }).click();
+ await expect(other.getByRole("alert")).toContainText(/changed|reload/i);
+ expect((await saved()).enabled).toBe(false);
+ await other.close();
+
+ await page.getByRole("button", { name: "Manage connection pool", exact: true }).click();
+ await page.getByRole("menuitem", { name: "Remove connection", exact: true }).click();
+ const confirmation = page.getByRole("alertdialog");
+ await expect(confirmation).toContainText("The connections in this pool are kept.");
+ await confirmation.getByRole("button", { name: "Cancel", exact: true }).click();
+ expect(await saved()).toBeTruthy();
+ await page.getByRole("link", { name: "All connectors", exact: true }).click();
+ await page.getByRole("button", { name: `Manage ${name} connection`, exact: true }).click();
+ await page.getByRole("menuitem", { name: "Remove connection", exact: true }).click();
+ await page.getByRole("alertdialog").getByRole("button", { name: "Remove connection", exact: true }).click();
+ await expect(page.getByRole("alertdialog")).toHaveCount(0);
+ await expect.poll(async () => (await listPools(request)).map(pool => pool.id).sort()).toEqual(originalPools.map(pool => pool.id).sort());
+ await expect(page.getByRole("button", { name: `Open ${name} permissions`, exact: true })).toHaveCount(0);
+ const remaining = await (await request.get(`/api/companies/${companyId}/ai-connections`)).json();
+ expect(remaining.connections.map((account: { id: string }) => account.id).sort()).toEqual(originalAccountIds);
+ } finally {
+ // Cleanup only this test's own disposable pool, through the normal API.
+ if (poolId) {
+ const pool = (await listPools(request)).find(pool => pool.id === poolId);
+ if (pool) expect((await request.delete(`${poolsPath}/${poolId}`, { data: { expectedRevision: pool.revision } })).ok()).toBe(true);
+ }
+ }
+});
+
+test("an unavailable dynamic router stays on an actionable setup page", async ({ page }) => {
+ await page.goto(`/${prefix}/apps/connect?${new URLSearchParams({ source: "ai-router-0000" })}`);
+ await expect(page.getByRole("alert")).toContainText("This connection pool plugin is unavailable. Enable it in Plugins.");
+ await expect(page).toHaveURL(/\/apps\/connect\?/);
+});
+
+test("a saved pool shows its configured agents with avatars and profile links", async ({ page, request }) => {
+ const pools = await listPools(request);
+ const response = await request.get(`/api/companies/${companyId}/agents`);
+ expect(response.ok()).toBe(true);
+ const agents = await response.json() as Array<{ id: string; name: string; status: string; runtimeConfig: { aiConnection?: { mode: string; connectionId?: string } } }>;
+ const pool = pools.find(candidate => agents.some(agent => agent.status !== "terminated" && agent.runtimeConfig.aiConnection?.mode === "router" && agent.runtimeConfig.aiConnection.connectionId === candidate.id));
+ test.skip(!pool, "Bind a test agent to a saved pool to verify populated usage");
+ const expected = agents.filter(agent => agent.status !== "terminated" && agent.runtimeConfig.aiConnection?.mode === "router" && agent.runtimeConfig.aiConnection.connectionId === pool!.id).sort((a, b) => a.name.localeCompare(b.name));
+ await page.goto(`/${prefix}/apps/${pool!.id}/permissions`);
+ const usedBy = page.getByRole("region", { name: "Used by", exact: true });
+ await expect(usedBy.getByRole("link")).toHaveCount(expected.length);
+ for (const agent of expected) {
+ const link = usedBy.getByRole("link", { name: agent.name, exact: true });
+ await expect(link).toHaveAttribute("href", `/${prefix}/agents/${agent.id}`);
+ await expect(link.locator('[data-slot="agent-avatar"]')).toBeVisible();
+ }
+});
diff --git a/ui/public/brands/apps/connection-pool.svg b/ui/public/brands/apps/connection-pool.svg
new file mode 100644
index 0000000000..a3b2b9a65e
--- /dev/null
+++ b/ui/public/brands/apps/connection-pool.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#8b8b8b" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m17 2 4 4-4 4M3 11V8a2 2 0 0 1 2-2h16M7 22l-4-4 4-4m14-1v3a2 2 0 0 1-2 2H3"/></svg>
diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts
index d1709a6800..7bd9cce985 100644
--- a/ui/src/api/agents.ts
+++ b/ui/src/api/agents.ts
@@ -226,11 +226,12 @@ export const agentsApi = {
adapterModels: (
companyId: string,
type: string,
- options?: { refresh?: boolean; environmentId?: string | null; provider?: string },
+ options?: { refresh?: boolean; environmentId?: string | null; provider?: string; poolId?: string },
) => {
const params = new URLSearchParams();
if (options?.refresh) params.set("refresh", "1");
if (options?.provider) params.set("provider", options.provider);
+ if (options?.poolId) params.set("poolId", options.poolId);
if (options?.environmentId) params.set("environmentId", options.environmentId);
const query = params.size > 0 ? `?${params.toString()}` : "";
return api.get<AdapterModel[]>(
@@ -246,7 +247,7 @@ export const agentsApi = {
type: string,
data: {
adapterConfig: Record<string, unknown>;
- aiConnection?: import("@paperclipai/shared").AiConnectionBinding;
+ aiConnection?: import("@paperclipai/shared").AiRuntimeConnectionBinding;
agentId?: string;
testCredentials?: Record<string, string>;
environmentId?: string | null;
diff --git a/ui/src/api/ai-connection-pools.ts b/ui/src/api/ai-connection-pools.ts
new file mode 100644
index 0000000000..20ffd06024
--- /dev/null
+++ b/ui/src/api/ai-connection-pools.ts
@@ -0,0 +1,9 @@
+import type { AiConnectionPool, AiConnectionPoolConfig, AiConnectionUsage } from "@paperclipai/shared";
+import { api } from "./client";
+export type PoolInspection = Record<string, { reason: string; checkedAt: string | null; usage?: AiConnectionUsage }>;
+export const aiConnectionPoolsApi = {
+ list: (companyId: string) => api.get<AiConnectionPool[]>(`/companies/${companyId}/ai-connection-pools`),
+ save: (companyId: string, body: { pluginKey: string; id?: string; expectedRevision?: number; config: AiConnectionPoolConfig }) => api.post<AiConnectionPool>(`/companies/${companyId}/ai-connection-pools`, body),
+ inspect: (companyId: string, id: string) => api.get<PoolInspection>(`/companies/${companyId}/ai-connection-pools/${id}/inspection`),
+ remove: (companyId: string, id: string, expectedRevision: number) => api.delete(`/companies/${companyId}/ai-connection-pools/${id}`, { expectedRevision }),
+};
diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx
index 630db5ca15..6f65505776 100644
--- a/ui/src/components/AgentConfigForm.tsx
+++ b/ui/src/components/AgentConfigForm.tsx
@@ -1,5 +1,5 @@
import { AiConnectionField } from "./ai-connections/AiConnectionField";
-import { aiConnectionBindingSchema } from "@paperclipai/shared";
+import { aiConnectionBindingSchema, aiRuntimeConnectionBindingSchema } from "@paperclipai/shared";
import { testAgentSetup } from "@/lib/test-agent-setup";
import { setupEfforts } from "../lib/agent-setup-fields";
import { RuntimeTestCard } from "./RuntimeTestCard";
@@ -1061,7 +1061,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
});
const adapterConfig = buildAdapterConfigForTest(adapterConfigPatch);
const agentId = isCreate ? undefined : props.agent.id;
- const aiConnection = isCreate ? undefined : aiConnectionBindingSchema.safeParse(
+ const aiConnection = isCreate ? undefined : aiRuntimeConnectionBindingSchema.safeParse(
(overlay.runtime.runtimeConfig as Record<string, unknown> | undefined)?.aiConnection ?? props.agent.runtimeConfig.aiConnection,
).data;
if (props.compactTestFeedback) {
@@ -1659,7 +1659,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
)}
{!isCreate && selectedCompanyId && <AiConnectionField companyId={selectedCompanyId} agentId={props.agent.id} agentName={props.agent.name} adapterType={adapterType === "paperclip_runner" ? eff("adapterConfig", "provider", config.provider) === "codex" ? "codex_local" : eff("adapterConfig", "provider", config.provider) === "opencode" ? "opencode_local" : eff("adapterConfig", "provider", config.provider) === "acpx" && eff("adapterConfig", "acpxAgent", config.acpxAgent) === "grok" ? "grok_local" : eff("adapterConfig", "provider", config.provider) === "acpx" && eff("adapterConfig", "acpxAgent", config.acpxAgent) === "claude" ? "claude_local" : adapterType : adapterType}
- value={aiConnectionBindingSchema.safeParse((overlay.runtime.runtimeConfig as Record<string, unknown> | undefined)?.aiConnection ?? runtimeConfig.aiConnection).data}
+ routerAdapterType={adapterType} value={aiRuntimeConnectionBindingSchema.safeParse((overlay.runtime.runtimeConfig as Record<string, unknown> | undefined)?.aiConnection ?? runtimeConfig.aiConnection).data}
model={String(eff("adapterConfig", "model", config.model) ?? "")} environmentId={currentDefaultEnvironmentId || undefined} legacy
onChange={binding => mark("runtime", "runtimeConfig", { ...runtimeConfig, aiConnection: binding })} />}
diff --git a/ui/src/components/AppConnectionSidebar.test.tsx b/ui/src/components/AppConnectionSidebar.test.tsx
index 5cbc65cdf8..a240268afa 100644
--- a/ui/src/components/AppConnectionSidebar.test.tsx
+++ b/ui/src/components/AppConnectionSidebar.test.tsx
@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AppDetailSidebar } from "./AppConnectionSidebar";
+import { aiConnectionRouterAppDefinition } from "@paperclipai/shared";
const sidebarNavItemMock = vi.hoisted(() => vi.fn());
const currentPath = vi.hoisted(() => ({ value: "/apps/conn-1/permissions" }));
@@ -207,6 +208,18 @@ describe("AppConnectionSidebar", () => {
expect(container.querySelector('[data-to="/apps/conn-1/setup"]')).toBeNull();
});
+ it("shows only pool settings and keeps connector branding after a pool is renamed", async () => {
+ const entry = aiConnectionRouterAppDefinition("example.pool", { name: "AI connection pool", description: "Use saved connections" });
+ mockToolsApi.getConnection.mockResolvedValue(connection({ name: "Research accounts", config: { aiRouter: { pluginKey: "example.pool" } } }));
+ mockToolsApi.listApplications.mockResolvedValue({ applications: [] });
+ mockToolsApi.listGallery.mockResolvedValue({ apps: [entry] });
+ await renderSidebar();
+ expect(container.querySelectorAll("[data-to]")).toHaveLength(1);
+ expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/permissions", label: "Settings", end: true }));
+ expect(container.querySelector("[data-app-logo]")?.getAttribute("data-logo-url")).toBe(entry.branding.logoUrl);
+ expect(container.textContent).not.toContain("Review");
+ });
+
it("uses the application key for a customized connection display name", async () => {
mockToolsApi.getConnection.mockResolvedValue(connection({ name: "Dotta's GitHub" }));
diff --git a/ui/src/components/AppConnectionSidebar.tsx b/ui/src/components/AppConnectionSidebar.tsx
index e3f657a44f..5a2bac07a7 100644
--- a/ui/src/components/AppConnectionSidebar.tsx
+++ b/ui/src/components/AppConnectionSidebar.tsx
@@ -1,6 +1,6 @@
import { ChevronLeft } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
-import { humanizeConnectionDisplayName } from "@paperclipai/shared";
+import { aiConnectionRouterPluginKey, aiConnectionRouterSlug, humanizeConnectionDisplayName } from "@paperclipai/shared";
import type { ToolApplication, ToolConnection } from "@paperclipai/shared";
import { Link } from "@/lib/router";
import { toolsApi } from "@/api/tools";
@@ -61,6 +61,7 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {
});
const connection = connectionQuery.data;
+ const poolPluginKey = connection && aiConnectionRouterPluginKey(connection);
const applicationId = props.kind === "application" ? props.applicationId : connection?.applicationId;
const application = (applicationsQuery.data?.applications ?? []).find((app) => app.id === applicationId) ?? null;
const appConnections = props.kind === "application"
@@ -112,11 +113,11 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {
<nav className="scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-3 py-2">
<div className="flex flex-col gap-0.5">
- {APP_TABS.map((tab) => (
+ {APP_TABS.filter(tab => !poolPluginKey || tab.key === "permissions").map((tab) => (
<SidebarNavItem
key={tab.key}
to={tabHref(props, tab.key)}
- label={tab.label}
+ label={poolPluginKey ? "Settings" : tab.label}
icon={tab.icon}
end
badge={tab.key === "review" && reviewCount > 0 ? reviewCount : undefined}
@@ -141,6 +142,8 @@ function galleryEntryFor(
connection: ToolConnection | undefined,
application: ToolApplication | undefined,
): AppGalleryDisplayEntry | null {
+ const router = connection && aiConnectionRouterPluginKey(connection);
+ if (router) return apps.find(app => appDefinitionSlug(app) === aiConnectionRouterSlug(router)) ?? null;
const sourceSlug = appApplicationSourceSlug(application) ?? appConnectionSourceSlug(connection);
if (sourceSlug) {
const keyed = apps.find((app) => appDefinitionSlug(app) === sourceSlug);
diff --git a/ui/src/components/IssueMonitorBanner.test.tsx b/ui/src/components/IssueMonitorBanner.test.tsx
index 412581a6b7..100be024fd 100644
--- a/ui/src/components/IssueMonitorBanner.test.tsx
+++ b/ui/src/components/IssueMonitorBanner.test.tsx
@@ -158,6 +158,21 @@ describe("IssueMonitorBanner / IssueMonitorComposerStrip rendering", () => {
flushSync(() => root.unmount());
});
+ it("explains pool exhaustion and retained account affinity on both waiting surfaces", () => {
+ const issue = {
+ status: "in_progress", scheduledRetry: { status: "scheduled_retry", scheduledRetryReason: "ai_connection_pool_wait", scheduledRetryAt: new Date(NOW.getTime() + 60_000).toISOString(), scheduledRetryAttempt: 1 },
+ } as Issue;
+ const root = createRoot(container);
+ flushSync(() => root.render(<><IssueMonitorBanner issue={issue} onCheckNow={vi.fn()} /><IssueMonitorComposerStrip issue={issue} onCheckNow={vi.fn()} /></>));
+ expect(container.textContent).toContain("Pool exhausted");
+ expect(container.textContent).toContain("Usage recheck in 1m");
+ expect(container.textContent).toContain("Tasks with a selected account keep it while waiting.");
+ expect(container.textContent).toContain("Work resumes when usage permits.");
+ expect(container.textContent).not.toContain("Attempt 1");
+ expect(container.querySelector("button")).not.toBeNull();
+ flushSync(() => root.unmount());
+ });
+
it("renders the banner with a working Check now button while waiting", () => {
const onCheckNow = vi.fn();
expect(hasVisibleMonitorSurface(issueWithMonitor(new Date(NOW.getTime() + 2 * 60 * 60_000).toISOString()))).toBe(true);
diff --git a/ui/src/components/IssueMonitorBanner.tsx b/ui/src/components/IssueMonitorBanner.tsx
index de0e83ff47..b46223ae87 100644
--- a/ui/src/components/IssueMonitorBanner.tsx
+++ b/ui/src/components/IssueMonitorBanner.tsx
@@ -81,6 +81,16 @@ export function buildMonitorSurfaceCopy(
const eta = formatMonitorEta(derived.nextCheckAt, now); // "in 2h 12m" | "due now" | "overdue by 18m"
const absolute = formatMonitorAbsolute(derived.nextCheckAt, {}, now); // local time, e.g. "Today, 4:08 PM"
+ if (derived.source === "scheduled-retry" && scheduledRetryReason === "ai_connection_pool_wait") {
+ return {
+ bannerTitle: "Pool exhausted",
+ stripTitle: "Pool exhausted",
+ bannerMeta: [`Usage recheck ${eta} · ${absolute} (your time)`, "Tasks with a selected account keep it while waiting. Work resumes when usage permits."],
+ stripMeta: [`Usage recheck ${eta} · ${absolute}`, "Tasks with a selected account keep it while waiting."],
+ tone: "info",
+ };
+ }
+
const isScheduledRetryOnly = derived.source === "scheduled-retry";
let bannerTitle: string;
diff --git a/ui/src/components/RunRetryDetails.tsx b/ui/src/components/RunRetryDetails.tsx
new file mode 100644
index 0000000000..5e92c8eba7
--- /dev/null
+++ b/ui/src/components/RunRetryDetails.tsx
@@ -0,0 +1,20 @@
+import { Link } from "@/lib/router";
+import { cn } from "@/lib/utils";
+import { describeRunRetryState } from "@/lib/runRetryState";
+
+/** Shared with the run page so Storybook exercises the production retry copy. */
+export function RunRetryDetails({ run, agentRouteId }: {
+ run: Parameters<typeof describeRunRetryState>[0];
+ agentRouteId: string;
+}) {
+ const retry = describeRunRetryState(run);
+ if (!retry) return null;
+ return <div className="rounded-md border border-border/70 bg-accent/20 px-3 py-2 text-xs leading-5">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className={cn("rounded-md border px-1.5 py-0.5 text-(length:--text-micro) font-medium", retry.tone)}>{retry.badgeLabel}</span>
+ {retry.retryOfRunId && <Link to={`/agents/${agentRouteId}/runs/${retry.retryOfRunId}`} className="font-mono text-foreground hover:underline">{retry.retryOfRunId.slice(0, 8)}</Link>}
+ </div>
+ {retry.detail && <p className="mt-2 text-muted-foreground">{retry.detail}</p>}
+ {retry.secondary && <p className="text-muted-foreground">{retry.secondary}</p>}
+ </div>;
+}
diff --git a/ui/src/components/ai-connections/AiConnectionField.tsx b/ui/src/components/ai-connections/AiConnectionField.tsx
index adf57ec293..726cfa24f8 100644
--- a/ui/src/components/ai-connections/AiConnectionField.tsx
+++ b/ui/src/components/ai-connections/AiConnectionField.tsx
@@ -4,6 +4,7 @@ import {
aiConnectionBindingSchema,
isAiConnectionCompatible,
type AiConnectionBinding,
+ type AiRuntimeConnectionBinding,
type AiAuthMethod,
type AiProvider,
type AiManagedConnectionSummary,
@@ -46,28 +47,30 @@ export function AiConnectionField({
environmentId,
legacy = false,
readOnly = false,
+ routerAdapterType,
}: {
companyId: string;
agentId?: string;
agentName: string;
adapterType: string;
model?: string;
- value?: AiConnectionBinding;
- onChange: (binding: AiConnectionBinding) => void;
+ value?: AiRuntimeConnectionBinding;
+ onChange: (binding: AiRuntimeConnectionBinding) => void;
environmentId?: string;
legacy?: boolean;
readOnly?: boolean;
+ routerAdapterType?: string;
}) {
const provider = aiProviderForAdapter(adapterType);
const returnFocus = useRef<HTMLElement | null>(null);
const restoreFocus = (event: Event) => { event.preventDefault(); returnFocus.current?.focus(); };
const [adopting, setAdopting] = useState(false);
- const [pendingAdoption, setPendingAdoption] = useState<AiConnectionBinding>();
+ const [pendingAdoption, setPendingAdoption] = useState<AiRuntimeConnectionBinding>();
const [connecting, setConnecting] = useState(false);
const [reconnecting, setReconnecting] = useState<AiManagedConnectionSummary>();
const [allAgents, setAllAgents] = useState(true);
const [savedAccount, setSavedAccount] = useState<{ connectionId: string; grantId: string; method: AiAuthMethod }>();
- const changeBinding = (next: AiConnectionBinding) => {
+ const changeBinding = (next: AiRuntimeConnectionBinding) => {
if (legacy && !value) { if (!connecting) returnFocus.current = document.activeElement as HTMLElement; setPendingAdoption(next); }
else onChange(next);
};
@@ -99,9 +102,10 @@ export function AiConnectionField({
selectDefault.reset();
setConnecting(true);
};
- const method: AiAuthMethod = (value?.mode !== "responsible_user" ? value?.method : undefined)
+ const method: AiAuthMethod = (value && value.mode !== "router" && value.mode !== "responsible_user" ? value.method : undefined)
?? accounts.data?.connections.find((account) => account.provider === provider && account.isDefault)?.method
?? (provider === "openrouter" ? "api_key" : "subscription");
+ const compatiblePools = agentId ? accounts.data?.pools?.filter(pool => pool.enabled && pool.members.some(member => isAiConnectionCompatible(member.binding, routerAdapterType ?? adapterType, member.profile.model, member.profile.provider, member.profile.acpxAgent))) ?? [] : [];
if (!provider) return null;
if (legacy && !value && !adopting)
return (
@@ -112,13 +116,25 @@ export function AiConnectionField({
);
return (
<div className="space-y-4">
- {value && (adapterType !== "opencode_local" || Boolean(model)) && !isAiConnectionCompatible(value, adapterType, model) && (
+ {value && value.mode !== "router" && (adapterType !== "opencode_local" || Boolean(model)) && !isAiConnectionCompatible(value, adapterType, model) && (
<p role="alert" className="text-sm text-destructive">
This connection does not support the current harness and model. Choose
a compatible connection before saving.
</p>
)}
- <AiConnectionPicker
+ {(compatiblePools.length > 0 || value?.mode === "router") && <label className="block space-y-1 text-sm">
+ AI connection
+ <select className="block w-full rounded-md border bg-background px-3 py-2" disabled={readOnly} value={value?.mode === "router" ? value.connectionId : ""} onChange={event => {
+ if (event.target.value) changeBinding({ mode: "router", connectionId: event.target.value });
+ else changeBinding({ mode: "responsible_user", provider, method });
+ }}>
+ <option value="">Individual account</option>
+ {compatiblePools.map(pool => <option key={pool.id} value={pool.id}>{pool.name} · Experimental pool</option>)}
+ {value?.mode === "router" && !compatiblePools.some(pool => pool.id === value.connectionId) && <option value={value.connectionId}>Pool unavailable — enable routing and the pool</option>}
+ </select>
+ {value?.mode === "router" && <span className="text-muted-foreground">New tasks rotate. Existing tasks keep their account.</span>}
+ </label>}
+ {value?.mode !== "router" && <AiConnectionPicker
requirement={{ companyId, provider }}
connections={accounts.data?.connections ?? []}
value={value}
@@ -134,7 +150,7 @@ export function AiConnectionField({
onConnect={() => openConnection()}
onReconnect={(!value || value.mode === "responsible_user") && personalDefault && personalDefault.status !== "connected" ? () => openConnection(personalDefault) : undefined}
onRetry={() => void accounts.refetch()}
- />
+ />}
<Dialog
open={Boolean(pendingAdoption)}
onOpenChange={(open) => {
@@ -143,24 +159,22 @@ export function AiConnectionField({
>
<DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl" onCloseAutoFocus={restoreFocus}>
<DialogHeader>
- <DialogTitle>Adopt Connections for {agentName}</DialogTitle>
+ <DialogTitle>{pendingAdoption?.mode === "router" ? `Use ${accounts.data?.pools?.find(pool => pool.id === pendingAdoption.connectionId)?.name ?? "this pool"}?` : `Adopt Connections for ${agentName}`}</DialogTitle>
<DialogDescription>
- Saving tests this account in {agentName}’s environment before
- replacing its existing authentication. Other agents keep their
- current configuration.
+ {pendingAdoption?.mode === "router" ? "Reset existing sessions that use an account outside this pool." : "Saving validates access to the selected connection. Existing sessions keep their account or require an explicit reset before adoption."}
</DialogDescription>
</DialogHeader>
- <p className="text-sm">
+ {pendingAdoption?.mode !== "router" && <p className="text-sm">
{pendingAdoption?.mode === "responsible_user"
? `Responsible user’s default. For you: ${accounts.data?.connections.find((account) => account.isDefault && account.provider === provider)?.name ?? "Not connected"}. Other users use their own default.`
: accounts.data?.connections.find(
(account) => account.id === pendingAdoption?.connectionId,
)?.name}
- </p>
- <p className="text-xs text-muted-foreground">
+ </p>}
+ {pendingAdoption?.mode !== "router" && <p className="text-xs text-muted-foreground">
After adoption, missing credentials block execution. Previous
authentication will not be used as a fallback.
- </p>
+ </p>}
<DialogFooter>
<Button
variant="ghost"
@@ -174,7 +188,7 @@ export function AiConnectionField({
setPendingAdoption(undefined);
}}
>
- Use this binding when saved
+ {pendingAdoption?.mode === "router" ? "Use pool" : "Use this binding when saved"}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx b/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx
new file mode 100644
index 0000000000..7eb2ee6e9d
--- /dev/null
+++ b/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx
@@ -0,0 +1,185 @@
+import { useEffect, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { ArrowDown, ArrowUp, ExternalLink, Loader2, MoreHorizontal, Plus, Search, Trash2, X } from "lucide-react";
+import { aiConnectionRouterAppDefinition, type AiConnectionPool, type AiConnectionPoolConfig, type AiConnectionPoolMember, type AiManagedConnectionSummary, type ToolConnection } from "@paperclipai/shared";
+import { aiConnectionsApi } from "@/api/ai-connections";
+import { aiConnectionPoolsApi, type PoolInspection } from "@/api/ai-connection-pools";
+import { toolsApi } from "@/api/tools";
+import { agentsApi } from "@/api/agents";
+import { useCompany } from "@/context/CompanyContext";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useToast } from "@/context/ToastContext";
+import { Link, useNavigate } from "@/lib/router";
+import { queryKeys } from "@/lib/queryKeys";
+import { AppLogo } from "@/pages/apps/AppLogo";
+import { AppDetailHeader } from "@/pages/apps/AppDetail";
+import { StepHeader } from "@/features/connections/ConnectionSetupHeader";
+import { Button } from "@/components/ui/button";
+import { AgentIdentity } from "@/components/AgentIdentity";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { AiConnectionUsagePanel } from "./AiConnectionUsagePanel";
+import { AI_PROVIDERS, aiMethodLabel } from "./model";
+
+const configOf = ({ name, enabled, members, mode, thresholdPercent }: AiConnectionPoolConfig): AiConnectionPoolConfig => ({ name, enabled, members, mode, thresholdPercent });
+const emptyConfig = (): AiConnectionPoolConfig => ({ name: "AI connection pool", enabled: false, members: [], mode: "round_robin", thresholdPercent: 90 });
+function memberOf(account: AiManagedConnectionSummary): AiConnectionPoolMember {
+ const profile: AiConnectionPoolMember["profile"] = account.provider === "openai" ? { provider: "codex", model: "gpt-5.6-sol" }
+ : account.provider === "anthropic" ? { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-5" }
+ : account.provider === "xai" ? { provider: "acpx", acpxAgent: "grok", model: "grok-4.7" }
+ : { provider: "opencode", model: "openrouter/anthropic/claude-sonnet-4.6" };
+ return { id: crypto.randomUUID(), binding: { mode: account.ownership === "shared" ? "shared" : "delegated", provider: account.provider, method: account.method, connectionId: account.id, grantId: account.grantId }, profile };
+}
+
+/** Native connector surface shared by all plugins implementing the pool contract. */
+export function AiConnectionPoolConnector({ pluginKey, connection }: { pluginKey: string; connection?: ToolConnection }) {
+ const { selectedCompanyId } = useCompany();
+ return selectedCompanyId ? <PoolConnector key={`${selectedCompanyId}:${connection?.id ?? pluginKey}`} companyId={selectedCompanyId} pluginKey={pluginKey} connection={connection} /> : <p>Select a company to continue.</p>;
+}
+function PoolConnector({ companyId, pluginKey, connection }: { companyId: string; pluginKey: string; connection?: ToolConnection }) {
+ const navigate = useNavigate();
+ const client = useQueryClient();
+ const { pushToast } = useToast();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const accountsQuery = useQuery({ queryKey: ["pool-accounts", companyId], queryFn: () => aiConnectionsApi.list(companyId) });
+ const poolsQuery = useQuery({ queryKey: ["ai-connection-pools", companyId], queryFn: () => aiConnectionPoolsApi.list(companyId), enabled: accountsQuery.data?.canManageConnections === true });
+ const galleryQuery = useQuery({ queryKey: queryKeys.apps.gallery(companyId), queryFn: () => toolsApi.listGallery(companyId) });
+ const [editing, setEditing] = useState<AiConnectionPool>();
+ const [draft, setDraft] = useState(emptyConfig);
+ const [step, setStep] = useState(0);
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [pickerMembers, setPickerMembers] = useState<AiConnectionPoolMember[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [removing, setRemoving] = useState(false);
+ const [renaming, setRenaming] = useState(false);
+ const [nameDraft, setNameDraft] = useState("");
+ const [inspectionError, setInspectionError] = useState("");
+ const [inspection, setInspection] = useState<PoolInspection>({});
+ const accounts = accountsQuery.data?.connections ?? [];
+ const entry = galleryQuery.data?.apps.find(app => app.aiConnectionRouter?.pluginKey === pluginKey);
+ const unavailable = galleryQuery.isSuccess && (!entry || entry.availability?.available === false);
+ const canManage = Boolean(accountsQuery.data?.canManageConnections);
+ const disabled = busy || !canManage || unavailable;
+ const agentsQuery = useQuery({ queryKey: queryKeys.agents.list(companyId), queryFn: () => agentsApi.list(companyId), enabled: Boolean(connection) && canManage });
+ const usingAgents = (agentsQuery.data ?? []).filter(agent => agent.status !== "terminated" && agent.runtimeConfig?.aiConnection?.mode === "router" && agent.runtimeConfig.aiConnection.connectionId === connection?.id).sort((a, b) => a.name.localeCompare(b.name));
+ useEffect(() => {
+ if (connection && !editing && canManage) {
+ const pool = poolsQuery.data?.find(pool => pool.id === connection.id && pool.pluginKey === pluginKey);
+ if (pool) { setEditing(pool); setDraft(configOf(pool)); }
+ }
+ }, [poolsQuery.data, connection, editing, pluginKey, canManage]);
+ useEffect(() => {
+ setBreadcrumbs([{ label: "Connectors", href: "/apps" }, { label: connection ? draft.name : "Add a connection pool" }]);
+ return () => setBreadcrumbs([]);
+ }, [connection, draft.name, setBreadcrumbs]);
+ useEffect(() => {
+ if (!editing || !canManage) return;
+ let alive = true;
+ void aiConnectionPoolsApi.inspect(companyId, editing.id).then(value => { if (alive) setInspection(value); }).catch(() => { if (alive) setInspectionError("Usage unavailable."); });
+ return () => { alive = false; };
+ }, [companyId, editing, canManage]);
+ async function invalidate() {
+ await Promise.all([
+ client.invalidateQueries({ queryKey: ["ai-connection-pools", companyId] }),
+ client.invalidateQueries({ queryKey: queryKeys.tools.connections(companyId) }),
+ client.invalidateQueries({ queryKey: queryKeys.tools.applications(companyId) }),
+ ...(connection ? [client.invalidateQueries({ queryKey: queryKeys.tools.connection(connection.id) })] : []),
+ ]);
+ }
+ async function save(config = draft) {
+ setBusy(true); setError("");
+ try {
+ const saved = await aiConnectionPoolsApi.save(companyId, { pluginKey, ...(editing ? { id: editing.id, expectedRevision: editing.revision } : {}), config });
+ setEditing(saved); setDraft(configOf(saved)); setRenaming(false);
+ await invalidate();
+ pushToast({ title: connection ? "Connection pool saved" : "Connection pool created", tone: "success" });
+ if (!connection) navigate(`/apps/${saved.id}/permissions`);
+ } catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
+ finally { setBusy(false); }
+ }
+ async function remove() {
+ if (!editing) return;
+ setBusy(true); setError("");
+ try { await aiConnectionPoolsApi.remove(companyId, editing.id, editing.revision); await invalidate(); navigate("/apps"); }
+ catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
+ finally { setBusy(false); }
+ }
+ function move(index: number, offset: number) {
+ setDraft(value => { const members = [...value.members]; [members[index], members[index + offset]] = [members[index + offset]!, members[index]!]; return { ...value, members }; });
+ }
+ const loadError = accountsQuery.error ?? poolsQuery.error ?? galleryQuery.error;
+ if (accountsQuery.isSuccess && !canManage) return <p role="alert" className="text-sm text-muted-foreground">A connection manager can view and edit connection pools.</p>;
+ if (loadError) return <div className="space-y-4"><p role="alert" className="text-sm text-destructive">{loadError.message}</p><Button variant="outline" onClick={() => { void accountsQuery.refetch(); void poolsQuery.refetch(); void galleryQuery.refetch(); }}>Try again</Button></div>;
+ if (accountsQuery.isPending || poolsQuery.isPending || galleryQuery.isPending || (connection && !editing && poolsQuery.data?.some(pool => pool.id === connection.id))) return <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Loading connections…</p>;
+ if (connection && !editing) return <p role="alert">This connection pool is no longer available.</p>;
+ const name = entry?.name ?? "AI connection pool";
+ const logoEntry = entry ?? aiConnectionRouterAppDefinition(pluginKey, { name, description: "Use existing AI connections." });
+ const orderedMembers = <ol aria-label="Connection order" className="divide-y divide-border rounded-lg border border-border">
+ {draft.members.map((member, index) => {
+ const account = accounts.find(account => account.id === member.binding.connectionId && account.grantId === member.binding.grantId);
+ const provider = AI_PROVIDERS[member.binding.provider];
+ return <li key={member.id} className="flex items-center gap-3 px-4 py-3">
+ <span className="w-4 text-center text-xs text-muted-foreground">{index + 1}</span>
+ <AppLogo name={provider.name} logoUrl={provider.logo} size={32} />
+ <div className="min-w-0 flex-1"><p className="truncate text-sm font-medium">{account?.name ?? "Connection unavailable"}</p><p className="text-xs text-muted-foreground">{account ? aiMethodLabel(account.provider, account.method) : "Restore access to this connection."}</p>{connection && draft.mode === "usage_aware" && account && <details className="mt-2 text-xs text-muted-foreground"><summary className="cursor-pointer">Usage</summary><div className="pt-3">{inspectionError ? <p role="status">{inspectionError}</p> : <AiConnectionUsagePanel account={account} cachedOnly observation={inspection[member.id]?.usage} />}</div></details>}</div>
+ <div className="flex shrink-0 items-center gap-1">
+ <Button type="button" variant="ghost" size="icon-sm" disabled={disabled || index === 0} aria-label={`Move ${account?.name ?? "connection"} up`} onClick={() => move(index, -1)}><ArrowUp className="size-4" /></Button>
+ <Button type="button" variant="ghost" size="icon-sm" disabled={disabled || index === draft.members.length - 1} aria-label={`Move ${account?.name ?? "connection"} down`} onClick={() => move(index, 1)}><ArrowDown className="size-4" /></Button>
+ <Button type="button" variant="ghost" size="icon-sm" disabled={disabled} aria-label={`Remove ${account?.name ?? "connection"}`} onClick={() => setDraft({ ...draft, members: draft.members.filter(item => item.id !== member.id) })}><X className="size-4" /></Button>
+ </div>
+ </li>;
+ })}
+ {draft.members.length === 0 && <li className="px-4 py-6 text-sm text-muted-foreground">Add a connection to get started.</li>}
+ </ol>;
+ return <div className={connection ? "space-y-6" : "mx-auto max-w-2xl"}>
+ {connection ? <div className="flex items-start justify-between gap-4">
+ <AppDetailHeader appName={draft.name} connection={connection} logoEntry={logoEntry} brandKey={logoEntry.slug} allowRemoteLogo canRename={!disabled} status={editing?.enabled ? { label: "Connected", tone: "connected" } : { label: "Paused", tone: "paused" }} actionCount={null} renaming={renaming} nameDraft={nameDraft} renamePending={disabled} onNameDraftChange={setNameDraft} onRenameStart={() => { if (!disabled) { setNameDraft(draft.name); setRenaming(true); } }} onRenameCancel={() => setRenaming(false)} onRenameSubmit={value => void save({ ...draft, name: value })} />
+ <DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon-sm" aria-label="Manage connection pool"><MoreHorizontal className="size-4" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem variant="destructive" disabled={busy || !canManage} onSelect={() => { setError(""); setRemoving(true); }}><Trash2 />Remove connection</DropdownMenuItem></DropdownMenuContent></DropdownMenu>
+ </div> : <StepHeader title="Add a connection pool" subtitle={step === 0 ? "Choose connections you already use." : "New tasks rotate in this order."} step="connect" activeIndex={step} labels={["Connections", "Order"]} appIdentity={{ name, logoUrl: logoEntry.branding.logoUrl }} />}
+ {unavailable && <p role="alert" className="text-sm text-destructive">{entry?.availability?.reason ?? "Enable the connection pool plugin in Plugins."}</p>}
+ {!canManage && <p role="alert" className="text-sm text-muted-foreground">A connection manager can edit this pool.</p>}
+ {error && !removing && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ {!connection && step === 0 ? <ConnectionPicker accounts={accounts} selected={draft.members} disabled={disabled} onChange={members => setDraft({ ...draft, members })} onRefresh={() => void accountsQuery.refetch()} /> : <div className="space-y-4">
+ {connection && <div className="flex items-center justify-between gap-3"><h2 className="text-sm font-semibold">Connections</h2><Button variant="outline" size="sm" disabled={disabled} onClick={() => { setPickerMembers(draft.members); setPickerOpen(true); }}><Plus className="size-4" />Add connections</Button></div>}
+ {orderedMembers}
+ <p className="text-xs text-muted-foreground">{connection ? "Order changes apply to new tasks." : "Created paused. Enable it when you’re ready."}</p>
+ {connection && <>
+ <label className="flex items-center gap-2 text-sm"><Checkbox checked={draft.enabled} disabled={disabled} onCheckedChange={checked => setDraft({ ...draft, enabled: checked === true })} />Enable this pool</label>
+ <details className="rounded-lg border border-border"><summary className="cursor-pointer px-4 py-3 text-sm font-medium">Advanced</summary><fieldset disabled={disabled} className="space-y-4 border-t border-border p-4">
+ <label className="flex items-center gap-2 text-sm"><Checkbox checked={draft.mode === "usage_aware"} onCheckedChange={checked => setDraft({ ...draft, mode: checked ? "usage_aware" : "round_robin" })} />Skip connections near their usage limit</label>
+ {draft.mode === "usage_aware" && <label className="flex items-center gap-3 text-sm">Skip at<Input className="w-20" aria-label="Usage threshold" type="number" min={1} max={100} step={1} value={draft.thresholdPercent} onChange={event => setDraft({ ...draft, thresholdPercent: Number(event.target.value) })} />% usage</label>}
+ {draft.members.map((member, index) => <div key={member.id} className="space-y-2"><p className="text-sm font-medium">{accounts.find(account => account.id === member.binding.connectionId)?.name ?? "Connection unavailable"}</p><div className="grid gap-3 sm:grid-cols-2"><label className="space-y-1 text-xs text-muted-foreground">Model<Input aria-label={`Model for connection ${index + 1}`} value={member.profile.model} onChange={event => setDraft({ ...draft, members: draft.members.map(row => row.id === member.id ? { ...row, profile: { ...row.profile, model: event.target.value } } : row) })} /></label><label className="space-y-1 text-xs text-muted-foreground">Effort (optional)<Input aria-label={`Effort for connection ${index + 1}`} value={member.profile.effort ?? ""} onChange={event => { const { effort: _old, ...profile } = member.profile; setDraft({ ...draft, members: draft.members.map(row => row.id === member.id ? { ...row, profile: { ...profile, ...(event.target.value.trim() ? { effort: event.target.value.trim() } : {}) } } : row) }); }} /></label></div></div>)}
+ </fieldset></details>
+ <section aria-labelledby="pool-used-by" className="space-y-3">
+ <h2 id="pool-used-by" className="text-sm font-semibold">Used by</h2>
+ {agentsQuery.isPending ? <p role="status" className="text-sm text-muted-foreground">Loading agents…</p>
+ : agentsQuery.isError ? <div className="flex items-center gap-2"><p role="alert" className="text-sm text-muted-foreground">Couldn’t load agents.</p><Button variant="ghost" size="sm" onClick={() => void agentsQuery.refetch()}>Retry</Button></div>
+ : usingAgents.length ? <ul className="flex flex-wrap gap-x-6 gap-y-3">{usingAgents.map(agent => <li key={agent.id} className="min-w-0 max-w-full"><Link to={`/agents/${agent.id}`} className="inline-flex max-w-full rounded-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><AgentIdentity agent={agent} /></Link></li>)}</ul>
+ : <p className="text-sm text-muted-foreground">No agents yet.</p>}
+ </section>
+ </>}
+ </div>}
+ <div className="mt-6 flex items-center justify-between gap-3 border-t border-border pt-4">
+ <Button variant="ghost" disabled={busy} onClick={() => connection ? navigate("/apps") : step ? setStep(0) : navigate("/apps")}>{!connection && step ? "Back" : "Cancel"}</Button>
+ <Button disabled={disabled || draft.members.length === 0 || !Number.isInteger(draft.thresholdPercent) || draft.thresholdPercent < 1 || draft.thresholdPercent > 100} onClick={() => !connection && step === 0 ? setStep(1) : void save()}>{busy && <Loader2 className="size-4 animate-spin" />}{busy ? "Saving…" : connection ? "Save changes" : step ? "Create pool" : "Continue"}</Button>
+ </div>
+ <Dialog open={pickerOpen} onOpenChange={setPickerOpen}><DialogContent className="sm:max-w-2xl"><DialogHeader><DialogTitle>Add connections</DialogTitle><DialogDescription>Choose connections you already use.</DialogDescription></DialogHeader><ConnectionPicker accounts={accounts} selected={pickerMembers} disabled={disabled} onChange={setPickerMembers} onRefresh={() => void accountsQuery.refetch()} /><div className="flex items-center justify-between gap-3"><Button variant="ghost" onClick={() => setPickerOpen(false)}>Cancel</Button><Button onClick={() => { setDraft({ ...draft, members: pickerMembers }); setPickerOpen(false); }}>Done</Button></div></DialogContent></Dialog>
+ <AlertDialog open={removing} onOpenChange={open => { if (!busy) setRemoving(open); }}><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Remove {draft.name}?</AlertDialogTitle><AlertDialogDescription>The connections in this pool are kept.</AlertDialogDescription></AlertDialogHeader>{error && <p role="alert" className="text-sm text-destructive">{error}</p>}<AlertDialogFooter className="sm:justify-between"><AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel><AlertDialogAction className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={busy} onClick={event => { event.preventDefault(); void remove(); }}>{busy ? "Removing…" : "Remove connection"}</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>
+ </div>;
+}
+function ConnectionPicker({ accounts, selected, disabled, onChange, onRefresh }: { accounts: AiManagedConnectionSummary[]; selected: AiConnectionPoolMember[]; disabled: boolean; onChange: (members: AiConnectionPoolMember[]) => void; onRefresh: () => void }) {
+ const [search, setSearch] = useState("");
+ const filtered = accounts.filter(account => `${account.name} ${AI_PROVIDERS[account.provider].name}`.toLowerCase().includes(search.toLowerCase()));
+ return <div className="space-y-4">
+ <div className="relative"><Search className="pointer-events-none absolute left-3 top-3 size-4 text-muted-foreground" /><Input aria-label="Search connections" placeholder="Search connections…" value={search} onChange={event => setSearch(event.target.value)} className="pl-9" /></div>
+ <div className="max-h-80 overflow-y-auto rounded-lg border border-border divide-y divide-border">
+ {filtered.map(account => { const existing = selected.find(member => member.binding.connectionId === account.id); const checked = existing?.binding.grantId === account.grantId; return <label key={account.grantId} className="flex cursor-pointer items-center gap-3 px-4 py-3 hover:bg-accent/50"><Checkbox checked={checked} disabled={disabled || (!checked && (account.status !== "connected" || Boolean(existing)))} onCheckedChange={value => onChange(value ? [...selected, memberOf(account)] : selected.filter(member => member.binding.connectionId !== account.id))} aria-label={account.name} /><AppLogo name={AI_PROVIDERS[account.provider].name} logoUrl={AI_PROVIDERS[account.provider].logo} size={32} /><span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium">{account.name}</span><span className="block text-xs text-muted-foreground">{aiMethodLabel(account.provider, account.method)} · {account.ownership === "shared" ? "Shared" : "Personal"}</span></span>{account.status !== "connected" && <span className="text-xs text-muted-foreground">Needs attention</span>}</label>; })}
+ {filtered.length === 0 && <p className="px-4 py-6 text-sm text-muted-foreground">{accounts.length ? "No matching connections." : "No AI connections yet."}</p>}
+ </div>
+ <div className="flex items-center justify-between gap-3 text-sm"><Link to="/apps" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-muted-foreground hover:text-foreground">Connect a new account<ExternalLink className="size-3.5" /></Link><Button variant="ghost" size="sm" onClick={onRefresh}>Refresh</Button></div>
+ </div>;
+}
diff --git a/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx
new file mode 100644
index 0000000000..34e75fe2ae
--- /dev/null
+++ b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx
@@ -0,0 +1,14 @@
+import type { AiConnectionRouterSelection } from "@paperclipai/shared";
+
+export function AiConnectionPoolRunDetails({ context }: { context: Record<string, unknown> | null }) {
+ const selection = context?.aiRouterSelection as AiConnectionRouterSelection | undefined;
+ if (!selection) return null;
+ const account = context?.aiConnection as { accountName?: string; connectionId?: string } | undefined;
+ const config = selection.runtimeConfig;
+ const effort = config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort ?? config.variant;
+ return <div className="rounded-lg border p-4 text-sm space-y-1">
+ <p className="font-medium">Task-pinned pool account · {account?.accountName ?? account?.connectionId ?? "Selected account"}</p>
+ <p>{[selection.binding.provider, config.provider, config.acpxAgent, config.model, effort].filter(Boolean).map(String).join(" · ")}</p>
+ {selection.notes.length > 0 && <p className="text-muted-foreground">{selection.notes.join(" ")}</p>}
+ </div>;
+}
diff --git a/ui/src/components/ai-connections/AiConnectionUsagePanel.test.tsx b/ui/src/components/ai-connections/AiConnectionUsagePanel.test.tsx
index a75043c894..2693f17d3e 100644
--- a/ui/src/components/ai-connections/AiConnectionUsagePanel.test.tsx
+++ b/ui/src/components/ai-connections/AiConnectionUsagePanel.test.tsx
@@ -97,3 +97,11 @@ it("shows explicit denial and distinguishes equal-duration provider windows", as
expect(host.querySelector('[aria-label="Plan usage · Primary · 5h: 100%"]')).not.toBeNull();
expect(host.querySelector('[aria-label="Plan usage · Secondary · 5h: 50%"]')).not.toBeNull();
});
+
+it("shows cached pool observations without offering or making a provider call", () => {
+ const observation: AiConnectionUsage = { connectionId: account.id, grantId: account.grantId, provider: account.provider, method: account.method, status: "ok", checkedAt: "2026-10-02T12:00:00Z", source: "fixture", planType: null, limits: [], overage: null };
+ flushSync(() => root.render(<QueryClientProvider client={client}><AiConnectionUsagePanel account={account} observation={observation} cachedOnly /></QueryClientProvider>));
+ expect(host.textContent).toContain("Usage not reported");
+ expect(host.querySelector("button")).toBeNull();
+ expect(api.probeUsage).not.toHaveBeenCalled();
+});
diff --git a/ui/src/components/ai-connections/AiConnectionUsagePanel.tsx b/ui/src/components/ai-connections/AiConnectionUsagePanel.tsx
index 546993765e..d0e7d9a5bb 100644
--- a/ui/src/components/ai-connections/AiConnectionUsagePanel.tsx
+++ b/ui/src/components/ai-connections/AiConnectionUsagePanel.tsx
@@ -68,24 +68,25 @@ function usageError(usage: AiConnectionUsage) {
case "invalid_response": return "Couldn’t read usage. Try again.";
case "connection_unavailable": return "Reconnect to check usage.";
case "unsupported": return "Usage unavailable.";
- default: return usage.message;
+ default: return usage.message ?? "Usage unavailable.";
}
}
-export function AiConnectionUsagePanel({ account }: { account: AiManagedConnectionSummary }) {
+export function AiConnectionUsagePanel({ account, observation, cachedOnly = false }: { account: AiManagedConnectionSummary; observation?: AiConnectionUsage; cachedOnly?: boolean }) {
const probe = useMutation({
mutationFn: () => aiConnectionsApi.probeUsage(account.companyId, account.id, account.grantId),
});
const supported = supportsAiConnectionUsage(account.provider, account.method);
- const usage = probe.isSuccess ? probe.data : undefined;
+ const usage = cachedOnly ? observation : probe.isSuccess ? probe.data : undefined;
return (
<section aria-label="Account usage limits" className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-sm font-semibold">Usage</h3>
- {supported && <Button variant="outline" size="sm" disabled={probe.isPending || account.status !== "connected"} onClick={() => probe.mutate()}>
+ {supported && !cachedOnly && <Button variant="outline" size="sm" disabled={probe.isPending || account.status !== "connected"} onClick={() => probe.mutate()}>
{probe.isPending ? "Checking…" : usage?.status === "ok" ? "Refresh" : "Check usage"}
</Button>}
</div>
+ {cachedOnly && !usage && <p className="text-xs text-muted-foreground">Usage not observed.</p>}
{!supported && <p className="text-xs text-muted-foreground">Unavailable for this sign-in method.</p>}
{probe.error && <p role="alert" className="text-sm text-destructive">{probe.error.message}</p>}
{usage && usage.status !== "ok" && <p role={usage.status === "unsupported" ? "status" : "alert"} className="text-sm text-muted-foreground">{usageError(usage)}</p>}
diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx
index d65b189a2f..33690f6e40 100644
--- a/ui/src/components/new-agent/NewAgentSetup.tsx
+++ b/ui/src/components/new-agent/NewAgentSetup.tsx
@@ -846,7 +846,7 @@ function Setup({
</div>
) : (
<AiConnectionField companyId={companyId} agentName={name} adapterType={brandType} model={model} environmentId={environmentId ?? undefined} value={aiBinding}
- onChange={binding => { setRuntimeAiBinding(binding); resetTest(); }} />
+ onChange={binding => { binding.mode !== "router" && setRuntimeAiBinding(binding); resetTest(); }} />
)
)}
{models.error && <p role="alert" className="text-sm text-destructive">Could not load models. Retry or enter a model ID manually.</p>}
diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx
index dd88b4c0f4..e8f6136762 100644
--- a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx
+++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
import { useQuery } from "@tanstack/react-query";
import { ArrowLeft, Check, ChevronDown, Plus, RotateCcw, Search, X, Zap } from "lucide-react";
-import type { Agent, IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
+import { aiRuntimeConnectionBindingSchema, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
import { agentsApi, type AdapterModel } from "@/api/agents";
import { queryKeys } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
@@ -52,6 +52,8 @@ function harnessLabel(agent: Agent | undefined): string {
if (!agent) return "Choose an agent";
const harness = HARNESS_LABELS[agent.adapterType] ?? agent.adapterType;
const provider = composerCatalogProvider(agent);
+ const binding = aiRuntimeConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data;
+ const poolId = binding?.mode === "router" ? binding.connectionId : undefined;
return provider === "openrouter" ? `${harness} · OpenRouter` : harness;
}
@@ -100,12 +102,14 @@ export function ComposerRunSettingsPicker({
const agent = agents.get(agentId);
const modelSupported = supportsComposerModel(agent);
const provider = composerCatalogProvider(agent);
+ const binding = aiRuntimeConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data;
+ const poolId = binding?.mode === "router" ? binding.connectionId : undefined;
const { data: fetchedModels = [], isPending: modelsPending } = useQuery({
queryKey: agent && modelSupported
- ? queryKeys.agents.adapterModels(companyId, agent.adapterType, agent.defaultEnvironmentId ?? null, provider)
+ ? [...queryKeys.agents.adapterModels(companyId, agent.adapterType, agent.defaultEnvironmentId ?? null, provider), poolId ?? null]
: ["agents", "composer-models", "none"],
queryFn: () => agentsApi.adapterModels(companyId, agent!.adapterType, {
- environmentId: agent!.defaultEnvironmentId ?? null, provider,
+ environmentId: agent!.defaultEnvironmentId ?? null, provider, poolId,
}),
enabled: Boolean(agent && modelSupported && !modelOptionsOverride),
});
diff --git a/ui/src/components/task-chat/composer-run-settings.ts b/ui/src/components/task-chat/composer-run-settings.ts
index 5df778ba79..9dc7fd4655 100644
--- a/ui/src/components/task-chat/composer-run-settings.ts
+++ b/ui/src/components/task-chat/composer-run-settings.ts
@@ -3,7 +3,7 @@ import { claudeLocalReasoningEffortsForModel } from "@paperclipai/adapter-claude
import { resolvePaperclipRunnerModel } from "@paperclipai/adapter-utils";
import { DEFAULT_GROK_LOCAL_MODEL, grokLocalReasoningEffortsForModel } from "@paperclipai/adapter-grok-local";
import { DEFAULT_KIMI_LOCAL_MODEL, modelSupportsEffort, KIMI_SUPPORTED_EFFORTS } from "@paperclipai/adapter-kimi-local";
-import { aiConnectionBindingSchema, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
+import { aiConnectionBindingSchema, aiRuntimeConnectionBindingSchema, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
export interface ComposerRunSettings {
model: string | null;
@@ -64,6 +64,8 @@ export function composerEfforts(agent: Agent | undefined, model: string, catalog
const effectiveModel = model.trim() || (agent.adapterType === "grok_local" ? DEFAULT_GROK_LOCAL_MODEL
: agent.adapterType === "kimi_local" ? DEFAULT_KIMI_LOCAL_MODEL : "");
if (!effectiveModel) return [];
+ const pool = aiRuntimeConnectionBindingSchema.safeParse(agent.runtimeConfig?.aiConnection).data?.mode === "router";
+ if (pool && agent.adapterType === "paperclip_runner") return isCodexLocalKnownModel(effectiveModel) ? codexLocalReasoningEffortsForModel(effectiveModel) : [];
if (agent.adapterType === "codex_local" || (agent.adapterType === "paperclip_runner" && composerCatalogProvider(agent) === "codex")) {
return isCodexLocalKnownModel(effectiveModel) ? codexLocalReasoningEffortsForModel(effectiveModel) : [];
}
diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx
index 79074ff0fd..21e32b48a3 100644
--- a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx
+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx
@@ -205,7 +205,7 @@ export function ConnectionIntentInteractionBody({
} else {
const agent = await agentsApi.get(interaction.payload.requestingAgentId, interaction.companyId);
const current = agent.runtimeConfig.aiConnection;
- if (!current || current.mode === "responsible_user" || current.connectionId !== previous.id || current.grantId !== previous.grantId) {
+ if (!current || current.mode === "responsible_user" || current.mode === "router" || current.connectionId !== previous.id || current.grantId !== previous.grantId) {
throw new Error("The agent’s AI connection changed. Reload the task and try again.");
}
if (result.generation !== setupGeneration.current) return;
diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx
index 0d6dfbad65..832f00677d 100644
--- a/ui/src/features/connections/ConnectionSetupFlow.tsx
+++ b/ui/src/features/connections/ConnectionSetupFlow.tsx
@@ -1,3 +1,5 @@
+import { StepHeader } from "./ConnectionSetupHeader";
+export { StepHeader } from "./ConnectionSetupHeader";
import { ConnectionInstructionsEditor } from "./ConnectionInstructions";
import { connectionInstructionsConfig, defaultConnectionAgentInstructions, type ConnectionAgentInstructions } from "@paperclipai/shared";
import { RemoteMcpProductionSetup } from "./remote-mcp/RemoteMcpProductionSetup";
@@ -2593,76 +2595,6 @@ function StandardConnectionSetupFlow({
);
}
-export function StepHeader({
- title,
- headingRef,
- subtitle,
- step,
- activeIndex,
- labels,
- appIdentity,
- unverifiedHost,
- onCancel,
-}: {
- title?: string;
- headingRef?: Ref<HTMLHeadingElement>;
- subtitle?: string;
- step: Step;
- activeIndex: number;
- labels: string[];
- appIdentity?: { name: string; logoUrl: string | null; darkLogoUrl?: string | null };
- /**
- * Host of an unknown remote MCP server. Present for the whole generic flow so
- * the operator can see whose server they are configuring at every step, not
- * just on the screen where they pasted the address.
- */
- unverifiedHost?: string | null;
- onCancel?: () => void;
-}) {
- return (
- <div className="mb-6">
- <div className="flex items-start justify-between gap-4">
- <div className="flex items-center gap-3">
- {appIdentity ? (
- <AppLogo name={appIdentity.name} logoUrl={appIdentity.logoUrl} darkLogoUrl={appIdentity.darkLogoUrl} size={44} />
- ) : null}
- <div>
- <h1 ref={headingRef} tabIndex={headingRef ? -1 : undefined} className="text-2xl font-bold tracking-tight outline-none">
- {title ?? (appIdentity ? `Connect ${appIdentity.name}` : "Connect your own MCP server")}
- </h1>
- {subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
- {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-2" /> : null}
- </div>
- </div>
- {onCancel && <Button variant="ghost" size="sm" onClick={onCancel}>
- Cancel
- </Button>}
- </div>
- {step !== "gallery" && labels.length > 1 && (
- // A landmark with stable hooks, so the step model can be read without
- // guessing at Tailwind classes. The dots are decoration — the label
- // line below already says the same thing, so announcing both would
- // read every step name twice.
- <nav className="mt-4" aria-label="Setup progress" data-testid="wizard-stepper">
- <ol className="flex gap-2" aria-hidden="true">
- {labels.map((label, i) => (
- <li
- key={label}
- data-testid="wizard-step-dot"
- data-step-active={i === activeIndex ? "true" : undefined}
- className={cn("h-1 w-20 rounded-full", i <= activeIndex ? "bg-foreground" : "bg-border")}
- />
- ))}
- </ol>
- <div className="mt-2 text-xs text-muted-foreground" data-testid="wizard-step-labels">
- {labels.join(" · ")}
- </div>
- </nav>
- )}
- </div>
- );
-}
-
export function OAuthConnectStateScreen({
entry,
identity,
diff --git a/ui/src/features/connections/ConnectionSetupHeader.tsx b/ui/src/features/connections/ConnectionSetupHeader.tsx
new file mode 100644
index 0000000000..0138cee499
--- /dev/null
+++ b/ui/src/features/connections/ConnectionSetupHeader.tsx
@@ -0,0 +1,76 @@
+import type { Ref } from "react";
+import { AppLogo } from "@/pages/apps/AppLogo";
+import { UnverifiedServerBadge } from "@/pages/apps/UnverifiedServerBadge";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+export function StepHeader({
+ title,
+ headingRef,
+ subtitle,
+ step,
+ activeIndex,
+ labels,
+ appIdentity,
+ unverifiedHost,
+ onCancel,
+}: {
+ title?: string;
+ headingRef?: Ref<HTMLHeadingElement>;
+ subtitle?: string;
+ step: string;
+ activeIndex: number;
+ labels: string[];
+ appIdentity?: { name: string; logoUrl: string | null; darkLogoUrl?: string | null };
+ /**
+ * Host of an unknown remote MCP server. Present for the whole generic flow so
+ * the operator can see whose server they are configuring at every step, not
+ * just on the screen where they pasted the address.
+ */
+ unverifiedHost?: string | null;
+ onCancel?: () => void;
+}) {
+ return (
+ <div className="mb-6">
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex items-center gap-3">
+ {appIdentity ? (
+ <AppLogo name={appIdentity.name} logoUrl={appIdentity.logoUrl} darkLogoUrl={appIdentity.darkLogoUrl} size={44} />
+ ) : null}
+ <div>
+ <h1 ref={headingRef} tabIndex={headingRef ? -1 : undefined} className="text-2xl font-bold tracking-tight outline-none">
+ {title ?? (appIdentity ? `Connect ${appIdentity.name}` : "Connect your own MCP server")}
+ </h1>
+ {subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
+ {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-2" /> : null}
+ </div>
+ </div>
+ {onCancel && <Button variant="ghost" size="sm" onClick={onCancel}>
+ Cancel
+ </Button>}
+ </div>
+ {step !== "gallery" && labels.length > 1 && (
+ // A landmark with stable hooks, so the step model can be read without
+ // guessing at Tailwind classes. The dots are decoration — the label
+ // line below already says the same thing, so announcing both would
+ // read every step name twice.
+ <nav className="mt-4" aria-label="Setup progress" data-testid="wizard-stepper">
+ <ol className="flex gap-2" aria-hidden="true">
+ {labels.map((label, i) => (
+ <li
+ key={label}
+ data-testid="wizard-step-dot"
+ data-step-active={i === activeIndex ? "true" : undefined}
+ className={cn("h-1 w-20 rounded-full", i <= activeIndex ? "bg-foreground" : "bg-border")}
+ />
+ ))}
+ </ol>
+ <div className="mt-2 text-xs text-muted-foreground" data-testid="wizard-step-labels">
+ {labels.join(" · ")}
+ </div>
+ </nav>
+ )}
+ </div>
+ );
+}
+
diff --git a/ui/src/lib/runRetryState.ts b/ui/src/lib/runRetryState.ts
index 1cc33db189..ce332b48e9 100644
--- a/ui/src/lib/runRetryState.ts
+++ b/ui/src/lib/runRetryState.ts
@@ -19,6 +19,7 @@ export type RunRetryStateSummary = {
};
const RETRY_REASON_LABELS: Record<string, string> = {
+ ai_connection_pool_wait: "Waiting for pool usage to recover",
transient_failure: "Transient failure",
missing_issue_comment: "Missing task comment",
process_lost: "Process lost",
@@ -65,7 +66,7 @@ export function describeRunRetryState(run: RetryAwareRun): RunRetryStateSummary
if (run.status === "scheduled_retry") {
return {
kind: "scheduled",
- badgeLabel: isMaxTurnContinuation ? "Continuation scheduled" : "Retry scheduled",
+ badgeLabel: run.scheduledRetryReason === "ai_connection_pool_wait" ? "Pool exhausted" : isMaxTurnContinuation ? "Continuation scheduled" : "Retry scheduled",
tone: "border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300",
detail: joinFragments([attemptLabel, reasonLabel]),
secondary: dueAt
diff --git a/ui/src/lib/test-agent-setup.test.ts b/ui/src/lib/test-agent-setup.test.ts
index 9154d951ed..514b8516e0 100644
--- a/ui/src/lib/test-agent-setup.test.ts
+++ b/ui/src/lib/test-agent-setup.test.ts
@@ -27,6 +27,12 @@ const ready = {
checks: [{ code: "runtime", level: "info", message: "Ready" }],
};
beforeEach(() => testEnvironment.mockReset());
+it("does not launch an ambient provider hello test for a pool preview", async () => {
+ testEnvironment.mockResolvedValue({ ...ready, status: "warn", checks: [{ code: "ai_connection_pool_task_test_required", level: "warn", message: "Run a task" }] });
+ await testAgentSetup({ ...input, aiConnection: { mode: "router", connectionId: "pool-id" } });
+ expect(testEnvironment).toHaveBeenCalledTimes(1);
+ expect(testEnvironment.mock.calls[0]?.[2].aiConnection).toEqual({ mode: "router", connectionId: "pool-id" });
+});
it("does not report a connection when runtime readiness passes but provider authentication fails", async () => {
testEnvironment
.mockResolvedValueOnce(ready)
diff --git a/ui/src/lib/test-agent-setup.ts b/ui/src/lib/test-agent-setup.ts
index e56cd8bbcb..8e49fc51f3 100644
--- a/ui/src/lib/test-agent-setup.ts
+++ b/ui/src/lib/test-agent-setup.ts
@@ -10,7 +10,7 @@ export async function testAgentSetup(input: {
adapterType: string;
providerAdapter: string;
adapterConfig: Record<string, unknown>;
- aiConnection?: import("@paperclipai/shared").AiConnectionBinding;
+ aiConnection?: import("@paperclipai/shared").AiRuntimeConnectionBinding;
testCredentials?: Record<string, string>;
environmentId: string | null;
}): Promise<AdapterEnvironmentTestResult> {
@@ -27,6 +27,7 @@ export async function testAgentSetup(input: {
payload,
);
if (
+ input.aiConnection?.mode === "router" ||
runtime.status === "fail" ||
runtime.checks.some(
(check) => check.code === ADAPTER_AUTH_MISSING_CHECK_CODE,
diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx
index 5465b731c7..84a616a77b 100644
--- a/ui/src/pages/AgentDetail.tsx
+++ b/ui/src/pages/AgentDetail.tsx
@@ -1,3 +1,4 @@
+import { AiConnectionPoolRunDetails } from "@/components/ai-connections/AiConnectionPoolRunDetails";
import { AgentConnectionInstructions } from "@/features/connections/ConnectionInstructions";
import type { AgentInstructionCandidate, AgentInstructionsBundle } from "@paperclipai/shared";
import { InstructionHistory } from "../components/InstructionHistory";
@@ -64,7 +65,7 @@ import { buildSameOriginWebSocketUrl } from "../lib/websocket-url";
import { tryCreateWebSocket } from "../lib/websocket";
import { formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";
import { cn } from "../lib/utils";
-import { describeRunRetryState } from "../lib/runRetryState";
+import { RunRetryDetails } from "../components/RunRetryDetails";
import { Button } from "@/components/ui/button";
import { Tabs } from "@/components/ui/tabs";
import { PageTabBar } from "../components/PageTabBar";
@@ -3571,7 +3572,6 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }
const sessionChanged = run.sessionIdBefore && run.sessionIdAfter && run.sessionIdBefore !== run.sessionIdAfter;
const sessionId = run.sessionIdAfter || run.sessionIdBefore;
const hasNonZeroExit = run.exitCode !== null && run.exitCode !== 0;
- const retryState = describeRunRetryState(run);
return (
<div className="space-y-4 min-w-0">
@@ -3579,6 +3579,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }
git workspace it could not validate, wired to the same reconcile / repair / re-issue /
break-glass handlers as the task detail page. */}
<RunWorkspaceRecoverySurface run={run} />
+ <AiConnectionPoolRunDetails context={run.contextSnapshot} />
{/* Run summary card */}
<div className="border border-border rounded-lg overflow-hidden">
<div className="flex flex-col sm:flex-row">
@@ -3801,30 +3802,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }
{run.signal && <span className="text-muted-foreground ml-1">(signal: {run.signal})</span>}
</div>
)}
- {retryState && (
- <div className="rounded-md border border-border/70 bg-accent/20 px-3 py-2 text-xs leading-5">
- <div className="flex flex-wrap items-center gap-2">
- <span
- className={cn(
- "rounded-md border px-1.5 py-0.5 text-(length:--text-micro) font-medium",
- retryState.tone,
- )}
- >
- {retryState.badgeLabel}
- </span>
- {retryState.retryOfRunId ? (
- <Link
- to={`/agents/${agentRouteId}/runs/${retryState.retryOfRunId}`}
- className="font-mono text-foreground hover:underline"
- >
- {retryState.retryOfRunId.slice(0, 8)}
- </Link>
- ) : null}
- </div>
- {retryState.detail ? <p className="mt-2 text-muted-foreground">{retryState.detail}</p> : null}
- {retryState.secondary ? <p className="text-muted-foreground">{retryState.secondary}</p> : null}
- </div>
- )}
+ <RunRetryDetails run={run} agentRouteId={agentRouteId} />
</div>
{/* Right column: metrics */}
diff --git a/ui/src/pages/InstanceExperimentalSettings.test.tsx b/ui/src/pages/InstanceExperimentalSettings.test.tsx
index b1f71435d4..568b46a4d7 100644
--- a/ui/src/pages/InstanceExperimentalSettings.test.tsx
+++ b/ui/src/pages/InstanceExperimentalSettings.test.tsx
@@ -72,6 +72,7 @@ function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload {
return {
enableEnvironments: false,
enableNativeRunner: false,
+ enableAiConnectionRouters: false,
enableManagedSandboxOnly: false,
enableIsolatedWorkspaces: false,
enableIsolatedWorkspacesByDefault: false,
@@ -1060,6 +1061,24 @@ describe("InstanceExperimentalSettings — operator-hidden cards", () => {
await flushReact();
}
+ it.each([
+ { cloud: false, enabled: false },
+ { cloud: false, enabled: true },
+ { cloud: true, enabled: false },
+ { cloud: true, enabled: true },
+ ])("offers no AI routing control with cloud=$cloud and enabled=$enabled", async ({ cloud, enabled }) => {
+ await renderPage(undefined, {
+ ...defaultExperimentalSettings(),
+ enableAiConnectionRouters: enabled,
+ ...(cloud ? { managedKeys: { enableAiConnectionRouters: { managed: true, managedBy: "paperclip-cloud" as const } } } : {}),
+ });
+
+ expect(container.textContent).toContain("Experimental features");
+ expect(container.textContent).not.toContain("AI connection routers");
+ expect(container.querySelector('button[aria-label="Toggle AI connection routers experimental setting"]')).toBeNull();
+ expect(mockInstanceSettingsApi.updateExperimental).not.toHaveBeenCalled();
+ });
+
it("renders nothing for an operator-hidden toggle and keeps the rest", async () => {
await renderPage(["instance.experimental.enableEnvironments"]);
diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx
index 5cb9347b06..d05c6da0a6 100644
--- a/ui/src/pages/apps/AppDetail.tsx
+++ b/ui/src/pages/apps/AppDetail.tsx
@@ -1,3 +1,5 @@
+import { AiConnectionPoolConnector } from "@/components/ai-connections/AiConnectionPoolConnector";
+import { aiConnectionRouterPluginKey } from "@paperclipai/shared";
import { ConnectionInstructionsSettings } from "@/features/connections/ConnectionInstructions";
import { HonchoWorkspaceSettings } from "@/features/connections/HonchoWorkspaceSettings";
import { BrowserUseSettingsPanel } from "./app-detail/BrowserUseSettingsPanel";
@@ -74,7 +76,16 @@ import {
export { connectionAddress, connectionTransportLabel };
-export function AppDetail({ renderActions, renderAgentSettings, renderConnectionSettings, onReconnect }: {
+export function AppDetail(props: { renderActions?: (connection: ToolConnection) => ReactNode; renderAgentSettings?: (connection: ToolConnection) => ReactNode; renderConnectionSettings?: (connection: ToolConnection) => ReactNode; onReconnect?: (connection: ToolConnection) => void } = {}) {
+ const { connectionId = "" } = useParams<{ connectionId: string }>();
+ const connection = useQuery({ queryKey: queryKeys.tools.connection(connectionId), queryFn: () => toolsApi.getConnection(connectionId), enabled: !!connectionId });
+ if (connection.isPending) return <p role="status">Loading connection…</p>;
+ if (connection.error) return <p role="alert">{connection.error.message}</p>;
+ const pluginKey = connection.data && aiConnectionRouterPluginKey(connection.data);
+ return pluginKey ? <AiConnectionPoolConnector pluginKey={pluginKey} connection={connection.data} /> : <StandardAppDetail {...props} />;
+}
+
+function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectionSettings, onReconnect }: {
renderActions?: (connection: ToolConnection) => ReactNode;
/** Optional agent settings within Permissions, following the access controls. */
renderAgentSettings?: (connection: ToolConnection) => ReactNode;
@@ -727,7 +738,7 @@ export function AppDetail({ renderActions, renderAgentSettings, renderConnection
);
}
-function AppDetailHeader({
+export function AppDetailHeader({
appName,
connection,
logoEntry,
@@ -735,6 +746,7 @@ function AppDetailHeader({
allowRemoteLogo,
status,
actionCount,
+ canRename = true,
renaming,
nameDraft,
renamePending,
@@ -750,6 +762,7 @@ function AppDetailHeader({
allowRemoteLogo: boolean;
status: StatusInfo;
actionCount: number | null;
+ canRename?: boolean;
renaming: boolean;
nameDraft: string;
renamePending: boolean;
@@ -801,6 +814,7 @@ function AppDetailHeader({
size="icon"
className="h-7 w-7 text-muted-foreground"
aria-label="Rename app"
+ disabled={!canRename}
onClick={onRenameStart}
>
<Pencil className="h-3.5 w-3.5" />
diff --git a/ui/src/pages/apps/AppsConnect.tsx b/ui/src/pages/apps/AppsConnect.tsx
index 69973b86bf..8d61d6ba53 100644
--- a/ui/src/pages/apps/AppsConnect.tsx
+++ b/ui/src/pages/apps/AppsConnect.tsx
@@ -1,3 +1,4 @@
+import { AiConnectionPoolConnector } from "@/components/ai-connections/AiConnectionPoolConnector";
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { isRetiredComposioConnection } from "@paperclipai/shared";
@@ -23,6 +24,8 @@ export function AppsConnect({ byoOnly = false, credentialSource = "paperclip_vau
const [searchParams] = useSearchParams();
const { appKey } = useParams<{ appKey?: string }>();
const source = searchParams.get("source") ?? appKey ?? searchParams.get("appKey");
+ const gallery = useQuery({ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"), queryFn: () => toolsApi.listGallery(selectedCompanyId!), enabled: !!selectedCompanyId && !!source?.startsWith("ai-router-") });
+ const router = gallery.data?.apps.find(app => app.slug === source)?.aiConnectionRouter;
const toolkit = searchParams.get("targetToolkit");
const reuseComposio = source === "composio" && Boolean(toolkit && findComposioCatalogApp(toolkit))
&& searchParams.get("new") !== "1" && !searchParams.get("resume") && !searchParams.get("reconnect")
@@ -45,6 +48,11 @@ export function AppsConnect({ byoOnly = false, credentialSource = "paperclip_vau
const path = selectedCompanyId && consumeSkillSourceReturn(selectedCompanyId);
if (path) navigate(path);
}
+ if (source?.startsWith("ai-router-")) {
+ if (gallery.isPending) return <p role="status">Loading connector…</p>;
+ if (!router) return <p role="alert">{gallery.error?.message ?? "This connection pool plugin is unavailable. Enable it in Plugins."}</p>;
+ return <AiConnectionPoolConnector pluginKey={router.pluginKey} />;
+ }
return <ConnectionSetupFlow byoOnly={byoOnly} credentialSource={credentialSource} host="page"
onComplete={returningToSkills ? returnToSkills : undefined}
onCancel={returningToSkills ? returnToSkills : undefined} />;
diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsx
index cdd58286e3..daab986744 100644
--- a/ui/src/pages/apps/Browse.test.tsx
+++ b/ui/src/pages/apps/Browse.test.tsx
@@ -5,7 +5,7 @@ import { createRoot } from "react-dom/client";
import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Browse } from "./Browse";
-import { getAppStoreDefinition } from "@paperclipai/shared";
+import { aiConnectionRouterAppDefinition, getAppStoreDefinition } from "@paperclipai/shared";
import { queryKeys } from "@/lib/queryKeys";
import { TooltipProvider } from "@/components/ui/tooltip";
import type { AggregatorAppCatalogEntry } from "@paperclipai/shared/aggregator-app-catalog";
@@ -35,6 +35,10 @@ vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIs
const accountIdentity = vi.hoisted(() => ({ userId: "board-user" as string | null, settled: true, failed: false }));
vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => accountIdentity }));
+const poolListMock = vi.hoisted(() => vi.fn());
+const poolRemoveMock = vi.hoisted(() => vi.fn());
+vi.mock("@/api/ai-connection-pools", () => ({ aiConnectionPoolsApi: { list: poolListMock, remove: poolRemoveMock } }));
+
const listGalleryMock = vi.hoisted(() => vi.fn());
const listApplicationsMock = vi.hoisted(() => vi.fn());
const listConnectionsMock = vi.hoisted(() => vi.fn());
@@ -1147,6 +1151,29 @@ describe("Connectors landing page", () => {
);
});
+ it("retains the confirmed pool revision when a concurrent edit rejects removal", async () => {
+ const app = aiConnectionRouterAppDefinition("example.pool", { name: "AI connection pool", description: "Use saved connections" });
+ listGalleryMock.mockResolvedValue({ apps: [app] });
+ listApplicationsMock.mockResolvedValue({ applications: [application({ name: app.name, metadata: { sourceTemplateKey: app.slug } })] });
+ listConnectionsMock.mockResolvedValue({ connections: [connection({ name: "Research", config: { aiRouter: { pluginKey: "example.pool" } } })] });
+ poolListMock.mockResolvedValue([{ id: "conn-notion", name: "Research", revision: 7 }]);
+ poolRemoveMock.mockRejectedValue(new Error("Pool changed; reload before deleting"));
+ await renderBrowse();
+ await act(() => { container.querySelector<HTMLButtonElement>('button[aria-label="Manage Research connection"]')!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); });
+ await flushReact();
+ await act(() => Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(item => item.textContent?.trim() === "Remove connection")!.click());
+ await flushReact();
+ expect(document.body.textContent).toContain("The connections in this pool are kept.");
+ poolListMock.mockResolvedValue([{ id: "conn-notion", name: "Edited elsewhere", revision: 8 }]);
+ await act(() => Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => button.textContent?.trim() === "Remove connection")!.click());
+ await flushReact();
+ expect(poolRemoveMock).toHaveBeenCalledWith("company-1", "conn-notion", 7);
+ expect(poolListMock).toHaveBeenCalledTimes(1);
+ expect(archiveConnectionMock).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="alertdialog"]')).not.toBeNull();
+ expect(pushToastMock).toHaveBeenCalledWith(expect.objectContaining({ body: "Pool changed; reload before deleting" }));
+ });
+
it("starts each AgentMail Add connection with a distinct setup identity", async () => {
chatListMock.mockResolvedValue([{ id: "chat-draft", provider: "agentmail", status: "draft", assignedAgentName: "Ralph" }]);
await renderBrowse();
diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx
index af142e9b3f..17fb9d657c 100644
--- a/ui/src/pages/apps/Browse.tsx
+++ b/ui/src/pages/apps/Browse.tsx
@@ -4,6 +4,7 @@ import { ExecutorManagementSetup } from "./ExecutorManagementSetup";
import { ArcadeDiscoverySetup } from "./ArcadeDiscoverySetup";
import { AggregatorAppManager } from "./AggregatorAppManager";
import {
+ aiConnectionRouterPluginKey,
connectionSetupVerbForApp,
isRetiredComposioConnection,
RETIRED_COMPOSIO_MESSAGE,
@@ -45,6 +46,7 @@ import { useCompany } from "@/context/CompanyContext";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useToast } from "@/context/ToastContext";
import { queryKeys } from "@/lib/queryKeys";
+import { aiConnectionPoolsApi } from "@/api/ai-connection-pools";
import { toolsApi } from "@/api/tools";
import { emailApi } from "@/api/email";
import { useAccountIdentity } from "@/api/companies-query";
@@ -131,6 +133,8 @@ type ConnectionRemovalTarget = {
accountName: string;
providerName: string;
remainingConnectionCount: number;
+ pool?: boolean;
+ poolRevision?: number;
} & ({ kind: "chat"; provider: ChatProvider } | { kind?: undefined });
// Temporary, page-only hold until Google OAuth verification is approved.
@@ -172,6 +176,7 @@ function chatConnectHref(
function connectHrefFor(entry: AppGalleryDisplayEntry): string | null {
const slug = appDefinitionSlug(entry);
+ if (entry.aiConnectionRouter) return appSourceConnectHref(slug);
const definition = getAppStoreDefinition(slug);
return appSupportsToolCatalogSetup(definition)
? appSourceConnectHref(slug)
@@ -252,6 +257,7 @@ function connectorAction(
href: string | null;
title?: string;
} {
+ if (row.entry?.aiConnectionRouter) return { label: "Add connection pool", href: row.entry.availability?.available === false ? null : connectHrefFor(row.entry), title: row.entry.availability?.reason };
if (row.aggregatorApp && isInstalled(row)) return { label: "Manage", href: null };
const applicationId = row.applications[0]?.id ?? null;
const chatHref = (row.slug === "agentmail" || chatConnectorsEnabled)
@@ -314,7 +320,7 @@ function accountActionHref(
* surface. Connected providers sort first and expand in place to show every
* account; unconnected providers retain the same catalog setup flows.
*/
-export function Browse({ renderAccountDetails = (connection) => connection.connectionPurpose === "ai" ? <ManagedAiConnectionRow connection={connection} /> : null }: { renderAccountDetails?: (connection: ToolConnection) => ReactNode } = {}) {
+export function Browse({ renderAccountDetails = (connection) => connection.connectionPurpose === "ai" && !aiConnectionRouterPluginKey(connection) ? <ManagedAiConnectionRow connection={connection} /> : null }: { renderAccountDetails?: (connection: ToolConnection) => ReactNode } = {}) {
const navigate = useNavigate();
const preselectedChatAgentId =
typeof window === "undefined"
@@ -418,6 +424,9 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
} else {
await chatEndpointsApi.setup(target.id, { action: "remove" });
}
+ } else if (target.pool) {
+ if (!target.poolRevision) throw new Error("Open the confirmation again before removing this pool.");
+ await aiConnectionPoolsApi.remove(selectedCompanyId!, target.id, target.poolRevision);
} else {
await toolsApi.archiveConnection(target.id);
}
@@ -439,7 +448,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
pushToast({
title: "Connection removed",
body:
- target.kind === "chat"
+ target.pool ? "The connections in the pool are kept." : target.kind === "chat"
? `${target.providerName} is disconnected. Existing Paperclip tasks remain available.`
: target.remainingConnectionCount > 0
? `${target.providerName} still has ${target.remainingConnectionCount} active ${target.remainingConnectionCount === 1 ? "connection" : "connections"} available to agents.`
@@ -455,9 +464,18 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
tone: "error",
}),
});
- function requestConnectionRemoval(target: ConnectionRemovalTarget) {
+ async function requestConnectionRemoval(target: ConnectionRemovalTarget) {
removeConnection.reset();
- setConnectionToRemove(target);
+ if (!target.pool) { setConnectionToRemove(target); return; }
+ try {
+ const pool = (await aiConnectionPoolsApi.list(selectedCompanyId!)).find(pool => pool.id === target.id);
+ if (!pool) throw new Error("This connection pool is no longer available.");
+ // Capture the revision when presenting the confirmation. Never replace
+ // it at submission time: concurrent edits must invalidate this consent.
+ setConnectionToRemove({ ...target, accountName: pool.name, poolRevision: pool.revision });
+ } catch (error) {
+ pushToast({ title: "Couldn't open the connection pool", body: error instanceof Error ? error.message : "Please try again.", tone: "error" });
+ }
}
const gallery = (
@@ -889,7 +907,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
userProfileById={userProfileById}
connectionById={connectionById}
onNavigate={navigate}
- onRequestRemove={requestConnectionRemoval}
+ onRequestRemove={target => void requestConnectionRemoval(target)}
preselectedAgentId={preselectedChatAgentId}
chatConnectorsEnabled={chatConnectorsEnabled}
onConnectAggregator={connectAggregator}
@@ -939,7 +957,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
Remove {connectionToRemove?.accountName ?? "this"} connection?
</AlertDialogTitle>
<AlertDialogDescription>
- {connectionToRemove && Object.values(AGGREGATOR_NAMES).includes(connectionToRemove.providerName as "Composio")
+ {connectionToRemove?.pool ? "The connections in this pool are kept." : connectionToRemove && Object.values(AGGREGATOR_NAMES).includes(connectionToRemove.providerName as "Composio")
? `This removes the saved ${connectionToRemove.providerName} connection from Paperclip and agents lose access through it. Your apps and accounts remain connected in ${connectionToRemove.providerName}.`
: connectionToRemove?.kind === "chat"
? `This connection will stop receiving new work from ${connectionToRemove.providerName}. Existing Paperclip tasks and conversation history remain available. This does not delete the app, bot, or account in ${connectionToRemove.providerName}.`
@@ -1106,6 +1124,7 @@ export function ConnectorCard({
);
onRequestRemove({
id: connection.id,
+ pool: Boolean(aiConnectionRouterPluginKey(connection)),
accountName,
providerName: row.name,
remainingConnectionCount: row.connections.filter(
diff --git a/ui/src/pages/apps/app-connect-policy.test.ts b/ui/src/pages/apps/app-connect-policy.test.ts
index 5756946ae5..481ce0e4c6 100644
--- a/ui/src/pages/apps/app-connect-policy.test.ts
+++ b/ui/src/pages/apps/app-connect-policy.test.ts
@@ -1,4 +1,4 @@
-import { APP_STORE_DEFINITIONS, appSupportsCatalogSetup } from "@paperclipai/shared";
+import { APP_STORE_DEFINITIONS, aiConnectionRouterAppDefinition, appSupportsCatalogSetup } from "@paperclipai/shared";
import { describe, expect, it } from "vitest";
import {
MCP_DIRECT_OAUTH_CONNECT_SLUGS,
@@ -63,6 +63,14 @@ describe("app connect policy", () => {
expect(vercelConnectSourceHref("notion")).toBe("/apps/vercel-connect?source=notion");
});
+ it("lets installed router connectors reach host catalog validation", () => {
+ const pool = aiConnectionRouterAppDefinition("example.pool", { name: "AI connection pool", description: "Use saved connections" });
+ const params = new URL(appSourceConnectHref(pool.slug), "http://paperclip.test").searchParams;
+ expect(canEnterAppsConnect(params)).toBe(true);
+ expect(canEnterAppsConnect(new URLSearchParams("source=ai-router-invalid"))).toBe(false);
+ expect(canEnterAppsConnect(new URLSearchParams("source=ai-router-1"))).toBe(false);
+ });
+
it("routes every capability-backed catalog definition through its source deep link", () => {
const connectableApps = APP_STORE_DEFINITIONS.filter(appSupportsCatalogSetup);
diff --git a/ui/src/pages/apps/app-connect-policy.ts b/ui/src/pages/apps/app-connect-policy.ts
index 60dfbea7ed..b54f8c9e7c 100644
--- a/ui/src/pages/apps/app-connect-policy.ts
+++ b/ui/src/pages/apps/app-connect-policy.ts
@@ -67,6 +67,11 @@ export function canEnterAppsConnect(
);
}
const source = searchParams.get("source") ?? "";
+ // Router connectors are registered by installed plugins, not the static
+ // catalog. AppsConnect resolves this reserved slug against the host gallery
+ // before rendering the pool wizard; unknown/uninstalled routers show its
+ // actionable unavailable state rather than bouncing back to the catalog.
+ if (/^ai-router-(?:[a-f0-9]{2})+$/.test(source)) return true;
const entry = getAppStoreDefinition(source);
if (
!chatConnectorsEnabled &&
diff --git a/ui/src/pages/apps/app-definition-display.ts b/ui/src/pages/apps/app-definition-display.ts
index 77740ad910..2c86abbe55 100644
--- a/ui/src/pages/apps/app-definition-display.ts
+++ b/ui/src/pages/apps/app-definition-display.ts
@@ -1,3 +1,4 @@
+import { aiConnectionRouterSlug, aiConnectionRouterPluginKey } from "@paperclipai/shared";
import type { AppDefinition, ToolApplication, ToolConnection } from "@paperclipai/shared";
export type AppGalleryDisplayEntry = AppDefinition & {
@@ -34,6 +35,8 @@ export function appApplicationSourceSlug(application: ToolApplication | null | u
if (typeof source === "string" && source.trim()) return source.trim();
const key = application.applicationKey?.trim();
if (!key) return null;
+ const router = key.match(/^plugin:(.+):ai-router$/);
+ if (router) return aiConnectionRouterSlug(router[1]);
const galleryPrefix = "app-gallery:";
if (key.startsWith(galleryPrefix)) {
const slug = key.slice(galleryPrefix.length).split(":")[0] || null;
@@ -47,6 +50,8 @@ export function appApplicationSourceSlug(application: ToolApplication | null | u
export function appConnectionSourceSlug(connection: ToolConnection | null | undefined): string | null {
if (!connection) return null;
+ const router = aiConnectionRouterPluginKey(connection);
+ if (router) return aiConnectionRouterSlug(router);
const source = connection.config?.sourceTemplateKey ?? connection.transportConfig?.sourceTemplateKey;
return typeof source === "string" && source.trim() ? source.trim() : null;
}
diff --git a/ui/storybook/prototypes/ConnectionPoolConnectorHost.tsx b/ui/storybook/prototypes/ConnectionPoolConnectorHost.tsx
new file mode 100644
index 0000000000..e5dbc35bde
--- /dev/null
+++ b/ui/storybook/prototypes/ConnectionPoolConnectorHost.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useState } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { Route, Routes, useNavigate, useParams } from "@/lib/router";
+import { aiConnectionRouterAppDefinition, aiConnectionRouterSlug, getAppStoreDefinition, type AiConnectionList, type AiConnectionPool, type ToolApplication, type ToolConnection } from "@paperclipai/shared";
+import { Browse } from "@/pages/apps/Browse";
+import { AppsConnect } from "@/pages/apps/AppsConnect";
+import { AppDetail } from "@/pages/apps/AppDetail";
+import { AppDetailSidebar } from "@/components/AppConnectionSidebar";
+import { BreadcrumbBar } from "@/components/BreadcrumbBar";
+
+export type PoolConnectorScenario = "catalog" | "setup" | "manage" | "empty" | "unavailable" | "permission" | "conflict" | "usage" | "exhausted" | "unknown" | "revoked";
+export interface PoolConnectorStoryProps { pluginKey?: string; descriptor?: { name: string; description: string }; scenario?: PoolConnectorScenario }
+const companyId = "company-storybook";
+const poolId = "10000000-0000-4000-8000-000000000001";
+const date = new Date("2026-09-10T12:00:00Z");
+export const poolStoryAccounts: AiConnectionList["connections"] = [
+ { id: "30000000-0000-4000-8000-000000000001", grantId: "40000000-0000-4000-8000-000000000001", companyId, provider: "openai", method: "subscription", name: "My ChatGPT account", ownership: "personal", isDefault: true, status: "connected" },
+ { id: "30000000-0000-4000-8000-000000000002", grantId: "40000000-0000-4000-8000-000000000002", companyId, provider: "anthropic", method: "subscription", name: "My Claude account", ownership: "personal", isDefault: true, status: "connected" },
+ { id: "30000000-0000-4000-8000-000000000003", grantId: "40000000-0000-4000-8000-000000000003", companyId, provider: "openrouter", method: "api_key", name: "Team OpenRouter", ownership: "shared", isDefault: true, status: "connected" },
+];
+/** Production Connectors routes with fixture data only. Used by host and plugin stories. */
+export function ConnectionPoolConnectorHost({ pluginKey = "example.pool-router", descriptor = { name: "AI connection pool", description: "Rotate tasks between your AI connections." }, scenario = "catalog" }: PoolConnectorStoryProps) {
+ const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false }, mutations: { retry: false } } }));
+ const [ready, setReady] = useState(false);
+ const navigate = useNavigate();
+ useEffect(() => {
+ const previous = window.fetch;
+ const catalog = [aiConnectionRouterAppDefinition(pluginKey, descriptor, scenario === "unavailable" ? { available: false, reason: "Ask your instance operator to enable AI connection routing." } : { available: true }), ...["openai", "anthropic", "openrouter", "github"].map(slug => getAppStoreDefinition(slug)!)];
+ let pools: AiConnectionPool[] = ["setup", "empty", "catalog", "unavailable"].includes(scenario) ? [] : [{ id: poolId, companyId, pluginKey, name: "Research accounts", enabled: false, mode: ["usage", "exhausted", "unknown"].includes(scenario) ? "usage_aware" : "round_robin", thresholdPercent: 90, revision: 1, members: poolStoryAccounts.slice(0, 2).map((account, index) => ({ id: `20000000-0000-4000-8000-00000000000${index + 1}`, binding: { mode: "delegated", provider: account.provider, method: account.method, connectionId: account.id, grantId: account.grantId }, profile: index === 0 ? { provider: "codex", model: "gpt-5.6-sol" } : { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-5" } })) }];
+ const accounts = scenario === "empty" ? [] : scenario === "revoked" ? poolStoryAccounts.slice(1) : poolStoryAccounts;
+ const applications = (): ToolApplication[] => catalog.map(app => ({ id: `app-${app.slug}`, companyId, applicationKey: app.aiConnectionRouter ? `plugin:${pluginKey}:ai-router` : `app-gallery:${app.slug}`, name: app.name, description: app.description, type: app.aiConnectionRouter ? "paperclip_plugin" : "mcp_http", status: "active", pluginId: app.aiConnectionRouter ? "plugin-storybook" : null, ownerAgentId: null, ownerUserId: "dotta", metadata: { sourceTemplateKey: app.slug }, archivedAt: null, createdAt: date, updatedAt: date }));
+ const connections = (): ToolConnection[] => [...accounts.map(account => ({ id: account.id, name: account.name, enabled: true, slug: account.provider, config: { sourceTemplateKey: account.provider, ai: { provider: account.provider, method: account.method }, aiIsolatedSubscription: true } })), ...pools.map(pool => ({ id: pool.id, name: pool.name, enabled: pool.enabled, slug: aiConnectionRouterSlug(pluginKey), config: { aiRouter: { pluginKey }, sourceTemplateKey: aiConnectionRouterSlug(pluginKey) } }))].map(row => ({ id: row.id, companyId, applicationId: `app-${row.slug}`, name: row.name, uid: row.id, connectionKind: "managed", ownership: "customer", connectionPurpose: "ai", transport: "runtime_auth", authKind: "none", credentialSource: "paperclip_vault", credentialPolicy: "per_user", status: "active", enabled: row.enabled, transportConfig: {}, config: row.config, credentialSecretRefs: [], healthStatus: "ok", healthCheckedAt: date, healthMessage: null, lastError: null, createdByAgentId: null, createdByUserId: "dotta", createdAt: date, updatedAt: date }));
+ window.fetch = async (input, init) => {
+ const request = input instanceof Request ? input : null;
+ const path = new URL(request?.url ?? String(input), window.location.origin).pathname;
+ const method = init?.method ?? request?.method ?? "GET";
+ const body = typeof init?.body === "string" ? JSON.parse(init.body) : {};
+ const reply = (value: unknown) => Response.json(value);
+ if (path === `/api/companies/${companyId}/chat-endpoints`) return reply([]);
+ if (path === `/api/companies/${companyId}/agents`) return reply(["setup", "empty", "catalog", "unavailable"].includes(scenario) ? [] : [
+ { id: "50000000-0000-4000-8000-000000000001", companyId, name: "Researcher", status: "idle", runtimeConfig: { aiConnection: { mode: "router", connectionId: poolId } } },
+ { id: "50000000-0000-4000-8000-000000000002", companyId, name: "Writer", status: "paused", runtimeConfig: { aiConnection: { mode: "router", connectionId: poolId } } },
+ { id: "50000000-0000-4000-8000-000000000003", companyId, name: "Other pool agent", status: "idle", runtimeConfig: { aiConnection: { mode: "router", connectionId: "another-pool" } } },
+ { id: "50000000-0000-4000-8000-000000000004", companyId, name: "Former researcher", status: "terminated", runtimeConfig: { aiConnection: { mode: "router", connectionId: poolId } } },
+ ]);
+ if (path === `/api/companies/${companyId}/user-directory`) return reply({ users: [{ principalId: "dotta", status: "active", user: { name: "Dotta", email: "[email protected]" } }] });
+ if (path === `/api/companies/${companyId}/tools/apps/attention`) return reply({ apps: [] });
+ if (path === `/api/companies/${companyId}/tools/gallery`) return reply({ apps: catalog, capabilities: { canCreateOrganizationGrant: true, canSetCompanyInstall: true } });
+ if (path === `/api/companies/${companyId}/tools/applications`) return reply({ applications: applications() });
+ if (path === `/api/companies/${companyId}/tools/connections`) return reply({ connections: connections() });
+ if (path === `/api/companies/${companyId}/ai-connections`) return reply({ currentUserId: "dotta", canManageConnections: scenario !== "permission", connections: accounts });
+ if (path === `/api/companies/${companyId}/ai-connection-pools`) {
+ if (scenario === "permission") return Response.json({ error: "A connection manager is required" }, { status: 403 });
+ if (method === "GET") return reply(pools);
+ if (scenario === "conflict") return Response.json({ error: "Pool changed; reload before saving" }, { status: 409 });
+ const previousPool = pools.find(pool => pool.id === body.id);
+ if (body.id && (!previousPool || previousPool.revision !== body.expectedRevision)) return Response.json({ error: "Pool changed; reload before saving" }, { status: 409 });
+ const saved = { ...body.config, id: body.id ?? poolId, companyId, pluginKey, revision: (previousPool?.revision ?? 0) + 1 };
+ pools = [...pools.filter(pool => pool.id !== saved.id), saved]; return reply(saved);
+ }
+ if (path.endsWith("/inspection")) return reply(Object.fromEntries((pools[0]?.members ?? []).map((member, index) => {
+ const percent = scenario === "exhausted" ? 100 : index === 0 ? 94 : 42;
+ const observed = ["usage", "exhausted", "unknown"].includes(scenario);
+ const checkedAt = new Date(Date.now() - 15000).toISOString();
+ return [member.id, { reason: "Eligible if agent access permits", checkedAt: observed ? checkedAt : null,
+ ...(observed ? { usage: { connectionId: member.binding.connectionId, grantId: member.binding.grantId, provider: member.binding.provider, method: member.binding.method, status: scenario === "unknown" ? "unsupported" : "ok", checkedAt, source: "fixture", planType: "subscription", overage: null, limits: scenario === "unknown" ? [] : [{ id: "subscription", label: "Subscription", scope: null, usedPercent: percent, remainingPercent: 100 - percent, windowDurationSeconds: 18000, resetsAt: new Date(Date.now() + 180000).toISOString(), used: null, limit: null, remaining: null, unit: null, limitReached: percent >= 100, allowed: percent < 100 }] } } : {}) }];
+ })));
+ if (method === "DELETE" && path.includes("/ai-connection-pools/")) { pools = pools.filter(pool => !path.endsWith(pool.id)); return reply({ ok: true }); }
+ const connection = path.match(/^\/api\/tool-connections\/([^/]+)$/);
+ if (connection) { const row = connections().find(row => row.id === connection[1]); if (method === "DELETE") pools = pools.filter(pool => pool.id !== connection[1]); return row ? reply(row) : Response.json({ error: "Connection not found" }, { status: 404 }); }
+ // Fixtures never forward a mutation to a live instance.
+ if (path.startsWith("/api/") && method !== "GET") return Response.json({ error: "This preview does not run live operations." }, { status: 400 });
+ return previous(input, init);
+ };
+ navigate(["setup", "empty"].includes(scenario) ? `/PAP/apps/connect?source=${aiConnectionRouterSlug(pluginKey)}` : ["catalog", "unavailable"].includes(scenario) ? "/PAP/apps" : `/PAP/apps/${poolId}/permissions`, { replace: true });
+ setReady(true);
+ return () => { window.fetch = previous; client.clear(); };
+ }, []);
+ if (!ready) return <p>Loading connectors…</p>;
+ return <QueryClientProvider client={client}><Routes>
+ <Route path="/:companyPrefix/apps" element={<div className="mx-auto max-w-5xl p-6"><BreadcrumbBar /><div className="pt-6"><Browse renderAccountDetails={() => null} /></div></div>} />
+ <Route path="/:companyPrefix/apps/connect" element={<div className="mx-auto max-w-5xl p-6"><BreadcrumbBar /><div className="pt-6"><AppsConnect /></div></div>} />
+ <Route path="/:companyPrefix/apps/:connectionId/:tab" element={<PoolDetailRoute />} />
+ </Routes></QueryClientProvider>;
+}
+function PoolDetailRoute() {
+ const { connectionId = "" } = useParams<{ connectionId: string }>();
+ return <div className="flex min-h-screen"><div className="hidden w-56 shrink-0 md:block"><AppDetailSidebar kind="connection" connectionId={connectionId} /></div><main className="min-w-0 flex-1 p-6"><BreadcrumbBar /><div className="mx-auto max-w-3xl pt-6"><AppDetail /></div></main></div>;
+}
diff --git a/ui/storybook/stories/connection-pool-connector.stories.tsx b/ui/storybook/stories/connection-pool-connector.stories.tsx
new file mode 100644
index 0000000000..d6dac52e8e
--- /dev/null
+++ b/ui/storybook/stories/connection-pool-connector.stories.tsx
@@ -0,0 +1,32 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, within } from "storybook/test";
+import { ConnectionPoolConnectorHost } from "../prototypes/ConnectionPoolConnectorHost";
+const meta = { title: "Connectors/Pool host", component: ConnectionPoolConnectorHost, parameters: { layout: "fullscreen" } } satisfies Meta<typeof ConnectionPoolConnectorHost>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+export const Catalog: Story = {};
+export const Setup: Story = { args: { scenario: "setup" } };
+export const OperatorSetupRequired: Story = { args: { scenario: "unavailable" }, play: async ({ canvasElement }) => {
+ const add = await within(canvasElement).findByRole("button", { name: "Add connection pool AI connection pool" });
+ await expect(add).toBeDisabled();
+ await expect(add).toHaveAttribute("title", "Ask your instance operator to enable AI connection routing.");
+} };
+export const Manage: Story = { args: { scenario: "manage" }, play: async ({ canvasElement }) => {
+ const usedBy = within(await within(canvasElement).findByRole("region", { name: "Used by" }));
+ await expect(await usedBy.findByRole("link", { name: "Researcher" })).toBeVisible();
+ await expect(usedBy.getByRole("link", { name: "Writer" })).toBeVisible();
+ await expect(usedBy.getAllByRole("link")).toHaveLength(2);
+} };
+export const CreateFromConnectors: Story = { play: async ({ canvasElement }) => {
+ const c = within(canvasElement);
+ await userEvent.click(await c.findByRole("button", { name: "Add connection pool AI connection pool" }));
+ await userEvent.click(await c.findByRole("checkbox", { name: "My ChatGPT account" }));
+ await userEvent.click(c.getByRole("checkbox", { name: "My Claude account" }));
+ await userEvent.click(c.getByRole("button", { name: "Continue" }));
+ await userEvent.click(c.getByRole("button", { name: "Move My Claude account up" }));
+ await expect(within(c.getByRole("list", { name: "Connection order" })).getAllByRole("listitem")[0]).toHaveTextContent("My Claude account");
+ await userEvent.click(c.getByRole("button", { name: "Create pool" }));
+ await expect(await c.findByRole("checkbox", { name: "Enable this pool" })).not.toBeChecked();
+ await expect(c.getByRole("heading", { level: 1, name: "AI connection pool" })).toBeVisible();
+ await expect(await within(c.getByRole("region", { name: "Used by" })).findByText("No agents yet.")).toBeVisible();
+} };
diff --git a/ui/storybook/stories/connection-pools.stories.tsx b/ui/storybook/stories/connection-pools.stories.tsx
new file mode 100644
index 0000000000..0f480d7156
--- /dev/null
+++ b/ui/storybook/stories/connection-pools.stories.tsx
@@ -0,0 +1,95 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, within } from "storybook/test";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Agent, AiConnectionList, AiConnectionPool, AiConnectionRouterSelection, AiRuntimeConnectionBinding, Issue } from "@paperclipai/shared";
+import { AiConnectionField } from "@/components/ai-connections/AiConnectionField";
+import { AiConnectionPoolRunDetails } from "@/components/ai-connections/AiConnectionPoolRunDetails";
+import { IssueMonitorBanner, IssueMonitorComposerStrip } from "@/components/IssueMonitorBanner";
+import { ComposerRunSettingsPicker } from "@/components/task-chat/ComposerRunSettingsPicker";
+import type { ComposerRunSettings } from "@/components/task-chat/composer-run-settings";
+import { RunRetryDetails } from "@/components/RunRetryDetails";
+import { queryKeys } from "@/lib/queryKeys";
+import { storybookAgents, storybookIssues } from "../fixtures/paperclipData";
+
+const companyId = "company-storybook", agentId = "agent-codex";
+const poolId = "10000000-0000-4000-8000-000000000001";
+const pool: AiConnectionPool = {
+ id: poolId, companyId, pluginKey: "paperclip-cloud.plugin-connection-pool", revision: 3,
+ name: "Research accounts", enabled: true, mode: "round_robin", thresholdPercent: 90,
+ members: [
+ { id: "20000000-0000-4000-8000-000000000001", binding: { mode: "delegated", provider: "openai", method: "subscription", connectionId: "30000000-0000-4000-8000-000000000001", grantId: "40000000-0000-4000-8000-000000000001" }, profile: { provider: "codex", model: "gpt-5.6-sol", effort: "high" } },
+ { id: "20000000-0000-4000-8000-000000000002", binding: { mode: "delegated", provider: "anthropic", method: "subscription", connectionId: "30000000-0000-4000-8000-000000000002", grantId: "40000000-0000-4000-8000-000000000002" }, profile: { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-5" } },
+ ],
+};
+const accounts: AiConnectionList = { currentUserId: "user-board", canManageConnections: true, pools: [pool], connections: pool.members.map((m, index) => ({
+ id: m.binding.connectionId!, grantId: m.binding.grantId!, companyId, provider: m.binding.provider, method: m.binding.method!, name: index === 0 ? "My OpenAI subscription" : "My Claude subscription", ownership: "personal", ownerUserId: "user-board", isDefault: true, status: "connected",
+})) };
+const models = [{ id: "gpt-5.6-sol", label: "GPT-5.6 Sol · Codex" }, { id: "claude-sonnet-5", label: "Claude Sonnet 5 · Claude ACP" }];
+const agent: Agent = { ...storybookAgents.find(a => a.id === agentId)!, adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-5.6-sol" }, runtimeConfig: { aiConnection: { mode: "router", connectionId: poolId } } };
+type Scenario = "overview" | "selector" | "legacy" | "adoption" | "unavailable" | "read-only" | "models" | "effort" | "mobile" | "claude-model" | "quota" | "checking" | "run-codex" | "run-claude" | "fallback" | "retry";
+
+function PoolComposer({ scenario }: { scenario: Scenario }) {
+ const [settings, setSettings] = useState<ComposerRunSettings>({ model: scenario === "claude-model" ? "claude-sonnet-5" : "gpt-5.6-sol", effort: null, fast: false });
+ return <div className="space-y-3 rounded-xl border bg-card p-4">
+ <p className="text-sm">Choose settings for the next turn. The task keeps its account and harness.</p>
+ <ComposerRunSettingsPicker companyId={companyId} assigneeValue={`agent:${agentId}`} currentAssigneeValue={`agent:${agentId}`}
+ options={[{ id: `agent:${agentId}`, label: agent.name }]} agents={new Map([[agentId, agent]])}
+ settings={settings} onSettingsChange={(next) => setSettings(next ?? { model: null, effort: null, fast: false })} onAssigneeChange={() => setSettings({ model: null, effort: null, fast: false })}
+ modelOptionsOverride={models} mobile={scenario === "mobile"} initialOpen={scenario !== "overview"}
+ initialView={scenario === "models" || scenario === "mobile" ? "models" : "settings"} />
+ </div>;
+}
+function PoolWait({ checking = false }: { checking?: boolean }) {
+ const [issue] = useState<Issue>(() => ({ ...storybookIssues[0]!, status: "in_progress", executionState: null,
+ scheduledRetry: { status: "scheduled_retry", scheduledRetryReason: "ai_connection_pool_wait", scheduledRetryAt: new Date(Date.now() + 60_000).toISOString(), scheduledRetryAttempt: 1 } as Issue["scheduledRetry"],
+ }));
+ return <div className="space-y-4"><IssueMonitorBanner issue={issue} onCheckNow={() => undefined} checkingNow={checking} /><IssueMonitorComposerStrip issue={issue} onCheckNow={() => undefined} checkingNow={checking} /></div>;
+}
+function PoolRun({ scenario }: { scenario: Scenario }) {
+ const claude = scenario === "run-claude", member = pool.members[claude ? 1 : 0]!;
+ const selection: AiConnectionRouterSelection = { poolId, memberId: member.id, binding: member.binding,
+ runtimeConfig: { ...member.profile, ...(claude ? {} : { modelReasoningEffort: "high" }) },
+ notes: scenario === "fallback" ? ["Model override is unavailable for this member; using its default.", "Effort override is unavailable for the effective model; using its default."] : [],
+ };
+ return <div className="space-y-4"><AiConnectionPoolRunDetails context={{ aiRouterSelection: selection, aiConnection: { accountName: claude ? "My Claude subscription" : "My OpenAI subscription" } }} />
+ {scenario === "retry" && <RunRetryDetails agentRouteId={agentId} run={{ status: "scheduled_retry", scheduledRetryReason: "ai_connection_pool_wait", scheduledRetryAt: new Date(Date.now() + 60_000).toISOString(), scheduledRetryAttempt: 1, retryOfRunId: "run-pool-wait" }} />}</div>;
+}
+function PoolSurfaces({ scenario = "overview" }: { scenario?: Scenario }) {
+ const [client] = useState(() => {
+ const query = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ query.setQueryData(["ai-connections", companyId, agentId], { ...accounts, pools: scenario === "unavailable" ? [] : accounts.pools });
+ query.setQueryData(queryKeys.instance.settings, {});
+ return query;
+ });
+ const [binding, setBinding] = useState<AiRuntimeConnectionBinding | undefined>(scenario === "adoption" ? undefined : { mode: "router", connectionId: poolId });
+ const overview = scenario === "overview";
+ return <QueryClientProvider client={client}><main className="mx-auto max-w-3xl space-y-6 p-6">
+ {scenario !== "adoption" && <header className="space-y-2"><h1 className="text-xl font-semibold">Experimental connection pools</h1><a className="text-sm text-primary underline" href="http://127.0.0.1:6010/?path=/story/plugins-connection-pools--in-connectors">Connection pool connector in Cloud Storybook</a></header>}
+ {(overview || ["selector", "legacy", "adoption", "unavailable", "read-only"].includes(scenario)) && <section className="space-y-2"><h2 className="text-sm font-semibold">Agent connection</h2><AiConnectionField companyId={companyId} agentId={agentId} agentName={agent.name}
+ adapterType={scenario === "legacy" ? "claude_local" : "codex_local"} routerAdapterType={scenario === "legacy" ? "claude_local" : "paperclip_runner"}
+ value={binding} onChange={setBinding} legacy={scenario === "adoption"} readOnly={scenario === "read-only"} /></section>}
+ {(overview || ["models", "effort", "mobile", "claude-model"].includes(scenario)) && <section className="space-y-2"><h2 className="text-sm font-semibold">Composer model and effort</h2><PoolComposer scenario={scenario} /></section>}
+ {(overview || scenario === "quota" || scenario === "checking") && <section><h2 className="text-sm font-semibold">Usage recovery</h2><PoolWait checking={scenario === "checking"} /></section>}
+ {(overview || ["run-codex", "run-claude", "fallback", "retry"].includes(scenario)) && <section className="space-y-2"><h2 className="text-sm font-semibold">Run account and runtime</h2><PoolRun scenario={scenario === "overview" ? "fallback" : scenario} /></section>}
+ </main></QueryClientProvider>;
+}
+const meta = { title: "AI Connections/Connection pools", component: PoolSurfaces, parameters: { layout: "fullscreen", docs: { description: { component: "All user-facing Core additions for the private connection-pool plugin. These stories mount the production selector, composer, quota banners, and run details/retry metadata. Routing requires manual operator configuration; there is no settings toggle. Accounts are fixtures; no live provider calls or instance mutations occur." } } }, render: args => <PoolSurfaces key={args.scenario} {...args} /> } satisfies Meta<typeof PoolSurfaces>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+export const AllCoreSurfaces: Story = { args: { scenario: "overview" } };
+export const ConnectionSelector: Story = { args: { scenario: "selector" }, play: async ({ canvasElement }) => { const c = within(canvasElement); await userEvent.selectOptions(c.getByRole("combobox", { name: /^AI connection/ }), ""); await expect(c.getByText("Responsible user’s connection", { exact: false })).toBeVisible(); await userEvent.selectOptions(c.getByRole("combobox", { name: /^AI connection/ }), poolId); await expect(c.getByText(/New tasks rotate/)).toBeVisible(); } };
+export const CompatibleLegacyHarness: Story = { args: { scenario: "legacy" } };
+export const ExistingSessionAdoption: Story = { args: { scenario: "adoption" }, play: async ({ canvasElement }) => { const c = within(canvasElement); await userEvent.click(c.getByRole("button", { name: "Choose a managed connection" })); await userEvent.selectOptions(c.getByRole("combobox", { name: /^AI connection/ }), poolId); await expect(await within(canvasElement.ownerDocument.body).findByRole("dialog", { name: "Use Research accounts?" })).toHaveTextContent("Reset existing sessions that use an account outside this pool."); } };
+export const PoolUnavailable: Story = { args: { scenario: "unavailable" } };
+export const ReadOnlySelection: Story = { args: { scenario: "read-only" } };
+export const ComposerModelsFromBothProviders: Story = { args: { scenario: "models" } };
+export const ComposerCodexEffort: Story = { args: { scenario: "effort" } };
+export const ComposerClaudeModelOnly: Story = { args: { scenario: "claude-model" } };
+export const MobileComposer: Story = { args: { scenario: "mobile" } };
+export const PoolExhaustedBannerAndStrip: Story = { args: { scenario: "quota" } };
+export const UsageRecheckInProgress: Story = { args: { scenario: "checking" } };
+export const PinnedCodexRun: Story = { args: { scenario: "run-codex" } };
+export const PinnedClaudeRun: Story = { args: { scenario: "run-claude" } };
+export const IndependentOverrideFallbackNotes: Story = { args: { scenario: "fallback" } };
+export const ScheduledQuotaRetry: Story = { args: { scenario: "retry" } };