diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index e700f79f562..41d7435d3a5 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 d2003e10805..25e05ab0581 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 00000000000..06f092c556f --- /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= \ +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 4072d63c423..88ec7ceed6e 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 00000000000..5f15b95940c --- /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 c5115c19742..8129db0a204 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 3a305202425..e411db27423 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 00000000000..524e432aa11 --- /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().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().notNull(), + member: jsonb("member").$type().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 9ca340d2240..6d3a9ddc29d 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>(), + 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 ce1ebff0787..874d13ebffb 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 ef5c5dc6f9b..947a67cbb55 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; + onResolveExternalObject?( params: ResolveExternalObjectParams, ): Promise; diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts index 788247f39ad..57f86281178 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 5476c10becb..9c08a45c42b 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 78d8308a297..0f0d4eb4cfd 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 b504a703628..cce6a3ae1a7 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 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(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 00000000000..9fbd89c385a --- /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; + +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(); + const grants = new Set(); + const connections = new Set(); + 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; +export type AiConnectionPoolConfig = z.infer; +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; notes: string[]; usage?: AiConnectionUsage }>; + now: string; +} +export type AiConnectionRouterResult = + | { kind: "selected"; memberId: string; skipped?: Record } + | { kind: "exhausted"; retryAt: string; skipped: Record } + | { kind: "unavailable"; skipped: Record }; +export interface AiConnectionPoolSaveInput { + companyId: string; + id?: string; + expectedRevision?: number; + config: AiConnectionPoolConfig; +} +export interface AiConnectionRouterSelection { + poolId: string; + memberId: string; + binding: AiConnectionBinding; + runtimeConfig: Record; + 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 | 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 59176427752..898a5f246e4 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 0970e05d064..4a050a35b0d 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 61a2b2b5bad..3e83f263130 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 457172b2fa2..9f6f23e1a3a 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 { } export type AgentRuntimeConfig = Record & { - 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 dc04bbabd7a..2e8d2d5c43e 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}; 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> } +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> } export type SelfServeMcpAuthMode = | "dcr" diff --git a/packages/shared/src/types/instance.ts b/packages/shared/src/types/instance.ts index 1bb6278d676..c9a6e61c67d 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 68662753a33..42643d3b00e 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 9c2ec1d0611..9f023c2b598 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 6cf59f19f92..5e48887fe67 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();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 d4c2235af7f..90970097a17 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 043a048b1ea..3c3b46cc9bf 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 55a915a0694..00249771642 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 d4f28de63d0..8fb798e261e 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>; let db: ReturnType; @@ -67,7 +70,144 @@ function hired(response: request.Response) { return response.body.agent ?? response.body; } +async function poolFixture(f: Awaited>, 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 00000000000..b2e13a92e8a --- /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>; +let db: ReturnType; +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 => { + 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(() => {})); + 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 00000000000..81bed1e2c4c --- /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[0]; +type CompatibilityInput = Parameters[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, next: Partial = {}, compatibility: Partial = {}, 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; 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 bc41cd3181e..ee9a3e05a62 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 32ce6a2c01d..86ed463b3ce 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 729b5f4af40..9263c0ba753 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 d7107c260c8..c99839e4fab 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 b882b09baca..adaf1a97ce6 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 223ee6fb8bd..ac6b84eb68e 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 b0dd653959e..2100b357d9c 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 d6fda59345a..d29b0783231 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 11fdc1ab3c3..93ab497d325 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(); + 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, binding: AiConnectionBinding, environmentId: string | null | undefined, test: boolean, newAgent = false) { + async function validateManagedAgentBinding(req: Request, companyId: string, agentId: string, adapterType: string, config: Record, 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(); + let compatible = false; + for (const member of pool.members) { + let runtime: ReturnType; + 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; 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; - 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 335ed8067b5..adcb505e5a1 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 { + 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 (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 fc0224f1246..c403cef41f3 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, 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 : {}; + 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 93c437da8db..3640a90d4e7 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 00000000000..4208bcd775a --- /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(); +const usageInFlight = new Map>(); +const routedRuntimeKeys = new Set(["provider", "acpxAgent", "model", "modelReasoningEffort", "reasoningEffort", "effort", "variant"]); +export function applyAiConnectionRouterTaskSettings(config: Record, 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 = {}) { + 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 = { 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 = {}; + 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 | undefined; + pending = Promise.race([ + aiConnectionService(db).probeUsage(companyId, userId, member.binding.connectionId, member.binding.grantId).catch(() => undefined), + new Promise(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 | undefined; + try { + return await Promise.race([ + pending, + new Promise(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; 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 534f5cf023a..ea691f5f3db 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 | 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] = ""; + } + } + 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 00000000000..1b0c4fc5836 --- /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; + afterConfig: Record; +}; + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record : {}; +} + +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) => { + 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; + 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 a3d2bf640c5..7cfdbeb1551 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 d369ad33cc8..175a2228d89 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>; }) { - 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 2673e2b33c3..c434e7b60a2 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 689137d9d99..dec0d847cf7 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 f6186b718f7..9e8617e2fcd 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 | 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 1191d7afab3..18d85bdbd12 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 6ab86f7ee43..64c4c7f2db8 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 | 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 143275d0941..6549cf69e08 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 00000000000..e90135ce171 --- /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 { + 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 00000000000..a3b2b9a65e2 --- /dev/null +++ b/ui/public/brands/apps/connection-pool.svg @@ -0,0 +1 @@ + diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts index d1709a68007..7bd9cce9855 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( @@ -246,7 +247,7 @@ export const agentsApi = { type: string, data: { adapterConfig: Record; - aiConnection?: import("@paperclipai/shared").AiConnectionBinding; + aiConnection?: import("@paperclipai/shared").AiRuntimeConnectionBinding; agentId?: string; testCredentials?: Record; 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 00000000000..20ffd060246 --- /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; +export const aiConnectionPoolsApi = { + list: (companyId: string) => api.get(`/companies/${companyId}/ai-connection-pools`), + save: (companyId: string, body: { pluginKey: string; id?: string; expectedRevision?: number; config: AiConnectionPoolConfig }) => api.post(`/companies/${companyId}/ai-connection-pools`, body), + inspect: (companyId: string, id: string) => api.get(`/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 630db5ca156..6f655057762 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 | undefined)?.aiConnection ?? props.agent.runtimeConfig.aiConnection, ).data; if (props.compactTestFeedback) { @@ -1659,7 +1659,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) { )} {!isCreate && selectedCompanyId && | undefined)?.aiConnection ?? runtimeConfig.aiConnection).data} + routerAdapterType={adapterType} value={aiRuntimeConnectionBindingSchema.safeParse((overlay.runtime.runtimeConfig as Record | 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 5cbc65cdf86..a240268afaf 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 e3f657a44f4..5a2bac07a77 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) {