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(personas): harness, mentions, cursor (#6005)
Eric Hayes539e78fb2dae
diff --git a/.gitignore b/.gitignoreindex b2812b0d7f..816de9dfc2 100644--- a/.gitignore+++ b/.gitignore@@ -40,3 +40,9 @@ infra/local/generated/# Raw SSE captures from CURSOR_ACP_RECORD_DIR; sanitize into# crates/cursor_acp/fixtures/real/ before committing one./recordings/++# Per-developer macrod daemon config and the state files it writes next to+# it (the credentials file holds this machine's harness bearer token).+/macro.toml+/macro.credentials.json+/macro.webhook-state.jsondiff --git a/.sqlx/query-0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf.json b/.sqlx/query-0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf.jsonnew file mode 100644index 0000000000..d391d7fbd9--- /dev/null+++ b/.sqlx/query-0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT COUNT(DISTINCT channel_id) = CARDINALITY($2::uuid[]) AS \"has_channels!\"\n FROM comms_channel_participants\n WHERE user_id = $1\n AND channel_id = ANY($2::uuid[])\n AND left_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "has_channels!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf"+}diff --git a/.sqlx/query-2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298.json b/.sqlx/query-2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298.jsonnew file mode 100644index 0000000000..c00086e9d7--- /dev/null+++ b/.sqlx/query-2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE user_id = $1\n AND left_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298"+}diff --git a/.sqlx/query-467f7cfe6bacaa5fb792ed46d9ac248e8d3e8b6becb635524e1e57de0e19282b.json b/.sqlx/query-467f7cfe6bacaa5fb792ed46d9ac248e8d3e8b6becb635524e1e57de0e19282b.jsonnew file mode 100644index 0000000000..d64c16e715--- /dev/null+++ b/.sqlx/query-467f7cfe6bacaa5fb792ed46d9ac248e8d3e8b6becb635524e1e57de0e19282b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)\n SELECT channel_id, $2, 'member'::comms_participant_role, NULL\n FROM UNNEST($1::uuid[]) AS channel_id\n ON CONFLICT (channel_id, user_id)\n DO UPDATE SET role = 'member'::comms_participant_role,\n left_at = NULL,\n joined_at = now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "467f7cfe6bacaa5fb792ed46d9ac248e8d3e8b6becb635524e1e57de0e19282b"+}diff --git a/.sqlx/query-5bb3d1e4961ecb793c701bae370e09a66c4457259088b66fb9240804f6a3645f.json b/.sqlx/query-5bb3d1e4961ecb793c701bae370e09a66c4457259088b66fb9240804f6a3645f.jsonnew file mode 100644index 0000000000..fc24266340--- /dev/null+++ b/.sqlx/query-5bb3d1e4961ecb793c701bae370e09a66c4457259088b66fb9240804f6a3645f.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)\n SELECT channel_id, $2, 'member'::comms_participant_role, NULL\n FROM UNNEST($1::uuid[]) AS channel_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "5bb3d1e4961ecb793c701bae370e09a66c4457259088b66fb9240804f6a3645f"+}diff --git a/.sqlx/query-635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544.json b/.sqlx/query-635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544.jsonnew file mode 100644index 0000000000..cc31b1c5a5--- /dev/null+++ b/.sqlx/query-635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n default_model = $4,\n channel_scope = $5,\n updated_at = now()\n WHERE bot_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "635357c9b365a422c05d7cbc82d25924f435ea3697a6ec62311f2d40e0548544"+}diff --git a/.sqlx/query-a24f4313310e3184aac7971988f6c31ba4829569be9ce2cd69b50a68fa76750e.json b/.sqlx/query-a24f4313310e3184aac7971988f6c31ba4829569be9ce2cd69b50a68fa76750e.jsonnew file mode 100644index 0000000000..ef3046a6b6--- /dev/null+++ b/.sqlx/query-a24f4313310e3184aac7971988f6c31ba4829569be9ce2cd69b50a68fa76750e.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM team_user\n WHERE user_id = $1\n AND team_id = $2\n AND team_role = 'owner'::team_role\n ) AS \"owns_team!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owns_team!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "a24f4313310e3184aac7971988f6c31ba4829569be9ce2cd69b50a68fa76750e"+}diff --git a/.sqlx/query-a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53.json b/.sqlx/query-a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53.jsonnew file mode 100644index 0000000000..17416b7ec8--- /dev/null+++ b/.sqlx/query-a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53.json@@ -0,0 +1,124 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "handle",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "avatar_url",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 12,+ "name": "has_agent",+ "type_info": "Bool"+ },+ {+ "ordinal": 13,+ "name": "instructions",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "harness",+ "type_info": "Text"+ },+ {+ "ordinal": 15,+ "name": "default_model",+ "type_info": "Text"+ },+ {+ "ordinal": 16,+ "name": "channel_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,+ "name": "channel_ids!",+ "type_info": "UuidArray"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false,+ false,+ false,+ false,+ null+ ]+ },+ "hash": "a4d77f4ccdf193d761babe6a541a21653703d17bfd823441427187f27ad21b53"+}diff --git a/.sqlx/query-afb7e1ae4a7f9978085299a9473a9f8ddf77e2177d937fe6d18dd4ae0e3a1b6d.json b/.sqlx/query-afb7e1ae4a7f9978085299a9473a9f8ddf77e2177d937fe6d18dd4ae0e3a1b6d.jsonnew file mode 100644index 0000000000..3af660c19b--- /dev/null+++ b/.sqlx/query-afb7e1ae4a7f9978085299a9473a9f8ddf77e2177d937fe6d18dd4ae0e3a1b6d.json@@ -0,0 +1,100 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE bots\n SET owner_user_id = $2,\n team_id = $3,\n name = $4,\n handle = $5,\n description = $6,\n avatar_url = $7,\n updated_at = now()\n WHERE id = $1\n AND deleted_at IS NULL\n AND EXISTS (SELECT 1 FROM agent_configs WHERE bot_id = $1)\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at,\n has_agent\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "handle",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "avatar_url",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 12,+ "name": "has_agent",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false,+ true,+ true,+ true,+ false,+ false,+ true,+ false+ ]+ },+ "hash": "afb7e1ae4a7f9978085299a9473a9f8ddf77e2177d937fe6d18dd4ae0e3a1b6d"+}diff --git a/.sqlx/query-bc6d0e554098cd09c94063bd6d85f90ced539d0c65f2ebf3b4a252aaa76d5493.json b/.sqlx/query-bc6d0e554098cd09c94063bd6d85f90ced539d0c65f2ebf3b4a252aaa76d5493.jsonnew file mode 100644index 0000000000..86ac3a4e6d--- /dev/null+++ b/.sqlx/query-bc6d0e554098cd09c94063bd6d85f90ced539d0c65f2ebf3b4a252aaa76d5493.json@@ -0,0 +1,101 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO bots (\n id, kind, owner_user_id, team_id, name, handle, description, avatar_url,\n created_by, has_agent\n )\n VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8, true)\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at,\n has_agent\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "handle",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "avatar_url",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 12,+ "name": "has_agent",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false,+ true,+ true,+ true,+ false,+ false,+ true,+ false+ ]+ },+ "hash": "bc6d0e554098cd09c94063bd6d85f90ced539d0c65f2ebf3b4a252aaa76d5493"+}diff --git a/.sqlx/query-d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43.json b/.sqlx/query-d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43.jsonnew file mode 100644index 0000000000..4bb0f825a9--- /dev/null+++ b/.sqlx/query-d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43.json@@ -0,0 +1,124 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "kind",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "handle",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "avatar_url",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 12,+ "name": "has_agent",+ "type_info": "Bool"+ },+ {+ "ordinal": 13,+ "name": "instructions",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "harness",+ "type_info": "Text"+ },+ {+ "ordinal": 15,+ "name": "default_model",+ "type_info": "Text"+ },+ {+ "ordinal": 16,+ "name": "channel_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,+ "name": "channel_ids!",+ "type_info": "UuidArray"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false,+ false,+ false,+ false,+ null+ ]+ },+ "hash": "d05b1c840950c3ead42dd8dce64bcb73a79bb293cf5fc5232bab344d04ffed43"+}diff --git a/.sqlx/query-ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce.json b/.sqlx/query-ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce.jsonnew file mode 100644index 0000000000..991d6191ca--- /dev/null+++ b/.sqlx/query-ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, default_model, channel_scope\n )\n VALUES ($1, $2, $3, $4, $5)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "ec69dbdf2fa28215718f9170a0664b4fc4302de767765ab6629615b810c15cce"+}diff --git a/Cargo.lock b/Cargo.lockindex f86b7174d3..af3654d768 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -325,6 +325,7 @@ dependencies = ["pipedream_mcp","rdkafka","reqwest 0.13.4",+ "rootcause","secretsmanager_client","serde","serde_json",@@ -438,6 +439,7 @@ dependencies = ["ai_usage","anyhow","bot_id",+ "bots","channel_sender","channels","chrono",@@ -2778,6 +2780,7 @@ dependencies = ["serde","serde_json","sqlx",+ "strum 0.27.2","thiserror 2.0.18","tokio","tower 0.5.3",diff --git a/apps/web/src/features/channel/Bots/BotDetailActions.tsx b/apps/web/src/features/channel/Bots/BotDetailActions.tsxindex e70c543e1a..77db96f32a 100644--- a/apps/web/src/features/channel/Bots/BotDetailActions.tsx+++ b/apps/web/src/features/channel/Bots/BotDetailActions.tsx@@ -1,7 +1,9 @@import TrashIcon from '@phosphor/trash.svg';import { Button } from '@ui';+import { Show } from 'solid-js';type BotDetailActionsProps = {+ canDelete: boolean;dirty: boolean;pending: boolean;saving: boolean;@@ -12,17 +14,19 @@ type BotDetailActionsProps = {export function BotDetailActions(props: BotDetailActionsProps) {return (<div class="flex items-center justify-between gap-3 pt-1">- <Button- type="button"- variant="danger"- size="sm"- disabled={props.pending}- onClick={props.onDelete}- >- <TrashIcon />- Delete bot- </Button>- <div class="flex items-center gap-2">+ <Show when={props.canDelete}>+ <Button+ type="button"+ variant="danger"+ size="sm"+ disabled={props.pending}+ onClick={props.onDelete}+ >+ <TrashIcon />+ Delete bot+ </Button>+ </Show>+ <div class="ml-auto flex items-center gap-2"><Buttontype="button"variant="ghost"diff --git a/apps/web/src/features/channel/Bots/BotDetailPage.tsx b/apps/web/src/features/channel/Bots/BotDetailPage.tsxindex 59c5ee8b43..03dededb71 100644--- a/apps/web/src/features/channel/Bots/BotDetailPage.tsx+++ b/apps/web/src/features/channel/Bots/BotDetailPage.tsx@@ -1,6 +1,7 @@import { LoadingSpinner } from '@core/component/LoadingSpinner';import { toast } from '@core/component/Toast/Toast';import { useChannelsContext } from '@core/context/channels';+import { useUserId } from '@core/context/user';import CaretLeftIcon from '@phosphor/caret-left.svg';import {useBotChannelsQuery,@@ -9,6 +10,7 @@ import {useUpdateBotMutation,} from '@queries/bots/bots';import { useSyncBotChannelsMutation } from '@queries/channel/channel-bots';+import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';import { Button } from '@ui';import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';import { createStore } from 'solid-js/store';@@ -27,12 +29,16 @@ import {slugBotHandle,validateBotForm,} from './botForm';+import { canDeleteBot } from './botPermissions';import { ChannelMultiSelect } from './ChannelMultiSelect';import { CreateBotTokenDialog } from './CreateBotTokenDialog';import { createBotAvatarUpload } from './createBotAvatarUpload';export function BotDetail(props: { botId: string; onBack: () => void }) {const channelsContext = useChannelsContext();+ const currentUserId = useUserId();+ const currentTeamQuery = useCurrentTeamQuery();+ const isTeamOwner = useIsTeamOwner();const botQuery = useBotQuery(() => props.botId);const botChannelsQuery = useBotChannelsQuery(() => props.botId);const updateBotMutation = useUpdateBotMutation();@@ -100,6 +106,18 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {});const pending = () =>saving() || avatarUpload.uploading() || deleteBotMutation.isPending;+ const canDelete = () => {+ const bot = botQuery.data;+ return (+ bot !== undefined &&+ canDeleteBot(+ bot,+ currentUserId(),+ currentTeamQuery.data?.team.id,+ isTeamOwner()+ )+ );+ };const leave = () => {if (pending()) return;@@ -278,6 +296,7 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {/><BotDetailActions+ canDelete={canDelete()}dirty={isDirty()}pending={pending()}saving={saving()}diff --git a/apps/web/src/features/channel/Bots/botPermissions.ts b/apps/web/src/features/channel/Bots/botPermissions.tsnew file mode 100644index 0000000000..81ba8f2533--- /dev/null+++ b/apps/web/src/features/channel/Bots/botPermissions.ts@@ -0,0 +1,20 @@+import type { Bot } from '@service-storage/generated/schemas/bot';++type BotOwnership = Pick<Bot, 'created_by' | 'owner'>;++/** Whether the current user may delete an owned bot. */+export function canDeleteBot(+ bot: BotOwnership,+ currentUserId: string | undefined,+ currentTeamId: string | undefined,+ isCurrentTeamOwner: boolean+): boolean {+ if (!currentUserId || !bot.owner) return false;+ if (bot.owner.type === 'user') {+ return bot.owner.user_id === currentUserId;+ }+ return (+ bot.created_by === currentUserId ||+ (bot.owner.team_id === currentTeamId && isCurrentTeamOwner)+ );+}diff --git a/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts b/apps/web/src/features/channel/Bots/tests/bot-permissions.test.tsnew file mode 100644index 0000000000..de6f054a54--- /dev/null+++ b/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';+import { canDeleteBot } from '../botPermissions';++const CURRENT_USER = 'macro|[email protected]';+const CREATOR = 'macro|[email protected]';+const TEAM_ID = 'team-1';++describe('canDeleteBot', () => {+ it('allows the owner of a private bot', () => {+ expect(+ canDeleteBot(+ {+ owner: { type: 'user', user_id: CURRENT_USER },+ created_by: CURRENT_USER,+ },+ CURRENT_USER,+ TEAM_ID,+ false+ )+ ).toBe(true);+ });++ it('allows either the creator or team owner for a team bot', () => {+ const bot = {+ owner: { type: 'team' as const, team_id: TEAM_ID },+ created_by: CREATOR,+ };++ expect(canDeleteBot(bot, CREATOR, TEAM_ID, false)).toBe(true);+ expect(canDeleteBot(bot, CURRENT_USER, TEAM_ID, true)).toBe(true);+ });++ it('rejects non-creator team members and owners of another team', () => {+ const bot = {+ owner: { type: 'team' as const, team_id: TEAM_ID },+ created_by: CREATOR,+ };++ expect(canDeleteBot(bot, CURRENT_USER, TEAM_ID, false)).toBe(false);+ expect(canDeleteBot(bot, CURRENT_USER, 'team-2', true)).toBe(false);+ });+});diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.test.tsnew file mode 100644index 0000000000..46ae8fc4d7--- /dev/null+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts@@ -0,0 +1,91 @@+import type { Agent } from '@service-storage/generated/schemas/agent';+import type { Bot } from '@service-storage/generated/schemas/bot';+import { describe, expect, it } from 'vitest';+import { availableBotMentionUsers } from './use-channel-bot-mention-users';++const timestamp = '2026-08-27T12:00:00Z';++function bot(id: string, name: string, avatarUrl?: string): Bot {+ return {+ id,+ kind: 'owned',+ name,+ handle: name.toLowerCase().replaceAll(' ', '-'),+ has_agent: true,+ avatar_url: avatarUrl,+ created_at: timestamp,+ updated_at: timestamp,+ };+}++function agent(+ id: string,+ name: string,+ channelScope: Agent['channel_scope'],+ harness = 'in-memory'+): Agent {+ return {+ bot: bot(id, name),+ channel_ids: channelScope === 'all' ? [] : ['channel-1'],+ channel_scope: channelScope,+ default_model: 'model',+ harness,+ instructions: '',+ };+}++describe('availableBotMentionUsers', () => {+ it('adds all-channel agents without adding selected agents from other channels', () => {+ expect(+ availableBotMentionUsers(+ [bot('installed', 'Installed')],+ [+ agent('global', 'Global', 'all'),+ agent('selected', 'Selected', 'selected'),+ ],+ false+ ).map((user) => user.id)+ ).toEqual(['bot|installed', 'bot|global']);+ });++ it('deduplicates an agent that is also an installed channel bot', () => {+ expect(+ availableBotMentionUsers(+ [bot('global', 'Global')],+ [agent('global', 'Global', 'all')],+ false+ )+ ).toHaveLength(1);+ });++ it('preserves the agent avatar for the mention menu', () => {+ const avatarUrl = 'https://example.com/global-agent.png';++ expect(+ availableBotMentionUsers(+ [],+ [+ {+ ...agent('global', 'Global', 'all'),+ bot: bot('global', 'Global', avatarUrl),+ },+ ],+ false+ )+ ).toEqual([+ {+ id: 'bot|global',+ name: 'Global',+ email: 'Global',+ photoUrl: avatarUrl,+ },+ ]);+ });++ it('only offers a global Cursor agent when Cursor is connected', () => {+ const cursorAgent = agent('cursor-agent', 'Cursor agent', 'all', 'cursor');++ expect(availableBotMentionUsers([], [cursorAgent], false)).toEqual([]);+ expect(availableBotMentionUsers([], [cursorAgent], true)).toHaveLength(1);+ });+});diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.tsindex f956671885..9d358c4c79 100644--- a/apps/web/src/features/channel/use-channel-bot-mention-users.ts+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.ts@@ -1,7 +1,43 @@import type { IUser } from '@core/user/types';+import { useAgentsQuery } from '@queries/agents/agents';+import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';import { useChannelBotsQuery } from '@queries/channel/channel-bots';+import type { Agent } from '@service-storage/generated/schemas/agent';+import type { Bot } from '@service-storage/generated/schemas/bot';import { type Accessor, createMemo } from 'solid-js';+function mentionUser(bot: Bot): IUser {+ return {+ id: `bot|${bot.id}`,+ name: bot.name,+ email: bot.name,+ photoUrl: bot.avatar_url ?? undefined,+ };+}++/** Build mention entries from installed channel bots and virtual global agents. */+export function availableBotMentionUsers(+ channelBots: readonly Bot[],+ agents: readonly Agent[],+ cursorConnected: boolean+): IUser[] {+ const globalAgents = agents.filter(+ (agent) =>+ agent.channel_scope === 'all' &&+ agent.bot.has_agent &&+ (agent.harness !== 'cursor' || cursorConnected)+ );+ const seen = new Set<string>();++ return [...channelBots, ...globalAgents.map((agent) => agent.bot)]+ .map(mentionUser)+ .filter((user) => {+ if (seen.has(user.id)) return false;+ seen.add(user.id);+ return true;+ });+}+/*** The channel's bots as synthetic [`IUser`] entries for the `@`-mention* typeahead. Like `macroAiMentionUser()`, `email` is set to the bot's name so@@ -12,13 +48,15 @@ import { type Accessor, createMemo } from 'solid-js';export function useChannelBotMentionUsers(channelId: Accessor<string>): Accessor<IUser[]> {- const query = useChannelBotsQuery(channelId);+ const channelBots = useChannelBotsQuery(channelId);+ const agents = useAgentsQuery();+ const cursorStatus = useCursorApiKeyStatusQuery();- return createMemo(() => {- return (query.data ?? []).map((bot) => ({- id: `bot|${bot.id}`,- name: bot.name,- email: bot.name,- }));- });+ return createMemo(() =>+ availableBotMentionUsers(+ channelBots.data ?? [],+ agents.data ?? [],+ cursorStatus.data?.registered ?? false+ )+ );}diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxnew file mode 100644index 0000000000..da39accb0b--- /dev/null+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -0,0 +1,516 @@+/**+ * @vitest-environment jsdom+ */++import { Model } from '@core/component/AI/constant/model';+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { Agents } from './Agents';++const cursorMocks = vi.hoisted(() => ({+ status: {+ data: {+ registered: false,+ updatedAt: null as string | null,+ },+ },+ models: {+ data: {+ models: [+ { id: 'cursor-small', displayName: 'Cursor Small' },+ { id: 'cursor-large', displayName: 'Cursor Large' },+ ],+ },+ },+}));++const agentMocks = vi.hoisted(() => ({+ query: {+ data: [] as unknown[],+ isError: false,+ },+ create: vi.fn(),+ delete: vi.fn(),+ update: vi.fn(),+ toastSuccess: vi.fn(),+ toastFailure: vi.fn(),+ currentUserId: 'macro|[email protected]',+ currentTeam: { team: { id: 'team-1' } } as { team: { id: string } } | null,+ isTeamOwner: false,+}));++vi.mock('@queries/auth/cursor-api-key', () => ({+ useCursorApiKeyStatusQuery: () => cursorMocks.status,+ useCursorModelsQuery: () => cursorMocks.models,+}));++vi.mock('@queries/agents/agents', () => ({+ useAgentsQuery: () => agentMocks.query,+ useCreateAgentMutation: () => ({+ mutateAsync: agentMocks.create,+ isPending: false,+ }),+ useDeleteAgentMutation: () => ({+ mutateAsync: agentMocks.delete,+ isPending: false,+ }),+ useUpdateAgentMutation: () => ({+ mutateAsync: agentMocks.update,+ isPending: false,+ }),+}));++vi.mock('@queries/team/teams', () => ({+ useCurrentTeamQuery: () => ({ data: agentMocks.currentTeam }),+ useIsTeamOwner: () => () => agentMocks.isTeamOwner,+}));++vi.mock('@core/context/user', () => ({+ useUserId: () => () => agentMocks.currentUserId,+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: {+ success: agentMocks.toastSuccess,+ failure: agentMocks.toastFailure,+ },+}));++vi.mock('@core/context/channels', () => ({+ useChannelsContext: () => ({+ channels: () => [+ { id: 'channel-general', name: 'general', channel_type: 'private' },+ {+ id: 'channel-engineering',+ name: 'engineering',+ channel_type: 'team',+ },+ ],+ }),+}));++beforeAll(() => {+ vi.stubGlobal('scrollTo', vi.fn());+});++beforeEach(() => {+ cursorMocks.status.data = {+ registered: false,+ updatedAt: null,+ };+ agentMocks.query.data = [];+ agentMocks.query.isError = false;+ agentMocks.create.mockResolvedValue(undefined);+ agentMocks.delete.mockResolvedValue(undefined);+ agentMocks.update.mockResolvedValue(undefined);+ agentMocks.currentUserId = 'macro|[email protected]';+ agentMocks.currentTeam = { team: { id: 'team-1' } };+ agentMocks.isTeamOwner = false;+});++describe('Agents', () => {+ it('lists the built-in global Macro agent as a team agent', () => {+ render(() => <Agents />);++ const teamSection = screen+ .getByRole('heading', { name: 'Team agents' })+ .closest('section') as HTMLElement;+ const privateSection = screen+ .getByRole('heading', { name: 'Private agents' })+ .closest('section') as HTMLElement;++ expect(within(teamSection).getByText('Macro')).toBeTruthy();+ expect(within(teamSection).getByText('@macro')).toBeTruthy();+ expect(within(teamSection).getByText('Team')).toBeTruthy();+ expect(within(teamSection).getByText(/All channels/)).toBeTruthy();+ expect(+ within(teamSection).queryByRole('button', { name: 'Delete Macro' })+ ).toBeNull();+ expect(+ within(privateSection).getByText('No private agents yet.')+ ).toBeTruthy();+ });++ it('groups server agents into team and private sections', () => {+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ description: 'Finds and fixes bugs.',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'all',+ channel_ids: [],+ },+ {+ bot: {+ id: 'agent-2',+ kind: 'owned',+ owner: { type: 'team', team_id: 'team-1' },+ name: 'Release helper',+ handle: 'release-helper',+ description: 'Coordinates releases.',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Keep releases moving.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'selected',+ channel_ids: ['channel-engineering'],+ },+ ];++ render(() => <Agents />);++ const teamSection = screen+ .getByRole('heading', { name: 'Team agents' })+ .closest('section') as HTMLElement;+ const privateSection = screen+ .getByRole('heading', { name: 'Private agents' })+ .closest('section') as HTMLElement;++ expect(within(teamSection).getByText('Macro')).toBeTruthy();+ expect(within(teamSection).getByText('Release helper')).toBeTruthy();+ expect(within(teamSection).queryByText('Coordinates releases.')).toBeNull();+ expect(within(teamSection).queryByText('Bug fixer')).toBeNull();++ const agentName = within(privateSection).getByText('Bug fixer');+ expect(within(privateSection).getByText('@bug-fixer')).toBeTruthy();+ expect(+ within(privateSection).queryByText('Finds and fixes bugs.')+ ).toBeNull();+ expect(within(privateSection).queryByText('Release helper')).toBeNull();+ expect(+ within(agentName.parentElement?.parentElement as HTMLElement).getByText(+ /All channels/+ )+ ).toBeTruthy();+ });++ it('edits and persists an existing agent through the agents API', async () => {+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ description: 'Finds and fixes bugs.',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'selected',+ channel_ids: ['channel-engineering'],+ },+ ];++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Edit agent')).toBeTruthy();+ expect(within(dialog).getByLabelText('Name')).toHaveProperty(+ 'value',+ 'Bug fixer'+ );+ expect(within(dialog).getByLabelText('@tag')).toHaveProperty(+ 'value',+ 'bug-fixer'+ );+ expect(within(dialog).getByLabelText('Specific channels')).toHaveProperty(+ 'checked',+ true+ );++ fireEvent.input(within(dialog).getByLabelText('Name'), {+ target: { value: 'Bug resolver' },+ });+ fireEvent.click(+ within(dialog).getByRole('button', { name: 'Save changes' })+ );++ await waitFor(() => {+ expect(agentMocks.update).toHaveBeenCalledWith({+ agentId: 'agent-1',+ avatarUrl: undefined,+ channelIds: ['channel-engineering'],+ channelScope: 'selected',+ defaultModel: Model.sonnet5,+ description: 'Finds and fixes bugs.',+ handle: 'bug-fixer',+ harness: 'in-memory',+ name: 'Bug resolver',+ instructions: 'Fix the root cause.',+ teamId: undefined,+ });+ expect(agentMocks.toastSuccess).toHaveBeenCalledWith('Agent updated');+ expect(screen.queryByRole('dialog')).toBeNull();+ });+ });++ it('lets team members edit without deleting or privatizing another creator agent', () => {+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'team', team_id: 'team-1' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ description: 'Finds and fixes bugs.',+ created_by: 'macro|[email protected]',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'all',+ channel_ids: [],+ },+ ];++ render(() => <Agents />);++ expect(screen.getByRole('button', { name: 'Edit Bug fixer' })).toBeTruthy();+ expect(+ screen.queryByRole('button', { name: 'Delete Bug fixer' })+ ).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));+ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByLabelText('Team')).toHaveProperty(+ 'checked',+ true+ );+ expect(within(dialog).getByLabelText('Private')).toHaveProperty(+ 'disabled',+ true+ );+ expect(+ within(dialog).getByText('Only the agent creator can make it private.')+ ).toBeTruthy();+ });++ it('lets the creator privatize and the team owner delete a team agent', () => {+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'team', team_id: 'team-1' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ description: 'Finds and fixes bugs.',+ created_by: 'macro|[email protected]',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'all',+ channel_ids: [],+ },+ ];++ const view = render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));+ expect(+ within(screen.getByRole('dialog')).getByLabelText('Private')+ ).toHaveProperty('disabled', false);+ view.unmount();++ agentMocks.currentUserId = 'macro|[email protected]';+ agentMocks.isTeamOwner = true;+ render(() => <Agents />);+ expect(+ screen.getByRole('button', { name: 'Delete Bug fixer' })+ ).toBeTruthy();+ });++ it('confirms before deleting a created agent', async () => {+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ description: 'Finds and fixes bugs.',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'selected',+ channel_ids: ['channel-engineering'],+ },+ ];++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Delete Bug fixer' }));++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Delete Bug fixer?')).toBeTruthy();+ expect(agentMocks.delete).not.toHaveBeenCalled();++ fireEvent.click(+ within(dialog).getByRole('button', { name: 'Delete agent' })+ );++ await waitFor(() => {+ expect(agentMocks.delete).toHaveBeenCalledWith({+ agentId: 'agent-1',+ channelIds: ['channel-engineering'],+ });+ expect(agentMocks.toastSuccess).toHaveBeenCalledWith('Agent deleted');+ expect(screen.queryByRole('dialog')).toBeNull();+ });+ });++ it('offers agent configuration without description and only connected harnesses', () => {+ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ const harness = within(dialog).getByLabelText('Harness');++ expect(+ within(dialog).getByRole('button', { name: 'Upload avatar' })+ ).toBeTruthy();+ const avatarInput = dialog.querySelector(+ 'input[type="file"]'+ ) as HTMLInputElement;+ fireEvent.change(avatarInput, {+ target: {+ files: [+ new File(['avatar'], 'agent-avatar.png', { type: 'image/png' }),+ ],+ },+ });+ expect(within(dialog).queryByText('agent-avatar.png')).toBeNull();+ expect(+ within(dialog).getByText('Optional · square images work best')+ ).toBeTruthy();+ expect(within(dialog).getByLabelText('Name')).toBeTruthy();+ expect(within(dialog).getByLabelText('@tag')).toBeTruthy();+ expect(within(dialog).queryByLabelText('Description')).toBeNull();+ expect(within(dialog).getByLabelText('System prompt')).toBeTruthy();+ expect(harness).toHaveProperty('value', 'in-memory');+ expect(within(harness).getAllByRole('option')).toHaveLength(1);+ expect(within(dialog).getByLabelText('Default model')).toBeTruthy();+ expect(+ within(dialog).getByRole('group', { name: 'Channels' })+ ).toBeTruthy();+ expect(within(dialog).getByRole('group', { name: 'Share' })).toBeTruthy();++ fireEvent.click(within(dialog).getByLabelText('Specific channels'));+ const channelSearch =+ within(dialog).getByPlaceholderText('Search channels…');+ fireEvent.input(channelSearch, { target: { value: 'gen' } });+ expect(screen.getByRole('option', { name: 'general' })).toBeTruthy();+ });++ it('explains why team sharing is disabled without a team', () => {+ agentMocks.currentTeam = null;++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ const teamOption = within(dialog).getByLabelText('Team');+ expect(teamOption).toHaveProperty('disabled', true);+ const teamCardClasses = teamOption.closest('label')?.classList;+ expect(teamCardClasses?.contains('cursor-not-allowed')).toBe(true);+ expect(teamCardClasses?.contains('opacity-50')).toBe(true);+ expect(+ within(dialog).getByText(+ 'Team agents need a team owner. Create or join a team in Team settings to enable this option.'+ )+ ).toBeTruthy();+ });++ it('persists creation through the agents API', async () => {+ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ fireEvent.input(within(dialog).getByLabelText('Name'), {+ target: { value: 'Bug fixer' },+ });+ fireEvent.input(within(dialog).getByLabelText('System prompt'), {+ target: { value: 'Fix the root cause and add tests.' },+ });+ fireEvent.click(within(dialog).getByLabelText('Team'));+ fireEvent.click(+ within(dialog).getByRole('button', { name: 'Create agent' })+ );++ await waitFor(() => {+ expect(agentMocks.create).toHaveBeenCalledWith({+ avatarUrl: undefined,+ channelIds: [],+ channelScope: 'all',+ defaultModel: Model.sonnet5,+ handle: 'bug-fixer',+ harness: 'in-memory',+ name: 'Bug fixer',+ instructions: 'Fix the root cause and add tests.',+ teamId: 'team-1',+ });+ expect(agentMocks.toastSuccess).toHaveBeenCalledWith('Agent created');+ expect(screen.queryByRole('dialog')).toBeNull();+ });+ });++ it('offers Cursor and its models when Cursor is connected', () => {+ cursorMocks.status.data = {+ registered: true,+ updatedAt: '2026-08-27T12:00:00Z',+ };++ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));++ const dialog = screen.getByRole('dialog');+ const harness = within(dialog).getByLabelText('Harness');+ expect(within(harness).getAllByRole('option')).toHaveLength(2);++ fireEvent.change(harness, { target: { value: 'cursor' } });+ expect(harness).toHaveProperty('value', 'cursor');++ const defaultModel = within(dialog).getByLabelText('Default model');+ expect(within(defaultModel).getAllByRole('option')).toHaveLength(2);+ expect(+ within(defaultModel).getByRole('option', { name: 'Cursor Small' })+ ).toHaveProperty('selected', true);+ });+});diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxnew file mode 100644index 0000000000..a895c309ac--- /dev/null+++ b/apps/web/src/features/settings/Agents.tsx@@ -0,0 +1,910 @@+import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';+import { toast } from '@core/component/Toast/Toast';+import { MACRO_AGENT_BOT_ID } from '@core/constant/macroAgent';+import { useChannelsContext } from '@core/context/channels';+import { useUserId } from '@core/context/user';+import MacroLogo from '@icon/macro-logo.svg';+import PencilIcon from '@phosphor/pencil-simple.svg';+import PlusIcon from '@phosphor/plus.svg';+import RobotIcon from '@phosphor/robot.svg';+import TrashIcon from '@phosphor/trash.svg';+import UploadIcon from '@phosphor/upload-simple.svg';+import XIcon from '@phosphor/x.svg';+import {+ type CreateAgentParams,+ useAgentsQuery,+ useCreateAgentMutation,+ useDeleteAgentMutation,+ useUpdateAgentMutation,+} from '@queries/agents/agents';+import {+ useCursorApiKeyStatusQuery,+ useCursorModelsQuery,+} from '@queries/auth/cursor-api-key';+import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';+import type { Agent } from '@service-storage/generated/schemas/agent';+import { Avatar, Button, Dialog, Panel } from '@ui';+import { createMemo, createSignal, For, Show } from 'solid-js';+import { botAssignableChannelOptions } from '../channel/Bots/botChannelOptions';+import { canDeleteBot } from '../channel/Bots/botPermissions';+import { ChannelMultiSelect } from '../channel/Bots/ChannelMultiSelect';+import { SettingsCard, SettingsPage, SettingsSection } from './primitives';++type AgentShare = 'Private' | 'Team';+type ChannelMode = 'all' | 'selected';++type AgentSummary = {+ id: string;+ name: string;+ tag: string;+ avatarUrl?: string;+ instructions: string;+ harness: string;+ defaultModel: string;+ channelSummary: string;+ share: AgentShare;+ persistedAgent?: Agent;+ editable?: boolean;+};++type ConnectedHarness = {+ id: string;+ name: string;+ models: readonly HarnessModel[];+};++type HarnessModel = {+ id: string;+ name: string;+};++type ChannelOption = ReturnType<typeof botAssignableChannelOptions>[number];++const IN_MEMORY_HARNESS: ConnectedHarness = {+ id: 'in-memory',+ name: 'In-memory',+ models: [Model.sonnet5, Model.opus5, Model.haiku45, Model.gpt56].map(+ (model) => ({ id: model, name: MODEL_PRETTYNAME[model] })+ ),+};++const MACRO_AGENT: AgentSummary = {+ id: MACRO_AGENT_BOT_ID,+ name: 'Macro',+ tag: 'macro',+ instructions: '',+ harness: 'In-memory',+ defaultModel: MODEL_PRETTYNAME[Model.sonnet5],+ channelSummary: 'All channels',+ share: 'Team',+};++/** Settings page for viewing and creating persistent agents. */+export function Agents() {+ const [creating, setCreating] = createSignal(false);+ const [editingAgent, setEditingAgent] = createSignal<Agent>();+ const [deletingAgent, setDeletingAgent] = createSignal<Agent>();+ const channelsContext = useChannelsContext();+ const currentUserId = useUserId();+ const agentsQuery = useAgentsQuery();+ const createAgentMutation = useCreateAgentMutation();+ const deleteAgentMutation = useDeleteAgentMutation();+ const updateAgentMutation = useUpdateAgentMutation();+ const currentTeamQuery = useCurrentTeamQuery();+ const isTeamOwner = useIsTeamOwner();+ const cursorStatus = useCursorApiKeyStatusQuery();+ const cursorConnected = () => cursorStatus.data?.registered ?? false;+ const cursorModels = useCursorModelsQuery(cursorConnected);+ const connectedHarnesses = (): readonly ConnectedHarness[] => [+ IN_MEMORY_HARNESS,+ ...(cursorConnected()+ ? [+ {+ id: 'cursor',+ name: 'Cursor',+ models: (cursorModels.data?.models ?? []).map((model) => ({+ id: model.id,+ name: model.displayName,+ })),+ },+ ]+ : []),+ ];+ const channelOptions = createMemo(() =>+ botAssignableChannelOptions(channelsContext.channels())+ );+ const currentTeamId = () => currentTeamQuery.data?.team.id;+ const canShareWithTeam = () => currentTeamId() !== undefined;+ const isAgentCreator = (agent: Agent) =>+ agent.bot.created_by === currentUserId();+ const canMakePrivate = (agent: Agent) =>+ agent.bot.owner?.type !== 'team' || isAgentCreator(agent);+ const canDeleteAgent = (agent: Agent) =>+ canDeleteBot(agent.bot, currentUserId(), currentTeamId(), isTeamOwner());+ const agents = createMemo(() =>+ (agentsQuery.data ?? []).map((agent) =>+ summarizeAgent(agent, connectedHarnesses(), channelOptions())+ )+ );+ const teamAgents = createMemo(() => [+ MACRO_AGENT,+ ...agents().filter((agent) => agent.share === 'Team'),+ ]);+ const privateAgents = createMemo(() =>+ agents().filter((agent) => agent.share === 'Private')+ );++ const createAgent = async (agent: CreateAgentParams) => {+ try {+ await createAgentMutation.mutateAsync(agent);+ toast.success('Agent created');+ return true;+ } catch {+ toast.failure('Failed to create agent');+ return false;+ }+ };++ const updateAgent = async (agent: CreateAgentParams) => {+ const current = editingAgent();+ if (!current) return false;++ try {+ await updateAgentMutation.mutateAsync({+ ...agent,+ agentId: current.bot.id,+ ...(current.bot.description+ ? { description: current.bot.description }+ : {}),+ });+ toast.success('Agent updated');+ return true;+ } catch {+ toast.failure('Failed to update agent');+ return false;+ }+ };++ const deleteAgent = async () => {+ const current = deletingAgent();+ if (!current) return;++ try {+ await deleteAgentMutation.mutateAsync({+ agentId: current.bot.id,+ channelIds: current.channel_ids,+ });+ setDeletingAgent(undefined);+ toast.success('Agent deleted');+ } catch {+ toast.failure('Failed to delete agent');+ }+ };++ return (+ <>+ <SettingsPage+ title="Agents"+ description="Create agents with their own identity, instructions, and runtime."+ actions={+ <Button variant="cta" size="sm" onClick={() => setCreating(true)}>+ <PlusIcon />+ Create agent+ </Button>+ }+ >+ <SettingsSection+ title="Team agents"+ description="Agents shared with your team, including Macro."+ >+ <SettingsCard>+ <For each={teamAgents()}>+ {(agent) => (+ <AgentRow+ agent={agent}+ onEdit={+ agent.editable && agent.persistedAgent+ ? () => setEditingAgent(agent.persistedAgent)+ : undefined+ }+ onDelete={+ agent.persistedAgent && canDeleteAgent(agent.persistedAgent)+ ? () => setDeletingAgent(agent.persistedAgent)+ : undefined+ }+ />+ )}+ </For>+ </SettingsCard>+ </SettingsSection>++ <SettingsSection+ title="Private agents"+ description="Agents owned by you rather than your team."+ >+ <SettingsCard>+ <Show+ when={privateAgents().length > 0}+ fallback={+ <p class="px-6 py-4 text-sm text-ink-muted">+ No private agents yet.+ </p>+ }+ >+ <For each={privateAgents()}>+ {(agent) => (+ <AgentRow+ agent={agent}+ onEdit={+ agent.editable && agent.persistedAgent+ ? () => setEditingAgent(agent.persistedAgent)+ : undefined+ }+ onDelete={+ agent.persistedAgent &&+ canDeleteAgent(agent.persistedAgent)+ ? () => setDeletingAgent(agent.persistedAgent)+ : undefined+ }+ />+ )}+ </For>+ </Show>+ <Show when={agentsQuery.isError}>+ <p class="px-6 py-4 text-xs text-negative">+ Could not load your agents. Try refreshing this page.+ </p>+ </Show>+ </SettingsCard>+ </SettingsSection>+ </SettingsPage>++ <Show when={creating()}>+ <AgentDialog+ connectedHarnesses={connectedHarnesses()}+ currentTeamId={currentTeamId()}+ canShareWithTeam={canShareWithTeam()}+ canMakePrivate+ pending={createAgentMutation.isPending}+ onClose={() => setCreating(false)}+ onSave={createAgent}+ />+ </Show>+ <Show when={editingAgent()} keyed>+ {(agent) => (+ <AgentDialog+ agent={agent}+ connectedHarnesses={connectedHarnesses()}+ currentTeamId={currentTeamId()}+ canShareWithTeam={canShareWithTeam()}+ canMakePrivate={canMakePrivate(agent)}+ pending={updateAgentMutation.isPending}+ onClose={() => setEditingAgent(undefined)}+ onSave={updateAgent}+ />+ )}+ </Show>+ <Show when={deletingAgent()} keyed>+ {(agent) => (+ <AgentDeleteDialog+ agentName={agent.bot.name}+ pending={deleteAgentMutation.isPending}+ onClose={() => setDeletingAgent(undefined)}+ onConfirm={() => void deleteAgent()}+ />+ )}+ </Show>+ </>+ );+}++function summarizeAgent(+ agent: Agent,+ harnesses: readonly ConnectedHarness[],+ channels: readonly ChannelOption[]+): AgentSummary {+ const harness = harnesses.find((option) => option.id === agent.harness);+ const model = harness?.models.find(+ (option) => option.id === agent.default_model+ );+ const selectedChannelNames = channels+ .filter((channel) => agent.channel_ids.includes(channel.id))+ .map((channel) => `#${channel.name}`);+ const channelSummary =+ agent.channel_scope === 'all'+ ? 'All channels'+ : selectedChannelNames.length > 0+ ? selectedChannelNames.join(', ')+ : `${agent.channel_ids.length} selected ${agent.channel_ids.length === 1 ? 'channel' : 'channels'}`;++ return {+ id: agent.bot.id,+ name: agent.bot.name,+ tag: agent.bot.handle,+ avatarUrl: agent.bot.avatar_url ?? undefined,+ instructions: agent.instructions,+ harness: harness?.name ?? harnessName(agent.harness),+ defaultModel: model?.name ?? agent.default_model,+ channelSummary,+ share: agent.bot.owner?.type === 'team' ? 'Team' : 'Private',+ persistedAgent: agent,+ editable: true,+ };+}++function harnessName(id: string): string {+ if (id === 'in-memory') return 'In-memory';+ if (id === 'cursor') return 'Cursor';+ return id;+}++function AgentRow(props: {+ agent: AgentSummary;+ onEdit?: () => void;+ onDelete?: () => void;+}) {+ return (+ <div class="flex items-center gap-4 px-6 py-4 mobile:items-start touch:px-4">+ <AgentAvatar agent={props.agent} />+ <div class="min-w-0 flex-1">+ <div class="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">+ <span class="truncate text-sm font-medium text-ink">+ {props.agent.name}+ </span>+ <span class="truncate text-xs text-ink-extra-muted">+ @{props.agent.tag}+ </span>+ <span class="shrink-0 rounded-full border border-edge-muted px-2 py-0.5 text-xxs font-medium uppercase text-ink-extra-muted">+ {props.agent.share}+ </span>+ </div>+ <p class="mt-0.5 text-xs text-ink-extra-muted">+ {props.agent.harness} · {props.agent.defaultModel} ·{' '}+ {props.agent.channelSummary}+ </p>+ </div>+ <div class="flex shrink-0 items-center gap-1">+ <Show when={props.onEdit}>+ {(onEdit) => (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={`Edit ${props.agent.name}`}+ onClick={onEdit()}+ >+ <PencilIcon />+ </Button>+ )}+ </Show>+ <Show when={props.onDelete}>+ {(onDelete) => (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ class="text-negative"+ aria-label={`Delete ${props.agent.name}`}+ onClick={onDelete()}+ >+ <TrashIcon />+ </Button>+ )}+ </Show>+ </div>+ </div>+ );+}++function AgentAvatar(props: { agent: AgentSummary }) {+ return (+ <Avatar size="lg" class="bg-surface text-accent ring ring-edge-muted">+ <Show+ when={props.agent.avatarUrl}+ fallback={+ <Avatar.Fallback>+ <Show+ when={props.agent.id === MACRO_AGENT_BOT_ID}+ fallback={<RobotIcon class="size-5" />}+ >+ <MacroLogo class="size-5" />+ </Show>+ </Avatar.Fallback>+ }+ >+ {(avatarUrl) => (+ <Avatar.Image src={avatarUrl()} alt={`${props.agent.name} avatar`} />+ )}+ </Show>+ </Avatar>+ );+}++function AgentDeleteDialog(props: {+ agentName: string;+ pending: boolean;+ onClose: () => void;+ onConfirm: () => void;+}) {+ return (+ <Dialog+ open+ onOpenChange={(open) => !open && !props.pending && props.onClose()}+ position="center"+ visibleScrim+ class="w-[min(480px,calc(100vw-16px))]"+ >+ <Panel depth={2} class="rounded-xl text-ink">+ <Panel.Header class="px-5 py-3">+ <Dialog.Title class="text-sm font-semibold">+ Delete {props.agentName}?+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-5">+ <Dialog.Description class="text-sm leading-5 text-ink-muted">+ This removes the agent from every channel and permanently deletes+ its configuration. This action cannot be undone.+ </Dialog.Description>+ </Panel.Body>+ <Panel.Footer class="justify-end gap-2 px-5 py-3">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={props.pending}+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="danger"+ size="sm"+ disabled={props.pending}+ onClick={props.onConfirm}+ >+ <TrashIcon />+ {props.pending ? 'Deleting…' : 'Delete agent'}+ </Button>+ </Panel.Footer>+ </Panel>+ </Dialog>+ );+}++function AgentDialog(props: {+ agent?: Agent;+ connectedHarnesses: readonly ConnectedHarness[];+ currentTeamId?: string;+ canShareWithTeam: boolean;+ canMakePrivate: boolean;+ pending: boolean;+ onClose: () => void;+ onSave: (agent: CreateAgentParams) => Promise<boolean>;+}) {+ const [name, setName] = createSignal(props.agent?.bot.name ?? '');+ const [tag, setTag] = createSignal(props.agent?.bot.handle ?? '');+ const [tagEdited, setTagEdited] = createSignal(props.agent !== undefined);+ const [avatarUrl, setAvatarUrl] = createSignal<string | undefined>(+ props.agent?.bot.avatar_url ?? undefined+ );+ const [instructions, setSystemPrompt] = createSignal(+ props.agent?.instructions ?? ''+ );+ const [harnessId, setHarnessId] = createSignal(+ props.agent?.harness ?? props.connectedHarnesses[0]?.id ?? ''+ );+ const selectedHarness = () =>+ props.connectedHarnesses.find((harness) => harness.id === harnessId());+ const [defaultModelId, setDefaultModelId] = createSignal(+ props.agent?.default_model ?? ''+ );+ const selectedDefaultModelId = () =>+ defaultModelId() || selectedHarness()?.models[0]?.id || '';+ const [channelMode, setChannelMode] = createSignal<ChannelMode>(+ props.agent?.channel_scope ?? 'all'+ );+ const [selectedChannelIds, setSelectedChannelIds] = createSignal<string[]>(+ props.agent?.channel_ids ?? []+ );+ const [share, setShare] = createSignal<AgentShare>(+ props.agent?.bot.owner?.type === 'team' ? 'Team' : 'Private'+ );+ let avatarInputRef: HTMLInputElement | undefined;++ const close = () => props.onClose();++ const handleNameInput = (value: string) => {+ setName(value);+ if (!tagEdited()) setTag(slugAgentTag(value));+ };++ const handleHarnessChange = (id: string) => {+ setHarnessId(id);+ const harness = props.connectedHarnesses.find((option) => option.id === id);+ setDefaultModelId(harness?.models[0]?.id ?? '');+ };++ const handleAvatarInput = (file: File | undefined) => {+ if (!file) return;+ const reader = new FileReader();+ reader.addEventListener('load', () => {+ if (typeof reader.result === 'string') setAvatarUrl(reader.result);+ });+ reader.readAsDataURL(file);+ };++ const canCreate = () =>+ !props.pending &&+ name().trim().length > 0 &&+ tag().trim().length > 0 &&+ selectedHarness() !== undefined &&+ selectedDefaultModelId().length > 0 &&+ (channelMode() === 'all' || selectedChannelIds().length > 0) &&+ (share() === 'Private' ? props.canMakePrivate : props.canShareWithTeam);++ const selectedTeamId = () => {+ if (share() === 'Private') return undefined;+ const currentOwner = props.agent?.bot.owner;+ return currentOwner?.type === 'team'+ ? currentOwner.team_id+ : props.currentTeamId;+ };++ const submit = async () => {+ if (!canCreate()) return;++ const saved = await props.onSave({+ avatarUrl: avatarUrl(),+ channelIds: channelMode() === 'all' ? [] : selectedChannelIds(),+ channelScope: channelMode(),+ defaultModel: selectedDefaultModelId(),+ handle: slugAgentTag(tag()),+ harness: selectedHarness()?.id ?? '',+ name: name().trim(),+ instructions: instructions().trim(),+ teamId: selectedTeamId(),+ });+ if (saved) close();+ };++ return (+ <Dialog+ open+ onOpenChange={(open) => !open && close()}+ position="center"+ visibleScrim+ class="w-[min(720px,calc(100vw-16px))]"+ >+ <Panel depth={2} class="max-h-[88vh] rounded-xl text-ink">+ <Panel.Header class="justify-between px-3">+ <Dialog.Title as="span" class="m-0 p-0 text-sm font-medium">+ {props.agent ? 'Edit agent' : 'Create agent'}+ </Dialog.Title>+ <Dialog.CloseButton as={Button} variant="ghost" size="icon-sm">+ <XIcon />+ </Dialog.CloseButton>+ </Panel.Header>++ <Panel.Body class="overflow-y-auto p-5">+ <form+ id="agent-form"+ class="flex flex-col gap-6"+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ >+ <AgentFormSection+ title="Profile"+ description="How this agent appears in channels and mentions."+ >+ <div class="flex items-center gap-3 border-b border-edge-muted pb-4">+ <button+ type="button"+ aria-label="Upload avatar"+ class="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent"+ onClick={() => avatarInputRef?.click()}+ >+ <AgentAvatar+ agent={{+ id: 'draft',+ name: name() || 'Agent',+ tag: tag(),+ avatarUrl: avatarUrl(),+ instructions: '',+ harness: '',+ defaultModel: '',+ channelSummary: '',+ share: share(),+ }}+ />+ </button>+ <div class="min-w-0 flex-1">+ <div class="text-sm font-medium text-ink">Avatar</div>+ <div class="mt-0.5 text-xs text-ink-muted">+ Optional · square images work best+ </div>+ </div>+ <input+ ref={avatarInputRef}+ type="file"+ accept="image/*"+ class="hidden"+ onChange={(event) =>+ handleAvatarInput(event.currentTarget.files?.[0])+ }+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => avatarInputRef?.click()}+ >+ <UploadIcon />+ Upload+ </Button>+ </div>++ <div class="mt-4 grid grid-cols-2 gap-3 mobile:grid-cols-1">+ <label class="flex flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">Name</span>+ <input+ autofocus+ class="settings-input w-full"+ placeholder="Bug fixer"+ value={name()}+ onInput={(event) =>+ handleNameInput(event.currentTarget.value)+ }+ />+ </label>+ <label for="agent-tag" class="flex flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">@tag</span>+ <div class="flex items-center rounded-lg border border-edge-muted px-2 focus-within:border-accent">+ <span class="text-sm text-ink-extra-muted">@</span>+ <input+ id="agent-tag"+ aria-label="@tag"+ class="min-w-0 flex-1 bg-transparent px-1.5 py-2 text-sm text-ink outline-none"+ placeholder="bug-fixer"+ value={tag()}+ onInput={(event) => {+ setTagEdited(true);+ setTag(slugAgentTag(event.currentTarget.value));+ }}+ />+ </div>+ </label>+ </div>+ </AgentFormSection>++ <AgentFormSection+ title="Behavior"+ description="Instructions the agent receives at the start of every conversation."+ >+ <label class="flex flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">System prompt</span>+ <textarea+ rows={5}+ class="settings-input h-auto min-h-30 w-full resize-y px-3 py-2.5 font-mono text-xs leading-5"+ placeholder="You are a bug-fixing agent. Reproduce issues, identify root causes, and make focused, tested fixes…"+ value={instructions()}+ onInput={(event) =>+ setSystemPrompt(event.currentTarget.value)+ }+ />+ </label>+ </AgentFormSection>++ <AgentFormSection+ title="Runtime"+ description="Harnesses and models are limited to those currently connected."+ >+ <div class="grid grid-cols-2 gap-3 mobile:grid-cols-1">+ <label class="flex flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">Harness</span>+ <select+ class="settings-input w-full"+ value={harnessId()}+ onChange={(event) =>+ handleHarnessChange(event.currentTarget.value)+ }+ >+ <For each={props.connectedHarnesses}>+ {(harness) => (+ <option value={harness.id}>{harness.name}</option>+ )}+ </For>+ </select>+ </label>+ <label class="flex flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">+ Default model+ </span>+ <select+ class="settings-input w-full"+ value={selectedDefaultModelId()}+ onChange={(event) =>+ setDefaultModelId(event.currentTarget.value)+ }+ >+ <For each={selectedHarness()?.models ?? []}>+ {(model) => (+ <option+ value={model.id}+ selected={model.id === selectedDefaultModelId()}+ >+ {model.name}+ </option>+ )}+ </For>+ </select>+ </label>+ </div>+ </AgentFormSection>++ <AgentFormSection+ title="Channels"+ description="Choose whether this agent is global or channel-specific."+ >+ <fieldset class="flex flex-col gap-2">+ <legend class="sr-only">Channels</legend>+ <ChoiceRow+ name="agent-channel-mode"+ value="all"+ checked={channelMode() === 'all'}+ title="All channels"+ description="The agent can be mentioned in every channel, like @macro."+ onChange={() => setChannelMode('all')}+ />+ <ChoiceRow+ name="agent-channel-mode"+ value="selected"+ checked={channelMode() === 'selected'}+ title="Specific channels"+ description="Only members of selected channels can use this agent."+ onChange={() => setChannelMode('selected')}+ />+ </fieldset>++ <Show when={channelMode() === 'selected'}>+ <div class="mt-3 border-t border-edge-muted pt-3">+ <ChannelMultiSelect+ channelIds={selectedChannelIds()}+ onChange={setSelectedChannelIds}+ />+ </div>+ </Show>+ </AgentFormSection>++ <AgentFormSection+ title="Share"+ description="Choose who owns and can configure this agent."+ >+ <fieldset class="grid grid-cols-2 gap-2 mobile:grid-cols-1">+ <legend class="sr-only">Share</legend>+ <ChoiceRow+ name="agent-share"+ value="private"+ checked={share() === 'Private'}+ title="Private"+ description={+ props.canMakePrivate+ ? 'Only you can use and manage this agent.'+ : 'Only the agent creator can make it private.'+ }+ disabled={!props.canMakePrivate}+ onChange={() => setShare('Private')}+ />+ <ChoiceRow+ name="agent-share"+ value="team"+ checked={share() === 'Team'}+ title="Team"+ description={+ props.canShareWithTeam+ ? 'Your team can use this agent in shared channels.'+ : 'Create or join a team before sharing agents.'+ }+ disabled={!props.canShareWithTeam}+ onChange={() => setShare('Team')}+ />+ </fieldset>+ <Show when={!props.canShareWithTeam}>+ <p class="mt-3 border-t border-edge-muted pt-3 text-xs text-ink-extra-muted">+ Team agents need a team owner. Create or join a team in Team+ settings to enable this option.+ </p>+ </Show>+ </AgentFormSection>+ </form>+ </Panel.Body>++ <Panel.Footer class="justify-end gap-2 px-3 py-2">+ <Button type="button" variant="ghost" size="sm" onClick={close}>+ Cancel+ </Button>+ <Button+ type="submit"+ form="agent-form"+ variant="cta"+ size="sm"+ disabled={!canCreate()}+ >+ {props.pending+ ? props.agent+ ? 'Saving…'+ : 'Creating…'+ : props.agent+ ? 'Save changes'+ : 'Create agent'}+ </Button>+ </Panel.Footer>+ </Panel>+ </Dialog>+ );+}++function AgentFormSection(props: {+ title: string;+ description: string;+ children: import('solid-js').JSX.Element;+}) {+ return (+ <section>+ <div class="mb-2 px-1">+ <h2 class="text-sm font-semibold text-ink">{props.title}</h2>+ <p class="mt-0.5 text-xs text-ink-muted">{props.description}</p>+ </div>+ <div class="rounded-xl border border-ink/[0.06] bg-surface-2 p-4">+ {props.children}+ </div>+ </section>+ );+}++function ChoiceRow(props: {+ name: string;+ value: string;+ checked: boolean;+ title: string;+ description: string;+ disabled?: boolean;+ onChange: () => void;+}) {+ return (+ <label+ class="flex min-w-0 items-start gap-3 rounded-lg border border-edge-muted p-3 has-checked:border-accent has-checked:bg-accent-bg"+ classList={{+ 'cursor-not-allowed opacity-50': props.disabled,+ 'cursor-pointer': !props.disabled,+ }}+ >+ <input+ type="radio"+ name={props.name}+ value={props.value}+ checked={props.checked}+ disabled={props.disabled}+ onChange={props.onChange}+ aria-label={props.title}+ class="mt-0.5 accent-accent"+ />+ <span class="min-w-0">+ <span class="block text-sm font-medium text-ink">{props.title}</span>+ <span class="mt-0.5 block text-xs text-ink-muted">+ {props.description}+ </span>+ </span>+ </label>+ );+}++function slugAgentTag(value: string): string {+ return value+ .toLowerCase()+ .replace(/^@/, '')+ .replace(/[^a-z0-9_-]+/g, '-')+ .replace(/^-+|-+$/g, '');+}diff --git a/apps/web/src/features/settings/ConnectedAccounts.tsx b/apps/web/src/features/settings/ConnectedAccounts.tsxindex 302711d1a1..75ff79b6f1 100644--- a/apps/web/src/features/settings/ConnectedAccounts.tsx+++ b/apps/web/src/features/settings/ConnectedAccounts.tsx@@ -1,8 +1,6 @@import { ENABLE_EMAIL } from '@core/constant/featureFlags';-import { useCursorAgentsAccess } from '@core/cursor/flag';import { usePipedreamMcpFlag } from '@core/pipedream/flag';import { Show, Suspense } from 'solid-js';-import { CursorCard } from './Cursor';import { EmailCard } from './Email';import { GitHubCard } from './GitHub';import { IntegrationsSection } from './Integrations';@@ -11,12 +9,10 @@ import { SettingsPage, SettingsSection } from './primitives';/*** Consolidated "Connections" page: one card per external account the user can- * link (Gmail, GitHub), then the agent's MCP integrations, then the coding- * agents — so everything Macro is connected to lives in one place.+ * link (Gmail, GitHub), followed by the agent's MCP integrations.*/export function ConnectedAccounts() {const pipedreamMcp = usePipedreamMcpFlag();- const canUseCursor = useCursorAgentsAccess();return (<SettingsPagetitle="Connections"@@ -39,16 +35,6 @@ export function ConnectedAccounts() {<PipedreamIntegrationsSection /></Show></Suspense>- <Show when={canUseCursor()}>- <SettingsSection- title="Coding sessions"- description="Connect a coding agent so Macro can run sessions on your own account."- >- <Suspense>- <CursorCard />- </Suspense>- </SettingsSection>- </Show></SettingsPage>);}diff --git a/apps/web/src/features/settings/Cursor.tsx b/apps/web/src/features/settings/Cursor.tsxdeleted file mode 100644index a238e7beac..0000000000--- a/apps/web/src/features/settings/Cursor.tsx+++ /dev/null@@ -1,169 +0,0 @@-import { toast } from '@core/component/Toast/Toast';-import { ThrownResultError } from '@core/util/result';-import {- useCursorApiKeyStatusQuery,- useCursorModelsQuery,- useDisconnectCursorApiKey,- useSaveCursorApiKey,- useSetCursorDefaultModel,-} from '@queries/auth/cursor-api-key';-import { Button } from '@ui';-import { createSignal, For, Match, Show, Switch } from 'solid-js';-import { ConnectAction, StatusDot } from './integration-ui';-import { IntegrationRow, SettingsCard, SettingsRow } from './primitives';--/** Cursor's key prefix; the server checks this too, and is the authority. */-const CURSOR_KEY_PREFIX = 'crsr_';--/**- * The server's own words for a failure, or `fallback` when it sent none.- *- * Worth the deviation from the fixed-message pattern the other cards use: the- * server distinguishes a key it rejected on shape from a caller it will not- * accept keys from at all, and only it knows which happened.- */-function failureMessage(error: unknown, fallback: string): string {- return (error instanceof ThrownResultError && error.message) || fallback;-}--/**- * Cursor as a Connected-accounts card.- */-export function CursorCard() {- const status = useCursorApiKeyStatusQuery();- const saveKey = useSaveCursorApiKey();- const disconnect = useDisconnectCursorApiKey();-- const [apiKey, setApiKey] = createSignal('');- const registered = () => status.data?.registered ?? false;-- // Only worth fetching once there is a key to ask Cursor through.- const models = useCursorModelsQuery(registered);- const setDefaultModel = useSetCursorDefaultModel();-- const handleModelChange = async (modelId: string) => {- try {- await setDefaultModel.mutateAsync(modelId);- toast.success('Default model updated');- } catch (error) {- toast.failure(failureMessage(error, 'Failed to set your default model'));- }- };-- const handleSave = async () => {- const key = apiKey().trim();- if (!key.startsWith(CURSOR_KEY_PREFIX)) {- toast.failure(`Cursor API keys start with ${CURSOR_KEY_PREFIX}`);- return;- }- try {- await saveKey.mutateAsync(key);- // Cleared on success so the key does not sit in the DOM, and because- // there is nothing to edit afterwards — replacing means pasting again.- setApiKey('');- toast.success('Cursor connected');- } catch (error) {- toast.failure(- failureMessage(error, 'Failed to save your Cursor API key')- );- }- };-- const handleDisconnect = async () => {- try {- await disconnect.mutateAsync();- toast.success('Cursor disconnected');- } catch (error) {- toast.failure(failureMessage(error, 'Failed to disconnect Cursor'));- }- };-- return (- <SettingsCard>- <IntegrationRow- icon={<span class="text-sm font-medium text-ink-muted">Cs</span>}- title="Cursor"- description="Run @cursor coding sessions on your Cursor account."- />-- <SettingsRow- label={- <span class="flex items-center gap-2">- <span>API key</span>- <Show when={registered()}>- <StatusDot state="connected" label="Connected" />- </Show>- </span>- }- description={- <Switch fallback="Paste a key from Cursor's dashboard. Macro stores it encrypted and never shows it again.">- <Match when={registered()}>Stored encrypted.</Match>- </Switch>- }- >- <Show- // The placeholder reads as "no key", which for this card would flash- // the paste-a-key input at someone who has one already.- when={!status.isPlaceholderData}- fallback={<span class="text-xs text-ink-muted">Loading…</span>}- >- <Switch- fallback={- <div class="flex items-center gap-2">- <input- type="password"- autocomplete="off"- class="settings-input ph-no-capture w-56"- placeholder={`${CURSOR_KEY_PREFIX}…`}- value={apiKey()}- onInput={(event) => setApiKey(event.currentTarget.value)}- onKeyDown={(event) => {- if (event.key === 'Enter') void handleSave();- }}- />- <Button- variant="outline"- size="sm"- depth={3}- disabled={apiKey().length === 0 || saveKey.isPending}- onClick={handleSave}- >- Save- </Button>- </div>- }- >- <Match when={registered()}>- <ConnectAction- label="Disconnect"- variant="danger"- onClick={handleDisconnect}- disabled={disconnect.isPending}- />- </Match>- </Switch>- </Show>- </SettingsRow>-- <Show when={registered()}>- <SettingsRow- label="Default model"- description="The model new @cursor sessions start on. You can still switch it per session."- >- <select- class="settings-input w-56"- value={status.data?.defaultModelId ?? ''}- disabled={setDefaultModel.isPending}- onChange={(event) =>- void handleModelChange(event.currentTarget.value)- }- >- <For each={models.data?.models ?? []}>- {(model) => <option value={model.id}>{model.displayName}</option>}- </For>- </select>- </SettingsRow>- </Show>- </SettingsCard>- );-}diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsxnew file mode 100644index 0000000000..d11ef8edd8--- /dev/null+++ b/apps/web/src/features/settings/Harness.test.tsx@@ -0,0 +1,152 @@+/**+ * @vitest-environment jsdom+ */++import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { Harness } from './Harness';++const mocks = vi.hoisted(() => ({+ status: {+ data: {+ registered: false,+ defaultModelId: null as string | null,+ updatedAt: null as string | null,+ },+ isPlaceholderData: false,+ },+ models: {+ data: {+ models: [{ id: 'default-model', displayName: 'Default Model' }],+ },+ },+ save: vi.fn(),+ disconnect: vi.fn(),+ setDefaultModel: vi.fn(),+ toastSuccess: vi.fn(),+ toastFailure: vi.fn(),+}));++vi.mock('@queries/auth/cursor-api-key', () => ({+ useCursorApiKeyStatusQuery: () => mocks.status,+ useSaveCursorApiKey: () => ({+ mutateAsync: mocks.save,+ isPending: false,+ }),+ useDisconnectCursorApiKey: () => ({+ mutateAsync: mocks.disconnect,+ isPending: false,+ }),+ useCursorModelsQuery: () => mocks.models,+ useSetCursorDefaultModel: () => ({+ mutateAsync: mocks.setDefaultModel,+ isPending: false,+ }),+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: {+ success: mocks.toastSuccess,+ failure: mocks.toastFailure,+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.status.data = {+ registered: false,+ defaultModelId: null,+ updatedAt: null,+ };+ mocks.status.isPlaceholderData = false;+ mocks.save.mockResolvedValue(undefined);+ mocks.disconnect.mockResolvedValue(undefined);+});++describe('Harness', () => {+ it('shows the three configurable harness options', () => {+ render(() => <Harness />);++ expect(screen.getByRole('heading', { name: 'In-memory' })).toBeTruthy();+ expect(screen.getByRole('heading', { name: 'Cursor' })).toBeTruthy();+ expect(+ screen.getByRole('heading', { name: 'Bring your own agent' })+ ).toBeTruthy();+ expect(screen.getByText(/This is not a coding harness/)).toBeTruthy();+ });++ it('validates and saves a Cursor API key', async () => {+ render(() => <Harness />);++ const apiKeyInput = screen.getByLabelText('API key');+ const saveButton = screen.getByRole('button', { name: 'Save' });++ expect(apiKeyInput).toHaveProperty('type', 'password');+ expect(saveButton).toHaveProperty('disabled', true);++ fireEvent.input(apiKeyInput, { target: { value: 'not-a-cursor-key' } });+ fireEvent.click(saveButton);++ expect(mocks.save).not.toHaveBeenCalled();+ expect(mocks.toastFailure).toHaveBeenCalledWith(+ 'Cursor API keys start with crsr_'+ );++ fireEvent.input(apiKeyInput, { target: { value: ' crsr_example ' } });+ fireEvent.click(saveButton);++ await waitFor(() => {+ expect(mocks.save).toHaveBeenCalledWith('crsr_example');+ expect(mocks.toastSuccess).toHaveBeenCalledWith('Cursor connected');+ expect(apiKeyInput).toHaveProperty('value', '');+ });+ });++ it('shows connection status, the default model picker, and disconnect for connected Cursor', async () => {+ mocks.status.data = {+ registered: true,+ defaultModelId: null,+ updatedAt: '2026-08-27T12:00:00Z',+ };++ render(() => <Harness />);++ expect(screen.getByText('Connected')).toBeTruthy();+ expect(screen.queryByLabelText('API key')).toBeNull();+ expect(screen.getByText(/does not revoke it in Cursor/)).toBeTruthy();++ fireEvent.change(screen.getByLabelText('Default model'), {+ target: { value: 'default-model' },+ });+ await waitFor(() => {+ expect(mocks.setDefaultModel).toHaveBeenCalledWith('default-model');+ expect(mocks.toastSuccess).toHaveBeenCalledWith('Default model updated');+ });++ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));++ await waitFor(() => {+ expect(mocks.disconnect).toHaveBeenCalledOnce();+ expect(mocks.toastSuccess).toHaveBeenCalledWith('Cursor disconnected');+ });+ });++ it('does not flash the API key form while connection status loads', () => {+ mocks.status.isPlaceholderData = true;++ render(() => <Harness />);++ expect(screen.getByText('Loading…')).toBeTruthy();+ expect(screen.queryByLabelText('API key')).toBeNull();+ });++ it('links the empty BYOA list to the setup documentation', () => {+ render(() => <Harness />);++ expect(screen.getByText('No agents connected')).toBeTruthy();+ expect(screen.getByRole('link', { name: /Setup guide/ })).toHaveProperty(+ 'href',+ 'https://docs.macro.com/AI/bring-your-own'+ );+ });+});diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsxnew file mode 100644index 0000000000..1a5077abe9--- /dev/null+++ b/apps/web/src/features/settings/Harness.tsx@@ -0,0 +1,288 @@+import { toast } from '@core/component/Toast/Toast';+import { ThrownResultError } from '@core/util/result';+import CursorIcon from '@icon/wide-cursor-ide.svg';+import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';+import HardDrivesIcon from '@phosphor/hard-drives.svg';+import TerminalWindowIcon from '@phosphor/terminal-window.svg';+import {+ useCursorApiKeyStatusQuery,+ useCursorModelsQuery,+ useDisconnectCursorApiKey,+ useSaveCursorApiKey,+ useSetCursorDefaultModel,+} from '@queries/auth/cursor-api-key';+import { Button } from '@ui';+import { createSignal, For, type JSX, Show } from 'solid-js';+import { SettingsCard, SettingsPage } from './primitives';++const BYOA_DOCS_URL = 'https://docs.macro.com/AI/bring-your-own';+const CURSOR_KEY_PREFIX = 'crsr_';++type ConnectedAgent = {+ id: string;+ name: string;+ description: string;+};++// Connected-agent data will replace this empty list when BYOA is wired up.+const connectedAgents: ConnectedAgent[] = [];++function failureMessage(error: unknown, fallback: string): string {+ return (error instanceof ThrownResultError && error.message) || fallback;+}++/** Settings UI for choosing and configuring the available agent harnesses. */+export function Harness() {+ const [cursorApiKey, setCursorApiKey] = createSignal('');+ const cursorStatus = useCursorApiKeyStatusQuery();+ const saveCursorApiKey = useSaveCursorApiKey();+ const disconnectCursor = useDisconnectCursorApiKey();+ const cursorRegistered = () => cursorStatus.data?.registered ?? false;++ // Only worth fetching once there is a key to ask Cursor through.+ const cursorModels = useCursorModelsQuery(cursorRegistered);+ const setCursorDefaultModel = useSetCursorDefaultModel();++ const handleCursorModelChange = async (modelId: string) => {+ try {+ await setCursorDefaultModel.mutateAsync(modelId);+ toast.success('Default model updated');+ } catch (error) {+ toast.failure(failureMessage(error, 'Failed to set your default model'));+ }+ };++ const handleSaveCursorApiKey = async () => {+ const apiKey = cursorApiKey().trim();+ if (!apiKey.startsWith(CURSOR_KEY_PREFIX)) {+ toast.failure(`Cursor API keys start with ${CURSOR_KEY_PREFIX}`);+ return;+ }++ try {+ await saveCursorApiKey.mutateAsync(apiKey);+ setCursorApiKey('');+ toast.success('Cursor connected');+ } catch (error) {+ toast.failure(+ failureMessage(error, 'Failed to save your Cursor API key')+ );+ }+ };++ const handleDisconnectCursor = async () => {+ try {+ await disconnectCursor.mutateAsync();+ setCursorApiKey('');+ toast.success('Cursor disconnected');+ } catch (error) {+ toast.failure(failureMessage(error, 'Failed to disconnect Cursor'));+ }+ };++ return (+ <SettingsPage+ title="Harness"+ description="Configure how agents run for your Macro workspace."+ >+ <SettingsCard>+ <section class="flex gap-4 px-6 py-5">+ <HarnessIcon>+ <HardDrivesIcon />+ </HarnessIcon>+ <div class="min-w-0 flex-1">+ <div class="flex items-center gap-2">+ <h2 class="text-sm font-medium text-ink">In-memory</h2>+ <span class="rounded-full bg-success-bg px-2 py-0.5 text-[11px] font-medium text-success">+ Built in+ </span>+ </div>+ <p class="mt-1 text-sm text-ink-muted">+ Macro's in-memory harness runs agents directly in your workspace.+ It is ready to use and does not require any configuration. This is+ not a coding harness.+ </p>+ </div>+ </section>++ <section class="flex gap-4 px-6 py-5">+ <HarnessIcon>+ <CursorIcon />+ </HarnessIcon>+ <div class="min-w-0 flex-1">+ <div class="flex items-center gap-2">+ <h2 class="text-sm font-medium text-ink">Cursor</h2>+ <Show when={cursorRegistered()}>+ <span class="rounded-full bg-success-bg px-2 py-0.5 text-[11px] font-medium text-success">+ Connected+ </span>+ </Show>+ </div>+ <p class="mt-1 text-sm text-ink-muted">+ Use your Cursor account to run agent sessions in Macro.+ </p>++ <Show+ when={!cursorStatus.isPlaceholderData}+ fallback={<p class="mt-4 text-xs text-ink-muted">Loading…</p>}+ >+ <Show+ when={cursorRegistered()}+ fallback={+ <div class="mt-4 flex flex-col gap-1.5">+ <label+ for="cursor-harness-api-key"+ class="text-xs text-ink"+ >+ API key+ </label>+ <div class="flex items-center gap-2 mobile:flex-col mobile:items-stretch">+ <input+ id="cursor-harness-api-key"+ type="password"+ autocomplete="off"+ spellcheck={false}+ class="settings-input ph-no-capture min-w-0 flex-1"+ placeholder={`${CURSOR_KEY_PREFIX}…`}+ value={cursorApiKey()}+ onInput={(event) =>+ setCursorApiKey(event.currentTarget.value)+ }+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ void handleSaveCursorApiKey();+ }+ }}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ depth={3}+ disabled={+ cursorApiKey().trim().length === 0 ||+ saveCursorApiKey.isPending+ }+ onClick={handleSaveCursorApiKey}+ >+ Save+ </Button>+ </div>+ <p class="text-xs text-ink-extra-muted">+ Create an API key in Cursor and paste it here. Macro+ stores it encrypted.+ </p>+ </div>+ }+ >+ <div class="mt-4 flex flex-col gap-1.5">+ <label for="cursor-default-model" class="text-xs text-ink">+ Default model+ </label>+ <select+ id="cursor-default-model"+ class="settings-input w-56"+ value={cursorStatus.data?.defaultModelId ?? ''}+ disabled={setCursorDefaultModel.isPending}+ onChange={(event) =>+ void handleCursorModelChange(event.currentTarget.value)+ }+ >+ <For each={cursorModels.data?.models ?? []}>+ {(model) => (+ <option value={model.id}>{model.displayName}</option>+ )}+ </For>+ </select>+ <p class="text-xs text-ink-extra-muted">+ The model new @cursor sessions start on. You can still+ switch it per session.+ </p>+ </div>++ <div class="mt-4 flex items-center justify-between gap-4 mobile:items-start">+ <p class="text-xs text-ink-extra-muted">+ Disconnecting removes Macro's copy of the key but does not+ revoke it in Cursor.+ </p>+ <Button+ type="button"+ variant="danger"+ size="sm"+ depth={3}+ class="shrink-0"+ disabled={disconnectCursor.isPending}+ onClick={handleDisconnectCursor}+ >+ Disconnect+ </Button>+ </div>+ </Show>+ </Show>+ </div>+ </section>++ <section class="flex gap-4 px-6 py-5">+ <HarnessIcon>+ <TerminalWindowIcon />+ </HarnessIcon>+ <div class="min-w-0 flex-1">+ <div class="flex items-center justify-between gap-4">+ <h2 class="text-sm font-medium text-ink">Bring your own agent</h2>+ <a+ href={BYOA_DOCS_URL}+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"+ >+ Setup guide+ <ArrowUpRightIcon class="size-3.5 opacity-70" />+ </a>+ </div>+ <p class="mt-1 text-sm text-ink-muted">+ Install macrod on your computer to connect Claude or another+ compatible agent.+ </p>++ <div class="mt-5">+ <div class="text-xs font-medium text-ink-muted">+ Connected agents+ </div>+ <For+ each={connectedAgents}+ fallback={+ <div class="flex flex-col items-center py-6 text-center">+ <p class="text-sm text-ink">No agents connected</p>+ <p class="mt-1 text-xs text-ink-extra-muted">+ Agents connected through macrod will appear here.+ </p>+ </div>+ }+ >+ {(agent) => (+ <div class="flex items-center justify-between gap-4 px-4 py-3">+ <div class="min-w-0">+ <p class="truncate text-sm text-ink">{agent.name}</p>+ <p class="truncate text-xs text-ink-extra-muted">+ {agent.description}+ </p>+ </div>+ <span class="text-xs text-success">Connected</span>+ </div>+ )}+ </For>+ </div>+ </div>+ </section>+ </SettingsCard>+ </SettingsPage>+ );+}++function HarnessIcon(props: { children: JSX.Element }) {+ return (+ <div class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-ink/4 text-ink-muted [&_svg]:size-5">+ {props.children}+ </div>+ );+}diff --git a/apps/web/src/features/settings/Settings.tsx b/apps/web/src/features/settings/Settings.tsxindex 6f5b14caf4..1ddffd26f3 100644--- a/apps/web/src/features/settings/Settings.tsx+++ b/apps/web/src/features/settings/Settings.tsx@@ -39,10 +39,12 @@ import {import { Account } from './Account';import { Admin } from './Admin';import { Agent } from './Agent';+import { Agents } from './Agents';import { ApiKeys } from './ApiKeys';import { Appearance } from './Appearance';import { ConnectedAccounts } from './ConnectedAccounts';import { Crm } from './Crm';+import { Harness } from './Harness';import { MobileApp } from './MobileApp';import { Notifications } from './Notifications';import { Shortcuts } from './Shortcuts';@@ -436,6 +438,12 @@ export function SettingsPanel(props: SettingsPanelProps) {<Show when={isCurrentTab('Agent')}><Agent /></Show>+ <Show when={isCurrentTab('Agents')}>+ <Agents />+ </Show>+ <Show when={isCurrentTab('Harness')}>+ <Harness />+ </Show><Show when={isCurrentTab('Bots')}><Suspense><Bots />diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsxindex cb791d057f..c2a93d9456 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx@@ -45,7 +45,14 @@ export function MentionsMenuItem(props: {const icon = () => {switch (props.item.kind) {case 'user':- return <UserIcon id={props.item.id} size="sm" isDeleted={false} />;+ return (+ <UserIcon+ id={props.item.id}+ size="sm"+ isDeleted={false}+ photoUrl={props.item.data.photoUrl}+ />+ );case 'group':return <UsersIcon class="size-4 text-ink-muted" />;diff --git a/apps/web/src/lib/core/component/UserIcon.tsx b/apps/web/src/lib/core/component/UserIcon.tsxindex e6ceb79dfc..28a903a6c9 100644--- a/apps/web/src/lib/core/component/UserIcon.tsx+++ b/apps/web/src/lib/core/component/UserIcon.tsx@@ -196,9 +196,16 @@ export function UserIcon(props: UserIconProps) {size={size()}class={cn('bg-surface text-accent ring ring-edge-muted', props.class)}>- <Avatar.Fallback>- <RobotIcon class="size-[62%]" />- </Avatar.Fallback>+ <Show+ when={props.photoUrl}+ fallback={+ <Avatar.Fallback>+ <RobotIcon class="size-[62%]" />+ </Avatar.Fallback>+ }+ >+ {(photoUrl) => <Avatar.Image src={photoUrl()} alt="" />}+ </Show></Avatar></Match>diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsxindex 927bfcc01d..c9778cc811 100644--- a/apps/web/src/lib/core/constant/SettingsState.tsx+++ b/apps/web/src/lib/core/constant/SettingsState.tsx@@ -27,6 +27,8 @@ export type SettingsTab =| 'Shortcuts'| 'Mobile App'| 'Agent'+ | 'Agents'+ | 'Harness'| 'Bots'| 'Team'| 'Tags'diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx b/apps/web/src/lib/core/constant/settingsTabsConfig.tsxindex a8ecae96d2..ce0b4f79e1 100644--- a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx@@ -6,9 +6,11 @@ import BuildingsIcon from '@phosphor/buildings.svg';import CpuIcon from '@phosphor/cpu.svg';import CreditCardIcon from '@phosphor/credit-card.svg';import DeviceMobileIcon from '@phosphor/device-mobile-speaker.svg';+import HardDrivesIcon from '@phosphor/hard-drives.svg';import KeyIcon from '@phosphor/key.svg';import KeyboardIcon from '@phosphor/keyboard.svg';import PlugIcon from '@phosphor/plug.svg';+import RobotIcon from '@phosphor/robot.svg';import SwatchesIcon from '@phosphor/swatches.svg';import TagIcon from '@phosphor/tag-simple.svg';import UserIconPhosphor from '@phosphor/user.svg';@@ -77,6 +79,13 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [{ tab: 'Bots', label: 'Bots', icon: BotIcon },],},+ {+ label: 'Agents',+ items: [+ { tab: 'Agents', label: 'Agents', icon: RobotIcon },+ { tab: 'Harness', label: 'Harness', icon: HardDrivesIcon },+ ],+ },{label: 'Admin',items: [{ tab: 'Admin', label: 'Debug', icon: BugIcon }],@@ -106,6 +115,8 @@ const SETTINGS_TAB_SLUGS: Record<SettingsTab, string> = {Shortcuts: 'shortcuts','Mobile App': 'mobile-app',Agent: 'mcp-server',+ Agents: 'agents',+ Harness: 'harness',Bots: 'bots',Team: 'team',Tags: 'tags',@@ -188,6 +199,9 @@ export const useSettingsTabAvailable = () => {return ENABLE_APP_STORE_QR_CODE && !isNativeMobilePlatform();case 'Agent':return !isNativeMobilePlatform();+ case 'Harness':+ case 'Agents':+ return true;case 'Bots':return botManagementFlag().enabled;case 'Mobile':diff --git a/apps/web/src/lib/core/user/types.ts b/apps/web/src/lib/core/user/types.tsindex 20d193cd4a..0ac8f6d140 100644--- a/apps/web/src/lib/core/user/types.ts+++ b/apps/web/src/lib/core/user/types.ts@@ -8,6 +8,7 @@ export type IUser = {id: string;email: string;name: string;+ photoUrl?: string;lastInteraction?: DateValue;};diff --git a/apps/web/src/lib/queries/agents/agents.test.tsx b/apps/web/src/lib/queries/agents/agents.test.tsxnew file mode 100644index 0000000000..f019118bfc--- /dev/null+++ b/apps/web/src/lib/queries/agents/agents.test.tsx@@ -0,0 +1,160 @@+/**+ * @vitest-environment jsdom+ */++import { storageServiceClient } from '@service-storage/client';+import type { Agent } from '@service-storage/generated/schemas/agent';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { ok } from 'neverthrow';+import type { JSX } from 'solid-js';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { channelKeys } from '../channel/keys';+import { agentKeys } from './keys';++let testQueryClient: QueryClient;++vi.mock('../client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));++vi.mock('@service-storage/client', () => ({+ storageServiceClient: {+ createAgent: vi.fn(),+ deleteBot: vi.fn(),+ updateAgent: vi.fn(),+ },+}));++import {+ type CreateAgentParams,+ useCreateAgentMutation,+ useDeleteAgentMutation,+ useUpdateAgentMutation,+} from './agents';++const params: CreateAgentParams = {+ channelIds: ['channel-new'],+ channelScope: 'selected',+ defaultModel: 'claude-sonnet-4-5',+ handle: 'bug-fixer',+ harness: 'in-memory',+ name: 'Bug fixer',+ instructions: 'Fix bugs.',+};++function agent(channelIds: string[]): Agent {+ return {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix bugs.',+ harness: 'in-memory',+ default_model: 'claude-sonnet-4-5',+ channel_scope: 'selected',+ channel_ids: channelIds,+ };+}++let dispose: (() => void) | undefined;++function renderHook<T>(factory: () => T): T {+ let hook!: T;+ dispose = render(+ () => (+ <QueryClientProvider client={testQueryClient}>+ {(() => {+ hook = factory();+ return null as unknown as JSX.Element;+ })()}+ </QueryClientProvider>+ ),+ document.body+ );+ return hook;+}++beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+ testQueryClient.clear();+});++describe('agent channel-bot cache invalidation', () => {+ it('invalidates selected channel bot queries after creation', async () => {+ const created = agent(['channel-new', 'channel-other']);+ vi.mocked(storageServiceClient.createAgent).mockResolvedValue(ok(created));+ const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');+ const mutation = renderHook(() => useCreateAgentMutation());++ await mutation.mutateAsync(params);++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: channelKeys.channelBots('channel-new').queryKey,+ });+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: channelKeys.channelBots('channel-other').queryKey,+ });+ });++ it('invalidates old and new channel bot queries after editing', async () => {+ testQueryClient.setQueryData(agentKeys.list.queryKey, [+ agent(['channel-old']),+ ]);+ const updated = agent(['channel-new']);+ vi.mocked(storageServiceClient.updateAgent).mockResolvedValue(ok(updated));+ const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');+ const mutation = renderHook(() => useUpdateAgentMutation());++ await mutation.mutateAsync({ ...params, agentId: 'agent-1' });++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: channelKeys.channelBots('channel-old').queryKey,+ });+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: channelKeys.channelBots('channel-new').queryKey,+ });+ });++ it('removes a deleted agent and invalidates its channel bot queries', async () => {+ const existing = agent(['channel-old']);+ testQueryClient.setQueryData(agentKeys.list.queryKey, [existing]);+ vi.mocked(storageServiceClient.deleteBot).mockResolvedValue(ok(undefined));+ const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');+ const mutation = renderHook(() => useDeleteAgentMutation());++ await mutation.mutateAsync({+ agentId: existing.bot.id,+ channelIds: existing.channel_ids,+ });++ expect(storageServiceClient.deleteBot).toHaveBeenCalledWith({+ bot_id: 'agent-1',+ });+ expect(+ testQueryClient.getQueryData<Agent[]>(agentKeys.list.queryKey)+ ).toEqual([]);+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: channelKeys.channelBots('channel-old').queryKey,+ });+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: channelKeys.participants('channel-old').queryKey,+ });+ });+});diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.tsnew file mode 100644index 0000000000..7ac66841c2--- /dev/null+++ b/apps/web/src/lib/queries/agents/agents.ts@@ -0,0 +1,161 @@+import { throwOnErr } from '@core/util/result';+import { botKeys } from '@queries/bots/keys';+import { channelKeys } from '@queries/channel/keys';+import { queryClient } from '@queries/client';+import { storageServiceClient } from '@service-storage/client';+import type { Agent } from '@service-storage/generated/schemas/agent';+import type { AgentChannelScope } from '@service-storage/generated/schemas/agentChannelScope';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { agentKeys } from './keys';++export type CreateAgentParams = {+ avatarUrl?: string;+ channelIds: string[];+ channelScope: AgentChannelScope;+ defaultModel: string;+ description?: string;+ handle: string;+ harness: string;+ name: string;+ instructions: string;+ teamId?: string;+};++export type UpdateAgentParams = CreateAgentParams & {+ agentId: string;+};++export type DeleteAgentParams = {+ agentId: string;+ channelIds: string[];+};++export function useAgentsQuery() {+ return useQuery(() => ({+ queryKey: agentKeys.list.queryKey,+ queryFn: async (): Promise<Agent[]> =>+ await throwOnErr(() => storageServiceClient.getAgents()),+ }));+}++export function invalidateAgents() {+ return queryClient.invalidateQueries({ queryKey: agentKeys.list.queryKey });+}++function invalidateAgentChannelBots(channelIds: string[]) {+ return Promise.all(+ [...new Set(channelIds)].map((channelId) =>+ queryClient.invalidateQueries({+ queryKey: channelKeys.channelBots(channelId).queryKey,+ })+ )+ );+}++export function useCreateAgentMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (vars: CreateAgentParams) =>+ await throwOnErr(() =>+ storageServiceClient.createAgent({+ avatar_url: vars.avatarUrl,+ channel_ids: vars.channelIds,+ channel_scope: vars.channelScope,+ default_model: vars.defaultModel,+ description: vars.description,+ handle: vars.handle,+ harness: vars.harness,+ name: vars.name,+ instructions: vars.instructions,+ team_id: vars.teamId,+ })+ ),+ onSuccess: async (agent) => {+ queryClient.setQueryData<Agent[]>(+ agentKeys.list.queryKey,+ (current = []) => [...current, agent]+ );+ await invalidateAgentChannelBots(agent.channel_ids);+ },+ onError: (error) => console.error('failed to create agent', error),+ }));+}++export function useUpdateAgentMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (vars: UpdateAgentParams) =>+ await throwOnErr(() =>+ storageServiceClient.updateAgent({+ agent_id: vars.agentId,+ avatar_url: vars.avatarUrl,+ channel_ids: vars.channelIds,+ channel_scope: vars.channelScope,+ default_model: vars.defaultModel,+ description: vars.description,+ handle: vars.handle,+ harness: vars.harness,+ name: vars.name,+ instructions: vars.instructions,+ team_id: vars.teamId,+ })+ ),+ onSuccess: async (updated) => {+ const previousChannelIds =+ queryClient+ .getQueryData<Agent[]>(agentKeys.list.queryKey)+ ?.find((agent) => agent.bot.id === updated.bot.id)?.channel_ids ?? [];+ queryClient.setQueryData<Agent[]>(+ agentKeys.list.queryKey,+ (current = []) =>+ current.map((agent) =>+ agent.bot.id === updated.bot.id ? updated : agent+ )+ );+ await invalidateAgentChannelBots([+ ...previousChannelIds,+ ...updated.channel_ids,+ ]);+ },+ onError: (error) => console.error('failed to update agent', error),+ }));+}++export function useDeleteAgentMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (vars: DeleteAgentParams) =>+ await throwOnErr(() =>+ storageServiceClient.deleteBot({ bot_id: vars.agentId })+ ),+ onSuccess: async (_data, vars) => {+ queryClient.setQueryData<Agent[]>(+ agentKeys.list.queryKey,+ (current = []) =>+ current.filter((agent) => agent.bot.id !== vars.agentId)+ );+ queryClient.removeQueries({+ queryKey: botKeys.detail(vars.agentId).queryKey,+ });+ queryClient.removeQueries({+ queryKey: botKeys.channels(vars.agentId).queryKey,+ });+ queryClient.removeQueries({+ queryKey: botKeys.tokens(vars.agentId).queryKey,+ });++ await Promise.all([+ queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),+ ...[...new Set(vars.channelIds)].flatMap((channelId) => [+ queryClient.invalidateQueries({+ queryKey: channelKeys.channelBots(channelId).queryKey,+ }),+ queryClient.invalidateQueries({+ queryKey: channelKeys.participants(channelId).queryKey,+ }),+ ]),+ ]);+ },+ onError: (error) => console.error('failed to delete agent', error),+ }));+}diff --git a/apps/web/src/lib/queries/agents/keys.ts b/apps/web/src/lib/queries/agents/keys.tsnew file mode 100644index 0000000000..cdbb754da5--- /dev/null+++ b/apps/web/src/lib/queries/agents/keys.ts@@ -0,0 +1,5 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++export const agentKeys = createQueryKeys('agents', {+ list: null,+});diff --git a/apps/web/src/lib/queries/auth/cursor-api-key.ts b/apps/web/src/lib/queries/auth/cursor-api-key.tsindex 5220badbd9..8b552598e8 100644--- a/apps/web/src/lib/queries/auth/cursor-api-key.ts+++ b/apps/web/src/lib/queries/auth/cursor-api-key.ts@@ -57,8 +57,8 @@ export function useSaveCursorApiKey() {/*** Forgets the stored Cursor API key.*- * This does not revoke anything at Cursor; see the button's copy in- * `CursorConnectionSection`.+ * This does not revoke anything at Cursor; the Harness settings copy makes+ * that distinction explicit.*/export function useDisconnectCursorApiKey() {return useMutation(() => ({@@ -73,7 +73,7 @@ export function useDisconnectCursorApiKey() {}/**- * The models the user's Cursor account offers, for the settings dropdown.+ * The models the user's Cursor account offers, for agent configuration.** Enabled only once a key is registered: the endpoint asks Cursor live through* that key, and a keyless account has nothing to list. Kept fresh for a whilediff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.tsindex 73933c995d..db45acb9bf 100644--- a/apps/web/src/lib/queries/team/teams.ts+++ b/apps/web/src/lib/queries/team/teams.ts@@ -66,6 +66,23 @@ export function useIsTeamAdmin(): Accessor<boolean> {};}+/** Reactive boolean: true iff the current user owns the current team. */+export function useIsTeamOwner(): Accessor<boolean> {+ const userId = useUserId();+ const teamQuery = useCurrentTeamQuery();+ return () => {+ const uid = userId();+ if (!uid) return false;+ if (!queryReadyGate(teamQuery)) return false;+ const team = teamQuery.data;+ if (!team) return false;+ return (+ team.members.find((member) => member.user_id === uid)?.role ===+ TeamRole.owner+ );+ };+}+export function invalidateUserTeams() {queryClient.invalidateQueries({queryKey: teamKeys.userTeams.queryKey,diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 4c8b6a8e21..4b4c552021 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -32,6 +32,7 @@ import type { AccessLevel } from './generated/schemas/accessLevel';import type { AddFavoriteRequest } from './generated/schemas/addFavoriteRequest';import type { AddParticipantsRequest } from './generated/schemas/addParticipantsRequest';import type { AddPinRequest } from './generated/schemas/addPinRequest';+import type { Agent } from './generated/schemas/agent';import type { AnchorResponse } from './generated/schemas/anchorResponse';import type { ApiActivity } from './generated/schemas/apiActivity';import type { ApiChannelAttachmentsPage } from './generated/schemas/apiChannelAttachmentsPage';@@ -53,6 +54,7 @@ import {type CloudStorageItemType,CloudStorageItemType as CloudStorageItemTypeMap,} from './generated/schemas/cloudStorageItemType';+import type { CreateAgentRequest } from './generated/schemas/createAgentRequest';import type { CreateChannelRequest } from './generated/schemas/createChannelRequest';import type { CreateChannelResponse } from './generated/schemas/createChannelResponse';import type { CreateChannelScopedBotRequest } from './generated/schemas/createChannelScopedBotRequest';@@ -154,6 +156,7 @@ import type { SoupPage } from './generated/schemas/soupPage';import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';import type { ThreadResponse } from './generated/schemas/threadResponse';import type { TypedSuccessResponse } from './generated/schemas/typedSuccessResponse';+import type { UpdateAgentRequest } from './generated/schemas/updateAgentRequest';import type { UpdateCrmTeamSettingsRequest } from './generated/schemas/updateCrmTeamSettingsRequest';import type { UpdateReminderRequest } from './generated/schemas/updateReminderRequest';import type { UploadExtractFolderHandler200 } from './generated/schemas/uploadExtractFolderHandler200';@@ -281,6 +284,7 @@ export type TaskSimilaritySearchResponse = {};type WithBotId = { bot_id: string };+type WithAgentId = { agent_id: string };type WithChannelId = { channel_id: string };type CreateBotRequest = {@@ -531,6 +535,33 @@ export const storageServiceClient = {).map((result) => result);},+ async getAgents() {+ return (+ await dssFetch<Agent[]>(`/agents`, {+ method: 'GET',+ })+ ).map((result) => result);+ },++ async createAgent(args: CreateAgentRequest) {+ return (+ await dssFetch<Agent>(`/agents`, {+ method: 'POST',+ body: JSON.stringify(args),+ })+ ).map((result) => result);+ },++ async updateAgent(args: WithAgentId & UpdateAgentRequest) {+ const { agent_id, ...request } = args;+ return (+ await dssFetch<Agent>(`/agents/${agent_id}`, {+ method: 'PUT',+ body: JSON.stringify(request),+ })+ ).map((result) => result);+ },+async createBot(args: CreateBotRequest) {return (await dssFetch<Bot>(`/bots`, {diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.tsnew file mode 100644index 0000000000..84d3dce724--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { AgentChannelScope } from './agentChannelScope';+import type { Bot } from './bot';++/**+ * A persisted user- or team-owned AI agent.+ */+export interface Agent {+ /** The bot identity used for mentions and channel participation. */+ bot: Bot;+ /** Selected channel ids. Empty for a global agent. */+ channel_ids: string[];+ /** Whether the agent is global or channel-specific. */+ channel_scope: AgentChannelScope;+ /** Model selected specifically for this agent. */+ default_model: string;+ /** Harness used to run the agent. */+ harness: string;+ /** Instructions supplied to the agent at the start of a conversation. */+ instructions: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentChannelScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentChannelScope.tsnew file mode 100644index 0000000000..63d7dd1268--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentChannelScope.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether an agent is available everywhere or only in selected channels.+ */+export type AgentChannelScope =+ (typeof AgentChannelScope)[keyof typeof AgentChannelScope];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const AgentChannelScope = {+ all: 'all',+ selected: 'selected',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.tsnew file mode 100644index 0000000000..09ee915492--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts@@ -0,0 +1,37 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { AgentChannelScope } from './agentChannelScope';+import type { CreateAgentRequestAvatarUrl } from './createAgentRequestAvatarUrl';+import type { CreateAgentRequestDescription } from './createAgentRequestDescription';+import type { CreateAgentRequestTeamId } from './createAgentRequestTeamId';++/**+ * Request to create a persisted AI agent.+ */+export interface CreateAgentRequest {+ /** Optional avatar URL or data URL. */+ avatar_url?: CreateAgentRequestAvatarUrl;+ /** Selected channels. Must be non-empty only for `selected` scope. */+ channel_ids?: string[];+ /** Whether the agent is global or channel-specific. */+ channel_scope: AgentChannelScope;+ /** Model selected specifically for this agent. */+ default_model: string;+ /** Optional description. */+ description?: CreateAgentRequestDescription;+ /** Stable `@` handle. */+ handle: string;+ /** Harness used to run the agent. */+ harness: string;+ /** Instructions supplied to the agent at the start of a conversation. */+ instructions: string;+ /** Display name. */+ name: string;+ /** Team owner. Omit for a private, user-owned agent. */+ team_id?: CreateAgentRequestTeamId;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestAvatarUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestAvatarUrl.tsnew file mode 100644index 0000000000..959ff5bc1f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestAvatarUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional avatar URL or data URL.+ */+export type CreateAgentRequestAvatarUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestDescription.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestDescription.tsnew file mode 100644index 0000000000..ae0f4c7792--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional description.+ */+export type CreateAgentRequestDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestTeamId.tsnew file mode 100644index 0000000000..e55e07bc8d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequestTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team owner. Omit for a private, user-owned agent.+ */+export type CreateAgentRequestTeamId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 5e46c0dea0..89e985e42a 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -13,6 +13,8 @@ export * from './addFavoriteRequest';export * from './addFavoriteRequestEntityType';export * from './addParticipantsRequest';export * from './addPinRequest';+export * from './agent';+export * from './agentChannelScope';export * from './anchor';export * from './anchorId';export * from './anchorIdOneOf';@@ -297,6 +299,10 @@ export * from './copyDocumentQueryParamsVersionId';export * from './copyDocumentRequest';export * from './copyDocumentRequestVersionId';export * from './copyDocumentResponse';+export * from './createAgentRequest';+export * from './createAgentRequestAvatarUrl';+export * from './createAgentRequestDescription';+export * from './createAgentRequestTeamId';export * from './createBotRequest';export * from './createBotRequestAvatarUrl';export * from './createBotRequestDescription';@@ -1179,6 +1185,10 @@ export * from './typingAction';export * from './unthreadedPdfUuidRequest';export * from './unthreadedPdfUuidRequestOneOf';export * from './unthreadedPdfUuidRequestOneOfAttachmentType';+export * from './updateAgentRequest';+export * from './updateAgentRequestAvatarUrl';+export * from './updateAgentRequestDescription';+export * from './updateAgentRequestTeamId';export * from './updateChannelSharePermission';export * from './updateChannelSharePermissionAccessLevel';export * from './updateCrmTeamSettingsRequest';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.tsnew file mode 100644index 0000000000..1a103d9589--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts@@ -0,0 +1,37 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { AgentChannelScope } from './agentChannelScope';+import type { UpdateAgentRequestAvatarUrl } from './updateAgentRequestAvatarUrl';+import type { UpdateAgentRequestDescription } from './updateAgentRequestDescription';+import type { UpdateAgentRequestTeamId } from './updateAgentRequestTeamId';++/**+ * Request to replace the editable configuration of a persisted AI agent.+ */+export interface UpdateAgentRequest {+ /** Optional avatar URL or data URL. */+ avatar_url?: UpdateAgentRequestAvatarUrl;+ /** Selected channels. Must be non-empty only for `selected` scope. */+ channel_ids?: string[];+ /** Whether the agent is global or channel-specific. */+ channel_scope: AgentChannelScope;+ /** Model selected specifically for this agent. */+ default_model: string;+ /** Optional description. */+ description?: UpdateAgentRequestDescription;+ /** Stable `@` handle. */+ handle: string;+ /** Harness used to run the agent. */+ harness: string;+ /** Instructions supplied to the agent at the start of a conversation. */+ instructions: string;+ /** Display name. */+ name: string;+ /** Team owner. Omit to make the agent private to the caller. */+ team_id?: UpdateAgentRequestTeamId;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestAvatarUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestAvatarUrl.tsnew file mode 100644index 0000000000..c521b86499--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestAvatarUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional avatar URL or data URL.+ */+export type UpdateAgentRequestAvatarUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestDescription.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestDescription.tsnew file mode 100644index 0000000000..45d2ce7072--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional description.+ */+export type UpdateAgentRequestDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestTeamId.tsnew file mode 100644index 0000000000..768753f3c7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequestTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team owner. Omit to make the agent private to the caller.+ */+export type UpdateAgentRequestTeamId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 46c919d5e6..485222958a 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -6,6 +6,234 @@*/import * as zod from 'zod';+/**+ * @summary Handler for `GET /agents`.+ */+export const listAgentsResponseItem = zod+ .object({+ bot: zod+ .object({+ avatar_url: zod.string().nullish().describe('Optional avatar URL.'),+ created_at: zod.iso.datetime({}).describe('Creation timestamp.'),+ created_by: zod+ .string()+ .nullish()+ .describe('User that created this bot.'),+ deleted_at: zod.iso+ .datetime({})+ .nullish()+ .describe('Soft-delete timestamp.'),+ description: zod.string().nullish().describe('Optional description.'),+ handle: zod.string().describe('Stable handle.'),+ has_agent: zod+ .boolean()+ .describe(+ 'Whether mentioning this bot opens a sandboxed coding-agent session.'+ ),+ id: zod.string(),+ kind: zod.enum(['owned', 'system']).describe('Bot kind.'),+ name: zod.string().describe('Display name.'),+ owner: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['user']),+ user_id: zod.string().describe('Owner user id.'),+ })+ .describe('User-owned bot.'),+ zod+ .object({+ team_id: zod.uuid().describe('Owner team id.'),+ type: zod.enum(['team']),+ })+ .describe('Team-owned bot.'),+ ])+ .describe('Bot owner.'),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}).describe('Update timestamp.'),+ })+ .describe(+ 'Bot row.\n\nClients deserialize this, so both derives are used.'+ ),+ channel_ids: zod+ .array(zod.uuid())+ .describe('Selected channel ids. Empty for a global agent.'),+ channel_scope: zod+ .enum(['all', 'selected'])+ .describe(+ 'Whether an agent is available everywhere or only in selected channels.'+ ),+ default_model: zod+ .string()+ .describe('Model selected specifically for this agent.'),+ harness: zod.string().describe('Harness used to run the agent.'),+ instructions: zod+ .string()+ .describe(+ 'Instructions supplied to the agent at the start of a conversation.'+ ),+ })+ .describe('A persisted user- or team-owned AI agent.');+export const listAgentsResponse = zod.array(listAgentsResponseItem);++/**+ * @summary Handler for `POST /agents`.+ */+export const createAgentBody = zod+ .object({+ avatar_url: zod+ .string()+ .nullish()+ .describe('Optional avatar URL or data URL.'),+ channel_ids: zod+ .array(zod.uuid())+ .optional()+ .describe(+ 'Selected channels. Must be non-empty only for `selected` scope.'+ ),+ channel_scope: zod+ .enum(['all', 'selected'])+ .describe(+ 'Whether an agent is available everywhere or only in selected channels.'+ ),+ default_model: zod+ .string()+ .describe('Model selected specifically for this agent.'),+ description: zod.string().nullish().describe('Optional description.'),+ handle: zod.string().describe('Stable `@` handle.'),+ harness: zod.string().describe('Harness used to run the agent.'),+ instructions: zod+ .string()+ .describe(+ 'Instructions supplied to the agent at the start of a conversation.'+ ),+ name: zod.string().describe('Display name.'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('Team owner. Omit for a private, user-owned agent.'),+ })+ .describe('Request to create a persisted AI agent.');++/**+ * @summary Handler for `PUT /agents/{agent_id}`.+ */+export const updateAgentParams = zod.object({+ agent_id: zod.string().describe('Agent bot ID'),+});++export const updateAgentBody = zod+ .object({+ avatar_url: zod+ .string()+ .nullish()+ .describe('Optional avatar URL or data URL.'),+ channel_ids: zod+ .array(zod.uuid())+ .optional()+ .describe(+ 'Selected channels. Must be non-empty only for `selected` scope.'+ ),+ channel_scope: zod+ .enum(['all', 'selected'])+ .describe(+ 'Whether an agent is available everywhere or only in selected channels.'+ ),+ default_model: zod+ .string()+ .describe('Model selected specifically for this agent.'),+ description: zod.string().nullish().describe('Optional description.'),+ handle: zod.string().describe('Stable `@` handle.'),+ harness: zod.string().describe('Harness used to run the agent.'),+ instructions: zod+ .string()+ .describe(+ 'Instructions supplied to the agent at the start of a conversation.'+ ),+ name: zod.string().describe('Display name.'),+ team_id: zod+ .uuid()+ .nullish()+ .describe('Team owner. Omit to make the agent private to the caller.'),+ })+ .describe(+ 'Request to replace the editable configuration of a persisted AI agent.'+ );++export const updateAgentResponse = zod+ .object({+ bot: zod+ .object({+ avatar_url: zod.string().nullish().describe('Optional avatar URL.'),+ created_at: zod.iso.datetime({}).describe('Creation timestamp.'),+ created_by: zod+ .string()+ .nullish()+ .describe('User that created this bot.'),+ deleted_at: zod.iso+ .datetime({})+ .nullish()+ .describe('Soft-delete timestamp.'),+ description: zod.string().nullish().describe('Optional description.'),+ handle: zod.string().describe('Stable handle.'),+ has_agent: zod+ .boolean()+ .describe(+ 'Whether mentioning this bot opens a sandboxed coding-agent session.'+ ),+ id: zod.string(),+ kind: zod.enum(['owned', 'system']).describe('Bot kind.'),+ name: zod.string().describe('Display name.'),+ owner: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['user']),+ user_id: zod.string().describe('Owner user id.'),+ })+ .describe('User-owned bot.'),+ zod+ .object({+ team_id: zod.uuid().describe('Owner team id.'),+ type: zod.enum(['team']),+ })+ .describe('Team-owned bot.'),+ ])+ .describe('Bot owner.'),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}).describe('Update timestamp.'),+ })+ .describe(+ 'Bot row.\n\nClients deserialize this, so both derives are used.'+ ),+ channel_ids: zod+ .array(zod.uuid())+ .describe('Selected channel ids. Empty for a global agent.'),+ channel_scope: zod+ .enum(['all', 'selected'])+ .describe(+ 'Whether an agent is available everywhere or only in selected channels.'+ ),+ default_model: zod+ .string()+ .describe('Model selected specifically for this agent.'),+ harness: zod.string().describe('Harness used to run the agent.'),+ instructions: zod+ .string()+ .describe(+ 'Instructions supplied to the agent at the start of a conversation.'+ ),+ })+ .describe('A persisted user- or team-owned AI agent.');+/*** @summary Deletes a single unthreaded anchor for a documentIf you need to delete a threaded anchor, see the delete comment handlerdiff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 90e9d25dce..75ce6c3709 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -10,6 +10,185 @@"version": "0.1.0"},"paths": {+ "/agents": {+ "get": {+ "tags": ["agents"],+ "summary": "Handler for `GET /agents`.",+ "operationId": "list_agents",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Agent"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["agents"],+ "summary": "Handler for `POST /agents`.",+ "operationId": "create_agent",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateAgentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Agent"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/agents/{agent_id}": {+ "put": {+ "tags": ["agents"],+ "summary": "Handler for `PUT /agents/{agent_id}`.",+ "operationId": "update_agent",+ "parameters": [+ {+ "name": "agent_id",+ "in": "path",+ "description": "Agent bot ID",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/BotId"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateAgentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Agent"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/annotations/anchors": {"delete": {"tags": ["annotations::delete_anchor"],@@ -11726,6 +11905,53 @@}}},+ "Agent": {+ "type": "object",+ "description": "A persisted user- or team-owned AI agent.",+ "required": [+ "bot",+ "instructions",+ "harness",+ "default_model",+ "channel_scope",+ "channel_ids"+ ],+ "properties": {+ "bot": {+ "$ref": "#/components/schemas/Bot",+ "description": "The bot identity used for mentions and channel participation."+ },+ "channel_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Selected channel ids. Empty for a global agent."+ },+ "channel_scope": {+ "$ref": "#/components/schemas/AgentChannelScope",+ "description": "Whether the agent is global or channel-specific."+ },+ "default_model": {+ "type": "string",+ "description": "Model selected specifically for this agent."+ },+ "harness": {+ "type": "string",+ "description": "Harness used to run the agent."+ },+ "instructions": {+ "type": "string",+ "description": "Instructions supplied to the agent at the start of a conversation."+ }+ }+ },+ "AgentChannelScope": {+ "type": "string",+ "description": "Whether an agent is available everywhere or only in selected channels.",+ "enum": ["all", "selected"]+ },"Anchor": {"oneOf": [{@@ -15462,6 +15688,65 @@}}},+ "CreateAgentRequest": {+ "type": "object",+ "description": "Request to create a persisted AI agent.",+ "required": [+ "name",+ "handle",+ "instructions",+ "harness",+ "default_model",+ "channel_scope"+ ],+ "properties": {+ "avatar_url": {+ "type": ["string", "null"],+ "description": "Optional avatar URL or data URL."+ },+ "channel_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Selected channels. Must be non-empty only for `selected` scope."+ },+ "channel_scope": {+ "$ref": "#/components/schemas/AgentChannelScope",+ "description": "Whether the agent is global or channel-specific."+ },+ "default_model": {+ "type": "string",+ "description": "Model selected specifically for this agent."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional description."+ },+ "handle": {+ "type": "string",+ "description": "Stable `@` handle."+ },+ "harness": {+ "type": "string",+ "description": "Harness used to run the agent."+ },+ "instructions": {+ "type": "string",+ "description": "Instructions supplied to the agent at the start of a conversation."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team owner. Omit for a private, user-owned agent."+ }+ }+ },"CreateBotRequest": {"type": "object","description": "Request to create a bot.",@@ -24694,6 +24979,65 @@}]},+ "UpdateAgentRequest": {+ "type": "object",+ "description": "Request to replace the editable configuration of a persisted AI agent.",+ "required": [+ "name",+ "handle",+ "instructions",+ "harness",+ "default_model",+ "channel_scope"+ ],+ "properties": {+ "avatar_url": {+ "type": ["string", "null"],+ "description": "Optional avatar URL or data URL."+ },+ "channel_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Selected channels. Must be non-empty only for `selected` scope."+ },+ "channel_scope": {+ "$ref": "#/components/schemas/AgentChannelScope",+ "description": "Whether the agent is global or channel-specific."+ },+ "default_model": {+ "type": "string",+ "description": "Model selected specifically for this agent."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional description."+ },+ "handle": {+ "type": "string",+ "description": "Stable `@` handle."+ },+ "harness": {+ "type": "string",+ "description": "Harness used to run the agent."+ },+ "instructions": {+ "type": "string",+ "description": "Instructions supplied to the agent at the start of a conversation."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team owner. Omit to make the agent private to the caller."+ }+ }+ },"UpdateChannelSharePermission": {"type": "object","required": ["operation", "channelId"],diff --git a/crates/agent_harness/src/domain/error.rs b/crates/agent_harness/src/domain/error.rsindex 73fc52d707..b255752516 100644--- a/crates/agent_harness/src/domain/error.rs+++ b/crates/agent_harness/src/domain/error.rs@@ -27,7 +27,7 @@ pub enum HarnessError {/// whose session never answers. Closing that needs a way to post a failure/// back to the thread, which [`crate::domain::ports::SessionAnnouncer`]/// does not have — it announces sessions and nothing else.- #[error("connect your Cursor account in Settings → Connections to use @cursor")]+ #[error("connect your Cursor account in Settings → Agents → Harness to use @cursor")]CursorNotConnected,/// The agent would not open an ACP session.#[error("acp handshake failed: {0}")]@@ -71,4 +71,7 @@ pub enum HarnessError {/// Forwarding a command to the session's managing replica failed.#[error("failed to forward an agent session command: {0}")]Forward(rootcause::Report),+ /// A bot's persisted agent runtime configuration could not be loaded.+ #[error("failed to resolve agent runtime configuration: {0}")]+ RuntimeDirectory(rootcause::Report),}diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rsindex bdef7069cb..8c5d7a981e 100644--- a/crates/agent_harness/src/domain/mod.rs+++ b/crates/agent_harness/src/domain/mod.rs@@ -5,3 +5,5 @@ pub mod ports;pub mod sandbox;/// The harness orchestrator: containers, announcements, and trigger commands.pub mod service;+/// Policy for turning broker trigger events into harness work.+pub mod trigger_router;diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex e1e8fc9892..56f32a242b 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -34,6 +34,8 @@ pub struct MentionOrigin {pub struct OpenSession {/// The bot that was mentioned.pub bot_id: BotId,+ /// Runtime configuration resolved for this bot when the trigger arrived.+ pub runtime: AgentRuntimeConfig,/// The mention itself.pub origin: MentionOrigin,}@@ -41,13 +43,9 @@ pub struct OpenSession {/// How a bot's sessions get a runtime — the closed set of first-party/// providers, one name per member.///-/// Derived from the bot rather than stored anywhere: the bot id is the-/// durable fact (on trigger events and session rows), and the kind is a pure-/// function of it, so deriving at each decision site is what keeps the two-/// from drifting. Matching on it is exhaustive on purpose — a new-/// provider becomes a compile error at every decision site instead of a-/// silently wrong `else`. This becomes a bot attribute the day the set-/// stops being closed.+/// Legacy system bots derive this from their stable IDs. User and team agents+/// derive it from their persisted harness slug, which is also copied onto each+/// session so resume and teardown keep routing correctly after a restart.////// A session's instructions are stored on its row whichever kind serves it,/// but only [`Self::InMemory`] reads them today - it builds its system prompt@@ -58,7 +56,7 @@ pub struct OpenSession {/// [`Self::External`] `_meta` on `session/new` for macrod to translate, and/// [`Self::Cursor`] - whose API takes a prompt and nothing more - has to fold/// them into the prompt body's hidden agent-context node.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub enum AgentKind {/// A sandbox this deployment provisions (Daytona, or local Docker when/// a developer has opted in).@@ -87,6 +85,26 @@ impl AgentKind {}}+ /// Resolve a database-backed agent's runtime from its persisted harness.+ #[must_use]+ pub fn from_harness(harness: &str) -> Self {+ match harness {+ "cursor" => Self::Cursor,+ "in-memory" | "macro-inmem" => Self::InMemory,+ _ => Self::External,+ }+ }++ /// Resolve a persisted session's runtime without losing fixed system-bot+ /// identities that predate per-agent harness configuration.+ #[must_use]+ pub fn for_session(bot: BotId, harness: &str) -> Self {+ match Self::of(bot) {+ Self::External => Self::from_harness(harness),+ fixed => fixed,+ }+ }+/// Whether a deployment provisions this kind's runtimes itself.////// Membership is about who provisions, not whether *this* deployment is@@ -98,10 +116,18 @@ impl AgentKind {}}-/// Whether a user belongs to the Macro staff domain - the egress crate's-/// predicate, reused so the harness's staff gates and the proxy's can never-/// disagree about who staff is.-pub(crate) use agent_egress::domain::model::is_macro_staff;+/// Runtime settings used to open one database-backed or fixed agent.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub struct AgentRuntimeConfig {+ /// Which runtime implementation serves the agent.+ pub kind: AgentKind,+ /// Model stamped onto the new session.+ pub model: String,+ /// Harness slug stamped onto the new session.+ pub harness: String,+ /// Configured agent instructions, reserved for a dedicated runtime transport.+ pub instructions: String,+}/// Where a prompt came from, when it came from somewhere the session should/// answer back into.diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rsindex d2ba3f3afe..d419392b1d 100644--- a/crates/agent_harness/src/domain/ports.rs+++ b/crates/agent_harness/src/domain/ports.rs@@ -9,8 +9,8 @@ use macro_user_id::user_id::MacroUserIdStr;use super::error::{HarnessError, Result};use super::model::{- HarnessCommand, PriorChannelMessage, ProvisionedEgress, SandboxEgress, SessionAnnouncement,- SpawnContainer,+ AgentRuntimeConfig, HarnessCommand, PriorChannelMessage, ProvisionedEgress, SandboxEgress,+ SessionAnnouncement, SpawnContainer,};use super::sandbox::SandboxResizeEffect;@@ -54,6 +54,17 @@ impl CommandForwarder for NoPeers {#[cfg(test)]mod test;+/// Resolves the runtime configuration for a bot that may receive agent+/// session triggers.+pub trait AgentRuntimeDirectory: Send + Sync + 'static {+ /// Return a runtime profile for a managed agent, an external profile for a+ /// BYOA bot, or `None` when the bot has no agent configuration.+ fn runtime_for(+ &self,+ bot_id: BotId,+ ) -> impl Future<Output = Result<Option<AgentRuntimeConfig>>> + Send;+}+/// Loads messages preceding a channel-originated agent prompt.pub trait ChannelPromptContext: Send + Sync + 'static {/// Verify that a user who triggered a prompt remains a channel member.diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rsindex 61cc2c0275..fbf5303f26 100644--- a/crates/agent_harness/src/domain/service.rs+++ b/crates/agent_harness/src/domain/service.rs@@ -23,7 +23,7 @@ use tracing::instrument::WithSubscriber as _;use crate::domain::error::{HarnessError, Result};use crate::domain::model::{AgentKind, AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand, HarnessDefaults,- OpenSession, SessionAnnouncement, SpawnContainer, is_macro_staff,+ OpenSession, SessionAnnouncement, SpawnContainer,};use crate::domain::ports::{AgentPromptComposer, ChannelPromptContext, CommandForwarder, ContainerManager,@@ -544,7 +544,7 @@ where.containers.spawn(SpawnContainer {session_id: session.id,- kind: AgentKind::of(session.bot_id),+ kind: AgentKind::for_session(session.bot_id, &session.harness),size: sandbox_size,egress: egress.sandbox,})@@ -692,26 +692,6 @@ where}async fn execute(&self, session_id: AgentSessionId, command: HarnessCommand) -> Result<()> {- match &command {- HarnessCommand::Open(open)- if AgentKind::of(open.bot_id) == AgentKind::Cursor- && !is_macro_staff(&open.origin.sender) =>- {- return Err(AgentSessionError::Forbidden.into());- }- HarnessCommand::Deliver(deliver) => {- let session = self.sessions.get_session(session_id).await?;- if AgentKind::of(session.bot_id) == AgentKind::Cursor- && !deliver.actor.as_ref().is_some_and(is_macro_staff)- {- return Err(AgentSessionError::Forbidden.into());- }- }- HarnessCommand::Open(_)- | HarnessCommand::SetSandboxSize(_)- | HarnessCommand::Delete => {}- }-match command {HarnessCommand::Open(command) => self.open(session_id, command).await,HarnessCommand::Deliver(command) => self.deliver(session_id, command).await,@@ -775,7 +755,7 @@ where// runs in Cursor's cloud, the in-memory bot has no sandbox, and an// external bot provisions its own. For all three, the size is only// recorded below as a preference.- if AgentKind::of(session.bot_id) == AgentKind::SandboxedCoder+ if AgentKind::for_session(session.bot_id, &session.harness) == AgentKind::SandboxedCoder&& effect != SandboxResizeEffect::NoOp{if effect == SandboxResizeEffect::Restart {@@ -812,7 +792,11 @@ whereagent.session.id = tracing::field::Empty,))]async fn open(&self, session_id: AgentSessionId, command: OpenSession) -> Result<()> {- let OpenSession { bot_id, origin } = command;+ let OpenSession {+ bot_id,+ runtime,+ origin,+ } = command;tracing::Span::current().record("agent.session.id", tracing::field::display(session_id));let defaults = self.defaults.for_bot(bot_id);let repo_url = defaults.repo_url.clone();@@ -842,8 +826,8 @@ wherebot_id,thread_id: Some(origin.thread_id),originating_message_id: Some(origin.message_id),- model: defaults.model.clone(),- harness: defaults.harness.clone(),+ model: runtime.model.clone(),+ harness: runtime.harness.clone(),repo_url: Some(repo_url.clone()),// Managed sandboxes run in the path baked into their image.workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),@@ -874,7 +858,7 @@ where.containers.spawn(SpawnContainer {session_id,- kind: AgentKind::of(bot_id),+ kind: runtime.kind,size: sandbox_size,egress: egress.sandbox,})@@ -973,7 +957,7 @@ where// wire.Err(AgentSessionError::Disconnected(_)) => {let session = self.sessions.get_session(session_id).await?;- if AgentKind::of(session.bot_id).is_managed() {+ if AgentKind::for_session(session.bot_id, &session.harness).is_managed() {let container = self.containers.resume(session_id).await?;let mcp_servers = self.resumed_mcp_servers(session_id, &session.owner_id)diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 291ba68017..72d2f5eb52 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -32,8 +32,8 @@ use macro_uuid::Uuid;use super::AgentHarnessService;use crate::domain::error::HarnessError;use crate::domain::model::{- AgentKind, AnnounceOrigin, DeliverAction, HarnessCommand, HarnessDefaults, MentionOrigin,- OpenSession, PriorChannelMessage, SessionDefaults, SpawnContainer,+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, DeliverAction, HarnessCommand, HarnessDefaults,+ MentionOrigin, OpenSession, PriorChannelMessage, SessionDefaults, SpawnContainer,};use crate::domain::ports::{AgentPromptComposer, ChannelPromptContext, ContainerManager as _, NoPeers,@@ -52,14 +52,16 @@ fn sender() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")}-fn staff_sender() -> MacroUserIdStr<'static> {- MacroUserIdStr::try_from_email("[email protected]").expect("a valid staff user id")-}-fn open_command() -> OpenSession {let thread_id = macro_uuid::generate_uuid_v7();OpenSession {bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),+ runtime: AgentRuntimeConfig {+ kind: AgentKind::SandboxedCoder,+ model: "agent-model".to_owned(),+ harness: "opencode".to_owned(),+ instructions: String::new(),+ },origin: MentionOrigin {channel_id: macro_uuid::generate_uuid_v7(),thread_id,@@ -370,6 +372,8 @@ async fn open_creates_announces_and_delivers_the_mention() {assert_eq!(session.acp_session_id, Some(SessionId::new("acp-test")));assert_eq!(session.originating_message_id, Some(origin.message_id));assert_eq!(session.thread_id, Some(origin.thread_id));+ assert_eq!(session.model, "agent-model");+ assert_eq!(session.harness, "opencode");let announced = announcer.announced();assert_eq!(announced.len(), 1);assert_eq!(announced[0].origin_channel_id, origin.channel_id);@@ -447,7 +451,7 @@ async fn composer_failure_stops_open_before_announcement_or_delivery() {}#[tokio::test]-async fn open_sends_prior_messages_only_to_the_agent_prompt() {+async fn open_sends_context_but_not_agent_instructions_to_the_agent_prompt() {let context = vec![PriorChannelMessage {sender: "[email protected]".to_owned(),content: "previous channel message".to_owned(),@@ -457,7 +461,8 @@ async fn open_sends_prior_messages_only_to_the_agent_prompt() {PromptContextMock::with_messages(context.clone()),composer.clone(),);- let command = open_command();+ let mut command = open_command();+ command.runtime.instructions = "Diagnose first.".to_owned();let raw = command.origin.content.clone();let id = AgentSessionId::new();@@ -945,7 +950,9 @@ async fn live_cursor_session() -> ContainerMock {let mut command = open_command();command.bot_id = bot_id::CURSOR_BOT_ID;- command.origin.sender = staff_sender();+ command.runtime.kind = AgentKind::Cursor;+ command.runtime.harness = "cursor".to_owned();+ command.origin.sender = sender();let open = service.execute(id, HarnessCommand::Open(command));let drive = async {loop {@@ -965,24 +972,6 @@ async fn live_cursor_session(container}-#[tokio::test]-async fn a_non_staff_sender_cannot_open_a_cursor_session() {- let (service, _repo, containers, _announcer, _runtimes) = harness();- let mut command = open_command();- command.bot_id = bot_id::CURSOR_BOT_ID;-- let error = service- .execute(AgentSessionId::new(), HarnessCommand::Open(command))- .await- .expect_err("non-staff must not open cursor sessions");-- assert!(matches!(- error,- HarnessError::Session(AgentSessionError::Forbidden)- ));- assert_eq!(containers.spawned(), 0);-}-#[tokio::test]async fn changing_the_model_persists_it_and_tells_the_running_agent() {let (service, repo, containers, _announcer, _runtimes) = harness();@@ -1081,28 +1070,7 @@ async fn a_prompt_through_control_reaches_the_agent_without_announcing() {}#[tokio::test]-async fn a_non_staff_control_event_cannot_drive_a_cursor_session() {- let (service, _repo, containers, _announcer, _runtimes) = harness();- let id = AgentSessionId::new();- let container = live_cursor_session(&service, &containers, id).await;-- let error = service- .control_event(- id,- ControlEvent {- action: AgentAction::prompt("spend cursor credits"),- actor: Some(sender()),- },- )- .await- .expect_err("non-staff must not control cursor sessions");-- assert!(matches!(error, AgentSessionError::Forbidden));- assert_eq!(prompts(&container.agent()).len(), 1);-}--#[tokio::test]-async fn a_staff_control_event_can_drive_a_cursor_session() {+async fn a_user_control_event_can_drive_their_cursor_session() {let (service, _repo, containers, _announcer, _runtimes) = harness();let id = AgentSessionId::new();let container = live_cursor_session(&service, &containers, id).await;@@ -1112,11 +1080,11 @@ async fn a_staff_control_event_can_drive_a_cursor_session() {id,ControlEvent {action: AgentAction::prompt("continue"),- actor: Some(staff_sender()),+ actor: Some(sender()),},).await- .expect("staff may control cursor sessions");+ .expect("the session owner may control cursor sessions");assert_eq!(prompts(&container.agent()).len(), 2);}diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rsnew file mode 100644index 0000000000..32e9488ff8--- /dev/null+++ b/crates/agent_harness/src/domain/trigger_router.rs@@ -0,0 +1,135 @@+//! Decide how agent-session broker events are handled by this deployment.++use agent_session::domain::model::AgentSessionId;+use agent_trigger::domain::broker_events::{+ AgentTriggerTopicEvent, ChannelEventMetadata, ExistingAgentSessionEvent, NewAgentSessionEvent,+};+use bot_id::BotId;++use super::model::{+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand,+ MentionOrigin, OpenSession,+};++/// What one trigger event asks this deployment to do.+#[derive(Debug, Clone)]+pub enum RoutedTrigger {+ /// Run a harness command for the managed bot's session.+ Command(AgentSessionId, HarnessCommand),+ /// Post the chip for a prompt an external bot's runtime delivers itself.+ Announce(AgentSessionId, AnnouncePrompt),+}++/// Why an event yielded no work. Only for logging - none of these are+/// errors, and the consumer commits the offset either way.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Skipped {+ /// The event is another deployment's to act on: an open for a bot whose+ /// runtime opens its own sessions, or managed traffic that is not ours.+ ForeignBot,+ /// The sender is not a user, so there is nobody to own the session.+ NotFromUser,+ /// An event shape this harness does not recognise yet - the trigger's+ /// vocabulary is non-exhaustive on purpose, and unknown shapes are+ /// skipped rather than wedging the partition.+ Unrecognized,+}++/// Bot targeted by a recognized trigger event shape.+#[must_use]+pub fn agent_trigger_bot_id(event: &AgentTriggerTopicEvent) -> Option<BotId> {+ match event {+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {+ Some(mentioned.bot_id)+ }+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) => {+ Some(metadata.bot_id)+ }+ _ => None,+ }+}++/// Route one trigger event: work for this deployment, or a reason it was+/// skipped.+///+/// Opens are only ours when `runtime` resolves to a managed profile. External+/// bots' runtimes open their own sessions over the API. Events for sessions+/// that already exist always carry work: a prompt to deliver when the session+/// is managed here, or just its announcement when the bot's own runtime+/// delivers the prompt.+pub fn route_agent_trigger(+ event: AgentTriggerTopicEvent,+ runtime: Option<AgentRuntimeConfig>,+) -> Result<RoutedTrigger, Skipped> {+ match event {+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {+ let Some(runtime) = runtime.filter(|runtime| runtime.kind.is_managed()) else {+ return Err(Skipped::ForeignBot);+ };+ let message = mentioned.message;+ let sender = message+ .sender+ .as_user()+ .cloned()+ .ok_or(Skipped::NotFromUser)?;+ Ok(RoutedTrigger::Command(+ AgentSessionId::new(),+ HarnessCommand::Open(OpenSession {+ bot_id: mentioned.bot_id,+ runtime,+ origin: MentionOrigin {+ channel_id: message.channel_id,+ // A top-level mention roots its own thread; a mention+ // inside a thread answers into that thread.+ thread_id: message.thread_id.unwrap_or(message.message_id),+ message_id: message.message_id,+ sender,+ content: message.content,+ },+ }),+ ))+ }+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(+ ChannelEventMetadata {+ bot_id,+ session_id,+ kind: _,+ message,+ },+ )) => {+ let origin = AnnounceOrigin {+ channel_id: message.channel_id,+ thread_id: message.thread_id.unwrap_or(message.message_id),+ message_id: message.message_id,+ };+ let kind = runtime+ .as_ref()+ .map_or(AgentKind::External, |runtime| runtime.kind);+ if kind.is_managed() {+ return Ok(RoutedTrigger::Command(+ session_id,+ HarnessCommand::Deliver(DeliverAction::prompt(+ message.content,+ message.sender.as_user().cloned(),+ Some(origin),+ )),+ ));+ }+ let sender = message+ .sender+ .as_user()+ .cloned()+ .ok_or(Skipped::NotFromUser)?;+ Ok(RoutedTrigger::Announce(+ session_id,+ AnnouncePrompt {+ bot_id,+ origin,+ content: message.content,+ sender,+ },+ ))+ }+ _ => Err(Skipped::Unrecognized),+ }+}diff --git a/crates/agent_harness/src/inbound/kafka.rs b/crates/agent_harness/src/inbound/kafka.rsindex 0b533a47c9..7c337d944d 100644--- a/crates/agent_harness/src/inbound/kafka.rs+++ b/crates/agent_harness/src/inbound/kafka.rs@@ -1,165 +1,12 @@-//! Translate `macro.agent_sessions` events into harness commands.+//! Compatibility re-exports for the agent trigger router.//!-//! The trigger service already did the hard part - watching the channel-//! firehose, matching mentions to sessions, dropping the bot's own messages --//! so this adapter only routes: is this event for our bot, and is it an open-//! or a forward? Pure translation, no IO; the consumer loop lives in the-//! service binary.+//! The broker consumer is owned by the service binary. Routing and beta-gate+//! policy live in the domain; this module remains so existing callers do not+//! need to change import paths atomically.-use agent_session::domain::model::AgentSessionId;-use agent_trigger::domain::broker_events::{- AgentTriggerTopicEvent, ChannelEventMetadata, ExistingAgentSessionEvent, NewAgentSessionEvent,-};-use bot_id::BotId;--use crate::domain::model::{- AgentKind, AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand, MentionOrigin,- OpenSession, is_macro_staff,+pub use crate::domain::trigger_router::{+ RoutedTrigger, Skipped, agent_trigger_bot_id, route_agent_trigger,};#[cfg(test)]mod test;--/// What one trigger event asks this deployment to do.-#[derive(Debug, Clone)]-pub enum RoutedTrigger {- /// Run a harness command for the managed bot's session.- Command(AgentSessionId, HarnessCommand),- /// Post the chip for a prompt an external bot's runtime delivers itself.- Announce(AgentSessionId, AnnouncePrompt),-}--/// Why an event yielded no work. Only for logging - none of these are-/// errors, and the consumer commits the offset either way.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum Skipped {- /// The event is another deployment's to act on: an open for a bot whose- /// runtime opens its own sessions, or managed traffic that is not ours.- ForeignBot,- /// The sender is not a user, so there is nobody to own the session.- NotFromUser,- /// An event shape this harness does not recognise yet - the trigger's- /// vocabulary is non-exhaustive on purpose, and unknown shapes are- /// skipped rather than wedging the partition.- Unrecognized,- /// We are in beta and only allow Macro employees to use this new harness system.- NotMacroStaff,-}--/// Route one trigger event: work for this deployment, or a reason it was-/// skipped.-///-/// Opens are only ours when the mentioned bot is one of `our_bots` - external-/// bots' runtimes open their own sessions over the API. A deployment serves-/// the sandboxed coder bot, the in-memory Macro bot when configured, and,-/// when it holds a Cursor API key, the Cursor bot too, which is why this is a-/// set rather than one id. Events for sessions that already exist always-/// carry work: a prompt to deliver when the session is managed here, or just-/// its announcement when the bot's own runtime delivers the prompt.-pub fn route_agent_trigger(- event: AgentTriggerTopicEvent,- our_bots: &[BotId],-) -> Result<RoutedTrigger, Skipped> {- match event {- AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {- // TODO: remove once the beta gate opens. Both managed bots are- // staff-only for the same reason — neither is finished — and a- // Cursor session now runs on the mentioner's own Cursor account,- // so nothing about the credential keeps it restricted.- if mentioned- .message- .sender- .as_user()- .is_some_and(|user| !is_macro_staff(user))- {- return Err(Skipped::NotMacroStaff);- }-- if !our_bots.contains(&mentioned.bot_id) {- return Err(Skipped::ForeignBot);- }- let message = mentioned.message;- let sender = message- .sender- .as_user()- .cloned()- .ok_or(Skipped::NotFromUser)?;- Ok(RoutedTrigger::Command(- AgentSessionId::new(),- HarnessCommand::Open(OpenSession {- bot_id: mentioned.bot_id,- origin: MentionOrigin {- channel_id: message.channel_id,- // A top-level mention roots its own thread; a mention- // inside a thread answers into that thread.- thread_id: message.thread_id.unwrap_or(message.message_id),- message_id: message.message_id,- sender,- content: message.content,- },- }),- ))- }- AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(- ChannelEventMetadata {- bot_id,- session_id,- kind: _,- message,- },- )) => {- let origin = AnnounceOrigin {- channel_id: message.channel_id,- thread_id: message.thread_id.unwrap_or(message.message_id),- message_id: message.message_id,- };- let kind = AgentKind::of(bot_id);- if kind.is_managed() {- // A managed session's prompt is delivered (and announced)- // by the deployment that manages it; anyone else stays out- // of the way entirely.- if !our_bots.contains(&bot_id) {- return Err(Skipped::ForeignBot);- }- // The open gate alone is not enough: the mentioning channel- // holds editor access to the session, so anyone in the- // thread can prompt it. A prompt to a Cursor session is spend- // on its *owner's* Cursor account, by someone who is not- // necessarily the owner - staff only while that is true, and- // a sender that is not a user at all is refused rather than- // waved through.- if kind == AgentKind::Cursor- && !message- .sender- .as_user()- .is_some_and(|user| is_macro_staff(user))- {- return Err(Skipped::NotMacroStaff);- }- return Ok(RoutedTrigger::Command(- session_id,- HarnessCommand::Deliver(DeliverAction::prompt(- message.content,- message.sender.as_user().cloned(),- Some(origin),- )),- ));- }- let sender = message- .sender- .as_user()- .cloned()- .ok_or(Skipped::NotFromUser)?;- Ok(RoutedTrigger::Announce(- session_id,- AnnouncePrompt {- bot_id,- origin,- content: message.content,- sender,- },- ))- }- _ => Err(Skipped::Unrecognized),- }-}diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex 41e0668aa2..fcd57d2df0 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -4,7 +4,7 @@ use agent_trigger::domain::broker_events::{AgentBotMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata, ChannelKind,ExistingAgentSessionEvent, NewAgentSessionEvent,};-use bot_id::MACRO_CODER_BOT_ID;+use bot_id::{BotId, MACRO_CODER_BOT_ID};use channel_sender::ChannelSender;use channels::domain::broker_events::ChannelMessagePostedMetadata;use channels::domain::models::ChannelType;@@ -13,7 +13,22 @@ use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use super::*;-use crate::domain::model::HarnessCommand;+use crate::domain::model::{AgentKind, AgentRuntimeConfig, HarnessCommand};++fn runtime(kind: AgentKind) -> Option<AgentRuntimeConfig> {+ Some(AgentRuntimeConfig {+ kind,+ model: "configured-model".to_owned(),+ harness: match kind {+ AgentKind::Cursor => "cursor",+ AgentKind::InMemory => "in-memory",+ AgentKind::SandboxedCoder => "opencode",+ AgentKind::External => "byoa",+ }+ .to_owned(),+ instructions: "configured instructions".to_owned(),+ })+}fn user() -> MacroUserIdStr<'static> {MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")@@ -56,7 +71,7 @@ fn channel_message(bot: BotId) -> AgentTriggerTopicEvent {fn a_mention_for_our_bot_opens_a_session() {let routed = route_agent_trigger(mentioned(BotId::TEST_A, ChannelSender::new_from_user(user())),- &[BotId::TEST_A],+ runtime(AgentKind::InMemory),).expect("a mention for our bot should yield work");@@ -64,6 +79,9 @@ fn a_mention_for_our_bot_opens_a_session() {panic!("a new-session event should open");};assert_eq!(open.bot_id, BotId::TEST_A);+ assert_eq!(open.runtime.kind, AgentKind::InMemory);+ assert_eq!(open.runtime.model, "configured-model");+ assert_eq!(open.runtime.instructions, "configured instructions");assert_eq!(open.origin.message_id, Uuid::from_u128(2));// A top-level mention roots its own thread.assert_eq!(open.origin.thread_id, Uuid::from_u128(2));@@ -84,7 +102,8 @@ fn a_threaded_mention_answers_into_its_thread() {));let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =- route_agent_trigger(event, &[BotId::TEST_A]).expect("the mention should yield work")+ route_agent_trigger(event, runtime(AgentKind::InMemory))+ .expect("the mention should yield work")else {panic!("a new-session event should open");};@@ -96,7 +115,7 @@ fn a_foreign_bots_open_is_skipped() {assert_eq!(route_agent_trigger(mentioned(BotId::TEST_A, ChannelSender::new_from_user(user())),- &[BotId::TEST_B],+ None,).unwrap_err(),Skipped::ForeignBot@@ -104,11 +123,11 @@ fn a_foreign_bots_open_is_skipped() {}#[test]-fn another_deployments_managed_traffic_is_skipped() {- assert_eq!(- route_agent_trigger(channel_message(MACRO_CODER_BOT_ID), &[BotId::TEST_B]).unwrap_err(),- Skipped::ForeignBot- );+fn an_unresolved_existing_session_is_treated_as_external() {+ assert!(matches!(+ route_agent_trigger(channel_message(MACRO_CODER_BOT_ID), None),+ Ok(RoutedTrigger::Announce(_, _))+ ));}#[test]@@ -116,7 +135,7 @@ fn a_bot_authored_mention_is_skipped() {assert_eq!(route_agent_trigger(mentioned(BotId::TEST_A, ChannelSender::new_from_bot(BotId::TEST_B)),- &[BotId::TEST_A],+ runtime(AgentKind::InMemory),).unwrap_err(),Skipped::NotFromUser@@ -124,23 +143,25 @@ fn a_bot_authored_mention_is_skipped() {}#[test]-fn a_non_staff_mention_is_skipped() {+fn any_user_mention_can_open_a_managed_agent() {let user = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");- assert_eq!(+ assert!(matches!(route_agent_trigger(mentioned(BotId::TEST_A, ChannelSender::new_from_user(user)),- &[BotId::TEST_A],- )- .unwrap_err(),- Skipped::NotMacroStaff- );+ runtime(AgentKind::InMemory),+ ),+ Ok(RoutedTrigger::Command(_, HarnessCommand::Open(_)))+ ));}#[test]fn a_managed_channel_message_forwards_to_its_session() {- let routed = route_agent_trigger(channel_message(MACRO_CODER_BOT_ID), &[MACRO_CODER_BOT_ID])- .expect("a channel event for our bot should yield work");+ let routed = route_agent_trigger(+ channel_message(MACRO_CODER_BOT_ID),+ runtime(AgentKind::SandboxedCoder),+ )+ .expect("a channel event for our bot should yield work");let RoutedTrigger::Command(session_id, HarnessCommand::Deliver(deliver)) = routed else {panic!("a managed existing-session event should deliver");@@ -164,7 +185,7 @@ fn a_managed_channel_message_forwards_to_its_session() {fn an_external_channel_message_announces_only() {// The external bot's own runtime delivers the prompt; this deployment// only posts the chip, whichever bot it manages itself.- let routed = route_agent_trigger(channel_message(BotId::TEST_A), &[MACRO_CODER_BOT_ID])+ let routed = route_agent_trigger(channel_message(BotId::TEST_A), runtime(AgentKind::External)).expect("an external existing-session event should yield work");let RoutedTrigger::Announce(session_id, prompt) = routed else {@@ -189,7 +210,7 @@ fn a_bot_authored_external_channel_message_is_skipped() {},));assert_eq!(- route_agent_trigger(event, &[MACRO_CODER_BOT_ID]).unwrap_err(),+ route_agent_trigger(event, runtime(AgentKind::External)).unwrap_err(),Skipped::NotFromUser);}@@ -203,61 +224,27 @@ fn channel_message_from(bot: BotId, sender: ChannelSender<'static>) -> AgentTrig}))}-/// The open gate alone does not protect an existing Cursor session: the-/// mentioning channel can prompt it, so a non-staff follow-up must be-/// refused there too — it is spend on Macro's Cursor account.#[test]-fn a_non_staff_follow_up_to_a_cursor_session_is_skipped() {- let outsider = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");- assert_eq!(- route_agent_trigger(- channel_message_from(- bot_id::CURSOR_BOT_ID,- ChannelSender::new_from_user(outsider)- ),- &[bot_id::CURSOR_BOT_ID],- )- .unwrap_err(),- Skipped::NotMacroStaff- );- // A sender that is not a user at all fails closed the same way.- assert_eq!(- route_agent_trigger(- channel_message_from(- bot_id::CURSOR_BOT_ID,- ChannelSender::new_from_bot(BotId::TEST_B)- ),- &[bot_id::CURSOR_BOT_ID],- )- .unwrap_err(),- Skipped::NotMacroStaff- );-}--/// Staff follow-ups to a Cursor session deliver like any managed session's.-#[test]-fn a_staff_follow_up_to_a_cursor_session_delivers() {- let routed = route_agent_trigger(- channel_message_from(bot_id::CURSOR_BOT_ID, ChannelSender::new_from_user(user())),- &[bot_id::CURSOR_BOT_ID],- )- .expect("staff follow-up is ours to deliver");+fn any_user_can_follow_up_to_their_cursor_session() {+ let user = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");assert!(matches!(- routed,- RoutedTrigger::Command(_, HarnessCommand::Deliver(_))+ route_agent_trigger(+ channel_message_from(bot_id::CURSOR_BOT_ID, ChannelSender::new_from_user(user)),+ runtime(AgentKind::Cursor),+ ),+ Ok(RoutedTrigger::Command(_, HarnessCommand::Deliver(_)))));}-/// Coder-bot follow-ups keep working for non-staff senders: the staff rule-/// on existing sessions is the Cursor bot's alone.+/// Managed sessions accept follow-ups from channel users regardless of email domain.#[test]-fn a_non_staff_follow_up_to_a_coder_session_still_delivers() {- let outsider = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");+fn any_user_can_follow_up_to_a_coder_session() {+ let user = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");let routed = route_agent_trigger(- channel_message_from(MACRO_CODER_BOT_ID, ChannelSender::new_from_user(outsider)),- &[MACRO_CODER_BOT_ID],+ channel_message_from(MACRO_CODER_BOT_ID, ChannelSender::new_from_user(user)),+ runtime(AgentKind::SandboxedCoder),)- .expect("coder follow-ups are not staff-gated");+ .expect("channel users may follow up");assert!(matches!(routed,RoutedTrigger::Command(_, HarnessCommand::Deliver(_))@@ -271,7 +258,7 @@ fn a_bot_authored_follow_up_to_a_managed_session_still_delivers() {MACRO_CODER_BOT_ID,ChannelSender::new_from_bot(BotId::TEST_B),),- &[MACRO_CODER_BOT_ID],+ runtime(AgentKind::SandboxedCoder),).expect("explicit bot mentions continue to reach managed sessions");diff --git a/crates/agent_harness/src/outbound/routing.rs b/crates/agent_harness/src/outbound/routing.rsindex 21e01d1721..b9af6ee46a 100644--- a/crates/agent_harness/src/outbound/routing.rs+++ b/crates/agent_harness/src/outbound/routing.rs@@ -65,7 +65,8 @@ where}async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {- match AgentKind::of(self.sessions.get(session).await?.bot_id) {+ let row = self.sessions.get(session).await?;+ match AgentKind::for_session(row.bot_id, &row.harness) {AgentKind::Cursor => Ok(RoutedTransport::Cursor(self.cursor.resume(session).await?)),AgentKind::SandboxedCoder | AgentKind::InMemory => Ok(RoutedTransport::Sandbox(self.sandbox.resume(session).await?,@@ -85,7 +86,8 @@ where}async fn teardown(&self, session: AgentSessionId) -> Result<()> {- match AgentKind::of(self.sessions.get(session).await?.bot_id) {+ let row = self.sessions.get(session).await?;+ match AgentKind::for_session(row.bot_id, &row.harness) {AgentKind::Cursor => self.cursor.teardown(session).await,AgentKind::SandboxedCoder | AgentKind::InMemory => self.sandbox.teardown(session).await,AgentKind::External => Err(external_is_unroutable()),@@ -100,7 +102,8 @@ where}async fn resize(&self, session: AgentSessionId, size: SandboxSize) -> Result<()> {- match AgentKind::of(self.sessions.get(session).await?.bot_id) {+ let row = self.sessions.get(session).await?;+ match AgentKind::for_session(row.bot_id, &row.harness) {AgentKind::SandboxedCoder => self.sandbox.resize(session, size).await,AgentKind::Cursor => Err(HarnessError::Container("a cursor session has no sandbox to resize".to_owned(),diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex fbd6d596e5..66e0375df3 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -239,3 +239,20 @@ async fn resume_and_teardown_route_by_the_stored_bot() {assert_eq!(cursor.calls(), ["cursor:resume", "cursor:teardown"]);assert!(sandbox.calls().is_empty());}++#[tokio::test]+async fn a_database_backed_cursor_agent_routes_by_its_stored_harness() {+ let sandbox = TaggedManager::new("sandbox");+ let cursor = TaggedManager::new("cursor");+ let router = RoutedContainerManager::new(+ sandbox.clone(),+ cursor.clone(),+ FixedBotSessions(BotId::TEST_A),+ );++ let session = AgentSessionId::new();+ router.resume(session).await.expect("resume");+ router.teardown(session).await.expect("teardown");+ assert_eq!(cursor.calls(), ["cursor:resume", "cursor:teardown"]);+ assert!(sandbox.calls().is_empty());+}diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.tomlindex 4038e22912..9b2d4ac333 100644--- a/crates/agent_trigger/Cargo.toml+++ b/crates/agent_trigger/Cargo.toml@@ -17,6 +17,7 @@ agent_session = { path = "../agent_session" }ai_usage = { path = "../ai_usage", optional = true }anyhow = { workspace = true }bot_id = { path = "../bot_id" }+bots = { path = "../bots", default-features = false, features = ["ports"] }lexical_client = { path = "../lexical_client", optional = true }channels = { path = "../channels", features = ["ports"] }chrono = { workspace = true }diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rsindex 8a7da20e44..64c9c2a12b 100644--- a/crates/agent_trigger/src/domain/processing.rs+++ b/crates/agent_trigger/src/domain/processing.rs@@ -7,7 +7,8 @@ use macro_event_broker::{EventBrokerError, MacroEvent as _, MacroEventBroker};use super::broker_events::AgentTriggerEventName;use super::service::{- AgentBotLookup, AgentTriggerService, ImplicitTriggerJudge, ReplyDetector, ThreadHistory,+ AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ImplicitTriggerJudge,+ ReplyDetector, TeamMembershipLookup, ThreadHistory,};/// Failure while evaluating or publishing one channel event.@@ -28,14 +29,16 @@ pub enum ProcessChannelEventError {////// Transport adapters retain ownership of decode and offset commit so their/// `kafka.process` span can cover the complete record lifecycle.-pub async fn process_channel_event<Repo, Bots, Replies, Judge, History, Broker>(- trigger: &AgentTriggerService<Repo, Bots, Replies, Judge, History>,+pub async fn process_channel_event<Repo, Bots, Teams, Channels, Replies, Judge, History, Broker>(+ trigger: &AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History>,publisher: &Broker,event: &ChannelMacroEvent,) -> Result<(), ProcessChannelEventError>whereRepo: AgentSessionRepo,Bots: AgentBotLookup,+ Teams: TeamMembershipLookup,+ Channels: ChannelParticipationLookup,Replies: ReplyDetector,Judge: ImplicitTriggerJudge,History: ThreadHistory,diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rsindex e7ce65aafc..eb723c53eb 100644--- a/crates/agent_trigger/src/domain/service.rs+++ b/crates/agent_trigger/src/domain/service.rs@@ -9,9 +9,12 @@ use agent_session::domain::error::Result;use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession};use agent_session::domain::ports::AgentSessionRepo;use bot_id::BotId;+use bots::domain::models::{Agent, AgentChannelScope, Bot, BotKind, BotOwner};use channels::domain::broker_events::ChannelMessagePostedMetadata;use channels::domain::side_effects::bot_mention_ids;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use crate::domain::broker_events::{AgentSessionMacroEvent, ChannelEventMetadata, ChannelKind};@@ -33,8 +36,39 @@ const TRANSCRIPT_CAP: usize = 40;/// Bot facts required to decide whether a mention may start an agent session.#[cfg_attr(test, mockall::automock)]pub trait AgentBotLookup: Send + Sync + 'static {- /// Whether this bot is configured with an agent.- fn has_agent(&self, bot_id: BotId) -> impl Future<Output = Result<bool>> + Send;+ /// Get an active persisted agent by bot id.+ fn get_agent(&self, bot_id: BotId) -> impl Future<Output = Result<Option<Agent>>> + Send;++ /// Get an active bot, including a fixed system bot, by id.+ fn get_bot(&self, bot_id: BotId) -> impl Future<Output = Result<Option<Bot>>> + Send;+}++/// Team-membership facts, for agents shared with their owning team.+///+/// Its own port rather than a bot fact: membership belongs to the teams+/// domain, and the trigger domain only ever asks this one question of it.+#[cfg_attr(test, mockall::automock)]+pub trait TeamMembershipLookup: Send + Sync + 'static {+ /// Check whether a user belongs to a team.+ fn user_has_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> impl Future<Output = Result<bool>> + Send;+}++/// Channel-participation facts, for agents scoped to selected channels.+///+/// Its own port rather than a bot fact: participation belongs to the channels+/// domain, and the trigger domain only ever asks this one question of it.+#[cfg_attr(test, mockall::automock)]+pub trait ChannelParticipationLookup: Send + Sync + 'static {+ /// Check whether a bot is an active channel participant.+ fn bot_active_in_channel(+ &self,+ channel_id: Uuid,+ bot_id: BotId,+ ) -> impl Future<Output = Result<bool>> + Send;}/// Detects whether a message is composed as a quote-reply - a leading@@ -73,26 +107,34 @@ pub trait ImplicitTriggerJudge: Send + Sync + 'static {}/// Looks up the session context for a channel message and evaluates its trigger rule.-pub struct AgentTriggerService<Repo, Bots, Replies, Judge, History> {+pub struct AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History> {sessions: Repo,bots: Bots,+ teams: Teams,+ channels: Channels,replies: Replies,judge: Judge,history: History,}-impl<Repo, Bots, Replies, Judge, History> AgentTriggerService<Repo, Bots, Replies, Judge, History>+impl<Repo, Bots, Teams, Channels, Replies, Judge, History>+ AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, History>whereRepo: AgentSessionRepo,Bots: AgentBotLookup,+ Teams: TeamMembershipLookup,+ Channels: ChannelParticipationLookup,Replies: ReplyDetector,Judge: ImplicitTriggerJudge,History: ThreadHistory,{- /// Creates a trigger service backed by session and bot lookups.+ /// Creates a trigger service backed by session, bot, membership, and+ /// participation lookups.pub const fn new(sessions: Repo,bots: Bots,+ teams: Teams,+ channels: Channels,replies: Replies,judge: Judge,history: History,@@ -100,12 +142,64 @@ whereSelf {sessions,bots,+ teams,+ channels,replies,judge,history,}}+ /// Whether `posted` may address `bot_id` under the bot's current scope.+ ///+ /// System agents are global. Persisted all-channel agents are private to+ /// their owner or shared with their owning team. Selected agents and+ /// legacy agent-backed bots use explicit channel participation.+ async fn agent_is_available(+ &self,+ posted: &ChannelMessagePostedMetadata,+ bot_id: BotId,+ ) -> Result<bool> {+ let Some(caller) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {+ return Ok(false);+ };++ if let Some(agent) = self.bots.get_agent(bot_id).await? {+ if !agent.bot.has_agent {+ return Ok(false);+ }+ return match agent.channel_scope {+ AgentChannelScope::All => match agent.bot.owner {+ Some(BotOwner::User { user_id }) => Ok(user_id == caller.as_ref()),+ Some(BotOwner::Team { team_id }) => {+ self.teams.user_has_team(caller, team_id).await+ }+ None => Ok(false),+ },+ AgentChannelScope::Selected => {+ self.channels+ .bot_active_in_channel(posted.channel_id, bot_id)+ .await+ }+ };+ }++ let Some(bot) = self.bots.get_bot(bot_id).await? else {+ return Ok(false);+ };+ if !bot.has_agent {+ return Ok(false);+ }+ match bot.kind {+ BotKind::System => Ok(true),+ BotKind::Owned => {+ self.channels+ .bot_active_in_channel(posted.channel_id, bot_id)+ .await+ }+ }+ }+/// Evaluates one channel message for every mentioned bot.#[tracing::instrument(err, skip(self, posted), fields(channel_id = %posted.channel_id,@@ -185,8 +279,8 @@ whereChannelSession::CreatedFromThread(session) => Some(session.bot_id),ChannelSession::None => mentioned_bot,};- let has_agent = match bot {- Some(bot_id) => self.bots.has_agent(bot_id).await?,+ let available = match bot {+ Some(bot_id) => self.agent_is_available(posted, bot_id).await?,None => false,};@@ -195,7 +289,7 @@ whereexisting: &existing,mentioned_bot,};- match yield_event(&message, has_agent) {+ match yield_event(&message, available) {AgentSessionEventDecision::Event(event) => {let outcome = match existing {ChannelSession::None => "top_level_mentioned",@@ -236,7 +330,7 @@ where}let mut candidates = Vec::new();for session in self.sessions.find_all_for_thread(thread_id).await? {- if self.bots.has_agent(session.bot_id).await? {+ if self.agent_is_available(posted, session.bot_id).await? {candidates.push(session);}}diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 027a304f90..47483a90a3 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -3,6 +3,7 @@ use super::*;use agent_session::domain::error::AgentSessionError;use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession, SessionStatus};use agent_session::domain::ports::MockAgentSessionRepo;+use bots::domain::models::{Agent, AgentChannelScope, Bot, BotKind, BotOwner};use channel_sender::ChannelSender;use channels::domain::models::{ChannelType, SimpleMention};use chrono::Utc;@@ -28,6 +29,61 @@ fn mention_of(bot: BotId) -> SimpleMention {}}+fn owned_bot(bot_id: BotId, owner: BotOwner) -> Bot {+ Bot {+ id: bot_id,+ kind: BotKind::Owned,+ owner: Some(owner),+ name: format!("Agent {bot_id}"),+ handle: format!("agent-{bot_id}"),+ description: None,+ avatar_url: None,+ created_by: Some(user().as_ref().to_owned()),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ deleted_at: None,+ has_agent: true,+ }+}++fn private_agent(bot_id: BotId) -> Agent {+ agent_with(+ bot_id,+ BotOwner::User {+ user_id: user().as_ref().to_owned(),+ },+ AgentChannelScope::All,+ )+}++fn agent_with(bot_id: BotId, owner: BotOwner, channel_scope: AgentChannelScope) -> Agent {+ Agent {+ bot: owned_bot(bot_id, owner),+ instructions: String::new(),+ harness: "in-memory".to_owned(),+ default_model: "model".to_owned(),+ channel_scope,+ channel_ids: vec![],+ }+}++fn system_bot(bot_id: BotId) -> Bot {+ Bot {+ id: bot_id,+ kind: BotKind::System,+ owner: None,+ name: "System agent".to_owned(),+ handle: "system-agent".to_owned(),+ description: None,+ avatar_url: None,+ created_by: None,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ deleted_at: None,+ has_agent: true,+ }+}+fn message(mentions: Vec<SimpleMention>) -> ChannelMessagePostedMetadata {ChannelMessagePostedMetadata {channel_id: Uuid::from_u128(1),@@ -78,30 +134,59 @@ fn thread_session(id: AgentSessionId, bot_id: BotId) -> AgentSession {type TestService = AgentTriggerService<MockAgentSessionRepo,MockAgentBotLookup,+ MockTeamMembershipLookup,+ MockChannelParticipationLookup,MockReplyDetector,MockImplicitTriggerJudge,MockThreadHistory,>;+/// Mocks holding the three fact ports one test scenario needs. Defaults to no+/// expectations, so any unplanned membership or participation call fails.+struct FactMocks {+ bots: MockAgentBotLookup,+ teams: MockTeamMembershipLookup,+ channels: MockChannelParticipationLookup,+}++impl From<MockAgentBotLookup> for FactMocks {+ fn from(bots: MockAgentBotLookup) -> Self {+ Self {+ bots,+ teams: MockTeamMembershipLookup::new(),+ channels: MockChannelParticipationLookup::new(),+ }+ }+}+/// A service over a thread that reads as empty; tests that care about thread/// context pass their own history with [`service_reading`].fn service(sessions: MockAgentSessionRepo,- bots: MockAgentBotLookup,+ facts: impl Into<FactMocks>,replies: MockReplyDetector,judge: MockImplicitTriggerJudge,) -> TestService {- AgentTriggerService::new(sessions, bots, replies, judge, thread_of(vec![]))+ service_reading(sessions, facts, replies, judge, thread_of(vec![]))}fn service_reading(sessions: MockAgentSessionRepo,- bots: MockAgentBotLookup,+ facts: impl Into<FactMocks>,replies: MockReplyDetector,judge: MockImplicitTriggerJudge,history: MockThreadHistory,) -> TestService {- AgentTriggerService::new(sessions, bots, replies, judge, history)+ let facts = facts.into();+ AgentTriggerService::new(+ sessions,+ facts.bots,+ facts.teams,+ facts.channels,+ replies,+ judge,+ history,+ )}/// A history that reads the given messages for any thread.@@ -132,6 +217,174 @@ fn existing_channel_metadata(metadata}+fn sessions_without_existing() -> MockAgentSessionRepo {+ let mut sessions = MockAgentSessionRepo::new();+ sessions+ .expect_find_for_channel()+ .once()+ .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));+ sessions+}++async fn mention_yields_event(+ posted: &ChannelMessagePostedMetadata,+ facts: impl Into<FactMocks>,+) -> bool {+ let (replies, judge) = no_implicit();+ !service(sessions_without_existing(), facts, replies, judge)+ .evaluate(posted)+ .await+ .expect("evaluate message")+ .is_empty()+}++#[tokio::test]+async fn a_private_global_agent_is_unavailable_to_another_user() {+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);+ posted.sender = ChannelSender::new_from_user(+ MacroUserIdStr::try_from_email("[email protected]").expect("valid user id"),+ );+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));++ assert!(!mention_yields_event(&posted, bots).await);+}++#[tokio::test]+async fn a_bot_authored_mention_cannot_trigger_an_agent() {+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);+ posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);+ let bots = MockAgentBotLookup::new();++ assert!(!mention_yields_event(&posted, bots).await);+}++#[tokio::test]+async fn a_team_global_agent_is_available_to_a_team_member() {+ let team_id = Uuid::from_u128(99);+ let posted = message(vec![mention_of(BotId::TEST_A)]);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent().once().return_once(move |bot_id| {+ Box::pin(async move {+ Ok(Some(agent_with(+ bot_id,+ BotOwner::Team { team_id },+ AgentChannelScope::All,+ )))+ })+ });+ let mut facts = FactMocks::from(bots);+ facts+ .teams+ .expect_user_has_team()+ .with(+ mockall::predicate::eq(user()),+ mockall::predicate::eq(team_id),+ )+ .once()+ .return_once(|_, _| Box::pin(async { Ok(true) }));++ assert!(mention_yields_event(&posted, facts).await);+}++#[tokio::test]+async fn a_team_global_agent_is_unavailable_outside_its_team() {+ let team_id = Uuid::from_u128(99);+ let posted = message(vec![mention_of(BotId::TEST_A)]);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent().once().return_once(move |bot_id| {+ Box::pin(async move {+ Ok(Some(agent_with(+ bot_id,+ BotOwner::Team { team_id },+ AgentChannelScope::All,+ )))+ })+ });+ let mut facts = FactMocks::from(bots);+ facts+ .teams+ .expect_user_has_team()+ .once()+ .return_once(|_, _| Box::pin(async { Ok(false) }));++ assert!(!mention_yields_event(&posted, facts).await);+}++#[tokio::test]+async fn a_selected_agent_requires_active_channel_membership() {+ let posted = message(vec![mention_of(BotId::TEST_A)]);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent().once().return_once(|bot_id| {+ Box::pin(async move {+ Ok(Some(agent_with(+ bot_id,+ BotOwner::User {+ user_id: "macro|[email protected]".to_owned(),+ },+ AgentChannelScope::Selected,+ )))+ })+ });+ let mut facts = FactMocks::from(bots);+ facts+ .channels+ .expect_bot_active_in_channel()+ .with(+ mockall::predicate::eq(posted.channel_id),+ mockall::predicate::eq(BotId::TEST_A),+ )+ .once()+ .return_once(|_, _| Box::pin(async { Ok(false) }));++ assert!(!mention_yields_event(&posted, facts).await);+}++#[tokio::test]+async fn an_active_selected_agent_is_available_to_channel_members() {+ let posted = message(vec![mention_of(BotId::TEST_A)]);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent().once().return_once(|bot_id| {+ Box::pin(async move {+ Ok(Some(agent_with(+ bot_id,+ BotOwner::User {+ user_id: "macro|[email protected]".to_owned(),+ },+ AgentChannelScope::Selected,+ )))+ })+ });+ let mut facts = FactMocks::from(bots);+ facts+ .channels+ .expect_bot_active_in_channel()+ .with(+ mockall::predicate::eq(posted.channel_id),+ mockall::predicate::eq(BotId::TEST_A),+ )+ .once()+ .return_once(|_, _| Box::pin(async { Ok(true) }));++ assert!(mention_yields_event(&posted, facts).await);+}++#[tokio::test]+async fn a_system_agent_is_available_without_channel_membership() {+ let posted = message(vec![mention_of(BotId::TEST_A)]);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .return_once(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot()+ .once()+ .return_once(|bot_id| Box::pin(async move { Ok(Some(system_bot(bot_id))) }));++ assert!(mention_yields_event(&posted, bots).await);+}+#[tokio::test]async fn forwards_a_mentioned_thread_reply_to_its_session() {let posted = message(vec![mention_of(BotId::TEST_A)]);@@ -152,10 +405,10 @@ async fn forwards_a_mentioned_thread_reply_to_its_session() {})});let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()+ bots.expect_get_agent().with(mockall::predicate::eq(BotId::TEST_A)).once()- .return_once(|_| Box::pin(async { Ok(true) }));+ .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));let (replies, judge) = no_implicit();let service = service(sessions, bots, replies, judge);@@ -194,9 +447,9 @@ async fn evaluates_every_mentioned_agent_bot() {.times(2).returning(|_, _| Box::pin(async { Ok(ChannelSession::None) }));let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()+ bots.expect_get_agent().times(2)- .returning(|_| Box::pin(async { Ok(true) }));+ .returning(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));let (replies, judge) = no_implicit();let service = service(sessions, bots, replies, judge);@@ -228,10 +481,10 @@ async fn evaluates_a_repeated_bot_mention_once() {.once().return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()+ bots.expect_get_agent().with(mockall::predicate::eq(BotId::TEST_A)).once()- .return_once(|_| Box::pin(async { Ok(true) }));+ .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));let (replies, judge) = no_implicit();let service = service(sessions, bots, replies, judge);@@ -254,10 +507,14 @@ async fn ignores_a_mentioned_bot_without_an_agent() {.once().return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()+ bots.expect_get_agent()+ .with(mockall::predicate::eq(BotId::TEST_A))+ .once()+ .return_once(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot().with(mockall::predicate::eq(BotId::TEST_A)).once()- .return_once(|_| Box::pin(async { Ok(false) }));+ .return_once(|_| Box::pin(async { Ok(None) }));let (replies, judge) = no_implicit();let service = service(sessions, bots, replies, judge);@@ -286,10 +543,10 @@ async fn deduplicates_a_session_found_for_multiple_mentions() {})});let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()+ bots.expect_get_agent().with(mockall::predicate::eq(BotId::TEST_A)).once()- .return_once(|_| Box::pin(async { Ok(true) }));+ .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));let (replies, judge) = no_implicit();let service = service(sessions, bots, replies, judge);@@ -316,8 +573,8 @@ fn implicit_sessions(found: Vec<AgentSession>) -> MockAgentSessionRepo {fn agent_bots() -> MockAgentBotLookup {let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()- .returning(|_| Box::pin(async { Ok(true) }));+ bots.expect_get_agent()+ .returning(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));bots}@@ -460,14 +717,18 @@ async fn implicit_triggering_skips_sessions_of_agentless_bots() {thread_session(AgentSessionId::TEST_B, BotId::TEST_B),]);let mut bots = MockAgentBotLookup::new();- bots.expect_has_agent()+ bots.expect_get_agent().with(mockall::predicate::eq(BotId::TEST_A)).once()- .return_once(|_| Box::pin(async { Ok(false) }));- bots.expect_has_agent()+ .return_once(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_agent().with(mockall::predicate::eq(BotId::TEST_B)).once()- .return_once(|_| Box::pin(async { Ok(true) }));+ .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));+ bots.expect_get_bot()+ .with(mockall::predicate::eq(BotId::TEST_A))+ .once()+ .return_once(|_| Box::pin(async { Ok(None) }));let service = service(sessions,bots,diff --git a/crates/agent_trigger/src/domain/yield_event.rs b/crates/agent_trigger/src/domain/yield_event.rsindex c395a07368..6cb1473b5e 100644--- a/crates/agent_trigger/src/domain/yield_event.rs+++ b/crates/agent_trigger/src/domain/yield_event.rs@@ -17,8 +17,8 @@ use crate::domain::broker_events::{pub enum NoEventReason {/// No existing session and no mentioned bot identified the target agent.MissingBotContext,- /// The target bot is not configured with an agent.- BotHasNoAgent {+ /// The target bot is not an available agent for this sender and channel.+ BotUnavailable {/// Bot that was evaluated.bot_id: BotId,},@@ -103,19 +103,19 @@ pub enum PotentialTriggerEvent<'a> {/// What to publish for one incoming message.///-/// Existing sessions carry their own bot identity. `has_agent` gates all-/// event production.+/// Existing sessions carry their own bot identity. Current agent availability+/// gates all event production.#[must_use]pub fn yield_event(message: &PotentialTriggerEvent<'_>,- has_agent: bool,+ available: bool,) -> AgentSessionEventDecision {match message {PotentialTriggerEvent::Channel {posted,existing,mentioned_bot,- } => yield_channel_event(posted, existing, *mentioned_bot, has_agent),+ } => yield_channel_event(posted, existing, *mentioned_bot, available),}}@@ -123,7 +123,7 @@ fn yield_channel_event(posted: &ChannelMessagePostedMetadata,existing: &ChannelSession,mentioned_bot: Option<BotId>,- has_agent: bool,+ available: bool,) -> AgentSessionEventDecision {let session_bot = match existing {ChannelSession::CreatedFromThread(session) => session.bot_id,@@ -135,8 +135,8 @@ fn yield_channel_event(},};- if !has_agent {- return AgentSessionEventDecision::NoEvent(NoEventReason::BotHasNoAgent {+ if !available {+ return AgentSessionEventDecision::NoEvent(NoEventReason::BotUnavailable {bot_id: session_bot,});}diff --git a/crates/agent_trigger/src/outbound/bot_repo_agent_lookup.rs b/crates/agent_trigger/src/outbound/bot_repo_agent_lookup.rsnew file mode 100644index 0000000000..9854098702--- /dev/null+++ b/crates/agent_trigger/src/outbound/bot_repo_agent_lookup.rs@@ -0,0 +1,72 @@+//! Adapting the bots repository to the trigger domain's bot-facts port.++use agent_session::domain::error::{AgentSessionError, Result};+use bot_id::BotId;+use bots::domain::models::{Agent, Bot};+use bots::domain::ports::BotRepo;+use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;++use crate::domain::service::{AgentBotLookup, ChannelParticipationLookup, TeamMembershipLookup};++/// Exposes bot repository facts to the agent trigger domain.+///+/// One adapter, three ports: the repository happens to answer all three fact+/// kinds today, so callers clone this into each collaborator slot.+#[derive(Clone)]+pub struct BotRepoAgentLookup<Repo> {+ repo: Repo,+}++impl<Repo> BotRepoAgentLookup<Repo> {+ /// Create a lookup over `repo`.+ pub const fn new(repo: Repo) -> Self {+ Self { repo }+ }+}++impl<Repo> AgentBotLookup for BotRepoAgentLookup<Repo>+where+ Repo: BotRepo,+{+ async fn get_agent(&self, bot_id: BotId) -> Result<Option<Agent>> {+ if bot_id::system_bot(bot_id).is_some() {+ return Ok(None);+ }+ self.repo+ .get_agent(bot_id)+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))+ }++ async fn get_bot(&self, bot_id: BotId) -> Result<Option<Bot>> {+ self.repo+ .get_bot(bot_id)+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))+ }+}++impl<Repo> TeamMembershipLookup for BotRepoAgentLookup<Repo>+where+ Repo: BotRepo,+{+ async fn user_has_team(&self, caller: MacroUserIdStr<'static>, team_id: Uuid) -> Result<bool> {+ self.repo+ .user_has_team(caller, team_id)+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))+ }+}++impl<Repo> ChannelParticipationLookup for BotRepoAgentLookup<Repo>+where+ Repo: BotRepo,+{+ async fn bot_active_in_channel(&self, channel_id: Uuid, bot_id: BotId) -> Result<bool> {+ self.repo+ .bot_active_in_channel(channel_id, bot_id)+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))+ }+}diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rsindex 403e63efac..e3b274a6ba 100644--- a/crates/agent_trigger/src/outbound/mod.rs+++ b/crates/agent_trigger/src/outbound/mod.rs@@ -1,9 +1,11 @@//! Adapters implementing the trigger's implicit-evaluation ports.+mod bot_repo_agent_lookup;mod channel_thread_history;mod fast_model_judge;mod lexical_reply_detector;+pub use bot_repo_agent_lookup::BotRepoAgentLookup;pub use channel_thread_history::ChannelThreadHistory;pub use fast_model_judge::FastModelTriggerJudge;pub use lexical_reply_detector::LexicalReplyDetector;diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.tomlindex 3f21ec8eef..a3428a9fff 100644--- a/crates/bots/Cargo.toml+++ b/crates/bots/Cargo.toml@@ -54,6 +54,7 @@ schemars = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true, optional = true }sqlx = { workspace = true, optional = true }+strum = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true, optional = true }tracing = { workspace = true }diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rsindex 8069eb4d7c..e04ca6775b 100644--- a/crates/bots/src/domain/models.rs+++ b/crates/bots/src/domain/models.rs@@ -156,6 +156,107 @@ impl Bot {}}+/// Whether an agent is available everywhere or only in selected channels.+#[derive(+ Debug,+ Clone,+ Copy,+ PartialEq,+ Eq,+ Serialize,+ Deserialize,+ strum::EnumString,+ strum::IntoStaticStr,+)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum AgentChannelScope {+ /// The agent is available in every channel its owner can use.+ All,+ /// The agent is available only in its persisted channel memberships.+ Selected,+}++impl AgentChannelScope {+ /// Storage representation.+ pub fn as_str(self) -> &'static str {+ self.into()+ }+}++/// A persisted user- or team-owned AI agent.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct Agent {+ /// The bot identity used for mentions and channel participation.+ pub bot: Bot,+ /// Instructions supplied to the agent at the start of a conversation.+ pub instructions: String,+ /// Harness used to run the agent.+ pub harness: String,+ /// Model selected specifically for this agent.+ pub default_model: String,+ /// Whether the agent is global or channel-specific.+ pub channel_scope: AgentChannelScope,+ /// Selected channel ids. Empty for a global agent.+ pub channel_ids: Vec<Uuid>,+}++/// Request to create a persisted AI agent.+#[derive(Debug, Clone, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct CreateAgentRequest {+ /// Team owner. Omit for a private, user-owned agent.+ pub team_id: Option<Uuid>,+ /// Display name.+ pub name: String,+ /// Stable `@` handle.+ pub handle: String,+ /// Optional description.+ pub description: Option<String>,+ /// Optional avatar URL or data URL.+ pub avatar_url: Option<String>,+ /// Instructions supplied to the agent at the start of a conversation.+ pub instructions: String,+ /// Harness used to run the agent.+ pub harness: String,+ /// Model selected specifically for this agent.+ pub default_model: String,+ /// Whether the agent is global or channel-specific.+ pub channel_scope: AgentChannelScope,+ /// Selected channels. Must be non-empty only for `selected` scope.+ #[serde(default)]+ pub channel_ids: Vec<Uuid>,+}++/// Request to replace the editable configuration of a persisted AI agent.+#[derive(Debug, Clone, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct UpdateAgentRequest {+ /// Team owner. Omit to make the agent private to the caller.+ pub team_id: Option<Uuid>,+ /// Display name.+ pub name: String,+ /// Stable `@` handle.+ pub handle: String,+ /// Optional description.+ pub description: Option<String>,+ /// Optional avatar URL or data URL.+ pub avatar_url: Option<String>,+ /// Instructions supplied to the agent at the start of a conversation.+ pub instructions: String,+ /// Harness used to run the agent.+ pub harness: String,+ /// Model selected specifically for this agent.+ pub default_model: String,+ /// Whether the agent is global or channel-specific.+ pub channel_scope: AgentChannelScope,+ /// Selected channels. Must be non-empty only for `selected` scope.+ #[serde(default)]+ pub channel_ids: Vec<Uuid>,+}+/// Channel containing a bot.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rsindex 3fb58c64a5..05bccc6119 100644--- a/crates/bots/src/domain/ports.rs+++ b/crates/bots/src/domain/ports.rs@@ -1,9 +1,10 @@//! Bot ports.use super::models::{- AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotOwner, BotToken,- BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,- CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,+ Agent, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotOwner, BotToken,+ BotTokenCandidate, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,+ CreateBotTokenResponse, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,+ PatchBotRequest, UpdateAgentRequest,};use bot_token::HashedBotToken;use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};@@ -17,6 +18,35 @@ pub trait BotRepo: Send + Sync + 'static {/// Repository error.type Err: Into<anyhow::Error> + Send;+ /// Create an owned agent and its selected channel memberships atomically.+ fn create_agent(+ &self,+ owner: BotOwner,+ created_by: MacroUserIdStr<'static>,+ req: CreateAgentRequest,+ ) -> impl Future<Output = Result<Agent, Self::Err>> + Send;++ /// Replace an owned agent and its selected channel memberships atomically.+ fn update_agent(+ &self,+ bot_id: BotId,+ owner: BotOwner,+ req: UpdateAgentRequest,+ ) -> impl Future<Output = Result<Option<Agent>, Self::Err>> + Send;++ /// List active agents manageable by a caller.+ fn list_manageable_agents(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<Vec<Agent>, Self::Err>> + Send;++ /// Check whether the caller is an active member of every supplied channel.+ fn user_has_channels(+ &self,+ caller: MacroUserIdStr<'static>,+ channel_ids: &[Uuid],+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;+/// Create an owned bot.fn create_owned_bot(&self,@@ -45,6 +75,12 @@ pub trait BotRepo: Send + Sync + 'static {fn get_bot(&self, bot_id: BotId)-> impl Future<Output = Result<Option<Bot>, Self::Err>> + Send;+ /// Get an active persisted agent by bot id.+ fn get_agent(+ &self,+ bot_id: BotId,+ ) -> impl Future<Output = Result<Option<Agent>, Self::Err>> + Send;+/// Check team membership.fn user_has_team(&self,@@ -66,6 +102,13 @@ pub trait BotRepo: Send + Sync + 'static {team_id: Uuid,) -> impl Future<Output = Result<bool, Self::Err>> + Send;+ /// Check whether a user owns a team.+ fn user_owns_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;+/// Patch an active bot.fn patch_bot(&self,@@ -144,6 +187,27 @@ pub trait BotRepo: Send + Sync + 'static {/// Bot service.#[cfg_attr(feature = "test-utils", mockall::automock)]pub trait BotService: Send + Sync + 'static {+ /// Create an agent owned by the caller or a team they administer.+ fn create_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ req: CreateAgentRequest,+ ) -> impl Future<Output = Result<Agent, BotError>> + Send;++ /// Replace the editable configuration of a manageable agent.+ fn update_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ req: UpdateAgentRequest,+ ) -> impl Future<Output = Result<Agent, BotError>> + Send;++ /// List agents manageable by the caller.+ fn list_agents(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<Vec<Agent>, BotError>> + Send;+/// Create a bot owned by the caller or a team they administer.fn create_bot(&self,diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rsindex 877fe101a6..4900e950b8 100644--- a/crates/bots/src/domain/service.rs+++ b/crates/bots/src/domain/service.rs@@ -3,9 +3,10 @@use super::{events::{BotCreatedMetadata, BotDeletedMetadata, BotMacroEvent, BotUpdatedMetadata},models::{- AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotKind, BotOwner,- BotToken, BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest,- CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,+ Agent, AgentChannelScope, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId,+ BotKind, BotOwner, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,+ CreateBotTokenRequest, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,+ PatchBotRequest, UpdateAgentRequest,},ports::{BotError, BotRepo, BotService},tokens,@@ -45,6 +46,100 @@ fn validate_handle(handle: &str) -> Result<(), BotError> {Ok(())}+/// The fields create and update requests share, borrowed for validation so+/// both paths run the exact same checks without repeating the field list.+struct AgentFields<'a> {+ name: &'a str,+ handle: &'a str,+ harness: &'a str,+ default_model: &'a str,+ channel_scope: AgentChannelScope,+ channel_ids: &'a [Uuid],+}++impl<'a> From<&'a CreateAgentRequest> for AgentFields<'a> {+ fn from(req: &'a CreateAgentRequest) -> Self {+ Self {+ name: &req.name,+ handle: &req.handle,+ harness: &req.harness,+ default_model: &req.default_model,+ channel_scope: req.channel_scope,+ channel_ids: &req.channel_ids,+ }+ }+}++impl<'a> From<&'a UpdateAgentRequest> for AgentFields<'a> {+ fn from(req: &'a UpdateAgentRequest) -> Self {+ Self {+ name: &req.name,+ handle: &req.handle,+ harness: &req.harness,+ default_model: &req.default_model,+ channel_scope: req.channel_scope,+ channel_ids: &req.channel_ids,+ }+ }+}++fn validate_agent_fields(+ AgentFields {+ name,+ handle,+ harness,+ default_model,+ channel_scope,+ channel_ids,+ }: AgentFields<'_>,+) -> Result<(), BotError> {+ validate_handle(handle)?;+ if name.trim().is_empty() {+ return Err(BotError::BadRequest(+ "agent name must not be empty".to_string(),+ ));+ }+ if harness.trim().is_empty() {+ return Err(BotError::BadRequest(+ "agent harness must not be empty".to_string(),+ ));+ }+ if default_model.trim().is_empty() {+ return Err(BotError::BadRequest(+ "agent default model must not be empty".to_string(),+ ));+ }++ match channel_scope {+ AgentChannelScope::All if !channel_ids.is_empty() => Err(BotError::BadRequest(+ "global agents must not include channel ids".to_string(),+ )),+ AgentChannelScope::Selected if channel_ids.is_empty() => Err(BotError::BadRequest(+ "channel-specific agents require at least one channel".to_string(),+ )),+ AgentChannelScope::Selected+ if channel_ids+ .iter()+ .collect::<std::collections::HashSet<_>>()+ .len()+ != channel_ids.len() =>+ {+ Err(BotError::BadRequest(+ "agent channel ids must be unique".to_string(),+ ))+ }+ _ => Ok(()),+ }+}++fn validate_agent_request(req: &CreateAgentRequest) -> Result<(), BotError> {+ validate_agent_fields(req.into())+}++fn validate_update_agent_request(req: &UpdateAgentRequest) -> Result<(), BotError> {+ validate_agent_fields(req.into())+}+fn token_candidate_is_valid(candidate: &BotTokenCandidate, now: &DateTime<Utc>) -> bool {candidate.token.revoked_at.is_none()&& candidate@@ -92,6 +187,57 @@ where})}+ async fn agent_owner_for_request(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Option<Uuid>,+ ) -> Result<BotOwner, BotError> {+ if let Some(team_id) = team_id {+ if !self+ .repo+ .user_has_team(caller.clone(), team_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ {+ return Err(BotError::Unauthorized);+ }+ return Ok(BotOwner::Team { team_id });+ }++ Ok(BotOwner::User {+ user_id: caller.as_ref().to_string(),+ })+ }++ async fn owner_for_agent_update(+ &self,+ caller: MacroUserIdStr<'static>,+ current: &Bot,+ requested_team_id: Option<Uuid>,+ ) -> Result<BotOwner, BotError> {+ match (current.owner.as_ref(), requested_team_id) {+ (Some(BotOwner::User { .. }), team_id) => {+ self.agent_owner_for_request(caller, team_id).await+ }+ (+ Some(BotOwner::Team {+ team_id: current_team_id,+ }),+ Some(requested_team_id),+ ) if *current_team_id == requested_team_id => Ok(BotOwner::Team {+ team_id: requested_team_id,+ }),+ (Some(BotOwner::Team { .. }), None)+ if current.created_by.as_deref() == Some(caller.as_ref()) =>+ {+ Ok(BotOwner::User {+ user_id: caller.as_ref().to_string(),+ })+ }+ _ => Err(BotError::Unauthorized),+ }+ }+async fn ensure_manageable(&self,caller: MacroUserIdStr<'static>,@@ -157,6 +303,110 @@ whereR: BotRepo,B: MacroEventBroker + Clone,{+ async fn create_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ req: CreateAgentRequest,+ ) -> Result<Agent, BotError> {+ validate_agent_request(&req)?;+ if req.channel_scope == AgentChannelScope::Selected+ && !self+ .repo+ .user_has_channels(caller.clone(), &req.channel_ids)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ {+ return Err(BotError::Unauthorized);+ }++ let owner = self+ .agent_owner_for_request(caller.clone(), req.team_id)+ .await?;+ let created_by_user_id = caller.clone();+ let agent = self+ .repo+ .create_agent(owner, caller, req)+ .await+ .map_err(|err| BotError::Repo(err.into()))?;++ self.publish_bot_event(&BotMacroEvent::created(BotCreatedMetadata {+ bot_id: agent.bot.id,+ kind: agent.bot.kind,+ owner: agent+ .bot+ .owner+ .clone()+ .expect("owned agent bot must have an owner"),+ name: agent.bot.name.clone(),+ handle: agent.bot.handle.clone(),+ description: agent.bot.description.clone(),+ avatar_url: agent.bot.avatar_url.clone(),+ created_by_user_id,+ channel_id: None,+ created_at: agent.bot.created_at,+ }));++ Ok(agent)+ }++ async fn update_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ req: UpdateAgentRequest,+ ) -> Result<Agent, BotError> {+ let current = self.ensure_manageable(caller.clone(), bot_id).await?;++ validate_update_agent_request(&req)?;+ if req.channel_scope == AgentChannelScope::Selected+ && !self+ .repo+ .user_has_channels(caller.clone(), &req.channel_ids)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ {+ return Err(BotError::Unauthorized);+ }++ let owner = self+ .owner_for_agent_update(caller.clone(), ¤t, req.team_id)+ .await?;+ let requested_name = req.name.clone();+ let requested_handle = req.handle.clone();+ let requested_description = req.description.clone();+ let requested_avatar_url = req.avatar_url.clone();+ let agent = self+ .repo+ .update_agent(bot_id, owner, req)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ .ok_or_else(|| BotError::NotFound("agent not found".to_string()))?;++ self.publish_bot_event(&BotMacroEvent::updated(BotUpdatedMetadata {+ bot_id: agent.bot.id,+ owner: agent+ .bot+ .owner+ .clone()+ .expect("owned agent bot must have an owner"),+ actor_user_id: caller,+ name: Some(requested_name),+ handle: Some(requested_handle),+ description: requested_description,+ avatar_url: requested_avatar_url,+ updated_at: agent.bot.updated_at,+ }));++ Ok(agent)+ }++ async fn list_agents(&self, caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {+ self.repo+ .list_manageable_agents(caller)+ .await+ .map_err(|err| BotError::Repo(err.into()))+ }+async fn create_bot(&self,caller: MacroUserIdStr<'static>,@@ -296,6 +546,16 @@ wherebot_id: BotId,) -> Result<(), BotError> {let bot = self.ensure_manageable(caller.clone(), bot_id).await?;+ if let Some(BotOwner::Team { team_id }) = &bot.owner+ && bot.created_by.as_deref() != Some(caller.as_ref())+ && !self+ .repo+ .user_owns_team(caller.clone(), *team_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ {+ return Err(BotError::Unauthorized);+ }if !self.repo.delete_bot(bot_id)diff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rsindex 7e502f1025..f9acdad6b2 100644--- a/crates/bots/src/inbound/axum_router.rs+++ b/crates/bots/src/inbound/axum_router.rs@@ -5,8 +5,9 @@ mod tests;use crate::domain::{models::{- AddChannelBotRequest, Bot, BotChannel, BotChannelListCaller, BotId, BotToken,- CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,+ AddChannelBotRequest, Agent, Bot, BotChannel, BotChannelListCaller, BotId, BotToken,+ CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,+ PatchBotRequest, UpdateAgentRequest,},ports::{BotError, BotService},};@@ -15,7 +16,7 @@ use axum::{extract::{FromRef, Path, State},http::StatusCode,response::IntoResponse,- routing::{delete, get, patch, post},+ routing::{delete, get, patch, post, put},};use entity_access::{domain::{@@ -84,6 +85,13 @@ pub struct BotPath {pub bot_id: BotId,}+/// Agent path.+#[derive(Debug, serde::Deserialize)]+pub struct AgentPath {+ /// Agent bot id.+ pub agent_id: BotId,+}+/// Bot token path.#[derive(Debug, serde::Deserialize)]pub struct BotTokenPath {@@ -127,6 +135,12 @@ whereT: Send + Sync,{Router::new()+ .route("/agents", get(list_agents_handler::<S, Svc, Auth>))+ .route("/agents", post(create_agent_handler::<S, Svc, Auth>))+ .route(+ "/agents/{agent_id}",+ put(update_agent_handler::<S, Svc, Auth>),+ ).route("/bots", get(list_bots_handler::<S, Svc, Auth>)).route("/bots", post(create_bot_handler::<S, Svc, Auth>)).route("/bots/me", get(get_self_bot_handler::<S, Svc, Auth>))@@ -168,6 +182,104 @@ where.with_state(state)}+/// Handler for `POST /agents`.+#[utoipa::path(+ post,+ tag = "agents",+ operation_id = "create_agent",+ path = "/agents",+ request_body = CreateAgentRequest,+ responses(+ (status = 201, body = Agent),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn create_agent_handler<+ S: BotService,+ Svc: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ State(state): State<BotsRouterState<S, Svc, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Json(req): Json<CreateAgentRequest>,+) -> Result<(StatusCode, Json<Agent>), BotsHandlerErr> {+ let agent = state+ .service+ .create_agent(authorization.authorization.user.macro_user_id, req)+ .await?;+ Ok((StatusCode::CREATED, Json(agent)))+}++/// Handler for `GET /agents`.+#[utoipa::path(+ get,+ tag = "agents",+ operation_id = "list_agents",+ path = "/agents",+ responses(+ (status = 200, body = Vec<Agent>),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn list_agents_handler<+ S: BotService,+ Svc: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ State(state): State<BotsRouterState<S, Svc, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+) -> Result<Json<Vec<Agent>>, BotsHandlerErr> {+ Ok(Json(+ state+ .service+ .list_agents(authorization.authorization.user.macro_user_id)+ .await?,+ ))+}++/// Handler for `PUT /agents/{agent_id}`.+#[utoipa::path(+ put,+ tag = "agents",+ operation_id = "update_agent",+ path = "/agents/{agent_id}",+ params(+ ("agent_id" = BotId, Path, description = "Agent bot ID")+ ),+ request_body = UpdateAgentRequest,+ responses(+ (status = 200, body = Agent),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn update_agent_handler<+ S: BotService,+ Svc: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ State(state): State<BotsRouterState<S, Svc, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(path): Path<AgentPath>,+ Json(req): Json<UpdateAgentRequest>,+) -> Result<Json<Agent>, BotsHandlerErr> {+ Ok(Json(+ state+ .service+ .update_agent(+ authorization.authorization.user.macro_user_id,+ path.agent_id,+ req,+ )+ .await?,+ ))+}+fn caller_from_receipt(receipt: &EntityAccessReceipt<MemberParticipantRole>,) -> Result<MacroUserIdStr<'static>, BotsHandlerErr> {diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rsindex 33aa5fcd44..df60c1e0e8 100644--- a/crates/bots/src/inbound/axum_router/tests.rs+++ b/crates/bots/src/inbound/axum_router/tests.rs@@ -1,7 +1,7 @@use super::*;use crate::domain::models::{- AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotKind, BotOwner,- CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,+ Agent, AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotKind, BotOwner,+ CreateAgentRequest, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,};use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};use axum::{@@ -97,6 +97,27 @@ impl TestBotService {}impl BotService for TestBotService {+ async fn create_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _req: CreateAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }++ async fn update_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: UpdateAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }++ async fn list_agents(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {+ unimplemented!()+ }+async fn create_bot(&self,_caller: MacroUserIdStr<'static>,diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rsindex b58682a186..6cc1bf93c7 100644--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs@@ -1,7 +1,8 @@use super::*;use crate::domain::models::{- AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotKind, BotOwner, BotToken,- CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,+ Agent, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotKind, BotOwner, BotToken,+ CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,+ PatchBotRequest, UpdateAgentRequest,};use axum::{Router,@@ -152,6 +153,27 @@ impl TestBotService {}impl BotService for TestBotService {+ async fn create_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _req: CreateAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }++ async fn update_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: UpdateAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }++ async fn list_agents(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {+ unimplemented!()+ }+async fn create_bot(&self,_caller: MacroUserIdStr<'static>,diff --git a/crates/bots/src/inbound/toolset/test.rs b/crates/bots/src/inbound/toolset/test.rsindex fe21ea77f4..b016e4fb9b 100644--- a/crates/bots/src/inbound/toolset/test.rs+++ b/crates/bots/src/inbound/toolset/test.rs@@ -6,9 +6,10 @@ use super::{manage_bot_channel_access::{BotChannelAccessAction, ManageBotChannelAccess},};use crate::domain::models::{- AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotToken, CreateBotRequest,- CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,- CreateChannelScopedBotResponse, PatchBotRequest,+ Agent, AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotToken,+ CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,+ CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,+ UpdateAgentRequest,};use crate::domain::{models::{Bot, BotKind, BotOwner},@@ -83,6 +84,27 @@ struct ToolTestBotService {}impl BotService for ToolTestBotService {+ async fn create_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _req: CreateAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }++ async fn update_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: UpdateAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }++ async fn list_agents(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {+ unimplemented!()+ }+async fn create_bot(&self,_caller: MacroUserIdStr<'static>,diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rsindex 358a017aa5..4aa6f87ce9 100644--- a/crates/bots/src/outbound/pg_bots_repo.rs+++ b/crates/bots/src/outbound/pg_bots_repo.rs@@ -5,9 +5,9 @@ mod tests;use crate::domain::{models::{- AuthenticatedBot, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken,- BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,- PatchBotRequest,+ Agent, AgentChannelScope, AuthenticatedBot, Bot, BotChannel, BotChannelType, BotId,+ BotKind, BotOwner, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,+ CreateBotTokenRequest, CreateChannelScopedBotRequest, PatchBotRequest, UpdateAgentRequest,},ports::BotRepo,};@@ -90,6 +90,64 @@ impl TryFrom<BotRow> for Bot {}}+#[derive(Debug)]+struct AgentRow {+ id: Uuid,+ kind: String,+ owner_user_id: Option<String>,+ team_id: Option<Uuid>,+ name: String,+ handle: String,+ description: Option<String>,+ avatar_url: Option<String>,+ created_by: Option<String>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ deleted_at: Option<DateTime<Utc>>,+ has_agent: bool,+ instructions: String,+ harness: String,+ default_model: String,+ channel_scope: String,+ channel_ids: Vec<Uuid>,+}++impl TryFrom<AgentRow> for Agent {+ type Error = anyhow::Error;++ fn try_from(row: AgentRow) -> Result<Self, Self::Error> {+ let channel_scope = row+ .channel_scope+ .parse::<AgentChannelScope>()+ .map_err(anyhow::Error::msg)?;+ let bot = BotRow {+ id: row.id,+ kind: row.kind,+ owner_user_id: row.owner_user_id,+ team_id: row.team_id,+ name: row.name,+ handle: row.handle,+ description: row.description,+ avatar_url: row.avatar_url,+ created_by: row.created_by,+ created_at: row.created_at,+ updated_at: row.updated_at,+ deleted_at: row.deleted_at,+ has_agent: row.has_agent,+ }+ .try_into()?;++ Ok(Self {+ bot,+ instructions: row.instructions,+ harness: row.harness,+ default_model: row.default_model,+ channel_scope,+ channel_ids: row.channel_ids,+ })+ }+}+#[derive(Debug)]struct BotChannelRow {channel_id: Uuid,@@ -196,6 +254,302 @@ fn map_token_row(row: BotTokenRow) -> BotToken {impl BotRepo for PgBotsRepo {type Err = anyhow::Error;+ async fn create_agent(+ &self,+ owner: BotOwner,+ created_by: MacroUserIdStr<'static>,+ req: CreateAgentRequest,+ ) -> Result<Agent, Self::Err> {+ let bot_id = BotId::new_from_uuid(macro_uuid::generate_uuid_v7());+ let (owner_user_id, team_id) = owner_columns(owner);+ let mut tx = self+ .pool+ .begin()+ .await+ .context("failed to begin agent creation transaction")?;++ let bot_row = sqlx::query_as!(+ BotRow,+ r#"+ INSERT INTO bots (+ id, kind, owner_user_id, team_id, name, handle, description, avatar_url,+ created_by, has_agent+ )+ VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8, true)+ RETURNING+ id,+ kind,+ owner_user_id,+ team_id,+ name,+ handle,+ description,+ avatar_url,+ created_by,+ created_at,+ updated_at,+ deleted_at,+ has_agent+ "#,+ bot_id.as_uuid(),+ owner_user_id,+ team_id,+ &req.name,+ &req.handle,+ req.description.as_deref(),+ req.avatar_url.as_deref(),+ created_by.as_ref(),+ )+ .fetch_one(&mut *tx)+ .await+ .context("failed to create agent bot")?;++ sqlx::query!(+ r#"+ INSERT INTO agent_configs (+ bot_id, instructions, harness, default_model, channel_scope+ )+ VALUES ($1, $2, $3, $4, $5)+ "#,+ bot_id.as_uuid(),+ &req.instructions,+ &req.harness,+ &req.default_model,+ req.channel_scope.as_str(),+ )+ .execute(&mut *tx)+ .await+ .context("failed to create agent config")?;++ if !req.channel_ids.is_empty() {+ let bot_principal = principal_id(bot_id);+ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)+ SELECT channel_id, $2, 'member'::comms_participant_role, NULL+ FROM UNNEST($1::uuid[]) AS channel_id+ "#,+ &req.channel_ids,+ bot_principal,+ )+ .execute(&mut *tx)+ .await+ .context("failed to add agent to selected channels")?;+ }++ tx.commit()+ .await+ .context("failed to commit agent creation transaction")?;++ Ok(Agent {+ bot: map_bot_row(bot_row)?,+ instructions: req.instructions,+ harness: req.harness,+ default_model: req.default_model,+ channel_scope: req.channel_scope,+ channel_ids: req.channel_ids,+ })+ }++ async fn update_agent(+ &self,+ bot_id: BotId,+ owner: BotOwner,+ req: UpdateAgentRequest,+ ) -> Result<Option<Agent>, Self::Err> {+ let (owner_user_id, team_id) = owner_columns(owner);+ let mut tx = self+ .pool+ .begin()+ .await+ .context("failed to begin agent update transaction")?;++ let Some(bot_row) = sqlx::query_as!(+ BotRow,+ r#"+ UPDATE bots+ SET owner_user_id = $2,+ team_id = $3,+ name = $4,+ handle = $5,+ description = $6,+ avatar_url = $7,+ updated_at = now()+ WHERE id = $1+ AND deleted_at IS NULL+ AND EXISTS (SELECT 1 FROM agent_configs WHERE bot_id = $1)+ RETURNING+ id,+ kind,+ owner_user_id,+ team_id,+ name,+ handle,+ description,+ avatar_url,+ created_by,+ created_at,+ updated_at,+ deleted_at,+ has_agent+ "#,+ bot_id.as_uuid(),+ owner_user_id,+ team_id,+ &req.name,+ &req.handle,+ req.description.as_deref(),+ req.avatar_url.as_deref(),+ )+ .fetch_optional(&mut *tx)+ .await+ .context("failed to update agent bot")?+ else {+ tx.rollback().await?;+ return Ok(None);+ };++ sqlx::query!(+ r#"+ UPDATE agent_configs+ SET instructions = $2,+ harness = $3,+ default_model = $4,+ channel_scope = $5,+ updated_at = now()+ WHERE bot_id = $1+ "#,+ bot_id.as_uuid(),+ &req.instructions,+ &req.harness,+ &req.default_model,+ req.channel_scope.as_str(),+ )+ .execute(&mut *tx)+ .await+ .context("failed to update agent config")?;++ let bot_principal = principal_id(bot_id);+ sqlx::query!(+ r#"+ UPDATE comms_channel_participants+ SET left_at = now()+ WHERE user_id = $1+ AND left_at IS NULL+ "#,+ &bot_principal,+ )+ .execute(&mut *tx)+ .await+ .context("failed to clear the agent's previous channels")?;++ if !req.channel_ids.is_empty() {+ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)+ SELECT channel_id, $2, 'member'::comms_participant_role, NULL+ FROM UNNEST($1::uuid[]) AS channel_id+ ON CONFLICT (channel_id, user_id)+ DO UPDATE SET role = 'member'::comms_participant_role,+ left_at = NULL,+ joined_at = now()+ "#,+ &req.channel_ids,+ &bot_principal,+ )+ .execute(&mut *tx)+ .await+ .context("failed to replace the agent's selected channels")?;+ }++ tx.commit()+ .await+ .context("failed to commit agent update transaction")?;++ Ok(Some(Agent {+ bot: map_bot_row(bot_row)?,+ instructions: req.instructions,+ harness: req.harness,+ default_model: req.default_model,+ channel_scope: req.channel_scope,+ channel_ids: req.channel_ids,+ }))+ }++ async fn list_manageable_agents(+ &self,+ caller: MacroUserIdStr<'static>,+ ) -> Result<Vec<Agent>, Self::Err> {+ let rows = sqlx::query_as!(+ AgentRow,+ r#"+ SELECT+ b.id,+ b.kind,+ b.owner_user_id,+ b.team_id,+ b.name,+ b.handle,+ b.description,+ b.avatar_url,+ b.created_by,+ b.created_at,+ b.updated_at,+ b.deleted_at,+ b.has_agent,+ a.instructions,+ a.harness,+ a.default_model,+ a.channel_scope,+ ARRAY(+ SELECT p.channel_id+ FROM comms_channel_participants p+ WHERE p.user_id = 'bot|' || b.id::text+ AND p.left_at IS NULL+ ORDER BY p.channel_id+ ) AS "channel_ids!"+ FROM bots b+ INNER JOIN agent_configs a ON a.bot_id = b.id+ WHERE b.kind = 'owned'+ AND b.deleted_at IS NULL+ AND (+ b.owner_user_id = $1+ OR b.team_id IN (+ SELECT team_id FROM team_user WHERE user_id = $1+ )+ )+ ORDER BY b.created_at ASC, b.id ASC+ "#,+ caller.as_ref(),+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to list manageable agents")?;++ rows.into_iter().map(Agent::try_from).collect()+ }++ async fn user_has_channels(+ &self,+ caller: MacroUserIdStr<'static>,+ channel_ids: &[Uuid],+ ) -> Result<bool, Self::Err> {+ sqlx::query_scalar!(+ r#"+ SELECT COUNT(DISTINCT channel_id) = CARDINALITY($2::uuid[]) AS "has_channels!"+ FROM comms_channel_participants+ WHERE user_id = $1+ AND channel_id = ANY($2::uuid[])+ AND left_at IS NULL+ "#,+ caller.as_ref(),+ channel_ids,+ )+ .fetch_one(&self.pool)+ .await+ .context("failed to check agent channel membership")+ }+async fn create_owned_bot(&self,owner: BotOwner,@@ -414,6 +768,50 @@ impl BotRepo for PgBotsRepo {row.map(map_bot_row).transpose()}+ async fn get_agent(&self, bot_id: BotId) -> Result<Option<Agent>, Self::Err> {+ let row = sqlx::query_as!(+ AgentRow,+ r#"+ SELECT+ b.id,+ b.kind,+ b.owner_user_id,+ b.team_id,+ b.name,+ b.handle,+ b.description,+ b.avatar_url,+ b.created_by,+ b.created_at,+ b.updated_at,+ b.deleted_at,+ b.has_agent,+ a.instructions,+ a.harness,+ a.default_model,+ a.channel_scope,+ ARRAY(+ SELECT p.channel_id+ FROM comms_channel_participants p+ WHERE p.user_id = 'bot|' || b.id::text+ AND p.left_at IS NULL+ ORDER BY p.channel_id+ ) AS "channel_ids!"+ FROM bots b+ INNER JOIN agent_configs a ON a.bot_id = b.id+ WHERE b.id = $1+ AND b.kind = 'owned'+ AND b.deleted_at IS NULL+ "#,+ bot_id.as_uuid(),+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to get agent")?;++ row.map(Agent::try_from).transpose()+ }+async fn user_has_team(&self,caller: MacroUserIdStr<'static>,@@ -485,6 +883,30 @@ impl BotRepo for PgBotsRepo {Ok(can_administer)}+ async fn user_owns_team(+ &self,+ caller: MacroUserIdStr<'static>,+ team_id: Uuid,+ ) -> Result<bool, Self::Err> {+ let owns_team = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM team_user+ WHERE user_id = $1+ AND team_id = $2+ AND team_role = 'owner'::team_role+ ) AS "owns_team!"+ "#,+ caller.as_ref(),+ team_id,+ )+ .fetch_one(&self.pool)+ .await+ .context("failed to check team ownership")?;+ Ok(owns_team)+ }+async fn patch_bot(&self,bot_id: BotId,diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rsindex 2f5387edea..4e9ebb0d5b 100644--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs@@ -1,8 +1,9 @@use super::*;use crate::domain::{models::{- BotChannelListCaller, BotChannelType, CreateBotRequest, CreateBotTokenRequest,- CreateChannelScopedBotRequest, PatchBotRequest,+ AgentChannelScope, BotChannelListCaller, BotChannelType, CreateAgentRequest,+ CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest, PatchBotRequest,+ UpdateAgentRequest,},ports::{BotError, BotService},service::BotServiceImpl,@@ -68,6 +69,36 @@ fn create_channel_scoped_req(handle: &str) -> CreateChannelScopedBotRequest {}}+fn create_agent_req(handle: &str, channel_scope: AgentChannelScope) -> CreateAgentRequest {+ CreateAgentRequest {+ team_id: None,+ name: "Bug fixer".to_string(),+ handle: handle.to_string(),+ description: Some("Finds and fixes bugs".to_string()),+ avatar_url: Some("https://static.example/bug-fixer.png".to_string()),+ instructions: "Fix the root cause and add tests.".to_string(),+ harness: "cursor".to_string(),+ default_model: "cursor-small".to_string(),+ channel_scope,+ channel_ids: Vec::new(),+ }+}++fn update_agent_req(handle: &str, channel_scope: AgentChannelScope) -> UpdateAgentRequest {+ UpdateAgentRequest {+ team_id: None,+ name: "Updated bug fixer".to_string(),+ handle: handle.to_string(),+ description: None,+ avatar_url: None,+ instructions: "Diagnose first, then make the smallest tested fix.".to_string(),+ harness: "in-memory".to_string(),+ default_model: "claude-sonnet-4-5".to_string(),+ channel_scope,+ channel_ids: Vec::new(),+ }+}+fn service(pool: &PgPool) -> BotServiceImpl<PgBotsRepo, NoopMacroEventBroker> {BotServiceImpl::new(PgBotsRepo::new(pool.clone()), NoopMacroEventBroker)}@@ -250,6 +281,25 @@ async fn insert_channel(pool: &PgPool, channel_id: Uuid) -> anyhow::Result<()> {Ok(())}+async fn insert_channel_member(+ pool: &PgPool,+ channel_id: Uuid,+ user_id: &str,+) -> anyhow::Result<()> {+ insert_channel(pool, channel_id).await?;+ sqlx::query!(+ r#"+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)+ VALUES ($1, $2, 'member'::comms_participant_role, NULL)+ "#,+ channel_id,+ user_id,+ )+ .execute(pool)+ .await?;+ Ok(())+}+async fn active_channel_participant_count(pool: &PgPool,channel_id: Uuid,@@ -355,6 +405,232 @@ async fn create_user_owned_bot_records_user_owner(pool: PgPool) -> anyhow::ResulOk(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn created_agent_round_trips_every_agent_field(pool: PgPool) -> anyhow::Result<()> {+ let service = service(&pool);+ let created = service+ .create_agent(+ user_id(USER_OWNER),+ create_agent_req("bug-fixer", AgentChannelScope::All),+ )+ .await?;++ assert!(created.bot.has_agent);+ assert_eq!(created.bot.handle, "bug-fixer");+ assert_eq!(created.instructions, "Fix the root cause and add tests.");+ assert_eq!(created.harness, "cursor");+ assert_eq!(created.default_model, "cursor-small");+ assert_eq!(created.channel_scope, AgentChannelScope::All);+ assert!(created.channel_ids.is_empty());++ let listed = service.list_agents(user_id(USER_OWNER)).await?;+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].bot.id, created.bot.id);+ assert_eq!(listed[0].instructions, created.instructions);+ assert_eq!(listed[0].harness, created.harness);+ assert_eq!(listed[0].default_model, created.default_model);++ let fetched = PgBotsRepo::new(pool.clone())+ .get_agent(created.bot.id)+ .await?+ .expect("created agent should be addressable by bot id");+ assert_eq!(fetched.bot.id, created.bot.id);+ assert_eq!(fetched.instructions, created.instructions);+ assert_eq!(fetched.harness, created.harness);+ assert_eq!(fetched.default_model, created.default_model);++ assert!(service.list_agents(user_id(USER_OTHER)).await?.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_team_agent_requires_membership_not_admin(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::new_v4();+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;+ let service = service(&pool);+ let mut request = create_agent_req("member-agent", AgentChannelScope::All);+ request.team_id = Some(team_id);++ let created = service+ .create_agent(user_id(TEAM_MEMBER), request.clone())+ .await?;+ assert_eq!(created.bot.owner, Some(BotOwner::Team { team_id }));+ assert_eq!(created.bot.created_by.as_deref(), Some(TEAM_MEMBER));++ request.handle = "outsider-agent".to_string();+ let error = service+ .create_agent(user_id(TEAM_OTHER), request)+ .await+ .expect_err("a non-member must not create a team agent");+ assert!(matches!(error, BotError::Unauthorized));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn updated_agent_replaces_every_field_and_selected_channel(+ pool: PgPool,+) -> anyhow::Result<()> {+ let first = Uuid::new_v4();+ let second = Uuid::new_v4();+ insert_channel_member(&pool, first, USER_OWNER).await?;+ insert_channel_member(&pool, second, USER_OWNER).await?;+ let service = service(&pool);+ let mut create = create_agent_req("bug-fixer", AgentChannelScope::Selected);+ create.channel_ids = vec![first];+ let created = service.create_agent(user_id(USER_OWNER), create).await?;++ let mut update = update_agent_req("updated-fixer", AgentChannelScope::Selected);+ update.channel_ids = vec![second];+ let updated = service+ .update_agent(user_id(USER_OWNER), created.bot.id, update)+ .await?;++ assert_eq!(updated.bot.name, "Updated bug fixer");+ assert_eq!(updated.bot.handle, "updated-fixer");+ assert_eq!(updated.bot.description, None);+ assert_eq!(updated.bot.avatar_url, None);+ assert_eq!(+ updated.instructions,+ "Diagnose first, then make the smallest tested fix."+ );+ assert_eq!(updated.harness, "in-memory");+ assert_eq!(updated.default_model, "claude-sonnet-4-5");+ assert_eq!(updated.channel_ids, vec![second]);+ assert_eq!(+ active_channel_participant_count(&pool, first, created.bot.id).await?,+ 0+ );+ assert_eq!(+ active_channel_participant_count(&pool, second, created.bot.id).await?,+ 1+ );++ let listed = service.list_agents(user_id(USER_OWNER)).await?;+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].bot.handle, "updated-fixer");+ assert_eq!(listed[0].channel_ids, vec![second]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_member_creator_can_change_agent_share_between_private_and_team(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::new_v4();+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;+ let service = service(&pool);+ let created = service+ .create_agent(+ user_id(TEAM_MEMBER),+ create_agent_req("share-fixer", AgentChannelScope::All),+ )+ .await?;++ let mut make_team = update_agent_req("share-fixer", AgentChannelScope::All);+ make_team.team_id = Some(team_id);+ let team_agent = service+ .update_agent(user_id(TEAM_MEMBER), created.bot.id, make_team)+ .await?;+ assert_eq!(team_agent.bot.owner, Some(BotOwner::Team { team_id }));++ let make_private = update_agent_req("share-fixer", AgentChannelScope::All);+ let private_agent = service+ .update_agent(user_id(TEAM_MEMBER), created.bot.id, make_private)+ .await?;+ assert_eq!(+ private_agent.bot.owner,+ Some(BotOwner::User {+ user_id: TEAM_MEMBER.to_string(),+ })+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_member_can_update_team_agent_but_cannot_make_it_private(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::new_v4();+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;+ let service = service(&pool);+ let mut create = create_agent_req("team-fixer", AgentChannelScope::All);+ create.team_id = Some(team_id);+ let created = service.create_agent(user_id(TEAM_ADMIN), create).await?;++ let mut update = update_agent_req("changed-by-member", AgentChannelScope::All);+ update.team_id = Some(team_id);+ let updated = service+ .update_agent(user_id(TEAM_MEMBER), created.bot.id, update)+ .await?;+ assert_eq!(updated.bot.handle, "changed-by-member");+ assert_eq!(updated.bot.owner, Some(BotOwner::Team { team_id }));++ let error = service+ .update_agent(+ user_id(TEAM_MEMBER),+ created.bot.id,+ update_agent_req("made-private-by-member", AgentChannelScope::All),+ )+ .await+ .expect_err("only the creator may make a team agent private");+ assert!(matches!(error, BotError::Unauthorized));++ let listed = service.list_agents(user_id(TEAM_ADMIN)).await?;+ assert_eq!(listed[0].bot.handle, "changed-by-member");+ assert_eq!(listed[0].bot.owner, Some(BotOwner::Team { team_id }));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn selected_agent_is_created_atomically_in_authorized_channels(+ pool: PgPool,+) -> anyhow::Result<()> {+ let first = Uuid::new_v4();+ let second = Uuid::new_v4();+ insert_channel_member(&pool, first, USER_OWNER).await?;+ insert_channel_member(&pool, second, USER_OWNER).await?;+ let service = service(&pool);+ let mut request = create_agent_req("channel-fixer", AgentChannelScope::Selected);+ request.channel_ids = vec![first, second];++ let created = service.create_agent(user_id(USER_OWNER), request).await?;+ assert_eq!(created.channel_ids, vec![first, second]);+ assert_eq!(+ active_channel_participant_count(&pool, first, created.bot.id).await?,+ 1+ );+ assert_eq!(+ active_channel_participant_count(&pool, second, created.bot.id).await?,+ 1+ );++ let listed = service.list_agents(user_id(USER_OWNER)).await?;+ assert_eq!(listed[0].channel_ids.len(), 2);+ assert!(listed[0].channel_ids.contains(&first));+ assert!(listed[0].channel_ids.contains(&second));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn selected_agent_rejects_channels_the_caller_cannot_access(+ pool: PgPool,+) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ insert_channel(&pool, channel_id).await?;+ let service = service(&pool);+ let mut request = create_agent_req("unauthorized-fixer", AgentChannelScope::Selected);+ request.channel_ids = vec![channel_id];++ let error = service+ .create_agent(user_id(USER_OTHER), request)+ .await+ .expect_err("a non-member must not create an agent in the channel");+ assert!(matches!(error, BotError::Unauthorized));+ assert!(service.list_agents(user_id(USER_OTHER)).await?.is_empty());+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_bot_stores_requested_has_agent(pool: PgPool) -> anyhow::Result<()> {let service = service(&pool);@@ -466,6 +742,52 @@ async fn create_team_owned_bot_requires_team_admin_or_owner(pool: PgPool) -> anyOk(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn only_creator_or_team_owner_can_delete_team_bots(pool: PgPool) -> anyhow::Result<()> {+ let service = service(&pool);+ let team_id = Uuid::new_v4();+ insert_team_user(&pool, team_id, TEAM_OWNER, "owner").await?;+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;++ let mut admin_bot_request = create_req("admin-team-bot");+ admin_bot_request.team_id = Some(team_id);+ let admin_bot = service+ .create_bot(user_id(TEAM_ADMIN), admin_bot_request)+ .await?;++ let member_delete = service.delete_bot(user_id(TEAM_MEMBER), admin_bot.id).await;+ assert!(matches!(member_delete, Err(BotError::Unauthorized)));+ service+ .delete_bot(user_id(TEAM_OWNER), admin_bot.id)+ .await?;++ let mut owner_bot_request = create_req("owner-team-bot");+ owner_bot_request.team_id = Some(team_id);+ let owner_bot = service+ .create_bot(user_id(TEAM_OWNER), owner_bot_request)+ .await?;++ let admin_delete = service.delete_bot(user_id(TEAM_ADMIN), owner_bot.id).await;+ assert!(matches!(admin_delete, Err(BotError::Unauthorized)));++ let mut member_agent_request = create_agent_req("member-team-agent", AgentChannelScope::All);+ member_agent_request.team_id = Some(team_id);+ let member_agent = service+ .create_agent(user_id(TEAM_MEMBER), member_agent_request)+ .await?;++ let admin_delete = service+ .delete_bot(user_id(TEAM_ADMIN), member_agent.bot.id)+ .await;+ assert!(matches!(admin_delete, Err(BotError::Unauthorized)));+ service+ .delete_bot(user_id(TEAM_MEMBER), member_agent.bot.id)+ .await?;++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_team_owned_channel_scoped_bot_requires_team_admin(pool: PgPool,diff --git a/crates/macro_db_client/migrations/20260827174457_persist_agent_configs.sql b/crates/macro_db_client/migrations/20260827174457_persist_agent_configs.sqlnew file mode 100644index 0000000000..c6af55c8ec--- /dev/null+++ b/crates/macro_db_client/migrations/20260827174457_persist_agent_configs.sql@@ -0,0 +1,16 @@+-- Agent identity and ownership live in `bots`; this table holds only the+-- agent-specific behavior and runtime selection. Channel reach remains in+-- `comms_channel_participants`, shared with every other bot.+CREATE TABLE agent_configs (+ bot_id UUID PRIMARY KEY REFERENCES bots(id) ON DELETE CASCADE,+ instructions TEXT NOT NULL,+ harness TEXT NOT NULL,+ default_model TEXT NOT NULL,+ channel_scope TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT agent_configs_harness_not_empty CHECK (harness <> ''),+ CONSTRAINT agent_configs_default_model_not_empty CHECK (default_model <> ''),+ CONSTRAINT agent_configs_channel_scope_valid+ CHECK (channel_scope IN ('all', 'selected'))+);diff --git a/docs/CURSOR_AGENT_TRANSPORT.md b/docs/CURSOR_AGENT_TRANSPORT.mdindex f990452997..8e39f383f7 100644--- a/docs/CURSOR_AGENT_TRANSPORT.md+++ b/docs/CURSOR_AGENT_TRANSPORT.md@@ -84,7 +84,7 @@ associated type, resolved once.## Product surface-### 1. Settings → Connections+### 1. Settings → Agents → HarnessA field to enter a Cursor API key. On submit we validate it before storing:`GET /v1/me` with the key. A `crsr_`-prefixed key that authenticates is stored;diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 6e42fff34f..aac63c2f92 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/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, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex fe15bc6368..6289590bec 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/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 { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -57,6 +57,41 @@ export class Sdk extends HeyApiClient {Sdk.__registry.set(this, args?.key);}+ /**+ * Handler for `GET /agents`.+ */+ public listAgents<ThrowOnError extends boolean = false>(options?: Options<ListAgentsData, ThrowOnError>): RequestResult<ListAgentsResponses, ListAgentsErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<ListAgentsResponses, ListAgentsErrors, ThrowOnError>({ url: '/agents', ...options });+ }++ /**+ * Handler for `POST /agents`.+ */+ public createAgent<ThrowOnError extends boolean = false>(options: Options<CreateAgentData, ThrowOnError>): RequestResult<CreateAgentResponses, CreateAgentErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateAgentResponses, CreateAgentErrors, ThrowOnError>({+ url: '/agents',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Handler for `PUT /agents/{agent_id}`.+ */+ public updateAgent<ThrowOnError extends boolean = false>(options: Options<UpdateAgentData, ThrowOnError>): RequestResult<UpdateAgentResponses, UpdateAgentErrors, ThrowOnError> {+ return (options.client ?? this.client).put<UpdateAgentResponses, UpdateAgentErrors, ThrowOnError>({+ url: '/agents/{agent_id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Deletes a single unthreaded anchor for a document* If you need to delete a threaded anchor, see the delete comment handlerdiff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 1de474072d..19af388fd7 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -86,6 +86,41 @@ export type AddPinRequest = {pinType: string;};+/**+ * A persisted user- or team-owned AI agent.+ */+export type Agent = {+ /**+ * The bot identity used for mentions and channel participation.+ */+ bot: Bot;+ /**+ * Selected channel ids. Empty for a global agent.+ */+ channel_ids: Array<string>;+ /**+ * Whether the agent is global or channel-specific.+ */+ channel_scope: AgentChannelScope;+ /**+ * Model selected specifically for this agent.+ */+ default_model: string;+ /**+ * Harness used to run the agent.+ */+ harness: string;+ /**+ * Instructions supplied to the agent at the start of a conversation.+ */+ instructions: string;+};++/**+ * Whether an agent is available everywhere or only in selected channels.+ */+export type AgentChannelScope = 'all' | 'selected';+export type Anchor = PdfAnchor;export type AnchorId = PdfAnchorId & {@@ -2671,6 +2706,52 @@ export type CopyDocumentResponse = {error: boolean;};+/**+ * Request to create a persisted AI agent.+ */+export type CreateAgentRequest = {+ /**+ * Optional avatar URL or data URL.+ */+ avatar_url?: string | null;+ /**+ * Selected channels. Must be non-empty only for `selected` scope.+ */+ channel_ids?: Array<string>;+ /**+ * Whether the agent is global or channel-specific.+ */+ channel_scope: AgentChannelScope;+ /**+ * Model selected specifically for this agent.+ */+ default_model: string;+ /**+ * Optional description.+ */+ description?: string | null;+ /**+ * Stable `@` handle.+ */+ handle: string;+ /**+ * Harness used to run the agent.+ */+ harness: string;+ /**+ * Instructions supplied to the agent at the start of a conversation.+ */+ instructions: string;+ /**+ * Display name.+ */+ name: string;+ /**+ * Team owner. Omit for a private, user-owned agent.+ */+ team_id?: string | null;+};+/*** Request to create a bot.*/@@ -8228,6 +8309,52 @@ export type UnthreadedPdfUuidRequest = {uuid: string;};+/**+ * Request to replace the editable configuration of a persisted AI agent.+ */+export type UpdateAgentRequest = {+ /**+ * Optional avatar URL or data URL.+ */+ avatar_url?: string | null;+ /**+ * Selected channels. Must be non-empty only for `selected` scope.+ */+ channel_ids?: Array<string>;+ /**+ * Whether the agent is global or channel-specific.+ */+ channel_scope: AgentChannelScope;+ /**+ * Model selected specifically for this agent.+ */+ default_model: string;+ /**+ * Optional description.+ */+ description?: string | null;+ /**+ * Stable `@` handle.+ */+ handle: string;+ /**+ * Harness used to run the agent.+ */+ harness: string;+ /**+ * Instructions supplied to the agent at the start of a conversation.+ */+ instructions: string;+ /**+ * Display name.+ */+ name: string;+ /**+ * Team owner. Omit to make the agent private to the caller.+ */+ team_id?: string | null;+};+export type UpdateChannelSharePermission = {accessLevel?: null | AccessLevel;/**@@ -8621,6 +8748,74 @@ export type WithProjectId = {id: string;};+export type ListAgentsData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/agents';+};++export type ListAgentsErrors = {+ 401: ErrorResponse;+ 500: ErrorResponse;+};++export type ListAgentsError = ListAgentsErrors[keyof ListAgentsErrors];++export type ListAgentsResponses = {+ 200: Array<Agent>;+};++export type ListAgentsResponse = ListAgentsResponses[keyof ListAgentsResponses];++export type CreateAgentData = {+ body: CreateAgentRequest;+ path?: never;+ query?: never;+ url: '/agents';+};++export type CreateAgentErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 500: ErrorResponse;+};++export type CreateAgentError = CreateAgentErrors[keyof CreateAgentErrors];++export type CreateAgentResponses = {+ 201: Agent;+};++export type CreateAgentResponse = CreateAgentResponses[keyof CreateAgentResponses];++export type UpdateAgentData = {+ body: UpdateAgentRequest;+ path: {+ /**+ * Agent bot ID+ */+ agent_id: BotId;+ };+ query?: never;+ url: '/agents/{agent_id}';+};++export type UpdateAgentErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type UpdateAgentError = UpdateAgentErrors[keyof UpdateAgentErrors];++export type UpdateAgentResponses = {+ 200: Agent;+};++export type UpdateAgentResponse = UpdateAgentResponses[keyof UpdateAgentResponses];+export type DeleteAnchorData = {body: DeleteUnthreadedAnchorRequest;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 90e9d25dce..75ce6c3709 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -10,6 +10,185 @@"version": "0.1.0"},"paths": {+ "/agents": {+ "get": {+ "tags": ["agents"],+ "summary": "Handler for `GET /agents`.",+ "operationId": "list_agents",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Agent"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["agents"],+ "summary": "Handler for `POST /agents`.",+ "operationId": "create_agent",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateAgentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Agent"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/agents/{agent_id}": {+ "put": {+ "tags": ["agents"],+ "summary": "Handler for `PUT /agents/{agent_id}`.",+ "operationId": "update_agent",+ "parameters": [+ {+ "name": "agent_id",+ "in": "path",+ "description": "Agent bot ID",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/BotId"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateAgentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Agent"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/annotations/anchors": {"delete": {"tags": ["annotations::delete_anchor"],@@ -11726,6 +11905,53 @@}}},+ "Agent": {+ "type": "object",+ "description": "A persisted user- or team-owned AI agent.",+ "required": [+ "bot",+ "instructions",+ "harness",+ "default_model",+ "channel_scope",+ "channel_ids"+ ],+ "properties": {+ "bot": {+ "$ref": "#/components/schemas/Bot",+ "description": "The bot identity used for mentions and channel participation."+ },+ "channel_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Selected channel ids. Empty for a global agent."+ },+ "channel_scope": {+ "$ref": "#/components/schemas/AgentChannelScope",+ "description": "Whether the agent is global or channel-specific."+ },+ "default_model": {+ "type": "string",+ "description": "Model selected specifically for this agent."+ },+ "harness": {+ "type": "string",+ "description": "Harness used to run the agent."+ },+ "instructions": {+ "type": "string",+ "description": "Instructions supplied to the agent at the start of a conversation."+ }+ }+ },+ "AgentChannelScope": {+ "type": "string",+ "description": "Whether an agent is available everywhere or only in selected channels.",+ "enum": ["all", "selected"]+ },"Anchor": {"oneOf": [{@@ -15462,6 +15688,65 @@}}},+ "CreateAgentRequest": {+ "type": "object",+ "description": "Request to create a persisted AI agent.",+ "required": [+ "name",+ "handle",+ "instructions",+ "harness",+ "default_model",+ "channel_scope"+ ],+ "properties": {+ "avatar_url": {+ "type": ["string", "null"],+ "description": "Optional avatar URL or data URL."+ },+ "channel_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Selected channels. Must be non-empty only for `selected` scope."+ },+ "channel_scope": {+ "$ref": "#/components/schemas/AgentChannelScope",+ "description": "Whether the agent is global or channel-specific."+ },+ "default_model": {+ "type": "string",+ "description": "Model selected specifically for this agent."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional description."+ },+ "handle": {+ "type": "string",+ "description": "Stable `@` handle."+ },+ "harness": {+ "type": "string",+ "description": "Harness used to run the agent."+ },+ "instructions": {+ "type": "string",+ "description": "Instructions supplied to the agent at the start of a conversation."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team owner. Omit for a private, user-owned agent."+ }+ }+ },"CreateBotRequest": {"type": "object","description": "Request to create a bot.",@@ -24694,6 +24979,65 @@}]},+ "UpdateAgentRequest": {+ "type": "object",+ "description": "Request to replace the editable configuration of a persisted AI agent.",+ "required": [+ "name",+ "handle",+ "instructions",+ "harness",+ "default_model",+ "channel_scope"+ ],+ "properties": {+ "avatar_url": {+ "type": ["string", "null"],+ "description": "Optional avatar URL or data URL."+ },+ "channel_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Selected channels. Must be non-empty only for `selected` scope."+ },+ "channel_scope": {+ "$ref": "#/components/schemas/AgentChannelScope",+ "description": "Whether the agent is global or channel-specific."+ },+ "default_model": {+ "type": "string",+ "description": "Model selected specifically for this agent."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional description."+ },+ "handle": {+ "type": "string",+ "description": "Stable `@` handle."+ },+ "harness": {+ "type": "string",+ "description": "Harness used to run the agent."+ },+ "instructions": {+ "type": "string",+ "description": "Instructions supplied to the agent at the start of a conversation."+ },+ "name": {+ "type": "string",+ "description": "Display name."+ },+ "team_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team owner. Omit to make the agent private to the caller."+ }+ }+ },"UpdateChannelSharePermission": {"type": "object","required": ["operation", "channelId"],diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex f647a45e32..403d7fcb42 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -309,6 +309,7 @@ export const storageExcluded = [] as const satisfies readonly (keyof StorageSdk)[];export const storageBacklog = [+ 'createAgent','createAnchor','createDocument','createEntityMention',@@ -331,6 +332,7 @@ export const storageBacklog = ['getProjectPermissionsV2','getProjectUserAccessLevel','getReminder',+ 'listAgents','listOccurrences','listReminders','listUserApiKeys',@@ -339,6 +341,7 @@ export const storageBacklog = ['saveDocumentHandler','simpleSave','toggleShareWithTeam',+ 'updateAgent','updateReminder','validateDocumentPermissionsToken',] as const satisfies readonly (keyof StorageSdk)[];diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 6baa4e0601..f37bc1a14d 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -47,6 +47,7 @@ macro_service_urls = { path = "../../crates/macro_service_urls" }macro_tower_layers = { path = "../../crates/macro_tower_layers" }notification = { path = "../../crates/notification" }rdkafka = { workspace = true }+rootcause = { workspace = true }channels = { path = "../../crates/channels", features = ["ports", "outbound"] }anyhow = { workspace = true }macro_user_id = { path = "../../crates/macro_user_id" }diff --git a/services/agent_harness_service/src/agent_runtime_directory.rs b/services/agent_harness_service/src/agent_runtime_directory.rsnew file mode 100644index 0000000000..15cba14031--- /dev/null+++ b/services/agent_harness_service/src/agent_runtime_directory.rs@@ -0,0 +1,44 @@+//! Postgres-backed runtime profiles for fixed and database-backed agents.++use agent_harness::domain::error::{HarnessError, Result};+use agent_harness::domain::model::{AgentKind, AgentRuntimeConfig};+use agent_harness::domain::ports::AgentRuntimeDirectory;+use bot_id::BotId;+use bots::domain::ports::BotRepo;+use bots::outbound::pg_bots_repo::PgBotsRepo;++/// Resolves fixed system profiles first, then user/team agent configuration.+#[derive(Clone)]+pub struct PgAgentRuntimeDirectory {+ repo: PgBotsRepo,+ fixed: Vec<(BotId, AgentRuntimeConfig)>,+}++impl PgAgentRuntimeDirectory {+ /// Build the directory over the bots repository and deployment-owned+ /// system profiles.+ pub fn new(repo: PgBotsRepo, fixed: Vec<(BotId, AgentRuntimeConfig)>) -> Self {+ Self { repo, fixed }+ }+}++impl AgentRuntimeDirectory for PgAgentRuntimeDirectory {+ async fn runtime_for(&self, bot_id: BotId) -> Result<Option<AgentRuntimeConfig>> {+ if let Some((_, runtime)) = self.fixed.iter().find(|(fixed, _)| *fixed == bot_id) {+ return Ok(Some(runtime.clone()));+ }++ let agent =+ self.repo.get_agent(bot_id).await.map_err(|error| {+ HarnessError::RuntimeDirectory(rootcause::report!(error).into())+ })?;+ Ok(agent+ .filter(|agent| agent.bot.has_agent)+ .map(|agent| AgentRuntimeConfig {+ kind: AgentKind::from_harness(&agent.harness),+ model: agent.default_model,+ harness: agent.harness,+ instructions: agent.instructions,+ }))+ }+}diff --git a/services/agent_harness_service/src/bots_directory.rs b/services/agent_harness_service/src/bots_directory.rsindex b6248537f1..44d657172e 100644--- a/services/agent_harness_service/src/bots_directory.rs+++ b/services/agent_harness_service/src/bots_directory.rs@@ -46,9 +46,22 @@ impl BotDirectory for PgBotDirectory {}Some(BotOwner::Team { .. }) | None => None,};+ let is_managed = if row.has_agent {+ self.repo+ .get_agent(bot)+ .await+ .map_err(AgentSessionError::Unknown)?+ .map_or_else(+ || AgentKind::of(bot),+ |agent| AgentKind::from_harness(&agent.harness),+ )+ .is_managed()+ } else {+ false+ };Ok(Some(BotFacts {has_agent: row.has_agent,- is_managed: AgentKind::of(bot).is_managed(),+ is_managed,owner_user_id,}))}diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rsindex e6038d7fc4..40f5e0f1b4 100644--- a/services/agent_harness_service/src/containers.rs+++ b/services/agent_harness_service/src/containers.rs@@ -19,7 +19,6 @@ use agent_runtime_protocol::domain::ports::{Transport, TransportError, Transportuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};use agent_session::domain::model::{AgentSessionId, SandboxSize};use agent_session::domain::service::AgentSessionService;-use bot_id::BotId;#[cfg(test)]mod test;@@ -67,11 +66,9 @@ impl TransportSender<ToRuntimeMessage> for RoutedSender {}}-/// The in-memory runtime and the bot whose sessions it serves.+/// The shared in-memory runtime used by every in-memory agent session.pub struct InMemRuntime {- /// Sessions of this bot run in-process.- pub bot: BotId,- /// Their provisioner.+ /// In-memory session provisioner.pub manager: InMemAgentManager,}@@ -120,8 +117,8 @@ where.get_session(session).await.map_err(HarnessError::Session)?;- if let Some(inmem) = &self.inmem- && row.bot_id == inmem.bot+ if self.inmem.is_some()+ && AgentKind::for_session(row.bot_id, &row.harness) == AgentKind::InMemory{return Ok(Route::InMem(SessionFacts {id: session,@@ -131,7 +128,7 @@ whereacp_session_id: row.acp_session_id,}));}- if AgentKind::of(row.bot_id) == AgentKind::InMemory {+ if AgentKind::for_session(row.bot_id, &row.harness) == AgentKind::InMemory {return Err(HarnessError::Container(format!("session {session} belongs to the in-process bot, which this deployment does not serve")));diff --git a/services/agent_harness_service/src/containers/test.rs b/services/agent_harness_service/src/containers/test.rsindex 0956dfa8c8..a808f420f4 100644--- a/services/agent_harness_service/src/containers/test.rs+++ b/services/agent_harness_service/src/containers/test.rs@@ -5,6 +5,7 @@ use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};use agent_session::domain::ports::NoOpRealtime;use agent_session::domain::service::AgentSessionServiceImpl;use agent_session::testing::{InMemoryAgentSessionRepo, test_agent_session};+use bot_id::BotId;/// A sandbox provider the tests never reach: every case here is decided by/// `route` before the provider is asked for anything.@@ -18,16 +19,40 @@ fn unreachable_sandbox() -> HarnessContainers {}fn sessions_with(bot: BotId) -> (AgentSessionId, impl AgentSessionService + use<>) {+ sessions_with_harness(bot, "opencode")+}++fn sessions_with_harness(+ bot: BotId,+ harness: &str,+) -> (AgentSessionId, impl AgentSessionService + use<>) {let repo = InMemoryAgentSessionRepo::new();let id = AgentSessionId::new();let mut session = test_agent_session(id);session.bot_id = bot;+ session.harness = harness.to_owned();repo.insert_session(session);let service =AgentSessionServiceImpl::new(repo.clone(), FoldedMessageService::new(repo), NoOpRealtime);(id, service)}+#[tokio::test]+async fn recognizes_a_database_backed_in_memory_agent() {+ let agent = BotId::new_from_uuid(macro_uuid::Uuid::from_u128(0x0000_5678));+ let (id, sessions) = sessions_with_harness(agent, "in-memory");+ let containers = RoutedContainers::new(unreachable_sandbox(), None, sessions);++ let error = containers+ .route(id)+ .await+ .expect_err("an in-memory agent requires the shared in-process runtime");++ assert!(+ matches!(error, HarnessError::Container(message) if message.contains("in-process bot"))+ );+}+/// The whole point of the refusal: `@macro-new`'s sessions have no repository to/// clone, so a deployment that cannot run them in-process must not quietly/// bill a sandbox for one.diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 9da1972d60..6a1d5aedc3 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -7,6 +7,7 @@//! announcements, derives agent triggers from `macro.channels`, then drives//! the orchestrator from the resulting `macro.agent_sessions` events.+mod agent_runtime_directory;mod api;mod bots_directory;mod config;@@ -22,10 +23,15 @@ use agent_egress::outbound::macro_mcp::{MacroApiTokenSigner, WithMacroMcp};use agent_egress::outbound::mcp_credentials::PipedreamMcpCredentials;use agent_egress::outbound::session_authority::StoredTokenSessionAuthority;use agent_fold::domain::service::FoldedMessageService;-use agent_harness::domain::model::{HarnessCommand, HarnessDefaults, SessionDefaults};+use agent_harness::domain::model::{+ AgentKind, AgentRuntimeConfig, HarnessCommand, HarnessDefaults, SessionDefaults,+};+use agent_harness::domain::ports::AgentRuntimeDirectory as _;use agent_harness::domain::service::AgentHarnessService;+use agent_harness::domain::trigger_router::{+ RoutedTrigger, agent_trigger_bot_id, route_agent_trigger,+};use agent_harness::inbound::forward::ForwardGatewayState;-use agent_harness::inbound::kafka::{RoutedTrigger, route_agent_trigger};use agent_harness::inbound::runtime_gateway::RuntimeGatewayState;use agent_harness::outbound::agent_prompt_composer::LexicalAgentPromptComposer;use agent_harness::outbound::channel_announcer::ChannelAnnouncer;@@ -44,6 +50,7 @@ use agent_harness::outbound::runtime_registry::RuntimeRegistry;use agent_inmem::outbound::log_frames::LogFrameSource;use agent_inmem::outbound::manager::InMemAgentManager;use agent_inmem::outbound::rig_engine::RigTurnEngine;+use agent_runtime_directory::PgAgentRuntimeDirectory;use agent_session::domain::model::{ReplicaAddress, ReplicaId};use agent_session::domain::ports::{NoOpRealtime, SessionOwnership as _};use agent_session::domain::service::AgentSessionServiceImpl;@@ -313,7 +320,7 @@ async fn run() -> anyhow::Result<()> {// closed and drained on shutdown so nothing is dropped mid-publish.let event_broker_tracker = tokio_util::task::TaskTracker::new();let inmem = match inmem_bot {- Some(bot) => {+ Some(_) => {let tool_context = ai_tools::build_tool_service_context_from_env(pool.clone(),event_broker_tracker.clone(),@@ -325,7 +332,6 @@ async fn run() -> anyhow::Result<()> {// their model context from the same log every frame lands in.let frames = Arc::new(LogFrameSource::new(session_repo.clone()));Some(InMemRuntime {- bot,manager: InMemAgentManager::new(engine, frames),})}@@ -358,19 +364,46 @@ async fn run() -> anyhow::Result<()> {.context("CURSOR_REPO_URL is not a valid repository url")?,session_repo.clone(),);- // Every deployment serves its sandbox bot, the configured in-memory bot,- // and Cursor. Whether a given user can open a Cursor session depends on- // the key they registered and is answered at spawn.- let our_bots: Vec<BotId> = std::iter::once(bot_id)- .chain(inmem_bot)- .chain(std::iter::once(bot_id::CURSOR_BOT_ID))- .collect();+ // Fixed system agents retain their deployment defaults. User/team agents+ // are resolved from agent_configs for every trigger so newly-created or+ // edited agents require no service restart.+ let mut fixed_runtimes = vec![(+ bot_id,+ AgentRuntimeConfig {+ kind: AgentKind::SandboxedCoder,+ model: config.harness_model.clone(),+ harness: config.harness_slug.clone(),+ instructions: String::new(),+ },+ )];+ if let Some(inmem_bot) = inmem_bot {+ fixed_runtimes.push((+ inmem_bot,+ AgentRuntimeConfig {+ kind: AgentKind::InMemory,+ model: config.inmem_model.clone(),+ harness: config.inmem_harness_slug.clone(),+ instructions: String::new(),+ },+ ));+ }+ fixed_runtimes.push((+ bot_id::CURSOR_BOT_ID,+ AgentRuntimeConfig {+ kind: AgentKind::Cursor,+ model: config.harness_model.clone(),+ harness: "cursor".to_owned(),+ instructions: String::new(),+ },+ ));+ let runtime_directory =+ PgAgentRuntimeDirectory::new(PgBotsRepo::new(pool.clone()), fixed_runtimes.clone());// Logged because the failure mode this replaced was silent: a harness that// resolved no in-process bot booted healthy, passed its health check, and// dropped every in-process-bot mention as ForeignBot with nothing to show// for it.tracing::info!(- bots = ?our_bots.iter().map(|bot| bot.as_uuid()).collect::<Vec<_>>(),+ bots = ?fixed_runtimes.iter().map(|(bot, _)| bot.as_uuid()).collect::<Vec<_>>(),in_process_bot = ?inmem_bot.map(BotId::as_uuid),environment = %config.environment,"agent harness serving bots"@@ -673,7 +706,12 @@ async fn run() -> anyhow::Result<()> {tracing::Span::current().record("macro.event.id", tracing::field::display(event.event().event_id));- let routed = match route_agent_trigger(event.event().event.clone(), &our_bots) {+ let trigger_event = event.event().event.clone();+ let runtime = match agent_trigger_bot_id(&trigger_event) {+ Some(bot_id) => runtime_directory.runtime_for(bot_id).await?,+ None => None,+ };+ let routed = match route_agent_trigger(trigger_event, runtime) {Ok(routed) => routed,Err(skipped) => {// Info, not debug: a skip is the last visible tracediff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rsindex b88d19c1a5..e9c4d409e1 100644--- a/services/agent_harness_service/src/trigger.rs+++ b/services/agent_harness_service/src/trigger.rs@@ -2,10 +2,10 @@use agent_session::outbound::postgres::PgAgentSessionRepo;use agent_trigger::domain::processing::process_channel_event;-use agent_trigger::domain::service::{AgentBotLookup, AgentTriggerService};-use agent_trigger::outbound::{ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector};-use bot_id::BotId;-use bots::domain::ports::BotRepo as _;+use agent_trigger::domain::service::AgentTriggerService;+use agent_trigger::outbound::{+ BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector,+};use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::domain::broker_events::ChannelMacroEvent;use channels::outbound::pg_channels_repo::PgChannelsRepo;@@ -33,18 +33,6 @@ macro_event_broker::declare_topics!(DeclaredChannelEvent: ChannelMacroEvent);type TriggerKafkaAdapter = KafkaConsumerAdapter<AgentTriggerConsumerGroup, DeclaredChannelEvent>;type TriggerConsumer = MacroEventConsumerService<DeclaredChannelEvent, TriggerKafkaAdapter>;-struct PgAgentBotLookup(PgBotsRepo);--impl AgentBotLookup for PgAgentBotLookup {- async fn has_agent(&self, bot_id: BotId) -> agent_session::domain::error::Result<bool> {- self.0- .get_bot(bot_id)- .await- .map(|bot| bot.is_some_and(|bot| bot.has_agent))- .map_err(agent_session::domain::error::AgentSessionError::Unknown)- }-}-fn commit_message(consumer: &TriggerConsumer, message: &BorrowedMessage<'_>) -> anyhow::Result<()> {consumer.inner()@@ -72,7 +60,9 @@ async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> alet lexical = LexicalClient::new(internal_api_key, LexicalServiceUrl::new()?.to_string());let trigger = AgentTriggerService::new(PgAgentSessionRepo::new(pool.clone()),- PgAgentBotLookup(PgBotsRepo::new(pool.clone())),+ BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),+ BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),+ BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),LexicalReplyDetector::new(lexical),FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),ChannelThreadHistory::new(PgChannelsRepo::new(pool)),diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rsindex 242cba00dc..55612246dd 100644--- a/services/agent_trigger_service/src/main.rs+++ b/services/agent_trigger_service/src/main.rs@@ -4,11 +4,11 @@ mod config;use agent_session::outbound::postgres::PgAgentSessionRepo;use agent_trigger::domain::processing::process_channel_event;-use agent_trigger::domain::service::{AgentBotLookup, AgentTriggerService};-use agent_trigger::outbound::{ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector};+use agent_trigger::domain::service::AgentTriggerService;+use agent_trigger::outbound::{+ BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector,+};use anyhow::Context as _;-use bots::domain::models::BotId;-use bots::domain::ports::BotRepo as _;use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::domain::broker_events::ChannelMacroEvent;use channels::outbound::pg_channels_repo::PgChannelsRepo;@@ -44,18 +44,6 @@ fn commit_message(consumer: &TriggerConsumer, message: &BorrowedMessage<'_>) ->.map_err(|error| anyhow::anyhow!("failed to commit channel event offset: {error:?}"))}-struct PgAgentBotLookup(PgBotsRepo);--impl AgentBotLookup for PgAgentBotLookup {- async fn has_agent(&self, bot_id: BotId) -> agent_session::domain::error::Result<bool> {- self.0- .get_bot(bot_id)- .await- .map(|bot| bot.is_some_and(|bot| bot.has_agent))- .map_err(agent_session::domain::error::AgentSessionError::Unknown)- }-}-#[tokio::main]async fn main() -> anyhow::Result<()> {let entrypoint = MacroEntrypoint::default().init();@@ -79,7 +67,9 @@ async fn run() -> anyhow::Result<()> {);let trigger = AgentTriggerService::new(PgAgentSessionRepo::new(pool.clone()),- PgAgentBotLookup(PgBotsRepo::new(pool.clone())),+ BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),+ BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),+ BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),LexicalReplyDetector::new(lexical),FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),ChannelThreadHistory::new(PgChannelsRepo::new(pool)),diff --git a/services/authentication_service/src/api/cursor_api_key.rs b/services/authentication_service/src/api/cursor_api_key.rsindex afb4921958..9664a7ee16 100644--- a/services/authentication_service/src/api/cursor_api_key.rs+++ b/services/authentication_service/src/api/cursor_api_key.rs@@ -10,16 +10,11 @@//! that needs it: a user who has lost their key rotates it at Cursor and pastes//! a new one.+use crate::api::context::ApiContext;use axum::{Router,routing::{delete, get, put},};-use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};--use crate::api::context::ApiContext;--#[cfg(test)]-mod test;pub(in crate::api) mod delete_cursor_api_key;pub(in crate::api) mod get_cursor_api_key;@@ -39,13 +34,6 @@ pub fn router() -> Router<ApiContext> {.route("/default-model", put(put_cursor_default_model::handler))}-fn require_macro_staff(user_id: &MacroUserIdStr<'_>) -> Result<(), CursorApiKeyError> {- if user_id.email_part().domain_part() != "macro.com" {- return Err(CursorApiKeyError::NotMacroStaff);- }- Ok(())-}-/// What settings needs to render the Cursor connection.////// Deliberately thin. `registered` drives the whole UI; `updatedAt` lets it say@@ -74,11 +62,8 @@ pub enum CursorApiKeyError {/// The supplied value does not look like a Cursor API key.#[error("value does not look like a Cursor API key")]MalformedKey,- /// Cursor agents are currently restricted to Macro staff.- #[error("Cursor agents are only available to Macro staff")]- NotMacroStaff,- /// An operation that needs a connected account was attempted without one —- /// e.g. choosing a model before pasting a key.+ /// An operation that needs a connected account was attempted without one,+ /// such as listing the account's available models before pasting a key.#[error("connect a Cursor API key first")]NotConnected,/// Cursor's own API could not be reached or refused the request — listing@@ -97,7 +82,6 @@ impl axum::response::IntoResponse for CursorApiKeyError {let status = match self {// A shape this service cannot use is the client's mistake.Self::MalformedKey => StatusCode::BAD_REQUEST,- Self::NotMacroStaff => StatusCode::FORBIDDEN,Self::NotConnected => StatusCode::CONFLICT,Self::CursorUnavailable => StatusCode::BAD_GATEWAY,Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,diff --git a/services/authentication_service/src/api/cursor_api_key/delete_cursor_api_key.rs b/services/authentication_service/src/api/cursor_api_key/delete_cursor_api_key.rsindex 73575528cf..6da8bde0be 100644--- a/services/authentication_service/src/api/cursor_api_key/delete_cursor_api_key.rs+++ b/services/authentication_service/src/api/cursor_api_key/delete_cursor_api_key.rs@@ -1,7 +1,7 @@use axum::{Json, extract::State};use macro_authorization::{MacroAuthorizationExtractor, UserOnly};-use super::{CursorApiKeyError, CursorApiKeyStatus, require_macro_staff};+use super::{CursorApiKeyError, CursorApiKeyStatus};use crate::api::context::{ApiContext, AuthorizationService};/// Forgets the caller's Cursor API key.@@ -28,7 +28,6 @@ pub async fn handler(user_context: MacroAuthorizationExtractor<AuthorizationService, UserOnly>,) -> Result<Json<CursorApiKeyStatus>, CursorApiKeyError> {let user_id = &user_context.authorization.macro_user_id;- require_macro_staff(user_id)?;cursor_api_key::store::delete_cursor_api_key(&ctx.db, user_id.as_ref()).awaitdiff --git a/services/authentication_service/src/api/cursor_api_key/get_cursor_api_key.rs b/services/authentication_service/src/api/cursor_api_key/get_cursor_api_key.rsindex c1d8d9df65..623e514698 100644--- a/services/authentication_service/src/api/cursor_api_key/get_cursor_api_key.rs+++ b/services/authentication_service/src/api/cursor_api_key/get_cursor_api_key.rs@@ -1,7 +1,7 @@use axum::{Json, extract::State};use macro_authorization::{MacroAuthorizationExtractor, UserOnly};-use super::{CursorApiKeyError, CursorApiKeyStatus, require_macro_staff};+use super::{CursorApiKeyError, CursorApiKeyStatus};use crate::api::context::{ApiContext, AuthorizationService};/// Whether the caller has a Cursor API key registered.@@ -24,7 +24,6 @@ pub async fn handler(user_context: MacroAuthorizationExtractor<AuthorizationService, UserOnly>,) -> Result<Json<CursorApiKeyStatus>, CursorApiKeyError> {let user_id = &user_context.authorization.macro_user_id;- require_macro_staff(user_id)?;// Read even when the deployment has no KMS key: a key registered before the// deployment lost its configuration is still stored, and reporting it asdiff --git a/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rs b/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rsindex 047e58d0ee..dbe3e136c6 100644--- a/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rs+++ b/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rs@@ -4,7 +4,7 @@ use cursor_cloud_agents::domain::ports::CursorAgents;use macro_authorization::{MacroAuthorizationExtractor, UserOnly};use utoipa::ToSchema;-use super::{CursorApiKeyError, require_macro_staff};+use super::CursorApiKeyError;use crate::api::context::{ApiContext, AuthorizationService};/// One model the settings dropdown can offer.@@ -54,7 +54,6 @@ pub async fn handler(user_context: MacroAuthorizationExtractor<AuthorizationService, UserOnly>,) -> Result<Json<CursorModelsResponse>, CursorApiKeyError> {let user_id = &user_context.authorization.macro_user_id;- require_macro_staff(user_id)?;let stored = cursor_api_key::store::get_cursor_api_key(&ctx.db, user_id.as_ref()).awaitdiff --git a/services/authentication_service/src/api/cursor_api_key/put_cursor_api_key.rs b/services/authentication_service/src/api/cursor_api_key/put_cursor_api_key.rsindex 0986ede190..f734d7961a 100644--- a/services/authentication_service/src/api/cursor_api_key/put_cursor_api_key.rs+++ b/services/authentication_service/src/api/cursor_api_key/put_cursor_api_key.rs@@ -6,7 +6,7 @@ use cursor_api_key::cipher::CursorApiKey;use macro_authorization::{MacroAuthorizationExtractor, UserOnly};use utoipa::ToSchema;-use super::{CursorApiKeyError, CursorApiKeyStatus, require_macro_staff};+use super::{CursorApiKeyError, CursorApiKeyStatus};use crate::api::context::{ApiContext, AuthorizationService};/// The key the user pasted.@@ -44,7 +44,6 @@ pub async fn handler(extract::Json(req): extract::Json<PutCursorApiKeyRequest>,) -> Result<Json<CursorApiKeyStatus>, CursorApiKeyError> {let user_id = &user_context.authorization.macro_user_id;- require_macro_staff(user_id)?;let cipher = &ctx.cursor_api_key_cipher;diff --git a/services/authentication_service/src/api/cursor_api_key/put_cursor_default_model.rs b/services/authentication_service/src/api/cursor_api_key/put_cursor_default_model.rsindex b4c99b311d..891f3466ee 100644--- a/services/authentication_service/src/api/cursor_api_key/put_cursor_default_model.rs+++ b/services/authentication_service/src/api/cursor_api_key/put_cursor_default_model.rs@@ -5,7 +5,7 @@ use axum::{use macro_authorization::{MacroAuthorizationExtractor, UserOnly};use utoipa::ToSchema;-use super::{CursorApiKeyError, CursorApiKeyStatus, require_macro_staff};+use super::{CursorApiKeyError, CursorApiKeyStatus};use crate::api::context::{ApiContext, AuthorizationService};/// The model the user chose for their sessions.@@ -43,7 +43,6 @@ pub async fn handler(extract::Json(req): extract::Json<PutCursorDefaultModelRequest>,) -> Result<Json<CursorApiKeyStatus>, CursorApiKeyError> {let user_id = &user_context.authorization.macro_user_id;- require_macro_staff(user_id)?;let updated = cursor_api_key::store::set_default_model_id(&ctx.db,diff --git a/services/authentication_service/src/api/cursor_api_key/test.rs b/services/authentication_service/src/api/cursor_api_key/test.rsdeleted file mode 100644index 02f8932ae6..0000000000--- a/services/authentication_service/src/api/cursor_api_key/test.rs+++ /dev/null@@ -1,22 +0,0 @@-use macro_user_id::user_id::MacroUserIdStr;--use super::{CursorApiKeyError, require_macro_staff};--#[test]-fn macro_staff_domain_is_allowed() {- let user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();-- assert!(require_macro_staff(&user_id).is_ok());-}--#[test]-fn non_staff_and_lookalike_domains_are_forbidden() {- for email in ["[email protected]", "[email protected]"] {- let user_id = MacroUserIdStr::try_from_email(email).unwrap();-- assert!(matches!(- require_macro_staff(&user_id),- Err(CursorApiKeyError::NotMacroStaff)- ));- }-}diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex a0b2006ef2..1b93aac784 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -255,6 +255,9 @@ use utoipa::OpenApi;channels::inbound::axum_router::post_activity_handler,// bots+ bots::inbound::axum_router::create_agent_handler,+ bots::inbound::axum_router::list_agents_handler,+ bots::inbound::axum_router::update_agent_handler,bots::inbound::axum_router::get_self_bot_handler,bots::inbound::axum_router::list_bot_channels_handler,bots::inbound::axum_router::remove_bot_channel_handler,@@ -562,6 +565,10 @@ use utoipa::OpenApi;PostActivityRequest,// Bots+ bots::domain::models::Agent,+ bots::domain::models::AgentChannelScope,+ bots::domain::models::CreateAgentRequest,+ bots::domain::models::UpdateAgentRequest,bots::domain::models::Bot,bots::domain::models::BotKind,bots::domain::models::BotOwner,