Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(web-search): Tavily-backed web search and fetch for every agent and the SDK (#9725)
Wolf Mermelstein06885e1e1927
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 3c104d8ed1..5dc275d3b4 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -925,6 +925,7 @@"crates/universal_input","crates/upstream_error","crates/user_quota",+ "crates/web_search","crates/workspace-hack","services/agent_harness_service","services/connection_gateway",@@ -1115,6 +1116,7 @@"crates/unfurl","crates/upstream_error","crates/user_quota",+ "crates/web_search","crates/workspace-hack"],"agent_preview": [@@ -2002,6 +2004,7 @@"crates/unfurl","crates/upstream_error","crates/user_quota",+ "crates/web_search","crates/workspace-hack"],"ai_tools": [@@ -2184,6 +2187,7 @@"crates/unfurl","crates/upstream_error","crates/user_quota",+ "crates/web_search","crates/workspace-hack"],"ai_toolset": [@@ -3460,6 +3464,7 @@"crates/unfurl","crates/upstream_error","crates/user_quota",+ "crates/web_search","crates/workspace-hack"],"channel_labels": [@@ -5645,6 +5650,7 @@"crates/upstream_error","crates/user_api_key","crates/user_quota",+ "crates/web_search","crates/webhook","crates/webhook_signature","crates/whatsapp_linked",@@ -15161,6 +15167,111 @@"crates/user_quota","crates/workspace-hack"],+ "web_search": [+ "crates/activity",+ "crates/agent",+ "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/database_env_vars",+ "crates/database_sql",+ "crates/databases",+ "crates/document_sub_type",+ "crates/dynamic_ui",+ "crates/email",+ "crates/email_api_client",+ "crates/email_db_client",+ "crates/email_utils",+ "crates/email_validator",+ "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/web_search",+ "crates/workspace-hack"+ ],"webhook": ["crates/activity","crates/agent",diff --git a/.sqlx/query-4114e7a1ddbe43f4d6015e1e475164a61c4c4786184ec275a18f7896c684ad84.json b/.sqlx/query-4114e7a1ddbe43f4d6015e1e475164a61c4c4786184ec275a18f7896c684ad84.jsondeleted file mode 100644index 9642e71e12..0000000000--- a/.sqlx/query-4114e7a1ddbe43f4d6015e1e475164a61c4c4786184ec275a18f7896c684ad84.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE ai_usage\n SET price_per_million_in = e.price_per_million_in,\n price_per_million_out = e.price_per_million_out,\n price_per_million_cache_read = e.price_per_million_cache_read,\n price_per_million_cache_write = e.price_per_million_cache_write,\n price_per_audio_minute = e.price_per_audio_minute,\n total = CASE\n WHEN (ai_usage.audio_seconds IS NULL) <> (e.price_per_audio_minute IS NULL) THEN NULL\n WHEN ai_usage.cache_read_input_tokens > 0 AND e.price_per_million_cache_read IS NULL THEN NULL\n WHEN ai_usage.cache_write_input_tokens > 0 AND e.price_per_million_cache_write IS NULL THEN NULL\n ELSE (ai_usage.input_tokens::real / 1000000.0::real) * e.price_per_million_in\n + (ai_usage.output_tokens::real / 1000000.0::real) * e.price_per_million_out\n + (ai_usage.cache_read_input_tokens::real / 1000000.0::real) * COALESCE(e.price_per_million_cache_read, 0)\n + (ai_usage.cache_write_input_tokens::real / 1000000.0::real) * COALESCE(e.price_per_million_cache_write, 0)\n + (COALESCE(ai_usage.audio_seconds, 0) / 60.0 * COALESCE(e.price_per_audio_minute, 0))::real\n END\n FROM ai_effective_pricing e\n WHERE ai_usage.model = $1 AND e.model = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "4114e7a1ddbe43f4d6015e1e475164a61c4c4786184ec275a18f7896c684ad84"-}diff --git a/.sqlx/query-a44e4e8e4235fab4cdf5324429e126fefec0e641b67efab41660eac550c28f42.json b/.sqlx/query-425383de9d871d17b149107468088e7964e80345d6cfaa42fb566c5cb0685129.jsonsimilarity index 73%rename from .sqlx/query-a44e4e8e4235fab4cdf5324429e126fefec0e641b67efab41660eac550c28f42.jsonrename to .sqlx/query-425383de9d871d17b149107468088e7964e80345d6cfaa42fb566c5cb0685129.jsonindex 88da14d509..aac31df8e0 100644--- a/.sqlx/query-a44e4e8e4235fab4cdf5324429e126fefec0e641b67efab41660eac550c28f42.json+++ b/.sqlx/query-425383de9d871d17b149107468088e7964e80345d6cfaa42fb566c5cb0685129.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n price_per_million_in AS \"price_per_million_in!\",\n price_per_million_out AS \"price_per_million_out!\",\n price_per_million_cache_read,\n price_per_million_cache_write,\n price_per_audio_minute\n FROM ai_effective_pricing\n WHERE model = $1\n ",+ "query": "\n SELECT\n price_per_million_in AS \"price_per_million_in!\",\n price_per_million_out AS \"price_per_million_out!\",\n price_per_million_cache_read,\n price_per_million_cache_write,\n price_per_audio_minute,\n price_per_provider_credit\n FROM ai_effective_pricing\n WHERE model = $1\n ","describe": {"columns": [{@@ -27,6 +27,11 @@"ordinal": 4,"name": "price_per_audio_minute","type_info": "Float4"+ },+ {+ "ordinal": 5,+ "name": "price_per_provider_credit",+ "type_info": "Float4"}],"parameters": {@@ -39,8 +44,9 @@true,true,true,+ true,true]},- "hash": "a44e4e8e4235fab4cdf5324429e126fefec0e641b67efab41660eac550c28f42"+ "hash": "425383de9d871d17b149107468088e7964e80345d6cfaa42fb566c5cb0685129"}diff --git a/.sqlx/query-48986332f87f1b365a5f30a7c96163f86c3dd1a6e01724d666d1c2b78653d796.json b/.sqlx/query-48986332f87f1b365a5f30a7c96163f86c3dd1a6e01724d666d1c2b78653d796.jsonnew file mode 100644index 0000000000..b1491228b5--- /dev/null+++ b/.sqlx/query-48986332f87f1b365a5f30a7c96163f86c3dd1a6e01724d666d1c2b78653d796.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_pricing (\n model, price_per_million_in, price_per_million_out,\n price_per_million_cache_read, price_per_million_cache_write,\n price_per_audio_minute, price_per_provider_credit\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (model) DO UPDATE\n SET price_per_million_in = EXCLUDED.price_per_million_in,\n price_per_million_out = EXCLUDED.price_per_million_out,\n price_per_million_cache_read = EXCLUDED.price_per_million_cache_read,\n price_per_million_cache_write = EXCLUDED.price_per_million_cache_write,\n price_per_audio_minute = EXCLUDED.price_per_audio_minute,\n price_per_provider_credit = EXCLUDED.price_per_provider_credit,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Float4",+ "Float4",+ "Float4",+ "Float4",+ "Float4",+ "Float4"+ ]+ },+ "nullable": []+ },+ "hash": "48986332f87f1b365a5f30a7c96163f86c3dd1a6e01724d666d1c2b78653d796"+}diff --git a/.sqlx/query-4927dad57dc4b6264e614d7b7baac6c4a8d99a96690e1e2ba16f73259b5d746a.json b/.sqlx/query-4927dad57dc4b6264e614d7b7baac6c4a8d99a96690e1e2ba16f73259b5d746a.jsonnew file mode 100644index 0000000000..5d99873f61--- /dev/null+++ b/.sqlx/query-4927dad57dc4b6264e614d7b7baac6c4a8d99a96690e1e2ba16f73259b5d746a.json@@ -0,0 +1,33 @@+{+ "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 provider_credits,\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, price_per_provider_credit, 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 $19, $20\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Uuid",+ "Text",+ "Int8",+ "Int8",+ "Int8",+ "Int8",+ "Float8",+ "Int8",+ "Float4",+ "Float4",+ "Float4",+ "Float4",+ "Float4",+ "Float4",+ "Float4",+ "Bool",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4927dad57dc4b6264e614d7b7baac6c4a8d99a96690e1e2ba16f73259b5d746a"+}diff --git a/.sqlx/query-8c9182ecd5f9e441857928105f0515902e2a9cd700bc9c636889bfa4497bcd1f.json b/.sqlx/query-8c9182ecd5f9e441857928105f0515902e2a9cd700bc9c636889bfa4497bcd1f.jsonnew file mode 100644index 0000000000..3494afeaa7--- /dev/null+++ b/.sqlx/query-8c9182ecd5f9e441857928105f0515902e2a9cd700bc9c636889bfa4497bcd1f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE ai_usage\n SET price_per_million_in = e.price_per_million_in,\n price_per_million_out = e.price_per_million_out,\n price_per_million_cache_read = e.price_per_million_cache_read,\n price_per_million_cache_write = e.price_per_million_cache_write,\n price_per_audio_minute = e.price_per_audio_minute,\n price_per_provider_credit = e.price_per_provider_credit,\n total = CASE\n WHEN (ai_usage.audio_seconds IS NULL) <> (e.price_per_audio_minute IS NULL) THEN NULL\n WHEN (ai_usage.provider_credits IS NULL) <> (e.price_per_provider_credit IS NULL) THEN NULL\n WHEN ai_usage.cache_read_input_tokens > 0 AND e.price_per_million_cache_read IS NULL THEN NULL\n WHEN ai_usage.cache_write_input_tokens > 0 AND e.price_per_million_cache_write IS NULL THEN NULL\n ELSE (ai_usage.input_tokens::real / 1000000.0::real) * e.price_per_million_in\n + (ai_usage.output_tokens::real / 1000000.0::real) * e.price_per_million_out\n + (ai_usage.cache_read_input_tokens::real / 1000000.0::real) * COALESCE(e.price_per_million_cache_read, 0)\n + (ai_usage.cache_write_input_tokens::real / 1000000.0::real) * COALESCE(e.price_per_million_cache_write, 0)\n + (COALESCE(ai_usage.audio_seconds, 0) / 60.0 * COALESCE(e.price_per_audio_minute, 0))::real\n + (COALESCE(ai_usage.provider_credits, 0)::double precision * COALESCE(e.price_per_provider_credit, 0))::real\n END\n FROM ai_effective_pricing e\n WHERE ai_usage.model = $1 AND e.model = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "8c9182ecd5f9e441857928105f0515902e2a9cd700bc9c636889bfa4497bcd1f"+}diff --git a/.sqlx/query-bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3.json b/.sqlx/query-b3fb0aa8ab84bbdc8650d781db0bf9cdc369b6caaf15398e876445f3988e02e9.jsonsimilarity index 70%rename from .sqlx/query-bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3.jsonrename to .sqlx/query-b3fb0aa8ab84bbdc8650d781db0bf9cdc369b6caaf15398e876445f3988e02e9.jsonindex bdfeb6ebcc..125f6ef9bb 100644--- a/.sqlx/query-bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3.json+++ b/.sqlx/query-b3fb0aa8ab84bbdc8650d781db0bf9cdc369b6caaf15398e876445f3988e02e9.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "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 ",+ "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 provider_credits,\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 price_per_provider_credit,\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": [{@@ -55,36 +55,46 @@},{"ordinal": 10,+ "name": "provider_credits",+ "type_info": "Int8"+ },+ {+ "ordinal": 11,"name": "price_per_million_in","type_info": "Float4"},{- "ordinal": 11,+ "ordinal": 12,"name": "price_per_million_out","type_info": "Float4"},{- "ordinal": 12,+ "ordinal": 13,"name": "price_per_million_cache_read","type_info": "Float4"},{- "ordinal": 13,+ "ordinal": 14,"name": "price_per_million_cache_write","type_info": "Float4"},{- "ordinal": 14,+ "ordinal": 15,"name": "price_per_audio_minute","type_info": "Float4"},{- "ordinal": 15,+ "ordinal": 16,+ "name": "price_per_provider_credit",+ "type_info": "Float4"+ },+ {+ "ordinal": 17,"name": "total","type_info": "Float4"},{- "ordinal": 16,+ "ordinal": 18,"name": "created_at","type_info": "Timestamptz"}@@ -114,8 +124,10 @@true,true,true,+ true,+ true,false]},- "hash": "bee224c961dadc74e3145dcc677bd55038ae91f7eeaeee9b1aa41b14fc86e8e3"+ "hash": "b3fb0aa8ab84bbdc8650d781db0bf9cdc369b6caaf15398e876445f3988e02e9"}diff --git a/.sqlx/query-c15f78da003195440fc4d66057d71dc89c5eb8803a3e90aa742e7399cb591614.json b/.sqlx/query-c15f78da003195440fc4d66057d71dc89c5eb8803a3e90aa742e7399cb591614.jsondeleted file mode 100644index dc47a3a0af..0000000000--- a/.sqlx/query-c15f78da003195440fc4d66057d71dc89c5eb8803a3e90aa742e7399cb591614.json+++ /dev/null@@ -1,19 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO ai_pricing (\n model, price_per_million_in, price_per_million_out,\n price_per_million_cache_read, price_per_million_cache_write,\n price_per_audio_minute\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (model) DO UPDATE\n SET price_per_million_in = EXCLUDED.price_per_million_in,\n price_per_million_out = EXCLUDED.price_per_million_out,\n price_per_million_cache_read = EXCLUDED.price_per_million_cache_read,\n price_per_million_cache_write = EXCLUDED.price_per_million_cache_write,\n price_per_audio_minute = EXCLUDED.price_per_audio_minute,\n updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Float4",- "Float4",- "Float4",- "Float4",- "Float4"- ]- },- "nullable": []- },- "hash": "c15f78da003195440fc4d66057d71dc89c5eb8803a3e90aa742e7399cb591614"-}diff --git a/.sqlx/query-da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b.json b/.sqlx/query-da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b.jsondeleted file mode 100644index 5229eb8109..0000000000--- a/.sqlx/query-da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b.json+++ /dev/null@@ -1,31 +0,0 @@-{- "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, 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": {- "Left": [- "Uuid",- "Text",- "Text",- "Uuid",- "Text",- "Int8",- "Int8",- "Int8",- "Int8",- "Float8",- "Float4",- "Float4",- "Float4",- "Float4",- "Float4",- "Float4",- "Bool",- "Uuid"- ]- },- "nullable": []- },- "hash": "da8e3070dec83034ff6dc9b198ee160dbb5191bd0de49d8eacb7768e401acf3b"-}diff --git a/Cargo.lock b/Cargo.lockindex 7bcdd4925a..eca74df042 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -658,6 +658,7 @@ dependencies = ["pipedream_mcp","prompt","properties",+ "rate_limit","rdkafka","readonly_pool","redis",@@ -700,6 +701,7 @@ dependencies = ["utoipa","utoipa-swagger-ui","uuid",+ "web_search","workspace-hack",]@@ -1263,6 +1265,7 @@ dependencies = ["url","utoipa","uuid",+ "web_search","workspace-hack",]@@ -1466,7 +1469,6 @@ dependencies = ["macro_env_var","macro_user_id","rand 0.9.4",- "regex","reqwest 0.13.4","schemars 1.2.1","serde",@@ -22042,6 +22044,40 @@ dependencies = ["string_cache_codegen 0.6.1",]+[[package]]+name = "web_search"+version = "0.1.0"+dependencies = [+ "ai_billing",+ "ai_toolset",+ "ai_usage",+ "anyhow",+ "async-trait",+ "axum",+ "axum-extra",+ "chrono",+ "http-body-util",+ "macro_authorization",+ "macro_env_var",+ "macro_user_id",+ "macro_uuid",+ "model_user",+ "rate_limit",+ "reqwest 0.13.4",+ "rootcause",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "tower 0.5.3",+ "tracing",+ "url",+ "utoipa",+ "wiremock",+ "workspace-hack",+]+[[package]]name = "webbrowser"version = "1.2.2"diff --git a/Cargo.toml b/Cargo.tomlindex 9fe1b257dc..1429646eb1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -57,6 +57,7 @@ members = ["crates/models_forms","crates/embedding","crates/image_generation",+ "crates/web_search","crates/dictation","crates/email_api_client","crates/entity_mutation",diff --git a/apps/docs/AI/mcp/tools/web-fetch.mdx b/apps/docs/AI/mcp/tools/web-fetch.mdxindex 4d03bcc299..6d34c5ab9b 100644--- a/apps/docs/AI/mcp/tools/web-fetch.mdx+++ b/apps/docs/AI/mcp/tools/web-fetch.mdx@@ -1,15 +1,16 @@---title: WebFetchdescription: >-- Fetch the contents of a web page using Claude's built-in web fetch tool.+ Read the text of one public web page as Markdown.---# WebFetch-Fetch the contents of a web page using Claude's built-in web fetch tool.+Read the text of one public web page as Markdown. Use it on a URL the user gave you or one WebSearch returned, when the snippet is not enough. Pages that need a login, or that render only with JavaScript, may fail. Cite the URL you read.## Parameters| Parameter | Type | Required | Description || --- | --- | --- | --- |-| `input` | string | Yes | The URL to fetch or an instruction describing what to fetch. |+| `url` | string | Yes | The `http` or `https` URL of the page. |+| `maxChars` | integer | No | Most characters of page text to return, 1 to 100,000 (default 20,000). |diff --git a/apps/docs/AI/mcp/tools/web-search.mdx b/apps/docs/AI/mcp/tools/web-search.mdxindex 731b12be1c..4ec674a73b 100644--- a/apps/docs/AI/mcp/tools/web-search.mdx+++ b/apps/docs/AI/mcp/tools/web-search.mdx@@ -1,15 +1,21 @@---title: WebSearchdescription: >-- Search the web for information using Claude's built-in web search tool.+ Search the public web.---# WebSearch-Search the web for information using Claude's built-in web search tool.+Search the public web. Returns up to `maxResults` pages, each with its title, URL, a query-relevant snippet and, for news, its publication date. Snippets are often enough to answer; call WebFetch on a result's URL when you need the full page. Cite the URLs you use.## Parameters| Parameter | Type | Required | Description || --- | --- | --- | --- |-| `input` | string | Yes | The search query or instruction. |+| `query` | string | Yes | What to search for, in natural language or keywords (at most 400 characters). |+| `domains` | string[] | No | Only return pages from these domains, e.g. `["docs.rs", "github.com"]`. |+| `excludeDomains` | string[] | No | Never return pages from these domains. |+| `since` | string | No | Only return pages published on or after this date (`YYYY-MM-DD`). |+| `topic` | `"general"` \| `"news"` | No | `news` for recent articles with publication dates; `general` (the default) otherwise. |+| `maxResults` | integer | No | How many results to return, 1 to 20 (default 5). |+| `includeContent` | boolean | No | Also return each page's text as Markdown (up to 8,000 characters per result). |diff --git a/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx b/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsxindex 16b8e550f7..bfff1cafa1 100644--- a/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx+++ b/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx@@ -207,14 +207,10 @@ const LIST_FAILED = macro(const WEB_SEARCH_FAILED = macro('web-search','WebSearch',- { input: 'macro launch status' },- {- tool_use_id: 'web-search',- content: {- type: 'web_search_tool_result_error',- error_code: 'unavailable',- },- }+ { query: 'macro launch status' },+ 'web_search_throttled: Web search is busy; try again shortly',+ 'failed',+ 'web_search_throttled: Web search is busy; try again shortly');const READ_FILE = tool('read-file', 'Read', {kind: 'read',diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.test.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.test.tsxindex dd754bb161..18986d59f9 100644--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.test.tsx@@ -110,7 +110,7 @@ describe('MacroToolCall unfinished calls', () => {<MacroToolCalldetail={{kind: 'macro',- input: { input: query() },+ input: { query: query() },output: null,error: null,}}diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsxindex beddabe81a..b95035d6ff 100644--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx@@ -65,15 +65,6 @@ export function MacroToolCall(props: {if (input && 'url' in input && typeof input.url === 'string') {return input.url;}- if (- (props.common.label === 'WebSearch' ||- props.common.label === 'WebFetch') &&- input &&- 'input' in input &&- typeof input.input === 'string'- ) {- return input.input;- }if ((props.common.label === 'SearchSkills' ||props.common.label === 'NameSearch') &&@@ -177,24 +168,9 @@ function resultSummary(response: ToolResponse | undefined): string | undefined {if ('items' in data && Array.isArray(data.items)) {return `${data.items.length} ${data.items.length === 1 ? 'item' : 'items'}`;}- if (- isResponse(response, 'WebSearch') &&- Array.isArray(response.data.content)- ) {- const count = response.data.content.length;- return `${count} ${count === 1 ? 'result' : 'results'}`;- }return undefined;}-/** The generated NamedTool type does not correlate its name and data unions. */-function isResponse<Name extends ToolName>(- response: ToolResponse | undefined,- name: Name-): response is NamedTool<Name, 'response'> {- return response?.name === name;-}-function responseError(response: ToolResponse | undefined): string | undefined {if (!response) return undefined;const data = response.data;@@ -204,17 +180,5 @@ function responseError(response: ToolResponse | undefined): string | undefined {? data.message || 'The tool did not succeed.': 'The tool did not succeed.';}- if (- isResponse(response, 'WebFetch') &&- response.data.content.type === 'web_fetch_tool_result_error'- ) {- return response.data.content.error_code;- }- if (- isResponse(response, 'WebSearch') &&- !Array.isArray(response.data.content)- ) {- return response.data.content.error_code;- }return undefined;}diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsxindex 7b5b5050d5..504c68733f 100644--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx@@ -1165,30 +1165,6 @@ describe('ToolCallPart result summaries', () => {output: { success: false, message: 'Denied' },reason: 'Denied',},- {- name: 'WebFetch',- input: { input: 'https://status.macro.com' },- output: {- tool_use_id: 'call-1',- content: {- type: 'web_fetch_tool_result_error',- error_code: 'url_not_accessible',- },- },- reason: 'url_not_accessible',- },- {- name: 'WebSearch',- input: { input: 'launch checklist' },- output: {- tool_use_id: 'call-1',- content: {- type: 'web_search_tool_result_error',- error_code: 'unavailable',- },- },- reason: 'unavailable',- },])('shows a validated $name response failure even if the call completed',({ name, input, output, reason }) => {diff --git a/apps/web/src/lib/core/component/AI/component/tool/WebFetch.tsx b/apps/web/src/lib/core/component/AI/component/tool/WebFetch.tsxindex c5d93a51e3..75bcfb3444 100644--- a/apps/web/src/lib/core/component/AI/component/tool/WebFetch.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/WebFetch.tsx@@ -2,19 +2,18 @@ import Globe from '@icon/system/regular/globe.svg';import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';-// Runtime type for successful web fetch (schema differs from generated types)const handler = createToolRenderer({name: 'WebFetch',render: (ctx) => (<BaseTool icon={Globe} renderContext={ctx.renderContext} type="call">{ctx.response ? 'Fetched' : 'Fetch'}{' '}<a- href={ctx.tool.data.input}+ href={ctx.tool.data.url}target="_blank"rel="noopener noreferrer"class="italic text-link hover:text-link-hover visited:text-link-visited underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2 hover:decoration-current">- {ctx.tool.data.input}+ {ctx.tool.data.url}</a></BaseTool>),diff --git a/apps/web/src/lib/core/component/AI/component/tool/WebSearch.tsx b/apps/web/src/lib/core/component/AI/component/tool/WebSearch.tsxindex 6f1f4f0e30..52073f0f6f 100644--- a/apps/web/src/lib/core/component/AI/component/tool/WebSearch.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/WebSearch.tsx@@ -9,10 +9,7 @@ const handler = createToolRenderer({name: 'WebSearch',render: (ctx) => {const [isExpanded, setIsExpanded] = createSignal(false);- const results = () => {- const content = ctx.response?.data.content;- return Array.isArray(content) ? content : [];- };+ const results = () => ctx.response?.data.results ?? [];const hitCount = () => results().length;const hasResults = () => hitCount() > 0;const statusText = () => {@@ -48,7 +45,7 @@ const handler = createToolRenderer({<div class="flex min-w-0 flex-1 items-center gap-2 overflow-hidden"><span class="min-w-0 truncate">{ctx.response ? 'Searched for' : 'Search for'}{' '}- <span class="text-ink">{ctx.tool.data.input}</span>+ <span class="text-ink">{ctx.tool.data.query}</span></span></div><Tool.ResultTogglediff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.tsindex 3f1f024a6f..10a1a2fb46 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts@@ -73,6 +73,11 @@ import type {UpsertProjectionRequest,UsageRequest,UsageSummary,+ WebErrorBody,+ WebFetch,+ WebFetchResponse,+ WebSearch,+ WebSearchResponse,} from './schemas';/**@@ -3370,3 +3375,171 @@ export const structuredCompletion = async (headers: res.headers,} as structuredCompletionResponse;};++/**+ * @summary Read one public web page as Markdown. Charged to the acting user's AI allowance.+ */+export type fetchWebPageResponse200 = {+ data: WebFetchResponse;+ status: 200;+};++export type fetchWebPageResponse400 = {+ data: WebErrorBody;+ status: 400;+};++export type fetchWebPageResponse401 = {+ data: void;+ status: 401;+};++export type fetchWebPageResponse402 = {+ data: WebErrorBody;+ status: 402;+};++export type fetchWebPageResponse422 = {+ data: WebErrorBody;+ status: 422;+};++export type fetchWebPageResponse429 = {+ data: void;+ status: 429;+};++export type fetchWebPageResponse502 = {+ data: WebErrorBody;+ status: 502;+};++export type fetchWebPageResponse503 = {+ data: WebErrorBody;+ status: 503;+};++export type fetchWebPageResponseSuccess = fetchWebPageResponse200 & {+ headers: Headers;+};+export type fetchWebPageResponseError = (+ | fetchWebPageResponse400+ | fetchWebPageResponse401+ | fetchWebPageResponse402+ | fetchWebPageResponse422+ | fetchWebPageResponse429+ | fetchWebPageResponse502+ | fetchWebPageResponse503+) & {+ headers: Headers;+};++export type fetchWebPageResponse =+ | fetchWebPageResponseSuccess+ | fetchWebPageResponseError;++export const getFetchWebPageUrl = () => {+ return `/web/fetch`;+};++export const fetchWebPage = async (+ webFetch: WebFetch,+ options?: RequestInit+): Promise<fetchWebPageResponse> => {+ const res = await fetch(getFetchWebPageUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(webFetch),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: fetchWebPageResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as fetchWebPageResponse;+};++/**+ * @summary Search the public web. Charged to the acting user's AI allowance.+ */+export type searchWebResponse200 = {+ data: WebSearchResponse;+ status: 200;+};++export type searchWebResponse400 = {+ data: WebErrorBody;+ status: 400;+};++export type searchWebResponse401 = {+ data: void;+ status: 401;+};++export type searchWebResponse402 = {+ data: WebErrorBody;+ status: 402;+};++export type searchWebResponse429 = {+ data: void;+ status: 429;+};++export type searchWebResponse502 = {+ data: WebErrorBody;+ status: 502;+};++export type searchWebResponse503 = {+ data: WebErrorBody;+ status: 503;+};++export type searchWebResponseSuccess = searchWebResponse200 & {+ headers: Headers;+};+export type searchWebResponseError = (+ | searchWebResponse400+ | searchWebResponse401+ | searchWebResponse402+ | searchWebResponse429+ | searchWebResponse502+ | searchWebResponse503+) & {+ headers: Headers;+};++export type searchWebResponse =+ | searchWebResponseSuccess+ | searchWebResponseError;++export const getSearchWebUrl = () => {+ return `/web/search`;+};++export const searchWeb = async (+ webSearch: WebSearch,+ options?: RequestInit+): Promise<searchWebResponse> => {+ const res = await fetch(getSearchWebUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(webSearch),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: searchWebResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as searchWebResponse;+};diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiFeature.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiFeature.tsindex d634856598..a701c66df4 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiFeature.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/aiFeature.ts@@ -29,4 +29,5 @@ export const AiFeature = {dictation: 'dictation',image_generation: 'image_generation',email_focus: 'email_focus',+ web_search: 'web_search',} as const;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.tsindex ccfceae162..578e4151ac 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts@@ -258,6 +258,7 @@ export * from './price';export * from './pricePricePerAudioMinute';export * from './pricePricePerMillionCacheRead';export * from './pricePricePerMillionCacheWrite';+export * from './pricePricePerProviderCredit';export * from './projectionStateResponse';export * from './projectionStateResponseData';export * from './projectionStateResponseError';@@ -283,6 +284,7 @@ export * from './setPricingRequestPricePerMilCacheRead';export * from './setPricingRequestPricePerMilCacheWrite';export * from './setPricingRequestPricePerMilIn';export * from './setPricingRequestPricePerMilOut';+export * from './setPricingRequestPricePerProviderCredit';export * from './sharePermissionV2';export * from './sharePermissionV2ChannelSharePermissions';export * from './sharePermissionV2LinkShare';@@ -353,6 +355,7 @@ export * from './upsertProjectionRequestOutputSchemaAnyOf';export * from './usage';export * from './usageAudioSeconds';export * from './usagePrice';+export * from './usageProviderCredits';export * from './usageRequest';export * from './usageRequestFrom';export * from './usageRequestUntil';@@ -364,4 +367,21 @@ export * from './webCitation';export * from './webCitationDescription';export * from './webCitationFaviconUrl';export * from './webCitationImageUrl';+export * from './webErrorBody';+export * from './webFetch';+export * from './webFetchMaxChars';+export * from './webFetchResponse';+export * from './webFetchResponseTitle';+export * from './webSearch';+export * from './webSearchDomains';+export * from './webSearchExcludeDomains';+export * from './webSearchIncludeContent';+export * from './webSearchMaxResults';+export * from './webSearchResponse';+export * from './webSearchResult';+export * from './webSearchResultContent';+export * from './webSearchResultPublishedAt';+export * from './webSearchSince';+export * from './webSearchTopic';+export * from './webSearchTopicProperty';export * from './withChatId';diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/price.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/price.tsindex aef725f8d8..0ed221c043 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/price.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/price.ts@@ -7,23 +7,26 @@import type { PricePricePerAudioMinute } from './pricePricePerAudioMinute';import type { PricePricePerMillionCacheRead } from './pricePricePerMillionCacheRead';import type { PricePricePerMillionCacheWrite } from './pricePricePerMillionCacheWrite';+import type { PricePricePerProviderCredit } from './pricePricePerProviderCredit';/*** Rates applied to an invocation and its resolved dollar cost.*/export interface Price {- /** Price per audio minute (USD), absent for token billing. */+ /** Price per audio minute (USD), absent for token and credit billing. */price_per_audio_minute?: PricePricePerAudioMinute;/** Price per million cache-read input tokens (USD), absent when the model-has no published rate and for audio billing. */+has no published rate and for audio and credit billing. */price_per_million_cache_read?: PricePricePerMillionCacheRead;/** Price per million cache-write input tokens (USD), absent when the model-has no published rate and for audio billing. */+has no published rate and for audio and credit billing. */price_per_million_cache_write?: PricePricePerMillionCacheWrite;- /** Price per million input tokens (USD); zero for audio billing. */+ /** Price per million input tokens (USD); zero for audio and credit billing. */price_per_million_in: number;- /** Price per million output tokens (USD); zero for audio billing. */+ /** Price per million output tokens (USD); zero for audio and credit billing. */price_per_million_out: number;+ /** Price per vendor credit (USD), absent for token and audio billing. */+ price_per_provider_credit?: PricePricePerProviderCredit;/** Total cost (USD). */total: number;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerAudioMinute.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerAudioMinute.tsindex 16a9115c96..dac6fa109a 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerAudioMinute.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerAudioMinute.ts@@ -6,6 +6,6 @@*//**- * Price per audio minute (USD), absent for token billing.+ * Price per audio minute (USD), absent for token and credit billing.*/export type PricePricePerAudioMinute = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheRead.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheRead.tsindex be03462d96..f570a03287 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheRead.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheRead.ts@@ -7,6 +7,6 @@/*** Price per million cache-read input tokens (USD), absent when the model-has no published rate and for audio billing.+has no published rate and for audio and credit billing.*/export type PricePricePerMillionCacheRead = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheWrite.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheWrite.tsindex 1d6481b30f..751722dbc6 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheWrite.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerMillionCacheWrite.ts@@ -7,6 +7,6 @@/*** Price per million cache-write input tokens (USD), absent when the model-has no published rate and for audio billing.+has no published rate and for audio and credit billing.*/export type PricePricePerMillionCacheWrite = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerProviderCredit.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerProviderCredit.tsnew file mode 100644index 0000000000..f4330a5c79--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pricePricePerProviderCredit.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Price per vendor credit (USD), absent for token and audio billing.+ */+export type PricePricePerProviderCredit = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequest.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequest.tsindex 9aee8d54e7..5404753a88 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequest.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequest.ts@@ -9,6 +9,7 @@ import type { SetPricingRequestPricePerMilCacheRead } from './setPricingRequestPimport type { SetPricingRequestPricePerMilCacheWrite } from './setPricingRequestPricePerMilCacheWrite';import type { SetPricingRequestPricePerMilIn } from './setPricingRequestPricePerMilIn';import type { SetPricingRequestPricePerMilOut } from './setPricingRequestPricePerMilOut';+import type { SetPricingRequestPricePerProviderCredit } from './setPricingRequestPricePerProviderCredit';/*** Request body for [`set_pricing_handler`].@@ -28,4 +29,6 @@ has no published rate: calls that report cache writes then stay unpriced. */price_per_mil_in?: SetPricingRequestPricePerMilIn;/** New price per million output tokens (USD). Required for token pricing. */price_per_mil_out?: SetPricingRequestPricePerMilOut;+ /** Price per vendor credit (USD), or null unless the model bills in credits. */+ price_per_provider_credit?: SetPricingRequestPricePerProviderCredit;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequestPricePerProviderCredit.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequestPricePerProviderCredit.tsnew file mode 100644index 0000000000..79062d3255--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/setPricingRequestPricePerProviderCredit.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Price per vendor credit (USD), or null unless the model bills in credits.+ */+export type SetPricingRequestPricePerProviderCredit = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usage.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usage.tsindex f0e0a5e1b3..0b90e4a9e3 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usage.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usage.ts@@ -6,36 +6,42 @@*/import type { UsageAudioSeconds } from './usageAudioSeconds';import type { UsagePrice } from './usagePrice';+import type { UsageProviderCredits } from './usageProviderCredits';/*** Measured usage for one invocation.*/export interface Usage {- /** Audio duration in seconds, absent for token billing. */+ /** Audio duration in seconds, absent for token and credit billing. */audio_seconds?: UsageAudioSeconds;/**- * Input tokens read from a prompt cache; zero for audio billing.+ * Input tokens read from a prompt cache; zero for audio and credit billing.* @minimum 0*/cache_read_input_tokens: number;/**- * Input tokens written to a prompt cache; zero for audio billing.+ * Input tokens written to a prompt cache; zero for audio and credit billing.* @minimum 0*/cache_write_input_tokens: number;/** Recording timestamp. */created_at: string;/**- * Uncached input tokens; zero for audio billing.+ * Uncached input tokens; zero for audio and credit billing.* @minimum 0*/input_tokens: number;/** Provider model identifier. */model: string;/**- * Output tokens; zero for audio billing.+ * Output tokens; zero for audio and credit billing.* @minimum 0*/output_tokens: number;price?: UsagePrice;+ /**+ * Vendor credits consumed, absent for token and audio billing.+ * @minimum 0+ */+ provider_credits?: UsageProviderCredits;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageAudioSeconds.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageAudioSeconds.tsindex ca432073c1..d8c8cee8fc 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageAudioSeconds.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageAudioSeconds.ts@@ -6,6 +6,6 @@*//**- * Audio duration in seconds, absent for token billing.+ * Audio duration in seconds, absent for token and credit billing.*/export type UsageAudioSeconds = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageProviderCredits.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageProviderCredits.tsnew file mode 100644index 0000000000..89956db447--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/usageProviderCredits.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Vendor credits consumed, absent for token and audio billing.+ * @minimum 0+ */+export type UsageProviderCredits = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webErrorBody.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webErrorBody.tsnew file mode 100644index 0000000000..0461887b7e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webErrorBody.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Machine-readable failure of a web request.+ */+export interface WebErrorBody {+ /** Stable failure code. */+ code: string;+ /** Explanation without provider diagnostics. */+ error: string;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetch.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetch.tsnew file mode 100644index 0000000000..f0031dcec6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetch.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebFetchMaxChars } from './webFetchMaxChars';++/**+ * Read one public web page.+ */+export interface WebFetch {+ /**+ * Most characters of page text to return, 1 to 100,000 (default 20,000).+ * @minimum 0+ */+ maxChars?: WebFetchMaxChars;+ /** The `http` or `https` URL of the page. */+ url: string;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchMaxChars.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchMaxChars.tsnew file mode 100644index 0000000000..a3409c4864--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchMaxChars.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Most characters of page text to return, 1 to 100,000 (default 20,000).+ * @minimum 0+ */+export type WebFetchMaxChars = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchResponse.tsnew file mode 100644index 0000000000..8ada19ff6f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchResponse.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebFetchResponseTitle } from './webFetchResponseTitle';++/**+ * The text of a fetched page.+ */+export interface WebFetchResponse {+ /** The page text as Markdown, cut to `maxChars`. */+ content: string;+ /** The page title, when the provider reports one. */+ title?: WebFetchResponseTitle;+ /** Whether `content` was cut to `maxChars`. */+ truncated: boolean;+ /** The URL that was read. */+ url: string;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchResponseTitle.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchResponseTitle.tsnew file mode 100644index 0000000000..18c6caf9f9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webFetchResponseTitle.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The page title, when the provider reports one.+ */+export type WebFetchResponseTitle = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearch.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearch.tsnew file mode 100644index 0000000000..28ad6d621c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearch.ts@@ -0,0 +1,34 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebSearchDomains } from './webSearchDomains';+import type { WebSearchExcludeDomains } from './webSearchExcludeDomains';+import type { WebSearchIncludeContent } from './webSearchIncludeContent';+import type { WebSearchMaxResults } from './webSearchMaxResults';+import type { WebSearchSince } from './webSearchSince';+import type { WebSearchTopicProperty } from './webSearchTopicProperty';++/**+ * Search the public web.+ */+export interface WebSearch {+ /** Only return pages from these domains, e.g. `["docs.rs", "github.com"]`. */+ domains?: WebSearchDomains;+ /** Never return pages from these domains. */+ excludeDomains?: WebSearchExcludeDomains;+ /** Also return each page's text as Markdown (up to 8,000 characters per result). */+ includeContent?: WebSearchIncludeContent;+ /**+ * How many results to return, 1 to 20 (default 5).+ * @minimum 0+ */+ maxResults?: WebSearchMaxResults;+ /** What to search for, in natural language or keywords (at most 400 characters). */+ query: string;+ /** Only return pages published on or after this date (`YYYY-MM-DD`). */+ since?: WebSearchSince;+ topic?: WebSearchTopicProperty;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchDomains.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchDomains.tsnew file mode 100644index 0000000000..5f9f1e9531--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchDomains.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Only return pages from these domains, e.g. `["docs.rs", "github.com"]`.+ */+export type WebSearchDomains = string[] | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchExcludeDomains.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchExcludeDomains.tsnew file mode 100644index 0000000000..4544837331--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchExcludeDomains.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Never return pages from these domains.+ */+export type WebSearchExcludeDomains = string[] | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchIncludeContent.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchIncludeContent.tsnew file mode 100644index 0000000000..eb56bec94c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchIncludeContent.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Also return each page's text as Markdown (up to 8,000 characters per result).+ */+export type WebSearchIncludeContent = boolean | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchMaxResults.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchMaxResults.tsnew file mode 100644index 0000000000..3fd93e29a3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchMaxResults.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * How many results to return, 1 to 20 (default 5).+ * @minimum 0+ */+export type WebSearchMaxResults = number | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResponse.tsnew file mode 100644index 0000000000..ad3fe7bd45--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebSearchResult } from './webSearchResult';++/**+ * The pages a search found, best match first.+ */+export interface WebSearchResponse {+ /** Results, best match first. Empty when nothing matched. */+ results: WebSearchResult[];+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResult.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResult.tsnew file mode 100644index 0000000000..1eb5dd874a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResult.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebSearchResultContent } from './webSearchResultContent';+import type { WebSearchResultPublishedAt } from './webSearchResultPublishedAt';++/**+ * One page a search found.+ */+export interface WebSearchResult {+ /** The page text as Markdown, when `includeContent` was set. */+ content?: WebSearchResultContent;+ /** When the page was published, as the search provider reports it. */+ publishedAt?: WebSearchResultPublishedAt;+ /** The part of the page most relevant to the query. */+ snippet: string;+ /** The page title. */+ title: string;+ /** The page URL; cite it when you use the result. */+ url: string;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResultContent.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResultContent.tsnew file mode 100644index 0000000000..59768ce9f1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResultContent.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The page text as Markdown, when `includeContent` was set.+ */+export type WebSearchResultContent = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResultPublishedAt.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResultPublishedAt.tsnew file mode 100644index 0000000000..ce6fa078e9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchResultPublishedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * When the page was published, as the search provider reports it.+ */+export type WebSearchResultPublishedAt = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchSince.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchSince.tsnew file mode 100644index 0000000000..5e8f2843c9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchSince.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Only return pages published on or after this date (`YYYY-MM-DD`).+ */+export type WebSearchSince = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchTopic.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchTopic.tsnew file mode 100644index 0000000000..6e7664a0b6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchTopic.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The kind of results a search favours.+ */+export type WebSearchTopic =+ (typeof WebSearchTopic)[keyof typeof WebSearchTopic];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const WebSearchTopic = {+ general: 'general',+ news: 'news',+} as const;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchTopicProperty.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchTopicProperty.tsnew file mode 100644index 0000000000..5ecbfe694c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/webSearchTopicProperty.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebSearchTopic } from './webSearchTopic';++export type WebSearchTopicProperty = null | WebSearchTopic;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 6fe742a2c4..5c200d5c41 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -19987,123 +19987,60 @@ export const UploadFileResponse = z.object({sizeBytes: z.number().int().gte(0),});-export const WebFetch = z.object({ input: z.string() });+export const WebFetch = z.object({+ url: z.string(),+ maxChars: z.union([z.number().int().gte(0), z.null()]).optional(),+});export const WebFetchResponse = z.object({- tool_use_id: z.string(),- content: z.any().superRefine((x, ctx) => {- const schemas = [- z.intersection(- z.object({- url: z.string(),- content: z.object({- source: z.any().superRefine((x, ctx) => {- const schemas = [- z.object({- media_type: z.string(),- data: z.string(),- type: z.literal('text'),- }),- z.object({- media_type: z.string(),- data: z.string(),- type: z.literal('base64'),- }),- ];- const errors = schemas.reduce<z.ZodError[]>(- (errors, schema) =>- ((result) =>- result.error ? [...errors, result.error] : errors)(- schema.safeParse(x)- ),- []- );- if (schemas.length - errors.length !== 1) {- ctx.addIssue({- path: ctx.path,- code: 'invalid_union',- unionErrors: errors,- message: 'Invalid input: Should pass single schema',- });- }- }),- title: z.union([z.string(), z.null()]).optional(),- citations: z- .union([z.object({ enabled: z.boolean() }), z.null()])- .optional(),- }),- retrieved_at: z.string(),- }),- z.object({ type: z.literal('web_fetch_result') })- ),- z.intersection(- z.object({- error_code: z.any().superRefine((x, ctx) => {- const schemas = [- z.literal('invalid_input'),- z.literal('url_too_long'),- z.literal('url_not_allowed'),- z.literal('url_not_accessible'),- z.literal('too_many_requests'),- z.literal('unsupported_content_type'),- z.literal('max_uses_exceeded'),- z.literal('unavailable'),- ];- const errors = schemas.reduce<z.ZodError[]>(- (errors, schema) =>- ((result) =>- result.error ? [...errors, result.error] : errors)(- schema.safeParse(x)- ),- []- );- if (schemas.length - errors.length !== 1) {- ctx.addIssue({- path: ctx.path,- code: 'invalid_union',- unionErrors: errors,- message: 'Invalid input: Should pass single schema',- });- }- }),- }),- z.object({ type: z.literal('web_fetch_tool_result_error') })- ),- ];- const errors = schemas.reduce<z.ZodError[]>(- (errors, schema) =>- ((result) => (result.error ? [...errors, result.error] : errors))(- schema.safeParse(x)- ),- []- );- if (schemas.length - errors.length !== 1) {- ctx.addIssue({- path: ctx.path,- code: 'invalid_union',- unionErrors: errors,- message: 'Invalid input: Should pass single schema',- });- }- }),+ url: z.string(),+ title: z.union([z.string(), z.null()]).optional(),+ content: z.string(),+ truncated: z.boolean(),});-export const WebSearch = z.object({ input: z.string() });+export const WebSearch = z.object({+ query: z.string(),+ domains: z.union([z.array(z.string()), z.null()]).optional(),+ excludeDomains: z.union([z.array(z.string()), z.null()]).optional(),+ since: z.union([z.string().date(), z.null()]).optional(),+ topic: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('general'), z.literal('news')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ maxResults: z.union([z.number().int().gte(0).lte(255), z.null()]).optional(),+ includeContent: z.union([z.boolean(), z.null()]).optional(),+});export const WebSearchResponse = z.object({- content: z.union([- z.array(- z.object({- title: z.string(),- url: z.string(),- encrypted_content: z.union([z.string(), z.null()]).optional(),- page_age: z.union([z.string(), z.null()]).optional(),- type: z.literal('web_search_result'),- })- ),- z.object({ type: z.string(), error_code: z.string() }),- ]),- tool_use_id: z.string(),+ results: z.array(+ z.object({+ title: z.string(),+ url: z.string(),+ snippet: z.string(),+ publishedAt: z.union([z.string(), z.null()]).optional(),+ content: z.union([z.string(), z.null()]).optional(),+ })+ ),});export const DescribeCodeTools = zdiff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 71295bba71..31953fab6e 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -4927,55 +4927,9 @@ export type ShareLinkScope = 'off' | 'public' | 'team';*/export type ShareAccess = 'off' | 'view' | 'comment' | 'edit';/**- * Content of a web fetch response - either a successful result or an error+ * The kind of results a search favours.*/-export type WebFetchContent =- | (WebFetchResult & {- type: 'web_fetch_result';- })- | (WebFetchToolError & {- type: 'web_fetch_tool_result_error';- });-/**- * Source content of a fetched document- */-export type WebFetchSource =- | {- media_type: string;- data: string;- type: 'text';- }- | {- media_type: string;- data: string;- type: 'base64';- };-/**- * Possible error codes for web fetch failures- */-export type WebFetchErrorCode =- | 'invalid_input'- | 'url_too_long'- | 'url_not_allowed'- | 'url_not_accessible'- | 'too_many_requests'- | 'unsupported_content_type'- | 'max_uses_exceeded'- | 'unavailable';-/**- * Content of a web search response — either search results or an error.- */-export type WebSearchContent = SearchResult[] | WebSearchToolError;-/**- * A single search result from web search- */-export type SearchResult = {- title: string;- url: string;- encrypted_content?: string | null;- page_age?: string | null;- type: 'web_search_result';-};+export type WebSearchTopic = 'general' | 'news';/*** Available SDK workflow guides.*/@@ -16323,83 +16277,105 @@ export interface UploadFileResponse {sizeBytes: number;}/**- * Fetch the contents of a web page using Claude's built-in web fetch tool.+ * Read the text of one public web page as Markdown. Use it on a URL the user gave you or one WebSearch returned, when the snippet is not enough. Pages that need a login, or that render only with JavaScript, may fail. Cite the URL you read.*/export interface WebFetch {/**- * The URL to fetch or an instruction describing what to fetch.+ * The `http` or `https` URL of the page.*/- input: string;+ url: string;+ /**+ * Most characters of page text to return, 1 to 100,000 (default 20,000).+ */+ maxChars?: number | null;}/**- * Web fetch tool response content returned by Claude when using the web_fetch tool+ * The text of a fetched page.*/export interface WebFetchResponse {- tool_use_id: string;- content: WebFetchContent;-}-/**- * Successful web fetch result containing the fetched content- */-export interface WebFetchResult {/**- * The URL that was fetched+ * The URL that was read.*/url: string;- content: WebFetchDocument;/**- * Timestamp when the content was retrieved+ * The page title, when the provider reports one.*/- retrieved_at: string;-}-/**- * Document content from a web fetch- */-export interface WebFetchDocument {- source: WebFetchSource;+ title?: string | null;/**- * Optional title of the document+ * The page text as Markdown, cut to `maxChars`.*/- title?: string | null;+ content: string;/**- * Optional citations configuration+ * Whether `content` was cut to `maxChars`.*/- citations?: CitationsConfig | null;-}-/**- * Citations configuration for web fetch- */-export interface CitationsConfig {- enabled: boolean;-}-/**- * Error returned when web fetch fails- */-export interface WebFetchToolError {- error_code: WebFetchErrorCode;+ truncated: boolean;}/**- * Search the web for information using Claude's built-in web search tool.+ * Search the public web. Returns up to `maxResults` pages, each with its title, URL, a query-relevant snippet and, for news, its publication date. Snippets are often enough to answer; call WebFetch on a result's URL when you need the full page. Cite the URLs you use.*/export interface WebSearch {/**- * The search query or instruction.+ * What to search for, in natural language or keywords (at most 400 characters).*/- input: string;+ query: string;+ /**+ * Only return pages from these domains, e.g. `["docs.rs", "github.com"]`.+ */+ domains?: string[] | null;+ /**+ * Never return pages from these domains.+ */+ excludeDomains?: string[] | null;+ /**+ * Only return pages published on or after this date (`YYYY-MM-DD`).+ */+ since?: string | null;+ /**+ * `news` for recent articles with publication dates; `general` (the default) otherwise.+ */+ topic?: WebSearchTopic | null;+ /**+ * How many results to return, 1 to 20 (default 5).+ */+ maxResults?: number | null;+ /**+ * Also return each page's text as Markdown (up to 8,000 characters per result).+ */+ includeContent?: boolean | null;}/**- * Web search response content returned by Claude when using the web_search tool+ * The pages a search found, best match first.*/export interface WebSearchResponse {- content: WebSearchContent;- tool_use_id: string;+ /**+ * Results, best match first. Empty when nothing matched.+ */+ results: WebSearchResult[];}/**- * Error returned when web search fails+ * One page a search found.*/-export interface WebSearchToolError {- type: string;- error_code: string;+export interface WebSearchResult {+ /**+ * The page title.+ */+ title: string;+ /**+ * The page URL; cite it when you use the result.+ */+ url: string;+ /**+ * The part of the page most relevant to the query.+ */+ snippet: string;+ /**+ * When the page was published, as the search provider reports it.+ */+ publishedAt?: string | null;+ /**+ * The page text as Markdown, when `includeContent` was set.+ */+ content?: string | null;}/*** Find Macro SDK methods for ExecuteCode. Before writing a program, pass task, a short description of what the program must do, to receive the index of every relevant SDK entity in one call; skip it only when the indexes you need are already in context. An index lists each class, method and type by symbol with its signature; read the symbols you need with ReadCodeDocs. Request up to five entity names together for their indexes, e.g. entities omitted for size. Request topics for workflow guides. With no arguments, returns the compact entity catalog.diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.jsonindex 78ce481e87..c7448cfcc8 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -2804,6 +2804,166 @@}}}+ },+ "/web/fetch": {+ "post": {+ "tags": ["web"],+ "summary": "Read one public web page as Markdown. Charged to the acting user's AI allowance.",+ "operationId": "fetch_web_page",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebFetch"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "The page text",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebFetchResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid URL or length",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "AI allowance exhausted",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "422": {+ "description": "The page could not be read",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "429": {+ "description": "Per-user hourly rate limit exceeded"+ },+ "502": {+ "description": "The fetch provider failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "503": {+ "description": "Web fetch unconfigured, busy, or usage validation unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ }+ }+ }+ },+ "/web/search": {+ "post": {+ "tags": ["web"],+ "summary": "Search the public web. Charged to the acting user's AI allowance.",+ "operationId": "search_web",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebSearch"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Results, best match first",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebSearchResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid query or filters",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "AI allowance exhausted",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "429": {+ "description": "Per-user hourly rate limit exceeded"+ },+ "502": {+ "description": "The search provider failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "503": {+ "description": "Web search unconfigured, busy, or usage validation unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ }+ }+ }}},"components": {@@ -2847,7 +3007,8 @@"agent_mode_choice","dictation","image_generation",- "email_focus"+ "email_focus",+ "web_search"]},"AssistantMessagePart": {@@ -5677,27 +5838,32 @@"price_per_audio_minute": {"type": ["number", "null"],"format": "float",- "description": "Price per audio minute (USD), absent for token billing."+ "description": "Price per audio minute (USD), absent for token and credit billing."},"price_per_million_cache_read": {"type": ["number", "null"],"format": "float",- "description": "Price per million cache-read input tokens (USD), absent when the model\nhas no published rate and for audio billing."+ "description": "Price per million cache-read input tokens (USD), absent when the model\nhas no published rate and for audio and credit billing."},"price_per_million_cache_write": {"type": ["number", "null"],"format": "float",- "description": "Price per million cache-write input tokens (USD), absent when the model\nhas no published rate and for audio billing."+ "description": "Price per million cache-write input tokens (USD), absent when the model\nhas no published rate and for audio and credit billing."},"price_per_million_in": {"type": "number","format": "float",- "description": "Price per million input tokens (USD); zero for audio billing."+ "description": "Price per million input tokens (USD); zero for audio and credit billing."},"price_per_million_out": {"type": "number","format": "float",- "description": "Price per million output tokens (USD); zero for audio billing."+ "description": "Price per million output tokens (USD); zero for audio and credit billing."+ },+ "price_per_provider_credit": {+ "type": ["number", "null"],+ "format": "float",+ "description": "Price per vendor credit (USD), absent for token and audio billing."},"total": {"type": "number",@@ -5960,6 +6126,11 @@"type": ["number", "null"],"format": "float","description": "New price per million output tokens (USD). Required for token pricing."+ },+ "price_per_provider_credit": {+ "type": ["number", "null"],+ "format": "float",+ "description": "Price per vendor credit (USD), or null unless the model bills in credits."}}},@@ -6553,18 +6724,18 @@"audio_seconds": {"type": ["number", "null"],"format": "double",- "description": "Audio duration in seconds, absent for token billing."+ "description": "Audio duration in seconds, absent for token and credit billing."},"cache_read_input_tokens": {"type": "integer","format": "int64",- "description": "Input tokens read from a prompt cache; zero for audio billing.",+ "description": "Input tokens read from a prompt cache; zero for audio and credit billing.","minimum": 0},"cache_write_input_tokens": {"type": "integer","format": "int64",- "description": "Input tokens written to a prompt cache; zero for audio billing.",+ "description": "Input tokens written to a prompt cache; zero for audio and credit billing.","minimum": 0},"created_at": {@@ -6575,7 +6746,7 @@"input_tokens": {"type": "integer","format": "int64",- "description": "Uncached input tokens; zero for audio billing.",+ "description": "Uncached input tokens; zero for audio and credit billing.","minimum": 0},"model": {@@ -6585,7 +6756,7 @@"output_tokens": {"type": "integer","format": "int64",- "description": "Output tokens; zero for audio billing.",+ "description": "Output tokens; zero for audio and credit billing.","minimum": 0},"price": {@@ -6598,6 +6769,12 @@"description": "Applied pricing, if known."}]+ },+ "provider_credits": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "Vendor credits consumed, absent for token and audio billing.",+ "minimum": 0}}},@@ -6728,6 +6905,158 @@}}},+ "WebErrorBody": {+ "type": "object",+ "description": "Machine-readable failure of a web request.",+ "required": ["error", "code"],+ "properties": {+ "code": {+ "type": "string",+ "description": "Stable failure code."+ },+ "error": {+ "type": "string",+ "description": "Explanation without provider diagnostics."+ }+ }+ },+ "WebFetch": {+ "type": "object",+ "description": "Read one public web page.",+ "required": ["url"],+ "properties": {+ "maxChars": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Most characters of page text to return, 1 to 100,000 (default 20,000).",+ "minimum": 0+ },+ "url": {+ "type": "string",+ "description": "The `http` or `https` URL of the page."+ }+ }+ },+ "WebFetchResponse": {+ "type": "object",+ "description": "The text of a fetched page.",+ "required": ["url", "content", "truncated"],+ "properties": {+ "content": {+ "type": "string",+ "description": "The page text as Markdown, cut to `maxChars`."+ },+ "title": {+ "type": ["string", "null"],+ "description": "The page title, when the provider reports one."+ },+ "truncated": {+ "type": "boolean",+ "description": "Whether `content` was cut to `maxChars`."+ },+ "url": {+ "type": "string",+ "description": "The URL that was read."+ }+ }+ },+ "WebSearch": {+ "type": "object",+ "description": "Search the public web.",+ "required": ["query"],+ "properties": {+ "domains": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Only return pages from these domains, e.g. `[\"docs.rs\", \"github.com\"]`."+ },+ "excludeDomains": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Never return pages from these domains."+ },+ "includeContent": {+ "type": ["boolean", "null"],+ "description": "Also return each page's text as Markdown (up to 8,000 characters per result)."+ },+ "maxResults": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "How many results to return, 1 to 20 (default 5).",+ "minimum": 0+ },+ "query": {+ "type": "string",+ "description": "What to search for, in natural language or keywords (at most 400 characters)."+ },+ "since": {+ "type": ["string", "null"],+ "format": "date",+ "description": "Only return pages published on or after this date (`YYYY-MM-DD`)."+ },+ "topic": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/WebSearchTopic",+ "description": "`news` for recent articles with publication dates; `general` (the default) otherwise."+ }+ ]+ }+ }+ },+ "WebSearchResponse": {+ "type": "object",+ "description": "The pages a search found, best match first.",+ "required": ["results"],+ "properties": {+ "results": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/WebSearchResult"+ },+ "description": "Results, best match first. Empty when nothing matched."+ }+ }+ },+ "WebSearchResult": {+ "type": "object",+ "description": "One page a search found.",+ "required": ["title", "url", "snippet"],+ "properties": {+ "content": {+ "type": ["string", "null"],+ "description": "The page text as Markdown, when `includeContent` was set."+ },+ "publishedAt": {+ "type": ["string", "null"],+ "description": "When the page was published, as the search provider reports it."+ },+ "snippet": {+ "type": "string",+ "description": "The part of the page most relevant to the query."+ },+ "title": {+ "type": "string",+ "description": "The page title."+ },+ "url": {+ "type": "string",+ "description": "The page URL; cite it when you use the result."+ }+ }+ },+ "WebSearchTopic": {+ "type": "string",+ "description": "The kind of results a search favours.",+ "enum": ["general", "news"]+ },"WithChatId": {"type": "object","required": ["chat_id"],diff --git a/crates/agent_code_mode/src/domain/service.rs b/crates/agent_code_mode/src/domain/service.rsindex b4f4d66ac7..1b781d442b 100644--- a/crates/agent_code_mode/src/domain/service.rs+++ b/crates/agent_code_mode/src/domain/service.rs@@ -254,6 +254,9 @@ pub fn covered_by_code_sdk(name: &str, user_tool: bool) -> bool {| "CreateSkill"| "Decide"| "GenerateObject"+ // macro.web.search() and macro.web.fetch().+ | "WebSearch"+ | "WebFetch"// macro.agents.list() and macro.agentSessions.createManaged.| "ListCodingAgents"| "DispatchCodingAgent"diff --git a/crates/ai_tools/AGENTS.md b/crates/ai_tools/AGENTS.mdindex 9713c15777..eca4a11cd9 100644--- a/crates/ai_tools/AGENTS.md+++ b/crates/ai_tools/AGENTS.md@@ -52,7 +52,8 @@ execution, display) that don't belong to a single domain.## Boundaries- Depends on: nearly every domain crate with tools (`forms`, `activity`,- `agent_session`, `anthropic`, `initiative`, `collab_surface`, `favorites`,+ `agent_session`, `anthropic` (code execution), `web_search` (`WebSearch`,+ `WebFetch` via Tavily), `initiative`, `collab_surface`, `favorites`,`messages`, `routines`, `ai_billing`, `ai_usage`, `ai_toolset`, `agent`),plus `bot_id`, `attachment`, `static_file`.- Used by: `document_storage_service`, `agent_harness_service` (sessiondiff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex c5b0711f69..78591f4a3a 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -127,6 +127,7 @@ tracing.workspace = trueunicode-segmentation.workspace = trueutoipa.workspace = trueuuid.workspace = true+web_search = { path = "../web_search" }remote_env_var = { path = "../remote_env_var" }macro_env = { path = "../macro_env" }secretsmanager_client = { path = "../secretsmanager_client" }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 671dec7be3..8691258d95 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -762,22 +762,26 @@ pub async fn build_tool_service_context_from_env(skill_tool_context,schedule_tool_context: crate::build_routine_tool_context()?,anthropic_tool_context,+ web_search_provider: build_web_search_provider_from_env(),admission,recorder,usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),})}+/// The vendor behind `WebSearch` and `WebFetch`: Tavily, keyed by+/// `TAVILY_API_KEY`. Without the key the host still boots, logs an error, and+/// every web call fails with a "not configured" error.+pub fn build_web_search_provider_from_env() -> Arc<dyn web_search::domain::ports::SearchProvider> {+ Arc::new(web_search::outbound::tavily::TavilyClient::from_env())+}+/// Build an [`AnthropicToolContext`] from environment variables.///-/// Reads `ANTHROPIC_API_KEY` and configures the client with the beta headers-/// required for web fetch and code execution server tools.+/// Reads `ANTHROPIC_API_KEY` and configures the client with the beta header+/// required for the code execution server tools.pub fn build_anthropic_tool_context() -> AnthropicToolContext {let mut config = anthropic::config::Config::dangrously_try_from_env();- config.headers.append(- anthropic::prelude::WEB_FETCH_TOOL_HEADER.0.clone(),- anthropic::prelude::WEB_FETCH_TOOL_HEADER.1.clone(),- );config.headers.append(anthropic::prelude::CODE_EXECUTION_TOOL_HEADER.0.clone(),anthropic::prelude::CODE_EXECUTION_TOOL_HEADER.1.clone(),diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex cbf2676291..cfd6af5ac6 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -69,7 +69,7 @@ use teams::inbound::toolset::team_toolset;pub use build_context::build_anthropic_tool_context_test;pub use build_context::{build_anthropic_tool_context, build_cognition_tool_context, build_image_generator_from_env,- build_tool_service_context_from_env,+ build_tool_service_context_from_env, build_web_search_provider_from_env,};pub use deferred::{DeferredToolSet, deferred_tools};pub use import_jobs::{IMPORT_JOBS_HANDOVER_TIMEOUT, ImportJobs};@@ -203,6 +203,9 @@ pub(crate) fn subagent_toolset() -> AiToolSet {.add_subtoolset::<ToolDatabasesSqlToolContext>(databases_sql_toolset()).add_subtoolset::<ToolSkillToolContext>(skill_toolset()).add_subtoolset::<AnthropicToolContext>(anthropic_toolset())+ .add_subtoolset::<web_search::inbound::toolset::WebToolContext>(+ web_search::inbound::toolset::web_toolset(),+ )}/// The host a toolset is assembled for.diff --git a/crates/ai_tools/src/schemas/anthropic_tools.rs b/crates/ai_tools/src/schemas/anthropic_tools.rsindex 8776a16241..2053622ac6 100644--- a/crates/ai_tools/src/schemas/anthropic_tools.rs+++ b/crates/ai_tools/src/schemas/anthropic_tools.rs@@ -3,19 +3,6 @@ use anthropic::types::response::code_execution::{BashCodeExecutionResponse, BashCodeExecutionToolCall, TextEditorCodeExecutionResponse,TextEditorCodeExecutionToolCall,};-use anthropic::types::response::web_fetch::{WebFetchResponse, WebFetchToolCall};-use anthropic::types::response::web_search::{WebSearchResponse, WebSearchToolCall};--/// Schemas for frontend type generation for the builtin claude web search tool-/// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>-/// This tool is built into anthropic so is not included in the toolset / sent in the request-pub fn web_search() -> PhantomTool<WebSearchToolCall, WebSearchResponse> {- PhantomTool::new("web_search")-}--pub fn web_fetch() -> PhantomTool<WebFetchToolCall, WebFetchResponse> {- PhantomTool::new("web_fetch")-}pub fn bash_code_execution() -> PhantomTool<BashCodeExecutionToolCall, BashCodeExecutionResponse> {PhantomTool::new("bash_code_execution")diff --git a/crates/ai_tools/src/self_knowledge.rs b/crates/ai_tools/src/self_knowledge.rsindex 96d2f88b31..42c4465b8a 100644--- a/crates/ai_tools/src/self_knowledge.rs+++ b/crates/ai_tools/src/self_knowledge.rs@@ -48,7 +48,7 @@ channels.something in Macro, treat the official docs as the source of truth.2. **Read the docs.** Macro's docs are published at docs.macro.com. Every page isalso served as plain Markdown — append `.md` to the page URL — so you can read- it with the WebFetch tool.+ it with the WebFetch tool (`macro.web.fetch()` in code mode).3. **Cite the docs.** Link the user to the specific docs page you used, but alwayslink the human-facing page, never the raw Markdown. The `.md` form is only foryour own WebFetch reads; when you show a user a link, drop the trailing `.md`diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 14b6040862..8fed9acc56 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -2115,6 +2115,9 @@ pub struct ToolServiceContext {pub schedule_tool_context: RoutineToolContext,#[from_ref(skip)]pub anthropic_tool_context: AnthropicToolContext,+ /// The web search vendor behind `WebSearch` and `WebFetch`.+ #[from_ref(skip)]+ pub web_search_provider: Arc<dyn web_search::domain::ports::SearchProvider>,/// Shared admission for independently initiated AI work. Hosts must inject/// their configured service; request identity always comes from RequestContext.pub admission: Arc<dyn ai_billing::domain::admission::AiAdmissionService>,@@ -2163,6 +2166,19 @@ impl FromRef<ToolServiceContext> for AnthropicToolContext {}}+impl FromRef<ToolServiceContext> for web_search::inbound::toolset::WebToolContext {+ fn from_ref(context: &ToolServiceContext) -> Self {+ Self {+ service: Arc::new(web_search::domain::service::WebSearchService::new(+ context.web_search_provider.clone(),+ context.admission.clone(),+ context.recorder.clone(),+ )),+ entity: context.usage_context.entity,+ }+ }+}+impl FromRef<ToolServiceContext> for ToolDocumentToolContext {fn from_ref(context: &ToolServiceContext) -> Self {contextdiff --git a/crates/ai_usage/AGENTS.md b/crates/ai_usage/AGENTS.mdindex b1c26f3f3f..561d7ed94d 100644--- a/crates/ai_usage/AGENTS.md+++ b/crates/ai_usage/AGENTS.md@@ -3,8 +3,9 @@## What it isPart of billing: a robust log of AI usage with cost computed from model id-and token counts (or audio duration), feeding `ai_billing`'s admission and-ledger decisions, plus a flexible admin query API.+and token counts (or audio duration, or provider credits a vendor such as+Tavily bills), feeding `ai_billing`'s admission and ledger decisions, plus a+flexible admin query API.## Start here@@ -53,7 +54,7 @@ ledger decisions, plus a flexible admin query API.— don't conflate the two when adding a new recording path.- Read prices from the `ai_effective_pricing` view, never `ai_pricing`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+ percent off (input's also covers cache, audio and provider-credit rates). Gemini 3.8 Flashis discounted to DeepSeek V4.1 Flash's $0.30 / $1.20.- `UsageContext::with_agent_api_key` marks usage an agent's own API key paidfor: it is stored with `agent_api_key_id` and never counted. Set it onlydiff --git a/crates/ai_usage/src/domain/counting.rs b/crates/ai_usage/src/domain/counting.rsindex 5c4de5a771..cbf89d8cc4 100644--- a/crates/ai_usage/src/domain/counting.rs+++ b/crates/ai_usage/src/domain/counting.rs@@ -66,6 +66,7 @@ pub const fn is_billable_feature(feature: AiFeature) -> bool {| AiFeature::Import| AiFeature::AgentSession| AiFeature::AgentRepositoryChoice- | AiFeature::ImageGeneration => true,+ | AiFeature::ImageGeneration+ | AiFeature::WebSearch => true,}}diff --git a/crates/ai_usage/src/domain/counting/test.rs b/crates/ai_usage/src/domain/counting/test.rsindex 7202c0252a..fca0b3c19f 100644--- a/crates/ai_usage/src/domain/counting/test.rs+++ b/crates/ai_usage/src/domain/counting/test.rs@@ -1,6 +1,6 @@use super::*;-const FEATURES: [(AiFeature, bool); 16] = [+const FEATURES: [(AiFeature, bool); 17] = [(AiFeature::Chat, true),(AiFeature::Memory, false),(AiFeature::Automation, true),@@ -17,6 +17,7 @@ const FEATURES: [(AiFeature, bool); 16] = [(AiFeature::Dictation, false),(AiFeature::ImageGeneration, true),(AiFeature::EmailFocus, false),+ (AiFeature::WebSearch, true),];#[test]diff --git a/crates/ai_usage/src/domain/ports.rs b/crates/ai_usage/src/domain/ports.rsindex 24163e2955..fbda2c2f5f 100644--- a/crates/ai_usage/src/domain/ports.rs+++ b/crates/ai_usage/src/domain/ports.rs@@ -79,6 +79,8 @@ pub enum AiFeature {ImageGeneration,/// Classifying signal email threads for the Focus view.EmailFocus,+ /// Web search and page fetches for agents and the SDK.+ WebSearch,}/// Strip a provider prefix from a routing id, yielding the bare model api id@@ -114,6 +116,11 @@ pub enum UsageAmount {/// Provider-reported duration of the audio.duration: std::time::Duration,},+ /// Credits a vendor billed for a request (e.g. Tavily search/extract credits).+ ProviderCredits {+ /// Vendor-reported credits consumed.+ credits: u64,+ },}/// Rates for a model's billing unit.@@ -135,6 +142,11 @@ pub enum ModelPricing {/// Audio minute rate.per_minute: f32,},+ /// Price per vendor credit (USD).+ ProviderCredits {+ /// Credit rate.+ per_credit: f32,+ },}impl ModelPricing {@@ -154,6 +166,7 @@ impl ModelPricing {&& cache_write.is_none_or(valid)}Self::Audio { per_minute } => valid(per_minute),+ Self::ProviderCredits { per_credit } => valid(per_credit),};if is_valid {Ok(self)@@ -199,6 +212,10 @@ impl Price {(ModelPricing::Audio { per_minute }, UsageAmount::Audio { duration }) => {duration.as_secs_f64() / 60.0 * f64::from(per_minute)}+ (+ ModelPricing::ProviderCredits { per_credit },+ UsageAmount::ProviderCredits { credits },+ ) => credits as f64 * f64::from(per_credit),_ => return None,};Some(Self {@@ -244,7 +261,7 @@ pub struct CompletionUsage {/// 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.+ /// Token/audio/credit usage and cost.pub cost: Usage,}@@ -377,6 +394,18 @@ impl UsageContext {agent_api_key_id: self.agent_api_key_id,}}++ /// Build a credit-based event for a vendor that bills in its own credits.+ pub fn into_provider_credits_event(self, model: String, credits: u64) -> UsageEvent {+ UsageEvent {+ feature: self.feature,+ user: self.user,+ entity: self.entity,+ model,+ amount: UsageAmount::ProviderCredits { credits },+ agent_api_key_id: self.agent_api_key_id,+ }+ }}/// Errors raised by the cost crate.diff --git a/crates/ai_usage/src/domain/service/test.rs b/crates/ai_usage/src/domain/service/test.rsindex 5c5b635da7..6d38036d95 100644--- a/crates/ai_usage/src/domain/service/test.rs+++ b/crates/ai_usage/src/domain/service/test.rs@@ -491,8 +491,15 @@ async fn admin_policy_protects_usage_and_price_changes() {async fn rejects_invalid_prices_before_writing() {let repo = FakeRepo::default();let service = UsageServiceImpl::new(repo.clone());- for price in [-0.001, f32::NAN, f32::INFINITY] {- let pricing = ModelPricing::Audio { per_minute: price };+ for pricing in [-0.001, f32::NAN, f32::INFINITY]+ .into_iter()+ .flat_map(|price| {+ [+ ModelPricing::Audio { per_minute: price },+ ModelPricing::ProviderCredits { per_credit: price },+ ]+ })+ {assert!(matches!(service.set_pricing(user(), "whisper-1".into(), pricing)@@ -579,3 +586,67 @@ async fn cache_tokens_without_a_cache_rate_record_an_unpriced_row() {);assert!(rows[0].cost.price.is_none());}++#[tokio::test]+async fn records_provider_credits_at_the_model_credit_rate() {+ let repo = FakeRepo::default();+ *repo.pricing.lock().unwrap() = Some(ModelPricing::ProviderCredits { per_credit: 0.008 });+ let event = UsageContext::new(AiFeature::WebSearch, user())+ .into_provider_credits_event("tavily".into(), 2);+ UsageServiceImpl::new(repo.clone())+ .record_now(event)+ .await+ .unwrap();+ let rows = repo.rows.lock().unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].user, user());+ assert_eq!(rows[0].feature, AiFeature::WebSearch);+ assert_eq!(rows[0].cost.model, "tavily");+ assert_eq!(+ rows[0].cost.amount,+ UsageAmount::ProviderCredits { credits: 2 }+ );+ let price = rows[0].cost.price.unwrap();+ assert_eq!(+ price.pricing,+ ModelPricing::ProviderCredits { per_credit: 0.008 }+ );+ assert!((price.total - 0.016).abs() < 1e-7);+}++#[tokio::test]+async fn credits_and_other_units_never_price_each_other() {+ let token_rates = ModelPricing::Tokens {+ input: 1.0,+ output: 1.0,+ cache_read: None,+ cache_write: None,+ };+ let credit_rate = ModelPricing::ProviderCredits { per_credit: 0.008 };+ let credits = UsageAmount::ProviderCredits { credits: 2 };+ for (pricing, amount) in [+ (token_rates, credits),+ (ModelPricing::Audio { per_minute: 0.006 }, credits),+ (+ credit_rate,+ UsageAmount::Tokens {+ input: 1_000,+ output: 1_000,+ cache_read: 0,+ cache_write: 0,+ },+ ),+ (+ credit_rate,+ UsageAmount::Audio {+ duration: std::time::Duration::from_secs(60),+ },+ ),+ ] {+ assert_eq!(+ Price::compute(pricing, amount),+ None,+ "{pricing:?} {amount:?}"+ );+ }+}diff --git a/crates/ai_usage/src/inbound/axum_router.rs b/crates/ai_usage/src/inbound/axum_router.rsindex 839234294c..002308b69c 100644--- a/crates/ai_usage/src/inbound/axum_router.rs+++ b/crates/ai_usage/src/inbound/axum_router.rs@@ -53,33 +53,41 @@ pub struct SetPricingRequest {pub price_per_mil_cache_write: Option<f32>,/// Price per minute of audio (USD), or null for token-only pricing.pub price_per_audio_minute: Option<f32>,+ /// Price per vendor credit (USD), or null unless the model bills in credits.+ pub price_per_provider_credit: Option<f32>,}impl SetPricingRequest {fn pricing(&self) -> Result<ModelPricing, &'static str> {let cache_read = self.price_per_mil_cache_read;let cache_write = self.price_per_mil_cache_write;+ let no_token_rates = self.price_per_mil_in.is_none_or(|price| price == 0.0)+ && self.price_per_mil_out.is_none_or(|price| price == 0.0)+ && cache_read.is_none()+ && cache_write.is_none();+match (self.price_per_mil_in,self.price_per_mil_out,self.price_per_audio_minute,+ self.price_per_provider_credit,) {- (input, output, Some(per_minute))- if input.is_none_or(|price| price == 0.0)- && output.is_none_or(|price| price == 0.0)- && cache_read.is_none()- && cache_write.is_none() =>- {+ (_, _, Some(per_minute), None) if no_token_rates => {Ok(ModelPricing::Audio { per_minute })}- (Some(input), Some(output), None) => Ok(ModelPricing::Tokens {+ (_, _, None, Some(per_credit)) if no_token_rates => {+ Ok(ModelPricing::ProviderCredits { per_credit })+ }+ (Some(input), Some(output), None, None) => Ok(ModelPricing::Tokens {input,output,cache_read,cache_write,}),- (_, _, Some(_)) => Err("choose token pricing or audio pricing"),- _ => Err("provide both token prices or an audio price"),+ (_, _, Some(_), _) | (_, _, _, Some(_)) => {+ Err("choose token, audio, or credit pricing")+ }+ _ => Err("provide both token prices, an audio price, or a credit price"),}}}diff --git a/crates/ai_usage/src/inbound/axum_router/test.rs b/crates/ai_usage/src/inbound/axum_router/test.rsindex c828c10cb9..5d13ea26b8 100644--- a/crates/ai_usage/src/inbound/axum_router/test.rs+++ b/crates/ai_usage/src/inbound/axum_router/test.rs@@ -17,7 +17,7 @@ fn omitted_token_prices_cannot_silently_reprice_usage_to_zero() {] {assert_eq!(pricing(body),- Err("provide both token prices or an audio price")+ Err("provide both token prices, an audio price, or a credit price"));}}@@ -66,7 +66,7 @@ fn mixed_billing_units_are_rejected() {"price_per_mil_out": output,"price_per_audio_minute": 0.006,})),- Err("choose token pricing or audio pricing")+ Err("choose token, audio, or credit pricing"));}}@@ -112,6 +112,48 @@ fn cache_rates_cannot_accompany_audio_pricing() {"price_per_audio_minute": 0.006,"price_per_mil_cache_read": 0.5,})),- Err("choose token pricing or audio pricing")+ Err("choose token, audio, or credit pricing"));}++#[test]+fn credit_prices_allow_omitted_or_zero_token_fields() {+ for body in [+ json!({"model": "tavily", "price_per_provider_credit": 0.008}),+ json!({+ "model": "tavily",+ "price_per_mil_in": 0.0,+ "price_per_mil_out": 0.0,+ "price_per_provider_credit": 0.008,+ }),+ ] {+ assert_eq!(+ pricing(body),+ Ok(ModelPricing::ProviderCredits { per_credit: 0.008 })+ );+ }+}++#[test]+fn credit_prices_cannot_accompany_token_or_audio_pricing() {+ for body in [+ json!({+ "model": "tavily",+ "price_per_mil_in": 1.0,+ "price_per_mil_out": 2.0,+ "price_per_provider_credit": 0.008,+ }),+ json!({+ "model": "tavily",+ "price_per_mil_cache_read": 0.5,+ "price_per_provider_credit": 0.008,+ }),+ json!({+ "model": "tavily",+ "price_per_audio_minute": 0.006,+ "price_per_provider_credit": 0.008,+ }),+ ] {+ assert_eq!(pricing(body), Err("choose token, audio, or credit pricing"));+ }+}diff --git a/crates/ai_usage/src/inbound/models.rs b/crates/ai_usage/src/inbound/models.rsindex b9b510bdf5..d2a7530d02 100644--- a/crates/ai_usage/src/inbound/models.rs+++ b/crates/ai_usage/src/inbound/models.rs@@ -11,32 +11,37 @@ use utoipa::ToSchema;/// Rates applied to an invocation and its resolved dollar cost.#[derive(Serialize, ToSchema)]pub struct Price {- /// Price per million input tokens (USD); zero for audio billing.+ /// Price per million input tokens (USD); zero for audio and credit billing.pub price_per_million_in: f32,- /// Price per million output tokens (USD); zero for audio billing.+ /// Price per million output tokens (USD); zero for audio and credit billing.pub price_per_million_out: f32,/// Price per million cache-read input tokens (USD), absent when the model- /// has no published rate and for audio billing.+ /// has no published rate and for audio and credit billing.pub price_per_million_cache_read: Option<f32>,/// Price per million cache-write input tokens (USD), absent when the model- /// has no published rate and for audio billing.+ /// has no published rate and for audio and credit billing.pub price_per_million_cache_write: Option<f32>,- /// Price per audio minute (USD), absent for token billing.+ /// Price per audio minute (USD), absent for token and credit billing.pub price_per_audio_minute: Option<f32>,+ /// Price per vendor credit (USD), absent for token and audio billing.+ pub price_per_provider_credit: Option<f32>,/// Total cost (USD).pub total: f32,}impl From<domain::Price> for Price {fn from(price: domain::Price) -> Self {- let (input, output, cache_read, cache_write, audio) = match price.pricing {+ let (input, output, cache_read, cache_write, audio, credit) = match price.pricing {ModelPricing::Tokens {input,output,cache_read,cache_write,- } => (input, output, cache_read, cache_write, None),- ModelPricing::Audio { per_minute } => (0.0, 0.0, None, None, Some(per_minute)),+ } => (input, output, cache_read, cache_write, None, None),+ ModelPricing::Audio { per_minute } => (0.0, 0.0, None, None, Some(per_minute), None),+ ModelPricing::ProviderCredits { per_credit } => {+ (0.0, 0.0, None, None, None, Some(per_credit))+ }};Self {price_per_million_in: input,@@ -44,6 +49,7 @@ impl From<domain::Price> for Price {price_per_million_cache_read: cache_read,price_per_million_cache_write: cache_write,price_per_audio_minute: audio,+ price_per_provider_credit: credit,total: price.total,}}@@ -52,16 +58,18 @@ impl From<domain::Price> for Price {/// Measured usage for one invocation.#[derive(Serialize, ToSchema)]pub struct Usage {- /// Uncached input tokens; zero for audio billing.+ /// Uncached input tokens; zero for audio and credit billing.pub input_tokens: u64,- /// Output tokens; zero for audio billing.+ /// Output tokens; zero for audio and credit billing.pub output_tokens: u64,- /// Input tokens read from a prompt cache; zero for audio billing.+ /// Input tokens read from a prompt cache; zero for audio and credit billing.pub cache_read_input_tokens: u64,- /// Input tokens written to a prompt cache; zero for audio billing.+ /// Input tokens written to a prompt cache; zero for audio and credit billing.pub cache_write_input_tokens: u64,- /// Audio duration in seconds, absent for token billing.+ /// Audio duration in seconds, absent for token and credit billing.pub audio_seconds: Option<f64>,+ /// Vendor credits consumed, absent for token and audio billing.+ pub provider_credits: Option<u64>,/// Provider model identifier.pub model: String,/// Applied pricing, if known.@@ -72,22 +80,30 @@ pub struct Usage {impl From<domain::Usage> for Usage {fn from(usage: domain::Usage) -> Self {- let (input_tokens, output_tokens, cache_read_input_tokens, cache_write_input_tokens, audio) =- match usage.amount {- UsageAmount::Tokens {- input,- output,- cache_read,- cache_write,- } => (input, output, cache_read, cache_write, None),- UsageAmount::Audio { duration } => (0, 0, 0, 0, Some(duration.as_secs_f64())),- };+ let (+ input_tokens,+ output_tokens,+ cache_read_input_tokens,+ cache_write_input_tokens,+ audio,+ credits,+ ) = match usage.amount {+ UsageAmount::Tokens {+ input,+ output,+ cache_read,+ cache_write,+ } => (input, output, cache_read, cache_write, None, None),+ UsageAmount::Audio { duration } => (0, 0, 0, 0, Some(duration.as_secs_f64()), None),+ UsageAmount::ProviderCredits { credits } => (0, 0, 0, 0, None, Some(credits)),+ };Self {input_tokens,output_tokens,cache_read_input_tokens,cache_write_input_tokens,audio_seconds: audio,+ provider_credits: credits,model: usage.model,price: usage.price.map(Into::into),created_at: usage.created_at,diff --git a/crates/ai_usage/src/inbound/models/test.rs b/crates/ai_usage/src/inbound/models/test.rsindex ee6d8fb940..66096aac39 100644--- a/crates/ai_usage/src/inbound/models/test.rs+++ b/crates/ai_usage/src/inbound/models/test.rs@@ -33,6 +33,7 @@ fn token_usage_keeps_the_existing_http_shape() {"cache_read_input_tokens": 0,"cache_write_input_tokens": 0,"audio_seconds": null,+ "provider_credits": null,"model": "text-model","created_at": "2026-09-18T00:00:00Z","price": {@@ -41,6 +42,7 @@ fn token_usage_keeps_the_existing_http_shape() {"price_per_million_cache_read": null,"price_per_million_cache_write": null,"price_per_audio_minute": null,+ "price_per_provider_credit": null,"total": 5.0}})@@ -78,6 +80,7 @@ fn cached_token_usage_exposes_cache_tokens_and_rates() {"cache_read_input_tokens": 1_000_000,"cache_write_input_tokens": 1_000_000,"audio_seconds": null,+ "provider_credits": null,"model": "claude-opus-5","created_at": "2026-10-05T00:00:00Z","price": {@@ -86,6 +89,7 @@ fn cached_token_usage_exposes_cache_tokens_and_rates() {"price_per_million_cache_read": 0.5,"price_per_million_cache_write": 6.25,"price_per_audio_minute": null,+ "price_per_provider_credit": null,"total": 36.75}})@@ -110,3 +114,37 @@ fn audio_usage_exposes_duration_and_rate_without_inventing_tokens() {assert!((json["price"]["price_per_audio_minute"].as_f64().unwrap() - 0.006).abs() < 1e-7);assert!((json["price"]["total"].as_f64().unwrap() - 0.00905).abs() < 1e-7);}++#[test]+fn credit_usage_exposes_credits_and_rate_without_inventing_tokens() {+ let created_at = "2026-11-04T00:00:00Z".parse().unwrap();+ let amount = UsageAmount::ProviderCredits { credits: 2 };+ let usage = Usage::from(domain::Usage {+ amount,+ model: "tavily".into(),+ price: domain::Price::compute(ModelPricing::ProviderCredits { per_credit: 0.5 }, amount),+ created_at,+ });+ assert_eq!(+ serde_json::to_value(usage).unwrap(),+ json!({+ "input_tokens": 0,+ "output_tokens": 0,+ "cache_read_input_tokens": 0,+ "cache_write_input_tokens": 0,+ "audio_seconds": null,+ "provider_credits": 2,+ "model": "tavily",+ "created_at": "2026-11-04T00:00:00Z",+ "price": {+ "price_per_million_in": 0.0,+ "price_per_million_out": 0.0,+ "price_per_million_cache_read": null,+ "price_per_million_cache_write": null,+ "price_per_audio_minute": null,+ "price_per_provider_credit": 0.5,+ "total": 1.0+ }+ })+ );+}diff --git a/crates/ai_usage/src/lib.rs b/crates/ai_usage/src/lib.rsindex 7b2ddcfef4..62ea48a21a 100644--- a/crates/ai_usage/src/lib.rs+++ b/crates/ai_usage/src/lib.rs@@ -4,7 +4,7 @@//!//! The crate follows the hexagonal layout used elsewhere in this workspace://! - [`domain`] holds the cost model, ports, and the service that computes-//! cost from a model id and token counts or audio duration.+//! cost from a model id and token counts, audio duration, or provider credits.//! - [`outbound`] holds the Postgres storage adapter.//! - [`inbound`] holds the axum router mounted in the document cognition//! service (DCS).diff --git a/crates/ai_usage/src/outbound/pg_usage_repo.rs b/crates/ai_usage/src/outbound/pg_usage_repo.rsindex cf20c9a5f2..ed200bc150 100644--- a/crates/ai_usage/src/outbound/pg_usage_repo.rs+++ b/crates/ai_usage/src/outbound/pg_usage_repo.rs@@ -26,54 +26,85 @@ impl PgUsageRepo {impl UsageRepo for PgUsageRepo {async fn insert_usage(&self, usage: &CompletionUsage, count_usage: bool) -> Result<()> {let id = macro_uuid::generate_uuid_v7();- let (input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, audio_seconds) =- match usage.cost.amount {- UsageAmount::Tokens {- input,- output,- cache_read,- cache_write,- } => (- token_column(input),- token_column(output),- token_column(cache_read),- token_column(cache_write),- None,- ),- UsageAmount::Audio { duration } => (0, 0, 0, 0, Some(duration.as_secs_f64())),- };- let (per_in, per_out, per_cache_read, per_cache_write, per_audio_minute, total) =- match usage.cost.price {- Some(Price {- pricing:- ModelPricing::Tokens {- input,- output,- cache_read,- cache_write,- },- total,- }) => (- Some(input),- Some(output),- cache_read,- cache_write,- None,- Some(total),- ),- Some(Price {- pricing: ModelPricing::Audio { per_minute },- total,- }) => (- Some(0.0),- Some(0.0),- None,- None,- Some(per_minute),- Some(total),- ),- None => (None, None, None, None, None, None),- };+ let (+ input_tokens,+ output_tokens,+ cache_read_tokens,+ cache_write_tokens,+ audio_seconds,+ provider_credits,+ ) = match usage.cost.amount {+ UsageAmount::Tokens {+ input,+ output,+ cache_read,+ cache_write,+ } => (+ token_column(input),+ token_column(output),+ token_column(cache_read),+ token_column(cache_write),+ None,+ None,+ ),+ UsageAmount::Audio { duration } => (0, 0, 0, 0, Some(duration.as_secs_f64()), None),+ UsageAmount::ProviderCredits { credits } => {+ (0, 0, 0, 0, None, Some(token_column(credits)))+ }+ };+ let (+ per_in,+ per_out,+ per_cache_read,+ per_cache_write,+ per_audio_minute,+ per_provider_credit,+ total,+ ) = match usage.cost.price {+ Some(Price {+ pricing:+ ModelPricing::Tokens {+ input,+ output,+ cache_read,+ cache_write,+ },+ total,+ }) => (+ Some(input),+ Some(output),+ cache_read,+ cache_write,+ None,+ None,+ Some(total),+ ),+ Some(Price {+ pricing: ModelPricing::Audio { per_minute },+ total,+ }) => (+ Some(0.0),+ Some(0.0),+ None,+ None,+ Some(per_minute),+ None,+ Some(total),+ ),+ Some(Price {+ pricing: ModelPricing::ProviderCredits { per_credit },+ total,+ }) => (+ Some(0.0),+ Some(0.0),+ None,+ None,+ None,+ Some(per_credit),+ Some(total),+ ),+ None => (None, None, None, None, None, None, None),+ };sqlx::query!(r#"@@ -81,13 +112,15 @@ impl UsageRepo for PgUsageRepo {id, feature, user_id, entity, model,input_tokens, output_tokens,cache_read_input_tokens, cache_write_input_tokens, audio_seconds,+ provider_credits,price_per_million_in, price_per_million_out,price_per_million_cache_read, price_per_million_cache_write,- price_per_audio_minute, total,+ price_per_audio_minute, price_per_provider_credit, total,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+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,+ $19, $20)"#,id,@@ -100,11 +133,13 @@ impl UsageRepo for PgUsageRepo {cache_read_tokens,cache_write_tokens,audio_seconds,+ provider_credits,per_in,per_out,per_cache_read,per_cache_write,per_audio_minute,+ per_provider_credit,total,count_usage,usage.agent_api_key_id,@@ -123,7 +158,8 @@ impl UsageRepo for PgUsageRepo {price_per_million_out AS "price_per_million_out!",price_per_million_cache_read,price_per_million_cache_write,- price_per_audio_minute+ price_per_audio_minute,+ price_per_provider_creditFROM ai_effective_pricingWHERE model = $1"#,@@ -132,26 +168,39 @@ impl UsageRepo for PgUsageRepo {.fetch_optional(&self.inner).await?;- Ok(row.map(|r| match r.price_per_audio_minute {- Some(per_minute) => ModelPricing::Audio { per_minute },- None => ModelPricing::Tokens {- input: r.price_per_million_in,- output: r.price_per_million_out,- cache_read: r.price_per_million_cache_read,- cache_write: r.price_per_million_cache_write,+ Ok(row.map(+ |r| match (r.price_per_audio_minute, r.price_per_provider_credit) {+ (_, Some(per_credit)) => ModelPricing::ProviderCredits { per_credit },+ (Some(per_minute), None) => ModelPricing::Audio { per_minute },+ (None, None) => ModelPricing::Tokens {+ input: r.price_per_million_in,+ output: r.price_per_million_out,+ cache_read: r.price_per_million_cache_read,+ cache_write: r.price_per_million_cache_write,+ },},- }))+ ))}async fn set_pricing(&self, model: &str, pricing: ModelPricing) -> Result<()> {- let (per_in, per_out, per_cache_read, per_cache_write, per_audio_minute) = match pricing {+ let (+ per_in,+ per_out,+ per_cache_read,+ per_cache_write,+ per_audio_minute,+ per_provider_credit,+ ) = match pricing {ModelPricing::Tokens {input,output,cache_read,cache_write,- } => (input, output, cache_read, cache_write, None),- ModelPricing::Audio { per_minute } => (0.0, 0.0, None, None, Some(per_minute)),+ } => (input, output, cache_read, cache_write, None, None),+ ModelPricing::Audio { per_minute } => (0.0, 0.0, None, None, Some(per_minute), None),+ ModelPricing::ProviderCredits { per_credit } => {+ (0.0, 0.0, None, None, None, Some(per_credit))+ }};let mut tx = self.inner.begin().await?;@@ -160,15 +209,16 @@ impl UsageRepo for PgUsageRepo {INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out,price_per_million_cache_read, price_per_million_cache_write,- price_per_audio_minute+ price_per_audio_minute, price_per_provider_credit)- VALUES ($1, $2, $3, $4, $5, $6)+ VALUES ($1, $2, $3, $4, $5, $6, $7)ON CONFLICT (model) DO UPDATESET price_per_million_in = EXCLUDED.price_per_million_in,price_per_million_out = EXCLUDED.price_per_million_out,price_per_million_cache_read = EXCLUDED.price_per_million_cache_read,price_per_million_cache_write = EXCLUDED.price_per_million_cache_write,price_per_audio_minute = EXCLUDED.price_per_audio_minute,+ price_per_provider_credit = EXCLUDED.price_per_provider_credit,updated_at = NOW()"#,model,@@ -177,6 +227,7 @@ impl UsageRepo for PgUsageRepo {per_cache_read,per_cache_write,per_audio_minute,+ per_provider_credit,).execute(&mut *tx).await?;@@ -191,8 +242,10 @@ impl UsageRepo for PgUsageRepo {price_per_million_cache_read = e.price_per_million_cache_read,price_per_million_cache_write = e.price_per_million_cache_write,price_per_audio_minute = e.price_per_audio_minute,+ price_per_provider_credit = e.price_per_provider_credit,total = CASEWHEN (ai_usage.audio_seconds IS NULL) <> (e.price_per_audio_minute IS NULL) THEN NULL+ WHEN (ai_usage.provider_credits IS NULL) <> (e.price_per_provider_credit IS NULL) THEN NULLWHEN ai_usage.cache_read_input_tokens > 0 AND e.price_per_million_cache_read IS NULL THEN NULLWHEN ai_usage.cache_write_input_tokens > 0 AND e.price_per_million_cache_write IS NULL THEN NULLELSE (ai_usage.input_tokens::real / 1000000.0::real) * e.price_per_million_in@@ -200,6 +253,7 @@ impl UsageRepo for PgUsageRepo {+ (ai_usage.cache_read_input_tokens::real / 1000000.0::real) * COALESCE(e.price_per_million_cache_read, 0)+ (ai_usage.cache_write_input_tokens::real / 1000000.0::real) * COALESCE(e.price_per_million_cache_write, 0)+ (COALESCE(ai_usage.audio_seconds, 0) / 60.0 * COALESCE(e.price_per_audio_minute, 0))::real+ + (COALESCE(ai_usage.provider_credits, 0)::double precision * COALESCE(e.price_per_provider_credit, 0))::realENDFROM ai_effective_pricing eWHERE ai_usage.model = $1 AND e.model = $1@@ -234,11 +288,13 @@ impl UsageRepo for PgUsageRepo {cache_read_input_tokens,cache_write_input_tokens,audio_seconds,+ provider_credits,price_per_million_in,price_per_million_out,price_per_million_cache_read,price_per_million_cache_write,price_per_audio_minute,+ price_per_provider_credit,total,created_atFROM ai_usage@@ -267,9 +323,10 @@ impl UsageRepo for PgUsageRepo {let price = match (r.price_per_million_in, r.price_per_million_out, r.total) {(Some(per_in), Some(per_out), Some(total)) => Some(Price {- pricing: match r.price_per_audio_minute {- Some(per_minute) => ModelPricing::Audio { per_minute },- None => ModelPricing::Tokens {+ pricing: match (r.price_per_audio_minute, r.price_per_provider_credit) {+ (_, Some(per_credit)) => ModelPricing::ProviderCredits { per_credit },+ (Some(per_minute), None) => ModelPricing::Audio { per_minute },+ (None, None) => ModelPricing::Tokens {input: per_in,output: per_out,cache_read: r.price_per_million_cache_read,@@ -287,12 +344,15 @@ impl UsageRepo for PgUsageRepo {entity: r.entity,agent_api_key_id: r.agent_api_key_id,cost: Usage {- amount: match r.audio_seconds {- Some(seconds) => UsageAmount::Audio {+ amount: match (r.audio_seconds, r.provider_credits) {+ (Some(seconds), _) => UsageAmount::Audio {duration: std::time::Duration::try_from_secs_f64(seconds).map_err(|error| UsageError::Other(error.into()))?,},- None => UsageAmount::Tokens {+ (None, Some(credits)) => UsageAmount::ProviderCredits {+ credits: credits.max(0) as u64,+ },+ (None, None) => UsageAmount::Tokens {input: r.input_tokens.max(0) as u64,output: r.output_tokens.max(0) as u64,cache_read: r.cache_read_input_tokens.max(0) as u64,@@ -309,7 +369,7 @@ impl UsageRepo for PgUsageRepo {}}-/// Token counts are `BIGINT`; a count past `i64::MAX` saturates.+/// Token and credit counts are `BIGINT`; a count past `i64::MAX` saturates.fn token_column(tokens: u64) -> i64 {i64::try_from(tokens).unwrap_or(i64::MAX)}diff --git a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_usage_repo/test.rsindex 370ce8f483..e1b9dc82dc 100644--- a/crates/ai_usage/src/outbound/pg_usage_repo/test.rs+++ b/crates/ai_usage/src/outbound/pg_usage_repo/test.rs@@ -61,6 +61,10 @@ async fn seeded_pricing_is_available(pool: PgPool) {repo.get_pricing("whisper-1").await.unwrap(),Some(ModelPricing::Audio { per_minute: 0.006 }));+ assert_eq!(+ repo.get_pricing("tavily").await.unwrap(),+ Some(ModelPricing::ProviderCredits { per_credit: 0.008 })+ );let price = repo.get_pricing("gemini-2.5-flash-image").await@@ -639,3 +643,106 @@ async fn accelerated_and_long_context_prices_remain_distinct(pool: PgPool) {);}}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn credit_usage_roundtrips_and_reprices_without_affecting_tokens(pool: PgPool) {+ let repo = PgUsageRepo::new(pool);+ let mut search = completion(AiFeature::WebSearch, "tavily", 0, 0);+ let amount = UsageAmount::ProviderCredits { credits: 3 };+ search.cost.amount = amount;+ search.cost.price = Price::compute(+ repo.get_pricing("tavily").await.unwrap().unwrap(),+ search.cost.amount,+ );+ repo.insert_usage(&search, true).await.unwrap();+ repo.insert_usage(+ &completion(AiFeature::Chat, "claude-opus-4-8", 1_000_000, 0),+ true,+ )+ .await+ .unwrap();++ let query = UsageApiParams {+ features: vec![AiFeature::WebSearch],+ ..Default::default()+ };+ let rows = repo.query_usage(&query).await.unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].cost.amount, amount);+ let price = rows[0].cost.price.unwrap();+ assert_eq!(+ price.pricing,+ ModelPricing::ProviderCredits { per_credit: 0.008 }+ );+ assert!((price.total - 0.024).abs() < 1e-7);++ repo.set_pricing(+ "tavily",+ ModelPricing::Tokens {+ input: 0.0,+ output: 0.0,+ cache_read: None,+ cache_write: None,+ },+ )+ .await+ .unwrap();+ let rows = repo.query_usage(&query).await.unwrap();+ assert_eq!(rows[0].cost.amount, amount);+ assert!(+ rows[0].cost.price.is_none(),+ "token rates must not price credit usage"+ );++ repo.set_pricing("tavily", ModelPricing::Audio { per_minute: 0.006 })+ .await+ .unwrap();+ let rows = repo.query_usage(&query).await.unwrap();+ assert!(+ rows[0].cost.price.is_none(),+ "audio rates must not price credit usage"+ );++ repo.set_pricing("tavily", ModelPricing::ProviderCredits { per_credit: 0.01 })+ .await+ .unwrap();+ let rows = repo.query_usage(&query).await.unwrap();+ assert_eq!(rows[0].cost.amount, amount);+ let price = rows[0].cost.price.unwrap();+ assert_eq!(+ price.pricing,+ ModelPricing::ProviderCredits { per_credit: 0.01 }+ );+ assert!((price.total - 0.03).abs() < 1e-7);++ let chat = repo+ .query_usage(&UsageApiParams {+ features: vec![AiFeature::Chat],+ ..Default::default()+ })+ .await+ .unwrap();+ assert!(+ chat[0].cost.price.is_none(),+ "repricing another model must not touch chat rows"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn repricing_cannot_apply_credit_rates_to_token_usage(pool: PgPool) {+ let repo = PgUsageRepo::new(pool);+ repo.insert_usage(+ &completion(AiFeature::Chat, "credit-history", 1_000_000, 0),+ true,+ )+ .await+ .unwrap();+ repo.set_pricing(+ "credit-history",+ ModelPricing::ProviderCredits { per_credit: 0.008 },+ )+ .await+ .unwrap();+ let rows = repo.query_usage(&UsageApiParams::default()).await.unwrap();+ assert!(rows[0].cost.price.is_none());+}diff --git a/crates/anthropic/AGENTS.md b/crates/anthropic/AGENTS.mdindex fd8bbbc262..1baeb27d5e 100644--- a/crates/anthropic/AGENTS.md+++ b/crates/anthropic/AGENTS.md@@ -5,8 +5,9 @@Part of AI: the SDK client for the Anthropic Messages API that the rest ofthe product's AI surfaces (via `agent`) build requests against, plus anOpenAI-compatible request/response mapping layer and Anthropic's own-server-side tools (web search, web fetch, bash/text-editor code-execution).+server-side code-execution tools (bash and text editor). Web search and+fetch are vendor-neutral tools in `crates/web_search`, not Anthropic server+tools.## Start here@@ -19,7 +20,8 @@ execution).## Scope- Owns: the Anthropic API client, its OpenAI-shaped adapter, and Anthropic's- built-in tools (web search/fetch, code execution).+ built-in code-execution tools.+- Not here: web search and fetch → `crates/web_search` (wired as tools in `crates/ai_tools`).- Not here: model selection, pricing, usage/billing policy, or the provider-agnosticchat abstraction → `crates/agent`, `crates/ai_billing`, `crates/ai_usage`.@@ -41,8 +43,8 @@ execution).## Gotchas-- `WebSearch` must tolerate a `pause_turn` stop reason and keep accumulating results- across turns rather than returning only the last turn's hits (#7421).+- Server tools must tolerate a `pause_turn` (or unknown) stop reason and still return+ the results produced so far (#7421).## Relateddiff --git a/crates/anthropic/Cargo.toml b/crates/anthropic/Cargo.tomlindex 6038fda2e3..6aed168894 100644--- a/crates/anthropic/Cargo.toml+++ b/crates/anthropic/Cargo.toml@@ -32,7 +32,6 @@ tokio-stream = { workspace = true }async-openai = { workspace = true, optional = true}chrono.workspace = truelazy_static = {workspace = true}-regex = { workspace = true }ai_toolset = { path = "../ai_toolset", optional = true }ai_usage = { path = "../ai_usage", optional = true }async-trait = { workspace = true, optional = true }diff --git a/crates/anthropic/examples/server_tool.rs b/crates/anthropic/examples/server_tool.rsindex 150f04617e..280782b7f5 100644--- a/crates/anthropic/examples/server_tool.rs+++ b/crates/anthropic/examples/server_tool.rs@@ -1,4 +1,5 @@-use anthropic::prelude::WEB_SEARCH_TOOL;+use anthropic::openai::request::{AnthropicRequestExtension, AnthropicRequestExtensions};+use anthropic::prelude::CODE_EXECUTION_TOOL;use std::io::Write;use std::process::exit;@@ -14,14 +15,19 @@ const LOG_MODE: bool = false;#[tokio::main]async fn main() {- let client = Client::dangerously_try_from_env(None);- let mut request = CreateMessageRequestBody::default();- request.max_tokens = 1000;- request.system = Some(SystemPrompt::Text(- "You are a helpful AI assistant in a CLI based demo. Use web search tool eagerly".into(),- ));- request.model = "claude-haiku-4-5".into();- request.tools = Some(vec![WEB_SEARCH_TOOL.clone().into()]);+ let client = Client::dangerously_try_from_env(Some(AnthropicRequestExtensions(vec![+ AnthropicRequestExtension::CodeExecutionTool,+ ])));+ let mut request = CreateMessageRequestBody {+ max_tokens: 1000,+ system: Some(SystemPrompt::Text(+ "You are a helpful AI assistant in a CLI based demo. Use the code execution tool eagerly"+ .into(),+ )),+ model: "claude-haiku-4-5".into(),+ tools: Some(vec![CODE_EXECUTION_TOOL.clone().into()]),+ ..Default::default()+ };let mut out = std::io::stdout();loop {@@ -57,12 +63,8 @@ async fn main() {continue;}if let Err(error) = event {- match error {- other => {- writeln!(out, "\nerror: {:#?}", other).expect("io");- exit(1);- }- }+ writeln!(out, "\nerror: {:#?}", error).expect("io");+ exit(1);} else {let event = event.unwrap();let response_text = match event {@@ -78,10 +80,12 @@ async fn main() {ContentDeltaEvent::TextDelta { text } => text,ContentDeltaEvent::ThinkingDelta { thinking } => thinking,ContentDeltaEvent::CitationsDelta { .. } => "[Citation]".into(),- ContentDeltaEvent::WebSearchToolResult(web_search_result) => {- format!("{:#?}", web_search_result)+ ContentDeltaEvent::BashCodeExecutionToolResult(result) => {+ format!("{:#?}", result)+ }+ ContentDeltaEvent::TextEditorCodeExecutionToolResult(result) => {+ format!("{:#?}", result)}-ContentDeltaEvent::ServerToolUse(tool) => {format!("{:#?}", tool)}@@ -92,8 +96,11 @@ async fn main() {ContentDeltaEvent::ServerToolUse(tool) => {format!("{:#?}", tool)}- ContentDeltaEvent::WebSearchToolResult(web_search_result) => {- format!("{:#?}", web_search_result)+ ContentDeltaEvent::BashCodeExecutionToolResult(result) => {+ format!("{:#?}", result)+ }+ ContentDeltaEvent::TextEditorCodeExecutionToolResult(result) => {+ format!("{:#?}", result)}_ => "".into(),},diff --git a/crates/anthropic/src/client.rs b/crates/anthropic/src/client.rsindex 1e1b0c06c4..20b16dd921 100644--- a/crates/anthropic/src/client.rs+++ b/crates/anthropic/src/client.rs@@ -2,7 +2,7 @@ pub mod chat;use crate::error::AnthropicError;use crate::openai::request::AnthropicRequestExtension;use crate::prelude::ApiError;-use crate::types::request::{CODE_EXECUTION_TOOL_HEADER, WEB_FETCH_TOOL_HEADER};+use crate::types::request::CODE_EXECUTION_TOOL_HEADER;use crate::{config::Config, openai::request::AnthropicRequestExtensions};use futures::stream::{Stream, StreamExt};use reqwest::Client as RequestClient;@@ -20,24 +20,16 @@ pub struct Client {impl Client {pub fn dangerously_try_from_env(extensions: Option<AnthropicRequestExtensions>) -> Self {let mut config = Config::dangrously_try_from_env();- if let Some(ref extensions) = extensions {- if extensions.0.contains(&AnthropicRequestExtension::FetchTool) {- tracing::debug!("Adding web_fetch beta header");- config.headers.append(- WEB_FETCH_TOOL_HEADER.0.clone(),- WEB_FETCH_TOOL_HEADER.1.clone(),- );- }- if extensions+ if extensions.is_some_and(|extensions| {+ extensions.0.contains(&AnthropicRequestExtension::CodeExecutionTool)- {- tracing::debug!("Adding code_execution beta header");- config.headers.append(- CODE_EXECUTION_TOOL_HEADER.0.clone(),- CODE_EXECUTION_TOOL_HEADER.1.clone(),- );- }+ }) {+ tracing::debug!("Adding code_execution beta header");+ config.headers.append(+ CODE_EXECUTION_TOOL_HEADER.0.clone(),+ CODE_EXECUTION_TOOL_HEADER.1.clone(),+ );}tracing::debug!("Anthropic client headers: {:?}", config.headers);Self::with_config(config)diff --git a/crates/anthropic/src/client/chat.rs b/crates/anthropic/src/client/chat.rsindex 9e379f078b..2b6167f4bf 100644--- a/crates/anthropic/src/client/chat.rs+++ b/crates/anthropic/src/client/chat.rs@@ -6,7 +6,6 @@ use std::pin::Pin;use super::Client;use crate::error::AnthropicError;use crate::types::request::CreateMessageRequestBody;-use crate::types::request::transform_request_web_fetch;use crate::types::response::{MessageResponse, StreamEvent};pub type MessageCompletionResponseStream =@@ -31,7 +30,6 @@ impl<'c> Chat<'c> {I: Into<CreateMessageRequestBody>,{let request = request.into();- let request = transform_request_web_fetch(request);self.inner.post("/v1/messages", request).await}@@ -41,7 +39,6 @@ impl<'c> Chat<'c> {{let mut request = request.into();request.stream = Some(true);- let request = transform_request_web_fetch(request);self.create_stream_unchecked(request).await}diff --git a/crates/anthropic/src/openai/request/request_extension.rs b/crates/anthropic/src/openai/request/request_extension.rsindex 84aa2c7c7b..b4176b7df6 100644--- a/crates/anthropic/src/openai/request/request_extension.rs+++ b/crates/anthropic/src/openai/request/request_extension.rs@@ -1,7 +1,4 @@-use crate::{- prelude::{ServerTool, WEB_FETCH_TOOL},- types::request::{CODE_EXECUTION_TOOL, WEB_SEARCH_TOOL},-};+use crate::{prelude::ServerTool, types::request::CODE_EXECUTION_TOOL};/// Request extensions are functionality that is supported by the anthropic API but not supported by OpenAI/completions/v1/// These will affect the request sent to anthropic@@ -10,10 +7,6 @@ use crate::{#[derive(Clone, Debug, Copy, PartialEq, Eq)]pub enum AnthropicRequestExtension {- /// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>- WebSearchTool,- /// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool>- FetchTool,/// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool>CodeExecutionTool,}@@ -35,9 +28,9 @@ impl AnthropicRequestExtensions {fn add_tool(tool: ServerTool, request: &mut crate::types::request::CreateMessageRequestBody) {if let Some(ref mut tools) = request.tools {- let search = tool.into();- if !tools.iter().any(|t| t == &search) {- tools.push(search);+ let tool = tool.into();+ if !tools.iter().any(|t| t == &tool) {+ tools.push(tool);}} else {request.tools = Some(vec![tool.into()])@@ -50,8 +43,6 @@ impl AnthropicRequestExtension {request: &mut crate::types::request::CreateMessageRequestBody,) {match self {- Self::WebSearchTool => add_tool(WEB_SEARCH_TOOL.clone(), request),- Self::FetchTool => add_tool(WEB_FETCH_TOOL.clone(), request),Self::CodeExecutionTool => add_tool(CODE_EXECUTION_TOOL.clone(), request),}}diff --git a/crates/anthropic/src/openai/stream_extension.rs b/crates/anthropic/src/openai/stream_extension.rsindex 797840951d..f92e84d9af 100644--- a/crates/anthropic/src/openai/stream_extension.rs+++ b/crates/anthropic/src/openai/stream_extension.rs@@ -3,8 +3,6 @@ use crate::types::response::Citation;use crate::types::response::code_execution::{BashCodeExecutionResponse, TextEditorCodeExecutionResponse,};-use crate::types::response::web_fetch::WebFetchResponse;-use crate::types::response::web_search::WebSearchResponse;use async_openai::error::OpenAIError;use async_openai::types::chat::CreateChatCompletionStreamResponse;use futures::Stream;@@ -14,8 +12,6 @@ use std::pin::Pin;#[derive(Clone, Debug, PartialEq)]pub enum AnthropicResponseExtension {Citation(Citation),- WebSearchToolResponse(WebSearchResponse),- WebFetchToolResponse(WebFetchResponse),BashCodeExecutionToolResponse(BashCodeExecutionResponse),TextEditorCodeExecutionToolResponse(TextEditorCodeExecutionResponse),ServerToolUse(ServerToolUse),diff --git a/crates/anthropic/src/openai/stream_response.rs b/crates/anthropic/src/openai/stream_response.rsindex 2053c45d48..4ba8a36759 100644--- a/crates/anthropic/src/openai/stream_response.rs+++ b/crates/anthropic/src/openai/stream_response.rs@@ -3,7 +3,7 @@ use super::stream_extension::{ExtendedAnthropicStreamItem, ExtendedStream};use crate::client::chat::MessageCompletionResponseStream;use crate::error::AnthropicError;use crate::openai::stream_extension::AnthropicResponseExtension;-use crate::prelude::{ServerToolUse, transform_request_web_fetch};+use crate::prelude::ServerToolUse;use crate::types::response::{ContentDeltaEvent, StopReason, StreamEvent, Usage};use crate::{client::chat::Chat, prelude::CreateMessageRequestBody};use async_openai::error::{ApiError, OpenAIError};@@ -207,12 +207,6 @@ fn map_stream_extended(mut stream: MessageCompletionResponseStream) -> ExtendedSContentDeltaEvent::ServerToolUse(server_tool) => {tool_state = ToolState::StreamingServerTool(server_tool.into())}- ContentDeltaEvent::WebSearchToolResult(web_search_response) => {- yield Ok(AnthropicResponseExtension::WebSearchToolResponse(web_search_response).into());- }- ContentDeltaEvent::WebFetchToolResult(web_fetch_response) => {- yield Ok(AnthropicResponseExtension::WebFetchToolResponse(web_fetch_response).into());- }ContentDeltaEvent::BashCodeExecutionToolResult(bash_response) => {yield Ok(AnthropicResponseExtension::BashCodeExecutionToolResponse(bash_response).into());}@@ -231,12 +225,6 @@ fn map_stream_extended(mut stream: MessageCompletionResponseStream) -> ExtendedSAnthropicResponseExtension::Citation(citation).into());}- ContentDeltaEvent::WebSearchToolResult(web_search_response) => {- yield Ok(AnthropicResponseExtension::WebSearchToolResponse(web_search_response).into());- }- ContentDeltaEvent::WebFetchToolResult(web_fetch_response) => {- yield Ok(AnthropicResponseExtension::WebFetchToolResponse(web_fetch_response).into());- }ContentDeltaEvent::BashCodeExecutionToolResult(bash_response) => {yield Ok(AnthropicResponseExtension::BashCodeExecutionToolResponse(bash_response).into());}@@ -385,7 +373,6 @@ impl<'c> Chat<'c> {{let mut request = request.into();request.stream = Some(true);- let request = transform_request_web_fetch(request);self.create_stream_openai_unchecked(request).await}@@ -401,7 +388,6 @@ impl<'c> Chat<'c> {let mut request = request.into();request.stream = Some(true);let request = extensions.extend_request(request);- let request = transform_request_web_fetch(request);self.create_stream_extended_unchecked(request).await}diff --git a/crates/anthropic/src/prelude.rs b/crates/anthropic/src/prelude.rsindex fd24109aae..c98e26ad2b 100644--- a/crates/anthropic/src/prelude.rs+++ b/crates/anthropic/src/prelude.rs@@ -2,15 +2,14 @@ pub use crate::client::{Client, chat};pub use crate::config::Config;#[cfg(feature = "openai")]pub use crate::openai::{request, stream_extension, stream_response};-pub(crate) use crate::types::request::transform_request_web_fetch;pub use crate::types::request::{CODE_EXECUTION_TOOL, CODE_EXECUTION_TOOL_HEADER, CacheControl, ClientTool,CreateMessageRequestBody, ImageSource, McpServer, Metadata, RequestContent, RequestContentKind,RequestMessage, Role, ServerTool, ServiceTier, SystemContent, SystemPrompt, Thinking, Tool,- ToolChoice, WEB_FETCH_TOOL, WEB_FETCH_TOOL_HEADER, WEB_SEARCH_TOOL,+ ToolChoice,};pub use crate::types::response::{ApiError, Citation, Container, Content, ContentDeltaEvent, Error, MessageResponse,RedactedThinking, ResponseContentKind, ServerToolUse, StopReason, StreamError, StreamEvent,- TextResponse, ThinkingResponse, ToolUse, Usage, code_execution, web_fetch, web_search,+ TextResponse, ThinkingResponse, ToolUse, Usage, code_execution,};diff --git a/crates/anthropic/src/toolset.rs b/crates/anthropic/src/toolset.rsindex 57a5e2c989..9965f13378 100644--- a/crates/anthropic/src/toolset.rs+++ b/crates/anthropic/src/toolset.rs@@ -2,13 +2,9 @@ mod bash_code_execution;#[cfg(test)]mod test;mod text_editor_code_execution;-mod web_fetch;-mod web_search;pub use bash_code_execution::BashCodeExecution;pub use text_editor_code_execution::TextEditorCodeExecution;-pub use web_fetch::WebFetch;-pub use web_search::WebSearch;use crate::client::Client;use crate::types::request::{@@ -107,8 +103,6 @@ fn response_usage(value: &serde_json::Value) -> UsageEvidence {/// Create the Anthropic server tools toolset.pub fn anthropic_toolset() -> AsyncToolCollection<AnthropicToolContext> {AsyncToolCollection::new()- .add_tool::<WebSearch, AnthropicToolContext>()- .add_tool::<WebFetch, AnthropicToolContext>().add_tool::<BashCodeExecution, AnthropicToolContext>().add_tool::<TextEditorCodeExecution, AnthropicToolContext>()}@@ -175,7 +169,6 @@ pub(crate) async fn invoke_server_tool(// alive after tool cancellation so already-incurred usage can be recorded.let (caller_alive, cancelled) = tokio::sync::oneshot::channel::<()>();let response = tokio::spawn(async move {- let request = crate::types::request::transform_request_web_fetch(request);let execution = async {let response = client.post_response("/v1/messages", request).await?;let status = response.status();diff --git a/crates/anthropic/src/toolset/test.rs b/crates/anthropic/src/toolset/test.rsindex bffb38a0d7..961b773398 100644--- a/crates/anthropic/src/toolset/test.rs+++ b/crates/anthropic/src/toolset/test.rs@@ -1,6 +1,6 @@use super::*;-use crate::types::response::web_search::{SearchResult, WebSearchContent, WebSearchToolError};-use crate::types::response::{Content, MessageResponse, ResponseContentKind};+use crate::types::response::ResponseContentKind;+use crate::types::response::code_execution::BashCodeExecutionContent;use ai_billing::domain::{DenyReason,admission::{AdmissionFuture, AiAdmissionError, AiAdmissionService},@@ -62,7 +62,7 @@ async fn direct_tools_refuse_before_both_provider_branches_and_observation() {RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());let second =RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());- let tool = WebSearch {+ let tool = BashCodeExecution {input: "test".into(),};let (a, b) = tokio::join!(@@ -167,7 +167,7 @@ async fn context_with_status(async fn independent_tool_uses_authenticated_user_and_records_before_parsing() {let journal = Arc::new(Observations::default());// Deliberately malformed tool content: usage must survive SDK/result failure.- let context = context_with_response(r#"{"id":"msg-1","content":42,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":2,"cache_creation_input_tokens":3,"server_tool_use":{"web_search_requests":1}}}"#, journal.clone()).await;+ let context = context_with_response(r#"{"id":"msg-1","content":42,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":2,"cache_creation_input_tokens":3,"server_tool_use":{"code_execution_requests":1}}}"#, journal.clone()).await;let request = RequestContext::new("macro|[email protected]".to_owned()@@ -178,7 +178,7 @@ async fn independent_tool_uses_authenticated_user_and_records_before_parsing() {invoke_server_tool(&context,&request,- crate::types::request::WEB_SEARCH_TOOL.clone(),+ crate::types::request::CODE_EXECUTION_TOOL.clone(),"query").await@@ -219,7 +219,7 @@ async fn recorder_failure_does_not_fail_tool_execution() {invoke_server_tool(&context,&request,- crate::types::request::WEB_SEARCH_TOOL.clone(),+ crate::types::request::CODE_EXECUTION_TOOL.clone(),"query",).await@@ -246,7 +246,7 @@ async fn failed_http_response_preserves_reported_usage() {invoke_server_tool(&context,&request,- crate::types::request::WEB_SEARCH_TOOL.clone(),+ crate::types::request::CODE_EXECUTION_TOOL.clone(),"query").await@@ -316,7 +316,7 @@ async fn live_tool_has_no_deadline_but_cancelled_tool_drain_is_bounded() {invoke_server_tool(&context,&request,- crate::types::request::WEB_SEARCH_TOOL.clone(),+ crate::types::request::CODE_EXECUTION_TOOL.clone(),"query",).await@@ -375,117 +375,11 @@ fn nullable_cache_counters_are_absent_but_malformed_usage_is_unresolved() {}}-#[test]-fn deserialize_web_search_response() {- // From the Anthropic docs: https://platform.claude.com/docs/en/docs/build-with-claude/tool-use/web-search-tool- let json = serde_json::json!({- "id": "msg_a930390d3a",- "type": "message",- "role": "assistant",- "model": "claude-sonnet-4-5-20250929",- "content": [- {- "type": "text",- "text": "I'll search for when Claude Shannon was born."- },- {- "type": "server_tool_use",- "id": "srvtoolu_01WYG3ziw53XMcoyKL4XcZmE",- "name": "web_search",- "input": {- "query": "claude shannon birth date"- }- },- {- "type": "web_search_tool_result",- "tool_use_id": "srvtoolu_01WYG3ziw53XMcoyKL4XcZmE",- "content": [- {- "type": "web_search_result",- "url": "https://en.wikipedia.org/wiki/Claude_Shannon",- "title": "Claude Shannon - Wikipedia",- "encrypted_content": "EqgfCioIARgB...",- "page_age": "April 30, 2025"- }- ]- },- {- "text": "Based on the search results, ",- "type": "text"- },- {- "text": "Claude Shannon was born on April 30, 1916",- "type": "text",- "citations": [- {- "type": "web_search_result_location",- "url": "https://en.wikipedia.org/wiki/Claude_Shannon",- "title": "Claude Shannon - Wikipedia",- "encrypted_index": "Eo8BCioIAhgB...",- "cited_text": "Claude Elwood Shannon (April 30, 1916 – February 24, 2001)..."- }- ]- }- ],- "stop_reason": "end_turn",- "stop_sequence": null,- "usage": {- "input_tokens": 6039,- "output_tokens": 931,- "server_tool_use": {- "web_search_requests": 1- }- }- });-- let result = serde_json::from_value::<MessageResponse>(json);- match &result {- Err(e) => panic!("Failed to deserialize web search response: {e}"),- Ok(msg) => {- let content = msg.content.as_ref().expect("content");- match content {- Content::Array(blocks) => {- assert!(- blocks.len() >= 4,- "expected at least 4 content blocks, got {}",- blocks.len()- );- assert!(- blocks- .iter()- .any(|b| matches!(b, ResponseContentKind::WebSearchToolResult(_))),- "expected a WebSearchToolResult block"- );- }- _ => panic!("expected Content::Array"),- }- }- }-}--fn search_result(url: &str) -> serde_json::Value {- serde_json::json!({- "type": "web_search_result",- "url": url,- "title": format!("Title of {url}"),- "encrypted_content": "EqgfCioIARgB...",- "page_age": "April 30, 2025"- })-}--fn search_result_block(tool_use_id: &str, content: serde_json::Value) -> serde_json::Value {- serde_json::json!({- "type": "web_search_tool_result",- "tool_use_id": tool_use_id,- "content": content- })-}--/// A paused server-tool loop is a real stop reason for web search, so the-/// tool must hand back the results found so far rather than fail on the+/// A paused server-tool loop is a real stop reason for server tools, so the+/// tool must hand back the result found so far rather than fail on the/// envelope; stop reasons this crate has never seen must not fail it either.#[tokio::test]-async fn web_search_survives_paused_and_unknown_stop_reasons() {+async fn server_tool_survives_paused_and_unknown_stop_reasons() {use ai_toolset::{AsyncTool, ServiceContext};for stop_reason in ["pause_turn",@@ -497,9 +391,18 @@ async fn web_search_survives_paused_and_unknown_stop_reasons() {"type": "message","role": "assistant","content": [- {"type": "server_tool_use", "id": "srv-1", "name": "web_search", "input": {"query": "a"}},- search_result_block("srv-1", serde_json::json!([search_result("https://a.example")])),- {"type": "server_tool_use", "id": "srv-2", "name": "web_search", "input": {"query": "b"}},+ {"type": "server_tool_use", "id": "srv-1", "name": "bash_code_execution", "input": {"command": "echo a"}},+ {+ "type": "bash_code_execution_tool_result",+ "tool_use_id": "srv-1",+ "content": {+ "type": "bash_code_execution_result",+ "stdout": "a\n",+ "stderr": "",+ "return_code": 0+ }+ },+ {"type": "server_tool_use", "id": "srv-2", "name": "bash_code_execution", "input": {"command": "echo b"}},],"stop_reason": stop_reason,"stop_sequence": null,@@ -512,118 +415,35 @@ async fn web_search_survives_paused_and_unknown_stop_reasons() {.try_into().unwrap(),);- let response = WebSearch {- input: "a and b".into(),+ let response = BashCodeExecution {+ input: "echo a and b".into(),}.call(ServiceContext(context), request).await.unwrap_or_else(|error| panic!("{stop_reason}: {}", error.description));assert_eq!(response.tool_use_id, "srv-1");match response.content {- WebSearchContent::Results(results) => assert_eq!(results.len(), 1),- WebSearchContent::Error(error) => panic!("{stop_reason}: {error:?}"),+ BashCodeExecutionContent::BashCodeExecutionResult(result) => {+ assert_eq!(result.stdout, "a\n")+ }+ BashCodeExecutionContent::BashCodeExecutionToolResultError(error) => {+ panic!("{stop_reason}: {error:?}")+ }}}}#[test]-fn web_search_output_folds_every_search_without_encrypted_content() {- let blocks: Vec<ResponseContentKind> = serde_json::from_value(serde_json::json!([- {"type": "text", "text": "Searching."},- {"type": "server_tool_use", "id": "srv-1", "name": "web_search", "input": {"query": "a"}},- search_result_block("srv-1", serde_json::json!([- search_result("https://a.example"),- search_result("https://shared.example"),- ])),- search_result_block("srv-2", serde_json::json!({- "type": "web_search_tool_result_error",- "error_code": "too_many_requests"- })),- search_result_block("srv-3", serde_json::json!([- search_result("https://shared.example"),- search_result("https://c.example"),- ])),- ]))- .unwrap();-- let response = web_search::collect_results(blocks).expect("a search ran");- assert_eq!(response.tool_use_id, "srv-1");- let WebSearchContent::Results(results) = response.content else {- panic!("one failed search must not hide the others' results");- };- let urls: Vec<_> = results- .iter()- .map(|result| match result {- SearchResult::WebSearchResult {- url,- encrypted_content,- ..- } => {- assert_eq!(encrypted_content, &None);- url.as_str()- }- })- .collect();- assert_eq!(- urls,- [- "https://a.example",- "https://shared.example",- "https://c.example"- ]- );-}--#[test]-fn web_search_output_reports_the_error_only_when_nothing_was_found() {- let blocks: Vec<ResponseContentKind> = serde_json::from_value(serde_json::json!([- search_result_block(- "srv-1",- serde_json::json!({- "type": "web_search_tool_result_error",- "error_code": "max_uses_exceeded"- })- ),- search_result_block(- "srv-2",- serde_json::json!({- "type": "web_search_tool_result_error",- "error_code": "unavailable"- })- ),- ]))- .unwrap();- let response = web_search::collect_results(blocks).expect("a search ran");- assert_eq!(response.tool_use_id, "srv-1");- assert!(matches!(- response.content,- WebSearchContent::Error(WebSearchToolError { ref error_code, .. }) if error_code == "max_uses_exceeded"- ));-- let no_search: Vec<ResponseContentKind> = serde_json::from_value(serde_json::json!([- {"type": "text", "text": "I do not need to search for that."}- ]))- .unwrap();- assert!(web_search::collect_results(no_search).is_none());-}--#[test]-fn deserialize_web_search_error_response() {- // Error case from docs — content is a single object, not an array+fn unknown_content_blocks_deserialize_as_unknown() {let json = serde_json::json!({"type": "web_search_tool_result","tool_use_id": "srvtoolu_a93jad",- "content": {- "type": "web_search_tool_result_error",- "error_code": "max_uses_exceeded"- }+ "content": []});-- let result = serde_json::from_value::<ResponseContentKind>(json);- match &result {- Err(e) => panic!("Failed to deserialize web search error: {e}"),- Ok(block) => assert!(matches!(block, ResponseContentKind::WebSearchToolResult(_))),- }+ assert_eq!(+ serde_json::from_value::<ResponseContentKind>(json).unwrap(),+ ResponseContentKind::Unknown+ );}#[test]diff --git a/crates/anthropic/src/toolset/web_fetch.rs b/crates/anthropic/src/toolset/web_fetch.rsdeleted file mode 100644index de36ea9bdb..0000000000--- a/crates/anthropic/src/toolset/web_fetch.rs+++ /dev/null@@ -1,54 +0,0 @@-use super::AnthropicToolContext;-use crate::types::request::WEB_FETCH_TOOL;-use crate::types::response::ResponseContentKind;-use crate::types::response::web_fetch::WebFetchResponse;-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};-use ai_toolset::{ToolAnnotated, ToolAnnotations};-use async_trait::async_trait;-use schemars::JsonSchema;-use serde::Deserialize;--/// Fetch a web page using Claude's built-in web fetch tool.-#[derive(Deserialize, JsonSchema, Clone)]-#[schemars(- title = "WebFetch",- description = "Fetch the contents of a web page using Claude's built-in web fetch tool."-)]-pub struct WebFetch {- /// The URL to fetch or an instruction describing what to fetch.- pub input: String,-}--impl ToolAnnotated for WebFetch {- const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Fetch a web page")- .with_open_world()- .without_idempotent();-}--#[async_trait]-impl AsyncTool<AnthropicToolContext> for WebFetch {- type Output = WebFetchResponse;-- #[tracing::instrument(skip_all, err)]- async fn call(- &self,- service_context: ServiceContext<AnthropicToolContext>,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- let ctx = &*service_context;- let blocks =- super::invoke_server_tool(ctx, &request_context, WEB_FETCH_TOOL.clone(), &self.input)- .await?;-- blocks- .into_iter()- .find_map(|b| match b {- ResponseContentKind::WebFetchToolResult(r) => Some(r),- _ => None,- })- .ok_or_else(|| ToolCallError {- internal_error: anyhow::anyhow!("no web fetch result in response"),- description: "No web fetch result returned".into(),- })- }-}diff --git a/crates/anthropic/src/toolset/web_search.rs b/crates/anthropic/src/toolset/web_search.rsdeleted file mode 100644index 45cb45f856..0000000000--- a/crates/anthropic/src/toolset/web_search.rs+++ /dev/null@@ -1,109 +0,0 @@-use super::AnthropicToolContext;-use crate::types::request::WEB_SEARCH_TOOL;-use crate::types::response::ResponseContentKind;-use crate::types::response::web_search::{SearchResult, WebSearchContent, WebSearchResponse};-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};-use ai_toolset::{ToolAnnotated, ToolAnnotations};-use async_trait::async_trait;-use schemars::JsonSchema;-use serde::Deserialize;-use std::collections::HashSet;--/// Search the web using Claude's built-in web search.-#[derive(Deserialize, JsonSchema, Clone)]-#[schemars(- title = "WebSearch",- description = "Search the web for information using Claude's built-in web search tool."-)]-pub struct WebSearch {- /// The search query or instruction.- pub input: String,-}--impl ToolAnnotated for WebSearch {- const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Search the web")- .with_open_world()- .without_idempotent();-}--#[async_trait]-impl AsyncTool<AnthropicToolContext> for WebSearch {- type Output = WebSearchResponse;-- #[tracing::instrument(skip_all, err)]- async fn call(- &self,- service_context: ServiceContext<AnthropicToolContext>,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- let ctx = &*service_context;- let blocks =- super::invoke_server_tool(ctx, &request_context, WEB_SEARCH_TOOL.clone(), &self.input)- .await?;-- collect_results(blocks).ok_or_else(|| ToolCallError {- internal_error: anyhow::anyhow!("no web search result in response"),- description: "No web search result returned".into(),- })- }-}--/// Fold every `web_search_tool_result` block of one response into the tool's-/// output.-///-/// The server-side model runs as many searches as the instruction needs, one-/// result block each, so the output carries all of them (deduplicated by URL)-/// under the first search's id rather than whichever block came first. A-/// search error is only the outcome when no search returned results, and-/// `None` means the model never searched.-///-/// `encrypted_content` is dropped: it is an opaque blob only the Anthropic-/// API can read, for citing within the same conversation, which never happens-/// here, and it is by far the largest part of every result.-pub(crate) fn collect_results(blocks: Vec<ResponseContentKind>) -> Option<WebSearchResponse> {- let mut searched = None;- let mut results = Vec::new();- let mut seen_urls = HashSet::new();- let mut failed = None;- for block in blocks {- let ResponseContentKind::WebSearchToolResult(result) = block else {- continue;- };- match result.content {- WebSearchContent::Results(found) => {- searched.get_or_insert(result.tool_use_id);- for found in found {- let SearchResult::WebSearchResult {- title,- url,- page_age,- ..- } = found;- if !seen_urls.insert(url.clone()) {- continue;- }- results.push(SearchResult::WebSearchResult {- title,- url,- encrypted_content: None,- page_age,- });- }- }- WebSearchContent::Error(error) => {- failed.get_or_insert((result.tool_use_id, error));- }- }- }- match (searched, failed) {- (Some(tool_use_id), _) => Some(WebSearchResponse {- content: WebSearchContent::Results(results),- tool_use_id,- }),- (None, Some((tool_use_id, error))) => Some(WebSearchResponse {- content: WebSearchContent::Error(error),- tool_use_id,- }),- (None, None) => None,- }-}diff --git a/crates/anthropic/src/types/request/mod.rs b/crates/anthropic/src/types/request/mod.rsindex 583d7ed7c4..7465112c45 100644--- a/crates/anthropic/src/types/request/mod.rs+++ b/crates/anthropic/src/types/request/mod.rs@@ -2,11 +2,7 @@ mod server_tools;mod types;mod util;-pub(crate) use server_tools::transform_request_web_fetch;-pub use server_tools::{- CODE_EXECUTION_TOOL, CODE_EXECUTION_TOOL_HEADER, WEB_FETCH_TOOL, WEB_FETCH_TOOL_HEADER,- WEB_SEARCH_TOOL,-};+pub use server_tools::{CODE_EXECUTION_TOOL, CODE_EXECUTION_TOOL_HEADER};pub use types::{CacheControl, ClientTool, CreateMessageRequestBody, ImageSource, McpServer, Metadata,RequestContent, RequestContentKind, RequestMessage, Role, ServerTool, ServiceTier,diff --git a/crates/anthropic/src/types/request/server_tools.rs b/crates/anthropic/src/types/request/server_tools.rsindex d1787bdcc0..cac7a52752 100644--- a/crates/anthropic/src/types/request/server_tools.rs+++ b/crates/anthropic/src/types/request/server_tools.rs@@ -1,20 +1,8 @@use super::types::ServerTool;-use crate::types::request::*;use lazy_static::lazy_static;-use regex::{Captures, Regex};use serde_json::Value;lazy_static! {- pub static ref WEB_SEARCH_TOOL: ServerTool = ServerTool {- name: "web_search".into(),- r#type: "web_search_20250305".into(),- args: Value::Null,- };- pub static ref WEB_FETCH_TOOL: ServerTool = ServerTool {- name: "web_fetch".into(),- r#type: "web_fetch_20250910".into(),- args: Value::Null,- };pub static ref CODE_EXECUTION_TOOL: ServerTool = ServerTool {name: "code_execution".into(),r#type: "code_execution_20250825".into(),@@ -22,60 +10,7 @@ lazy_static! {};}-pub static WEB_FETCH_TOOL_HEADER: (reqwest::header::HeaderName, reqwest::header::HeaderValue) = (- reqwest::header::HeaderName::from_static("anthropic-beta"),- reqwest::header::HeaderValue::from_static("web-fetch-2025-09-10"),-);-pub static CODE_EXECUTION_TOOL_HEADER: (reqwest::header::HeaderName, reqwest::header::HeaderValue) = (reqwest::header::HeaderName::from_static("anthropic-beta"),reqwest::header::HeaderValue::from_static("code-execution-2025-08-25"),);--lazy_static! {- static ref re: Regex = Regex::new("<m-link>(.+?)</m-link>").expect("link-regex");-}--fn replace_links(s: String) -> String {- re.replace_all(&s, |caps: &Captures| {- let json_str = &caps[1];- serde_json::from_str::<serde_json::Value>(json_str)- .ok()- .and_then(|v| v.get("url")?.as_str().map(String::from))- .unwrap_or_else(|| caps[0].to_string())- })- .into_owned()-}--// yes this is a compute virus-pub(crate) fn transform_request_web_fetch(- mut request: CreateMessageRequestBody,-) -> CreateMessageRequestBody {- request.messages = request- .messages- .into_iter()- .map(|mut message| {- message.content = match message.content {- RequestContent::Text(t) => RequestContent::Text(replace_links(t)),- RequestContent::Blocks(b) => RequestContent::Blocks(- b.into_iter()- .map(|b| match b {- RequestContentKind::Text {- text,- cache_control,- citations,- } => RequestContentKind::Text {- text: replace_links(text),- cache_control,- citations,- },- other => other,- })- .collect(),- ),- };- message- })- .collect();- request-}diff --git a/crates/anthropic/src/types/response/mod.rs b/crates/anthropic/src/types/response/mod.rsindex e7825cdd90..9a9da9cb70 100644--- a/crates/anthropic/src/types/response/mod.rs+++ b/crates/anthropic/src/types/response/mod.rs@@ -1,10 +1,6 @@pub mod code_execution;mod stream_types;-#[cfg(test)]-mod test;mod types;-pub mod web_fetch;-pub mod web_search;pub use stream_types::{Citation, ContentDeltaEvent, StreamError, StreamEvent};pub use types::{diff --git a/crates/anthropic/src/types/response/stream_types.rs b/crates/anthropic/src/types/response/stream_types.rsindex 40be4c6423..ef9b0855ed 100644--- a/crates/anthropic/src/types/response/stream_types.rs+++ b/crates/anthropic/src/types/response/stream_types.rs@@ -1,8 +1,6 @@use crate::prelude::ServerToolUse;use super::code_execution::{BashCodeExecutionResponse, TextEditorCodeExecutionResponse};-use super::web_fetch::WebFetchResponse;-use super::web_search::WebSearchResponse;use super::{MessageResponse, Usage};use serde::{Deserialize, Serialize};@@ -70,8 +68,6 @@ pub enum ContentDeltaEvent {CitationsDelta {citation: Citation,},- WebSearchToolResult(WebSearchResponse),- WebFetchToolResult(WebFetchResponse),BashCodeExecutionToolResult(BashCodeExecutionResponse),TextEditorCodeExecutionToolResult(TextEditorCodeExecutionResponse),}@@ -213,11 +209,7 @@ mod test {serde_json::from_str::<StreamEvent>(&serde_json::to_string(&start()).expect("str")).expect("deserialize_start");assert!(- if let StreamEvent::MessageStart { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::MessageStart { .. }),"deserialize start");}@@ -239,11 +231,7 @@ mod test {).expect("deserialize_content_block_start_text");assert!(- if let StreamEvent::ContentBlockStart { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::ContentBlockStart { .. }),"deserialize content_block_start_text");}@@ -271,11 +259,7 @@ mod test {).expect("deserialize_content_block_start_tool_use");assert!(- if let StreamEvent::ContentBlockStart { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::ContentBlockStart { .. }),"deserialize content_block_start_tool_use");}@@ -299,11 +283,7 @@ mod test {).expect("deserialize_content_block_delta_text");assert!(- if let StreamEvent::ContentBlockDelta { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::ContentBlockDelta { .. }),"deserialize content_block_delta_text");}@@ -327,11 +307,7 @@ mod test {).expect("deserialize_content_block_delta_json");assert!(- if let StreamEvent::ContentBlockDelta { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::ContentBlockDelta { .. }),"deserialize content_block_delta_json");}@@ -350,11 +326,7 @@ mod test {).expect("deserialize_content_block_stop");assert!(- if let StreamEvent::ContentBlockStop { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::ContentBlockStop { .. }),"deserialize content_block_stop");}@@ -395,11 +367,7 @@ mod test {).expect("deserialize_message_delta");assert!(- if let StreamEvent::MessageDelta { .. } = de {- true- } else {- false- },+ matches!(de, StreamEvent::MessageDelta { .. }),"deserialize message_delta");}@@ -417,11 +385,7 @@ mod test {).expect("deserialize_message_stop");assert!(- if let StreamEvent::MessageStop = de {- true- } else {- false- },+ matches!(de, StreamEvent::MessageStop),"deserialize message_stop");}@@ -436,13 +400,6 @@ mod test {fn test_de_ping() {let de = serde_json::from_str::<StreamEvent>(&serde_json::to_string(&ping()).expect("str")).expect("deserialize_ping");- assert!(- if let StreamEvent::Ping = de {- true- } else {- false- },- "deserialize ping"- );+ assert!(matches!(de, StreamEvent::Ping), "deserialize ping");}}diff --git a/crates/anthropic/src/types/response/test.rs b/crates/anthropic/src/types/response/test.rsdeleted file mode 100644index 48f50d4a39..0000000000--- a/crates/anthropic/src/types/response/test.rs+++ /dev/null@@ -1,87 +0,0 @@-use super::web_fetch::*;--#[test]-fn test_deserialize_web_fetch_result() {- let json = r#"{- "tool_use_id": "srvtoolu_01234567890abcdef",- "content": {- "type": "web_fetch_result",- "url": "https://example.com/article",- "content": {- "source": {- "type": "text",- "media_type": "text/plain",- "data": "Full text content of the article..."- },- "title": "Article Title",- "citations": {"enabled": true}- },- "retrieved_at": "2025-08-25T10:30:00Z"- }- }"#;-- let result: WebFetchResponse = serde_json::from_str(json).expect("deserialize");- assert_eq!(result.tool_use_id, "srvtoolu_01234567890abcdef");- if let WebFetchContent::WebFetchResult(r) = result.content {- assert_eq!(r.url, "https://example.com/article");- assert_eq!(r.content.title, Some("Article Title".to_string()));- } else {- panic!("Expected WebFetchResult");- }-}--#[test]-fn test_deserialize_web_fetch_pdf() {- let json = r#"{- "tool_use_id": "srvtoolu_02",- "content": {- "type": "web_fetch_result",- "url": "https://example.com/paper.pdf",- "content": {- "source": {- "type": "base64",- "media_type": "application/pdf",- "data": "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmo..."- },- "citations": {"enabled": true}- },- "retrieved_at": "2025-08-25T10:30:02Z"- }- }"#;-- let result: WebFetchResponse = serde_json::from_str(json).expect("deserialize");- if let WebFetchContent::WebFetchResult(r) = result.content {- if let WebFetchSource::Base64 { media_type, .. } = r.content.source {- assert_eq!(media_type, "application/pdf");- } else {- panic!("Expected Base64 source");- }- } else {- panic!("Expected WebFetchResult");- }-}--#[test]-fn test_deserialize_web_fetch_error() {- let json = r#"{- "tool_use_id": "srvtoolu_a93jad",- "content": {- "type": "web_fetch_tool_result_error",- "error_code": "url_not_accessible"- }- }"#;-- let result: WebFetchResponse = serde_json::from_str(json).expect("deserialize");- if let WebFetchContent::WebFetchToolError(e) = result.content {- assert_eq!(e.error_code, WebFetchErrorCode::UrlNotAccessible);- } else {- panic!("Expected WebFetchToolError");- }-}--#[test]-fn test_deserialize_tool_call() {- let json = r#"{"url": "https://example.com/article"}"#;- let call: WebFetchToolCall = serde_json::from_str(json).expect("deserialize");- assert_eq!(call.url, "https://example.com/article");-}diff --git a/crates/anthropic/src/types/response/types.rs b/crates/anthropic/src/types/response/types.rsindex 5d995b8eb6..888019be41 100644--- a/crates/anthropic/src/types/response/types.rs+++ b/crates/anthropic/src/types/response/types.rs@@ -2,8 +2,6 @@ use crate::types::request::Role;use crate::types::response::code_execution::{BashCodeExecutionResponse, TextEditorCodeExecutionResponse,};-use crate::types::response::web_fetch::WebFetchResponse;-use crate::types::response::web_search::WebSearchResponse;use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]@@ -13,8 +11,6 @@ pub enum ResponseContentKind {Thinking(ThinkingResponse),ToolUse(ToolUse),ServerToolUse(ServerToolUse),- WebSearchToolResult(WebSearchResponse),- WebFetchToolResult(WebFetchResponse),BashCodeExecutionToolResult(BashCodeExecutionResponse),TextEditorCodeExecutionToolResult(TextEditorCodeExecutionResponse),#[serde(other)]@@ -32,7 +28,7 @@ pub enum Content {pub struct ServerToolUse {pub id: String,pub input: serde_json::Value,- // one of web_search | web_fetch | code_execution | bash_code_execution | text_editor_code_execution+ // one of code_execution | bash_code_execution | text_editor_code_executionpub name: String,}@@ -73,7 +69,7 @@ pub enum StopReason {MaxTokens,StopSequence,ToolUse,- /// A server-tool loop (web search, web fetch, code execution) hit its+ /// A server-tool loop (such as code execution) hit its/// iteration limit. The content so far is complete up to that point;/// sending it back continues the turn.PauseTurn,diff --git a/crates/anthropic/src/types/response/web_fetch.rs b/crates/anthropic/src/types/response/web_fetch.rsdeleted file mode 100644index cfe4efd2a8..0000000000--- a/crates/anthropic/src/types/response/web_fetch.rs+++ /dev/null@@ -1,93 +0,0 @@-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};--/// Web fetch tool response content returned by Claude when using the web_fetch tool-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(rename_all = "snake_case")]-pub struct WebFetchResponse {- pub tool_use_id: String,- pub content: WebFetchContent,-}--/// Content of a web fetch response - either a successful result or an error-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum WebFetchContent {- WebFetchResult(WebFetchResult),- #[serde(rename = "web_fetch_tool_result_error")]- WebFetchToolError(WebFetchToolError),-}--/// Successful web fetch result containing the fetched content-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct WebFetchResult {- /// The URL that was fetched- pub url: String,- /// The fetched document content- pub content: WebFetchDocument,- /// Timestamp when the content was retrieved- pub retrieved_at: String,-}--/// Document content from a web fetch-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct WebFetchDocument {- /// The source content (text or base64)- pub source: WebFetchSource,- /// Optional title of the document- #[serde(skip_serializing_if = "Option::is_none")]- pub title: Option<String>,- /// Optional citations configuration- #[serde(skip_serializing_if = "Option::is_none")]- pub citations: Option<CitationsConfig>,-}--/// Source content of a fetched document-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum WebFetchSource {- /// Plain text content- Text { media_type: String, data: String },- /// Base64-encoded content (e.g., PDF)- Base64 { media_type: String, data: String },-}--/// Citations configuration for web fetch-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct CitationsConfig {- pub enabled: bool,-}--/// Error returned when web fetch fails-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct WebFetchToolError {- pub error_code: WebFetchErrorCode,-}--/// Possible error codes for web fetch failures-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(rename_all = "snake_case")]-pub enum WebFetchErrorCode {- /// Invalid URL format- InvalidInput,- /// URL exceeds maximum length (250 characters)- UrlTooLong,- /// URL blocked by domain filtering rules and model restrictions- UrlNotAllowed,- /// Failed to fetch content (HTTP error)- UrlNotAccessible,- /// Rate limit exceeded- TooManyRequests,- /// Content type not supported (only text and PDF)- UnsupportedContentType,- /// Maximum web fetch tool uses exceeded- MaxUsesExceeded,- /// An internal error occurred- Unavailable,-}--/// The expected shape of the streamed JSON following a `server_tool_use` in content_block_start event-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct WebFetchToolCall {- pub url: String,-}diff --git a/crates/anthropic/src/types/response/web_search.rs b/crates/anthropic/src/types/response/web_search.rsdeleted file mode 100644index d7f46dfb4f..0000000000--- a/crates/anthropic/src/types/response/web_search.rs+++ /dev/null@@ -1,45 +0,0 @@-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};--/// Web search response content returned by Claude when using the web_search tool-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(rename_all = "snake_case")]-pub struct WebSearchResponse {- pub content: WebSearchContent,- pub tool_use_id: String,-}--/// Content of a web search response — either search results or an error.-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(untagged)]-pub enum WebSearchContent {- Results(Vec<SearchResult>),- Error(WebSearchToolError),-}--/// A single search result from web search-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum SearchResult {- WebSearchResult {- title: String,- url: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- encrypted_content: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- page_age: Option<String>,- },-}--/// Error returned when web search fails-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct WebSearchToolError {- pub r#type: String,- pub error_code: String,-}--/// This is the expected shape of the streamed json following a `server_tool_use` in content_block_start event-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]-pub struct WebSearchToolCall {- pub query: String,-}diff --git a/crates/macro_db_client/migrations/20261104221338_add_provider_credit_usage_pricing.sql b/crates/macro_db_client/migrations/20261104221338_add_provider_credit_usage_pricing.sqlnew file mode 100644index 0000000000..d67f2841e3--- /dev/null+++ b/crates/macro_db_client/migrations/20261104221338_add_provider_credit_usage_pricing.sql@@ -0,0 +1,35 @@+-- Add vendor credit billing (e.g. Tavily search/extract credits) alongside+-- token and audio billing; deployed writers can continue omitting every new+-- column.+ALTER TABLE ai_pricing+ ADD COLUMN price_per_provider_credit REAL+ CHECK (price_per_provider_credit >= 0 AND price_per_provider_credit < 'Infinity'::real);++ALTER TABLE ai_usage+ ADD COLUMN provider_credits BIGINT CHECK (provider_credits >= 0),+ ADD COLUMN price_per_provider_credit REAL+ CHECK (price_per_provider_credit >= 0 AND price_per_provider_credit < 'Infinity'::real);++-- The input discount covers credit rates, as it does cache and audio rates.+CREATE OR REPLACE VIEW ai_effective_pricing AS+SELECT+ p.model,+ (p.price_per_million_in::numeric * f.input)::real AS price_per_million_in,+ (p.price_per_million_out::numeric * f.output)::real AS price_per_million_out,+ (p.price_per_million_cache_read::numeric * f.input)::real AS price_per_million_cache_read,+ (p.price_per_million_cache_write::numeric * f.input)::real AS price_per_million_cache_write,+ (p.price_per_audio_minute::numeric * f.input)::real AS price_per_audio_minute,+ (p.price_per_provider_credit::numeric * f.input)::real AS price_per_provider_credit+FROM ai_pricing p+LEFT JOIN ai_pricing_discount d ON d.model = p.model+CROSS JOIN LATERAL (+ SELECT+ 1 - COALESCE(d.input_discount_percent, 0) / 100 AS input,+ 1 - COALESCE(d.output_discount_percent, 0) / 100 AS output+) f;++-- https://tavily.com/pricing — $0.008 per pay-as-you-go credit.+-- Preserve any rate already configured by an administrator.+INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out, price_per_provider_credit)+VALUES ('tavily', 0, 0, 0.008)+ON CONFLICT (model) DO NOTHING;diff --git a/crates/prompt/src/about_macro.rs b/crates/prompt/src/about_macro.rsindex 8d87630104..2d2ced095f 100644--- a/crates/prompt/src/about_macro.rs+++ b/crates/prompt/src/about_macro.rs@@ -13,7 +13,7 @@ static INSTRUCTIONS: &str = r##"Macro is one fast workspace where a team's workWhen a user asks an open-ended question about Macro itself — what it is, what it'sfor, what it can do, or how to do something in Macro — call the SelfKnowledge tool.It returns an overview of Macro plus links into the docs (docs.macro.com) that you-can read with WebFetch. Do not answer these questions from memory; your training+can read with WebFetch (`macro.web.fetch()` in code mode). Do not answer these questions from memory; your trainingdata may be stale.Watch for ambiguity. A message like "what is this for?" could mean "what is Macrodiff --git a/crates/web_search/AGENTS.md b/crates/web_search/AGENTS.mdnew file mode 100644index 0000000000..9ec15d3cec--- /dev/null+++ b/crates/web_search/AGENTS.md@@ -0,0 +1,48 @@+# web_search++## What it is++Part of AI tools: web search and page fetch for every agent and the SDK. One+`SearchProvider` port with a Tavily adapter backs the `WebSearch`/`WebFetch`+agent tools (any model, any host) and cognition's `POST /web/search` and+`POST /web/fetch`, which `macro.web.search()`/`macro.web.fetch()` call.++## Start here++- `src/domain/service.rs`: `WebSearchService` — validation, AI admission+ (`AiFeature::WebSearch`), the provider call, and metering the vendor's+ credits to the user (`UsageAmount::ProviderCredits`, pricing id `tavily`).+- `src/domain/models.rs`: the request/response DTOs, shared by the HTTP routes+ and the tools (their schemars titles are the tool names).+- `src/outbound/tavily.rs`: typed reqwest client for `/search` and `/extract`.+- `src/inbound/axum_router.rs`: routes, `ActingUser` auth, per-user hourly limit.+- `src/inbound/toolset.rs`: the agent tools; `ai_tools` builds their context.++## Scope++- Owns: web search/fetch request policy, the vendor adapter, routes and tools.+- Not here: pricing rows and quota counting → `crates/ai_usage`, `crates/ai_billing`.++## Recipes++- Swap or add a vendor: implement `SearchProvider` in `src/outbound/<vendor>.rs`+ → seed its `ai_pricing` row (a migration) → construct it in+ `ai_tools::build_web_search_provider_from_env`.++## Checks++- `cargo test -p web_search --features axum` (no network: Tavily is mocked with+ the fixtures in `src/outbound/tavily/fixtures/`).++## Gotchas++- `TAVILY_API_KEY` is optional at startup so a missing secret cannot stop a+ host; every call then fails with `web_search_not_configured`. Never log it.+- Only the HTTP routes are rate limited; tool calls are bounded by agent turns.+- Usage is recorded only when Tavily reports `usage.credits`; the service warns otherwise.+- Code mode hides the tools (`agent_code_mode::domain::covered_by_code_sdk`);+ agents there use the SDK.++## Related++- Rules: `.agents/rules/rust/architecture.md`diff --git a/crates/web_search/CLAUDE.md b/crates/web_search/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/web_search/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/web_search/Cargo.toml b/crates/web_search/Cargo.tomlnew file mode 100644index 0000000000..f851b62980--- /dev/null+++ b/crates/web_search/Cargo.toml@@ -0,0 +1,54 @@+[package]+name = "web_search"+version = "0.1.0"+edition = "2024"+publish = false++[features]+axum = [+ "dep:axum",+ "dep:axum-extra",+ "dep:macro_authorization",+ "dep:rate_limit",+ "dep:rootcause",+]++[dependencies]+ai_billing = { path = "../ai_billing" }+ai_toolset = { path = "../ai_toolset" }+ai_usage = { path = "../ai_usage" }+anyhow.workspace = true+async-trait.workspace = true+axum = { workspace = true, optional = true }+axum-extra = { workspace = true, optional = true }+chrono.workspace = true+macro_authorization = { path = "../macro_authorization", default-features = false, features = [+ "axum",+], optional = true }+macro_env_var = { path = "../macro_env_var" }+macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid" }+rate_limit = { path = "../rate_limit", default-features = false, features = [+ "axum",+], optional = true }+reqwest.workspace = true+rootcause = { workspace = true, optional = true }+schemars.workspace = true+serde.workspace = true+thiserror.workspace = true+tracing.workspace = true+url.workspace = true+utoipa.workspace = true+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+http-body-util.workspace = true+model_user = { path = "../model_user" }+rate_limit = { path = "../rate_limit", default-features = false, features = [+ "axum",+ "testing",+] }+serde_json.workspace = true+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }+tower = { workspace = true, features = ["util"] }+wiremock.workspace = truediff --git a/crates/web_search/src/domain.rs b/crates/web_search/src/domain.rsnew file mode 100644index 0000000000..8ba82ac2a9--- /dev/null+++ b/crates/web_search/src/domain.rs@@ -0,0 +1,5 @@+//! Web search use cases, independent of HTTP and vendors.++pub mod models;+pub mod ports;+pub mod service;diff --git a/crates/web_search/src/domain/models.rs b/crates/web_search/src/domain/models.rsnew file mode 100644index 0000000000..6948122b19--- /dev/null+++ b/crates/web_search/src/domain/models.rs@@ -0,0 +1,235 @@+//! Web search and page fetch requests, results, and failures.++use chrono::NaiveDate;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++/// Longest accepted query, in characters.+pub const MAX_QUERY_CHARS: usize = 400;+/// Most results one search may return.+pub const MAX_RESULTS: u8 = 20;+/// Results returned when the caller does not ask for a count.+pub const DEFAULT_RESULTS: u8 = 5;+/// Most domains a search may be restricted to.+pub const MAX_DOMAINS: usize = 300;+/// Most domains a search may exclude.+pub const MAX_EXCLUDED_DOMAINS: usize = 150;+/// Page text kept per search result when `includeContent` is set.+pub const SEARCH_CONTENT_CHARS: usize = 8_000;+/// Page text a fetch returns when the caller does not ask for a length.+pub const DEFAULT_FETCH_CHARS: u32 = 20_000;+/// Most page text one fetch may return.+pub const MAX_FETCH_CHARS: u32 = 100_000;++/// The kind of results a search favours.+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, ToSchema, JsonSchema,+)]+#[serde(rename_all = "snake_case")]+pub enum WebSearchTopic {+ /// Any page on the web.+ #[default]+ General,+ /// Recent news articles, with publication dates.+ News,+}++/// Search the public web.+#[derive(Debug, Clone, Deserialize, Serialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "WebSearch",+ description = "Search the public web. Returns up to `maxResults` pages, each with its title, URL, a query-relevant snippet and, for news, its publication date. Snippets are often enough to answer; call WebFetch on a result's URL when you need the full page. Cite the URLs you use."+)]+pub struct WebSearch {+ /// What to search for, in natural language or keywords (at most 400 characters).+ pub query: String,+ /// Only return pages from these domains, e.g. `["docs.rs", "github.com"]`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub domains: Option<Vec<String>>,+ /// Never return pages from these domains.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub exclude_domains: Option<Vec<String>>,+ /// Only return pages published on or after this date (`YYYY-MM-DD`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub since: Option<NaiveDate>,+ /// `news` for recent articles with publication dates; `general` (the default) otherwise.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub topic: Option<WebSearchTopic>,+ /// How many results to return, 1 to 20 (default 5).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_results: Option<u8>,+ /// Also return each page's text as Markdown (up to 8,000 characters per result).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub include_content: Option<bool>,+}++/// One page a search found.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct WebSearchResult {+ /// The page title.+ pub title: String,+ /// The page URL; cite it when you use the result.+ pub url: String,+ /// The part of the page most relevant to the query.+ pub snippet: String,+ /// When the page was published, as the search provider reports it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub published_at: Option<String>,+ /// The page text as Markdown, when `includeContent` was set.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub content: Option<String>,+}++/// The pages a search found, best match first.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct WebSearchResponse {+ /// Results, best match first. Empty when nothing matched.+ pub results: Vec<WebSearchResult>,+}++/// Read one public web page.+#[derive(Debug, Clone, Deserialize, Serialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "WebFetch",+ description = "Read the text of one public web page as Markdown. Use it on a URL the user gave you or one WebSearch returned, when the snippet is not enough. Pages that need a login, or that render only with JavaScript, may fail. Cite the URL you read."+)]+pub struct WebFetch {+ /// The `http` or `https` URL of the page.+ pub url: String,+ /// Most characters of page text to return, 1 to 100,000 (default 20,000).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_chars: Option<u32>,+}++/// The text of a fetched page.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, ToSchema, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct WebFetchResponse {+ /// The URL that was read.+ pub url: String,+ /// The page title, when the provider reports one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ /// The page text as Markdown, cut to `maxChars`.+ pub content: String,+ /// Whether `content` was cut to `maxChars`.+ pub truncated: bool,+}++/// A validated search, as a provider receives it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SearchQuery {+ /// What to search for.+ pub query: String,+ /// Domains results must come from; empty means any.+ pub domains: Vec<String>,+ /// Domains results must not come from.+ pub exclude_domains: Vec<String>,+ /// Earliest publication date.+ pub since: Option<NaiveDate>,+ /// The kind of results to favour.+ pub topic: WebSearchTopic,+ /// How many results to return.+ pub max_results: u8,+ /// Whether to return each page's text.+ pub include_content: bool,+}++/// A validated fetch, as a provider receives it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PageRequest {+ /// The page to read.+ pub url: url::Url,+}++/// A page a provider read, before it is cut to the caller's length.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FetchedPage {+ /// The URL that was read.+ pub url: String,+ /// The page title, when known.+ pub title: Option<String>,+ /// The page text as Markdown.+ pub content: String,+}++/// A provider's answer and the credits it billed for it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Billed<T> {+ /// The answer.+ pub value: T,+ /// Credits the provider reported billing, or `None` when it reported none.+ pub credits: Option<u64>,+}++/// Why a provider call failed.+#[derive(Debug, thiserror::Error)]+pub enum ProviderError {+ /// The provider has no credentials in this deployment.+ #[error("web search is not configured: {0} is not set")]+ NotConfigured(&'static str),+ /// The provider is throttling us or our plan's credits are exhausted.+ #[error("web search provider is rate limited (HTTP {0})")]+ Throttled(u16),+ /// The provider could not read the requested page.+ #[error("the page could not be read: {0}")]+ PageUnavailable(String),+ /// Any other provider failure.+ #[error(transparent)]+ Failed(#[from] anyhow::Error),+}++/// Why a web search or fetch was refused or failed.+#[derive(Debug, thiserror::Error)]+pub enum WebSearchError {+ /// The request is malformed or out of bounds.+ #[error("{0}")]+ InvalidRequest(String),+ /// Shared AI admission refused the request.+ #[error(transparent)]+ Admission(#[from] ai_billing::AiAdmissionError),+ /// No provider credentials are configured.+ #[error("{0}")]+ NotConfigured(String),+ /// The provider is throttling requests.+ #[error("Web search is busy; try again shortly")]+ Throttled,+ /// The page could not be read.+ #[error("{0}")]+ PageUnavailable(String),+ /// The provider failed.+ #[error("Web search failed; try again")]+ Provider(#[source] anyhow::Error),+}++impl WebSearchError {+ /// Stable machine-readable failure code.+ pub fn code(&self) -> &'static str {+ match self {+ Self::InvalidRequest(_) => "invalid_request",+ Self::Admission(error) => error.code(),+ Self::NotConfigured(_) => "web_search_not_configured",+ Self::Throttled => "web_search_throttled",+ Self::PageUnavailable(_) => "fetch_failed",+ Self::Provider(_) => "web_search_failed",+ }+ }+}++impl From<ProviderError> for WebSearchError {+ fn from(error: ProviderError) -> Self {+ match error {+ ProviderError::NotConfigured(_) => Self::NotConfigured(error.to_string()),+ ProviderError::Throttled(_) => Self::Throttled,+ ProviderError::PageUnavailable(reason) => {+ Self::PageUnavailable(format!("The page could not be read: {reason}"))+ }+ ProviderError::Failed(error) => Self::Provider(error),+ }+ }+}diff --git a/crates/web_search/src/domain/ports.rs b/crates/web_search/src/domain/ports.rsnew file mode 100644index 0000000000..fbfe79752e--- /dev/null+++ b/crates/web_search/src/domain/ports.rs@@ -0,0 +1,23 @@+//! The seam a web search vendor plugs into.++use async_trait::async_trait;++use super::models::{+ Billed, FetchedPage, PageRequest, ProviderError, SearchQuery, WebSearchResult,+};++/// A web search vendor: search the web and read pages. One adapter per vendor.+#[async_trait]+pub trait SearchProvider: Send + Sync {+ /// The pricing id usage is recorded under (`ai_pricing.model`).+ fn pricing_model(&self) -> &'static str;++ /// Search the web, best match first.+ async fn search(+ &self,+ query: &SearchQuery,+ ) -> Result<Billed<Vec<WebSearchResult>>, ProviderError>;++ /// Read one page as Markdown.+ async fn fetch(&self, request: &PageRequest) -> Result<Billed<FetchedPage>, ProviderError>;+}diff --git a/crates/web_search/src/domain/service.rs b/crates/web_search/src/domain/service.rsnew file mode 100644index 0000000000..64f0d706e7--- /dev/null+++ b/crates/web_search/src/domain/service.rs@@ -0,0 +1,222 @@+//! Web search and fetch for a user: validation, AI admission, the provider+//! call, and usage metering. HTTP and tool adapters share this service.++use std::sync::Arc;++use ai_billing::AiAdmissionService;+use ai_usage::{AiFeature, UsageContext, UsageRecorder};+use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;++use super::models::{+ Billed, DEFAULT_FETCH_CHARS, DEFAULT_RESULTS, MAX_DOMAINS, MAX_EXCLUDED_DOMAINS,+ MAX_FETCH_CHARS, MAX_QUERY_CHARS, MAX_RESULTS, PageRequest, SEARCH_CONTENT_CHARS, SearchQuery,+ WebFetch, WebFetchResponse, WebSearch, WebSearchError, WebSearchResponse, WebSearchResult,+};+use super::ports::SearchProvider;++#[cfg(test)]+mod test;++/// Who a request is for, for admission and usage attribution.+#[derive(Debug, Clone)]+pub struct WebCaller {+ /// The user whose allowance pays for the request.+ pub user: MacroUserIdStr<'static>,+ /// The entity the request relates to (a chat or agent session), if any.+ pub entity: Option<Uuid>,+}++impl WebCaller {+ /// A request attributed only to `user`.+ pub fn user(user: MacroUserIdStr<'static>) -> Self {+ Self { user, entity: None }+ }+}++/// Web search and fetch, admitted against and metered to the caller's AI allowance.+#[derive(Clone)]+pub struct WebSearchService {+ provider: Arc<dyn SearchProvider>,+ admission: Arc<dyn AiAdmissionService>,+ recorder: Arc<dyn UsageRecorder>,+}++impl WebSearchService {+ /// Compose a provider with the host's admission policy and usage recorder.+ pub fn new(+ provider: Arc<dyn SearchProvider>,+ admission: Arc<dyn AiAdmissionService>,+ recorder: Arc<dyn UsageRecorder>,+ ) -> Self {+ Self {+ provider,+ admission,+ recorder,+ }+ }++ /// Search the web for `caller`.+ #[tracing::instrument(name = "web.search", skip_all, err, fields(+ web.provider = self.provider.pricing_model(),+ web.max_results = tracing::field::Empty,+ web.result_count = tracing::field::Empty,+ web.credits = tracing::field::Empty,+ ))]+ pub async fn search(+ &self,+ caller: WebCaller,+ request: WebSearch,+ ) -> Result<WebSearchResponse, WebSearchError> {+ let query = validate_search(request)?;+ tracing::Span::current().record("web.max_results", query.max_results);+ self.admission+ .admit(&caller.user, AiFeature::WebSearch)+ .await?;++ let Billed { value, credits } = self.provider.search(&query).await?;+ self.record(caller, credits);++ let results: Vec<WebSearchResult> = value+ .into_iter()+ .take(usize::from(query.max_results))+ .map(|result| WebSearchResult {+ content: result+ .content+ .filter(|_| query.include_content)+ .map(|content| truncate(content, SEARCH_CONTENT_CHARS).0),+ ..result+ })+ .collect();+ tracing::Span::current().record("web.result_count", results.len());+ Ok(WebSearchResponse { results })+ }++ /// Read one page for `caller`.+ #[tracing::instrument(name = "web.fetch", skip_all, err, fields(+ web.provider = self.provider.pricing_model(),+ web.truncated = tracing::field::Empty,+ web.credits = tracing::field::Empty,+ ))]+ pub async fn fetch(+ &self,+ caller: WebCaller,+ request: WebFetch,+ ) -> Result<WebFetchResponse, WebSearchError> {+ let (page, max_chars) = validate_fetch(request)?;+ self.admission+ .admit(&caller.user, AiFeature::WebSearch)+ .await?;++ let Billed { value, credits } = self.provider.fetch(&page).await?;+ self.record(caller, credits);++ let (content, truncated) = truncate(value.content, max_chars);+ tracing::Span::current().record("web.truncated", truncated);+ Ok(WebFetchResponse {+ url: value.url,+ title: value.title,+ content,+ truncated,+ })+ }++ fn record(&self, caller: WebCaller, credits: Option<u64>) {+ let Some(credits) = credits else {+ tracing::warn!("web search provider reported no usage; nothing recorded");+ return;+ };+ tracing::Span::current().record("web.credits", credits);+ self.recorder.record(+ UsageContext::new(AiFeature::WebSearch, caller.user)+ .with_entity(caller.entity)+ .into_provider_credits_event(self.provider.pricing_model().to_owned(), credits),+ );+ }+}++fn validate_search(request: WebSearch) -> Result<SearchQuery, WebSearchError> {+ let query = request.query.trim().to_owned();+ if query.is_empty() || query.chars().count() > MAX_QUERY_CHARS {+ return Err(WebSearchError::InvalidRequest(format!(+ "query must be between 1 and {MAX_QUERY_CHARS} characters"+ )));+ }++ let max_results = request.max_results.unwrap_or(DEFAULT_RESULTS);+ if !(1..=MAX_RESULTS).contains(&max_results) {+ return Err(WebSearchError::InvalidRequest(format!(+ "maxResults must be between 1 and {MAX_RESULTS}"+ )));+ }++ let domains = validate_domains(request.domains, MAX_DOMAINS, "domains")?;+ let exclude_domains = validate_domains(+ request.exclude_domains,+ MAX_EXCLUDED_DOMAINS,+ "excludeDomains",+ )?;++ Ok(SearchQuery {+ query,+ domains,+ exclude_domains,+ since: request.since,+ topic: request.topic.unwrap_or_default(),+ max_results,+ include_content: request.include_content.unwrap_or(false),+ })+}++fn validate_domains(+ domains: Option<Vec<String>>,+ limit: usize,+ field: &str,+) -> Result<Vec<String>, WebSearchError> {+ let domains: Vec<String> = domains+ .unwrap_or_default()+ .into_iter()+ .map(|domain| domain.trim().to_owned())+ .collect();+ if domains.len() > limit {+ return Err(WebSearchError::InvalidRequest(format!(+ "{field} accepts at most {limit} domains"+ )));+ }+ if domains+ .iter()+ .any(|domain| domain.is_empty() || domain.contains(char::is_whitespace))+ {+ return Err(WebSearchError::InvalidRequest(format!(+ "{field} must be domain names such as example.com"+ )));+ }+ Ok(domains)+}++fn validate_fetch(request: WebFetch) -> Result<(PageRequest, usize), WebSearchError> {+ let url = url::Url::parse(request.url.trim())+ .map_err(|_| WebSearchError::InvalidRequest("url must be an absolute URL".into()))?;+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {+ return Err(WebSearchError::InvalidRequest(+ "url must be an http or https URL with a host".into(),+ ));+ }++ let max_chars = request.max_chars.unwrap_or(DEFAULT_FETCH_CHARS);+ if !(1..=MAX_FETCH_CHARS).contains(&max_chars) {+ return Err(WebSearchError::InvalidRequest(format!(+ "maxChars must be between 1 and {MAX_FETCH_CHARS}"+ )));+ }++ Ok((PageRequest { url }, max_chars as usize))+}++/// Cut `text` to at most `max_chars` characters, reporting whether it was cut.+fn truncate(text: String, max_chars: usize) -> (String, bool) {+ match text.char_indices().nth(max_chars) {+ Some((end, _)) => (text[..end].to_owned(), true),+ None => (text, false),+ }+}diff --git a/crates/web_search/src/domain/service/test.rs b/crates/web_search/src/domain/service/test.rsnew file mode 100644index 0000000000..fcb2aa5623--- /dev/null+++ b/crates/web_search/src/domain/service/test.rs@@ -0,0 +1,334 @@+use std::sync::{Arc, Mutex};++use ai_billing::{AiAdmissionError, AiAdmissionService, DenyReason, DisabledAiAdmissionService};+use ai_usage::{AiFeature, UsageAmount, UsageEvent, UsageRecorder};+use async_trait::async_trait;+use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;++use super::{WebCaller, WebSearchService};+use crate::domain::models::{+ Billed, FetchedPage, PageRequest, ProviderError, SearchQuery, WebFetch, WebFetchResponse,+ WebSearch, WebSearchError, WebSearchResponse, WebSearchResult, WebSearchTopic,+};+use crate::domain::ports::SearchProvider;++#[derive(Default)]+struct FakeProvider {+ searches: Mutex<Vec<SearchQuery>>,+ fetches: Mutex<Vec<PageRequest>>,+}++#[async_trait]+impl SearchProvider for FakeProvider {+ fn pricing_model(&self) -> &'static str {+ "fake"+ }++ async fn search(+ &self,+ query: &SearchQuery,+ ) -> Result<Billed<Vec<WebSearchResult>>, ProviderError> {+ self.searches.lock().unwrap().push(query.clone());+ Ok(Billed {+ credits: Some(1),+ value: vec![+ WebSearchResult {+ title: "First".into(),+ url: "https://example.com/1".into(),+ snippet: "one".into(),+ published_at: None,+ content: Some("abcdef".repeat(2_000)),+ },+ WebSearchResult {+ title: "Second".into(),+ url: "https://example.com/2".into(),+ snippet: "two".into(),+ published_at: Some("2026-11-01".into()),+ content: None,+ },+ ],+ })+ }++ async fn fetch(&self, request: &PageRequest) -> Result<Billed<FetchedPage>, ProviderError> {+ self.fetches.lock().unwrap().push(request.clone());+ Ok(Billed {+ credits: Some(1),+ value: FetchedPage {+ url: request.url.to_string(),+ title: None,+ content: "héllo wörld".into(),+ },+ })+ }+}++#[derive(Default)]+struct Recorder(Mutex<Vec<UsageEvent>>);++impl UsageRecorder for Recorder {+ fn record(&self, event: UsageEvent) {+ self.0.lock().unwrap().push(event);+ }+}++struct Denied;++impl AiAdmissionService for Denied {+ fn admit<'a>(+ &'a self,+ _: &'a MacroUserIdStr<'_>,+ _: AiFeature,+ ) -> ai_billing::AdmissionFuture<'a> {+ Box::pin(async { Err(AiAdmissionError::Denied(DenyReason::AllowanceExhausted)) })+ }+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap()+}++#[tokio::test]+async fn search_passes_defaults_and_meters_credits_to_the_user() {+ let provider = Arc::new(FakeProvider::default());+ let recorder = Arc::new(Recorder::default());+ let service = WebSearchService::new(+ provider.clone(),+ Arc::new(DisabledAiAdmissionService),+ recorder.clone(),+ );+ let entity = Uuid::new_v4();++ let response = service+ .search(+ WebCaller {+ user: user(),+ entity: Some(entity),+ },+ WebSearch {+ query: " macro docs ".into(),+ domains: None,+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: None,+ include_content: None,+ },+ )+ .await+ .unwrap();++ assert_eq!(+ *provider.searches.lock().unwrap(),+ vec![SearchQuery {+ query: "macro docs".into(),+ domains: vec![],+ exclude_domains: vec![],+ since: None,+ topic: WebSearchTopic::General,+ max_results: 5,+ include_content: false,+ }]+ );+ assert_eq!(+ response,+ WebSearchResponse {+ results: vec![+ WebSearchResult {+ title: "First".into(),+ url: "https://example.com/1".into(),+ snippet: "one".into(),+ published_at: None,+ content: None,+ },+ WebSearchResult {+ title: "Second".into(),+ url: "https://example.com/2".into(),+ snippet: "two".into(),+ published_at: Some("2026-11-01".into()),+ content: None,+ },+ ],+ }+ );+ let events = recorder.0.lock().unwrap();+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].feature, AiFeature::WebSearch);+ assert_eq!(events[0].user, user());+ assert_eq!(events[0].entity, Some(entity));+ assert_eq!(events[0].model, "fake");+ assert_eq!(+ events[0].amount,+ UsageAmount::ProviderCredits { credits: 1 }+ );+}++#[tokio::test]+async fn search_content_is_cut_to_eight_thousand_characters() {+ let service = WebSearchService::new(+ Arc::new(FakeProvider::default()),+ Arc::new(DisabledAiAdmissionService),+ Arc::new(Recorder::default()),+ );++ let response = service+ .search(+ WebCaller::user(user()),+ WebSearch {+ query: "macro".into(),+ domains: None,+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: Some(1),+ include_content: Some(true),+ },+ )+ .await+ .unwrap();++ assert_eq!(response.results.len(), 1);+ assert_eq!(+ response.results[0].content.as_deref().map(str::len),+ Some(8_000)+ );+}++#[tokio::test]+async fn invalid_requests_never_reach_the_provider() {+ let provider = Arc::new(FakeProvider::default());+ let service = WebSearchService::new(+ provider.clone(),+ Arc::new(DisabledAiAdmissionService),+ Arc::new(Recorder::default()),+ );++ for request in [+ WebSearch {+ query: " ".into(),+ domains: None,+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: None,+ include_content: None,+ },+ WebSearch {+ query: "x".repeat(401),+ domains: None,+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: None,+ include_content: None,+ },+ WebSearch {+ query: "macro".into(),+ domains: None,+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: Some(21),+ include_content: None,+ },+ WebSearch {+ query: "macro".into(),+ domains: Some(vec!["not a domain".into()]),+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: None,+ include_content: None,+ },+ ] {+ let error = service+ .search(WebCaller::user(user()), request)+ .await+ .unwrap_err();+ assert!(+ matches!(error, WebSearchError::InvalidRequest(_)),+ "{error:?}"+ );+ }++ for url in ["ftp://example.com/file", "/relative", "https://"] {+ let error = service+ .fetch(+ WebCaller::user(user()),+ WebFetch {+ url: url.into(),+ max_chars: None,+ },+ )+ .await+ .unwrap_err();+ assert!(+ matches!(error, WebSearchError::InvalidRequest(_)),+ "{url}: {error:?}"+ );+ }++ assert!(provider.searches.lock().unwrap().is_empty());+ assert!(provider.fetches.lock().unwrap().is_empty());+}++#[tokio::test]+async fn admission_refusal_skips_the_provider_and_metering() {+ let provider = Arc::new(FakeProvider::default());+ let recorder = Arc::new(Recorder::default());+ let service = WebSearchService::new(provider.clone(), Arc::new(Denied), recorder.clone());++ let error = service+ .fetch(+ WebCaller::user(user()),+ WebFetch {+ url: "https://example.com/".into(),+ max_chars: None,+ },+ )+ .await+ .unwrap_err();++ assert!(+ matches!(+ error,+ WebSearchError::Admission(AiAdmissionError::Denied(DenyReason::AllowanceExhausted))+ ),+ "{error:?}"+ );+ assert!(provider.fetches.lock().unwrap().is_empty());+ assert!(recorder.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn fetch_cuts_on_character_boundaries() {+ let recorder = Arc::new(Recorder::default());+ let service = WebSearchService::new(+ Arc::new(FakeProvider::default()),+ Arc::new(DisabledAiAdmissionService),+ recorder.clone(),+ );++ let response = service+ .fetch(+ WebCaller::user(user()),+ WebFetch {+ url: "https://example.com/page".into(),+ max_chars: Some(2),+ },+ )+ .await+ .unwrap();++ assert_eq!(+ response,+ WebFetchResponse {+ url: "https://example.com/page".into(),+ title: None,+ content: "hé".into(),+ truncated: true,+ }+ );+ assert_eq!(recorder.0.lock().unwrap().len(), 1);+}diff --git a/crates/web_search/src/inbound.rs b/crates/web_search/src/inbound.rsnew file mode 100644index 0000000000..536a62e03e--- /dev/null+++ b/crates/web_search/src/inbound.rs@@ -0,0 +1,5 @@+//! HTTP routes and agent tools.++#[cfg(feature = "axum")]+pub mod axum_router;+pub mod toolset;diff --git a/crates/web_search/src/inbound/axum_router.rs b/crates/web_search/src/inbound/axum_router.rsnew file mode 100644index 0000000000..a9d3031508--- /dev/null+++ b/crates/web_search/src/inbound/axum_router.rs@@ -0,0 +1,281 @@+//! HTTP adapter: `POST /web/search` and `POST /web/fetch` for any caller with a+//! verified acting user (signed-in users, API keys, and code-mode SDK tokens).++use std::{sync::Arc, time::Duration};++use ai_billing::inbound::admission::admission_status;+use axum::{+ Json, RequestPartsExt, Router,+ extract::{FromRef, FromRequestParts, State, rejection::JsonRejection},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::post,+};+use axum_extra::extract::Cached;+use macro_authorization::{+ ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,+};+use rate_limit::{+ RateLimitConfig, RateLimitKey, RateLimitResult, RateLimitService,+ domain::models::RateLimitOk,+ inbound::{RateLimitExtractable, RateLimitExtractor},+};+use rootcause::Report;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++use crate::domain::models::{+ WebFetch, WebFetchResponse, WebSearch, WebSearchError, WebSearchResponse,+};+use crate::domain::service::{WebCaller, WebSearchService};++#[cfg(test)]+mod test;++/// Searches and fetches each user may make per hour, counted together.+const PER_USER_REQUESTS_PER_HOUR: u64 = 600;++/// Router state: the use case, a rate limiter, and caller authentication.+pub struct WebRouterState<R, Auth> {+ service: Arc<WebSearchService>,+ rate_limiter: R,+ authorization: MacroAuthorizationState<Auth>,+}++impl<R: Clone, Auth> Clone for WebRouterState<R, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ rate_limiter: self.rate_limiter.clone(),+ authorization: self.authorization.clone(),+ }+ }+}++impl<R, Auth> WebRouterState<R, Auth> {+ /// Compose the use case with the host's rate limiter and authorization.+ pub fn new(+ service: Arc<WebSearchService>,+ rate_limiter: R,+ authorization: MacroAuthorizationState<Auth>,+ ) -> Self {+ Self {+ service,+ rate_limiter,+ authorization,+ }+ }+}++impl<R, Auth> FromRef<WebRouterState<R, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &WebRouterState<R, Auth>) -> Self {+ state.authorization.clone()+ }+}++impl<R, Auth> RateLimitService for WebRouterState<R, Auth>+where+ R: RateLimitService,+ Auth: MacroAuthorizationService,+{+ async fn check_rate_limit(+ &self,+ key: RateLimitKey,+ config: RateLimitConfig,+ ) -> Result<RateLimitResult, Report> {+ let result = self.rate_limiter.check_rate_limit(key, config).await?;+ if result.is_err() {+ tracing::warn!("web search rate limit exceeded");+ }+ Ok(result)+ }++ async fn rollback_ticket(&self, ticket: RateLimitOk) -> Result<(), Report> {+ self.rate_limiter.rollback_ticket(ticket).await+ }+}++/// Per-user web request limit, keyed by the verified acting user.+pub struct PerUserWebRateLimit<Auth>(MacroAuthorizationExtractor<Auth, ActingUser>);++impl<S, Auth> RateLimitExtractable<S> for PerUserWebRateLimit<Auth>+where+ S: Send + Sync + 'static,+ Auth: MacroAuthorizationService,+ MacroAuthorizationState<Auth>: FromRef<S>,+{+ fn config() -> RateLimitConfig {+ RateLimitConfig::new(PER_USER_REQUESTS_PER_HOUR, Duration::from_secs(3600))+ }++ fn key(&self) -> RateLimitKey {+ RateLimitKey::builder(&"per-user-web-search")+ .append(&self.0.authorization.user.macro_user_id.as_ref())+ .finish()+ }+}++impl<S, Auth> FromRequestParts<S> for PerUserWebRateLimit<Auth>+where+ S: Send + Sync + 'static,+ Auth: MacroAuthorizationService,+ MacroAuthorizationState<Auth>: FromRef<S>,+{+ type Rejection = Response;++ async fn from_request_parts(+ parts: &mut axum::http::request::Parts,+ state: &S,+ ) -> Result<Self, Self::Rejection> {+ let Cached(authorization): Cached<MacroAuthorizationExtractor<Auth, ActingUser>> = parts+ .extract_with_state(state)+ .await+ .map_err(IntoResponse::into_response)?;+ Ok(Self(authorization))+ }+}++/// `POST /web/search` and `POST /web/fetch`.+pub fn web_router<R, Auth, S>(state: WebRouterState<R, Auth>) -> Router<S>+where+ R: RateLimitService + Clone,+ Auth: MacroAuthorizationService,+ S: Send + Sync + Clone + 'static,+{+ Router::new()+ .route("/web/search", post(search_handler::<R, Auth>))+ .route("/web/fetch", post(fetch_handler::<R, Auth>))+ .with_state(state)+}++/// Machine-readable failure of a web request.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct WebErrorBody {+ /// Explanation without provider diagnostics.+ pub error: String,+ /// Stable failure code.+ pub code: String,+}++/// An HTTP status with its [`WebErrorBody`].+pub struct WebFailure {+ status: StatusCode,+ body: WebErrorBody,+}++impl From<WebSearchError> for WebFailure {+ fn from(error: WebSearchError) -> Self {+ let status = match &error {+ WebSearchError::InvalidRequest(_) => StatusCode::BAD_REQUEST,+ WebSearchError::Admission(admission) => admission_status(*admission),+ WebSearchError::NotConfigured(_) | WebSearchError::Throttled => {+ StatusCode::SERVICE_UNAVAILABLE+ }+ WebSearchError::PageUnavailable(_) => StatusCode::UNPROCESSABLE_ENTITY,+ WebSearchError::Provider(_) => StatusCode::BAD_GATEWAY,+ };+ if status.is_server_error() {+ tracing::error!(error = ?error, code = error.code(), "web request failed");+ }+ Self {+ status,+ body: WebErrorBody {+ error: error.to_string(),+ code: error.code().to_owned(),+ },+ }+ }+}++impl IntoResponse for WebFailure {+ fn into_response(self) -> Response {+ (self.status, Json(self.body)).into_response()+ }+}++fn invalid_body(rejection: JsonRejection) -> WebFailure {+ WebFailure {+ status: StatusCode::BAD_REQUEST,+ body: WebErrorBody {+ error: rejection.body_text(),+ code: "invalid_request".to_owned(),+ },+ }+}++/// Search the public web. Charged to the acting user's AI allowance.+#[utoipa::path(+ post,+ path = "/web/search",+ operation_id = "search_web",+ tag = "web",+ request_body = WebSearch,+ responses(+ (status = 200, description = "Results, best match first", body = WebSearchResponse),+ (status = 400, description = "Invalid query or filters", body = WebErrorBody),+ (status = 401, description = "Unauthorized"),+ (status = 402, description = "AI allowance exhausted", body = WebErrorBody),+ (status = 429, description = "Per-user hourly rate limit exceeded"),+ (status = 502, description = "The search provider failed", body = WebErrorBody),+ (status = 503, description = "Web search unconfigured, busy, or usage validation unavailable", body = WebErrorBody),+ )+)]+pub async fn search_handler<R, Auth>(+ Cached(caller): Cached<MacroAuthorizationExtractor<Auth, ActingUser>>,+ _limit: RateLimitExtractor<PerUserWebRateLimit<Auth>, WebRouterState<R, Auth>>,+ State(state): State<WebRouterState<R, Auth>>,+ request: Result<Json<WebSearch>, JsonRejection>,+) -> Result<Json<WebSearchResponse>, WebFailure>+where+ R: RateLimitService + Clone,+ Auth: MacroAuthorizationService,+{+ let Json(request) = request.map_err(invalid_body)?;+ let response = state+ .service+ .search(+ WebCaller::user(caller.authorization.user.macro_user_id),+ request,+ )+ .await?;+ Ok(Json(response))+}++/// Read one public web page as Markdown. Charged to the acting user's AI allowance.+#[utoipa::path(+ post,+ path = "/web/fetch",+ operation_id = "fetch_web_page",+ tag = "web",+ request_body = WebFetch,+ responses(+ (status = 200, description = "The page text", body = WebFetchResponse),+ (status = 400, description = "Invalid URL or length", body = WebErrorBody),+ (status = 401, description = "Unauthorized"),+ (status = 402, description = "AI allowance exhausted", body = WebErrorBody),+ (status = 422, description = "The page could not be read", body = WebErrorBody),+ (status = 429, description = "Per-user hourly rate limit exceeded"),+ (status = 502, description = "The fetch provider failed", body = WebErrorBody),+ (status = 503, description = "Web fetch unconfigured, busy, or usage validation unavailable", body = WebErrorBody),+ )+)]+pub async fn fetch_handler<R, Auth>(+ Cached(caller): Cached<MacroAuthorizationExtractor<Auth, ActingUser>>,+ _limit: RateLimitExtractor<PerUserWebRateLimit<Auth>, WebRouterState<R, Auth>>,+ State(state): State<WebRouterState<R, Auth>>,+ request: Result<Json<WebFetch>, JsonRejection>,+) -> Result<Json<WebFetchResponse>, WebFailure>+where+ R: RateLimitService + Clone,+ Auth: MacroAuthorizationService,+{+ let Json(request) = request.map_err(invalid_body)?;+ let response = state+ .service+ .fetch(+ WebCaller::user(caller.authorization.user.macro_user_id),+ request,+ )+ .await?;+ Ok(Json(response))+}diff --git a/crates/web_search/src/inbound/axum_router/test.rs b/crates/web_search/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..5c802ed778--- /dev/null+++ b/crates/web_search/src/inbound/axum_router/test.rs@@ -0,0 +1,333 @@+use std::sync::{Arc, Mutex};++use ai_billing::{AiAdmissionError, AiAdmissionService, DenyReason, DisabledAiAdmissionService};+use ai_usage::{AiFeature, UsageAmount, UsageEvent, UsageRecorder};+use async_trait::async_trait;+use axum::{+ Router,+ body::{Body, to_bytes},+ http::{Request, StatusCode, header},+};+use macro_authorization::{+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,+ MacroAuthorizationState, ValidatedCredential,+};+use macro_user_id::user_id::MacroUserIdStr;+use model_user::UserContext;+use rate_limit::{+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitService,+ domain::models::RateLimitOk,+};+use rootcause::Report;+use serde_json::{Value, json};+use tower::ServiceExt;++use super::{WebRouterState, web_router};+use crate::domain::models::{+ Billed, FetchedPage, PageRequest, ProviderError, SearchQuery, WebSearchResult,+};+use crate::domain::ports::SearchProvider;+use crate::domain::service::WebSearchService;++const USER_ID: &str = "macro|[email protected]";++#[derive(Default)]+struct FakeProvider {+ calls: Mutex<usize>,+}++#[async_trait]+impl SearchProvider for FakeProvider {+ fn pricing_model(&self) -> &'static str {+ "tavily"+ }++ async fn search(&self, _: &SearchQuery) -> Result<Billed<Vec<WebSearchResult>>, ProviderError> {+ *self.calls.lock().unwrap() += 1;+ Ok(Billed {+ credits: Some(1),+ value: vec![WebSearchResult {+ title: "Macro".into(),+ url: "https://macro.com/".into(),+ snippet: "Macro is a workspace.".into(),+ published_at: None,+ content: None,+ }],+ })+ }++ async fn fetch(&self, _: &PageRequest) -> Result<Billed<FetchedPage>, ProviderError> {+ *self.calls.lock().unwrap() += 1;+ Err(ProviderError::PageUnavailable(+ "Failed to retrieve content".into(),+ ))+ }+}++#[derive(Default)]+struct Recorder(Mutex<Vec<UsageEvent>>);++impl UsageRecorder for Recorder {+ fn record(&self, event: UsageEvent) {+ self.0.lock().unwrap().push(event);+ }+}++struct Denied;++impl AiAdmissionService for Denied {+ fn admit<'a>(+ &'a self,+ _: &'a MacroUserIdStr<'_>,+ _: AiFeature,+ ) -> ai_billing::AdmissionFuture<'a> {+ Box::pin(async { Err(AiAdmissionError::Denied(DenyReason::AllowanceExhausted)) })+ }+}++#[derive(Clone, Default)]+struct FakeRateLimiter {+ exceeded: bool,+ checks: Arc<Mutex<Vec<(String, u64, u64)>>>,+}++impl RateLimitService for FakeRateLimiter {+ async fn check_rate_limit(+ &self,+ key: RateLimitKey,+ config: RateLimitConfig,+ ) -> Result<RateLimitResult, Report> {+ self.checks.lock().unwrap().push((+ key.to_hex_string(),+ config.max_count,+ config.window.as_secs(),+ ));+ if self.exceeded {+ return Ok(Err(RateLimitExceeded {+ current_count: config.max_count,+ max_count: config.max_count,+ retry_after: config.window,+ }));+ }+ Ok(Ok(RateLimitOk::new_testing_value(1, key, config)))+ }++ async fn rollback_ticket(&self, _: RateLimitOk) -> Result<(), Report> {+ Ok(())+ }+}++#[derive(Clone, Default)]+struct FakeAuthorization;++impl MacroAuthorizationService for FakeAuthorization {+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {+ match jwt {+ "valid" => Ok(UserContext {+ user_id: USER_ID.to_owned(),+ ..UserContext::default()+ }),+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),+ }+ }++ async fn authorize_identity(+ &self,+ jwt: &str,+ ) -> Result<ValidatedCredential, Report<MacroAuthorizationError>> {+ self.authorize(jwt).await.map(ValidatedCredential::session)+ }++ async fn authorize_internal(+ &self,+ _: &str,+ _: InternalIdentityClaims,+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))+ }+}++fn router(+ provider: Arc<FakeProvider>,+ admission: Arc<dyn AiAdmissionService>,+ recorder: Arc<Recorder>,+ limiter: FakeRateLimiter,+) -> Router {+ web_router::<_, _, ()>(WebRouterState::new(+ Arc::new(WebSearchService::new(provider, admission, recorder)),+ limiter,+ MacroAuthorizationState::new(Arc::new(FakeAuthorization)),+ ))+}++fn post(uri: &str, authorization: Option<&str>, body: Value) -> Request<Body> {+ let mut request = Request::builder()+ .method("POST")+ .uri(uri)+ .header(header::CONTENT_TYPE, "application/json");+ if let Some(token) = authorization {+ request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));+ }+ request.body(Body::from(body.to_string())).unwrap()+}++async fn json_body(response: axum::response::Response) -> Value {+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap()+}++#[tokio::test]+async fn search_returns_results_and_meters_the_caller() {+ let provider = Arc::new(FakeProvider::default());+ let recorder = Arc::new(Recorder::default());+ let limiter = FakeRateLimiter::default();+ let response = router(+ provider.clone(),+ Arc::new(DisabledAiAdmissionService),+ recorder.clone(),+ limiter.clone(),+ )+ .oneshot(post(+ "/web/search",+ Some("valid"),+ json!({ "query": "what is macro", "maxResults": 1, "topic": "news" }),+ ))+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ json_body(response).await,+ json!({ "results": [{+ "title": "Macro",+ "url": "https://macro.com/",+ "snippet": "Macro is a workspace."+ }] })+ );+ let checks = limiter.checks.lock().unwrap();+ assert_eq!(checks.len(), 1);+ assert_eq!((checks[0].1, checks[0].2), (600, 3600));+ let events = recorder.0.lock().unwrap();+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].user.as_ref(), USER_ID);+ assert_eq!(events[0].feature, AiFeature::WebSearch);+ assert_eq!(events[0].model, "tavily");+ assert_eq!(+ events[0].amount,+ UsageAmount::ProviderCredits { credits: 1 }+ );+}++#[tokio::test]+async fn unauthenticated_requests_do_no_work() {+ let provider = Arc::new(FakeProvider::default());+ let limiter = FakeRateLimiter::default();+ let app = router(+ provider.clone(),+ Arc::new(DisabledAiAdmissionService),+ Arc::new(Recorder::default()),+ limiter.clone(),+ );++ for token in [None, Some("forged")] {+ let response = app+ .clone()+ .oneshot(post("/web/search", token, json!({ "query": "macro" })))+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ }++ assert_eq!(*provider.calls.lock().unwrap(), 0);+ assert!(limiter.checks.lock().unwrap().is_empty());+}++#[tokio::test]+async fn admission_refusal_is_payment_required() {+ let provider = Arc::new(FakeProvider::default());+ let recorder = Arc::new(Recorder::default());+ let response = router(+ provider.clone(),+ Arc::new(Denied),+ recorder.clone(),+ FakeRateLimiter::default(),+ )+ .oneshot(post(+ "/web/search",+ Some("valid"),+ json!({ "query": "macro" }),+ ))+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::PAYMENT_REQUIRED);+ assert_eq!(+ json_body(response).await["code"],+ DenyReason::AllowanceExhausted.code()+ );+ assert_eq!(*provider.calls.lock().unwrap(), 0);+ assert!(recorder.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn the_hourly_limit_refuses_before_the_provider() {+ let provider = Arc::new(FakeProvider::default());+ let response = router(+ provider.clone(),+ Arc::new(DisabledAiAdmissionService),+ Arc::new(Recorder::default()),+ FakeRateLimiter {+ exceeded: true,+ ..FakeRateLimiter::default()+ },+ )+ .oneshot(post(+ "/web/fetch",+ Some("valid"),+ json!({ "url": "https://example.com/" }),+ ))+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);+ assert_eq!(*provider.calls.lock().unwrap(), 0);+}++#[tokio::test]+async fn unreadable_pages_and_bad_input_have_distinct_codes() {+ let app = router(+ Arc::new(FakeProvider::default()),+ Arc::new(DisabledAiAdmissionService),+ Arc::new(Recorder::default()),+ FakeRateLimiter::default(),+ );++ let unreadable = app+ .clone()+ .oneshot(post(+ "/web/fetch",+ Some("valid"),+ json!({ "url": "https://example.com/members-only" }),+ ))+ .await+ .unwrap();+ assert_eq!(unreadable.status(), StatusCode::UNPROCESSABLE_ENTITY);+ assert_eq!(+ json_body(unreadable).await,+ json!({+ "error": "The page could not be read: Failed to retrieve content",+ "code": "fetch_failed"+ })+ );++ let invalid = app+ .oneshot(post(+ "/web/fetch",+ Some("valid"),+ json!({ "url": "file:///etc/passwd" }),+ ))+ .await+ .unwrap();+ assert_eq!(invalid.status(), StatusCode::BAD_REQUEST);+ assert_eq!(json_body(invalid).await["code"], "invalid_request");+}diff --git a/crates/web_search/src/inbound/toolset.rs b/crates/web_search/src/inbound/toolset.rsnew file mode 100644index 0000000000..9360618a9b--- /dev/null+++ b/crates/web_search/src/inbound/toolset.rs@@ -0,0 +1,99 @@+//! `WebSearch` and `WebFetch` agent tools, for every model and host.++use std::sync::Arc;++use ai_toolset::{+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,+ ToolCallError, ToolResult,+};+use async_trait::async_trait;+use macro_uuid::Uuid;++use crate::domain::models::{+ WebFetch, WebFetchResponse, WebSearch, WebSearchError, WebSearchResponse,+};+use crate::domain::service::{WebCaller, WebSearchService};++#[cfg(test)]+mod test;++/// The use case plus the entity the calling turn belongs to.+#[derive(Clone)]+pub struct WebToolContext {+ /// Web search, admitted and metered to the requesting user.+ pub service: Arc<WebSearchService>,+ /// Entity usage is attributed to (the chat or agent session), if any.+ pub entity: Option<Uuid>,+}++/// The web tools.+pub fn web_toolset() -> AsyncToolCollection<WebToolContext> {+ AsyncToolCollection::new()+ .add_tool::<WebSearch, WebToolContext>()+ .add_tool::<WebFetch, WebToolContext>()+}++impl ToolAnnotated for WebSearch {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Search the web")+ .with_open_world()+ .without_idempotent();+}++impl ToolAnnotated for WebFetch {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Fetch a web page")+ .with_open_world()+ .without_idempotent();+}++fn tool_error(error: WebSearchError) -> ToolCallError {+ ToolCallError {+ description: format!("{}: {error}", error.code()),+ internal_error: error.into(),+ }+}++#[async_trait]+impl AsyncTool<WebToolContext> for WebSearch {+ type Output = WebSearchResponse;++ async fn call(+ &self,+ service_context: ServiceContext<WebToolContext>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ service_context+ .service+ .search(+ WebCaller {+ user: request_context.user_id,+ entity: service_context.entity,+ },+ self.clone(),+ )+ .await+ .map_err(tool_error)+ }+}++#[async_trait]+impl AsyncTool<WebToolContext> for WebFetch {+ type Output = WebFetchResponse;++ async fn call(+ &self,+ service_context: ServiceContext<WebToolContext>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ service_context+ .service+ .fetch(+ WebCaller {+ user: request_context.user_id,+ entity: service_context.entity,+ },+ self.clone(),+ )+ .await+ .map_err(tool_error)+ }+}diff --git a/crates/web_search/src/inbound/toolset/test.rs b/crates/web_search/src/inbound/toolset/test.rsnew file mode 100644index 0000000000..6299210d75--- /dev/null+++ b/crates/web_search/src/inbound/toolset/test.rs@@ -0,0 +1,110 @@+use std::sync::{Arc, Mutex};++use ai_billing::DisabledAiAdmissionService;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext};+use ai_usage::{UsageEvent, UsageRecorder};+use async_trait::async_trait;+use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;++use super::WebToolContext;+use crate::domain::models::{+ Billed, FetchedPage, PageRequest, ProviderError, SearchQuery, WebFetch, WebSearch,+ WebSearchResult,+};+use crate::domain::ports::SearchProvider;+use crate::domain::service::WebSearchService;++struct Unconfigured;++#[async_trait]+impl SearchProvider for Unconfigured {+ fn pricing_model(&self) -> &'static str {+ "tavily"+ }++ async fn search(&self, _: &SearchQuery) -> Result<Billed<Vec<WebSearchResult>>, ProviderError> {+ Err(ProviderError::NotConfigured("TAVILY_API_KEY"))+ }++ async fn fetch(&self, request: &PageRequest) -> Result<Billed<FetchedPage>, ProviderError> {+ Ok(Billed {+ credits: Some(1),+ value: FetchedPage {+ url: request.url.to_string(),+ title: None,+ content: "page".into(),+ },+ })+ }+}++#[derive(Default)]+struct Recorder(Mutex<Vec<UsageEvent>>);++impl UsageRecorder for Recorder {+ fn record(&self, event: UsageEvent) {+ self.0.lock().unwrap().push(event);+ }+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap()+}++#[tokio::test]+async fn fetch_is_attributed_to_the_requesting_user_and_turn_entity() {+ let recorder = Arc::new(Recorder::default());+ let entity = Uuid::new_v4();+ let context = ServiceContext(WebToolContext {+ service: Arc::new(WebSearchService::new(+ Arc::new(Unconfigured),+ Arc::new(DisabledAiAdmissionService),+ recorder.clone(),+ )),+ entity: Some(entity),+ });++ let page = WebFetch {+ url: "https://example.com/".into(),+ max_chars: None,+ }+ .call(context, RequestContext::new(user()))+ .await+ .unwrap();++ assert_eq!(page.content, "page");+ let events = recorder.0.lock().unwrap();+ assert_eq!(events[0].user, user());+ assert_eq!(events[0].entity, Some(entity));+}++#[tokio::test]+async fn a_missing_key_reaches_the_model_as_a_clear_error() {+ let context = ServiceContext(WebToolContext {+ service: Arc::new(WebSearchService::new(+ Arc::new(Unconfigured),+ Arc::new(DisabledAiAdmissionService),+ Arc::new(Recorder::default()),+ )),+ entity: None,+ });++ let error = WebSearch {+ query: "macro".into(),+ domains: None,+ exclude_domains: None,+ since: None,+ topic: None,+ max_results: None,+ include_content: None,+ }+ .call(context, RequestContext::new(user()))+ .await+ .unwrap_err();++ assert_eq!(+ error.description,+ "web_search_not_configured: web search is not configured: TAVILY_API_KEY is not set"+ );+}diff --git a/crates/web_search/src/lib.rs b/crates/web_search/src/lib.rsnew file mode 100644index 0000000000..659f941040--- /dev/null+++ b/crates/web_search/src/lib.rs@@ -0,0 +1,9 @@+//! Web search and page fetch for agents and the SDK, behind a vendor port.+//!+//! The domain admits each request against the caller's AI allowance and meters+//! the vendor's credits to them; [`outbound::tavily`] is the vendor adapter.+#![deny(missing_docs)]++pub mod domain;+pub mod inbound;+pub mod outbound;diff --git a/crates/web_search/src/outbound.rs b/crates/web_search/src/outbound.rsnew file mode 100644index 0000000000..501f8f2279--- /dev/null+++ b/crates/web_search/src/outbound.rs@@ -0,0 +1,3 @@+//! Vendor adapters.++pub mod tavily;diff --git a/crates/web_search/src/outbound/tavily.rs b/crates/web_search/src/outbound/tavily.rsnew file mode 100644index 0000000000..743b93ae82--- /dev/null+++ b/crates/web_search/src/outbound/tavily.rs@@ -0,0 +1,267 @@+//! Tavily (<https://docs.tavily.com>) search and extract adapter.+//!+//! Tavily keeps no query data by default (zero data retention). Requests use+//! basic depth: one credit per search, one per five extracted URLs.++use std::time::Duration;++use anyhow::Context;+use async_trait::async_trait;+use macro_env_var::maybe_env_var;+use reqwest::StatusCode;+use serde::{Deserialize, Serialize};++use crate::domain::models::{+ Billed, FetchedPage, PageRequest, ProviderError, SearchQuery, WebSearchResult, WebSearchTopic,+};+use crate::domain::ports::SearchProvider;++#[cfg(test)]+mod test;++maybe_env_var! {+ /// Tavily API key. Without it every web search and fetch fails with a+ /// "not configured" error. Never logged or sent to clients.+ pub struct TavilyApiKey;+}++const API_BASE: &str = "https://api.tavily.com";+const KEY_NAME: &str = "TAVILY_API_KEY";+/// Extract's own server-side timeout is 10 s at basic depth; leave headroom.+const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);++/// Tavily search and extract over HTTPS.+#[derive(Clone)]+pub struct TavilyClient {+ http: reqwest::Client,+ base_url: String,+ api_key: Option<String>,+}++impl TavilyClient {+ /// A client for `api_key`, or one whose calls fail as not configured+ /// when the key is unset or blank.+ pub fn new(api_key: &TavilyApiKey) -> Self {+ Self::with_base_url(api_key, API_BASE)+ }++ /// Read `TAVILY_API_KEY`, logging an error at startup when it is missing.+ pub fn from_env() -> Self {+ let api_key = TavilyApiKey::new().unwrap_or(TavilyApiKey::Unset);+ let client = Self::new(&api_key);+ if client.api_key.is_none() {+ tracing::error!("{KEY_NAME} is not set; WebSearch and WebFetch will fail");+ }+ client+ }++ /// A client against another base URL, for tests.+ pub fn with_base_url(api_key: &TavilyApiKey, base_url: &str) -> Self {+ Self {+ http: reqwest::Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .build()+ .expect("static reqwest configuration is valid"),+ base_url: base_url.trim_end_matches('/').to_owned(),+ api_key: api_key+ .value()+ .map(str::trim)+ .filter(|key| !key.is_empty())+ .map(str::to_owned),+ }+ }++ async fn post<Request: Serialize, Response: for<'de> Deserialize<'de>>(+ &self,+ path: &str,+ body: &Request,+ ) -> Result<Response, ProviderError> {+ let api_key = self+ .api_key+ .as_deref()+ .ok_or(ProviderError::NotConfigured(KEY_NAME))?;+ let response = self+ .http+ .post(format!("{}{path}", self.base_url))+ .bearer_auth(api_key)+ .json(body)+ .send()+ .await+ .context("tavily request failed")?;+ let status = response.status();+ // 432/433 are Tavily's plan and pay-as-you-go limits.+ if status == StatusCode::TOO_MANY_REQUESTS || matches!(status.as_u16(), 432 | 433) {+ return Err(ProviderError::Throttled(status.as_u16()));+ }+ if !status.is_success() {+ return Err(ProviderError::Failed(anyhow::anyhow!(+ "tavily {path} returned HTTP {status}"+ )));+ }+ Ok(response+ .json()+ .await+ .with_context(|| format!("tavily {path} returned an unexpected body"))?)+ }+}++#[async_trait]+impl SearchProvider for TavilyClient {+ fn pricing_model(&self) -> &'static str {+ "tavily"+ }++ async fn search(+ &self,+ query: &SearchQuery,+ ) -> Result<Billed<Vec<WebSearchResult>>, ProviderError> {+ let response: SearchResponse = self.post("/search", &SearchRequest::from(query)).await?;+ Ok(Billed {+ credits: response.usage.map(|usage| usage.credits),+ value: response+ .results+ .into_iter()+ .map(|result| WebSearchResult {+ title: result.title,+ url: result.url,+ snippet: result.content,+ published_at: result.published_date,+ content: result.raw_content,+ })+ .collect(),+ })+ }++ async fn fetch(&self, request: &PageRequest) -> Result<Billed<FetchedPage>, ProviderError> {+ let response: ExtractResponse = self+ .post(+ "/extract",+ &ExtractRequest {+ urls: [request.url.as_str()],+ extract_depth: "basic",+ format: "markdown",+ include_usage: true,+ },+ )+ .await?;+ let credits = response.usage.map(|usage| usage.credits);+ match response.results.into_iter().next() {+ Some(page) => Ok(Billed {+ credits,+ value: FetchedPage {+ url: page.url,+ title: None,+ content: page.raw_content,+ },+ }),+ None => Err(ProviderError::PageUnavailable(+ response+ .failed_results+ .into_iter()+ .next()+ .map(|failure| failure.error)+ .unwrap_or_else(|| "no content was returned".to_owned()),+ )),+ }+ }+}++#[derive(Debug, Serialize, PartialEq)]+struct SearchRequest<'a> {+ query: &'a str,+ topic: Topic,+ search_depth: &'static str,+ max_results: u8,+ #[serde(skip_serializing_if = "<[String]>::is_empty")]+ include_domains: &'a [String],+ #[serde(skip_serializing_if = "<[String]>::is_empty")]+ exclude_domains: &'a [String],+ #[serde(skip_serializing_if = "Option::is_none")]+ start_date: Option<String>,+ include_published_date: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ include_raw_content: Option<&'static str>,+ include_answer: bool,+ include_images: bool,+ include_usage: bool,+}++#[derive(Debug, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+enum Topic {+ General,+ News,+}++impl<'a> From<&'a SearchQuery> for SearchRequest<'a> {+ fn from(query: &'a SearchQuery) -> Self {+ Self {+ query: &query.query,+ topic: match query.topic {+ WebSearchTopic::General => Topic::General,+ WebSearchTopic::News => Topic::News,+ },+ search_depth: "basic",+ max_results: query.max_results,+ include_domains: &query.domains,+ exclude_domains: &query.exclude_domains,+ start_date: query.since.map(|date| date.format("%Y-%m-%d").to_string()),+ include_published_date: true,+ include_raw_content: query.include_content.then_some("markdown"),+ include_answer: false,+ include_images: false,+ include_usage: true,+ }+ }+}++#[derive(Debug, Deserialize)]+struct SearchResponse {+ results: Vec<SearchResult>,+ #[serde(default)]+ usage: Option<Usage>,+}++#[derive(Debug, Deserialize)]+struct SearchResult {+ title: String,+ url: String,+ content: String,+ #[serde(default)]+ raw_content: Option<String>,+ #[serde(default)]+ published_date: Option<String>,+}++#[derive(Debug, Serialize)]+struct ExtractRequest<'a> {+ urls: [&'a str; 1],+ extract_depth: &'static str,+ format: &'static str,+ include_usage: bool,+}++#[derive(Debug, Deserialize)]+struct ExtractResponse {+ results: Vec<ExtractResult>,+ #[serde(default)]+ failed_results: Vec<ExtractFailure>,+ #[serde(default)]+ usage: Option<Usage>,+}++#[derive(Debug, Deserialize)]+struct ExtractResult {+ url: String,+ raw_content: String,+}++#[derive(Debug, Deserialize)]+struct ExtractFailure {+ error: String,+}++#[derive(Debug, Deserialize)]+struct Usage {+ credits: u64,+}diff --git a/crates/web_search/src/outbound/tavily/fixtures/extract.json b/crates/web_search/src/outbound/tavily/fixtures/extract.jsonnew file mode 100644index 0000000000..2696a57d3f--- /dev/null+++ b/crates/web_search/src/outbound/tavily/fixtures/extract.json@@ -0,0 +1,13 @@+{+ "results": [+ {+ "url": "https://tokio.rs/blog/2025-10-tokio-1-48",+ "raw_content": "# Announcing Tokio 1.48\n\nTokio 1.48 ships a faster multi-threaded scheduler.",+ "images": []+ }+ ],+ "failed_results": [],+ "response_time": 0.48,+ "usage": { "credits": 1 },+ "request_id": "0c7f6a8e-6d2a-4c1e-8f5b-2b9d1e7a3c55"+}diff --git a/crates/web_search/src/outbound/tavily/fixtures/extract_failed.json b/crates/web_search/src/outbound/tavily/fixtures/extract_failed.jsonnew file mode 100644index 0000000000..6006627799--- /dev/null+++ b/crates/web_search/src/outbound/tavily/fixtures/extract_failed.json@@ -0,0 +1,12 @@+{+ "results": [],+ "failed_results": [+ {+ "url": "https://example.com/members-only",+ "error": "Failed to retrieve content"+ }+ ],+ "response_time": 0.31,+ "usage": { "credits": 0 },+ "request_id": "5a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d"+}diff --git a/crates/web_search/src/outbound/tavily/fixtures/search.json b/crates/web_search/src/outbound/tavily/fixtures/search.jsonnew file mode 100644index 0000000000..ac699ab66a--- /dev/null+++ b/crates/web_search/src/outbound/tavily/fixtures/search.json@@ -0,0 +1,26 @@+{+ "query": "rust async runtime comparison",+ "follow_up_questions": null,+ "answer": null,+ "images": [],+ "results": [+ {+ "url": "https://tokio.rs/blog/2025-10-tokio-1-48",+ "title": "Announcing Tokio 1.48",+ "content": "Tokio 1.48 ships a faster multi-threaded scheduler and stabilises task dumps.",+ "score": 0.91,+ "raw_content": "# Announcing Tokio 1.48\n\nTokio 1.48 ships a faster scheduler.",+ "published_date": "Tue, 14 Oct 2025 09:00:00 GMT"+ },+ {+ "url": "https://example.com/async-runtimes",+ "title": "Comparing Rust async runtimes",+ "content": "Tokio, smol and glommio take different approaches to scheduling.",+ "score": 0.77,+ "raw_content": null+ }+ ],+ "response_time": 1.21,+ "usage": { "credits": 1 },+ "request_id": "8b3e43c3-1f0d-4b5e-9a37-5a8d3e1b4c11"+}diff --git a/crates/web_search/src/outbound/tavily/test.rs b/crates/web_search/src/outbound/tavily/test.rsnew file mode 100644index 0000000000..225fc0ee3f--- /dev/null+++ b/crates/web_search/src/outbound/tavily/test.rs@@ -0,0 +1,234 @@+use chrono::NaiveDate;+use serde_json::json;+use wiremock::matchers::{body_json, header, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++use super::{TavilyApiKey, TavilyClient};+use crate::domain::models::{+ Billed, FetchedPage, PageRequest, ProviderError, SearchQuery, WebSearchResult, WebSearchTopic,+};+use crate::domain::ports::SearchProvider;++const SEARCH: &str = include_str!("fixtures/search.json");+const EXTRACT: &str = include_str!("fixtures/extract.json");+const EXTRACT_FAILED: &str = include_str!("fixtures/extract_failed.json");++fn fixture(body: &str) -> ResponseTemplate {+ ResponseTemplate::new(200).set_body_raw(body.to_owned(), "application/json")+}++#[tokio::test]+async fn search_sends_typed_filters_and_maps_results() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/search"))+ .and(header("authorization", "Bearer tvly-test"))+ .and(body_json(json!({+ "query": "rust async runtime comparison",+ "topic": "news",+ "search_depth": "basic",+ "max_results": 2,+ "include_domains": ["tokio.rs", "example.com"],+ "exclude_domains": ["reddit.com"],+ "start_date": "2025-10-01",+ "include_published_date": true,+ "include_raw_content": "markdown",+ "include_answer": false,+ "include_images": false,+ "include_usage": true+ })))+ .respond_with(fixture(SEARCH))+ .expect(1)+ .mount(&server)+ .await;+ let client =+ TavilyClient::with_base_url(&TavilyApiKey::new_testing("tvly-test"), &server.uri());++ let billed = client+ .search(&SearchQuery {+ query: "rust async runtime comparison".into(),+ domains: vec!["tokio.rs".into(), "example.com".into()],+ exclude_domains: vec!["reddit.com".into()],+ since: Some(NaiveDate::from_ymd_opt(2025, 10, 1).unwrap()),+ topic: WebSearchTopic::News,+ max_results: 2,+ include_content: true,+ })+ .await+ .unwrap();++ assert_eq!(+ billed,+ Billed {+ credits: Some(1),+ value: vec![+ WebSearchResult {+ title: "Announcing Tokio 1.48".into(),+ url: "https://tokio.rs/blog/2025-10-tokio-1-48".into(),+ snippet: "Tokio 1.48 ships a faster multi-threaded scheduler and stabilises task dumps.".into(),+ published_at: Some("Tue, 14 Oct 2025 09:00:00 GMT".into()),+ content: Some(+ "# Announcing Tokio 1.48\n\nTokio 1.48 ships a faster scheduler.".into()+ ),+ },+ WebSearchResult {+ title: "Comparing Rust async runtimes".into(),+ url: "https://example.com/async-runtimes".into(),+ snippet: "Tokio, smol and glommio take different approaches to scheduling."+ .into(),+ published_at: None,+ content: None,+ },+ ],+ }+ );+}++#[tokio::test]+async fn search_omits_unset_filters() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/search"))+ .and(body_json(json!({+ "query": "macro",+ "topic": "general",+ "search_depth": "basic",+ "max_results": 5,+ "include_published_date": true,+ "include_answer": false,+ "include_images": false,+ "include_usage": true+ })))+ .respond_with(fixture(SEARCH))+ .expect(1)+ .mount(&server)+ .await;+ let client =+ TavilyClient::with_base_url(&TavilyApiKey::new_testing("tvly-test"), &server.uri());++ client+ .search(&SearchQuery {+ query: "macro".into(),+ domains: vec![],+ exclude_domains: vec![],+ since: None,+ topic: WebSearchTopic::General,+ max_results: 5,+ include_content: false,+ })+ .await+ .unwrap();+}++#[tokio::test]+async fn fetch_extracts_markdown() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/extract"))+ .and(header("authorization", "Bearer tvly-test"))+ .and(body_json(json!({+ "urls": ["https://tokio.rs/blog/2025-10-tokio-1-48"],+ "extract_depth": "basic",+ "format": "markdown",+ "include_usage": true+ })))+ .respond_with(fixture(EXTRACT))+ .expect(1)+ .mount(&server)+ .await;+ let client =+ TavilyClient::with_base_url(&TavilyApiKey::new_testing("tvly-test"), &server.uri());++ let billed = client+ .fetch(&PageRequest {+ url: "https://tokio.rs/blog/2025-10-tokio-1-48".parse().unwrap(),+ })+ .await+ .unwrap();++ assert_eq!(+ billed,+ Billed {+ credits: Some(1),+ value: FetchedPage {+ url: "https://tokio.rs/blog/2025-10-tokio-1-48".into(),+ title: None,+ content:+ "# Announcing Tokio 1.48\n\nTokio 1.48 ships a faster multi-threaded scheduler."+ .into(),+ },+ }+ );+}++#[tokio::test]+async fn fetch_reports_the_providers_failure_reason() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/extract"))+ .respond_with(fixture(EXTRACT_FAILED))+ .mount(&server)+ .await;+ let client =+ TavilyClient::with_base_url(&TavilyApiKey::new_testing("tvly-test"), &server.uri());++ let error = client+ .fetch(&PageRequest {+ url: "https://example.com/members-only".parse().unwrap(),+ })+ .await+ .unwrap_err();++ assert!(+ matches!(&error, ProviderError::PageUnavailable(reason) if reason == "Failed to retrieve content"),+ "{error:?}"+ );+}++#[tokio::test]+async fn plan_limits_and_rate_limits_are_throttling() {+ for status in [429, 432, 433] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(status))+ .mount(&server)+ .await;+ let client =+ TavilyClient::with_base_url(&TavilyApiKey::new_testing("tvly-test"), &server.uri());++ let error = client+ .fetch(&PageRequest {+ url: "https://example.com/".parse().unwrap(),+ })+ .await+ .unwrap_err();++ assert!(+ matches!(error, ProviderError::Throttled(code) if code == status),+ "{status}: {error:?}"+ );+ }+}++#[tokio::test]+async fn a_missing_key_fails_without_calling_tavily() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(fixture(SEARCH))+ .expect(0)+ .mount(&server)+ .await;+ let client = TavilyClient::with_base_url(&TavilyApiKey::new_testing(" "), &server.uri());++ let error = client+ .fetch(&PageRequest {+ url: "https://example.com/".parse().unwrap(),+ })+ .await+ .unwrap_err();++ assert_eq!(+ error.to_string(),+ "web search is not configured: TAVILY_API_KEY is not set"+ );+}diff --git a/docs/runbooks/ai-billing-rollout.md b/docs/runbooks/ai-billing-rollout.mdindex 7d6e758140..19fd2a96d4 100644--- a/docs/runbooks/ai-billing-rollout.md+++ b/docs/runbooks/ai-billing-rollout.md@@ -95,7 +95,7 @@ regressions, not live-provider or deployment verification.| DCS chat, dynamic/structured completion, rename | Per-operation `UsageContext` from existing authenticated handlers; `services/agent_harness_service/src/cognition/main.rs` wraps its settling recorder | Rig HTTP attempts → journal, including failed parsing/retries; legacy final aggregates unchanged | `agent` metering/structured tests, DCS package tests; financial activation off || Subagent in any common-context host | `crates/ai_tools/src/subagent.rs` replaces shared-context user with `RequestContext.user_id`, retains parent feature/entity | `agent::complete` binds a fresh or matching inherited scope → journal; no shared mutable user | `ai_tools` subagent isolation; `agent` scope/independent recorder tests. Shared system identity is not an authenticated payer || MCP native Anthropic tools and subagent | `AuthenticatedToolService` builds `RequestContext` from authenticated HTTP extensions; `services/agent_harness_service/src/public_mcp/context.rs` injects the configured recorder; `ToolServiceContext::FromRef` supplies inherited feature/entity and recorder | Independent Anthropic HTTP attempts and subagent attempts → journal, not merely successful tool aggregates; default feature remains Chat | Anthropic authenticated attribution/malformed-result/failure tests; MCP auth tests. MCP client's own model and remote MCP servers are not covered |-| Anthropic WebSearch, WebFetch, BashCodeExecution, TextEditorCodeExecution in all common hosts | Manual per-operation `FromRef<ToolServiceContext>` copies recorder + feature/entity; tool call always uses authenticated `RequestContext.user_id` | One journal attempt per independent native Messages HTTP execution. Counters recorded before SDK/result parsing, including non-2xx evidence; cancellation retains execution/evidence task. No separate tool fees | `anthropic --features toolset` tests. Native client has no application retry loop; any future retries must create fresh attempt IDs. Server-tool-specific non-token fees are intentionally not priced |+| Anthropic BashCodeExecution, TextEditorCodeExecution in all common hosts | Manual per-operation `FromRef<ToolServiceContext>` copies recorder + feature/entity; tool call always uses authenticated `RequestContext.user_id` | One journal attempt per independent native Messages HTTP execution. Counters recorded before SDK/result parsing, including non-2xx evidence; cancellation retains execution/evidence task. No separate tool fees | `anthropic --features toolset` tests. Native client has no application retry loop; any future retries must create fresh attempt IDs. Server-tool-specific non-token fees are intentionally not priced || In-memory harness sessions | `services/agent_harness_service/src/main.rs` settling recorder passed into the common context → `RigTurnEngine`; trusted `TurnRequest.owner`, AgentSession feature | Captured scope carried into spawned turn; AgentLoop binds immutable owner scope; Rig attempts → journal, final analytics retained | `agent` spawned scope/cancellation tests; `agent_inmem` package tests. Non-user owners remain rejected by existing behavior || Harness session naming | The harness's settling recorder supplied to `HaikuAgentSessionNameGenerator` in harness `main.rs`; session owner, ChatRename feature/entity | One-shot model attempts → journal (feature classification unchanged) | Existing name-generator/host tests plus shared completion tests; not covered merely by common-context injection || Harness repository selection | The harness's settling recorder passed to `CursorContainerManager` in harness `main.rs`; repository chooser's trusted owner, AgentRepositoryChoice feature | Rust selection completion attempts → journal | Shared completion tests and host tests. Does not cover Cursor's external agent runtime |diff --git a/docs/runbooks/ai-quota-enforcement.md b/docs/runbooks/ai-quota-enforcement.mdindex f25883b15a..90b19b6764 100644--- a/docs/runbooks/ai-quota-enforcement.md+++ b/docs/runbooks/ai-quota-enforcement.md@@ -350,7 +350,8 @@ requests settlement). Admission itself never records usage or calls settlement.| Structured completion / DynamicCompletionsApi | [completion handler](../../services/agent_harness_service/src/cognition/api/structured_completion.rs) | DCS main, same recorder across both phases | [both phases and OpenAPI](../../services/agent_harness_service/src/cognition/api/structured_completion/test.rs) || Chat naming / ChatRename | [chat renamer](../../services/agent_harness_service/src/cognition/service/chat_renamer.rs) | DCS main, same recorder | [safe naming skip](../../services/agent_harness_service/src/cognition/service/chat_renamer/test.rs) || Direct subagent / inherited feature | [operations service](../../crates/ai_tools/src/ai_operations.rs), [subagent](../../crates/ai_tools/src/subagent.rs) | Host common context: T, DCS main, or [MCP context](../../services/agent_harness_service/src/public_mcp/context.rs) using `pg_settling_recorder` | [zero provider calls](../../crates/ai_tools/src/ai_operations/test.rs), [concurrent caller isolation](../../crates/ai_tools/src/subagent/test.rs) |-| Native Anthropic WebSearch/WebFetch/code tools / inherited feature | [invoke_server_tool](../../crates/anthropic/src/toolset.rs) before both provider branches | Same common contexts via `FromRef`; observation only, **no legacy aggregate producer** | [tool attribution/refusal](../../crates/anthropic/src/toolset/test.rs) |+| Native Anthropic code tools / inherited feature | [invoke_server_tool](../../crates/anthropic/src/toolset.rs) before both provider branches | Same common contexts via `FromRef`; observation only, **no legacy aggregate producer** | [tool attribution/refusal](../../crates/anthropic/src/toolset/test.rs) |+| `WebSearch`/`WebFetch` tools and cognition `POST /web/search`, `/web/fetch` / `web_search` | [WebSearchService](../../crates/web_search/src/domain/service.rs) admits `web_search` before the Tavily call | `UsageRecorder` records Tavily's reported credits (`provider_credits`, pricing id `tavily`), counted when enforcement is on | [service and router tests](../../crates/web_search/src/domain/service/test.rs) || AI document editing / AiEditing | [document orchestration](../../crates/documents/src/domain/ai_editing.rs) after verified edit receipt | Common context's recorder, existing per-model worker usage | [domain](../../crates/documents/src/domain/ai_editing/test.rs), [direct tool and permission precedence](../../crates/documents/src/inbound/toolset/edit_document/test.rs) || Notion page imports / Import | [import admission](../../crates/import/src/domain/service/admission.rs), [execution/rechecks](../../crates/import/src/domain/service.rs) | DCS main, wrapped recorder | [delayed/deterministic cases](../../crates/import/src/domain/service/test/admission.rs), [HTTP](../../crates/import/src/inbound/axum_router/test.rs) || Channel responder / ChannelBot | [bot service](../../crates/channel_bots/src/domain/service.rs) | [DSS main](../../services/document_storage_service/src/main.rs), common context T | [response refusal](../../crates/channel_bots/src/domain/service/tests.rs) |diff --git a/infra/stacks/document-cognition-service/Pulumi.dev.yaml b/infra/stacks/document-cognition-service/Pulumi.dev.yamlindex 69738b7399..3e51e23052 100644--- a/infra/stacks/document-cognition-service/Pulumi.dev.yaml+++ b/infra/stacks/document-cognition-service/Pulumi.dev.yaml@@ -14,6 +14,7 @@ config:document-cognition:open-router-api-key: open-router-api-key-dev-v2document-cognition:sync_service_auth_key: sync-service-key-devdocument-cognition:perplexity-api-key: perplexity-api-key+ document-cognition:tavily-api-key: tavily-api-keydocument-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-devdocument-cognition:macro_db_proxy_secret_key: macrodb-rds-proxy-devdatadog:validate: "false"diff --git a/infra/stacks/document-cognition-service/Pulumi.prod.yaml b/infra/stacks/document-cognition-service/Pulumi.prod.yamlindex afca9dfc5f..de2347f31e 100644--- a/infra/stacks/document-cognition-service/Pulumi.prod.yaml+++ b/infra/stacks/document-cognition-service/Pulumi.prod.yaml@@ -14,5 +14,6 @@ config:document-cognition:open-router-api-key: open-router-api-key-prod-v2document-cognition:sync_service_auth_key: sync-service-key-proddocument-cognition:perplexity-api-key: perplexity-api-key+ document-cognition:tavily-api-key: tavily-api-keydocument-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-proddocument-cognition:macro_db_proxy_secret_key: macrodb-rds-proxy-proddiff --git a/packages/code-mode-sdk/scripts/catalog.ts b/packages/code-mode-sdk/scripts/catalog.tsindex 4c5cbfb711..f86186749d 100644--- a/packages/code-mode-sdk/scripts/catalog.ts+++ b/packages/code-mode-sdk/scripts/catalog.ts@@ -12,6 +12,7 @@ export const entityDirectories: readonly string[] = ['meetings','routines','unfurls',+ 'web','ai','bots','calendar',diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.mdindex 1f1abd0da5..ce7fc117f1 100644--- a/packages/sdk/AGENTS.md+++ b/packages/sdk/AGENTS.md@@ -33,6 +33,10 @@ enforced by the ordinary backend APIs.`POST /images/generate`, admitted against the user's AI allowance) returns asized `GeneratedImage`; `StaticImage` handles attach to `channel.send(text,{ images })` and `thread.reply` as `static/image` attachments.+- `src/entities/web/`: `macro.web.search()` / `macro.web.fetch()` (cognition+ `POST /web/search`, `/web/fetch`, Tavily via `crates/web_search`), admitted and+ metered against the user's AI allowance; code mode hides the `WebSearch` /+ `WebFetch` tools in their favour.- `services.ts`, `openapi-ts.config.ts`: generated service contract inputs.## Boundariesdiff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.tsindex ba0e53b0de..db585ed0ea 100644--- a/packages/sdk/generated/cognition/index.ts+++ b/packages/sdk/generated/cognition/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponse, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponse, CancelWorkspaceHandlerResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectData, CompletePipedreamMcpConnectError, CompletePipedreamMcpConnectErrors, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectResponse, CompletePipedreamMcpConnectResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DatabaseQueryAnswer, DatabaseQueryChart, DatabaseQueryDisplayMode, DatabaseQueryRequest, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissedPrompts, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponse, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponse, DismissPromptHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, FreeTierModel, GenerateDatabaseQueryData, GenerateDatabaseQueryError, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponse, GenerateDatabaseQueryResponses, GenerateImageAspectRatio, GenerateImageData, GenerateImageError, GenerateImageErrorBody, GenerateImageErrors, GenerateImageReference, GenerateImageRequest, GenerateImageResponse, GenerateImageResponse2, GenerateImageResponses, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportKind, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysError, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponse, ListPipedreamMcpOverlaysResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionAlreadyImported, NotionDecision, NotionDocMeta, NotionImporter, NotionImportReport, NotionPlanItem, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponse, NotionReportHandlerResponses, NotionReportItem, NotionTaskFields, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectCompleteRequest, PipedreamConnectionResponse, PipedreamOverlayResponse, PipedreamProviderResponse, PipedreamRecoverRequest, PipedreamTokenRequest, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionError, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponse, RecoverPipedreamMcpConnectionResponses, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, ScanCounts, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId, WorkspaceReportHandlerData, WorkspaceReportHandlerResponse, WorkspaceReportHandlerResponses } from './types.gen';+export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponse, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponse, CancelWorkspaceHandlerResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectData, CompletePipedreamMcpConnectError, CompletePipedreamMcpConnectErrors, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectResponse, CompletePipedreamMcpConnectResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DatabaseQueryAnswer, DatabaseQueryChart, DatabaseQueryDisplayMode, DatabaseQueryRequest, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissedPrompts, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponse, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponse, DismissPromptHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FetchWebPageData, FetchWebPageError, FetchWebPageErrors, FetchWebPageResponse, FetchWebPageResponses, FileType, FreeTierModel, GenerateDatabaseQueryData, GenerateDatabaseQueryError, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponse, GenerateDatabaseQueryResponses, GenerateImageAspectRatio, GenerateImageData, GenerateImageError, GenerateImageErrorBody, GenerateImageErrors, GenerateImageReference, GenerateImageRequest, GenerateImageResponse, GenerateImageResponse2, GenerateImageResponses, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportKind, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysError, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponse, ListPipedreamMcpOverlaysResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionAlreadyImported, NotionDecision, NotionDocMeta, NotionImporter, NotionImportReport, NotionPlanItem, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponse, NotionReportHandlerResponses, NotionReportItem, NotionTaskFields, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectCompleteRequest, PipedreamConnectionResponse, PipedreamOverlayResponse, PipedreamProviderResponse, PipedreamRecoverRequest, PipedreamTokenRequest, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionError, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponse, RecoverPipedreamMcpConnectionResponses, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, ScanCounts, SearchWebData, SearchWebError, SearchWebErrors, SearchWebResponse, SearchWebResponses, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WebErrorBody, WebFetch, WebFetchResponse, WebSearch, WebSearchResponse, WebSearchResult, WebSearchTopic, WithChatId, WorkspaceReportHandlerData, WorkspaceReportHandlerResponse, WorkspaceReportHandlerResponses } from './types.gen';diff --git a/packages/sdk/generated/cognition/sdk.gen.ts b/packages/sdk/generated/cognition/sdk.gen.tsindex cbd89fc3c9..9a75336889 100644--- a/packages/sdk/generated/cognition/sdk.gen.ts+++ b/packages/sdk/generated/cognition/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 { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectData, CompletePipedreamMcpConnectErrors, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DecisionsData, DecisionsErrors, DecisionsResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponses, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponses, GenerateDatabaseQueryData, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponses, GenerateImageData, GenerateImageErrors, GenerateImageResponses, GetBatchPreviewData, GetBatchPreviewErrors, GetBatchPreviewResponses, GetChatData, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsErrors, GetChatPermissionsResponses, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponses, GetCitationHandlerData, GetCitationHandlerErrors, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerErrors, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerErrors, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponses, ListMcpServersData, ListMcpServersErrors, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponses, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatErrors, RevertDeleteChatResponses, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponses, SendChatMessageData, SendChatMessageErrors, SendChatMessageResponses, SetPricingHandlerData, SetPricingHandlerErrors, SetPricingHandlerResponses, StartMcpAuthData, StartMcpAuthErrors, StartMcpAuthResponses, StopChatStreamData, StopChatStreamErrors, StopChatStreamResponses, StructuredCompletionData, StructuredCompletionErrors, StructuredCompletionResponses, UpdateMcpServerData, UpdateMcpServerErrors, UpdateMcpServerResponses, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponses, UpdateToolCallData, UpdateToolCallErrors, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseErrors, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionErrors, UpsertAiProjectionResponses, WorkspaceReportHandlerData, WorkspaceReportHandlerResponses } from './types.gen';+import type { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectData, CompletePipedreamMcpConnectErrors, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DecisionsData, DecisionsErrors, DecisionsResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponses, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponses, FetchWebPageData, FetchWebPageErrors, FetchWebPageResponses, GenerateDatabaseQueryData, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponses, GenerateImageData, GenerateImageErrors, GenerateImageResponses, GetBatchPreviewData, GetBatchPreviewErrors, GetBatchPreviewResponses, GetChatData, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsErrors, GetChatPermissionsResponses, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponses, GetCitationHandlerData, GetCitationHandlerErrors, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerErrors, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerErrors, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponses, ListMcpServersData, ListMcpServersErrors, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponses, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatErrors, RevertDeleteChatResponses, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponses, SearchWebData, SearchWebErrors, SearchWebResponses, SendChatMessageData, SendChatMessageErrors, SendChatMessageResponses, SetPricingHandlerData, SetPricingHandlerErrors, SetPricingHandlerResponses, StartMcpAuthData, StartMcpAuthErrors, StartMcpAuthResponses, StopChatStreamData, StopChatStreamErrors, StopChatStreamResponses, StructuredCompletionData, StructuredCompletionErrors, StructuredCompletionResponses, UpdateMcpServerData, UpdateMcpServerErrors, UpdateMcpServerResponses, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponses, UpdateToolCallData, UpdateToolCallErrors, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseErrors, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionErrors, UpsertAiProjectionResponses, WorkspaceReportHandlerData, WorkspaceReportHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -653,4 +653,32 @@ export class Sdk extends HeyApiClient {}});}++ /**+ * Read one public web page as Markdown. Charged to the acting user's AI allowance.+ */+ public fetchWebPage<ThrowOnError extends boolean = false>(options: Options<FetchWebPageData, ThrowOnError>): RequestResult<FetchWebPageResponses, FetchWebPageErrors, ThrowOnError> {+ return (options.client ?? this.client).post<FetchWebPageResponses, FetchWebPageErrors, ThrowOnError>({+ url: '/web/fetch',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Search the public web. Charged to the acting user's AI allowance.+ */+ public searchWeb<ThrowOnError extends boolean = false>(options: Options<SearchWebData, ThrowOnError>): RequestResult<SearchWebResponses, SearchWebErrors, ThrowOnError> {+ return (options.client ?? this.client).post<SearchWebResponses, SearchWebErrors, ThrowOnError>({+ url: '/web/search',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }}diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.tsindex 7ac1f6721d..4e3b4662bb 100644--- a/packages/sdk/generated/cognition/types.gen.ts+++ b/packages/sdk/generated/cognition/types.gen.ts@@ -27,7 +27,7 @@ export type AddServerRequest = {* Everything we use AI for. The wire / DB form of each variant is its* `snake_case` name.*/-export type AiFeature = 'chat' | 'memory' | 'automation' | 'dynamic_completions_api' | 'chat_rename' | 'call_summary' | 'channel_bot' | 'ai_projection' | 'ai_editing' | 'import' | 'agent_session' | 'agent_repository_choice' | 'agent_mode_choice' | 'dictation' | 'image_generation' | 'email_focus';+export type AiFeature = 'chat' | 'memory' | 'automation' | 'dynamic_completions_api' | 'chat_rename' | 'call_summary' | 'channel_bot' | 'ai_projection' | 'ai_editing' | 'import' | 'agent_session' | 'agent_repository_choice' | 'agent_mode_choice' | 'dictation' | 'image_generation' | 'email_focus' | 'web_search';/*** A structured part within an assistant message.@@ -1635,27 +1635,31 @@ export type PipedreamUpdateRequest = {*/export type Price = {/**- * Price per audio minute (USD), absent for token billing.+ * Price per audio minute (USD), absent for token and credit billing.*/price_per_audio_minute?: number | null;/*** Price per million cache-read input tokens (USD), absent when the model- * has no published rate and for audio billing.+ * has no published rate and for audio and credit billing.*/price_per_million_cache_read?: number | null;/*** Price per million cache-write input tokens (USD), absent when the model- * has no published rate and for audio billing.+ * has no published rate and for audio and credit billing.*/price_per_million_cache_write?: number | null;/**- * Price per million input tokens (USD); zero for audio billing.+ * Price per million input tokens (USD); zero for audio and credit billing.*/price_per_million_in: number;/**- * Price per million output tokens (USD); zero for audio billing.+ * Price per million output tokens (USD); zero for audio and credit billing.*/price_per_million_out: number;+ /**+ * Price per vendor credit (USD), absent for token and audio billing.+ */+ price_per_provider_credit?: number | null;/*** Total cost (USD).*/@@ -1870,6 +1874,10 @@ export type SetPricingRequest = {* New price per million output tokens (USD). Required for token pricing.*/price_per_mil_out?: number | null;+ /**+ * Price per vendor credit (USD), or null unless the model bills in credits.+ */+ price_per_provider_credit?: number | null;};export type SharePermissionV2 = {@@ -2211,15 +2219,15 @@ export type UpsertProjectionRequest = {*/export type Usage = {/**- * Audio duration in seconds, absent for token billing.+ * Audio duration in seconds, absent for token and credit billing.*/audio_seconds?: number | null;/**- * Input tokens read from a prompt cache; zero for audio billing.+ * Input tokens read from a prompt cache; zero for audio and credit billing.*/cache_read_input_tokens: number;/**- * Input tokens written to a prompt cache; zero for audio billing.+ * Input tokens written to a prompt cache; zero for audio and credit billing.*/cache_write_input_tokens: number;/**@@ -2227,7 +2235,7 @@ export type Usage = {*/created_at: string;/**- * Uncached input tokens; zero for audio billing.+ * Uncached input tokens; zero for audio and credit billing.*/input_tokens: number;/**@@ -2235,10 +2243,14 @@ export type Usage = {*/model: string;/**- * Output tokens; zero for audio billing.+ * Output tokens; zero for audio and credit billing.*/output_tokens: number;price?: null | Price;+ /**+ * Vendor credits consumed, absent for token and audio billing.+ */+ provider_credits?: number | null;};/**@@ -2324,6 +2336,128 @@ export type WebCitation = {url: string;};+/**+ * Machine-readable failure of a web request.+ */+export type WebErrorBody = {+ /**+ * Stable failure code.+ */+ code: string;+ /**+ * Explanation without provider diagnostics.+ */+ error: string;+};++/**+ * Read one public web page.+ */+export type WebFetch = {+ /**+ * Most characters of page text to return, 1 to 100,000 (default 20,000).+ */+ maxChars?: number | null;+ /**+ * The `http` or `https` URL of the page.+ */+ url: string;+};++/**+ * The text of a fetched page.+ */+export type WebFetchResponse = {+ /**+ * The page text as Markdown, cut to `maxChars`.+ */+ content: string;+ /**+ * The page title, when the provider reports one.+ */+ title?: string | null;+ /**+ * Whether `content` was cut to `maxChars`.+ */+ truncated: boolean;+ /**+ * The URL that was read.+ */+ url: string;+};++/**+ * Search the public web.+ */+export type WebSearch = {+ /**+ * Only return pages from these domains, e.g. `["docs.rs", "github.com"]`.+ */+ domains?: Array<string> | null;+ /**+ * Never return pages from these domains.+ */+ excludeDomains?: Array<string> | null;+ /**+ * Also return each page's text as Markdown (up to 8,000 characters per result).+ */+ includeContent?: boolean | null;+ /**+ * How many results to return, 1 to 20 (default 5).+ */+ maxResults?: number | null;+ /**+ * What to search for, in natural language or keywords (at most 400 characters).+ */+ query: string;+ /**+ * Only return pages published on or after this date (`YYYY-MM-DD`).+ */+ since?: string | null;+ topic?: null | WebSearchTopic;+};++/**+ * The pages a search found, best match first.+ */+export type WebSearchResponse = {+ /**+ * Results, best match first. Empty when nothing matched.+ */+ results: Array<WebSearchResult>;+};++/**+ * One page a search found.+ */+export type WebSearchResult = {+ /**+ * The page text as Markdown, when `includeContent` was set.+ */+ content?: string | null;+ /**+ * When the page was published, as the search provider reports it.+ */+ publishedAt?: string | null;+ /**+ * The part of the page most relevant to the query.+ */+ snippet: string;+ /**+ * The page title.+ */+ title: string;+ /**+ * The page URL; cite it when you use the result.+ */+ url: string;+};++/**+ * The kind of results a search favours.+ */+export type WebSearchTopic = 'general' | 'news';+export type WithChatId = {chat_id: string;};@@ -3776,3 +3910,97 @@ export type StructuredCompletionResponses = {};export type StructuredCompletionResponse2 = StructuredCompletionResponses[keyof StructuredCompletionResponses];++export type FetchWebPageData = {+ body: WebFetch;+ path?: never;+ query?: never;+ url: '/web/fetch';+};++export type FetchWebPageErrors = {+ /**+ * Invalid URL or length+ */+ 400: WebErrorBody;+ /**+ * Unauthorized+ */+ 401: unknown;+ /**+ * AI allowance exhausted+ */+ 402: WebErrorBody;+ /**+ * The page could not be read+ */+ 422: WebErrorBody;+ /**+ * Per-user hourly rate limit exceeded+ */+ 429: unknown;+ /**+ * The fetch provider failed+ */+ 502: WebErrorBody;+ /**+ * Web fetch unconfigured, busy, or usage validation unavailable+ */+ 503: WebErrorBody;+};++export type FetchWebPageError = FetchWebPageErrors[keyof FetchWebPageErrors];++export type FetchWebPageResponses = {+ /**+ * The page text+ */+ 200: WebFetchResponse;+};++export type FetchWebPageResponse = FetchWebPageResponses[keyof FetchWebPageResponses];++export type SearchWebData = {+ body: WebSearch;+ path?: never;+ query?: never;+ url: '/web/search';+};++export type SearchWebErrors = {+ /**+ * Invalid query or filters+ */+ 400: WebErrorBody;+ /**+ * Unauthorized+ */+ 401: unknown;+ /**+ * AI allowance exhausted+ */+ 402: WebErrorBody;+ /**+ * Per-user hourly rate limit exceeded+ */+ 429: unknown;+ /**+ * The search provider failed+ */+ 502: WebErrorBody;+ /**+ * Web search unconfigured, busy, or usage validation unavailable+ */+ 503: WebErrorBody;+};++export type SearchWebError = SearchWebErrors[keyof SearchWebErrors];++export type SearchWebResponses = {+ /**+ * Results, best match first+ */+ 200: WebSearchResponse;+};++export type SearchWebResponse = SearchWebResponses[keyof SearchWebResponses];diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.jsonindex 78ce481e87..c7448cfcc8 100644--- a/packages/sdk/specs/cognition.json+++ b/packages/sdk/specs/cognition.json@@ -2804,6 +2804,166 @@}}}+ },+ "/web/fetch": {+ "post": {+ "tags": ["web"],+ "summary": "Read one public web page as Markdown. Charged to the acting user's AI allowance.",+ "operationId": "fetch_web_page",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebFetch"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "The page text",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebFetchResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid URL or length",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "AI allowance exhausted",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "422": {+ "description": "The page could not be read",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "429": {+ "description": "Per-user hourly rate limit exceeded"+ },+ "502": {+ "description": "The fetch provider failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "503": {+ "description": "Web fetch unconfigured, busy, or usage validation unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ }+ }+ }+ },+ "/web/search": {+ "post": {+ "tags": ["web"],+ "summary": "Search the public web. Charged to the acting user's AI allowance.",+ "operationId": "search_web",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebSearch"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Results, best match first",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebSearchResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid query or filters",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "AI allowance exhausted",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "429": {+ "description": "Per-user hourly rate limit exceeded"+ },+ "502": {+ "description": "The search provider failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ },+ "503": {+ "description": "Web search unconfigured, busy, or usage validation unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WebErrorBody"+ }+ }+ }+ }+ }+ }}},"components": {@@ -2847,7 +3007,8 @@"agent_mode_choice","dictation","image_generation",- "email_focus"+ "email_focus",+ "web_search"]},"AssistantMessagePart": {@@ -5677,27 +5838,32 @@"price_per_audio_minute": {"type": ["number", "null"],"format": "float",- "description": "Price per audio minute (USD), absent for token billing."+ "description": "Price per audio minute (USD), absent for token and credit billing."},"price_per_million_cache_read": {"type": ["number", "null"],"format": "float",- "description": "Price per million cache-read input tokens (USD), absent when the model\nhas no published rate and for audio billing."+ "description": "Price per million cache-read input tokens (USD), absent when the model\nhas no published rate and for audio and credit billing."},"price_per_million_cache_write": {"type": ["number", "null"],"format": "float",- "description": "Price per million cache-write input tokens (USD), absent when the model\nhas no published rate and for audio billing."+ "description": "Price per million cache-write input tokens (USD), absent when the model\nhas no published rate and for audio and credit billing."},"price_per_million_in": {"type": "number","format": "float",- "description": "Price per million input tokens (USD); zero for audio billing."+ "description": "Price per million input tokens (USD); zero for audio and credit billing."},"price_per_million_out": {"type": "number","format": "float",- "description": "Price per million output tokens (USD); zero for audio billing."+ "description": "Price per million output tokens (USD); zero for audio and credit billing."+ },+ "price_per_provider_credit": {+ "type": ["number", "null"],+ "format": "float",+ "description": "Price per vendor credit (USD), absent for token and audio billing."},"total": {"type": "number",@@ -5960,6 +6126,11 @@"type": ["number", "null"],"format": "float","description": "New price per million output tokens (USD). Required for token pricing."+ },+ "price_per_provider_credit": {+ "type": ["number", "null"],+ "format": "float",+ "description": "Price per vendor credit (USD), or null unless the model bills in credits."}}},@@ -6553,18 +6724,18 @@"audio_seconds": {"type": ["number", "null"],"format": "double",- "description": "Audio duration in seconds, absent for token billing."+ "description": "Audio duration in seconds, absent for token and credit billing."},"cache_read_input_tokens": {"type": "integer","format": "int64",- "description": "Input tokens read from a prompt cache; zero for audio billing.",+ "description": "Input tokens read from a prompt cache; zero for audio and credit billing.","minimum": 0},"cache_write_input_tokens": {"type": "integer","format": "int64",- "description": "Input tokens written to a prompt cache; zero for audio billing.",+ "description": "Input tokens written to a prompt cache; zero for audio and credit billing.","minimum": 0},"created_at": {@@ -6575,7 +6746,7 @@"input_tokens": {"type": "integer","format": "int64",- "description": "Uncached input tokens; zero for audio billing.",+ "description": "Uncached input tokens; zero for audio and credit billing.","minimum": 0},"model": {@@ -6585,7 +6756,7 @@"output_tokens": {"type": "integer","format": "int64",- "description": "Output tokens; zero for audio billing.",+ "description": "Output tokens; zero for audio and credit billing.","minimum": 0},"price": {@@ -6598,6 +6769,12 @@"description": "Applied pricing, if known."}]+ },+ "provider_credits": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "Vendor credits consumed, absent for token and audio billing.",+ "minimum": 0}}},@@ -6728,6 +6905,158 @@}}},+ "WebErrorBody": {+ "type": "object",+ "description": "Machine-readable failure of a web request.",+ "required": ["error", "code"],+ "properties": {+ "code": {+ "type": "string",+ "description": "Stable failure code."+ },+ "error": {+ "type": "string",+ "description": "Explanation without provider diagnostics."+ }+ }+ },+ "WebFetch": {+ "type": "object",+ "description": "Read one public web page.",+ "required": ["url"],+ "properties": {+ "maxChars": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Most characters of page text to return, 1 to 100,000 (default 20,000).",+ "minimum": 0+ },+ "url": {+ "type": "string",+ "description": "The `http` or `https` URL of the page."+ }+ }+ },+ "WebFetchResponse": {+ "type": "object",+ "description": "The text of a fetched page.",+ "required": ["url", "content", "truncated"],+ "properties": {+ "content": {+ "type": "string",+ "description": "The page text as Markdown, cut to `maxChars`."+ },+ "title": {+ "type": ["string", "null"],+ "description": "The page title, when the provider reports one."+ },+ "truncated": {+ "type": "boolean",+ "description": "Whether `content` was cut to `maxChars`."+ },+ "url": {+ "type": "string",+ "description": "The URL that was read."+ }+ }+ },+ "WebSearch": {+ "type": "object",+ "description": "Search the public web.",+ "required": ["query"],+ "properties": {+ "domains": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Only return pages from these domains, e.g. `[\"docs.rs\", \"github.com\"]`."+ },+ "excludeDomains": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Never return pages from these domains."+ },+ "includeContent": {+ "type": ["boolean", "null"],+ "description": "Also return each page's text as Markdown (up to 8,000 characters per result)."+ },+ "maxResults": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "How many results to return, 1 to 20 (default 5).",+ "minimum": 0+ },+ "query": {+ "type": "string",+ "description": "What to search for, in natural language or keywords (at most 400 characters)."+ },+ "since": {+ "type": ["string", "null"],+ "format": "date",+ "description": "Only return pages published on or after this date (`YYYY-MM-DD`)."+ },+ "topic": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/WebSearchTopic",+ "description": "`news` for recent articles with publication dates; `general` (the default) otherwise."+ }+ ]+ }+ }+ },+ "WebSearchResponse": {+ "type": "object",+ "description": "The pages a search found, best match first.",+ "required": ["results"],+ "properties": {+ "results": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/WebSearchResult"+ },+ "description": "Results, best match first. Empty when nothing matched."+ }+ }+ },+ "WebSearchResult": {+ "type": "object",+ "description": "One page a search found.",+ "required": ["title", "url", "snippet"],+ "properties": {+ "content": {+ "type": ["string", "null"],+ "description": "The page text as Markdown, when `includeContent` was set."+ },+ "publishedAt": {+ "type": ["string", "null"],+ "description": "When the page was published, as the search provider reports it."+ },+ "snippet": {+ "type": "string",+ "description": "The part of the page most relevant to the query."+ },+ "title": {+ "type": "string",+ "description": "The page title."+ },+ "url": {+ "type": "string",+ "description": "The page URL; cite it when you use the result."+ }+ }+ },+ "WebSearchTopic": {+ "type": "string",+ "description": "The kind of results a search favours.",+ "enum": ["general", "news"]+ },"WithChatId": {"type": "object","required": ["chat_id"],diff --git a/packages/sdk/src/entities/web/namespace.test.ts b/packages/sdk/src/entities/web/namespace.test.tsnew file mode 100644index 0000000000..fbc390c60d--- /dev/null+++ b/packages/sdk/src/entities/web/namespace.test.ts@@ -0,0 +1,108 @@+import { describe, expect, test } from 'bun:test';+import type {+ WebFetch,+ WebSearch,+} from '../../../generated/cognition/types.gen';+import type { MacroClient } from '../../utils/client';+import { WebNamespace } from './namespace';++describe('web', () => {+ test('search sends the query with its filters and returns the results', async () => {+ const requests: WebSearch[] = [];+ const client = {+ cognition: {+ searchWeb: async ({ body }: { body: WebSearch }) => {+ requests.push(body);+ return {+ data: {+ results: [+ {+ title: 'Announcing Tokio 1.48',+ url: 'https://tokio.rs/blog/2025-10-tokio-1-48',+ snippet: 'Tokio 1.48 ships a faster scheduler.',+ publishedAt: 'Tue, 14 Oct 2025 09:00:00 GMT',+ },+ ],+ },+ };+ },+ },+ } as unknown as MacroClient;++ const found = await new WebNamespace(client).search('tokio release', {+ domains: ['tokio.rs'],+ since: '2025-10-01',+ topic: 'news',+ maxResults: 3,+ });++ expect(requests).toEqual([+ {+ query: 'tokio release',+ domains: ['tokio.rs'],+ excludeDomains: undefined,+ since: '2025-10-01',+ topic: 'news',+ maxResults: 3,+ includeContent: undefined,+ },+ ]);+ expect(found).toEqual({+ results: [+ {+ title: 'Announcing Tokio 1.48',+ url: 'https://tokio.rs/blog/2025-10-tokio-1-48',+ snippet: 'Tokio 1.48 ships a faster scheduler.',+ publishedAt: 'Tue, 14 Oct 2025 09:00:00 GMT',+ },+ ],+ });+ });++ test('fetch reads one page with a length cap', async () => {+ const requests: WebFetch[] = [];+ const client = {+ cognition: {+ fetchWebPage: async ({ body }: { body: WebFetch }) => {+ requests.push(body);+ return {+ data: {+ url: 'https://example.com/',+ content: '# Example',+ truncated: false,+ },+ };+ },+ },+ } as unknown as MacroClient;++ const page = await new WebNamespace(client).fetch('https://example.com/', {+ maxChars: 500,+ });++ expect(requests).toEqual([{ url: 'https://example.com/', maxChars: 500 }]);+ expect(page).toEqual({+ url: 'https://example.com/',+ content: '# Example',+ truncated: false,+ });+ });++ test('fetch surfaces an unreadable page as an error', async () => {+ const client = {+ cognition: {+ fetchWebPage: async () => ({+ error: {+ error: 'The page could not be read: Failed to retrieve content',+ code: 'fetch_failed',+ },+ response: new Response(null, { status: 422 }),+ }),+ },+ } as unknown as MacroClient;++ await expect(+ new WebNamespace(client).fetch('https://example.com/members-only'),+ ).rejects.toThrow();+ });+});diff --git a/packages/sdk/src/entities/web/namespace.ts b/packages/sdk/src/entities/web/namespace.tsnew file mode 100644index 0000000000..60b0c5885f--- /dev/null+++ b/packages/sdk/src/entities/web/namespace.ts@@ -0,0 +1,95 @@+import type {+ WebFetchResponse,+ WebSearchResult,+ WebSearchTopic,+} from '../../../generated/cognition/types.gen';+import { unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';++export type { WebFetchResponse, WebSearchResult, WebSearchTopic };++/** Filters for {@link WebNamespace.search}. */+export interface WebSearchOptions {+ /** Only return pages from these domains, e.g. `['docs.rs', 'github.com']`. */+ domains?: string[];+ /** Never return pages from these domains. */+ excludeDomains?: string[];+ /** Only return pages published on or after this date, as `YYYY-MM-DD`. */+ since?: string;+ /** `news` for recent articles with publication dates; `general` (the default) otherwise. */+ topic?: WebSearchTopic;+ /** How many results to return, 1 to 20. Defaults to 5. */+ maxResults?: number;+ /** Also return each page's text as Markdown, up to 8,000 characters per result. */+ includeContent?: boolean;+}++/** Options for {@link WebNamespace.fetch}. */+export interface WebFetchOptions {+ /** Most characters of page text to return, 1 to 100,000. Defaults to 20,000. */+ maxChars?: number;+}++/**+ * Search the public web and read web pages, charged to the acting user's AI+ * allowance.+ *+ * @routing Use when finding or reading information on the public internet; not searching the user's Macro workspace (`macro.search`) or reading a URL's preview card (`macro.unfurls`).+ *+ * @agent Search returns snippets, which often answer the question on their+ * own; fetch a result's URL only when you need the whole page. Cite the URL of+ * every page you rely on. Pages behind a login, or rendered only by+ * JavaScript, may fail to fetch with `fetch_failed`.+ */+export class WebNamespace {+ constructor(private readonly client: MacroClient) {}++ /**+ * Search the public web; returns title, URL and a query-relevant snippet per+ * page, best match first. Cite the URLs you use.+ *+ * @example+ * const { results } = await macro.web.search('Tokio 1.48 release notes', {+ * domains: ['tokio.rs'],+ * maxResults: 3,+ * });+ * for (const result of results) console.log(result.title, result.url, result.snippet);+ */+ async search(+ query: string,+ options: WebSearchOptions = {},+ ): Promise<{ results: WebSearchResult[] }> {+ return unwrap(+ await this.client.cognition.searchWeb({+ body: {+ query,+ domains: options.domains,+ excludeDomains: options.excludeDomains,+ since: options.since,+ topic: options.topic,+ maxResults: options.maxResults,+ includeContent: options.includeContent,+ },+ }),+ );+ }++ /**+ * Read one public web page as Markdown, cut to `maxChars` (`truncated` says+ * whether it was). Use it when a search snippet is not enough; cite the URL.+ *+ * @example+ * const page = await macro.web.fetch('https://tokio.rs/blog/2025-10-tokio-1-48');+ * console.log(page.content);+ */+ async fetch(+ url: string,+ options: WebFetchOptions = {},+ ): Promise<WebFetchResponse> {+ return unwrap(+ await this.client.cognition.fetchWebPage({+ body: { url, maxChars: options.maxChars },+ }),+ );+ }+}diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex 06b18d92e2..e4a665c3f8 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -34,6 +34,7 @@ import { TeamNamespace } from './entities/teams/namespace';import { UnfurlNamespace } from './entities/unfurls/namespace';import { UserNamespace } from './entities/users/namespace';import type { User } from './entities/users/user';+import { WebNamespace } from './entities/web/namespace';import { WebhooksNamespace } from './entities/webhooks/namespace';import { WhatsAppNamespace } from './entities/whatsapp/namespace';import { WorkspaceNamespace } from './entities/workspace/namespace';@@ -158,6 +159,8 @@ export class Macro<T extends MacroOpts = MacroOpts> {/** Generate images with AI and attach them to messages. */readonly images: ImagesNamespace;+ /** Search the public web and read web pages. */+ readonly web: WebNamespace;/** Your own profile: set your name and profile picture. */readonly me: MeNamespace;@@ -224,6 +227,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {this.foreignEntities = new ForeignEntityNamespace(client);this.forms = new FormNamespace(client);this.images = new ImagesNamespace(client);+ this.web = new WebNamespace(client);this.notifications = new NotificationNamespace(client);this.pins = new PinsNamespace(client);this.projects = new ProjectNamespace(client);@@ -359,6 +363,13 @@ export { AccessRequest, EntityAccess } from './entities/sharing/access';export type { SharePermissionOptions } from './entities/sharing/permissions';export type { TaskSummary } from './entities/tasks/task';export { TeamInvite } from './entities/teams/invite';+export type {+ WebFetchOptions,+ WebFetchResponse,+ WebSearchOptions,+ WebSearchResult,+ WebSearchTopic,+} from './entities/web/namespace';export { WhatsAppAccount } from './entities/whatsapp/account';export {WhatsAppChat,diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex bb77483482..78e66812b7 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -42,6 +42,9 @@ Pulumi stacks; they do not host extra agent processes.`src/cognition/service/integration_analytics.rs` sends PostHog`integration_connected` / `integration_disconnected` for native MCP serversand Pipedream apps, from the router hooks wired in `src/cognition/server.rs`.+- `crates/web_search` owns `POST /web/search` and `/web/fetch` (mounted in+ `src/cognition/api.rs`, rate limited per user through cognition's Redis) and the+ `WebSearch`/`WebFetch` tools; `TAVILY_API_KEY` comes from Doppler `shared_ai`.- `crates/universal_input` owns Command K's authenticated `/universal_input/classify`and `/universal_input/extract` routes, mounted directly by `src/api.rs`. The rootcomposes staged search type/field extraction and Clairic content extractiondiff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex cab1d3893d..2f7363cb16 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -164,6 +164,7 @@ prompt = { path = "../../crates/prompt" }properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }rdkafka = { workspace = true }readonly_pool = { path = "../../crates/readonly_pool" }+rate_limit = { path = "../../crates/rate_limit" }redis = { workspace = true, features = ["aio", "streams", "tokio-comp", "tokio-rustls-comp"] }regex = { workspace = true }reqwest = { workspace = true }@@ -203,6 +204,7 @@ url = { workspace = true }utoipa = { workspace = true, features = ["axum_extras", "chrono"] }utoipa-swagger-ui = { workspace = true, features = ["axum"] }uuid = { workspace = true }+web_search = { path = "../../crates/web_search", features = ["axum"] }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }[dev-dependencies]diff --git a/services/agent_harness_service/src/cognition/api.rs b/services/agent_harness_service/src/cognition/api.rsindex c3264ec575..ae7587a215 100644--- a/services/agent_harness_service/src/cognition/api.rs+++ b/services/agent_harness_service/src/cognition/api.rs@@ -99,6 +99,16 @@ fn api_router(api_context: ApiContext) -> Router {non_user_owners: api_context.non_user_owners,};+ let web_state = web_search::inbound::axum_router::WebRouterState::new(+ std::sync::Arc::new(web_search::domain::service::WebSearchService::new(+ api_context.tool_service_context.web_search_provider.clone(),+ api_context.ai_admission.clone(),+ api_context.tool_service_context.recorder.clone(),+ )),+ api_context.web_rate_limiter.clone(),+ authorization_state.clone(),+ );+let internal_router = Router::new().nest("/chats", chats::router(api_context.clone())).nest("/stream", stream::router())@@ -149,6 +159,7 @@ fn api_router(api_context: ApiContext) -> Router {.merge(image_generation::inbound::axum_router::image_generation_router(image_generation_state),)+ .merge(web_search::inbound::axum_router::web_router(web_state)).merge(mcp_client::inbound::mcp_router(mcp_state.clone())).merge(pipedream_mcp::inbound::pipedream_mcp_router(api_context.pipedream_state.clone(),diff --git a/services/agent_harness_service/src/cognition/api/context.rs b/services/agent_harness_service/src/cognition/api/context.rsindex b3294a99bb..e728903255 100644--- a/services/agent_harness_service/src/cognition/api/context.rs+++ b/services/agent_harness_service/src/cognition/api/context.rs@@ -136,6 +136,10 @@ pub type DcsPipedreamRouterState = pipedream_mcp::inbound::PipedreamRouterState<DcsAuthorizationService,>;+/// Redis-backed rate limiting for the web routes.+pub type WebRateLimiter =+ rate_limit::RateLimitServiceImpl<rate_limit::RedisRateLimitAdapter<redis::Client>>;+#[derive(Clone, FromRef)]pub struct ApiContext {pub db: PgPool,@@ -177,6 +181,8 @@ pub struct ApiContext {pub entity_access_service: Arc<DcsEntityAccessService>,pub message_service: Arc<DcsMessageService>,pub ai_stream_registry: AiStreamRegistry,+ /// Per-user limit on `/web/search` and `/web/fetch`.+ pub web_rate_limiter: WebRateLimiter,pub mcp_state: DcsMcpRouterState,pub pipedream_state: DcsPipedreamRouterState,pub granola_sync: Option<Arc<dyn granola_sync::domain::service::SyncService>>,diff --git a/services/agent_harness_service/src/cognition/api/context/test.rs b/services/agent_harness_service/src/cognition/api/context/test.rsindex 0de70ec9b9..3e853c1ea1 100644--- a/services/agent_harness_service/src/cognition/api/context/test.rs+++ b/services/agent_harness_service/src/cognition/api/context/test.rs@@ -591,6 +591,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar),schedule_tool_context: ai_tools::no_op_schedule_context(),anthropic_tool_context: ai_tools::build_anthropic_tool_context_test(),+ web_search_provider: std::sync::Arc::new(web_search::outbound::tavily::TavilyClient::new(+ &web_search::outbound::tavily::TavilyApiKey::new_unset(),+ )),admission: admission.clone(),recorder: recorder.clone(),usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),@@ -817,6 +820,11 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arai_stream_registry: crate::cognition::service::ai_stream_registry::AiStreamRegistry::new(Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url")),),+ web_rate_limiter: rate_limit::RateLimitServiceImpl {+ repo: rate_limit::RedisRateLimitAdapter {+ redis: redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"),+ },+ },granola_sync: None,pipedream_state: pipedream_mcp::inbound::PipedreamRouterState::new(pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(pool.clone()),diff --git a/services/agent_harness_service/src/cognition/api/swagger.rs b/services/agent_harness_service/src/cognition/api/swagger.rsindex 1c03e1eb05..dea403c80a 100644--- a/services/agent_harness_service/src/cognition/api/swagger.rs+++ b/services/agent_harness_service/src/cognition/api/swagger.rs@@ -96,6 +96,8 @@ use utoipa::OpenApi;structured_completion::structured_completion,decisions::decide,image_generation_api::generate_image_handler,+ web_search::inbound::axum_router::search_handler,+ web_search::inbound::axum_router::fetch_handler,database_query::generate_database_query,memory_api::get_memory_handler,import_api::get_state_handler,@@ -211,6 +213,13 @@ use utoipa::OpenApi;image_generation_api::GenerateImageErrorBody,image_generation_api::GenerateImageAspectRatio,image_generation_api::GenerateImageReference,+ web_search::domain::models::WebSearch,+ web_search::domain::models::WebSearchResponse,+ web_search::domain::models::WebSearchResult,+ web_search::domain::models::WebSearchTopic,+ web_search::domain::models::WebFetch,+ web_search::domain::models::WebFetchResponse,+ web_search::inbound::axum_router::WebErrorBody,agent::structured_output::DynamicSchema,// Memorydiff --git a/services/agent_harness_service/src/cognition/server.rs b/services/agent_harness_service/src/cognition/server.rsindex aa5407f23c..d640a09bf7 100644--- a/services/agent_harness_service/src/cognition/server.rs+++ b/services/agent_harness_service/src/cognition/server.rs@@ -951,6 +951,7 @@ pub async fn build(),schedule_tool_context: ai_tools::build_routine_tool_context()?,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),+ web_search_provider: ai_tools::build_web_search_provider_from_env(),admission,recorder,usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),@@ -1160,6 +1161,11 @@ pub async fn build(ai_stream_registry: service::ai_stream_registry::AiStreamRegistry::new(redis_client.clone(),),+ web_rate_limiter: rate_limit::RateLimitServiceImpl {+ repo: rate_limit::RedisRateLimitAdapter {+ redis: (*redis_client).clone(),+ },+ },mcp_state,pipedream_state,granola_sync,