Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agents): let an agent run on its own Anthropic or OpenAI API key (#8698)

Wolf Mermelsteina2e7f31b2e73
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index bc32882712..b75f1e0e0e 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -83,6 +83,110 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "agent_api_keys": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_api_keys",
+ "crates/agent_runtime_protocol",
+ "crates/ai_billing",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/analytics_client",
+ "crates/attachment",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/cursor_api_key",
+ "crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
+ "crates/document_sub_type",
+ "crates/email",
+ "crates/email_api_client",
+ "crates/email_db_client",
+ "crates/email_utils",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/entity_registry/shared_entity_registry",
+ "crates/filter_ast",
+ "crates/folds/agent_fold",
+ "crates/frecency",
+ "crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/gmail_client",
+ "crates/google_token",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/initiative",
+ "crates/invite_email",
+ "crates/ip_extractor",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/maybe_send",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_databases",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/system_properties",
+ "crates/teams",
+ "crates/trigger_context",
+ "crates/unfurl",
+ "crates/workspace-hack"
+ ],
"agent_changes": [
"crates/activity",
"crates/agent",
@@ -448,6 +552,7 @@
"agent_harness": [
"crates/activity",
"crates/agent",
+ "crates/agent_api_keys",
"crates/agent_egress",
"crates/agent_harness",
"crates/agent_runtime_protocol",
@@ -591,6 +696,7 @@
"agent_harness_service": [
"crates/activity",
"crates/agent",
+ "crates/agent_api_keys",
"crates/agent_changes",
"crates/agent_code_mode",
"crates/agent_egress",
@@ -790,6 +896,7 @@
"agent_inmem": [
"crates/activity",
"crates/agent",
+ "crates/agent_api_keys",
"crates/agent_changes",
"crates/agent_code_mode",
"crates/agent_egress",
@@ -825,6 +932,7 @@
"crates/contacts",
"crates/cowlike",
"crates/crm",
+ "crates/cursor_api_key",
"crates/database_env_vars",
"crates/database_sql",
"crates/databases",
@@ -2131,6 +2239,7 @@
"authentication_service": [
"crates/activity",
"crates/agent",
+ "crates/agent_api_keys",
"crates/agent_runtime_protocol",
"crates/agent_session",
"crates/ai_billing",
diff --git a/.sqlx/query-34215e7aee9f8703e5f7654d001076e3bde7cbe17acd7c175d98625f9e263dfc.json b/.sqlx/query-34215e7aee9f8703e5f7654d001076e3bde7cbe17acd7c175d98625f9e263dfc.json
new file mode 100644
index 0000000000..f82995c140
--- /dev/null
+++ b/.sqlx/query-34215e7aee9f8703e5f7654d001076e3bde7cbe17acd7c175d98625f9e263dfc.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM agent_api_keys WHERE bot_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "34215e7aee9f8703e5f7654d001076e3bde7cbe17acd7c175d98625f9e263dfc"
+}
diff --git a/.sqlx/query-4d03597d9939bb3dd27ac4055490a0387962e7080372c95374ead72c625c7214.json b/.sqlx/query-4d03597d9939bb3dd27ac4055490a0387962e7080372c95374ead72c625c7214.json
new file mode 100644
index 0000000000..8e2d1bb49b
--- /dev/null
+++ b/.sqlx/query-4d03597d9939bb3dd27ac4055490a0387962e7080372c95374ead72c625c7214.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT provider, updated_at FROM agent_api_keys WHERE bot_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "provider",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "4d03597d9939bb3dd27ac4055490a0387962e7080372c95374ead72c625c7214"
+}
diff --git a/.sqlx/query-995474f84dd5262c37009ab55b6fc111af55f3f98ba4be3d2eecd7d7a565d469.json b/.sqlx/query-995474f84dd5262c37009ab55b6fc111af55f3f98ba4be3d2eecd7d7a565d469.json
new file mode 100644
index 0000000000..0351abdef0
--- /dev/null
+++ b/.sqlx/query-995474f84dd5262c37009ab55b6fc111af55f3f98ba4be3d2eecd7d7a565d469.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM team_user WHERE user_id = $1 AND team_id = $2) AS \"member!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "member!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "995474f84dd5262c37009ab55b6fc111af55f3f98ba4be3d2eecd7d7a565d469"
+}
diff --git a/.sqlx/query-bd37498ee33dd9810dae0c4b867993edf31e5fcbf1e369a43cab4feefc10fed1.json b/.sqlx/query-bd37498ee33dd9810dae0c4b867993edf31e5fcbf1e369a43cab4feefc10fed1.json
new file mode 100644
index 0000000000..aba4b77072
--- /dev/null
+++ b/.sqlx/query-bd37498ee33dd9810dae0c4b867993edf31e5fcbf1e369a43cab4feefc10fed1.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n agent_key.provider,\n agent_key.key_ciphertext,\n agent_key.encryption_version,\n agent_key.kms_key_id,\n bot.owner_user_id,\n bot.team_id,\n config.harness,\n config.default_model\n FROM agent_api_keys agent_key\n JOIN bots bot ON bot.id = agent_key.bot_id AND bot.deleted_at IS NULL\n JOIN agent_configs config ON config.bot_id = agent_key.bot_id\n WHERE agent_key.bot_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "provider",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "key_ciphertext",
+ "type_info": "Bytea"
+ },
+ {
+ "ordinal": 2,
+ "name": "encryption_version",
+ "type_info": "Int2"
+ },
+ {
+ "ordinal": 3,
+ "name": "kms_key_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 6,
+ "name": "harness",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "default_model",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "bd37498ee33dd9810dae0c4b867993edf31e5fcbf1e369a43cab4feefc10fed1"
+}
diff --git a/.sqlx/query-aa07da306b358f70b0ab59cfee0fa4b1abbf46fb7f17196c079bce976f470159.json b/.sqlx/query-bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3.json
similarity index 66%
rename from .sqlx/query-aa07da306b358f70b0ab59cfee0fa4b1abbf46fb7f17196c079bce976f470159.json
rename to .sqlx/query-bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3.json
index 9f634b564b..bdfeb6ebcc 100644
--- a/.sqlx/query-aa07da306b358f70b0ab59cfee0fa4b1abbf46fb7f17196c079bce976f470159.json
+++ b/.sqlx/query-bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n feature,\n user_id,\n entity,\n model,\n input_tokens,\n output_tokens,\n cache_read_input_tokens,\n cache_write_input_tokens,\n audio_seconds,\n price_per_million_in,\n price_per_million_out,\n price_per_million_cache_read,\n price_per_million_cache_write,\n price_per_audio_minute,\n total,\n created_at\n FROM ai_usage\n WHERE ($1::timestamptz IS NULL OR created_at >= $1)\n AND ($2::timestamptz IS NULL OR created_at < $2)\n AND (cardinality($3::text[]) = 0 OR user_id = ANY($3))\n AND (cardinality($4::text[]) = 0 OR feature = ANY($4))\n ORDER BY created_at DESC\n ",
+ "query": "\n SELECT\n feature,\n user_id,\n entity,\n agent_api_key_id,\n model,\n input_tokens,\n output_tokens,\n cache_read_input_tokens,\n cache_write_input_tokens,\n audio_seconds,\n price_per_million_in,\n price_per_million_out,\n price_per_million_cache_read,\n price_per_million_cache_write,\n price_per_audio_minute,\n total,\n created_at\n FROM ai_usage\n WHERE ($1::timestamptz IS NULL OR created_at >= $1)\n AND ($2::timestamptz IS NULL OR created_at < $2)\n AND (cardinality($3::text[]) = 0 OR user_id = ANY($3))\n AND (cardinality($4::text[]) = 0 OR feature = ANY($4))\n ORDER BY created_at DESC\n ",
"describe": {
"columns": [
{
@@ -20,66 +20,71 @@
},
{
"ordinal": 3,
+ "name": "agent_api_key_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
"name": "model",
"type_info": "Text"
},
{
- "ordinal": 4,
+ "ordinal": 5,
"name": "input_tokens",
"type_info": "Int8"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "output_tokens",
"type_info": "Int8"
},
{
- "ordinal": 6,
+ "ordinal": 7,
"name": "cache_read_input_tokens",
"type_info": "Int8"
},
{
- "ordinal": 7,
+ "ordinal": 8,
"name": "cache_write_input_tokens",
"type_info": "Int8"
},
{
- "ordinal": 8,
+ "ordinal": 9,
"name": "audio_seconds",
"type_info": "Float8"
},
{
- "ordinal": 9,
+ "ordinal": 10,
"name": "price_per_million_in",
"type_info": "Float4"
},
{
- "ordinal": 10,
+ "ordinal": 11,
"name": "price_per_million_out",
"type_info": "Float4"
},
{
- "ordinal": 11,
+ "ordinal": 12,
"name": "price_per_million_cache_read",
"type_info": "Float4"
},
{
- "ordinal": 12,
+ "ordinal": 13,
"name": "price_per_million_cache_write",
"type_info": "Float4"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "price_per_audio_minute",
"type_info": "Float4"
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "total",
"type_info": "Float4"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "created_at",
"type_info": "Timestamptz"
}
@@ -96,6 +101,7 @@
false,
false,
true,
+ true,
false,
false,
false,
@@ -111,5 +117,5 @@
false
]
},
- "hash": "aa07da306b358f70b0ab59cfee0fa4b1abbf46fb7f17196c079bce976f470159"
+ "hash": "bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3"
}
diff --git a/.sqlx/query-cc214d197e3aea78568b228f7163faaa6abe7534ed228068b5c3a159b25e6bf4.json b/.sqlx/query-cc214d197e3aea78568b228f7163faaa6abe7534ed228068b5c3a159b25e6bf4.json
new file mode 100644
index 0000000000..85a72b7bb4
--- /dev/null
+++ b/.sqlx/query-cc214d197e3aea78568b228f7163faaa6abe7534ed228068b5c3a159b25e6bf4.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_api_keys (\n bot_id, provider, key_ciphertext, encryption_version, kms_key_id, key_prefix\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (bot_id) DO UPDATE SET\n provider = EXCLUDED.provider,\n key_ciphertext = EXCLUDED.key_ciphertext,\n encryption_version = EXCLUDED.encryption_version,\n kms_key_id = EXCLUDED.kms_key_id,\n key_prefix = EXCLUDED.key_prefix,\n updated_at = NOW()\n RETURNING updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Bytea",
+ "Int2",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "cc214d197e3aea78568b228f7163faaa6abe7534ed228068b5c3a159b25e6bf4"
+}
diff --git a/.sqlx/query-a3e224b7264094b0b69a08e904af23acd93fd4c01be59324e197522238240d79.json b/.sqlx/query-da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b.json
similarity index 74%
rename from .sqlx/query-a3e224b7264094b0b69a08e904af23acd93fd4c01be59324e197522238240d79.json
rename to .sqlx/query-da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b.json
index 2ca844d16d..5229eb8109 100644
--- a/.sqlx/query-a3e224b7264094b0b69a08e904af23acd93fd4c01be59324e197522238240d79.json
+++ b/.sqlx/query-da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO ai_usage (\n id, feature, user_id, entity, model,\n input_tokens, output_tokens,\n cache_read_input_tokens, cache_write_input_tokens, audio_seconds,\n price_per_million_in, price_per_million_out,\n price_per_million_cache_read, price_per_million_cache_write,\n price_per_audio_minute, total,\n count_usage\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)\n ",
+ "query": "\n INSERT INTO ai_usage (\n id, feature, user_id, entity, model,\n input_tokens, output_tokens,\n cache_read_input_tokens, cache_write_input_tokens, audio_seconds,\n price_per_million_in, price_per_million_out,\n price_per_million_cache_read, price_per_million_cache_write,\n price_per_audio_minute, total,\n count_usage, agent_api_key_id\n )\n VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18\n )\n ",
"describe": {
"columns": [],
"parameters": {
@@ -21,10 +21,11 @@
"Float4",
"Float4",
"Float4",
- "Bool"
+ "Bool",
+ "Uuid"
]
},
"nullable": []
},
- "hash": "a3e224b7264094b0b69a08e904af23acd93fd4c01be59324e197522238240d79"
+ "hash": "da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b"
}
diff --git a/.sqlx/query-eba1acf141a51c1e9ba85101b866d8207933d3e393bad2a7bad7b6bd453b7709.json b/.sqlx/query-eba1acf141a51c1e9ba85101b866d8207933d3e393bad2a7bad7b6bd453b7709.json
deleted file mode 100644
index a6f49cead7..0000000000
--- a/.sqlx/query-eba1acf141a51c1e9ba85101b866d8207933d3e393bad2a7bad7b6bd453b7709.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT record AS \"record: Json<ReviewRecord>\" FROM agent_session_review WHERE id = $1",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "record: Json<ReviewRecord>",
- "type_info": "Jsonb"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "eba1acf141a51c1e9ba85101b866d8207933d3e393bad2a7bad7b6bd453b7709"
-}
diff --git a/Cargo.lock b/Cargo.lock
index 42a0cdc3ee..bc0050225a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -251,6 +251,26 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "agent_api_keys"
+version = "0.1.0"
+dependencies = [
+ "ai_billing",
+ "anyhow",
+ "async-trait",
+ "chrono",
+ "cursor_api_key",
+ "lazy-regex",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tokio",
+ "workspace-hack",
+ "zeroize",
+]
+
[[package]]
name = "agent_changes"
version = "0.1.0"
@@ -399,6 +419,7 @@ version = "0.1.0"
dependencies = [
"agent",
"agent-client-protocol",
+ "agent_api_keys",
"agent_egress",
"agent_fold",
"agent_runtime_protocol",
@@ -482,6 +503,7 @@ dependencies = [
"activity",
"agent",
"agent-client-protocol",
+ "agent_api_keys",
"agent_changes",
"agent_code_mode",
"agent_egress",
@@ -659,6 +681,7 @@ version = "0.1.0"
dependencies = [
"agent",
"agent-client-protocol",
+ "agent_api_keys",
"agent_code_mode",
"agent_egress",
"agent_fold",
@@ -2084,6 +2107,7 @@ name = "authentication_service"
version = "0.1.0"
dependencies = [
"aes-gcm 0.10.3",
+ "agent_api_keys",
"ai_billing",
"ai_usage",
"analytics_client",
diff --git a/Cargo.toml b/Cargo.toml
index 7f73c2b0bd..3d425addd3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,6 +3,7 @@ resolver = "2"
members = [
"crates/access_requests",
+ "crates/agent_api_keys",
"crates/routines",
"crates/activity",
"crates/agent", "crates/agent_changes", "crates/agent_egress", "crates/folds/agent_fold", "crates/folds/claude_fold", "crates/folds/codex_fold",
diff --git a/apps/web/src/components/ui/components/ApiKeyInput.docs.tsx b/apps/web/src/components/ui/components/ApiKeyInput.docs.tsx
new file mode 100644
index 0000000000..9c261a5621
--- /dev/null
+++ b/apps/web/src/components/ui/components/ApiKeyInput.docs.tsx
@@ -0,0 +1,71 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { createSignal } from 'solid-js';
+import { ApiKeyInput } from './ApiKeyInput';
+import { Button } from './Button';
+
+// #region demo:new
+function NewKeyDemo() {
+ const [key, setKey] = createSignal('');
+
+ return (
+ <div class="flex w-full max-w-sm items-center gap-2">
+ <ApiKeyInput
+ prefix="sk-ant-"
+ value={key()}
+ onValueChange={setKey}
+ aria-label="Anthropic API key"
+ />
+ <Button variant="outline" size="sm" disabled={key().trim() === ''}>
+ Save
+ </Button>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:saved
+function SavedKeyDemo() {
+ const [key, setKey] = createSignal('');
+
+ return (
+ <div class="flex w-full max-w-sm items-center gap-2">
+ <ApiKeyInput
+ prefix="sk-ant-"
+ saved
+ value={key()}
+ onValueChange={setKey}
+ aria-label="Anthropic API key"
+ />
+ <Button variant="outline" size="sm" disabled={key().trim() === ''}>
+ Replace
+ </Button>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'ApiKeyInput',
+ category: 'Inputs',
+ description:
+ 'A field for pasting a secret API key: masked, never prefilled with a stored key, and kept out of autofill, spellcheck and session replay.',
+ status: 'stable',
+ exports: ['ApiKeyInput'],
+ import: "import { ApiKeyInput } from '@ui';",
+ demos: [
+ {
+ id: 'new',
+ title: 'No key yet',
+ description:
+ 'The placeholder shows the provider prefix so people paste the right kind of key.',
+ render: NewKeyDemo,
+ },
+ {
+ id: 'saved',
+ title: 'Key saved',
+ description:
+ 'A stored key is write-only, so `saved` shows it masked as `sk-ant-••••`; typing replaces it.',
+ render: SavedKeyDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/ApiKeyInput.test.tsx b/apps/web/src/components/ui/components/ApiKeyInput.test.tsx
new file mode 100644
index 0000000000..98245bcb1d
--- /dev/null
+++ b/apps/web/src/components/ui/components/ApiKeyInput.test.tsx
@@ -0,0 +1,49 @@
+/** @vitest-environment jsdom */
+
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ApiKeyInput } from './ApiKeyInput';
+
+afterEach(cleanup);
+
+describe('ApiKeyInput', () => {
+ it('masks a saved key and reports what is typed and Enter', () => {
+ const onValueChange = vi.fn();
+ const onSubmit = vi.fn();
+ const { getByLabelText } = render(() => (
+ <ApiKeyInput
+ prefix="sk-ant-"
+ saved
+ value=""
+ onValueChange={onValueChange}
+ onSubmit={onSubmit}
+ aria-label="Anthropic API key"
+ />
+ ));
+ const input = getByLabelText('Anthropic API key') as HTMLInputElement;
+
+ expect(input.type).toBe('password');
+ expect(input.placeholder).toBe('sk-ant-••••••••••••');
+ expect(input.autocomplete).toBe('new-password');
+ fireEvent.input(input, { target: { value: 'sk-ant-api03-new' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect(onValueChange).toHaveBeenCalledWith('sk-ant-api03-new');
+ expect(onSubmit).toHaveBeenCalledOnce();
+ });
+
+ it('shows the provider prefix before a key is saved', () => {
+ const { getByLabelText } = render(() => (
+ <ApiKeyInput
+ prefix="sk-"
+ value=""
+ onValueChange={() => {}}
+ aria-label="OpenAI API key"
+ />
+ ));
+
+ expect(
+ (getByLabelText('OpenAI API key') as HTMLInputElement).placeholder
+ ).toBe('sk-…');
+ });
+});
diff --git a/apps/web/src/components/ui/components/ApiKeyInput.tsx b/apps/web/src/components/ui/components/ApiKeyInput.tsx
new file mode 100644
index 0000000000..5feabbd5fb
--- /dev/null
+++ b/apps/web/src/components/ui/components/ApiKeyInput.tsx
@@ -0,0 +1,68 @@
+import KeyIcon from '@phosphor/key.svg';
+import { splitProps } from 'solid-js';
+import { cn } from '../utils/classname';
+import type { InputSize } from './Input';
+import { InputGroup, type InputGroupInputProps } from './InputGroup';
+
+/** Stands in for a stored key, which is never readable again. */
+const MASK = '••••••••••••';
+
+export type ApiKeyInputProps = Omit<
+ InputGroupInputProps,
+ 'type' | 'value' | 'onInput' | 'placeholder'
+> & {
+ /** What the person has typed so far. */
+ value: string;
+ onValueChange: (value: string) => void;
+ /** The key's public prefix, such as `sk-ant-`, shown in the placeholder. */
+ prefix?: string;
+ /** A key is already stored: the empty field shows it masked (`sk-ant-••••`). */
+ saved?: boolean;
+ /** Enter, the field's natural submit. */
+ onSubmit?: () => void;
+ size?: InputSize;
+};
+
+/**
+ * A field for pasting a secret API key. It never shows a stored key, only a
+ * masked placeholder, and keeps what is typed out of autofill, spellcheck and
+ * session replay.
+ *
+ * @do Pair it with a Save button; `onSubmit` handles Enter.
+ * @dont Do not pass a stored key as `value`: keys are write-only.
+ */
+export function ApiKeyInput(props: ApiKeyInputProps) {
+ const [local, rest] = splitProps(props, [
+ 'value',
+ 'onValueChange',
+ 'prefix',
+ 'saved',
+ 'onSubmit',
+ 'size',
+ 'class',
+ 'onKeyDown',
+ ]);
+ const placeholder = () =>
+ local.saved ? `${local.prefix ?? ''}${MASK}` : `${local.prefix ?? ''}…`;
+ return (
+ <InputGroup size={local.size ?? 'md'} class={cn('min-w-0', local.class)}>
+ <InputGroup.Input
+ type="password"
+ autocomplete="new-password"
+ spellcheck={false}
+ class="ph-no-capture font-mono"
+ placeholder={placeholder()}
+ value={local.value}
+ onInput={(event) => local.onValueChange(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (typeof local.onKeyDown === 'function') local.onKeyDown(event);
+ if (event.key === 'Enter') local.onSubmit?.();
+ }}
+ {...rest}
+ />
+ <InputGroup.Addon align="inline-start">
+ <KeyIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ </InputGroup>
+ );
+}
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index a414fb68d3..c07d47a8ed 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -1,4 +1,6 @@
export { ActionDialogShell } from './components/ActionDialogShell';
+export type { ApiKeyInputProps } from './components/ApiKeyInput';
+export { ApiKeyInput } from './components/ApiKeyInput';
export type {
AvatarGroupProps,
AvatarGroupSize,
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsx
index 257f1fad75..c293cdbe10 100644
--- a/apps/web/src/features/settings/Agents.test.tsx
+++ b/apps/web/src/features/settings/Agents.test.tsx
@@ -98,6 +98,25 @@ vi.mock('@queries/agents/avatar', () => ({
useUploadAgentAvatarMutation: () => ({ mutateAsync: avatarMocks.upload }),
}));
+const apiKeyMocks = vi.hoisted(() => ({
+ query: {
+ isSuccess: true,
+ data: undefined as
+ | {
+ key?: { provider: string; updatedAt: string } | null;
+ planAllows: boolean;
+ }
+ | undefined,
+ },
+ save: vi.fn(),
+ remove: vi.fn(),
+}));
+vi.mock('@queries/agents/agent-api-key', () => ({
+ useAgentApiKeyQuery: () => apiKeyMocks.query,
+ saveAgentApiKey: apiKeyMocks.save,
+ removeAgentApiKey: apiKeyMocks.remove,
+}));
+
vi.mock('@queries/auth/cursor-api-key', () => ({
useCursorApiKeyStatusQuery: () => cursorMocks.status,
}));
@@ -285,6 +304,9 @@ beforeAll(() => {
beforeEach(() => {
avatarMocks.upload.mockReset();
+ apiKeyMocks.query.data = undefined;
+ apiKeyMocks.save.mockReset();
+ apiKeyMocks.remove.mockReset();
avatarMocks.upload.mockResolvedValue('https://static.example/avatar.png');
updateSearchParams({ createAgent: undefined });
setSearchParams.mockClear();
@@ -294,7 +316,7 @@ beforeEach(() => {
};
agentMocks.query.data = [];
agentMocks.query.isError = false;
- agentMocks.create.mockResolvedValue(undefined);
+ agentMocks.create.mockResolvedValue({ bot: { id: 'created-agent' } });
agentMocks.delete.mockResolvedValue(undefined);
agentMocks.update.mockResolvedValue(undefined);
agentMocks.currentUserId = 'macro|[email protected]';
@@ -1223,6 +1245,109 @@ describe('Agents', () => {
});
});
+ it("saves a new agent's API key after the agent, for its model's provider", async () => {
+ render(() => <Agents {...agentsPageProps} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Add agent' }));
+
+ const dialog = screen.getByRole('region', { name: /^(New|Edit) agent$/ });
+ fireEvent.input(within(dialog).getByLabelText('Name'), {
+ target: { value: 'Bug fixer' },
+ });
+ fireEvent.input(within(dialog).getByLabelText('Anthropic API key'), {
+ target: { value: 'sk-ant-api03-abc' },
+ });
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Create agent' })
+ );
+
+ await waitFor(() => {
+ expect(apiKeyMocks.save).toHaveBeenCalledWith(
+ 'created-agent',
+ 'sk-ant-api03-abc'
+ );
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+ });
+
+ it("removes an agent's saved API key, and locks the field on a free plan", async () => {
+ agentMocks.query.data = [
+ {
+ bot: {
+ id: 'agent-1',
+ kind: 'owned',
+ owner: { type: 'user', user_id: 'macro|[email protected]' },
+ name: 'Bug fixer',
+ handle: 'bug-fixer',
+ has_agent: true,
+ created_at: '2026-08-27T12:00:00Z',
+ updated_at: '2026-08-27T12:00:00Z',
+ },
+ instructions: 'Fix the root cause.',
+ harness: 'in-memory',
+ default_model: Model.sonnet55,
+ channel_scope: 'all',
+ channel_ids: [],
+ },
+ ];
+ apiKeyMocks.query.data = {
+ key: { provider: 'anthropic', updatedAt: '2026-10-20T12:00:00Z' },
+ planAllows: true,
+ };
+
+ render(() => <Agents {...agentsPageProps} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));
+ const dialog = screen.getByRole('region', { name: /^(New|Edit) agent$/ });
+ const field = within(dialog).getByLabelText(
+ 'Anthropic API key'
+ ) as HTMLInputElement;
+ expect(field.placeholder).toBe('sk-ant-••••••••••••');
+
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Remove' }));
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Save changes' })
+ );
+ await waitFor(() => {
+ expect(apiKeyMocks.remove).toHaveBeenCalledWith('agent-1');
+ });
+ });
+
+ it('locks the API key field when the plan does not include agent keys', () => {
+ apiKeyMocks.query.data = { key: null, planAllows: false };
+ agentMocks.query.data = [
+ {
+ bot: {
+ id: 'agent-1',
+ kind: 'owned',
+ owner: { type: 'user', user_id: 'macro|[email protected]' },
+ name: 'Bug fixer',
+ handle: 'bug-fixer',
+ has_agent: true,
+ created_at: '2026-08-27T12:00:00Z',
+ updated_at: '2026-08-27T12:00:00Z',
+ },
+ instructions: 'Fix the root cause.',
+ harness: 'in-memory',
+ default_model: Model.sonnet55,
+ channel_scope: 'all',
+ channel_ids: [],
+ },
+ ];
+
+ render(() => <Agents {...agentsPageProps} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));
+ const dialog = screen.getByRole('region', { name: /^(New|Edit) agent$/ });
+
+ expect(
+ (within(dialog).getByLabelText('Anthropic API key') as HTMLInputElement)
+ .disabled
+ ).toBe(true);
+ expect(
+ within(dialog).getByText(
+ 'Agent API keys are part of the Premium and Max plans.'
+ )
+ ).toBeTruthy();
+ });
+
it('offers Cursor and saves the model chosen from its dropdown', async () => {
cursorMocks.status.data = {
registered: true,
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index 73c616b282..6ea64ff4f1 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -25,6 +25,11 @@ import AgentIcon from '@phosphor/sparkle.svg';
import TerminalIcon from '@phosphor/terminal-window.svg';
import TrashIcon from '@phosphor/trash.svg';
import UploadIcon from '@phosphor/upload-simple.svg';
+import {
+ removeAgentApiKey,
+ saveAgentApiKey,
+ useAgentApiKeyQuery,
+} from '@queries/agents/agent-api-key';
import {
type AgentWithHarnessId,
type CreateAgentParams,
@@ -50,7 +55,7 @@ import {
import type { AgentMcpServer } from '@service-storage/generated/schemas/agentMcpServer';
import type { AgentMcpServers } from '@service-storage/generated/schemas/agentMcpServers';
import { useSearchParams } from '@solidjs/router';
-import { Avatar, Button, Dialog, Panel } from '@ui';
+import { ApiKeyInput, Avatar, Button, Dialog, Panel } from '@ui';
import { tourTarget } from '@ui/components/Tour';
import {
createMemo,
@@ -70,6 +75,11 @@ import { CodingPreferencesSetting } from './components/coding-preferences-settin
import { AgentInstructionsEditor } from './components/instructions-editor';
import { SettingsSelect } from './components/settings-select';
import { WhereItRunsOption } from './components/where-it-runs-option';
+import {
+ type ApiKeyProvider,
+ apiKeyProviderName,
+ apiKeyProviderOf,
+} from './core/agent-api-key';
import { PipedreamAppPicker } from './PipedreamAppPicker';
import {
ChoiceRow,
@@ -231,18 +241,18 @@ export function Agents(props: {
const createAgent = async (agent: CreateAgentParams) => {
try {
- await createAgentMutation.mutateAsync(agent);
+ const created = await createAgentMutation.mutateAsync(agent);
toast.success('Agent created');
- return true;
+ return created.bot.id;
} catch {
toast.failure('Failed to create agent');
- return false;
+ return undefined;
}
};
const updateAgent = async (agent: CreateAgentParams) => {
const current = editingAgent();
- if (!current) return false;
+ if (!current) return undefined;
try {
await updateAgentMutation.mutateAsync({
@@ -253,10 +263,10 @@ export function Agents(props: {
: {}),
});
toast.success('Agent updated');
- return true;
+ return current.bot.id;
} catch {
toast.failure('Failed to update agent');
- return false;
+ return undefined;
}
};
@@ -596,7 +606,8 @@ function AgentEditorPage(props: {
canMakePrivate: boolean;
pending: boolean;
onClose: () => void;
- onSave: (agent: CreateAgentParams) => Promise<boolean>;
+ /** Saves the agent, resolving to its id, or `undefined` when it failed. */
+ onSave: (agent: CreateAgentParams) => Promise<string | undefined>;
onDelete?: () => void;
}) {
const [name, setName] = createSignal(props.agent?.bot.name ?? '');
@@ -861,6 +872,89 @@ function AgentEditorPage(props: {
);
const modelField = () => <div class="max-w-[280px]">{modelPicker()}</div>;
+ // An agent that runs in Macro on an Anthropic or OpenAI model can run on
+ // its own API key instead of Macro usage. The key is write-only: a saved
+ // one shows masked, and is replaced by typing a new one.
+ const apiKey = useAgentApiKeyQuery(() => props.agent?.bot.id);
+ const [apiKeyDraft, setApiKeyDraft] = createSignal('');
+ const [removingApiKey, setRemovingApiKey] = createSignal(false);
+ const keyProvider = () =>
+ harnessId() === IN_MEMORY_HARNESS.id
+ ? apiKeyProviderOf(selectedDefaultModelId())
+ : undefined;
+ // A new agent has no id yet, so its query stays disabled; read the data
+ // only once it has loaded, or the editor would suspend on it.
+ const apiKeyData = () => (apiKey.isSuccess ? apiKey.data : undefined);
+ const savedApiKey = () =>
+ removingApiKey() ? undefined : (apiKeyData()?.key ?? undefined);
+ const apiKeyLocked = () => apiKeyData()?.planAllows === false;
+ const apiKeyHelp = (provider: ApiKeyProvider) => {
+ const saved = savedApiKey();
+ if (apiKeyLocked())
+ return saved
+ ? 'Agent API keys are part of the Premium and Max plans. This agent runs on Macro usage until you upgrade.'
+ : 'Agent API keys are part of the Premium and Max plans.';
+ if (saved && saved.provider !== provider.id)
+ return `The saved ${apiKeyProviderName(saved.provider)} key isn’t used with this model.`;
+ return 'Bill usage to your own API key.';
+ };
+ const apiKeyField = () => (
+ <Show when={keyProvider()}>
+ {(provider) => (
+ <div class="flex max-w-[420px] flex-col gap-1.5">
+ <span class="text-xs font-medium text-ink-muted">
+ {provider().name} API key
+ </span>
+ <div class="flex min-w-0 items-center gap-2">
+ <ApiKeyInput
+ aria-label={`${provider().name} API key`}
+ class="flex-1"
+ prefix={provider().prefix}
+ saved={savedApiKey()?.provider === provider().id}
+ disabled={busy() || apiKeyLocked()}
+ value={apiKeyDraft()}
+ onValueChange={setApiKeyDraft}
+ />
+ <Show when={savedApiKey()}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={busy()}
+ onClick={() => {
+ setApiKeyDraft('');
+ setRemovingApiKey(true);
+ }}
+ >
+ Remove
+ </Button>
+ </Show>
+ </div>
+ <p class="text-xs text-ink-extra-muted">{apiKeyHelp(provider())}</p>
+ </div>
+ )}
+ </Show>
+ );
+ // Saved after the agent, which a new agent needs an id from first.
+ const saveApiKey = async (agentId: string) => {
+ const draft = apiKeyDraft().trim();
+ try {
+ if (draft.length > 0 && keyProvider()) {
+ await saveAgentApiKey(agentId, draft);
+ } else if (removingApiKey()) {
+ await removeAgentApiKey(agentId);
+ }
+ } catch (error) {
+ toast.failure(
+ `The agent was saved, but not its API key: ${
+ error instanceof Error && error.message
+ ? error.message
+ : 'something went wrong'
+ }`
+ );
+ }
+ };
+
const close = () => {
if (!busy()) props.onClose();
};
@@ -933,7 +1027,9 @@ function AgentEditorPage(props: {
autoAcceptPermissions: autoAcceptPermissions(),
isCoding: isCoding(),
});
- if (saved) close();
+ if (!saved) return;
+ await saveApiKey(saved);
+ close();
};
return (
@@ -1085,7 +1181,10 @@ function AgentEditorPage(props: {
checked={harnessId() === IN_MEMORY_HARNESS.id}
onSelect={() => handleHarnessChange(IN_MEMORY_HARNESS.id)}
>
- {modelField()}
+ <div class="flex flex-col gap-3">
+ {modelField()}
+ {apiKeyField()}
+ </div>
</WhereItRunsOption>
<WhereItRunsOption
value="cursor"
@@ -1160,6 +1259,26 @@ function AgentEditorPage(props: {
</div>
</WhereItRunsOption>
</fieldset>
+ <Show when={!keyProvider() ? savedApiKey() : undefined}>
+ {(saved) => (
+ <div class="mt-3 flex items-center justify-between gap-3 text-xs text-ink-muted">
+ <span>
+ This agent has a saved{' '}
+ {apiKeyProviderName(saved().provider)} API key it
+ doesn’t use here.
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={busy()}
+ onClick={() => setRemovingApiKey(true)}
+ >
+ Remove key
+ </Button>
+ </div>
+ )}
+ </Show>
</AgentFormSection>
<AgentFormSection
diff --git a/apps/web/src/features/settings/CursorConnectPage.tsx b/apps/web/src/features/settings/CursorConnectPage.tsx
index b0e801f614..99d201c318 100644
--- a/apps/web/src/features/settings/CursorConnectPage.tsx
+++ b/apps/web/src/features/settings/CursorConnectPage.tsx
@@ -7,7 +7,7 @@ import {
useDisconnectCursorApiKey,
useSaveCursorApiKey,
} from '@queries/auth/cursor-api-key';
-import { Button, confirmDialog } from '@ui';
+import { ApiKeyInput, Button, confirmDialog } from '@ui';
import { createSignal, Show } from 'solid-js';
import cursorApiKeysScreenshot from './assets/cursor-api-keys.png';
import { CursorDefaultModel } from './components/cursor-default-model';
@@ -18,7 +18,7 @@ import {
} from './components/runtime-setup-steps';
import {
CURSOR_KEY_FORMAT_ERROR,
- CURSOR_KEY_PLACEHOLDER,
+ CURSOR_KEY_PREFIX,
isCursorApiKey,
} from './core/cursor-api-key';
import { SettingsPage, SettingsSurface } from './primitives';
@@ -147,23 +147,16 @@ export function CursorConnectPage(props: { onClose: () => void }) {
>
API key
</label>
- <SetupField>
- <input
- ref={focusOnMount}
- id="cursor-api-key"
- type="password"
- autocomplete="off"
- spellcheck={false}
- aria-describedby="cursor-api-key-help"
- class="ph-no-capture min-w-0 flex-1 bg-transparent font-mono text-sm text-ink outline-none"
- placeholder={CURSOR_KEY_PLACEHOLDER}
- value={apiKey()}
- disabled={saveKey.isPending}
- onInput={(event) =>
- setApiKey(event.currentTarget.value)
- }
- />
- </SetupField>
+ <ApiKeyInput
+ ref={focusOnMount}
+ id="cursor-api-key"
+ aria-describedby="cursor-api-key-help"
+ size="lg"
+ prefix={CURSOR_KEY_PREFIX}
+ value={apiKey()}
+ disabled={saveKey.isPending}
+ onValueChange={setApiKey}
+ />
<p
id="cursor-api-key-help"
class="text-xs text-ink-extra-muted"
diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsx
index 91fccc59ea..05081e7a66 100644
--- a/apps/web/src/features/settings/Harness.tsx
+++ b/apps/web/src/features/settings/Harness.tsx
@@ -17,14 +17,14 @@ import {
} from '@queries/harnesses/harnesses';
import type { Harness as RegisteredHarness } from '@service-storage/client';
import { useSearchParams } from '@solidjs/router';
-import { Button, confirmDialog, Dialog, Panel } from '@ui';
+import { ApiKeyInput, Button, confirmDialog, Dialog, Panel } from '@ui';
import { createSignal, For, onMount, Show } from 'solid-js';
import { CodexHarness } from './codex/views/CodexHarness';
import { CursorDefaultModel } from './components/cursor-default-model';
import { LocalRuntimeCard } from './components/local-runtime-card';
import {
CURSOR_KEY_FORMAT_ERROR,
- CURSOR_KEY_PLACEHOLDER,
+ CURSOR_KEY_PREFIX,
isCursorApiKey,
} from './core/cursor-api-key';
import { ConnectAction, HarnessIcon, StatusDot } from './integration-ui';
@@ -212,25 +212,19 @@ export function Harness(
API key
</label>
<div class="flex items-center gap-2 mobile:flex-col mobile:items-stretch">
- <input
+ <ApiKeyInput
id="cursor-harness-api-key"
- type="password"
- autocomplete="off"
- spellcheck={false}
- class="settings-input ph-no-capture min-w-0 flex-1"
- placeholder={CURSOR_KEY_PLACEHOLDER}
+ class="flex-1"
+ size="sm"
+ prefix={CURSOR_KEY_PREFIX}
value={cursorApiKey()}
- onInput={(event) =>
- setCursorApiKey(event.currentTarget.value)
+ onValueChange={setCursorApiKey}
+ onSubmit={() =>
+ fireAndForget(
+ handleSaveCursorApiKey(),
+ 'cursor-connect'
+ )
}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- fireAndForget(
- handleSaveCursorApiKey(),
- 'cursor-connect'
- );
- }
- }}
/>
<Button
type="button"
diff --git a/apps/web/src/features/settings/core/agent-api-key.test.ts b/apps/web/src/features/settings/core/agent-api-key.test.ts
new file mode 100644
index 0000000000..eead980779
--- /dev/null
+++ b/apps/web/src/features/settings/core/agent-api-key.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+import { apiKeyProviderOf } from './agent-api-key';
+
+describe('apiKeyProviderOf', () => {
+ it('names the provider whose key can pay for a routed model', () => {
+ expect(apiKeyProviderOf('anthropic/claude-sonnet-5-5')?.prefix).toBe(
+ 'sk-ant-'
+ );
+ expect(apiKeyProviderOf('openai/gpt-6-astra')?.name).toBe('OpenAI');
+ expect(apiKeyProviderOf('google/gemini-3.8-flash')).toBeUndefined();
+ expect(apiKeyProviderOf('auto')).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/settings/core/agent-api-key.ts b/apps/web/src/features/settings/core/agent-api-key.ts
new file mode 100644
index 0000000000..7d77ab06ac
--- /dev/null
+++ b/apps/web/src/features/settings/core/agent-api-key.ts
@@ -0,0 +1,24 @@
+import type { AgentApiKeyProvider } from '@service-auth/generated/schemas/agentApiKeyProvider';
+
+/** A provider an agent can bring its own key for. */
+export type ApiKeyProvider = {
+ id: AgentApiKeyProvider;
+ name: string;
+ /** The prefix every key the provider mints starts with. */
+ prefix: string;
+};
+
+const PROVIDERS: readonly ApiKeyProvider[] = [
+ { id: 'anthropic', name: 'Anthropic', prefix: 'sk-ant-' },
+ { id: 'openai', name: 'OpenAI', prefix: 'sk-' },
+];
+
+/** The provider whose key can pay for a routed `provider/model` id. */
+export function apiKeyProviderOf(model: string): ApiKeyProvider | undefined {
+ const routed = model.split('/', 1)[0];
+ return PROVIDERS.find((provider) => provider.id === routed);
+}
+
+export function apiKeyProviderName(provider: AgentApiKeyProvider): string {
+ return PROVIDERS.find(({ id }) => id === provider)?.name ?? provider;
+}
diff --git a/apps/web/src/features/settings/core/cursor-api-key.ts b/apps/web/src/features/settings/core/cursor-api-key.ts
index 8aee42704b..60579a8f2f 100644
--- a/apps/web/src/features/settings/core/cursor-api-key.ts
+++ b/apps/web/src/features/settings/core/cursor-api-key.ts
@@ -1,7 +1,8 @@
// Cursor now mints `grok_` keys; the `crsr_` keys minted before that still work.
const CURSOR_KEY_PREFIXES = ['grok_', 'crsr_'];
-export const CURSOR_KEY_PLACEHOLDER = `${CURSOR_KEY_PREFIXES[0]}…`;
+/** The prefix of the keys Cursor mints today. */
+export const CURSOR_KEY_PREFIX = CURSOR_KEY_PREFIXES[0];
export const CURSOR_KEY_FORMAT_ERROR = `Cursor API keys start with ${CURSOR_KEY_PREFIXES.join(' or ')}`;
diff --git a/apps/web/src/lib/queries/agents/agent-api-key.ts b/apps/web/src/lib/queries/agents/agent-api-key.ts
new file mode 100644
index 0000000000..2c66e0c0ea
--- /dev/null
+++ b/apps/web/src/lib/queries/agents/agent-api-key.ts
@@ -0,0 +1,40 @@
+import { throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import { authServiceClient } from '@service-auth/client';
+import type { AgentApiKey } from '@service-auth/generated/schemas/agentApiKey';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { agentKeys } from './keys';
+
+/**
+ * The agent's own API key, if it has one, and whether its owner's plan lets
+ * it run on one. The response never carries a key.
+ */
+export function useAgentApiKeyQuery(agentId: Accessor<string | undefined>) {
+ return useQuery(() => ({
+ queryKey: agentKeys.apiKey(agentId() ?? '').queryKey,
+ enabled: agentId() !== undefined,
+ queryFn: () =>
+ throwOnErr(() => authServiceClient.getAgentApiKey(agentId() ?? '')),
+ }));
+}
+
+function store(agentId: string, key: AgentApiKey) {
+ queryClient.setQueryData(agentKeys.apiKey(agentId).queryKey, key);
+}
+
+/** Stores the agent's key, for its model's provider, replacing any. */
+export async function saveAgentApiKey(agentId: string, apiKey: string) {
+ store(
+ agentId,
+ await throwOnErr(() => authServiceClient.putAgentApiKey(agentId, apiKey))
+ );
+}
+
+/** Forgets the agent's key. Does not revoke it at the provider. */
+export async function removeAgentApiKey(agentId: string) {
+ store(
+ agentId,
+ await throwOnErr(() => authServiceClient.deleteAgentApiKey(agentId))
+ );
+}
diff --git a/apps/web/src/lib/queries/agents/keys.ts b/apps/web/src/lib/queries/agents/keys.ts
index d113d77a49..6e38d7ef30 100644
--- a/apps/web/src/lib/queries/agents/keys.ts
+++ b/apps/web/src/lib/queries/agents/keys.ts
@@ -3,4 +3,5 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const agentKeys = createQueryKeys('agents', {
list: null,
codingPreferences: null,
+ apiKey: (agentId: string) => [agentId],
});
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index f382ccf482..ce526ad4c9 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -45,6 +45,7 @@ import type {
TrialEligibility,
UserQuota,
} from './generated/schemas';
+import type { AgentApiKey } from './generated/schemas/agentApiKey';
import type { AppleLoginRequest } from './generated/schemas/appleLoginRequest';
import type { CreatedTeamInviteLinkResponse } from './generated/schemas/createdTeamInviteLinkResponse';
import type { CreateGtmInviteLinkRequest } from './generated/schemas/createGtmInviteLinkRequest';
@@ -226,6 +227,12 @@ const cursorApiKeyErrorResponseHandler: ErrorResponseHandler<'CURSOR_API_KEY_ERR
};
};
+const agentApiKeyErrorResponseHandler: ErrorResponseHandler<'AGENT_API_KEY_ERROR'> =
+ async function handleAgentApiKeyErrorResponse(response) {
+ const { message } = await cursorApiKeyErrorResponseHandler(response);
+ return { code: 'AGENT_API_KEY_ERROR', message };
+ };
+
/**
* Errors a merge can end in beyond the shared GitHub ones: the user has no
* GitHub account linked, or GitHub declined the merge and said why.
@@ -911,6 +918,49 @@ export const authServiceClient = {
).map((result) => result);
},
+ /**
+ * The agent's own API key, if it has one, and whether its owner's plan
+ * lets it run on one. Never returns a key or any part of one.
+ */
+ async getAgentApiKey(agentId: string) {
+ return (
+ await fetchWithAuth<AgentApiKey, 'AGENT_API_KEY_ERROR'>(
+ `${authHost}/agents/${agentId}/api-key`,
+ {
+ method: 'GET',
+ errorResponseHandler: agentApiKeyErrorResponseHandler,
+ }
+ )
+ ).map((result) => result);
+ },
+
+ /** Stores the agent's own API key, for its model's provider, replacing any. */
+ async putAgentApiKey(agentId: string, apiKey: string) {
+ return (
+ await fetchWithAuth<AgentApiKey, 'AGENT_API_KEY_ERROR'>(
+ `${authHost}/agents/${agentId}/api-key`,
+ {
+ method: 'PUT',
+ body: JSON.stringify({ apiKey }),
+ errorResponseHandler: agentApiKeyErrorResponseHandler,
+ }
+ )
+ ).map((result) => result);
+ },
+
+ /** Forgets the agent's API key. Does not revoke it at the provider. */
+ async deleteAgentApiKey(agentId: string) {
+ return (
+ await fetchWithAuth<AgentApiKey, 'AGENT_API_KEY_ERROR'>(
+ `${authHost}/agents/${agentId}/api-key`,
+ {
+ method: 'DELETE',
+ errorResponseHandler: agentApiKeyErrorResponseHandler,
+ }
+ )
+ ).map((result) => result);
+ },
+
/**
* Stores a Cursor API key for the signed-in user, replacing any existing one.
*
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index b550134f49..205a42aed6 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type {
+ AgentApiKey,
AiBillingErrorBody,
AppleLoginRequest,
ChangePlanRequest,
@@ -76,6 +77,7 @@ import type {
PostGetNamesRequestBody,
ProfilePictures,
PublicGtmInviteLink,
+ PutAgentApiKeyRequest,
PutCursorApiKeyRequest,
PutCursorDefaultModelRequest,
PutProfilePictureParams,
@@ -112,6 +114,200 @@ import type {
UserTokensResponse,
} from './schemas';
+/**
+ * @summary The agent's API key, if it has one, and whether its plan allows one.
+ */
+export type getAgentApiKeyResponse200 = {
+ data: AgentApiKey;
+ status: 200;
+};
+
+export type getAgentApiKeyResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getAgentApiKeyResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type getAgentApiKeyResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type getAgentApiKeyResponseSuccess = getAgentApiKeyResponse200 & {
+ headers: Headers;
+};
+export type getAgentApiKeyResponseError = (
+ | getAgentApiKeyResponse401
+ | getAgentApiKeyResponse403
+ | getAgentApiKeyResponse404
+) & {
+ headers: Headers;
+};
+
+export type getAgentApiKeyResponse =
+ | getAgentApiKeyResponseSuccess
+ | getAgentApiKeyResponseError;
+
+export const getGetAgentApiKeyUrl = (agentId: string) => {
+ return `/agents/${agentId}/api-key`;
+};
+
+export const getAgentApiKey = async (
+ agentId: string,
+ options?: RequestInit
+): Promise<getAgentApiKeyResponse> => {
+ const res = await fetch(getGetAgentApiKeyUrl(agentId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAgentApiKeyResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAgentApiKeyResponse;
+};
+
+/**
+ * @summary Registers or replaces the agent's API key, for its model's provider.
+Only in-memory agents on an Anthropic or OpenAI model, on a paid plan.
+ */
+export type putAgentApiKeyResponse200 = {
+ data: AgentApiKey;
+ status: 200;
+};
+
+export type putAgentApiKeyResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type putAgentApiKeyResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type putAgentApiKeyResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type putAgentApiKeyResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type putAgentApiKeyResponseSuccess = putAgentApiKeyResponse200 & {
+ headers: Headers;
+};
+export type putAgentApiKeyResponseError = (
+ | putAgentApiKeyResponse400
+ | putAgentApiKeyResponse401
+ | putAgentApiKeyResponse403
+ | putAgentApiKeyResponse404
+) & {
+ headers: Headers;
+};
+
+export type putAgentApiKeyResponse =
+ | putAgentApiKeyResponseSuccess
+ | putAgentApiKeyResponseError;
+
+export const getPutAgentApiKeyUrl = (agentId: string) => {
+ return `/agents/${agentId}/api-key`;
+};
+
+export const putAgentApiKey = async (
+ agentId: string,
+ putAgentApiKeyRequest: PutAgentApiKeyRequest,
+ options?: RequestInit
+): Promise<putAgentApiKeyResponse> => {
+ const res = await fetch(getPutAgentApiKeyUrl(agentId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(putAgentApiKeyRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: putAgentApiKeyResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as putAgentApiKeyResponse;
+};
+
+/**
+ * @summary Forgets the agent's API key. Does not revoke it at the provider; succeeds
+when there was none.
+ */
+export type deleteAgentApiKeyResponse200 = {
+ data: AgentApiKey;
+ status: 200;
+};
+
+export type deleteAgentApiKeyResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type deleteAgentApiKeyResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type deleteAgentApiKeyResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type deleteAgentApiKeyResponseSuccess = deleteAgentApiKeyResponse200 & {
+ headers: Headers;
+};
+export type deleteAgentApiKeyResponseError = (
+ | deleteAgentApiKeyResponse401
+ | deleteAgentApiKeyResponse403
+ | deleteAgentApiKeyResponse404
+) & {
+ headers: Headers;
+};
+
+export type deleteAgentApiKeyResponse =
+ | deleteAgentApiKeyResponseSuccess
+ | deleteAgentApiKeyResponseError;
+
+export const getDeleteAgentApiKeyUrl = (agentId: string) => {
+ return `/agents/${agentId}/api-key`;
+};
+
+export const deleteAgentApiKey = async (
+ agentId: string,
+ options?: RequestInit
+): Promise<deleteAgentApiKeyResponse> => {
+ const res = await fetch(getDeleteAgentApiKeyUrl(agentId), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: deleteAgentApiKeyResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as deleteAgentApiKeyResponse;
+};
+
/**
* @summary Turn automatic credit reloads on with the given
thresholds, or off. Payer only. Enabling settles right away, so a balance
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKey.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKey.ts
new file mode 100644
index 0000000000..589eba0d61
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKey.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentApiKeyKey } from './agentApiKeyKey';
+
+/**
+ * An agent's API key, and whether its turns can run on it.
+ */
+export interface AgentApiKey {
+ key?: AgentApiKeyKey;
+ /** Whether the agent owner's plan includes API keys. A key saved before a
+downgrade is still listed, and removable, but unused. */
+ planAllows: boolean;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKeyKey.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKeyKey.ts
new file mode 100644
index 0000000000..412434a4aa
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKeyKey.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SavedAgentApiKey } from './savedAgentApiKey';
+
+export type AgentApiKeyKey = null | SavedAgentApiKey;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKeyProvider.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKeyProvider.ts
new file mode 100644
index 0000000000..b8451703ce
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/agentApiKeyProvider.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A provider an agent can bring its own key for.
+ */
+export type AgentApiKeyProvider =
+ (typeof AgentApiKeyProvider)[keyof typeof AgentApiKeyProvider];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentApiKeyProvider = {
+ anthropic: 'anthropic',
+ openai: 'openai',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index c682e2b41b..fb0075ab28 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -6,6 +6,9 @@
*/
export * from './aBGroup';
+export * from './agentApiKey';
+export * from './agentApiKeyKey';
+export * from './agentApiKeyProvider';
export * from './aiBillingErrorBody';
export * from './appleLoginRequest';
export * from './autoReloadDefaults';
@@ -175,6 +178,7 @@ export * from './postGetNamesRequestBody';
export * from './profilePictureQueryParams';
export * from './profilePictures';
export * from './publicGtmInviteLink';
+export * from './putAgentApiKeyRequest';
export * from './putCursorApiKeyRequest';
export * from './putCursorDefaultModelRequest';
export * from './putCursorDefaultModelRequestModelId';
@@ -185,6 +189,7 @@ export * from './putUserNameQueryParamsFirstName';
export * from './putUserNameQueryParamsLastName';
export * from './redeemGtmInviteLinkRequest';
export * from './resendFusionauthVerifyUserEmailRequest';
+export * from './savedAgentApiKey';
export * from './scheduledSeatPlan';
export * from './seatPlan';
export * from './sendInviteBody';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/putAgentApiKeyRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/putAgentApiKeyRequest.ts
new file mode 100644
index 0000000000..cceecb5085
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/putAgentApiKeyRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The key someone pasted.
+ */
+export interface PutAgentApiKeyRequest {
+ /** An Anthropic (`sk-ant-…`) or OpenAI (`sk-…`) key, for the provider of
+the agent's model. */
+ apiKey: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/savedAgentApiKey.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/savedAgentApiKey.ts
new file mode 100644
index 0000000000..1c7dd8d004
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/savedAgentApiKey.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentApiKeyProvider } from './agentApiKeyProvider';
+
+/**
+ * The agent's saved key. Never includes the key.
+ */
+export interface SavedAgentApiKey {
+ /** The provider the key is for. */
+ provider: AgentApiKeyProvider;
+ /** When the key was last replaced. */
+ updatedAt: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index ffbdbdbd24..b9147e1a21 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -10,6 +10,199 @@
"version": "0.1.0"
},
"paths": {
+ "/agents/{agent_id}/api-key": {
+ "get": {
+ "tags": ["crate::api::agent_api_keys"],
+ "summary": "The agent's API key, if it has one, and whether its plan allows one.",
+ "operationId": "get_agent_api_key",
+ "parameters": [
+ {
+ "name": "agent_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentApiKey"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["crate::api::agent_api_keys"],
+ "summary": "Registers or replaces the agent's API key, for its model's provider.\nOnly in-memory agents on an Anthropic or OpenAI model, on a paid plan.",
+ "operationId": "put_agent_api_key",
+ "parameters": [
+ {
+ "name": "agent_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PutAgentApiKeyRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentApiKey"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["crate::api::agent_api_keys"],
+ "summary": "Forgets the agent's API key. Does not revoke it at the provider; succeeds\nwhen there was none.",
+ "operationId": "delete_agent_api_key",
+ "parameters": [
+ {
+ "name": "agent_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentApiKey"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/ai-billing/auto-reload": {
"patch": {
"tags": ["ai_billing"],
@@ -5442,6 +5635,33 @@
"type": "string",
"enum": ["A", "B"]
},
+ "AgentApiKey": {
+ "type": "object",
+ "description": "An agent's API key, and whether its turns can run on it.",
+ "required": ["planAllows"],
+ "properties": {
+ "key": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SavedAgentApiKey",
+ "description": "The saved key, if any."
+ }
+ ]
+ },
+ "planAllows": {
+ "type": "boolean",
+ "description": "Whether the agent owner's plan includes API keys. A key saved before a\ndowngrade is still listed, and removable, but unused."
+ }
+ }
+ },
+ "AgentApiKeyProvider": {
+ "type": "string",
+ "description": "A provider an agent can bring its own key for.",
+ "enum": ["anthropic", "openai"]
+ },
"AiBillingErrorBody": {
"type": "object",
"description": "Error response body.",
@@ -7269,6 +7489,17 @@
}
}
},
+ "PutAgentApiKeyRequest": {
+ "type": "object",
+ "description": "The key someone pasted.",
+ "required": ["apiKey"],
+ "properties": {
+ "apiKey": {
+ "type": "string",
+ "description": "An Anthropic (`sk-ant-…`) or OpenAI (`sk-…`) key, for the provider of\nthe agent's model."
+ }
+ }
+ },
"PutCursorApiKeyRequest": {
"type": "object",
"description": "The key the user pasted.",
@@ -7324,6 +7555,22 @@
}
}
},
+ "SavedAgentApiKey": {
+ "type": "object",
+ "description": "The agent's saved key. Never includes the key.",
+ "required": ["provider", "updatedAt"],
+ "properties": {
+ "provider": {
+ "$ref": "#/components/schemas/AgentApiKeyProvider",
+ "description": "The provider the key is for."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the key was last replaced."
+ }
+ }
+ },
"ScheduledSeatPlan": {
"type": "object",
"description": "A seat's future plan in the subscription's currently attached schedule.",
diff --git a/crates/agent/AGENTS.md b/crates/agent/AGENTS.md
index 6db01f4e9b..062b4297cc 100644
--- a/crates/agent/AGENTS.md
+++ b/crates/agent/AGENTS.md
@@ -55,6 +55,9 @@ and usage metering.
- `rig-core`/`rig-agent` are pinned exact versions (not workspace deps);
bump both together and check `test-utils` feature compatibility.
+- `AgentLoop::with_provider_api_key` rekeys only the loop's own model calls
+ (native Anthropic/OpenAI); call it after `with_model`. Tools and
+ `complete*` still use the deployment's keys.
## Related
diff --git a/crates/agent/src/agent_loop.rs b/crates/agent/src/agent_loop.rs
index 74e256644a..5c96c1d106 100644
--- a/crates/agent/src/agent_loop.rs
+++ b/crates/agent/src/agent_loop.rs
@@ -2,7 +2,9 @@
use crate::error::AgentError;
use crate::hook::{BridgeInputs, RegisterFn, ToolLoads, ToolRouter, UserToolFinisher};
use crate::model::metering::MeteringContext;
+use crate::model::metering_http::MeteredHttpClient;
use crate::model::router::{ModelRouter, ProviderAgent};
+use crate::model::types::Model;
use crate::model::{ModelSpeed, PredefinedModel, ReasoningEffort};
use crate::stream::ChatCompletionStream;
use crate::telemetry::GenAiContext;
@@ -115,6 +117,9 @@ pub struct AgentLoop {
/// Whether this loop enriches the runtime's GenAI spans (see
/// [`Self::with_genai_telemetry`]).
genai_telemetry: bool,
+ /// The router this loop's model calls use instead of the shared one, when
+ /// a caller-supplied key pays for them (see [`Self::with_provider_api_key`]).
+ router: Option<ModelRouter<MeteredHttpClient>>,
}
impl AgentLoop {
@@ -138,9 +143,26 @@ impl AgentLoop {
conversation_id: None,
agent_name: None,
genai_telemetry: true,
+ router: None,
}
}
+ /// Run the model's calls on `api_key` instead of the deployment's key for
+ /// its provider. Call after [`Self::with_model`]: the key is for the
+ /// selected model's provider, which must be native Anthropic or OpenAI.
+ ///
+ /// Fails rather than falling back when the model does not route, since a
+ /// fallback would run on the deployment's key while the usage is recorded
+ /// as the caller's. Only the loop's own model calls use the key; tools
+ /// that call models themselves still use the deployment's keys.
+ pub fn with_provider_api_key(mut self, api_key: &str) -> Result<Self, AgentError> {
+ let provider = Model::try_from(self.model.as_str())?.provider().to_owned();
+ let router = ModelRouter::shared()?.with_provider_api_key(&provider, api_key)?;
+ router.route(&self.model)?;
+ self.router = Some(router);
+ Ok(self)
+ }
+
/// Select a supported inference speed without changing the model or effort.
pub fn with_speed(mut self, speed: ModelSpeed) -> Result<Self, AgentError> {
if !speed.supported(&self.model) {
@@ -255,9 +277,11 @@ impl AgentLoop {
system_prompt,
usage_ctx,
|handle, prompt, tool_search, max_turns, max_tokens, telemetry| {
- let routed = ModelRouter::shared()
- .expect("failed to initialize model router")
- .route_or_default(&self.model);
+ let router = match &self.router {
+ Some(router) => router,
+ None => ModelRouter::shared().expect("failed to initialize model router"),
+ };
+ let routed = router.route_or_default(&self.model);
telemetry.set_model(routed.provider(), routed.model_name());
routed.into_agent(
self.reasoning_effort,
diff --git a/crates/agent/src/model/router.rs b/crates/agent/src/model/router.rs
index 390d5615ab..1831061db1 100644
--- a/crates/agent/src/model/router.rs
+++ b/crates/agent/src/model/router.rs
@@ -483,6 +483,50 @@ impl<H: HttpClientExt + Clone + 'static> ModelRouter<H> {
}
impl ModelRouter<MeteredHttpClient> {
+ /// This router with `provider`'s client authenticating with `api_key`
+ /// instead of the deployment's key, for a turn an agent's own key pays for.
+ ///
+ /// Only the native Anthropic and OpenAI clients can be rekeyed; any other
+ /// provider is [`AgentError::UnknownModel`]. The rebuilt client keeps its
+ /// own plain copy of the key as a header value, so drop the router with
+ /// the turn that needed it.
+ pub fn with_provider_api_key(&self, provider: &str, api_key: &str) -> Result<Self, AgentError> {
+ let http = ReqwestClient::builder()
+ .retry(reqwest::retry::never())
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .map_err(|error| rig_core::http_client::Error::Instance(Box::new(error)))?;
+ let mut router = self.clone();
+ match provider {
+ ANTHROPIC_PROVIDER => {
+ router.anthropic = Arc::new(
+ anthropic::Client::builder()
+ .api_key(api_key)
+ .http_client(AnthropicPromptLayout::new(MeteredHttpClient::new(
+ http,
+ ANTHROPIC_PROVIDER,
+ WireProtocol::Anthropic,
+ )))
+ .build()?,
+ );
+ }
+ OPENAI_PROVIDER => {
+ router.openai = Arc::new(
+ openai::Client::builder()
+ .api_key(api_key)
+ .http_client(MeteredHttpClient::new(
+ http,
+ OPENAI_PROVIDER,
+ WireProtocol::Responses,
+ ))
+ .build()?,
+ );
+ }
+ other => return Err(AgentError::UnknownModel(other.to_owned())),
+ }
+ Ok(router)
+ }
+
/// Register an OpenAI-compatible Chat Completions provider from a base URL
/// and key.
///
diff --git a/crates/agent_api_keys/AGENTS.md b/crates/agent_api_keys/AGENTS.md
new file mode 100644
index 0000000000..617a3a6c1f
--- /dev/null
+++ b/crates/agent_api_keys/AGENTS.md
@@ -0,0 +1,53 @@
+# agent_api_keys
+
+## What it is
+
+Part of agents: an agent's own Anthropic or OpenAI API key. An in-memory
+agent on an Anthropic or OpenAI model can have one; while it fits, every turn
+of the agent runs on it instead of Macro's allowance. See the crate doc in
+`src/lib.rs`.
+
+## Start here
+
+- `src/domain/service.rs`: the policy — which agents take a key, the paid-plan
+ check on save and on every turn, and `AgentKeys` for the chat runtime.
+- `src/domain/models.rs`: `ModelProvider`, `ProviderApiKey` (prefix rules),
+ `KeyedAgent` (the agent a caller authorized).
+- `src/outbound/pg.rs`: `agent_api_keys`, joined to `bots` and
+ `agent_configs` so a turn sees the agent as configured now.
+- `src/outbound/plans.rs`: `KeyPlans` over ai_billing's entitlements.
+
+## Scope
+
+- Owns: `agent_api_keys`.
+- Not here: who may change an agent → `crates/bots` (`BotService`); routing a
+ turn's model calls on a key → `crates/agent` (`AgentLoop::with_provider_api_key`);
+ deciding a turn runs on one → `crates/agent_inmem`.
+
+## Boundaries
+
+- Depends on: `cursor_api_key` (the `KmsCiphertexts` seam and its CMK),
+ `ai_billing` (plans).
+- Used by: `authentication_service` (save/remove routes, encrypts),
+ `agent_harness_service` (decrypt-only, for turns).
+
+## Checks
+
+- `cargo test -p agent_api_keys` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Never cache a decrypted key or a plan answer across turns: `usable_key` is
+ called per turn.
+- A key counts only while the agent is in-memory, its model's provider is the
+ key's, and its owner's plan includes keys. Otherwise the agent runs on Macro
+ usage and the key stays stored (shown and removable).
+- Prefixes are enforced twice: `ProviderApiKey::parse` and the
+ `agent_api_keys_key_prefix` check. Change both together.
+- Bots are soft-deleted, so the `ON DELETE CASCADE` rarely fires; `stored`
+ ignores deleted agents.
+- Deleting a key does not revoke it at the provider.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`, `.agents/rules/rust/db.md`
diff --git a/crates/agent_api_keys/CLAUDE.md b/crates/agent_api_keys/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_api_keys/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_api_keys/Cargo.toml b/crates/agent_api_keys/Cargo.toml
new file mode 100644
index 0000000000..2357166be3
--- /dev/null
+++ b/crates/agent_api_keys/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+edition = "2024"
+name = "agent_api_keys"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+ai_billing = { path = "../ai_billing" }
+anyhow = { workspace = true }
+async-trait = { workspace = true }
+chrono = { workspace = true }
+cursor_api_key = { path = "../cursor_api_key" }
+lazy-regex = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+zeroize = { workspace = true }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/crates/agent_api_keys/src/domain.rs b/crates/agent_api_keys/src/domain.rs
new file mode 100644
index 0000000000..47c43c670d
--- /dev/null
+++ b/crates/agent_api_keys/src/domain.rs
@@ -0,0 +1,7 @@
+mod models;
+mod ports;
+mod service;
+
+pub use models::*;
+pub use ports::*;
+pub use service::*;
diff --git a/crates/agent_api_keys/src/domain/models.rs b/crates/agent_api_keys/src/domain/models.rs
new file mode 100644
index 0000000000..007ffd2bba
--- /dev/null
+++ b/crates/agent_api_keys/src/domain/models.rs
@@ -0,0 +1,259 @@
+#[cfg(test)]
+mod test;
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use zeroize::Zeroizing;
+
+/// A model provider an agent can bring its own key for.
+///
+/// The string form is both the `agent_api_keys.provider` value and the
+/// provider segment of a routed model id (`anthropic/claude-opus-5-5`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ModelProvider {
+ /// Anthropic's Messages API.
+ Anthropic,
+ /// OpenAI's Responses API.
+ OpenAi,
+}
+
+impl ModelProvider {
+ /// Every provider a key can be registered for.
+ pub const ALL: [Self; 2] = [Self::Anthropic, Self::OpenAi];
+
+ /// The stored and routed name.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Anthropic => "anthropic",
+ Self::OpenAi => "openai",
+ }
+ }
+
+ /// The provider named `value`, if it is one.
+ #[must_use]
+ pub fn parse(value: &str) -> Option<Self> {
+ Self::ALL
+ .into_iter()
+ .find(|provider| provider.as_str() == value)
+ }
+
+ /// The provider serving a routed `provider/model` id, if an agent key
+ /// can pay for it.
+ #[must_use]
+ pub fn of_model(model: &str) -> Option<Self> {
+ model
+ .split_once('/')
+ .and_then(|(provider, _)| Self::parse(provider))
+ }
+
+ /// The provider's name as people know it.
+ #[must_use]
+ pub const fn display_name(self) -> &'static str {
+ match self {
+ Self::Anthropic => "Anthropic",
+ Self::OpenAi => "OpenAI",
+ }
+ }
+
+ /// The prefix every key this provider mints starts with. The table's
+ /// `agent_api_keys_key_prefix` check names the same values.
+ const fn key_prefix(self) -> &'static str {
+ match self {
+ Self::Anthropic => "sk-ant-",
+ Self::OpenAi => "sk-",
+ }
+ }
+}
+
+/// An agent's provider API key in plaintext.
+///
+/// Redacts its `Debug` and zeroizes on drop, like `CursorApiKey`: a decrypted
+/// key becomes a request header and is dropped with the turn that used it.
+pub struct ProviderApiKey {
+ provider: ModelProvider,
+ key: Zeroizing<String>,
+}
+
+impl ProviderApiKey {
+ /// Accept a key someone pasted for `provider`, checking its shape.
+ ///
+ /// Surrounding whitespace and quotes are stripped rather than rejected,
+ /// since they are what a paste most often adds. Shape only: this cannot
+ /// tell a live key from random characters behind the right prefix.
+ pub fn parse(provider: ModelProvider, supplied: &str) -> Result<Self, MalformedProviderApiKey> {
+ let trimmed = supplied
+ .trim()
+ .trim_matches(|character| character == '"' || character == '\'');
+ // OpenAI's `sk-` also prefixes Anthropic's `sk-ant-`, so an OpenAI
+ // key must not be an Anthropic one. The length cap keeps a stray
+ // paste a 400 rather than a KMS failure.
+ let well_formed = match provider {
+ ModelProvider::Anthropic => {
+ lazy_regex::regex_is_match!(r"\Ask-ant-[A-Za-z0-9_-]{1,500}\z", trimmed)
+ }
+ ModelProvider::OpenAi => {
+ lazy_regex::regex_is_match!(r"\Ask-[A-Za-z0-9_-]{1,500}\z", trimmed)
+ && !lazy_regex::regex_is_match!(r"\Ask-ant-", trimmed)
+ }
+ };
+ if !well_formed {
+ return Err(MalformedProviderApiKey);
+ }
+ Ok(Self {
+ provider,
+ key: Zeroizing::new(trimmed.to_owned()),
+ })
+ }
+
+ /// The provider the key authenticates with.
+ #[must_use]
+ pub fn provider(&self) -> ModelProvider {
+ self.provider
+ }
+
+ /// The public prefix stored beside the ciphertext.
+ #[must_use]
+ pub fn prefix(&self) -> &'static str {
+ self.provider.key_prefix()
+ }
+
+ /// The plaintext key. Only for the client that authenticates with it —
+ /// never for a log, a span field, an error, or an API response.
+ #[must_use]
+ pub fn expose(&self) -> &str {
+ &self.key
+ }
+}
+
+impl std::fmt::Debug for ProviderApiKey {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ formatter,
+ "ProviderApiKey({}, redacted)",
+ self.provider.as_str()
+ )
+ }
+}
+
+/// A supplied string that is not a key for the provider it was given for.
+/// Carries nothing: the rejected value is a credential.
+#[derive(Debug, thiserror::Error)]
+#[error("value does not look like an API key for this provider")]
+pub struct MalformedProviderApiKey;
+
+/// An encrypted key, as the row stores it.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct EncryptedProviderApiKey {
+ /// The KMS ciphertext blob.
+ pub key_ciphertext: Vec<u8>,
+ /// The scheme that produced the ciphertext.
+ pub encryption_version: i16,
+ /// The KMS key that encrypted it.
+ pub kms_key_id: String,
+}
+
+/// Who an agent belongs to, and so whose plan its key needs.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum AgentOwner {
+ /// A person's own agent.
+ User(MacroUserIdStr<'static>),
+ /// A team's agent.
+ Team(Uuid),
+}
+
+/// The agent a key is for, as its caller already authorized it.
+#[derive(Clone, Debug)]
+pub struct KeyedAgent {
+ /// The agent's bot id.
+ pub bot_id: Uuid,
+ /// Who owns the agent.
+ pub owner: AgentOwner,
+ /// The harness the agent runs on.
+ pub harness: String,
+ /// The agent's model, a routed `provider/model` id.
+ pub model: String,
+}
+
+impl KeyedAgent {
+ /// The provider whose key this agent can run on: only in-memory agents
+ /// on an Anthropic or OpenAI model have one.
+ #[must_use]
+ pub fn key_provider(&self) -> Option<ModelProvider> {
+ runs_in_memory(&self.harness)
+ .then(|| ModelProvider::of_model(&self.model))
+ .flatten()
+ }
+}
+
+/// Whether `harness` is Macro's in-memory runtime, the only one that runs
+/// model calls on an agent's key.
+#[must_use]
+pub fn runs_in_memory(harness: &str) -> bool {
+ matches!(harness, "in-memory" | "macro-inmem")
+}
+
+/// That an agent has a key. Never carries the key.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct AgentKeyStatus {
+ /// The provider the key is for.
+ pub provider: ModelProvider,
+ /// When the key was last replaced.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// An agent's key, and whether its turns can run on it.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct AgentKeyView {
+ /// The stored key, if any.
+ pub key: Option<AgentKeyStatus>,
+ /// Whether the agent's owner's plan includes keys. A key saved before a
+ /// downgrade is still shown (and removable) but unused.
+ pub plan_allows: bool,
+}
+
+/// A stored key with the agent facts that decide whether it is usable.
+#[derive(Clone, Debug)]
+pub struct StoredAgentKey {
+ /// The agent, as it is configured now.
+ pub agent: KeyedAgent,
+ /// The provider the key is for.
+ pub provider: ModelProvider,
+ /// The ciphertext.
+ pub encrypted: EncryptedProviderApiKey,
+}
+
+/// An agent's key a turn may run on, decrypted for that turn.
+#[derive(Debug)]
+pub struct UsableAgentKey {
+ /// The agent's bot id, which usage on the key references.
+ pub bot_id: Uuid,
+ /// The key.
+ pub key: ProviderApiKey,
+}
+
+/// Why an agent key operation failed.
+#[derive(Debug, thiserror::Error)]
+pub enum AgentKeyError {
+ /// The supplied value is not a key for the provider.
+ #[error("value does not look like an API key for this provider")]
+ MalformedKey,
+ /// The agent cannot run on a key: it is not an in-memory agent on an
+ /// Anthropic or OpenAI model.
+ #[error("only in-memory agents on an Anthropic or OpenAI model can use an API key")]
+ UnsupportedAgent,
+ /// The agent owner's plan does not include API keys.
+ #[error("a paid plan is required to use an agent's own API key")]
+ PlanRequired,
+ /// The owner's plan could not be read.
+ #[error("the plan could not be read")]
+ Plan(#[source] anyhow::Error),
+ /// Encryption or decryption failed. Opaque: KMS's reason can tell a
+ /// prober whether the encryption context matched.
+ #[error("the key could not be encrypted or decrypted")]
+ Cipher,
+ /// The row could not be read or written.
+ #[error("the key could not be stored")]
+ Storage(#[source] anyhow::Error),
+}
diff --git a/crates/agent_api_keys/src/domain/models/test.rs b/crates/agent_api_keys/src/domain/models/test.rs
new file mode 100644
index 0000000000..b93701373b
--- /dev/null
+++ b/crates/agent_api_keys/src/domain/models/test.rs
@@ -0,0 +1,56 @@
+use super::*;
+
+#[test]
+fn keys_parse_only_for_their_own_provider() {
+ let anthropic = ProviderApiKey::parse(ModelProvider::Anthropic, " \"sk-ant-api03-abc\"\n")
+ .expect("pasted quotes and whitespace are stripped");
+ assert_eq!(anthropic.expose(), "sk-ant-api03-abc");
+ assert_eq!(anthropic.prefix(), "sk-ant-");
+
+ let openai = ProviderApiKey::parse(ModelProvider::OpenAi, "sk-proj-abc")
+ .expect("project keys are OpenAI keys");
+ assert_eq!(openai.prefix(), "sk-");
+
+ for (provider, rejected) in [
+ (ModelProvider::Anthropic, ""),
+ (ModelProvider::Anthropic, "sk-ant-"),
+ (ModelProvider::Anthropic, "sk-proj-abc"),
+ (ModelProvider::Anthropic, "grok_abc"),
+ (ModelProvider::OpenAi, "sk-"),
+ (ModelProvider::OpenAi, "sk-ant-api03-abc"),
+ (ModelProvider::OpenAi, "crsr_abc"),
+ (ModelProvider::OpenAi, "sk-two words"),
+ (ModelProvider::Anthropic, "sk-ant-api03-abc;rm"),
+ (ModelProvider::OpenAi, "sk-proj-abc\u{0}"),
+ (ModelProvider::OpenAi, &format!("sk-{}", "a".repeat(501))),
+ ] {
+ assert!(
+ ProviderApiKey::parse(provider, rejected).is_err(),
+ "{rejected:?} should be rejected for {provider:?}"
+ );
+ }
+}
+
+#[test]
+fn a_key_never_prints_itself() {
+ let key = ProviderApiKey::parse(ModelProvider::OpenAi, "sk-proj-secret").expect("valid");
+ let printed = format!("{key:?}");
+ assert!(
+ !printed.contains("secret"),
+ "Debug leaked the key: {printed}"
+ );
+}
+
+#[test]
+fn routed_models_name_the_provider_whose_key_pays_for_them() {
+ assert_eq!(
+ ModelProvider::of_model("anthropic/claude-opus-5-5"),
+ Some(ModelProvider::Anthropic)
+ );
+ assert_eq!(
+ ModelProvider::of_model("openai/gpt-6-astra"),
+ Some(ModelProvider::OpenAi)
+ );
+ assert_eq!(ModelProvider::of_model("google/gemini-3.8-flash"), None);
+ assert_eq!(ModelProvider::of_model("claude-opus-5-5"), None);
+}
diff --git a/crates/agent_api_keys/src/domain/ports.rs b/crates/agent_api_keys/src/domain/ports.rs
new file mode 100644
index 0000000000..6533db307a
--- /dev/null
+++ b/crates/agent_api_keys/src/domain/ports.rs
@@ -0,0 +1,106 @@
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::models::{
+ AgentKeyError, AgentKeyStatus, AgentOwner, EncryptedProviderApiKey, ModelProvider,
+ ProviderApiKey, StoredAgentKey, UsableAgentKey,
+};
+
+/// Result alias for this crate.
+pub type Result<T> = std::result::Result<T, AgentKeyError>;
+
+/// Encrypts a key so only its agent and provider can decrypt it.
+#[async_trait::async_trait]
+pub trait AgentKeyCipher: Send + Sync + 'static {
+ /// Encrypt `key` for the agent `bot_id`.
+ async fn encrypt(&self, bot_id: Uuid, key: &ProviderApiKey) -> Result<EncryptedProviderApiKey>;
+
+ /// Decrypt the `provider` key of the agent `bot_id`.
+ async fn decrypt(
+ &self,
+ bot_id: Uuid,
+ provider: ModelProvider,
+ encrypted: &EncryptedProviderApiKey,
+ ) -> Result<ProviderApiKey>;
+}
+
+/// Where agents' keys are stored. Never decrypts.
+#[async_trait::async_trait]
+pub trait AgentKeyRepo: Send + Sync + 'static {
+ /// Register or replace the agent's key.
+ async fn upsert(
+ &self,
+ bot_id: Uuid,
+ provider: ModelProvider,
+ encrypted: &EncryptedProviderApiKey,
+ key_prefix: &str,
+ ) -> Result<AgentKeyStatus>;
+
+ /// The agent's key, if it has one.
+ async fn status(&self, bot_id: Uuid) -> Result<Option<AgentKeyStatus>>;
+
+ /// Forget the agent's key, reporting whether there was one.
+ async fn delete(&self, bot_id: Uuid) -> Result<bool>;
+
+ /// The agent's key with the agent as it is configured now, for a live,
+ /// undeleted agent.
+ async fn stored(&self, bot_id: Uuid) -> Result<Option<StoredAgentKey>>;
+
+ /// Whether `user` is currently a member of `team_id`.
+ async fn is_team_member(&self, user: &MacroUserIdStr<'_>, team_id: Uuid) -> Result<bool>;
+}
+
+/// Whether an agent owner's plan includes agents' own API keys.
+#[async_trait::async_trait]
+pub trait KeyPlans: Send + Sync + 'static {
+ /// Whether agents `owner` owns may save keys and run turns on them.
+ async fn allows_keys(&self, owner: &AgentOwner) -> Result<bool>;
+}
+
+/// What the in-memory runtime asks before a turn of an agent in a session
+/// owned by `user`.
+///
+/// A key counts only while the agent is an in-memory agent whose model's
+/// provider matches the key, its owner's plan includes keys, and the session
+/// is its owner's: the person's own for a personal agent, a current member's
+/// for a team agent. Otherwise the agent runs on Macro usage as if it had
+/// none, so nobody else spends a person's or a team's key.
+#[async_trait::async_trait]
+pub trait AgentKeys: Send + Sync + 'static {
+ /// The provider of the key the agent's turns run on, without decrypting.
+ async fn usable_provider(
+ &self,
+ bot_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<ModelProvider>>;
+
+ /// The key the agent's next turn runs on, decrypted for that turn.
+ async fn usable_key(
+ &self,
+ bot_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<UsableAgentKey>>;
+}
+
+/// A deployment where no agent has a key: every turn runs on Macro usage.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoAgentKeys;
+
+#[async_trait::async_trait]
+impl AgentKeys for NoAgentKeys {
+ async fn usable_provider(
+ &self,
+ _bot_id: Uuid,
+ _user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<ModelProvider>> {
+ Ok(None)
+ }
+
+ async fn usable_key(
+ &self,
+ _bot_id: Uuid,
+ _user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<UsableAgentKey>> {
+ Ok(None)
+ }
+}
diff --git a/crates/agent_api_keys/src/domain/service.rs b/crates/agent_api_keys/src/domain/service.rs
new file mode 100644
index 0000000000..8c8bb586d5
--- /dev/null
+++ b/crates/agent_api_keys/src/domain/service.rs
@@ -0,0 +1,133 @@
+#[cfg(test)]
+mod test;
+
+use macro_uuid::Uuid;
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::models::{
+ AgentKeyError, AgentKeyView, AgentOwner, KeyedAgent, ModelProvider, ProviderApiKey,
+ StoredAgentKey, UsableAgentKey,
+};
+use super::ports::{AgentKeyCipher, AgentKeyRepo, AgentKeys, KeyPlans, Result};
+
+/// Saving, showing and using agents' own API keys.
+///
+/// Only an in-memory agent on an Anthropic or OpenAI model can have one, for
+/// its model's provider, and only on a paid plan of the agent's owner. Who
+/// may change an agent is decided by its caller, which hands over the
+/// agent it authorized.
+pub struct AgentKeyService<Repo, Cipher, Plans> {
+ repo: Repo,
+ cipher: Cipher,
+ plans: Plans,
+}
+
+impl<Repo, Cipher, Plans> AgentKeyService<Repo, Cipher, Plans> {
+ /// Store keys in `repo`, encrypted with `cipher`, for owners `plans`
+ /// allows.
+ pub fn new(repo: Repo, cipher: Cipher, plans: Plans) -> Self {
+ Self {
+ repo,
+ cipher,
+ plans,
+ }
+ }
+}
+
+impl<Repo: AgentKeyRepo, Cipher: AgentKeyCipher, Plans: KeyPlans>
+ AgentKeyService<Repo, Cipher, Plans>
+{
+ /// The agent's key, and whether its owner's plan lets it run on one.
+ pub async fn view(&self, agent: &KeyedAgent) -> Result<AgentKeyView> {
+ Ok(AgentKeyView {
+ key: self.repo.status(agent.bot_id).await?,
+ plan_allows: self.plans.allows_keys(&agent.owner).await?,
+ })
+ }
+
+ /// Register or replace the agent's key, for its model's provider.
+ ///
+ /// The key is parsed before anything else, so a malformed value never
+ /// reaches KMS or the table.
+ pub async fn set(&self, agent: &KeyedAgent, supplied: &str) -> Result<AgentKeyView> {
+ let provider = agent
+ .key_provider()
+ .ok_or(AgentKeyError::UnsupportedAgent)?;
+ let key =
+ ProviderApiKey::parse(provider, supplied).map_err(|_| AgentKeyError::MalformedKey)?;
+ if !self.plans.allows_keys(&agent.owner).await? {
+ return Err(AgentKeyError::PlanRequired);
+ }
+ let encrypted = self.cipher.encrypt(agent.bot_id, &key).await?;
+ self.repo
+ .upsert(agent.bot_id, provider, &encrypted, key.prefix())
+ .await?;
+ self.view(agent).await
+ }
+
+ /// Forget the agent's key. Does not revoke it at the provider.
+ pub async fn remove(&self, agent: &KeyedAgent) -> Result<AgentKeyView> {
+ self.repo.delete(agent.bot_id).await?;
+ self.view(agent).await
+ }
+
+ /// The stored key, when the agent can run on it now in a session `user`
+ /// owns.
+ async fn usable(
+ &self,
+ bot_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<StoredAgentKey>> {
+ let Some(stored) = self.repo.stored(bot_id).await? else {
+ return Ok(None);
+ };
+ if stored.agent.key_provider() != Some(stored.provider)
+ || !self.owns_key(&stored.agent.owner, user).await?
+ || !self.plans.allows_keys(&stored.agent.owner).await?
+ {
+ return Ok(None);
+ }
+ Ok(Some(stored))
+ }
+
+ /// Whether `user` may spend a key `owner` holds: their own, or that of a
+ /// team they are currently a member of.
+ async fn owns_key(&self, owner: &AgentOwner, user: &MacroUserIdStr<'_>) -> Result<bool> {
+ match owner {
+ AgentOwner::User(owner) => Ok(owner.as_ref() == user.as_ref()),
+ AgentOwner::Team(team_id) => self.repo.is_team_member(user, *team_id).await,
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl<Repo: AgentKeyRepo, Cipher: AgentKeyCipher, Plans: KeyPlans> AgentKeys
+ for AgentKeyService<Repo, Cipher, Plans>
+{
+ async fn usable_provider(
+ &self,
+ bot_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<ModelProvider>> {
+ Ok(self
+ .usable(bot_id, user)
+ .await?
+ .map(|stored| stored.provider))
+ }
+
+ async fn usable_key(
+ &self,
+ bot_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> Result<Option<UsableAgentKey>> {
+ let Some(stored) = self.usable(bot_id, user).await? else {
+ return Ok(None);
+ };
+ let key = self
+ .cipher
+ .decrypt(bot_id, stored.provider, &stored.encrypted)
+ .await?;
+ Ok(Some(UsableAgentKey { bot_id, key }))
+ }
+}
diff --git a/crates/agent_api_keys/src/domain/service/test.rs b/crates/agent_api_keys/src/domain/service/test.rs
new file mode 100644
index 0000000000..2beb39786d
--- /dev/null
+++ b/crates/agent_api_keys/src/domain/service/test.rs
@@ -0,0 +1,298 @@
+use std::sync::Mutex;
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::*;
+use crate::domain::models::{AgentKeyStatus, AgentOwner, EncryptedProviderApiKey};
+
+const BOT: &str = "00000000-0000-0000-0000-0000000000b0";
+
+fn agent(harness: &str, model: &str) -> KeyedAgent {
+ KeyedAgent {
+ bot_id: BOT.parse().expect("uuid"),
+ owner: AgentOwner::User(MacroUserIdStr::try_from(OWNER.to_owned()).expect("user id")),
+ harness: harness.to_owned(),
+ model: model.to_owned(),
+ }
+}
+
+fn encrypted() -> EncryptedProviderApiKey {
+ EncryptedProviderApiKey {
+ key_ciphertext: vec![1],
+ encryption_version: 1,
+ kms_key_id: "kms".to_owned(),
+ }
+}
+
+/// One agent's key, and the agent as it is configured now.
+#[derive(Default)]
+struct FakeRepo {
+ stored: Mutex<Option<(ModelProvider, String)>>,
+ agent: Mutex<Option<KeyedAgent>>,
+ team_members: Mutex<Vec<String>>,
+}
+
+#[async_trait::async_trait]
+impl AgentKeyRepo for FakeRepo {
+ async fn upsert(
+ &self,
+ _bot_id: Uuid,
+ provider: ModelProvider,
+ _encrypted: &EncryptedProviderApiKey,
+ key_prefix: &str,
+ ) -> Result<AgentKeyStatus> {
+ *self.stored.lock().expect("lock") = Some((provider, key_prefix.to_owned()));
+ Ok(AgentKeyStatus {
+ provider,
+ updated_at: chrono::Utc::now(),
+ })
+ }
+
+ async fn status(&self, _bot_id: Uuid) -> Result<Option<AgentKeyStatus>> {
+ Ok(self
+ .stored
+ .lock()
+ .expect("lock")
+ .as_ref()
+ .map(|(provider, _)| AgentKeyStatus {
+ provider: *provider,
+ updated_at: chrono::Utc::now(),
+ }))
+ }
+
+ async fn delete(&self, _bot_id: Uuid) -> Result<bool> {
+ Ok(self.stored.lock().expect("lock").take().is_some())
+ }
+
+ async fn stored(&self, _bot_id: Uuid) -> Result<Option<StoredAgentKey>> {
+ let stored = self.stored.lock().expect("lock").clone();
+ let agent = self.agent.lock().expect("lock").clone();
+ Ok(stored
+ .zip(agent)
+ .map(|((provider, _), agent)| StoredAgentKey {
+ agent,
+ provider,
+ encrypted: encrypted(),
+ }))
+ }
+
+ async fn is_team_member(&self, user: &MacroUserIdStr<'_>, _team_id: Uuid) -> Result<bool> {
+ Ok(self
+ .team_members
+ .lock()
+ .expect("lock")
+ .iter()
+ .any(|member| member == user.as_ref()))
+ }
+}
+
+const OWNER: &str = "macro|[email protected]";
+
+fn user(id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(id.to_owned()).expect("user id")
+}
+
+#[derive(Default)]
+struct FakeCipher {
+ encrypted: Mutex<usize>,
+}
+
+#[async_trait::async_trait]
+impl AgentKeyCipher for FakeCipher {
+ async fn encrypt(
+ &self,
+ _bot_id: Uuid,
+ _key: &ProviderApiKey,
+ ) -> Result<EncryptedProviderApiKey> {
+ *self.encrypted.lock().expect("lock") += 1;
+ Ok(encrypted())
+ }
+
+ async fn decrypt(
+ &self,
+ _bot_id: Uuid,
+ provider: ModelProvider,
+ _encrypted: &EncryptedProviderApiKey,
+ ) -> Result<ProviderApiKey> {
+ let plaintext = match provider {
+ ModelProvider::Anthropic => "sk-ant-api03-abc",
+ ModelProvider::OpenAi => "sk-proj-abc",
+ };
+ ProviderApiKey::parse(provider, plaintext).map_err(|_| AgentKeyError::Cipher)
+ }
+}
+
+/// A plan that includes agent keys, or one that does not.
+struct Paid(Mutex<bool>);
+
+#[async_trait::async_trait]
+impl KeyPlans for Paid {
+ async fn allows_keys(&self, _owner: &AgentOwner) -> Result<bool> {
+ Ok(*self.0.lock().expect("lock"))
+ }
+}
+
+fn service(paid: bool) -> AgentKeyService<FakeRepo, FakeCipher, Paid> {
+ AgentKeyService::new(
+ FakeRepo::default(),
+ FakeCipher::default(),
+ Paid(Mutex::new(paid)),
+ )
+}
+
+#[tokio::test]
+async fn an_in_memory_agent_stores_a_key_for_its_models_provider() {
+ let service = service(true);
+ let agent = agent("in-memory", "anthropic/claude-sonnet-5-5");
+
+ let view = service
+ .set(&agent, "sk-ant-api03-abc")
+ .await
+ .expect("saved");
+
+ assert_eq!(
+ view.key.map(|key| key.provider),
+ Some(ModelProvider::Anthropic)
+ );
+ assert!(view.plan_allows);
+ assert_eq!(
+ *service.repo.stored.lock().expect("lock"),
+ Some((ModelProvider::Anthropic, "sk-ant-".to_owned()))
+ );
+}
+
+#[tokio::test]
+async fn only_in_memory_agents_on_anthropic_or_openai_models_take_a_key() {
+ for (harness, model) in [
+ ("cursor", "anthropic/claude-sonnet-5-5"),
+ ("in-memory", "google/gemini-3.8-flash"),
+ ] {
+ let service = service(true);
+ let error = service
+ .set(&agent(harness, model), "sk-ant-api03-abc")
+ .await
+ .expect_err("unsupported");
+ assert!(
+ matches!(error, AgentKeyError::UnsupportedAgent),
+ "{harness} {model}"
+ );
+ assert_eq!(*service.cipher.encrypted.lock().expect("lock"), 0);
+ }
+}
+
+#[tokio::test]
+async fn a_key_for_another_provider_or_a_free_plan_never_reaches_kms() {
+ let service = service(true);
+ let error = service
+ .set(
+ &agent("in-memory", "openai/gpt-6-astra"),
+ "sk-ant-api03-abc",
+ )
+ .await
+ .expect_err("an Anthropic key is not an OpenAI key");
+ assert!(matches!(error, AgentKeyError::MalformedKey));
+
+ let free = self::service(false);
+ let error = free
+ .set(&agent("in-memory", "openai/gpt-6-astra"), "sk-proj-abc")
+ .await
+ .expect_err("free plans have no keys");
+ assert!(matches!(error, AgentKeyError::PlanRequired));
+
+ assert_eq!(*service.cipher.encrypted.lock().expect("lock"), 0);
+ assert_eq!(*free.cipher.encrypted.lock().expect("lock"), 0);
+}
+
+#[tokio::test]
+async fn turns_run_on_the_key_only_while_the_agent_and_plan_still_fit_it() {
+ let service = service(true);
+ let bot: Uuid = BOT.parse().expect("uuid");
+ let keyed = agent("in-memory", "anthropic/claude-sonnet-5-5");
+ service
+ .set(&keyed, "sk-ant-api03-abc")
+ .await
+ .expect("saved");
+
+ *service.repo.agent.lock().expect("lock") = Some(keyed);
+ let key = service
+ .usable_key(bot, &user(OWNER))
+ .await
+ .expect("read")
+ .expect("usable");
+ assert_eq!(key.key.expose(), "sk-ant-api03-abc");
+
+ *service.repo.agent.lock().expect("lock") = Some(agent("in-memory", "openai/gpt-6-astra"));
+ assert_eq!(
+ service
+ .usable_provider(bot, &user(OWNER))
+ .await
+ .expect("read"),
+ None,
+ "an agent moved to another provider's model runs on Macro usage"
+ );
+
+ *service.repo.agent.lock().expect("lock") =
+ Some(agent("in-memory", "anthropic/claude-sonnet-5-5"));
+ *service.plans.0.lock().expect("lock") = false;
+ assert!(
+ service
+ .usable_key(bot, &user(OWNER))
+ .await
+ .expect("read")
+ .is_none(),
+ "a downgraded owner keeps the key but turns do not run on it"
+ );
+ assert!(
+ service
+ .view(&agent("in-memory", "anthropic/claude-sonnet-5-5"))
+ .await
+ .expect("view")
+ .key
+ .is_some(),
+ "the key is still shown, so it can be removed"
+ );
+}
+
+#[tokio::test]
+async fn only_the_agents_owner_or_its_team_spends_its_key() {
+ let service = service(true);
+ let bot: Uuid = BOT.parse().expect("uuid");
+ let personal = agent("in-memory", "anthropic/claude-sonnet-5-5");
+ service
+ .set(&personal, "sk-ant-api03-abc")
+ .await
+ .expect("saved");
+
+ *service.repo.agent.lock().expect("lock") = Some(personal);
+ assert!(
+ service
+ .usable_key(bot, &user("macro|[email protected]"))
+ .await
+ .expect("read")
+ .is_none(),
+ "someone else's session of a personal agent runs on Macro usage"
+ );
+
+ let team = KeyedAgent {
+ owner: AgentOwner::Team(Uuid::nil()),
+ ..agent("in-memory", "anthropic/claude-sonnet-5-5")
+ };
+ *service.repo.agent.lock().expect("lock") = Some(team);
+ *service.repo.team_members.lock().expect("lock") = vec!["macro|[email protected]".to_owned()];
+ assert!(
+ service
+ .usable_provider(bot, &user("macro|[email protected]"))
+ .await
+ .expect("read")
+ .is_some(),
+ "a member's session of a team agent runs on the team's key"
+ );
+ assert!(
+ service
+ .usable_provider(bot, &user("macro|[email protected]"))
+ .await
+ .expect("read")
+ .is_none(),
+ "a non-member never spends the team's key"
+ );
+}
diff --git a/crates/agent_api_keys/src/lib.rs b/crates/agent_api_keys/src/lib.rs
new file mode 100644
index 0000000000..7486207e24
--- /dev/null
+++ b/crates/agent_api_keys/src/lib.rs
@@ -0,0 +1,17 @@
+#![deny(missing_docs)]
+//! Agents' own model provider API keys (Anthropic, OpenAI).
+//!
+//! An in-memory agent on an Anthropic or OpenAI model can have one key, for
+//! its model's provider. While the agent still fits the key and its owner is
+//! on a paid plan, every turn of the agent runs on the key instead of Macro's
+//! allowance, and usage on it is recorded against the key without counting.
+//!
+//! Keys live in `agent_api_keys`, one row per agent, encrypted with the
+//! Cursor key's KMS key under an encryption context bound to the agent and
+//! the provider. They are write-only: nothing reads a key back out but a
+//! turn that runs on it.
+
+/// Models, ports and the policy around saving and using keys.
+pub mod domain;
+/// Postgres, KMS and plan adapters for the domain ports.
+pub mod outbound;
diff --git a/crates/agent_api_keys/src/outbound.rs b/crates/agent_api_keys/src/outbound.rs
new file mode 100644
index 0000000000..c9a89b15a1
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound.rs
@@ -0,0 +1,7 @@
+mod kms;
+mod pg;
+mod plans;
+
+pub use kms::KmsAgentKeyCipher;
+pub use pg::PgAgentKeyRepo;
+pub use plans::EntitlementKeyPlans;
diff --git a/crates/agent_api_keys/src/outbound/kms.rs b/crates/agent_api_keys/src/outbound/kms.rs
new file mode 100644
index 0000000000..05dd1ef8af
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound/kms.rs
@@ -0,0 +1,89 @@
+#[cfg(test)]
+mod test;
+
+use std::collections::HashMap;
+
+use cursor_api_key::cipher::KmsCiphertexts;
+use macro_uuid::Uuid;
+
+use crate::domain::{
+ AgentKeyCipher, AgentKeyError, EncryptedProviderApiKey, ModelProvider, ProviderApiKey, Result,
+};
+
+/// The encryption scheme this adapter writes.
+const ENCRYPTION_VERSION: i16 = 1;
+
+/// Names the purpose in the encryption context, so neither a Cursor key nor
+/// any other feature's ciphertext decrypts as an agent key.
+const ENCRYPTION_PURPOSE: &str = "agent-api-key";
+
+/// Direct `kms:Encrypt` under the Cursor key's CMK, as `cursor_api_key` does:
+/// a provider key is far below KMS's 4 KB limit, the authentication service
+/// that saves agent keys already encrypts with that CMK, and the agent
+/// harness that reads them already decrypts with it.
+///
+/// The context binds the agent and the provider, so KMS refuses a row moved
+/// to another agent or relabelled as another provider's key.
+pub struct KmsAgentKeyCipher<Kms> {
+ kms: Kms,
+}
+
+impl<Kms> KmsAgentKeyCipher<Kms> {
+ /// Encrypt and decrypt through `kms`.
+ pub fn new(kms: Kms) -> Self {
+ Self { kms }
+ }
+}
+
+fn encryption_context(bot_id: Uuid, provider: ModelProvider) -> HashMap<String, String> {
+ HashMap::from([
+ ("macro:purpose".to_owned(), ENCRYPTION_PURPOSE.to_owned()),
+ (
+ "macro:encryption-version".to_owned(),
+ ENCRYPTION_VERSION.to_string(),
+ ),
+ ("macro:bot-id".to_owned(), bot_id.to_string()),
+ ("macro:provider".to_owned(), provider.as_str().to_owned()),
+ ])
+}
+
+#[async_trait::async_trait]
+impl<Kms: KmsCiphertexts + 'static> AgentKeyCipher for KmsAgentKeyCipher<Kms> {
+ async fn encrypt(&self, bot_id: Uuid, key: &ProviderApiKey) -> Result<EncryptedProviderApiKey> {
+ let (key_ciphertext, kms_key_id) = self
+ .kms
+ .encrypt(
+ encryption_context(bot_id, key.provider()),
+ key.expose().as_bytes(),
+ )
+ .await
+ .map_err(|_| AgentKeyError::Cipher)?;
+ Ok(EncryptedProviderApiKey {
+ key_ciphertext,
+ encryption_version: ENCRYPTION_VERSION,
+ kms_key_id,
+ })
+ }
+
+ async fn decrypt(
+ &self,
+ bot_id: Uuid,
+ provider: ModelProvider,
+ encrypted: &EncryptedProviderApiKey,
+ ) -> Result<ProviderApiKey> {
+ if encrypted.encryption_version != ENCRYPTION_VERSION {
+ return Err(AgentKeyError::Cipher);
+ }
+ let plaintext = self
+ .kms
+ .decrypt(
+ &encrypted.kms_key_id,
+ &encrypted.key_ciphertext,
+ encryption_context(bot_id, provider),
+ )
+ .await
+ .map_err(|_| AgentKeyError::Cipher)?;
+ let plaintext = std::str::from_utf8(&plaintext).map_err(|_| AgentKeyError::Cipher)?;
+ ProviderApiKey::parse(provider, plaintext).map_err(|_| AgentKeyError::Cipher)
+ }
+}
diff --git a/crates/agent_api_keys/src/outbound/kms/test.rs b/crates/agent_api_keys/src/outbound/kms/test.rs
new file mode 100644
index 0000000000..e3e06b4cdb
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound/kms/test.rs
@@ -0,0 +1,78 @@
+use std::sync::Mutex;
+
+use cursor_api_key::cipher::KmsCiphertextsError;
+use zeroize::Zeroizing;
+
+use super::*;
+
+/// A KMS that, like the real one, refuses a decrypt whose context differs
+/// from the one the ciphertext was encrypted under.
+#[derive(Default)]
+struct FakeKms {
+ stored: Mutex<Vec<(Vec<u8>, HashMap<String, String>, Vec<u8>)>>,
+}
+
+#[async_trait::async_trait]
+impl KmsCiphertexts for FakeKms {
+ async fn encrypt(
+ &self,
+ encryption_context: HashMap<String, String>,
+ plaintext: &[u8],
+ ) -> std::result::Result<(Vec<u8>, String), KmsCiphertextsError> {
+ let mut stored = self.stored.lock().expect("lock");
+ let ciphertext = format!("ciphertext-{}", stored.len()).into_bytes();
+ stored.push((ciphertext.clone(), encryption_context, plaintext.to_vec()));
+ Ok((ciphertext, "fake-kms-key".to_owned()))
+ }
+
+ async fn decrypt(
+ &self,
+ _kms_key_id: &str,
+ ciphertext: &[u8],
+ encryption_context: HashMap<String, String>,
+ ) -> std::result::Result<Zeroizing<Vec<u8>>, KmsCiphertextsError> {
+ self.stored
+ .lock()
+ .expect("lock")
+ .iter()
+ .find(|(stored, context, _)| stored == ciphertext && *context == encryption_context)
+ .map(|(_, _, plaintext)| Zeroizing::new(plaintext.clone()))
+ .ok_or(KmsCiphertextsError)
+ }
+}
+
+const BOT: &str = "00000000-0000-0000-0000-0000000000aa";
+const OTHER_BOT: &str = "00000000-0000-0000-0000-0000000000bb";
+
+#[tokio::test]
+async fn a_key_decrypts_only_for_its_agent_and_provider() {
+ let cipher = KmsAgentKeyCipher::new(FakeKms::default());
+ let bot: Uuid = BOT.parse().expect("uuid");
+ let key = ProviderApiKey::parse(ModelProvider::Anthropic, "sk-ant-api03-abc").expect("valid");
+ let encrypted = cipher.encrypt(bot, &key).await.expect("encrypted");
+
+ let decrypted = cipher
+ .decrypt(bot, ModelProvider::Anthropic, &encrypted)
+ .await
+ .expect("its own agent decrypts it");
+ assert_eq!(decrypted.expose(), "sk-ant-api03-abc");
+
+ assert!(
+ cipher
+ .decrypt(
+ OTHER_BOT.parse().expect("uuid"),
+ ModelProvider::Anthropic,
+ &encrypted
+ )
+ .await
+ .is_err(),
+ "a row moved to another agent must not decrypt"
+ );
+ assert!(
+ cipher
+ .decrypt(bot, ModelProvider::OpenAi, &encrypted)
+ .await
+ .is_err(),
+ "a row relabelled as another provider must not decrypt"
+ );
+}
diff --git a/crates/agent_api_keys/src/outbound/pg.rs b/crates/agent_api_keys/src/outbound/pg.rs
new file mode 100644
index 0000000000..eb2ccc5b30
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound/pg.rs
@@ -0,0 +1,163 @@
+#[cfg(test)]
+mod test;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+
+use crate::domain::{
+ AgentKeyError, AgentKeyRepo, AgentKeyStatus, AgentOwner, EncryptedProviderApiKey, KeyedAgent,
+ ModelProvider, Result, StoredAgentKey,
+};
+
+/// Agents' keys in `agent_api_keys`, one row per agent.
+#[derive(Clone)]
+pub struct PgAgentKeyRepo {
+ pool: PgPool,
+}
+
+impl PgAgentKeyRepo {
+ /// Read and write keys through `pool`.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+fn storage(error: impl Into<anyhow::Error>) -> AgentKeyError {
+ AgentKeyError::Storage(error.into())
+}
+
+fn provider(stored: &str) -> Result<ModelProvider> {
+ ModelProvider::parse(stored)
+ .ok_or_else(|| storage(anyhow::anyhow!("unknown provider {stored:?}")))
+}
+
+fn owner(user_id: Option<String>, team_id: Option<Uuid>) -> Result<AgentOwner> {
+ match (user_id, team_id) {
+ (Some(user_id), None) => MacroUserIdStr::try_from(user_id)
+ .map(AgentOwner::User)
+ .map_err(|error| storage(anyhow::anyhow!("invalid owner user id: {error:?}"))),
+ (None, Some(team_id)) => Ok(AgentOwner::Team(team_id)),
+ _ => Err(storage(anyhow::anyhow!(
+ "an agent must have exactly one owner"
+ ))),
+ }
+}
+
+#[async_trait::async_trait]
+impl AgentKeyRepo for PgAgentKeyRepo {
+ async fn upsert(
+ &self,
+ bot_id: Uuid,
+ provider: ModelProvider,
+ encrypted: &EncryptedProviderApiKey,
+ key_prefix: &str,
+ ) -> Result<AgentKeyStatus> {
+ let updated_at = sqlx::query_scalar!(
+ r#"
+ INSERT INTO agent_api_keys (
+ bot_id, provider, key_ciphertext, encryption_version, kms_key_id, key_prefix
+ )
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (bot_id) DO UPDATE SET
+ provider = EXCLUDED.provider,
+ key_ciphertext = EXCLUDED.key_ciphertext,
+ encryption_version = EXCLUDED.encryption_version,
+ kms_key_id = EXCLUDED.kms_key_id,
+ key_prefix = EXCLUDED.key_prefix,
+ updated_at = NOW()
+ RETURNING updated_at
+ "#,
+ bot_id,
+ provider.as_str(),
+ &encrypted.key_ciphertext,
+ encrypted.encryption_version,
+ encrypted.kms_key_id,
+ key_prefix,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(AgentKeyStatus {
+ provider,
+ updated_at,
+ })
+ }
+
+ async fn status(&self, bot_id: Uuid) -> Result<Option<AgentKeyStatus>> {
+ let row = sqlx::query!(
+ "SELECT provider, updated_at FROM agent_api_keys WHERE bot_id = $1",
+ bot_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ row.map(|row| {
+ Ok(AgentKeyStatus {
+ provider: provider(&row.provider)?,
+ updated_at: row.updated_at,
+ })
+ })
+ .transpose()
+ }
+
+ async fn delete(&self, bot_id: Uuid) -> Result<bool> {
+ let result = sqlx::query!("DELETE FROM agent_api_keys WHERE bot_id = $1", bot_id)
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(result.rows_affected() > 0)
+ }
+
+ async fn stored(&self, bot_id: Uuid) -> Result<Option<StoredAgentKey>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ agent_key.provider,
+ agent_key.key_ciphertext,
+ agent_key.encryption_version,
+ agent_key.kms_key_id,
+ bot.owner_user_id,
+ bot.team_id,
+ config.harness,
+ config.default_model
+ FROM agent_api_keys agent_key
+ JOIN bots bot ON bot.id = agent_key.bot_id AND bot.deleted_at IS NULL
+ JOIN agent_configs config ON config.bot_id = agent_key.bot_id
+ WHERE agent_key.bot_id = $1
+ "#,
+ bot_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ row.map(|row| {
+ Ok(StoredAgentKey {
+ agent: KeyedAgent {
+ bot_id,
+ owner: owner(row.owner_user_id, row.team_id)?,
+ harness: row.harness,
+ model: row.default_model,
+ },
+ provider: provider(&row.provider)?,
+ encrypted: EncryptedProviderApiKey {
+ key_ciphertext: row.key_ciphertext,
+ encryption_version: row.encryption_version,
+ kms_key_id: row.kms_key_id,
+ },
+ })
+ })
+ .transpose()
+ }
+
+ async fn is_team_member(&self, user: &MacroUserIdStr<'_>, team_id: Uuid) -> Result<bool> {
+ sqlx::query_scalar!(
+ r#"SELECT EXISTS (SELECT 1 FROM team_user WHERE user_id = $1 AND team_id = $2) AS "member!""#,
+ user.as_ref(),
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(storage)
+ }
+}
diff --git a/crates/agent_api_keys/src/outbound/pg/test.rs b/crates/agent_api_keys/src/outbound/pg/test.rs
new file mode 100644
index 0000000000..98d60f60ea
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound/pg/test.rs
@@ -0,0 +1,117 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+use super::*;
+
+const OWNER: &str = "macro|[email protected]";
+
+fn encrypted() -> EncryptedProviderApiKey {
+ EncryptedProviderApiKey {
+ key_ciphertext: vec![1, 2, 3],
+ encryption_version: 1,
+ kms_key_id: "arn:aws:kms:us-east-1:123456789012:key/1".to_owned(),
+ }
+}
+
+/// A user-owned in-memory agent on `model`.
+async fn insert_agent(pool: &PgPool, model: &str) -> anyhow::Result<Uuid> {
+ sqlx::query!(
+ r#"
+ WITH new_macro_user AS (
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES (gen_random_uuid(), '[email protected]', '[email protected]', 'stripe_owner')
+ RETURNING id
+ )
+ INSERT INTO "User" ("id", "email", "macro_user_id")
+ SELECT $1, '[email protected]', new_macro_user.id FROM new_macro_user
+ "#,
+ OWNER,
+ )
+ .execute(pool)
+ .await?;
+ let bot_id = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ "INSERT INTO bots (id, kind, name, handle, has_agent, owner_user_id) VALUES ($1, 'owned', 'Agent', 'agent', true, $2)",
+ bot_id,
+ OWNER,
+ )
+ .execute(pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_configs (bot_id, instructions, harness, default_model, channel_scope, is_coding)
+ VALUES ($1, 'Be brief.', 'in-memory', $2, 'all', false)
+ "#,
+ bot_id,
+ model,
+ )
+ .execute(pool)
+ .await?;
+ Ok(bot_id)
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_stored_key_carries_the_agent_as_configured_now(pool: PgPool) -> anyhow::Result<()> {
+ let bot_id = insert_agent(&pool, "anthropic/claude-sonnet-5-5").await?;
+ let repo = PgAgentKeyRepo::new(pool.clone());
+ let saved = repo
+ .upsert(bot_id, ModelProvider::Anthropic, &encrypted(), "sk-ant-")
+ .await?;
+ assert_eq!(repo.status(bot_id).await?, Some(saved));
+
+ let stored = repo.stored(bot_id).await?.expect("the agent has a key");
+ assert_eq!(stored.provider, ModelProvider::Anthropic);
+ assert_eq!(stored.encrypted, encrypted());
+ assert_eq!(
+ stored.agent.owner,
+ AgentOwner::User(MacroUserIdStr::try_from(OWNER.to_owned())?)
+ );
+ assert_eq!(stored.agent.model, "anthropic/claude-sonnet-5-5");
+ assert_eq!(stored.agent.harness, "in-memory");
+
+ sqlx::query!("UPDATE bots SET deleted_at = NOW() WHERE id = $1", bot_id)
+ .execute(&pool)
+ .await?;
+ assert!(
+ repo.stored(bot_id).await?.is_none(),
+ "a deleted agent's key is never used"
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn registering_again_replaces_the_key(pool: PgPool) -> anyhow::Result<()> {
+ let bot_id = insert_agent(&pool, "openai/gpt-6-astra").await?;
+ let repo = PgAgentKeyRepo::new(pool);
+ repo.upsert(bot_id, ModelProvider::Anthropic, &encrypted(), "sk-ant-")
+ .await?;
+ let second = repo
+ .upsert(bot_id, ModelProvider::OpenAi, &encrypted(), "sk-")
+ .await?;
+
+ assert_eq!(repo.status(bot_id).await?, Some(second));
+ assert!(repo.delete(bot_id).await?);
+ assert!(!repo.delete(bot_id).await?);
+ assert!(repo.status(bot_id).await?.is_none());
+ Ok(())
+}
+
+/// Postgres cannot read the ciphertext, so the stored prefix is how it
+/// refuses a key filed under the wrong provider.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn the_table_refuses_a_prefix_that_is_not_the_providers(pool: PgPool) -> anyhow::Result<()> {
+ let bot_id = insert_agent(&pool, "openai/gpt-6-astra").await?;
+ let repo = PgAgentKeyRepo::new(pool);
+ for (provider, prefix) in [
+ (ModelProvider::OpenAi, "sk-ant-"),
+ (ModelProvider::OpenAi, "grok_"),
+ (ModelProvider::Anthropic, "sk-"),
+ ] {
+ assert!(
+ repo.upsert(bot_id, provider, &encrypted(), prefix)
+ .await
+ .is_err(),
+ "{prefix:?} must be refused for {provider:?}"
+ );
+ }
+ Ok(())
+}
diff --git a/crates/agent_api_keys/src/outbound/plans.rs b/crates/agent_api_keys/src/outbound/plans.rs
new file mode 100644
index 0000000000..8df310d32f
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound/plans.rs
@@ -0,0 +1,42 @@
+#[cfg(test)]
+mod test;
+
+use ai_billing::domain::EntitlementSource;
+
+use crate::domain::{AgentKeyError, AgentOwner, KeyPlans, Result};
+
+/// Agent keys come with a paid plan: Premium, Max, or an enterprise team. A
+/// person's agent goes by their plan; a team's goes by the plan of the
+/// team's payer, its owner.
+pub struct EntitlementKeyPlans<Entitlements> {
+ entitlements: Entitlements,
+}
+
+impl<Entitlements> EntitlementKeyPlans<Entitlements> {
+ /// Read plans through `entitlements`.
+ pub fn new(entitlements: Entitlements) -> Self {
+ Self { entitlements }
+ }
+}
+
+fn plan(error: impl std::error::Error + Send + Sync + 'static) -> AgentKeyError {
+ AgentKeyError::Plan(error.into())
+}
+
+#[async_trait::async_trait]
+impl<Entitlements: EntitlementSource> KeyPlans for EntitlementKeyPlans<Entitlements> {
+ async fn allows_keys(&self, owner: &AgentOwner) -> Result<bool> {
+ let payer = match owner {
+ AgentOwner::User(user) => user.clone(),
+ AgentOwner::Team(team_id) => {
+ let Some(payer) = self.entitlements.team_payer(*team_id).await.map_err(plan)?
+ else {
+ return Ok(false);
+ };
+ payer
+ }
+ };
+ let entitlement = self.entitlements.entitlement(&payer).await.map_err(plan)?;
+ Ok(entitlement.unlimited || entitlement.tier.is_paid())
+ }
+}
diff --git a/crates/agent_api_keys/src/outbound/plans/test.rs b/crates/agent_api_keys/src/outbound/plans/test.rs
new file mode 100644
index 0000000000..95ba5fe6a4
--- /dev/null
+++ b/crates/agent_api_keys/src/outbound/plans/test.rs
@@ -0,0 +1,85 @@
+use ai_billing::domain::{BillingError, Entitlement, PlanTier};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::*;
+
+const OWNER: &str = "macro|[email protected]";
+
+/// Every user is on `tier`; every team is paid for by [`OWNER`].
+struct Plans {
+ tier: PlanTier,
+ unlimited: bool,
+ team_has_payer: bool,
+}
+
+impl EntitlementSource for Plans {
+ async fn entitlement(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> std::result::Result<Entitlement, BillingError> {
+ Ok(Entitlement {
+ unlimited: self.unlimited,
+ ..Entitlement::personal(
+ MacroUserIdStr::try_from(user.as_ref().to_owned()).expect("user id"),
+ self.tier,
+ )
+ })
+ }
+
+ async fn stripe_customer_id(
+ &self,
+ _user: &MacroUserIdStr<'_>,
+ ) -> std::result::Result<Option<String>, BillingError> {
+ Ok(None)
+ }
+
+ async fn team_payer(
+ &self,
+ _team_id: Uuid,
+ ) -> std::result::Result<Option<MacroUserIdStr<'static>>, BillingError> {
+ Ok(self
+ .team_has_payer
+ .then(|| MacroUserIdStr::try_from(OWNER.to_owned()).expect("user id")))
+ }
+}
+
+#[tokio::test]
+async fn only_paid_and_enterprise_plans_include_agent_keys() {
+ let person = AgentOwner::User(MacroUserIdStr::try_from(OWNER.to_owned()).expect("user id"));
+ let team = AgentOwner::Team(Uuid::nil());
+ for (tier, unlimited, allowed) in [
+ (PlanTier::Free, false, false),
+ (PlanTier::Premium, false, true),
+ (PlanTier::Max, false, true),
+ (PlanTier::Free, true, true),
+ ] {
+ let plans = EntitlementKeyPlans::new(Plans {
+ tier,
+ unlimited,
+ team_has_payer: true,
+ });
+ for owner in [&person, &team] {
+ assert_eq!(
+ plans.allows_keys(owner).await.expect("plan read"),
+ allowed,
+ "{tier:?}, unlimited {unlimited}, {owner:?}"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn a_team_without_a_payer_has_no_agent_keys() {
+ let plans = EntitlementKeyPlans::new(Plans {
+ tier: PlanTier::Max,
+ unlimited: false,
+ team_has_payer: false,
+ });
+ assert!(
+ !plans
+ .allows_keys(&AgentOwner::Team(Uuid::nil()))
+ .await
+ .expect("plan read")
+ );
+}
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index e2b7768735..8b3cdd55e7 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -42,6 +42,9 @@
"agent-harness.decideSessionReview": "Decide Session Review",
"agent-harness.putAgentSessionSandboxSize": "Put Agent Session Sandbox Size",
"agent-harness.answerAgentSessionToolApproval": "Answer Agent Session Tool Approval",
+ "auth.deleteAgentApiKey": "Delete Agent Api Key",
+ "auth.getAgentApiKey": "Get Agent Api Key",
+ "auth.putAgentApiKey": "Put Agent Api Key",
"auth.updateAiBillingAutoReload": "Update Ai Billing Auto Reload",
"auth.createAiCreditCheckout": "Create Ai Credit Checkout",
"auth.updateAiBillingOverage": "Update Ai Billing Overage",
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index fe8355dd49..7b5eacb2e7 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -11,6 +11,7 @@ async-trait = { workspace = true }
codex_cloud_agents = { path = "../codex_cloud_agents", features = ["postgres"] }
codex_connection = { path = "../codex_connection" }
agent = { path = "../agent" }
+agent_api_keys = { path = "../agent_api_keys" }
agent-client-protocol = { workspace = true }
# The session-token claim shape and its signing, so the harness and the proxy
# cannot disagree about what a token says.
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index a7f8dfbe48..00cca0635b 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -134,6 +134,7 @@ struct AgentHarnessInner<
> {
sessions: Sessions,
admission: Arc<dyn ai_billing::AiAdmissionService>,
+ agent_keys: Arc<dyn agent_api_keys::domain::AgentKeys>,
containers: Containers,
announcer: Announcer,
runtimes: Runtimes,
@@ -366,6 +367,7 @@ where
inner: Arc::new(AgentHarnessInner {
sessions,
admission: Arc::new(ai_billing::DisabledAiAdmissionService),
+ agent_keys: Arc::new(agent_api_keys::domain::NoAgentKeys),
containers,
announcer,
runtimes,
@@ -630,6 +632,19 @@ where
self
}
+ /// Let in-memory sessions of agents with their own usable API key past
+ /// the allowance gate: their turns never run on Macro usage. Configure
+ /// before sharing the harness.
+ pub fn with_agent_keys(
+ mut self,
+ agent_keys: Arc<dyn agent_api_keys::domain::AgentKeys>,
+ ) -> Self {
+ Arc::get_mut(&mut self.inner)
+ .expect("configure agent keys before sharing the harness")
+ .agent_keys = agent_keys;
+ self
+ }
+
/// Enable explicit repository choices, authorized against the owner's reachable repositories.
pub fn with_repositories(
mut self,
diff --git a/crates/agent_harness/src/domain/service/admission.rs b/crates/agent_harness/src/domain/service/admission.rs
index f71a6253b1..7e217602dc 100644
--- a/crates/agent_harness/src/domain/service/admission.rs
+++ b/crates/agent_harness/src/domain/service/admission.rs
@@ -55,15 +55,37 @@ where
pub(super) async fn admit_session(&self, session: &AgentSession) -> Result<()> {
let kind = AgentKind::for_session(session.bot_id, &session.harness);
- if macro_funded(kind) {
- // Never use the actor or a system fallback for a missing user owner.
- self.admission
- .admit(session.owner_user()?, AiFeature::AgentSession)
- .await?;
+ if !macro_funded(kind) || self.runs_on_agent_key(kind, session).await {
+ return Ok(());
}
+ // Never use the actor or a system fallback for a missing user owner.
+ self.admission
+ .admit(session.owner_user()?, AiFeature::AgentSession)
+ .await?;
Ok(())
}
+ /// Whether an in-memory session's agent runs on its own usable key, so
+ /// its turns never spend the owner's allowance. A failed lookup leaves the
+ /// allowance gate in place.
+ async fn runs_on_agent_key(&self, kind: AgentKind, session: &AgentSession) -> bool {
+ if kind != AgentKind::InMemory {
+ return false;
+ }
+ let Ok(owner) = session.owner_user() else {
+ return false;
+ };
+ self.agent_keys
+ .usable_provider(session.bot_id.as_uuid(), owner)
+ .await
+ .inspect_err(
+ |error| tracing::error!(error = ?error, "could not read the agent's API key"),
+ )
+ .ok()
+ .flatten()
+ .is_some()
+ }
+
pub(super) async fn admit_session_id(&self, session_id: AgentSessionId) -> Result<()> {
self.admit_session(&self.sessions.get_session(session_id).await?)
.await
diff --git a/crates/agent_inmem/AGENTS.md b/crates/agent_inmem/AGENTS.md
index cbd9dbb81e..cbf5039e34 100644
--- a/crates/agent_inmem/AGENTS.md
+++ b/crates/agent_inmem/AGENTS.md
@@ -18,6 +18,9 @@ milliseconds instead of waiting on container provisioning.
and log replay on reconnect.
- `src/domain/admission.rs` + `src/outbound/approval_gate.rs`: usage/plan
admission and tool-approval gating for in-memory sessions.
+- `src/domain/model_access.rs` (`SessionModels`) and `AgentState::turn_agent_key`:
+ an agent with its own usable API key (`agent_api_keys`) runs every turn on
+ it without admission, and its session offers only that provider's models.
## Scope
diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.toml
index 358a497d97..2902e9c448 100644
--- a/crates/agent_inmem/Cargo.toml
+++ b/crates/agent_inmem/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
agent_code_mode = { path = "../agent_code_mode" }
ai_billing = { path = "../ai_billing" }
agent = { path = "../agent" }
+agent_api_keys = { path = "../agent_api_keys" }
# The egress proxy's domain service, driven in-process: the same verification,
# resolution and stamping a sandbox reaches over the wire, minus the wire.
agent_egress = { path = "../agent_egress" }
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index 09c635b720..5d46135fd4 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -13,10 +13,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
-use crate::domain::model_access::{InMemModelAccess, ModelAccess, ModelAccessError};
+use crate::domain::model_access::{InMemModelAccess, ModelAccessError, SessionModels};
use agent::types::{AssistantMessagePart, ChatMessage};
use agent::{ModelSpeed, ReasoningEffort};
use agent::{StreamAccumulator, StreamPart, ToolResponse};
+use agent_api_keys::domain::{AgentKeys, ModelProvider, UsableAgentKey};
use agent_client_protocol::schema::v1::{
AgentCapabilities, AvailableCommand, AvailableCommandInput, AvailableCommandsUpdate,
BooleanPropertySchema, CancelNotification, ContentBlock, ContentChunk,
@@ -127,6 +128,9 @@ pub struct AgentState {
pub admission: Arc<dyn AiAdmissionService>,
/// Current model permissions for the trusted session owner.
pub model_access: Arc<dyn InMemModelAccess>,
+ /// Agents' own API keys, which the session's agent's turns run on
+ /// instead of the owner's Macro allowance when it has a usable one.
+ pub agent_keys: Arc<dyn AgentKeys>,
/// Conversation state, shared with the manager so it survives reattach.
pub store: Arc<SessionStore>,
/// Every outstanding turn's cancellation token - the running turn and any
@@ -254,7 +258,69 @@ impl AgentState {
/// ACP model configuration backed by the engine's supported-model source
/// and this session's current selection.
- fn session_config_options(&self, access: ModelAccess) -> Vec<SessionConfigOption> {
+ /// The models the session may run: the owner's plan access, or the
+ /// models of the agent's key's provider when its agent has a usable key.
+ /// A failed key lookup offers the plan's models: turns then check the
+ /// key again before running.
+ async fn session_models(&self) -> Result<SessionModels, AcpError> {
+ let access = self
+ .model_access
+ .access(&self.owner)
+ .await
+ .map_err(model_access_error)?;
+ let (Some(bot), Some(user)) = (self.agent_bot(), self.owner.as_user()) else {
+ return Ok(SessionModels::new(access, None));
+ };
+ let agent_key = self
+ .agent_keys
+ .usable_provider(bot, user)
+ .await
+ .inspect_err(
+ |error| tracing::error!(error = ?error, "could not read the agent's API key"),
+ )
+ .ok()
+ .flatten();
+ Ok(SessionModels::new(access, agent_key))
+ }
+
+ /// The agent's own key this turn runs on, decrypted for it, if the
+ /// session's agent has a usable one. A key for a provider other than
+ /// `model`'s refuses the turn rather than quietly billing Macro.
+ async fn turn_agent_key(&self, model: &str) -> Result<Option<UsableAgentKey>, AcpError> {
+ let (Some(bot), Some(user)) = (self.agent_bot(), self.owner.as_user()) else {
+ return Ok(None);
+ };
+ let key =
+ self.agent_keys
+ .usable_key(bot, user)
+ .await
+ .map_err(|error| {
+ tracing::error!(error = ?error, "could not read the agent's API key");
+ AcpError::new(-32603, "The agent's API key could not be read")
+ .data(serde_json::json!({ "code": "agent_api_key_unavailable", "retryable": true }))
+ })?;
+ match key {
+ Some(key) if ModelProvider::of_model(model) != Some(key.key.provider()) => {
+ let provider = key.key.provider().display_name();
+ Err(AcpError::invalid_params().data(format!(
+ "This agent runs on its {provider} API key. Choose a {provider} model."
+ )))
+ }
+ key => Ok(key),
+ }
+ }
+
+ /// The bot id of the agent this session belongs to, if any.
+ fn agent_bot(&self) -> Option<macro_uuid::Uuid> {
+ self.store.get(&self.session_id).and_then(|session| {
+ session
+ .identity
+ .as_ref()
+ .map(|identity| identity.bot.as_uuid())
+ })
+ }
+
+ fn session_config_options(&self, access: SessionModels) -> Vec<SessionConfigOption> {
let Some(session) = self.store.get(&self.session_id) else {
return Vec::new();
};
@@ -576,18 +642,20 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
let state = Arc::clone(&state);
async move |request: NewSessionRequest, responder, connection| {
let state = Arc::clone(&state);
- let access = match state.model_access.access(&state.owner).await {
+ let access = match state.session_models().await {
Ok(access) => access,
- Err(error) => {
- return responder.respond_with_error(model_access_error(error));
- }
+ Err(error) => return responder.respond_with_error(error),
};
if let Some(model) = state
.store
.get(&state.session_id)
.map(|session| session.model.clone())
{
- state.set_model(access.default_model(&model).to_owned());
+ state.set_model(
+ access
+ .default_model(&model, state.engine.supported_models())
+ .to_owned(),
+ );
}
let acp_id = SessionId::new(macro_uuid::generate_uuid_v7().to_string());
state.bind_acp_session(acp_id.clone(), false);
@@ -607,18 +675,20 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
let state = Arc::clone(&state);
async move |request: ResumeSessionRequest, responder, connection| {
let state = Arc::clone(&state);
- let access = match state.model_access.access(&state.owner).await {
+ let access = match state.session_models().await {
Ok(access) => access,
- Err(error) => {
- return responder.respond_with_error(model_access_error(error));
- }
+ Err(error) => return responder.respond_with_error(error),
};
if let Some(model) = state
.store
.get(&state.session_id)
.map(|session| session.model.clone())
{
- state.set_model(access.default_model(&model).to_owned());
+ state.set_model(
+ access
+ .default_model(&model, state.engine.supported_models())
+ .to_owned(),
+ );
}
// Kept when the state already belongs to this ACP id -
// either this process served the session, or a cold
@@ -652,6 +722,7 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
agent.turn.ttft_ms = tracing::field::Empty,
agent.turn.first_text_ms = tracing::field::Empty,
agent.turn.admission_wait_ms = tracing::field::Empty,
+ agent.turn.agent_key = tracing::field::Empty,
agent.turn.lock_wait_ms = tracing::field::Empty,
agent.turn.stop_reason = tracing::field::Empty,
agent.turn.text_chars = tracing::field::Empty,
@@ -725,11 +796,9 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
if let Err(error) = state.expect_session(&request.session_id) {
return responder.respond_with_error(error);
}
- let access = match state.model_access.access(&state.owner).await {
+ let access = match state.session_models().await {
Ok(access) => access,
- Err(error) => {
- return responder.respond_with_error(model_access_error(error));
- }
+ Err(error) => return responder.respond_with_error(error),
};
let Some(value) = request.value.as_value_id() else {
return responder.respond_with_error(
@@ -854,26 +923,36 @@ async fn run_turn(
let span = tracing::Span::current();
span.record("agent.turn.lock_wait_ms", elapsed_ms(started));
let admission_started = Instant::now();
- // Check at execution time, not enqueue time. Cancellation stays responsive
- // even if billing is slow, and neither denial nor cancellation adds history.
- tokio::select! {
+ let session_model = state
+ .store
+ .get(&state.session_id)
+ .map(|session| session.model.clone())
+ .unwrap_or_default();
+ // An agent with its own usable key runs every turn on it, never on the
+ // owner's allowance; one without runs on Macro usage.
+ let agent_key = tokio::select! {
biased;
_ = cancel.cancelled() => return Ok(StopReason::Cancelled),
- result = admit_turn(state.admission.as_ref(), &state.owner) => result.map_err(|error|
- AcpError::new(-32603, error.to_string()).data(serde_json::json!({
- "code": error.code(), "retryable": error.is_retryable(),
- }))
- )?,
+ key = state.turn_agent_key(&session_model) => key?,
+ };
+ span.record("agent.turn.agent_key", agent_key.is_some());
+ // Check at execution time, not enqueue time. Cancellation stays responsive
+ // even if billing is slow, and neither denial nor cancellation adds history.
+ if agent_key.is_none() {
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => return Ok(StopReason::Cancelled),
+ result = admit_turn(state.admission.as_ref(), &state.owner) => result.map_err(|error|
+ AcpError::new(-32603, error.to_string()).data(serde_json::json!({
+ "code": error.code(), "retryable": error.is_retryable(),
+ }))
+ )?,
+ }
}
span.record(
"agent.turn.admission_wait_ms",
elapsed_ms(admission_started),
);
- let session_model = state
- .store
- .get(&state.session_id)
- .map(|session| session.model.clone())
- .unwrap_or_default();
if compaction::too_long(&prompt, &session_model) {
return Err(AcpError::invalid_params().data(
"This message is too long. Split it into smaller messages or attach it as a file.",
@@ -898,10 +977,15 @@ async fn run_turn(
identity,
instructions,
} = state.turn_input(&prompt);
+ // The turn already holds the key, so its provider decides the models
+ // without asking for the key again.
let access = tokio::select! {
biased;
_ = cancel.cancelled() => return Ok(StopReason::Cancelled),
- result = state.model_access.access(&state.owner) => result.map_err(model_access_error)?,
+ result = state.model_access.access(&state.owner) => SessionModels::new(
+ result.map_err(model_access_error)?,
+ agent_key.as_ref().map(|key| key.key.provider()),
+ ),
};
if !access.allows(&model) {
return Err(model_access_error(ModelAccessError::Forbidden));
@@ -944,6 +1028,7 @@ async fn run_turn(
.clone()
.map(|requester| requester as SharedUserInputRequester),
reviewer: requester.map(|requester| requester as Arc<dyn UserToolReviewer>),
+ agent_key,
});
let mut accumulator = StreamAccumulator::new();
diff --git a/crates/agent_inmem/src/domain/agent/compaction.rs b/crates/agent_inmem/src/domain/agent/compaction.rs
index 5e41723005..468edc5284 100644
--- a/crates/agent_inmem/src/domain/agent/compaction.rs
+++ b/crates/agent_inmem/src/domain/agent/compaction.rs
@@ -594,6 +594,7 @@ async fn complete(
cancel: call,
user_input: None,
reviewer: None,
+ agent_key: None,
});
let mut text = String::new();
loop {
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 252be631f9..1e1d66c2b4 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -93,7 +93,14 @@ async fn with_model_access<Engine: TurnEngine, Out>(
model_access: Arc<dyn InMemModelAccess>,
scenario: impl AsyncFnOnce(ConnectionTo<Agent>, SessionId, Arc<AgentState>) -> Out,
) -> (Vec<SessionNotification>, Vec<SessionConfigOption>, Out) {
- let (notifications, recorded) = record(engine, admission, model_access, scenario).await;
+ let (notifications, recorded) = record(
+ engine,
+ admission,
+ model_access,
+ Arc::new(agent_api_keys::domain::NoAgentKeys),
+ scenario,
+ )
+ .await;
let (config_options, out) = recorded.out;
(notifications, config_options, out)
}
@@ -108,6 +115,7 @@ async fn with_summaries<Engine: TurnEngine, Out>(
engine,
Arc::new(DisabledAiAdmissionService),
Arc::new(crate::testing::TestModelAccess::paid()),
+ Arc::new(agent_api_keys::domain::NoAgentKeys),
scenario,
)
.await;
@@ -121,6 +129,7 @@ async fn record<Engine: TurnEngine, Out>(
engine: Arc<Engine>,
admission: Arc<dyn AiAdmissionService>,
model_access: Arc<dyn InMemModelAccess>,
+ agent_keys: Arc<dyn agent_api_keys::domain::AgentKeys>,
scenario: impl AsyncFnOnce(ConnectionTo<Agent>, SessionId, Arc<AgentState>) -> Out,
) -> (
Vec<SessionNotification>,
@@ -139,6 +148,7 @@ async fn record<Engine: TurnEngine, Out>(
),
engine,
admission,
+ agent_keys,
model_access,
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
@@ -481,6 +491,132 @@ async fn cancel_during_billing_does_not_start_engine_or_write_history() {
assert!(engine.requests().is_empty());
}
+/// An agent with its own key for `provider`, or none.
+struct OneAgentKey(Option<agent_api_keys::domain::ModelProvider>);
+
+#[async_trait::async_trait]
+impl agent_api_keys::domain::AgentKeys for OneAgentKey {
+ async fn usable_provider(
+ &self,
+ _bot_id: macro_uuid::Uuid,
+ _user: &MacroUserIdStr<'_>,
+ ) -> agent_api_keys::domain::Result<Option<agent_api_keys::domain::ModelProvider>> {
+ Ok(self.0)
+ }
+
+ async fn usable_key(
+ &self,
+ bot_id: macro_uuid::Uuid,
+ _user: &MacroUserIdStr<'_>,
+ ) -> agent_api_keys::domain::Result<Option<agent_api_keys::domain::UsableAgentKey>> {
+ Ok(self
+ .0
+ .map(|provider| agent_api_keys::domain::UsableAgentKey {
+ bot_id,
+ key: agent_api_keys::domain::ProviderApiKey::parse(provider, "sk-ant-api03-abc")
+ .expect("valid key"),
+ }))
+ }
+}
+
+fn be_agent(state: &AgentState, bot: bot_id::BotId) {
+ state
+ .store
+ .get_mut(&state.session_id)
+ .expect("session")
+ .identity = Some(crate::domain::engine::AgentIdentity {
+ bot,
+ name: "Grunk".to_owned(),
+ handle: "grunk".to_owned(),
+ });
+}
+
+#[tokio::test]
+async fn an_agent_with_its_own_key_runs_turns_on_it_without_spending_the_allowance() {
+ let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content(
+ "reply".into(),
+ )]));
+ let admission = Arc::new(TestAdmission::new(Err(AiAdmissionError::Denied(
+ DenyReason::AllowanceExhausted,
+ ))));
+ let bot = bot_id::BotId::new_from_uuid(macro_uuid::generate_uuid_v7());
+ record(
+ engine.clone(),
+ admission.clone(),
+ Arc::new(crate::testing::TestModelAccess::paid()),
+ Arc::new(OneAgentKey(Some(
+ agent_api_keys::domain::ModelProvider::Anthropic,
+ ))),
+ async |connection, session, state| {
+ be_agent(&state, bot);
+ connection
+ .send_request(text_prompt(&session, "hello"))
+ .block_task()
+ .await
+ .expect("the turn runs on the agent's key");
+ },
+ )
+ .await;
+
+ assert_eq!(engine.requests()[0].agent_key, Some(bot.as_uuid()));
+ assert!(
+ admission.calls.lock().unwrap().is_empty(),
+ "the owner's allowance is never asked"
+ );
+}
+
+#[tokio::test]
+async fn an_agent_with_a_key_offers_only_its_providers_models() {
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let bot = bot_id::BotId::new_from_uuid(macro_uuid::generate_uuid_v7());
+ let (_, recorded) = record(
+ engine,
+ Arc::new(DisabledAiAdmissionService),
+ // A free plan alone would offer only the free model.
+ Arc::new(crate::testing::TestModelAccess::new(
+ crate::domain::model_access::ModelAccess::Free,
+ )),
+ Arc::new(OneAgentKey(Some(
+ agent_api_keys::domain::ModelProvider::Anthropic,
+ ))),
+ async |connection, session, state| {
+ // Attach seeds the agent and its model before `session/new`; this
+ // harness opens the session first, so put them back.
+ be_agent(&state, bot);
+ use_model(&state, "anthropic/claude-sonnet-5-5");
+ let resumed = connection
+ .send_request(ResumeSessionRequest::new(session.clone(), "/"))
+ .block_task()
+ .await
+ .expect("resumed");
+ let other = connection
+ .send_request(SetSessionConfigOptionRequest::new(
+ session.clone(),
+ MODEL_CONFIG_ID,
+ SessionConfigValueId::new("other-model"),
+ ))
+ .block_task()
+ .await;
+ (resumed.config_options.unwrap_or_default(), other.is_err())
+ },
+ )
+ .await;
+ let (options, other_refused) = recorded.out.1;
+
+ let selection = agent_fold::domain::model_selection::model_selection(&options)
+ .expect("resume should advertise a model select");
+ assert_eq!(selection.current, "anthropic/claude-sonnet-5-5");
+ assert_eq!(
+ selection
+ .options
+ .iter()
+ .map(|model| model.id.as_str())
+ .collect::<Vec<_>>(),
+ vec!["anthropic/claude-sonnet-5-5"]
+ );
+ assert!(other_refused, "another provider's model cannot be picked");
+}
+
#[tokio::test]
async fn new_session_advertises_the_engine_supported_models() {
let (_notifications, config_options, ()) =
@@ -1535,6 +1671,7 @@ async fn serve_with_mcp(
),
engine,
admission: Arc::new(DisabledAiAdmissionService),
+ agent_keys: Arc::new(agent_api_keys::domain::NoAgentKeys),
model_access: Arc::new(crate::testing::TestModelAccess::paid()),
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
@@ -1591,6 +1728,7 @@ async fn session_new_dials_the_advertised_servers_except_macros_own() {
),
engine: Arc::new(ScriptedEngine::new(Vec::new())),
admission: Arc::new(DisabledAiAdmissionService),
+ agent_keys: Arc::new(agent_api_keys::domain::NoAgentKeys),
model_access: Arc::new(crate::testing::TestModelAccess::paid()),
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
@@ -1680,6 +1818,7 @@ async fn first_prompt_waits_for_background_mcp_connect() {
),
engine: Arc::clone(&engine) as Arc<dyn TurnEngine>,
admission: Arc::new(DisabledAiAdmissionService),
+ agent_keys: Arc::new(agent_api_keys::domain::NoAgentKeys),
model_access: Arc::new(crate::testing::TestModelAccess::paid()),
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
@@ -1784,6 +1923,7 @@ where
),
engine,
admission: Arc::new(DisabledAiAdmissionService),
+ agent_keys: Arc::new(agent_api_keys::domain::NoAgentKeys),
model_access: Arc::new(crate::testing::TestModelAccess::paid()),
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rs
index 5901e32c10..abce24acc9 100644
--- a/crates/agent_inmem/src/domain/engine.rs
+++ b/crates/agent_inmem/src/domain/engine.rs
@@ -6,6 +6,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use agent::ReasoningEffort;
use agent::types::ChatMessage;
use agent::{AgentError, StreamPart};
+use agent_api_keys::domain::UsableAgentKey;
use ai_tools::user_tool_review::UserToolReviewer;
use bot_id::BotId;
use mcp_toolset::RemoteMcpToolSet;
@@ -77,6 +78,10 @@ pub struct TurnRequest {
/// rejected - before the model reads its result. Absent for the same
/// reason as `user_input`; a pending call then stays pending.
pub reviewer: Option<Arc<dyn UserToolReviewer>>,
+ /// The agent's own key the turn's model calls run on instead of Macro's,
+ /// with their usage recorded against it rather than the owner's
+ /// allowance. `None` runs on Macro.
+ pub agent_key: Option<UsableAgentKey>,
}
/// Whether a model call answers the user or condenses their conversation.
diff --git a/crates/agent_inmem/src/domain/model_access.rs b/crates/agent_inmem/src/domain/model_access.rs
index 18ffd73315..31d8907041 100644
--- a/crates/agent_inmem/src/domain/model_access.rs
+++ b/crates/agent_inmem/src/domain/model_access.rs
@@ -1,5 +1,6 @@
//! Plan-based model access for the in-memory runtime only.
+use agent_api_keys::domain::ModelProvider;
use async_trait::async_trait;
use chat::domain::models::FREE_MODEL;
use model_owner::Owner;
@@ -39,6 +40,67 @@ impl ModelAccess {
}
}
+/// The models a session may run: its owner's plan access, unless the
+/// session's agent runs on its own key, in which case it is that key's
+/// provider's models. The plan limits only what Macro pays for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SessionModels {
+ access: ModelAccess,
+ agent_key: Option<ModelProvider>,
+}
+
+impl SessionModels {
+ /// Models from `access`, or from the `agent_key` provider when the
+ /// session's agent has a usable key.
+ #[must_use]
+ pub fn new(access: ModelAccess, agent_key: Option<ModelProvider>) -> Self {
+ Self { access, agent_key }
+ }
+
+ /// The provider of the agent's key the session's turns run on, if any.
+ #[must_use]
+ pub fn agent_key(self) -> Option<ModelProvider> {
+ self.agent_key
+ }
+
+ /// Whether the session may run `model`; runtime support is checked
+ /// separately.
+ #[must_use]
+ pub fn allows(self, model: &str) -> bool {
+ match self.agent_key {
+ Some(provider) => ModelProvider::of_model(model) == Some(provider),
+ None => self.access.allows(model),
+ }
+ }
+
+ /// Keep a persisted/default model the session may run. Without a key, an
+ /// inaccessible one becomes the free model; with one, a model from
+ /// another provider (saved before the key) becomes the first `supported`
+ /// model the key can run.
+ #[must_use]
+ pub fn default_model<'a>(self, configured: &'a str, supported: &[&'a str]) -> &'a str {
+ match self.agent_key {
+ Some(_) if self.allows(configured) => configured,
+ Some(_) => supported
+ .iter()
+ .copied()
+ .find(|model| self.allows(model))
+ .unwrap_or(configured),
+ None => self.access.default_model(configured),
+ }
+ }
+
+ /// The supported models the session may select.
+ #[must_use]
+ pub fn models<'a>(self, supported: &[&'a str]) -> Vec<&'a str> {
+ supported
+ .iter()
+ .copied()
+ .filter(|model| self.allows(model))
+ .collect()
+ }
+}
+
/// Failure to resolve or enforce model access. Lookup failures fail closed.
#[derive(Debug, Clone, Copy, thiserror::Error)]
pub enum ModelAccessError {
diff --git a/crates/agent_inmem/src/domain/model_access/test.rs b/crates/agent_inmem/src/domain/model_access/test.rs
index 582414dd43..750c43fd3f 100644
--- a/crates/agent_inmem/src/domain/model_access/test.rs
+++ b/crates/agent_inmem/src/domain/model_access/test.rs
@@ -88,3 +88,35 @@ async fn non_user_owners_cannot_bypass_model_access() {
Err(ModelAccessError::Unavailable)
));
}
+
+#[test]
+fn an_agents_key_replaces_the_plan_with_its_providers_models() {
+ let supported = [
+ "anthropic/claude-sonnet-5-5",
+ "openai/gpt-6-astra",
+ FREE_MODEL,
+ ];
+ let keyed = SessionModels::new(
+ ModelAccess::Free,
+ Some(agent_api_keys::domain::ModelProvider::Anthropic),
+ );
+ assert_eq!(keyed.models(&supported), ["anthropic/claude-sonnet-5-5"]);
+ assert!(!keyed.allows(FREE_MODEL));
+ assert_eq!(
+ keyed.default_model("anthropic/claude-sonnet-5-5", &supported),
+ "anthropic/claude-sonnet-5-5",
+ "a free plan does not clamp a model the agent's key pays for"
+ );
+ assert_eq!(
+ keyed.default_model("openai/gpt-6-astra", &supported),
+ "anthropic/claude-sonnet-5-5",
+ "a model saved before the key moves to one the key can run"
+ );
+
+ let plan = SessionModels::new(ModelAccess::Free, None);
+ assert_eq!(plan.models(&supported), [FREE_MODEL]);
+ assert_eq!(
+ plan.default_model("anthropic/claude-sonnet-5-5", &supported),
+ FREE_MODEL
+ );
+}
diff --git a/crates/agent_inmem/src/outbound/local_attachments/test.rs b/crates/agent_inmem/src/outbound/local_attachments/test.rs
index f883b9e5e9..eed6747ec5 100644
--- a/crates/agent_inmem/src/outbound/local_attachments/test.rs
+++ b/crates/agent_inmem/src/outbound/local_attachments/test.rs
@@ -159,6 +159,7 @@ fn request(messages: Vec<ChatMessage>) -> TurnRequest {
cancel: CancellationToken::new(),
user_input: None,
reviewer: None,
+ agent_key: None,
}
}
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index da5e4aaf6e..1601879c52 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -8,6 +8,7 @@
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
+use agent_api_keys::domain::{AgentKeys, NoAgentKeys};
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::channel::Channel;
use agent_runtime_protocol::domain::connection::{RuntimeConnection, ServerChannel};
@@ -69,6 +70,7 @@ impl Drop for LiveAgent {
pub struct InMemAgentManager {
engine: Arc<dyn TurnEngine>,
admission: Arc<dyn AiAdmissionService>,
+ agent_keys: Arc<dyn AgentKeys>,
model_access: Arc<dyn crate::domain::model_access::InMemModelAccess>,
frames: Arc<dyn FrameSource>,
mcp: Arc<dyn DynMcpToolConnector>,
@@ -96,6 +98,7 @@ impl InMemAgentManager {
engine,
model_access,
admission: Arc::new(DisabledAiAdmissionService),
+ agent_keys: Arc::new(NoAgentKeys),
frames,
mcp,
enable_dev_commands: false,
@@ -113,6 +116,14 @@ impl InMemAgentManager {
self
}
+ /// Let agents' turns run on their own API keys. Without this, every turn
+ /// runs on Macro's allowance.
+ #[must_use]
+ pub fn with_agent_keys(mut self, agent_keys: Arc<dyn AgentKeys>) -> Self {
+ self.agent_keys = agent_keys;
+ self
+ }
+
/// The egress token `attach` was handed for `session`, if this process
/// still holds it.
#[must_use]
@@ -190,6 +201,7 @@ impl InMemAgentManager {
owner: facts.owner,
engine: Arc::clone(&self.engine),
admission: Arc::clone(&self.admission),
+ agent_keys: Arc::clone(&self.agent_keys),
model_access: Arc::clone(&self.model_access),
store: Arc::clone(&self.store),
active_cancel: std::sync::Mutex::new(Vec::new()),
diff --git a/crates/agent_inmem/src/outbound/rig_engine/test/tool_mode.rs b/crates/agent_inmem/src/outbound/rig_engine/test/tool_mode.rs
index d68d3453ee..57d5bf543b 100644
--- a/crates/agent_inmem/src/outbound/rig_engine/test/tool_mode.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine/test/tool_mode.rs
@@ -61,6 +61,7 @@ fn request(mcp_tools: Option<RemoteMcpToolSet>) -> TurnRequest {
cancel: CancellationToken::new(),
user_input: None,
reviewer: None,
+ agent_key: None,
}
}
diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rs
index 1f714a077e..534f0f043e 100644
--- a/crates/agent_inmem/src/rig_engine.rs
+++ b/crates/agent_inmem/src/rig_engine.rs
@@ -451,6 +451,7 @@ async fn drive_turn(
cancel,
user_input,
reviewer,
+ agent_key,
} = request;
let started = tokio::time::Instant::now();
@@ -473,6 +474,13 @@ async fn drive_turn(
// reads no memory, offers the model no tools, and is read, not shown, so
// no opening line races it.
let summarizing = purpose == crate::domain::engine::TurnPurpose::Summary;
+ if let Some(key) = &agent_key
+ && agent_api_keys::domain::ModelProvider::of_model(&model) != Some(key.key.provider())
+ {
+ return Err(AgentError::Other(anyhow::anyhow!(
+ "the agent's API key does not serve {model}"
+ )));
+ }
// Started before anything else so its line is out before the turn's
// model has a first token.
@@ -499,7 +507,9 @@ async fn drive_turn(
)
};
// A closed receiver has no verdict, and the turn's own stream follows.
- let mut opening_line = if summarizing {
+ // The opening line runs on Macro's own fast model, so a turn the agent's
+ // key pays for goes without one.
+ let mut opening_line = if summarizing || agent_key.is_some() {
mpsc::channel(1).1
} else {
opener_span.in_scope(|| {
@@ -585,6 +595,16 @@ async fn drive_turn(
.with_reasoning_effort(reasoning_effort)
.with_speed(speed)?
.with_genai_telemetry(false);
+ // Only the loop's own model calls run on the agent's key, so only they are
+ // recorded against it; tools keep `usage_ctx`, since they call models on
+ // Macro's keys.
+ let loop_usage = match agent_key {
+ Some(key) => {
+ agent_loop = agent_loop.with_provider_api_key(key.key.expose())?;
+ usage_ctx.with_agent_api_key(key.bot_id)
+ }
+ None => usage_ctx,
+ };
let mut reviewed_tools = Vec::new();
if let Some(reviewer) = reviewer.filter(|_| !summarizing) {
reviewed_tools = toolset.user_tools.keys().cloned().collect();
@@ -653,7 +673,7 @@ async fn drive_turn(
reviewed_tools,
});
let session = agent_loop
- .session(toolset, Arc::new(tool_context), system_prompt, usage_ctx)
+ .session(toolset, Arc::new(tool_context), system_prompt, loop_usage)
.await;
let (mut session, loop_cancel) = session.cancellable();
diff --git a/crates/agent_inmem/src/testing.rs b/crates/agent_inmem/src/testing.rs
index 3d851f60fa..85007cc844 100644
--- a/crates/agent_inmem/src/testing.rs
+++ b/crates/agent_inmem/src/testing.rs
@@ -161,6 +161,8 @@ pub(crate) struct RecordedTurn {
pub(crate) instructions: Option<String>,
/// Who the agent is, as handed to the engine.
pub(crate) identity: Option<AgentIdentity>,
+ /// The agent whose own key the turn ran on, if any.
+ pub(crate) agent_key: Option<macro_uuid::Uuid>,
}
impl ScriptedEngine {
@@ -211,6 +213,7 @@ impl TurnEngine for ScriptedEngine {
.collect(),
instructions: request.instructions.clone(),
identity: request.identity.clone(),
+ agent_key: request.agent_key.as_ref().map(|key| key.bot_id),
});
let (parts, receiver) = mpsc::channel(64);
let script = self.script.clone();
diff --git a/crates/ai_billing/src/composition.rs b/crates/ai_billing/src/composition.rs
index d5c36bcadc..eb813a19b3 100644
--- a/crates/ai_billing/src/composition.rs
+++ b/crates/ai_billing/src/composition.rs
@@ -86,6 +86,30 @@ pub fn pg_admission_service(
)
}
+/// Postgres-backed [`crate::domain::EntitlementSource`]: plans from roles,
+/// seats from team membership.
+#[cfg(feature = "pg-admission")]
+pub type PgEntitlementSource = RolesTeamsEntitlementSource<
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl<
+ roles_and_permissions::outbound::pgpool::MacroDB,
+ roles_and_permissions::outbound::pgpool::MacroDB,
+ >,
+ teams::outbound::team_repo::TeamRepositoryImpl,
+>;
+
+/// Compose [`PgEntitlementSource`] over one database pool, for hosts that
+/// only read plans.
+#[cfg(feature = "pg-admission")]
+pub fn pg_entitlement_source(pool: PgPool) -> PgEntitlementSource {
+ RolesTeamsEntitlementSource::new(
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ ),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(pool),
+ )
+}
+
/// Postgres-backed [`CreditGrantService`] for operator tools.
#[cfg(feature = "pg-admission")]
pub type PgCreditGrantService = crate::domain::CreditGrantService<
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
index 6113dcff2b..e066e20b2b 100644
--- a/crates/ai_billing/src/domain/service/test.rs
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -3436,6 +3436,7 @@ async fn assert_upgrade_resets_snapshot_and_gate(pool: sqlx::PgPool, from: PlanT
feature: AiFeature::Chat,
user: payer.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input: 1_000_000,
diff --git a/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rs b/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rs
index c4dad16d76..2b3054c781 100644
--- a/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rs
+++ b/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rs
@@ -21,6 +21,7 @@ async fn usage_row(
feature: AiFeature::Chat,
user: user.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input: 1_000,
diff --git a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
index a763b83e7e..04bc21a065 100644
--- a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
+++ b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
@@ -15,6 +15,7 @@ fn completion(
feature,
user,
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input: 1_000_000,
@@ -309,6 +310,7 @@ async fn priced_cache_tokens_count_through_the_stored_total(pool: PgPool) {
feature: AiFeature::Chat,
user: user.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount,
model: "claude-opus-5".to_string(),
@@ -354,6 +356,7 @@ async fn unpriced_cache_tokens_fall_back_to_the_opus_5_cache_rates(pool: PgPool)
feature: AiFeature::Chat,
user: user.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input: 1_000_000,
diff --git a/crates/ai_usage/AGENTS.md b/crates/ai_usage/AGENTS.md
index f144c6ca24..b1c26f3f3f 100644
--- a/crates/ai_usage/AGENTS.md
+++ b/crates/ai_usage/AGENTS.md
@@ -55,6 +55,9 @@ ledger decisions, plus a flexible admin query API.
directly: it applies `ai_pricing_discount`, a per-model input and output
percent off (input's also covers cache and audio rates). Gemini 3.8 Flash
is discounted to DeepSeek V4.1 Flash's $0.30 / $1.20.
+- `UsageContext::with_agent_api_key` marks usage an agent's own API key paid
+ for: it is stored with `agent_api_key_id` and never counted. Set it only
+ on calls that actually authenticate with that key.
## Related
diff --git a/crates/ai_usage/src/domain/ports.rs b/crates/ai_usage/src/domain/ports.rs
index 48ba362857..687536a48e 100644
--- a/crates/ai_usage/src/domain/ports.rs
+++ b/crates/ai_usage/src/domain/ports.rs
@@ -237,6 +237,9 @@ pub struct CompletionUsage {
pub user: MacroUserIdStr<'static>,
/// The entity the completion related to, if any.
pub entity: Option<Uuid>,
+ /// The agent's own API key that paid for the completion, if Macro
+ /// did not. Such usage is recorded but never counted toward a quota.
+ pub agent_api_key_id: Option<Uuid>,
/// Token/audio usage and cost.
pub cost: Usage,
}
@@ -288,6 +291,8 @@ pub struct UsageEvent {
pub model: String,
/// The invocation's billable quantity.
pub amount: UsageAmount,
+ /// The agent's own API key that paid for the completion, if any.
+ pub agent_api_key_id: Option<Uuid>,
}
/// The constant attributes of a logical completion (everything except the model
@@ -303,6 +308,9 @@ pub struct UsageContext {
pub user: MacroUserIdStr<'static>,
/// The entity the completion relates to, if any.
pub entity: Option<Uuid>,
+ /// The agent's own API key the completion runs on, when Macro is
+ /// not paying for it.
+ pub agent_api_key_id: Option<Uuid>,
}
impl UsageContext {
@@ -312,6 +320,7 @@ impl UsageContext {
feature,
user,
entity: None,
+ agent_api_key_id: None,
}
}
@@ -321,6 +330,7 @@ impl UsageContext {
feature,
user: SYSTEM_USER_ID.clone(),
entity: None,
+ agent_api_key_id: None,
}
}
@@ -330,6 +340,14 @@ impl UsageContext {
self
}
+ /// Attribute the completion to an agent's own API key. Only for calls
+ /// that actually authenticate with that key: the usage is not counted
+ /// toward the user's Macro allowance.
+ pub fn with_agent_api_key(mut self, agent_api_key_id: Uuid) -> Self {
+ self.agent_api_key_id = Some(agent_api_key_id);
+ self
+ }
+
/// Build a [`UsageEvent`] from this context plus a completion's model and
/// measured usage. Token callers normalize their provider's counters into
/// disjoint [`UsageAmount::Tokens`] dimensions first.
@@ -340,6 +358,7 @@ impl UsageContext {
entity: self.entity,
model,
amount,
+ agent_api_key_id: self.agent_api_key_id,
}
}
@@ -351,6 +370,7 @@ impl UsageContext {
entity: self.entity,
model,
amount: UsageAmount::Audio { duration },
+ agent_api_key_id: self.agent_api_key_id,
}
}
}
diff --git a/crates/ai_usage/src/domain/service.rs b/crates/ai_usage/src/domain/service.rs
index 0f199b1b3c..8147c52afc 100644
--- a/crates/ai_usage/src/domain/service.rs
+++ b/crates/ai_usage/src/domain/service.rs
@@ -16,6 +16,11 @@ fn require_admin(actor: &macro_user_id::user_id::MacroUserIdStr<'_>) -> Result<(
}
}
+/// Usage paid for by an agent's own API key never counts toward a quota.
+fn counts(enforcement: AiUsageEnforcement, event: &UsageEvent) -> bool {
+ event.agent_api_key_id.is_none() && enforcement.should_count(&event.user, event.feature)
+}
+
/// The cost service. Generic over the storage [`UsageRepo`].
///
/// Implements:
@@ -46,7 +51,7 @@ impl<Repo> UsageServiceImpl<Repo> {
/// Whether this recorder will persist the event as quota-counted usage.
/// Settlement wrappers use the same policy as persistence, never a second flag.
pub fn counts_usage(&self, event: &UsageEvent) -> bool {
- self.enforcement.should_count(&event.user, event.feature)
+ counts(self.enforcement, event)
}
}
@@ -71,7 +76,7 @@ where
enforcement: AiUsageEnforcement,
event: UsageEvent,
) -> Result<()> {
- let count_usage = enforcement.should_count(&event.user, event.feature);
+ let count_usage = counts(enforcement, &event);
// Store and price by the bare api id; chat hands us `provider/model`.
let model = normalize_model_id(&event.model).to_string();
let mut cost = Usage {
@@ -100,6 +105,7 @@ where
feature: event.feature,
user: event.user,
entity: event.entity,
+ agent_api_key_id: event.agent_api_key_id,
cost,
};
diff --git a/crates/ai_usage/src/domain/service/test.rs b/crates/ai_usage/src/domain/service/test.rs
index cf1a304cb1..5c5b635da7 100644
--- a/crates/ai_usage/src/domain/service/test.rs
+++ b/crates/ai_usage/src/domain/service/test.rs
@@ -10,6 +10,7 @@ fn completion(feature: AiFeature, total: Option<f32>) -> CompletionUsage {
feature,
user: user(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input: 1000,
@@ -384,6 +385,31 @@ async fn both_recording_paths_persist_the_same_counting_policy() {
}
}
+#[tokio::test]
+async fn usage_on_a_team_provider_key_is_recorded_against_it_and_never_counted() {
+ let repo = FakeRepo::default();
+ let service = UsageServiceImpl::new(repo.clone()).with_enforcement(AiUsageEnforcement::Enabled);
+ let actor = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ let key = macro_uuid::generate_uuid_v7();
+ let event = UsageContext::new(AiFeature::AgentSession, actor)
+ .with_agent_api_key(key)
+ .into_event(
+ "anthropic/claude-opus-5".into(),
+ UsageAmount::Tokens {
+ input: 100,
+ output: 200,
+ cache_read: 0,
+ cache_write: 0,
+ },
+ );
+
+ assert!(!service.counts_usage(&event));
+ service.record_now(event).await.unwrap();
+
+ assert_eq!(*repo.counting.lock().unwrap(), vec![false]);
+ assert_eq!(repo.rows.lock().unwrap()[0].agent_api_key_id, Some(key));
+}
+
#[tokio::test]
async fn default_disabled_writes_do_not_change_previously_counted_usage() {
let repo = FakeRepo::default();
diff --git a/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
index 9946a861c7..e91c47d170 100644
--- a/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
+++ b/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
@@ -385,6 +385,7 @@ async fn legacy_analytics_writes_and_repricing_leave_financial_evidence_unchange
feature: AiFeature::Chat,
user: SYSTEM_USER_ID.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount,
model: "test-model".into(),
diff --git a/crates/ai_usage/src/outbound/pg_usage_repo.rs b/crates/ai_usage/src/outbound/pg_usage_repo.rs
index 8c01c5562e..cf20c9a5f2 100644
--- a/crates/ai_usage/src/outbound/pg_usage_repo.rs
+++ b/crates/ai_usage/src/outbound/pg_usage_repo.rs
@@ -84,9 +84,11 @@ impl UsageRepo for PgUsageRepo {
price_per_million_in, price_per_million_out,
price_per_million_cache_read, price_per_million_cache_write,
price_per_audio_minute, total,
- count_usage
+ count_usage, agent_api_key_id
+ )
+ VALUES (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
"#,
id,
usage.feature.to_string(),
@@ -105,6 +107,7 @@ impl UsageRepo for PgUsageRepo {
per_audio_minute,
total,
count_usage,
+ usage.agent_api_key_id,
)
.execute(&self.inner)
.await?;
@@ -224,6 +227,7 @@ impl UsageRepo for PgUsageRepo {
feature,
user_id,
entity,
+ agent_api_key_id,
model,
input_tokens,
output_tokens,
@@ -281,6 +285,7 @@ impl UsageRepo for PgUsageRepo {
feature,
user,
entity: r.entity,
+ agent_api_key_id: r.agent_api_key_id,
cost: Usage {
amount: match r.audio_seconds {
Some(seconds) => UsageAmount::Audio {
diff --git a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
index c6e97e1f3b..370ce8f483 100644
--- a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
+++ b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs
@@ -9,6 +9,7 @@ fn completion(feature: AiFeature, model: &str, input: u64, output: u64) -> Compl
feature,
user: SYSTEM_USER_ID.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input,
@@ -88,6 +89,52 @@ async fn seeded_pricing_is_available(pool: PgPool) {
assert_eq!(repo.get_pricing("nonexistent-model").await.unwrap(), None);
}
+/// Usage on an agent's own key references that key, and forgetting the key
+/// keeps the usage while dropping the reference.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn usage_references_the_agent_key_that_paid_for_it(pool: PgPool) {
+ let key_id = sqlx::query_scalar!(
+ r#"
+ WITH owner_identity AS (
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES (gen_random_uuid(), '[email protected]', '[email protected]', 'stripe_owner')
+ RETURNING id
+ ), owner_profile AS (
+ INSERT INTO "User" ("id", "email", "macro_user_id")
+ SELECT 'macro|[email protected]', '[email protected]', id FROM owner_identity
+ RETURNING "id"
+ ), agent AS (
+ INSERT INTO bots (id, kind, name, handle, has_agent, owner_user_id)
+ SELECT gen_random_uuid(), 'owned', 'Agent', 'agent', true, "id" FROM owner_profile
+ RETURNING id
+ )
+ INSERT INTO agent_api_keys (
+ bot_id, provider, key_ciphertext, encryption_version, kms_key_id, key_prefix
+ )
+ SELECT id, 'anthropic', '\x01'::bytea, 1, 'kms-key', 'sk-ant-' FROM agent
+ RETURNING bot_id
+ "#
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ let repo = PgUsageRepo::new(pool.clone());
+ let mut row = completion(AiFeature::AgentSession, "claude-opus-5", 10, 20);
+ row.agent_api_key_id = Some(key_id);
+ repo.insert_usage(&row, false).await.unwrap();
+
+ let rows = repo.query_usage(&UsageApiParams::default()).await.unwrap();
+ assert_eq!(rows[0].agent_api_key_id, Some(key_id));
+
+ sqlx::query!("DELETE FROM agent_api_keys WHERE bot_id = $1", key_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let rows = repo.query_usage(&UsageApiParams::default()).await.unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].agent_api_key_id, None);
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn insert_and_query_roundtrips(pool: PgPool) {
let repo = PgUsageRepo::new(pool);
@@ -462,6 +509,7 @@ async fn cached_token_usage_roundtrips_with_its_cache_rates(pool: PgPool) {
feature: AiFeature::AgentSession,
user: SYSTEM_USER_ID.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount,
model: "claude-opus-5".to_string(),
@@ -506,6 +554,7 @@ async fn repricing_bills_cache_tokens_and_unprices_them_without_a_cache_rate(poo
feature: AiFeature::AgentSession,
user: SYSTEM_USER_ID.clone(),
entity: None,
+ agent_api_key_id: None,
cost: Usage {
amount: UsageAmount::Tokens {
input: 1_000_000,
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index ec2d0c5232..bd50f27f7e 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -268,6 +268,14 @@ pub trait BotService: Send + Sync + 'static {
req: UpdateAgentRequest,
) -> impl Future<Output = Result<Agent, BotError>> + Send;
+ /// A live agent the caller may change: their own, or their team's. For
+ /// settings kept beside the agent, such as its API key.
+ fn manageable_agent(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<Agent, BotError>> + Send;
+
/// Change part of a manageable agent's instructions or settings, keeping
/// everything the patch leaves unnamed - owner and profile included.
fn patch_agent(
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index 9ea8bd67b9..3464594b10 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -592,6 +592,19 @@ where
self.replace_agent(caller, &current, req).await
}
+ async fn manageable_agent(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<Agent, BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ self.repo
+ .get_agent(bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ .ok_or_else(|| BotError::NotFound("agent not found".to_string()))
+ }
+
async fn patch_agent(
&self,
caller: MacroUserIdStr<'static>,
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index 95cda06eb4..c17af61382 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -126,6 +126,14 @@ impl BotService for TestBotService {
unimplemented!()
}
+ async fn manageable_agent(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Agent, BotError> {
+ unimplemented!()
+ }
+
async fn patch_agent(
&self,
_caller: MacroUserIdStr<'static>,
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index 98e3f3279a..33c89321be 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -173,6 +173,14 @@ impl BotService for TestBotService {
unimplemented!()
}
+ async fn manageable_agent(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Agent, BotError> {
+ unimplemented!()
+ }
+
async fn patch_agent(
&self,
_caller: MacroUserIdStr<'static>,
diff --git a/crates/bots/src/inbound/toolset/test.rs b/crates/bots/src/inbound/toolset/test.rs
index 132c7cdf85..e58b5f19d6 100644
--- a/crates/bots/src/inbound/toolset/test.rs
+++ b/crates/bots/src/inbound/toolset/test.rs
@@ -122,6 +122,14 @@ impl BotService for ToolTestBotService {
unimplemented!()
}
+ async fn manageable_agent(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Agent, BotError> {
+ unimplemented!()
+ }
+
async fn patch_agent(
&self,
_caller: MacroUserIdStr<'static>,
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 5b775af4af..bfcecc2551 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -9,7 +9,7 @@ async function gO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre
`);N=k.pop()??"";for(let r of k){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await I(C)}}}()}}var B7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},L7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},U7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Fj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(L7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=B7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return HO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},HO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Y,J])=>{K=[...K,Y,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=U7(x),X=Object.entries(S).map(([K,L])=>HO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var N7=/\{[^{}]+\}/g,z7=({path:$,url:O})=>{let j=O,x=O.match(N7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,Fj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,Ej({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${HO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},o1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function f0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $S=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var OS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var jS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=Fj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=Ej({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=HO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},xS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},I7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function SS($){for(let O of $.security??[]){if(I7($,O.name))continue;let j=await $S(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var b0=($)=>o1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:jS($.querySerializer),url:$.url}),g0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=qj($.headers,O.headers),j},T7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},qj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?T7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class wj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var ZS=()=>({error:new wj,request:new wj,response:new wj}),H7=jS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),R7={"Content-Type":"application/json"},nO=($={})=>({...OS,headers:R7,parseAs:"auto",querySerializer:H7,...$});var k0=($={})=>{let O=g0(nO(),$),j=()=>({...O}),x=(Y)=>{return O=g0(O,Y),j()},S=ZS(),G=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:qj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await SS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=b0(I);return{opts:I,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,I=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Y),T={redirect:"follow",...V,body:f0(V)};z=new Request(B,T);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?xS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Y);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),K=(Y)=>async(J)=>{let{opts:I,url:z}=await G(J);return e1({...I,body:I.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:f0(I),url:z})};return{buildUrl:(Y)=>b0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var XS=k0(nO());class GS{client;constructor($){this.client=$?.client??XS}}class KS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class fj extends GS{static __registry=new KS;constructor($){super($);fj.__registry.set(this,$?.key)}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function YS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Y}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Y.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:T},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:J,retry:V}),F.length)yield _}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await I(C)}}}()}}var B7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},L7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},U7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Fj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(L7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=B7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return HO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},HO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Y,J])=>{K=[...K,Y,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=U7(x),X=Object.entries(S).map(([K,L])=>HO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var N7=/\{[^{}]+\}/g,z7=({path:$,url:O})=>{let j=O,x=O.match(N7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,Fj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,Ej({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${HO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},o1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function f0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $S=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var OS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var jS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=Fj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=Ej({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=HO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},xS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},I7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function SS($){for(let O of $.security??[]){if(I7($,O.name))continue;let j=await $S(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var b0=($)=>o1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:jS($.querySerializer),url:$.url}),g0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=qj($.headers,O.headers),j},T7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},qj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?T7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class wj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var ZS=()=>({error:new wj,request:new wj,response:new wj}),H7=jS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),R7={"Content-Type":"application/json"},nO=($={})=>({...OS,headers:R7,parseAs:"auto",querySerializer:H7,...$});var k0=($={})=>{let O=g0(nO(),$),j=()=>({...O}),x=(Y)=>{return O=g0(O,Y),j()},S=ZS(),G=async(Y)=>{let J={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:qj(O.headers,Y.headers),serializedBody:void 0};if(J.security)await SS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=b0(I);return{opts:I,url:z}},Z=async(Y)=>{let J=Y.throwOnError??O.throwOnError,I=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Y),T={redirect:"follow",...V,body:f0(V)};z=new Request(B,T);for(let U of S.request.fns)if(U)z=await U(z,V);let P=V.fetch;W=await P(z);for(let U of S.response.fns)if(U)W=await U(W,z,V);let D={request:z,response:W};if(W.ok){let U=(V.parseAs==="auto"?xS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let N;switch(U){case"arrayBuffer":case"blob":case"text":N=await W[U]();break;case"formData":N=new FormData;break;case"stream":N=W.body;break;case"json":default:N={};break}return V.responseStyle==="data"?N:{data:N,...D}}let H;switch(U){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[U]();break;case"json":{let N=await W.text();H=N?JSON.parse(N):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(U==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),w;try{w=JSON.parse(C)}catch{}throw w??C}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Y);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(J)=>Z({...J,method:Y}),K=(Y)=>async(J)=>{let{opts:I,url:z}=await G(J);return e1({...I,body:I.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:f0(I),url:z})};return{buildUrl:(Y)=>b0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var XS=k0(nO());class GS{client;constructor($){this.client=$?.client??XS}}class KS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class fj extends GS{static __registry=new KS;constructor($){super($);fj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function YS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Y}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Y.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:T},C=new Request(L,D);if($)C=await $(L,D);let U=await(Y.fetch??globalThis.fetch)(C);if(!U.ok)throw Error(`SSE failed: ${U.status} ${U.statusText}`);if(!U.body)throw Error("No body in SSE response");let H=U.body.pipeThrough(new TextDecoderStream).getReader(),N="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;N+=l,N=N.replace(/\r\n?/g,`
`);let k=N.split(`
`);N=k.pop()??"";for(let r of k){let p=r.split(`
diff --git a/crates/macro_db_client/migrations/20261025185030_agent_api_keys.sql b/crates/macro_db_client/migrations/20261025185030_agent_api_keys.sql
new file mode 100644
index 0000000000..581eeaffff
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261025185030_agent_api_keys.sql
@@ -0,0 +1,36 @@
+-- An agent's own Anthropic or OpenAI API key. An in-memory agent with one
+-- runs every turn on it instead of Macro's allowance; usage on it is recorded
+-- against the key and never counted. One key per agent, for the provider of
+-- the agent's model; it goes when the agent's bot row does.
+SET LOCAL lock_timeout = '5s';
+
+CREATE TABLE agent_api_keys (
+ bot_id UUID PRIMARY KEY REFERENCES bots (id) ON DELETE CASCADE,
+ provider TEXT NOT NULL,
+ -- The key's public prefix, written from the parsed plaintext before it is
+ -- encrypted. Postgres cannot read the ciphertext, so this is how it
+ -- refuses a key whose shape does not match its provider.
+ key_prefix TEXT NOT NULL,
+ key_ciphertext BYTEA NOT NULL,
+ encryption_version SMALLINT NOT NULL,
+ kms_key_id TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ CONSTRAINT agent_api_keys_provider_known CHECK (provider IN ('anthropic', 'openai')),
+ CONSTRAINT agent_api_keys_key_prefix CHECK (
+ CASE provider
+ WHEN 'anthropic' THEN key_prefix = 'sk-ant-'
+ WHEN 'openai' THEN key_prefix = 'sk-'
+ ELSE FALSE
+ END
+ )
+);
+
+-- Usage paid for by an agent's own key: recorded for visibility and never
+-- counted against Macro usage. Added NOT VALID so this only takes a brief lock
+-- on `ai_usage`; a later migration validates it and indexes the column outside
+-- a transaction.
+ALTER TABLE ai_usage ADD COLUMN agent_api_key_id UUID;
+ALTER TABLE ai_usage ADD CONSTRAINT ai_usage_agent_api_key_id_fkey
+ FOREIGN KEY (agent_api_key_id) REFERENCES agent_api_keys (bot_id) ON DELETE SET NULL
+ NOT VALID;
diff --git a/crates/macro_db_client/migrations/20261025185032_ai_usage_agent_api_key_idx_concurrently.sql b/crates/macro_db_client/migrations/20261025185032_ai_usage_agent_api_key_idx_concurrently.sql
new file mode 100644
index 0000000000..fa47b68562
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261025185032_ai_usage_agent_api_key_idx_concurrently.sql
@@ -0,0 +1,8 @@
+-- no-transaction
+-- Removing an agent's key sets its usage rows' `agent_api_key_id` to NULL, so
+-- the delete needs an index to find them. Partial: almost every row is paid
+-- for by Macro and has no key. Built CONCURRENTLY so completions keep writing;
+-- an INVALID leftover from an interrupted build must be dropped by hand first.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS ai_usage_agent_api_key_id_idx
+ ON ai_usage (agent_api_key_id)
+ WHERE agent_api_key_id IS NOT NULL;
diff --git a/crates/macro_db_client/migrations/20261025185033_validate_ai_usage_agent_api_key_fkey.sql b/crates/macro_db_client/migrations/20261025185033_validate_ai_usage_agent_api_key_fkey.sql
new file mode 100644
index 0000000000..79415a319e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261025185033_validate_ai_usage_agent_api_key_fkey.sql
@@ -0,0 +1,5 @@
+-- Every row predates `agent_api_key_id` and is NULL, so this only confirms the
+-- constraint. VALIDATE takes a lock that still allows inserts, unlike the one
+-- adding the constraint, which is why the two are separate migrations.
+SET LOCAL lock_timeout = '5s';
+ALTER TABLE ai_usage VALIDATE CONSTRAINT ai_usage_agent_api_key_id_fkey;
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index f513521c79..ab9b883867 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -568,7 +568,9 @@ the shimmer.
The agent editor has Profile, Instructions, **Where it runs** (In Macro, In
Cursor, In your harness) and **Who can use it** (Private / Team). The selected
place opens its Model picker inside its card; In your harness adds a Harness
- picker beside it. An unconnected Cursor or unpaired harness is disabled with
+ picker beside it. In Macro on an Anthropic or OpenAI model also shows an
+ optional **Anthropic API key** / **OpenAI API key** field (see
+ [agent API keys](#agent-api-keys)). An unconnected Cursor or unpaired harness is disabled with
**Connect** / **Set up**, which open the setup guide in place and return to the
editor with that option selected. Mention style, permission requests,
connections, and channels sit in a collapsed **Advanced** section whose
@@ -836,6 +838,33 @@ ordinary HTTP failures and background queries do not. Document AI-edit refusals
apply no edits and open this dialog instead of the generic `AI edit failed`
toast. Legacy chat tool errors carrying a recognized quota code also open it.
+### Agent API keys
+
+An agent that runs **In Macro** on an Anthropic or OpenAI model can have its own
+API key, set in the agent editor under its model: **Anthropic API key** or
+**OpenAI API key** (the shared `ApiKeyInput`, which shows a saved key only as
+`sk-ant-••••`). Whoever may edit the agent may set or **Remove** its key; a
+saved key is never shown again, and removing it does not revoke it at the
+provider. The key is saved after the agent (`PUT /auth/agents/{id}/api-key`).
+
+- Every turn of an agent with a usable key runs on it: never admitted against
+ or counted toward the person's Macro usage, and recorded against the key
+ (`ai_usage.agent_api_key_id`). Such turns skip the quick opening line, which
+ runs on Macro's model; tools that call models and context summaries still
+ run on Macro's keys and count.
+- Only the agent's own sessions spend its key: the owner's for a personal
+ agent, a current member's for a team agent. Anyone else's session of it
+ runs on their Macro usage.
+- The session's model list is the key's provider's models, whatever the
+ person's plan, and another provider's model cannot be picked.
+- Keys are part of the Premium and Max plans (and enterprise teams), checked
+ against the agent's owner: a personal agent's owner, or a team agent's team
+ payer. On Free the field is disabled with a note; a key saved before a
+ downgrade stays (and can be removed) but the agent runs on Macro usage.
+- A key stops counting while the agent no longer fits it (moved to another
+ provider's model or another harness); the editor says the saved key isn't
+ used, and offers **Remove key** under Where it runs.
+
### Quota manual checks
Use an isolated local backend with local billing fixtures, not real hosted
diff --git a/docs/runbooks/ai-quota-enforcement.md b/docs/runbooks/ai-quota-enforcement.md
index 806de55582..88a5f68cd2 100644
--- a/docs/runbooks/ai-quota-enforcement.md
+++ b/docs/runbooks/ai-quota-enforcement.md
@@ -25,10 +25,17 @@ admission and recording:
| True, real user, billable feature | Check existing allowance; fail closed on validation error | `true` when existing producer records usage |
| True, exempt feature | No quota billing I/O | `false` |
| Genuinely system-owned work | No user quota billing I/O | `false` |
+| Paid for by an agent's own API key (`agent_api_key_id` set) | No admission for that turn | `false`, row references the key |
| Rejected before execution | No provider work | No usage row for work not executed |
| Historical rows / inserts omitting column | Never retrospectively classified | `false` |
| Disabled after activation | Stop admission and new counting | Existing booleans unchanged |
+**Agent API keys:** turns of an in-memory agent with its own Anthropic or
+OpenAI key (see [agent API keys](../agent-guide/ai-chat.md#agent-api-keys))
+skip admission and record `ai_usage.agent_api_key_id`, which keeps them out
+of `count_usage`. Only the loop's own model calls run on the key; tools,
+opening lines, and summaries in those turns still use Macro's keys and count.
+
**Exempt:** Memory, AiProjection, CallSummary, Dictation, ChatRename.
**Billable:** Chat, Automation, DynamicCompletionsApi, ChannelBot, AiEditing,
Import, AgentSession, AgentRepositoryChoice, ImageGeneration. In particular, AI
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/README.md b/packages/sdk-docs/reference/generated/auth/types.gen/README.md
index 3a742d8fe0..94d16929c5 100644
--- a/packages/sdk-docs/reference/generated/auth/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/README.md
@@ -3,6 +3,8 @@
## Type Aliases
- [AbGroup](type-aliases/AbGroup.md)
+- [AgentApiKey](type-aliases/AgentApiKey.md)
+- [AgentApiKeyProvider](type-aliases/AgentApiKeyProvider.md)
- [AiBillingErrorBody](type-aliases/AiBillingErrorBody.md)
- [AppleLoginData](type-aliases/AppleLoginData.md)
- [AppleLoginError](type-aliases/AppleLoginError.md)
@@ -98,6 +100,11 @@
- [CursorApiKeyStatus](type-aliases/CursorApiKeyStatus.md)
- [CursorModelOption](type-aliases/CursorModelOption.md)
- [CursorModelsResponse](type-aliases/CursorModelsResponse.md)
+- [DeleteAgentApiKeyData](type-aliases/DeleteAgentApiKeyData.md)
+- [DeleteAgentApiKeyError](type-aliases/DeleteAgentApiKeyError.md)
+- [DeleteAgentApiKeyErrors](type-aliases/DeleteAgentApiKeyErrors.md)
+- [DeleteAgentApiKeyResponse](type-aliases/DeleteAgentApiKeyResponse.md)
+- [DeleteAgentApiKeyResponses](type-aliases/DeleteAgentApiKeyResponses.md)
- [DeleteCursorApiKeyData](type-aliases/DeleteCursorApiKeyData.md)
- [DeleteCursorApiKeyError](type-aliases/DeleteCursorApiKeyError.md)
- [DeleteCursorApiKeyErrors](type-aliases/DeleteCursorApiKeyErrors.md)
@@ -153,6 +160,11 @@
- [GenerateEmailLinkResponse](type-aliases/GenerateEmailLinkResponse.md)
- [GenerateEmailLinkResponses](type-aliases/GenerateEmailLinkResponses.md)
- [GenericSuccessResponse](type-aliases/GenericSuccessResponse.md)
+- [GetAgentApiKeyData](type-aliases/GetAgentApiKeyData.md)
+- [GetAgentApiKeyError](type-aliases/GetAgentApiKeyError.md)
+- [GetAgentApiKeyErrors](type-aliases/GetAgentApiKeyErrors.md)
+- [GetAgentApiKeyResponse](type-aliases/GetAgentApiKeyResponse.md)
+- [GetAgentApiKeyResponses](type-aliases/GetAgentApiKeyResponses.md)
- [GetAiBillingPlansData](type-aliases/GetAiBillingPlansData.md)
- [GetAiBillingPlansResponse](type-aliases/GetAiBillingPlansResponse.md)
- [GetAiBillingPlansResponses](type-aliases/GetAiBillingPlansResponses.md)
@@ -445,6 +457,12 @@
- [ProfilePictureQueryParams](type-aliases/ProfilePictureQueryParams.md)
- [ProfilePictures](type-aliases/ProfilePictures.md)
- [PublicGtmInviteLink](type-aliases/PublicGtmInviteLink.md)
+- [PutAgentApiKeyData](type-aliases/PutAgentApiKeyData.md)
+- [PutAgentApiKeyError](type-aliases/PutAgentApiKeyError.md)
+- [PutAgentApiKeyErrors](type-aliases/PutAgentApiKeyErrors.md)
+- [PutAgentApiKeyRequest](type-aliases/PutAgentApiKeyRequest.md)
+- [PutAgentApiKeyResponse](type-aliases/PutAgentApiKeyResponse.md)
+- [PutAgentApiKeyResponses](type-aliases/PutAgentApiKeyResponses.md)
- [PutCursorApiKeyData](type-aliases/PutCursorApiKeyData.md)
- [PutCursorApiKeyError](type-aliases/PutCursorApiKeyError.md)
- [PutCursorApiKeyErrors](type-aliases/PutCursorApiKeyErrors.md)
@@ -503,6 +521,7 @@
- [RevokeGtmInviteLinkErrors](type-aliases/RevokeGtmInviteLinkErrors.md)
- [RevokeGtmInviteLinkResponse](type-aliases/RevokeGtmInviteLinkResponse.md)
- [RevokeGtmInviteLinkResponses](type-aliases/RevokeGtmInviteLinkResponses.md)
+- [SavedAgentApiKey](type-aliases/SavedAgentApiKey.md)
- [ScheduledSeatPlan](type-aliases/ScheduledSeatPlan.md)
- [SeatPlan](type-aliases/SeatPlan.md)
- [SendInviteBody](type-aliases/SendInviteBody.md)
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentApiKey.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentApiKey.md
new file mode 100644
index 0000000000..3f4231ef68
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentApiKey.md
@@ -0,0 +1,12 @@
+# Type Alias: AgentApiKey
+
+> **AgentApiKey** = \{ `key?`: `null` \| [`SavedAgentApiKey`](SavedAgentApiKey.md); `planAllows`: `boolean`; \}
+
+An agent's API key, and whether its turns can run on it.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-key"></a> `key?` | `null` \| [`SavedAgentApiKey`](SavedAgentApiKey.md) | - |
+| <a id="property-planallows"></a> `planAllows` | `boolean` | Whether the agent owner's plan includes API keys. A key saved before a downgrade is still listed, and removable, but unused. |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentApiKeyProvider.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentApiKeyProvider.md
new file mode 100644
index 0000000000..cdfdd784c5
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AgentApiKeyProvider.md
@@ -0,0 +1,5 @@
+# Type Alias: AgentApiKeyProvider
+
+> **AgentApiKeyProvider** = `"anthropic"` \| `"openai"`
+
+A provider an agent can bring its own key for.
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyData.md
new file mode 100644
index 0000000000..57bf2c267f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyData.md
@@ -0,0 +1,13 @@
+# Type Alias: DeleteAgentApiKeyData
+
+> **DeleteAgentApiKeyData** = \{ `body?`: `never`; `path`: \{ `agent_id`: `string`; \}; `query?`: `never`; `url`: `"/agents/{agent_id}/api-key"`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` |
+| <a id="property-path"></a> `path` | \{ `agent_id`: `string`; \} |
+| `path.agent_id` | `string` |
+| <a id="property-query"></a> `query?` | `never` |
+| <a id="property-url"></a> `url` | `"/agents/{agent_id}/api-key"` |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyError.md
new file mode 100644
index 0000000000..023c6604f0
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyError.md
@@ -0,0 +1,3 @@
+# Type Alias: DeleteAgentApiKeyError
+
+> **DeleteAgentApiKeyError** = [`DeleteAgentApiKeyErrors`](DeleteAgentApiKeyErrors.md)\[keyof [`DeleteAgentApiKeyErrors`](DeleteAgentApiKeyErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyErrors.md
new file mode 100644
index 0000000000..2030fea3b0
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyErrors.md
@@ -0,0 +1,11 @@
+# Type Alias: DeleteAgentApiKeyErrors
+
+> **DeleteAgentApiKeyErrors** = \{ `401`: `string`; `403`: [`ErrorResponse`](ErrorResponse.md); `404`: [`ErrorResponse`](ErrorResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-401"></a> `401` | `string` |
+| <a id="property-403"></a> `403` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyResponse.md
new file mode 100644
index 0000000000..e6de193cb8
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: DeleteAgentApiKeyResponse
+
+> **DeleteAgentApiKeyResponse** = [`DeleteAgentApiKeyResponses`](DeleteAgentApiKeyResponses.md)\[keyof [`DeleteAgentApiKeyResponses`](DeleteAgentApiKeyResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyResponses.md
new file mode 100644
index 0000000000..a9b3a8b0ca
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/DeleteAgentApiKeyResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: DeleteAgentApiKeyResponses
+
+> **DeleteAgentApiKeyResponses** = \{ `200`: [`AgentApiKey`](AgentApiKey.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`AgentApiKey`](AgentApiKey.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyData.md
new file mode 100644
index 0000000000..7b07bfb50d
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyData.md
@@ -0,0 +1,13 @@
+# Type Alias: GetAgentApiKeyData
+
+> **GetAgentApiKeyData** = \{ `body?`: `never`; `path`: \{ `agent_id`: `string`; \}; `query?`: `never`; `url`: `"/agents/{agent_id}/api-key"`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` |
+| <a id="property-path"></a> `path` | \{ `agent_id`: `string`; \} |
+| `path.agent_id` | `string` |
+| <a id="property-query"></a> `query?` | `never` |
+| <a id="property-url"></a> `url` | `"/agents/{agent_id}/api-key"` |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyError.md
new file mode 100644
index 0000000000..d1c125f2ea
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyError.md
@@ -0,0 +1,3 @@
+# Type Alias: GetAgentApiKeyError
+
+> **GetAgentApiKeyError** = [`GetAgentApiKeyErrors`](GetAgentApiKeyErrors.md)\[keyof [`GetAgentApiKeyErrors`](GetAgentApiKeyErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyErrors.md
new file mode 100644
index 0000000000..54d426de12
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyErrors.md
@@ -0,0 +1,11 @@
+# Type Alias: GetAgentApiKeyErrors
+
+> **GetAgentApiKeyErrors** = \{ `401`: `string`; `403`: [`ErrorResponse`](ErrorResponse.md); `404`: [`ErrorResponse`](ErrorResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-401"></a> `401` | `string` |
+| <a id="property-403"></a> `403` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyResponse.md
new file mode 100644
index 0000000000..0948c391e4
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: GetAgentApiKeyResponse
+
+> **GetAgentApiKeyResponse** = [`GetAgentApiKeyResponses`](GetAgentApiKeyResponses.md)\[keyof [`GetAgentApiKeyResponses`](GetAgentApiKeyResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyResponses.md
new file mode 100644
index 0000000000..103abe096f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetAgentApiKeyResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: GetAgentApiKeyResponses
+
+> **GetAgentApiKeyResponses** = \{ `200`: [`AgentApiKey`](AgentApiKey.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`AgentApiKey`](AgentApiKey.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyData.md
new file mode 100644
index 0000000000..e5b7addb53
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyData.md
@@ -0,0 +1,13 @@
+# Type Alias: PutAgentApiKeyData
+
+> **PutAgentApiKeyData** = \{ `body`: [`PutAgentApiKeyRequest`](PutAgentApiKeyRequest.md); `path`: \{ `agent_id`: `string`; \}; `query?`: `never`; `url`: `"/agents/{agent_id}/api-key"`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-body"></a> `body` | [`PutAgentApiKeyRequest`](PutAgentApiKeyRequest.md) |
+| <a id="property-path"></a> `path` | \{ `agent_id`: `string`; \} |
+| `path.agent_id` | `string` |
+| <a id="property-query"></a> `query?` | `never` |
+| <a id="property-url"></a> `url` | `"/agents/{agent_id}/api-key"` |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyError.md
new file mode 100644
index 0000000000..f038df309b
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyError.md
@@ -0,0 +1,3 @@
+# Type Alias: PutAgentApiKeyError
+
+> **PutAgentApiKeyError** = [`PutAgentApiKeyErrors`](PutAgentApiKeyErrors.md)\[keyof [`PutAgentApiKeyErrors`](PutAgentApiKeyErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyErrors.md
new file mode 100644
index 0000000000..db9b5b83ae
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyErrors.md
@@ -0,0 +1,12 @@
+# Type Alias: PutAgentApiKeyErrors
+
+> **PutAgentApiKeyErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); `401`: `string`; `403`: [`ErrorResponse`](ErrorResponse.md); `404`: [`ErrorResponse`](ErrorResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-401"></a> `401` | `string` |
+| <a id="property-403"></a> `403` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyRequest.md
new file mode 100644
index 0000000000..6cbf6dfd82
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyRequest.md
@@ -0,0 +1,11 @@
+# Type Alias: PutAgentApiKeyRequest
+
+> **PutAgentApiKeyRequest** = \{ `apiKey`: `string`; \}
+
+The key someone pasted.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-apikey"></a> `apiKey` | `string` | An Anthropic (`sk-ant-…`) or OpenAI (`sk-…`) key, for the provider of the agent's model. |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyResponse.md
new file mode 100644
index 0000000000..2b5479ad51
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: PutAgentApiKeyResponse
+
+> **PutAgentApiKeyResponse** = [`PutAgentApiKeyResponses`](PutAgentApiKeyResponses.md)\[keyof [`PutAgentApiKeyResponses`](PutAgentApiKeyResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyResponses.md
new file mode 100644
index 0000000000..8adec2640c
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PutAgentApiKeyResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: PutAgentApiKeyResponses
+
+> **PutAgentApiKeyResponses** = \{ `200`: [`AgentApiKey`](AgentApiKey.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`AgentApiKey`](AgentApiKey.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SavedAgentApiKey.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SavedAgentApiKey.md
new file mode 100644
index 0000000000..c9aab09ed2
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SavedAgentApiKey.md
@@ -0,0 +1,12 @@
+# Type Alias: SavedAgentApiKey
+
+> **SavedAgentApiKey** = \{ `provider`: [`AgentApiKeyProvider`](AgentApiKeyProvider.md); `updatedAt`: `string`; \}
+
+The agent's saved key. Never includes the key.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-provider"></a> `provider` | [`AgentApiKeyProvider`](AgentApiKeyProvider.md) | The provider the key is for. |
+| <a id="property-updatedat"></a> `updatedAt` | `string` | When the key was last replaced. |
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index f761d76bcd..5114acb8f1 100644
--- a/packages/sdk/generated/auth/index.ts
+++ b/packages/sdk/generated/auth/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
+export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index c73fddefd2..eabbd4aadf 100644
--- a/packages/sdk/generated/auth/sdk.gen.ts
+++ b/packages/sdk/generated/auth/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -57,6 +57,36 @@ export class Sdk extends HeyApiClient {
Sdk.__registry.set(this, args?.key);
}
+ /**
+ * Forgets the agent's API key. Does not revoke it at the provider; succeeds
+ * when there was none.
+ */
+ public deleteAgentApiKey<ThrowOnError extends boolean = false>(options: Options<DeleteAgentApiKeyData, ThrowOnError>): RequestResult<DeleteAgentApiKeyResponses, DeleteAgentApiKeyErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<DeleteAgentApiKeyResponses, DeleteAgentApiKeyErrors, ThrowOnError>({ url: '/agents/{agent_id}/api-key', ...options });
+ }
+
+ /**
+ * The agent's API key, if it has one, and whether its plan allows one.
+ */
+ public getAgentApiKey<ThrowOnError extends boolean = false>(options: Options<GetAgentApiKeyData, ThrowOnError>): RequestResult<GetAgentApiKeyResponses, GetAgentApiKeyErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetAgentApiKeyResponses, GetAgentApiKeyErrors, ThrowOnError>({ url: '/agents/{agent_id}/api-key', ...options });
+ }
+
+ /**
+ * Registers or replaces the agent's API key, for its model's provider.
+ * Only in-memory agents on an Anthropic or OpenAI model, on a paid plan.
+ */
+ public putAgentApiKey<ThrowOnError extends boolean = false>(options: Options<PutAgentApiKeyData, ThrowOnError>): RequestResult<PutAgentApiKeyResponses, PutAgentApiKeyErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<PutAgentApiKeyResponses, PutAgentApiKeyErrors, ThrowOnError>({
+ url: '/agents/{agent_id}/api-key',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Turn automatic credit reloads on with the given
* thresholds, or off. Payer only. Enabling settles right away, so a balance
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 62d35e0d55..44e9a28aae 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -6,6 +6,23 @@ export type ClientOptions = {
export type AbGroup = 'A' | 'B';
+/**
+ * An agent's API key, and whether its turns can run on it.
+ */
+export type AgentApiKey = {
+ key?: null | SavedAgentApiKey;
+ /**
+ * Whether the agent owner's plan includes API keys. A key saved before a
+ * downgrade is still listed, and removable, but unused.
+ */
+ planAllows: boolean;
+};
+
+/**
+ * A provider an agent can bring its own key for.
+ */
+export type AgentApiKeyProvider = 'anthropic' | 'openai';
+
/**
* Error response body.
*/
@@ -1424,6 +1441,17 @@ export type PublicGtmInviteLink = {
status: GtmInviteLinkStatus;
};
+/**
+ * The key someone pasted.
+ */
+export type PutAgentApiKeyRequest = {
+ /**
+ * An Anthropic (`sk-ant-…`) or OpenAI (`sk-…`) key, for the provider of
+ * the agent's model.
+ */
+ apiKey: string;
+};
+
/**
* The key the user pasted.
*/
@@ -1473,6 +1501,20 @@ export type ResendFusionauthVerifyUserEmailRequest = {
email: string;
};
+/**
+ * The agent's saved key. Never includes the key.
+ */
+export type SavedAgentApiKey = {
+ /**
+ * The provider the key is for.
+ */
+ provider: AgentApiKeyProvider;
+ /**
+ * When the key was last replaced.
+ */
+ updatedAt: string;
+};
+
/**
* A seat's future plan in the subscription's currently attached schedule.
*/
@@ -1981,6 +2023,76 @@ export type UserTokensResponse = {
refresh_token: string;
};
+export type DeleteAgentApiKeyData = {
+ body?: never;
+ path: {
+ agent_id: string;
+ };
+ query?: never;
+ url: '/agents/{agent_id}/api-key';
+};
+
+export type DeleteAgentApiKeyErrors = {
+ 401: string;
+ 403: ErrorResponse;
+ 404: ErrorResponse;
+};
+
+export type DeleteAgentApiKeyError = DeleteAgentApiKeyErrors[keyof DeleteAgentApiKeyErrors];
+
+export type DeleteAgentApiKeyResponses = {
+ 200: AgentApiKey;
+};
+
+export type DeleteAgentApiKeyResponse = DeleteAgentApiKeyResponses[keyof DeleteAgentApiKeyResponses];
+
+export type GetAgentApiKeyData = {
+ body?: never;
+ path: {
+ agent_id: string;
+ };
+ query?: never;
+ url: '/agents/{agent_id}/api-key';
+};
+
+export type GetAgentApiKeyErrors = {
+ 401: string;
+ 403: ErrorResponse;
+ 404: ErrorResponse;
+};
+
+export type GetAgentApiKeyError = GetAgentApiKeyErrors[keyof GetAgentApiKeyErrors];
+
+export type GetAgentApiKeyResponses = {
+ 200: AgentApiKey;
+};
+
+export type GetAgentApiKeyResponse = GetAgentApiKeyResponses[keyof GetAgentApiKeyResponses];
+
+export type PutAgentApiKeyData = {
+ body: PutAgentApiKeyRequest;
+ path: {
+ agent_id: string;
+ };
+ query?: never;
+ url: '/agents/{agent_id}/api-key';
+};
+
+export type PutAgentApiKeyErrors = {
+ 400: ErrorResponse;
+ 401: string;
+ 403: ErrorResponse;
+ 404: ErrorResponse;
+};
+
+export type PutAgentApiKeyError = PutAgentApiKeyErrors[keyof PutAgentApiKeyErrors];
+
+export type PutAgentApiKeyResponses = {
+ 200: AgentApiKey;
+};
+
+export type PutAgentApiKeyResponse = PutAgentApiKeyResponses[keyof PutAgentApiKeyResponses];
+
export type UpdateAiBillingAutoReloadData = {
body: UpdateAutoReloadRequest;
path?: never;
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index ffbdbdbd24..b9147e1a21 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -10,6 +10,199 @@
"version": "0.1.0"
},
"paths": {
+ "/agents/{agent_id}/api-key": {
+ "get": {
+ "tags": ["crate::api::agent_api_keys"],
+ "summary": "The agent's API key, if it has one, and whether its plan allows one.",
+ "operationId": "get_agent_api_key",
+ "parameters": [
+ {
+ "name": "agent_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentApiKey"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["crate::api::agent_api_keys"],
+ "summary": "Registers or replaces the agent's API key, for its model's provider.\nOnly in-memory agents on an Anthropic or OpenAI model, on a paid plan.",
+ "operationId": "put_agent_api_key",
+ "parameters": [
+ {
+ "name": "agent_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PutAgentApiKeyRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentApiKey"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["crate::api::agent_api_keys"],
+ "summary": "Forgets the agent's API key. Does not revoke it at the provider; succeeds\nwhen there was none.",
+ "operationId": "delete_agent_api_key",
+ "parameters": [
+ {
+ "name": "agent_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentApiKey"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/ai-billing/auto-reload": {
"patch": {
"tags": ["ai_billing"],
@@ -5442,6 +5635,33 @@
"type": "string",
"enum": ["A", "B"]
},
+ "AgentApiKey": {
+ "type": "object",
+ "description": "An agent's API key, and whether its turns can run on it.",
+ "required": ["planAllows"],
+ "properties": {
+ "key": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SavedAgentApiKey",
+ "description": "The saved key, if any."
+ }
+ ]
+ },
+ "planAllows": {
+ "type": "boolean",
+ "description": "Whether the agent owner's plan includes API keys. A key saved before a\ndowngrade is still listed, and removable, but unused."
+ }
+ }
+ },
+ "AgentApiKeyProvider": {
+ "type": "string",
+ "description": "A provider an agent can bring its own key for.",
+ "enum": ["anthropic", "openai"]
+ },
"AiBillingErrorBody": {
"type": "object",
"description": "Error response body.",
@@ -7269,6 +7489,17 @@
}
}
},
+ "PutAgentApiKeyRequest": {
+ "type": "object",
+ "description": "The key someone pasted.",
+ "required": ["apiKey"],
+ "properties": {
+ "apiKey": {
+ "type": "string",
+ "description": "An Anthropic (`sk-ant-…`) or OpenAI (`sk-…`) key, for the provider of\nthe agent's model."
+ }
+ }
+ },
"PutCursorApiKeyRequest": {
"type": "object",
"description": "The key the user pasted.",
@@ -7324,6 +7555,22 @@
}
}
},
+ "SavedAgentApiKey": {
+ "type": "object",
+ "description": "The agent's saved key. Never includes the key.",
+ "required": ["provider", "updatedAt"],
+ "properties": {
+ "provider": {
+ "$ref": "#/components/schemas/AgentApiKeyProvider",
+ "description": "The provider the key is for."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the key was last replaced."
+ }
+ }
+ },
"ScheduledSeatPlan": {
"type": "object",
"description": "A seat's future plan in the subscription's currently attached schedule.",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index a027d04d06..2d1d5620f8 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -54,6 +54,8 @@ export const authExcluded = [
'createPortalSession',
'createTeam',
'createTeamInviteLink',
+ // An agent's own API key is a credential managed in the app's agent settings.
+ 'deleteAgentApiKey',
'deleteCursorApiKey',
'deleteGithubLink',
'deleteTeam',
@@ -63,6 +65,7 @@ export const authExcluded = [
'disconnectCodex',
'enrichGithubPullRequests',
'generateEmailLink',
+ 'getAgentApiKey',
'getAiBillingPlans',
'getAiBillingSummary',
'getCodexConnection',
@@ -111,6 +114,7 @@ export const authExcluded = [
'patchUserTutorial',
'pollCodexLogin',
'postProfilePictures',
+ 'putAgentApiKey',
'putCursorApiKey',
'putCursorDefaultModel',
'putProfilePicture',
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 67d550abab..391ee29115 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -41,6 +41,7 @@ agent_session_realtime = { path = "../../crates/agent_session_realtime" }
agent_trigger = { path = "../../crates/agent_trigger", features = ["outbound"] }
aho-corasick = "1.1.3"
ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }
+agent_api_keys = { path = "../../crates/agent_api_keys" }
ai_projections = { path = "../../crates/ai_projections", features = ["agent"] }
ai_tools = { path = "../../crates/ai_tools" }
ai_toolset = { path = "../../crates/ai_toolset" }
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 6402daff50..496647da92 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -786,6 +786,20 @@ async fn run() -> anyhow::Result<()> {
),
),
);
+ // Agents' own Anthropic and OpenAI keys, under the Cursor key's CMK this
+ // role already decrypts with. Decrypt-only for the same reason as Cursor
+ // keys: saving them is the authentication service's job. Only agents
+ // whose owner is on a paid plan run on them.
+ let agent_keys: Arc<dyn agent_api_keys::domain::AgentKeys> =
+ Arc::new(agent_api_keys::domain::AgentKeyService::new(
+ agent_api_keys::outbound::PgAgentKeyRepo::new(pool.clone()),
+ agent_api_keys::outbound::KmsAgentKeyCipher::new(AwsKmsCiphertexts::decrypting(
+ aws_sdk_kms::Client::new(&aws_config),
+ )),
+ agent_api_keys::outbound::EntitlementKeyPlans::new(
+ ai_billing::composition::pg_entitlement_source(pool.clone()),
+ ),
+ ));
let inmem = InMemRuntime {
manager: InMemAgentManager::new(
Arc::clone(&inmem_model_engine),
@@ -794,6 +808,7 @@ async fn run() -> anyhow::Result<()> {
Arc::clone(&inmem_model_access),
)
.with_admission(admission.clone())
+ .with_agent_keys(Arc::clone(&agent_keys))
.with_dev_commands(enable_dev_commands),
};
// The sandbox provider serves every bot but the in-memory one, which the
@@ -1205,6 +1220,7 @@ async fn run() -> anyhow::Result<()> {
))
.with_conversation_turns(conversation_turns)
.with_admission(admission.clone())
+ .with_agent_keys(agent_keys)
.with_repositories(open_repositories)
.with_warm_sessions(Arc::new(session_repo.clone()), tool_catalog),
);
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 321305ebef..4128816b01 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -32,6 +32,7 @@ return_passwordless_code = []
[dependencies]
crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }
+agent_api_keys = { path = "../../crates/agent_api_keys" }
ai_billing = { path = "../../crates/ai_billing" }
ai_usage = { path = "../../crates/ai_usage" }
initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }
diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rs
index 68a7a05a59..4e2bd85df8 100644
--- a/services/authentication_service/src/api.rs
+++ b/services/authentication_service/src/api.rs
@@ -15,6 +15,7 @@ use utoipa_swagger_ui::SwaggerUi;
pub(crate) mod context;
// Routes
+mod agent_api_keys;
mod codex;
mod cursor_api_key;
#[allow(unused_imports)]
@@ -120,6 +121,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
.nest("/user", user::router())
.nest("/link", link::router())
.nest("/cursor-api-key", cursor_api_key::router())
+ .nest("/agents", agent_api_keys::router())
.nest("/codex", codex::router())
.nest("/github_pull_requests", github_pull_requests::router())
.nest(
diff --git a/services/authentication_service/src/api/agent_api_keys.rs b/services/authentication_service/src/api/agent_api_keys.rs
new file mode 100644
index 0000000000..7a9fc7200a
--- /dev/null
+++ b/services/authentication_service/src/api/agent_api_keys.rs
@@ -0,0 +1,272 @@
+//! An agent's own Anthropic or OpenAI API key, set from the agent's settings.
+//!
+//! Whoever may edit the agent may set or remove its key: its owner, or any
+//! member of its team (the agents' own rule, from `BotService`). Like the
+//! Cursor key, a saved key is never readable again through this API.
+
+use agent_api_keys::domain::{
+ AgentKeyError, AgentKeyStatus, AgentKeyView, AgentOwner, KeyedAgent, ModelProvider,
+};
+use axum::{
+ Json, Router,
+ extract::{Path, State},
+ routing::get,
+};
+use bot_id::BotId;
+use bots::domain::{
+ models::{Agent, BotOwner},
+ ports::{BotError, BotService},
+};
+use macro_authorization::{MacroAuthorizationExtractor, UserOnly};
+use macro_user_id::user_id::MacroUserIdStr;
+use utoipa::ToSchema;
+
+use crate::api::context::{ApiContext, AuthorizationService};
+
+type Caller = MacroAuthorizationExtractor<AuthorizationService, UserOnly>;
+
+/// Routes for an agent's API key, under `/agents/{agent_id}/api-key`.
+pub fn router() -> Router<ApiContext> {
+ Router::new().route(
+ "/{agent_id}/api-key",
+ get(get_handler).put(put_handler).delete(delete_handler),
+ )
+}
+
+/// A provider an agent can bring its own key for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentApiKeyProvider {
+ /// Anthropic (`sk-ant-…` keys).
+ Anthropic,
+ /// OpenAI (`sk-…` keys).
+ Openai,
+}
+
+impl From<ModelProvider> for AgentApiKeyProvider {
+ fn from(provider: ModelProvider) -> Self {
+ match provider {
+ ModelProvider::Anthropic => Self::Anthropic,
+ ModelProvider::OpenAi => Self::Openai,
+ }
+ }
+}
+
+/// The agent's saved key. Never includes the key.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct SavedAgentApiKey {
+ /// The provider the key is for.
+ pub provider: AgentApiKeyProvider,
+ /// When the key was last replaced.
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+}
+
+impl From<AgentKeyStatus> for SavedAgentApiKey {
+ fn from(status: AgentKeyStatus) -> Self {
+ Self {
+ provider: status.provider.into(),
+ updated_at: status.updated_at,
+ }
+ }
+}
+
+/// An agent's API key, and whether its turns can run on it.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentApiKey {
+ /// The saved key, if any.
+ pub key: Option<SavedAgentApiKey>,
+ /// Whether the agent owner's plan includes API keys. A key saved before a
+ /// downgrade is still listed, and removable, but unused.
+ pub plan_allows: bool,
+}
+
+impl From<AgentKeyView> for AgentApiKey {
+ fn from(view: AgentKeyView) -> Self {
+ Self {
+ key: view.key.map(Into::into),
+ plan_allows: view.plan_allows,
+ }
+ }
+}
+
+/// The key someone pasted.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PutAgentApiKeyRequest {
+ /// An Anthropic (`sk-ant-…`) or OpenAI (`sk-…`) key, for the provider of
+ /// the agent's model.
+ pub api_key: String,
+}
+
+/// Why an agent API key request failed.
+#[derive(Debug, thiserror::Error)]
+pub enum AgentApiKeyError {
+ /// No live agent with this id.
+ #[error("agent not found")]
+ NotFound,
+ /// The caller may not change this agent.
+ #[error("you cannot change this agent")]
+ Forbidden,
+ /// The value is not a key for the agent's model's provider.
+ #[error("value does not look like an API key for this agent's model")]
+ MalformedKey,
+ /// The agent is not an in-memory agent on an Anthropic or OpenAI model.
+ #[error("only agents that run in Macro on an Anthropic or OpenAI model can use an API key")]
+ UnsupportedAgent,
+ /// The agent owner's plan does not include API keys.
+ #[error("agent API keys are part of the Premium and Max plans")]
+ PlanRequired,
+ /// Encryption, storage, or a lookup failed.
+ #[error("internal error")]
+ Internal,
+}
+
+impl From<AgentKeyError> for AgentApiKeyError {
+ fn from(error: AgentKeyError) -> Self {
+ match error {
+ AgentKeyError::MalformedKey => Self::MalformedKey,
+ AgentKeyError::UnsupportedAgent => Self::UnsupportedAgent,
+ AgentKeyError::PlanRequired => Self::PlanRequired,
+ other => {
+ tracing::error!(error = ?other, "agent api key operation failed");
+ Self::Internal
+ }
+ }
+ }
+}
+
+impl From<BotError> for AgentApiKeyError {
+ fn from(error: BotError) -> Self {
+ match error {
+ BotError::NotFound(_) => Self::NotFound,
+ BotError::Unauthorized => Self::Forbidden,
+ other => {
+ tracing::error!(error = ?other, "could not read the agent");
+ Self::Internal
+ }
+ }
+ }
+}
+
+impl axum::response::IntoResponse for AgentApiKeyError {
+ fn into_response(self) -> axum::response::Response {
+ use axum::http::StatusCode;
+ let status = match self {
+ Self::NotFound => StatusCode::NOT_FOUND,
+ Self::Forbidden | Self::PlanRequired => StatusCode::FORBIDDEN,
+ Self::MalformedKey | Self::UnsupportedAgent => StatusCode::BAD_REQUEST,
+ Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (
+ status,
+ Json(model::response::ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+/// The agent the caller may change, as the key policy needs it.
+async fn keyed_agent(
+ ctx: &ApiContext,
+ caller: &Caller,
+ agent_id: BotId,
+) -> Result<KeyedAgent, AgentApiKeyError> {
+ let agent: Agent = ctx
+ .bots
+ .manageable_agent(caller.authorization.macro_user_id.clone(), agent_id)
+ .await?;
+ let owner = match agent.bot.owner {
+ Some(BotOwner::User { user_id }) => AgentOwner::User(
+ MacroUserIdStr::try_from(user_id).map_err(|_| AgentApiKeyError::Internal)?,
+ ),
+ Some(BotOwner::Team { team_id }) => AgentOwner::Team(team_id),
+ None => return Err(AgentApiKeyError::Forbidden),
+ };
+ Ok(KeyedAgent {
+ bot_id: agent.bot.id.as_uuid(),
+ owner,
+ harness: agent.harness,
+ model: agent.default_model,
+ })
+}
+
+/// The agent's API key, if it has one, and whether its plan allows one.
+#[utoipa::path(
+ get,
+ path = "/agents/{agent_id}/api-key",
+ operation_id = "get_agent_api_key",
+ params(("agent_id" = String, Path)),
+ responses(
+ (status = 200, body = AgentApiKey),
+ (status = 401, body = String),
+ (status = 403, body = model::response::ErrorResponse),
+ (status = 404, body = model::response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, err, fields(agent_id = %agent_id))]
+pub async fn get_handler(
+ State(ctx): State<ApiContext>,
+ caller: Caller,
+ Path(agent_id): Path<BotId>,
+) -> Result<Json<AgentApiKey>, AgentApiKeyError> {
+ let agent = keyed_agent(&ctx, &caller, agent_id).await?;
+ Ok(Json(ctx.agent_api_keys.view(&agent).await?.into()))
+}
+
+/// Registers or replaces the agent's API key, for its model's provider.
+/// Only in-memory agents on an Anthropic or OpenAI model, on a paid plan.
+#[utoipa::path(
+ put,
+ path = "/agents/{agent_id}/api-key",
+ operation_id = "put_agent_api_key",
+ params(("agent_id" = String, Path)),
+ request_body = PutAgentApiKeyRequest,
+ responses(
+ (status = 200, body = AgentApiKey),
+ (status = 400, body = model::response::ErrorResponse),
+ (status = 401, body = String),
+ (status = 403, body = model::response::ErrorResponse),
+ (status = 404, body = model::response::ErrorResponse),
+ )
+)]
+// The body is skipped: it is the key itself.
+#[tracing::instrument(skip_all, err, fields(agent_id = %agent_id))]
+pub async fn put_handler(
+ State(ctx): State<ApiContext>,
+ caller: Caller,
+ Path(agent_id): Path<BotId>,
+ Json(req): Json<PutAgentApiKeyRequest>,
+) -> Result<Json<AgentApiKey>, AgentApiKeyError> {
+ let agent = keyed_agent(&ctx, &caller, agent_id).await?;
+ Ok(Json(
+ ctx.agent_api_keys.set(&agent, &req.api_key).await?.into(),
+ ))
+}
+
+/// Forgets the agent's API key. Does not revoke it at the provider; succeeds
+/// when there was none.
+#[utoipa::path(
+ delete,
+ path = "/agents/{agent_id}/api-key",
+ operation_id = "delete_agent_api_key",
+ params(("agent_id" = String, Path)),
+ responses(
+ (status = 200, body = AgentApiKey),
+ (status = 401, body = String),
+ (status = 403, body = model::response::ErrorResponse),
+ (status = 404, body = model::response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip_all, err, fields(agent_id = %agent_id))]
+pub async fn delete_handler(
+ State(ctx): State<ApiContext>,
+ caller: Caller,
+ Path(agent_id): Path<BotId>,
+) -> Result<Json<AgentApiKey>, AgentApiKeyError> {
+ let agent = keyed_agent(&ctx, &caller, agent_id).await?;
+ Ok(Json(ctx.agent_api_keys.remove(&agent).await?.into()))
+}
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 850e145c54..0f9a574e10 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -151,6 +151,22 @@ pub(crate) type FavoritesServiceType = favorites::domain::service::FavoritesServ
pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
+pub(crate) type AgentApiKeysType = agent_api_keys::domain::AgentKeyService<
+ agent_api_keys::outbound::PgAgentKeyRepo,
+ agent_api_keys::outbound::KmsAgentKeyCipher<cursor_api_key::cipher::AwsKmsCiphertexts>,
+ agent_api_keys::outbound::EntitlementKeyPlans<
+ ai_billing::outbound::RolesTeamsEntitlementSource<
+ UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
+ teams::outbound::team_repo::TeamRepositoryImpl,
+ >,
+ >,
+>;
+
+pub(crate) type BotsServiceType = bots::domain::service::BotServiceImpl<
+ bots::outbound::pg_bots_repo::PgBotsRepo,
+ AuthenticationEventBroker,
+>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: PgPool,
@@ -161,6 +177,10 @@ pub(crate) struct ApiContext {
pub microsoft_auth: Option<Arc<dyn MicrosoftAuth>>,
/// Encrypts users' Cursor API keys.
pub cursor_api_key_cipher: Arc<dyn CursorApiKeyCipher>,
+ /// Agents' own Anthropic and OpenAI API keys.
+ pub agent_api_keys: Arc<AgentApiKeysType>,
+ /// Who may change an agent, for its API key.
+ pub bots: Arc<BotsServiceType>,
/// Owner-bound Codex OAuth lifecycle and cloud target settings.
pub codex_connection: Option<Arc<dyn codex_connection::domain::ConnectionService>>,
pub macro_cache_client: Arc<MacroCache>,
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index f419732f7a..c8bf23d1a3 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -30,6 +30,9 @@ use teams::inbound::axum_router::{
use user_quota::UserQuota;
use utoipa::OpenApi;
+use crate::api::agent_api_keys::{
+ AgentApiKey, AgentApiKeyProvider, PutAgentApiKeyRequest, SavedAgentApiKey,
+};
use crate::api::cursor_api_key::{CursorApiKeyStatus, put_cursor_api_key::PutCursorApiKeyRequest};
use crate::api::email::generate_email_link::GenerateEmailLinkRequest;
use crate::api::email::resend_fusionauth_verify_user_email::ResendFusionauthVerifyUserEmailRequest;
@@ -111,6 +114,9 @@ use model::user::{
crate::api::codex::configure,
crate::api::cursor_api_key::get_cursor_api_key::handler,
crate::api::cursor_api_key::put_cursor_api_key::handler,
+ crate::api::agent_api_keys::get_handler,
+ crate::api::agent_api_keys::put_handler,
+ crate::api::agent_api_keys::delete_handler,
crate::api::cursor_api_key::delete_cursor_api_key::handler,
crate::api::cursor_api_key::list_cursor_models::handler,
crate::api::cursor_api_key::put_cursor_default_model::handler,
@@ -243,6 +249,10 @@ use model::user::{
InitOutlookLinkResponse,
CursorApiKeyStatus,
PutCursorApiKeyRequest,
+ AgentApiKey,
+ SavedAgentApiKey,
+ AgentApiKeyProvider,
+ PutAgentApiKeyRequest,
// GTM invite links
GtmInviteLink,
diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rs
index 6dc2b7f64d..11dd247047 100644
--- a/services/authentication_service/src/server.rs
+++ b/services/authentication_service/src/server.rs
@@ -130,11 +130,14 @@ pub async fn run() -> anyhow::Result<()> {
// A separate KMS key from the Microsoft one by design: sharing it would
// grant whatever decrypts Cursor keys access to the key protecting
// everyone's mailbox credentials.
+ // Agents' own API keys share it: they are read by the same agent harness
+ // and protected by the same IAM grants.
+ let cursor_kms = cursor_api_key::cipher::AwsKmsCiphertexts::new(
+ aws_sdk_kms::Client::new(&aws_config),
+ config.cursor_api_key_kms_key_id()?,
+ );
let cursor_api_key_cipher = Arc::new(cursor_api_key::cipher::KmsCursorApiKeyCipher::new(
- cursor_api_key::cipher::AwsKmsCiphertexts::new(
- aws_sdk_kms::Client::new(&aws_config),
- config.cursor_api_key_kms_key_id()?,
- ),
+ cursor_kms.clone(),
)) as Arc<dyn cursor_api_key::cipher::CursorApiKeyCipher>;
let internal_api_key = config.internal_api_key.clone();
@@ -630,7 +633,7 @@ pub async fn run() -> anyhow::Result<()> {
team_analytics,
)
.with_contacts_enqueuer(contacts_enqueuer)
- .with_event_broker(macro_event_broker)
+ .with_event_broker(macro_event_broker.clone())
.with_open_seat_release((*ai_billing_service).clone())
.with_owned_entity_cleanup(team_owned_entity_cleanup);
let teams_service = Arc::new(teams_service_impl);
@@ -663,6 +666,23 @@ pub async fn run() -> anyhow::Result<()> {
}
});
+ let agent_api_keys = Arc::new(agent_api_keys::domain::AgentKeyService::new(
+ agent_api_keys::outbound::PgAgentKeyRepo::new(db.clone()),
+ agent_api_keys::outbound::KmsAgentKeyCipher::new(cursor_kms),
+ agent_api_keys::outbound::EntitlementKeyPlans::new(
+ ai_billing::outbound::RolesTeamsEntitlementSource::new(
+ user_roles_and_permissions_service.clone(),
+ teams_repo_impl.clone(),
+ ),
+ ),
+ ));
+ // Only to authorize changes to an agent's API key, with the agents' own
+ // rule; agents themselves are created and edited in document storage.
+ let bots = Arc::new(bots::domain::service::BotServiceImpl::new(
+ PgBotsRepo::new(db.clone()),
+ macro_event_broker.clone(),
+ ));
+
let server_result = api::setup_and_serve(
ApiContext {
inbox_connections: Arc::new(email::domain::inbox_entitlement::InboxConnectionService(
@@ -673,6 +693,8 @@ pub async fn run() -> anyhow::Result<()> {
auth_client: Arc::new(auth_client),
microsoft_auth,
cursor_api_key_cipher,
+ agent_api_keys,
+ bots,
codex_connection,
macro_cache_client: Arc::new(macro_cache_client),
stripe_client,