diff --git a/backend/.sqlx/query-127d1d6a9cec24f34ff91718cf62befb986da3c1081b08a3a650435c53a88df5.json b/backend/.sqlx/query-127d1d6a9cec24f34ff91718cf62befb986da3c1081b08a3a650435c53a88df5.json new file mode 100644 index 0000000000..1bb018341b --- /dev/null +++ b/backend/.sqlx/query-127d1d6a9cec24f34ff91718cf62befb986da3c1081b08a3a650435c53a88df5.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH a AS (DELETE FROM slack_answered_message WHERE created_at < now() - interval '1 day')\n DELETE FROM slack_thread_agent WHERE created_at < now() - interval '90 days'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "127d1d6a9cec24f34ff91718cf62befb986da3c1081b08a3a650435c53a88df5" +} diff --git a/backend/.sqlx/query-2b39b2273d05ebe6e99be5b9051c153a170f5387831cd27e8cdbe5d052f839d0.json b/backend/.sqlx/query-2b39b2273d05ebe6e99be5b9051c153a170f5387831cd27e8cdbe5d052f839d0.json new file mode 100644 index 0000000000..7a12caaf6a --- /dev/null +++ b/backend/.sqlx/query-2b39b2273d05ebe6e99be5b9051c153a170f5387831cd27e8cdbe5d052f839d0.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM slack_agent_channel\n WHERE workspace_id = $1 AND agent_path = $2 AND channel_id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "2b39b2273d05ebe6e99be5b9051c153a170f5387831cd27e8cdbe5d052f839d0" +} diff --git a/backend/.sqlx/query-3164d5bc31dc128e59f9108c63ab8c11f7fe26ef16c5e6bfbd13bd081fc00ba3.json b/backend/.sqlx/query-3164d5bc31dc128e59f9108c63ab8c11f7fe26ef16c5e6bfbd13bd081fc00ba3.json new file mode 100644 index 0000000000..abb7a110c6 --- /dev/null +++ b/backend/.sqlx/query-3164d5bc31dc128e59f9108c63ab8c11f7fe26ef16c5e6bfbd13bd081fc00ba3.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, agent_path FROM slack_thread_agent\n WHERE slack_team_id = $1 AND channel_id = $2 AND thread_ts = $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "agent_path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "3164d5bc31dc128e59f9108c63ab8c11f7fe26ef16c5e6bfbd13bd081fc00ba3" +} diff --git a/backend/.sqlx/query-3e9f4f055c26a36ff60bf40f0c93a6ad1935e18cd09e08c3bd29d2ad7e2ae5dd.json b/backend/.sqlx/query-3e9f4f055c26a36ff60bf40f0c93a6ad1935e18cd09e08c3bd29d2ad7e2ae5dd.json new file mode 100644 index 0000000000..60c326a809 --- /dev/null +++ b/backend/.sqlx/query-3e9f4f055c26a36ff60bf40f0c93a6ad1935e18cd09e08c3bd29d2ad7e2ae5dd.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT c.channel_id, c.channel_name, c.agent_path, c.is_default\n FROM slack_agent_channel c\n JOIN resource r ON r.workspace_id = c.workspace_id AND r.path = c.agent_path\n WHERE c.workspace_id = $1 ORDER BY c.channel_name, c.agent_path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "channel_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "channel_name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "agent_path", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "is_default", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "3e9f4f055c26a36ff60bf40f0c93a6ad1935e18cd09e08c3bd29d2ad7e2ae5dd" +} diff --git a/backend/.sqlx/query-429004f6f71a06a93e8cdd688510ef502c1fc11ee23dec437e0f85f7b1e60a92.json b/backend/.sqlx/query-429004f6f71a06a93e8cdd688510ef502c1fc11ee23dec437e0f85f7b1e60a92.json new file mode 100644 index 0000000000..45ff97e02b --- /dev/null +++ b/backend/.sqlx/query-429004f6f71a06a93e8cdd688510ef502c1fc11ee23dec437e0f85f7b1e60a92.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM slack_thread_agent WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "429004f6f71a06a93e8cdd688510ef502c1fc11ee23dec437e0f85f7b1e60a92" +} diff --git a/backend/.sqlx/query-44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f.json b/backend/.sqlx/query-44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f.json new file mode 100644 index 0000000000..212f6f067b --- /dev/null +++ b/backend/.sqlx/query-44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT c.workspace_id, c.agent_path, c.is_default FROM slack_agent_channel c\n JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id\n AND ws.slack_team_id = c.slack_team_id\n WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "agent_path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_default", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false + ] + }, + "hash": "44866e040f382b5e12aa21595bd1452aae8ca746348a6ac6b5bba26f5249166f" +} diff --git a/backend/.sqlx/query-4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e.json b/backend/.sqlx/query-4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e.json new file mode 100644 index 0000000000..1e83c28a49 --- /dev/null +++ b/backend/.sqlx/query-4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT result AS \"result: sqlx::types::Json\",\n status = 'success' AS \"success!\"\n FROM v2_job_completed WHERE id = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "result: sqlx::types::Json", + "type_info": "Jsonb" + }, + { + "ordinal": 1, + "name": "success!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + true, + null + ] + }, + "hash": "4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e" +} diff --git a/backend/.sqlx/query-5ef435d2a11fb8c834c0aa0ddbfd49f5962e2bfc8016dc7a7f8314675a9598d2.json b/backend/.sqlx/query-5ef435d2a11fb8c834c0aa0ddbfd49f5962e2bfc8016dc7a7f8314675a9598d2.json new file mode 100644 index 0000000000..4a0eefb573 --- /dev/null +++ b/backend/.sqlx/query-5ef435d2a11fb8c834c0aa0ddbfd49f5962e2bfc8016dc7a7f8314675a9598d2.json @@ -0,0 +1,19 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO slack_agent_channel\n (slack_team_id, channel_id, channel_name, workspace_id, agent_path, is_default)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (slack_team_id, channel_id, workspace_id, agent_path) DO UPDATE\n SET channel_name = EXCLUDED.channel_name, is_default = EXCLUDED.is_default", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "5ef435d2a11fb8c834c0aa0ddbfd49f5962e2bfc8016dc7a7f8314675a9598d2" +} diff --git a/backend/.sqlx/query-61546bd1f5cbb0fce960ce1f0603be0ee757a50739fd149836d1cd946087c878.json b/backend/.sqlx/query-61546bd1f5cbb0fce960ce1f0603be0ee757a50739fd149836d1cd946087c878.json new file mode 100644 index 0000000000..7268e60241 --- /dev/null +++ b/backend/.sqlx/query-61546bd1f5cbb0fce960ce1f0603be0ee757a50739fd149836d1cd946087c878.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT channel_id, channel_name, agent_path, is_default\n FROM slack_agent_channel WHERE workspace_id = $1 AND agent_path = $2 ORDER BY channel_name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "channel_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "channel_name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "agent_path", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "is_default", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "61546bd1f5cbb0fce960ce1f0603be0ee757a50739fd149836d1cd946087c878" +} diff --git a/backend/.sqlx/query-8b0a0dddd15b390b4d23067f55a74535817926e69a8df1bbc909b952635643fa.json b/backend/.sqlx/query-8b0a0dddd15b390b4d23067f55a74535817926e69a8df1bbc909b952635643fa.json new file mode 100644 index 0000000000..cccc6a7525 --- /dev/null +++ b/backend/.sqlx/query-8b0a0dddd15b390b4d23067f55a74535817926e69a8df1bbc909b952635643fa.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value->'run_on_behalf_of' = 'true'::jsonb AS run_on_behalf_of,\n value->>'on_behalf_of' AS on_behalf_of,\n value->'slack_anyone' = 'true'::jsonb AS slack_anyone\n FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run_on_behalf_of", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "on_behalf_of", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "slack_anyone", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "8b0a0dddd15b390b4d23067f55a74535817926e69a8df1bbc909b952635643fa" +} diff --git a/backend/.sqlx/query-8e1bd1c87ace3addbf2e641f5c0f315df6ffbb6461a4d466971f4cf30fba623b.json b/backend/.sqlx/query-8e1bd1c87ace3addbf2e641f5c0f315df6ffbb6461a4d466971f4cf30fba623b.json new file mode 100644 index 0000000000..9dec923475 --- /dev/null +++ b/backend/.sqlx/query-8e1bd1c87ace3addbf2e641f5c0f315df6ffbb6461a4d466971f4cf30fba623b.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, agent_path FROM slack_agent_channel\n WHERE slack_team_id = $1 AND channel_id = $2 AND is_default", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "agent_path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "8e1bd1c87ace3addbf2e641f5c0f315df6ffbb6461a4d466971f4cf30fba623b" +} diff --git a/backend/.sqlx/query-97b7a06758129c918392886eb05aac8df983a410e2e75f4bd4d29147a4f48b17.json b/backend/.sqlx/query-97b7a06758129c918392886eb05aac8df983a410e2e75f4bd4d29147a4f48b17.json new file mode 100644 index 0000000000..28e041fe00 --- /dev/null +++ b/backend/.sqlx/query-97b7a06758129c918392886eb05aac8df983a410e2e75f4bd4d29147a4f48b17.json @@ -0,0 +1,31 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COALESCE(r.value->'run_on_behalf_of' = 'true'::jsonb\n AND r.value->'slack_anyone' = 'true'::jsonb, false) AS \"anyone!\",\n r.value->>'on_behalf_of' AS on_behalf_of\n FROM slack_agent_channel c\n JOIN resource r ON r.workspace_id = c.workspace_id AND r.path = c.agent_path\n WHERE c.slack_team_id = $1 AND c.channel_id = $2 AND c.workspace_id = $3\n AND c.agent_path = $4 AND r.resource_type = 'ai_agent'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "anyone!", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "on_behalf_of", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "97b7a06758129c918392886eb05aac8df983a410e2e75f4bd4d29147a4f48b17" +} diff --git a/backend/.sqlx/query-af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc.json b/backend/.sqlx/query-af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc.json new file mode 100644 index 0000000000..c15c64b3cc --- /dev/null +++ b/backend/.sqlx/query-af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT c.agent_path FROM slack_agent_channel c\n JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id\n AND ws.slack_team_id = c.slack_team_id\n WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path LIMIT 11", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "agent_path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "af9c259d71af873d81ad788ab05cd0b52f561bfaac0d4e8d17b1aa0900dcc3bc" +} diff --git a/backend/.sqlx/query-c5697a48239f96add86676e2776582da9d9b3e33fdec630f4beac214e98c0cbc.json b/backend/.sqlx/query-c5697a48239f96add86676e2776582da9d9b3e33fdec630f4beac214e98c0cbc.json new file mode 100644 index 0000000000..417fe15655 --- /dev/null +++ b/backend/.sqlx/query-c5697a48239f96add86676e2776582da9d9b3e33fdec630f4beac214e98c0cbc.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO slack_answered_message (slack_team_id, channel_id, ts)\n VALUES ($1, $2, $3) ON CONFLICT DO NOTHING RETURNING true", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar" + ] + }, + "nullable": [ + null + ] + }, + "hash": "c5697a48239f96add86676e2776582da9d9b3e33fdec630f4beac214e98c0cbc" +} diff --git a/backend/.sqlx/query-c9a8aca5b40f9393ccab04edd10cb507b5e8dc0cca2ddd424e09d784e3e22be5.json b/backend/.sqlx/query-c9a8aca5b40f9393ccab04edd10cb507b5e8dc0cca2ddd424e09d784e3e22be5.json new file mode 100644 index 0000000000..9b906031dc --- /dev/null +++ b/backend/.sqlx/query-c9a8aca5b40f9393ccab04edd10cb507b5e8dc0cca2ddd424e09d784e3e22be5.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO slack_thread_agent (slack_team_id, channel_id, thread_ts, workspace_id, agent_path)\n VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "c9a8aca5b40f9393ccab04edd10cb507b5e8dc0cca2ddd424e09d784e3e22be5" +} diff --git a/backend/.sqlx/query-da0a8271da6f436e285afcf5e038baf294a42db77a301db01e5d2ccf1c8ae3a5.json b/backend/.sqlx/query-da0a8271da6f436e285afcf5e038baf294a42db77a301db01e5d2ccf1c8ae3a5.json new file mode 100644 index 0000000000..e662011ab0 --- /dev/null +++ b/backend/.sqlx/query-da0a8271da6f436e285afcf5e038baf294a42db77a301db01e5d2ccf1c8ae3a5.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username, email FROM usr\n WHERE workspace_id = $1 AND lower(email) = lower($2) AND NOT disabled", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "da0a8271da6f436e285afcf5e038baf294a42db77a301db01e5d2ccf1c8ae3a5" +} diff --git a/backend/.sqlx/query-f14b48a16ca770a062043a034a9d174c959438b5c6886935a2895879dbf72e3e.json b/backend/.sqlx/query-f14b48a16ca770a062043a034a9d174c959438b5c6886935a2895879dbf72e3e.json new file mode 100644 index 0000000000..4c11f9a737 --- /dev/null +++ b/backend/.sqlx/query-f14b48a16ca770a062043a034a9d174c959438b5c6886935a2895879dbf72e3e.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COALESCE(slack_name, slack_team_id) FROM workspace_settings\n WHERE workspace_id = $1 AND slack_team_id IS NOT NULL", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "coalesce", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "f14b48a16ca770a062043a034a9d174c959438b5c6886935a2895879dbf72e3e" +} diff --git a/backend/.sqlx/query-f4726ac9311b2206088e5cfce32b47532839f91d2ecc462a5971f8de2194a9bf.json b/backend/.sqlx/query-f4726ac9311b2206088e5cfce32b47532839f91d2ecc462a5971f8de2194a9bf.json new file mode 100644 index 0000000000..e893140464 --- /dev/null +++ b/backend/.sqlx/query-f4726ac9311b2206088e5cfce32b47532839f91d2ecc462a5971f8de2194a9bf.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT slack_team_id FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "slack_team_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "f4726ac9311b2206088e5cfce32b47532839f91d2ecc462a5971f8de2194a9bf" +} diff --git a/backend/.sqlx/query-f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397.json b/backend/.sqlx/query-f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397.json new file mode 100644 index 0000000000..30ec07404b --- /dev/null +++ b/backend/.sqlx/query-f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, slack_command_script IS NOT NULL AS \"has_script!\"\n FROM workspace_settings WHERE slack_team_id = $1\n ORDER BY slack_command_script IS NOT NULL DESC LIMIT 2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "has_script!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "f91c3e12549a3e037e8e784ad6ed439d762d17acb70793e9b26454572a156397" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 7db4a977f7..5aa1835620 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -a00bc02d4cf16a14d13cb6d2e86c55bf42129348 +4871a58b74a8a24029b63826013f565fc23ea5be diff --git a/backend/migrations/20261016105641_slack_agents.down.sql b/backend/migrations/20261016105641_slack_agents.down.sql new file mode 100644 index 0000000000..11210c1e87 --- /dev/null +++ b/backend/migrations/20261016105641_slack_agents.down.sql @@ -0,0 +1,3 @@ +DROP TABLE IF EXISTS slack_answered_message; +DROP TABLE IF EXISTS slack_thread_agent; +DROP TABLE IF EXISTS slack_agent_channel; diff --git a/backend/migrations/20261016105641_slack_agents.up.sql b/backend/migrations/20261016105641_slack_agents.up.sql new file mode 100644 index 0000000000..d59ad45ea4 --- /dev/null +++ b/backend/migrations/20261016105641_slack_agents.up.sql @@ -0,0 +1,54 @@ +-- The Slack channels an agent is shared in: anyone in one of them can ask it when it runs on +-- behalf of its identity, the workspace members their Slack email belongs to otherwise. Keyed by the Slack team rather than the workspace, as channels are, +-- and at most one agent per channel answers a message that names none. The agent key cascades, +-- so a renamed agent keeps its channels and a deleted one leaves them. +CREATE TABLE slack_agent_channel ( + slack_team_id VARCHAR(255) NOT NULL, + channel_id VARCHAR(255) NOT NULL, + channel_name VARCHAR(255) NOT NULL, + workspace_id VARCHAR(50) NOT NULL, + agent_path VARCHAR(255) NOT NULL, + is_default BOOLEAN NOT NULL DEFAULT false, + PRIMARY KEY (slack_team_id, channel_id, workspace_id, agent_path), + FOREIGN KEY (workspace_id, agent_path) REFERENCES resource (workspace_id, path) + ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE INDEX index_slack_agent_channel_workspace ON slack_agent_channel (workspace_id, agent_path); +CREATE UNIQUE INDEX index_slack_agent_channel_default ON slack_agent_channel (slack_team_id, channel_id) + WHERE is_default; + +-- The agent a Slack thread was started with, so a follow-up that names no agent goes to it. +CREATE TABLE slack_thread_agent ( + slack_team_id VARCHAR(255) NOT NULL, + channel_id VARCHAR(255) NOT NULL, + thread_ts VARCHAR(255) NOT NULL, + workspace_id VARCHAR(50) NOT NULL, + agent_path VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (slack_team_id, channel_id, thread_ts), + FOREIGN KEY (workspace_id, agent_path) REFERENCES resource (workspace_id, path) + ON DELETE CASCADE ON UPDATE CASCADE +); + +CREATE INDEX index_slack_thread_agent_workspace ON slack_thread_agent (workspace_id, agent_path); +CREATE INDEX index_slack_thread_agent_created_at ON slack_thread_agent (created_at); + +-- The Slack messages an agent has taken up. Slack resends an event it did not see acknowledged, +-- and posts a direct message mentioning the bot as two events; only the first is answered. +CREATE TABLE slack_answered_message ( + slack_team_id VARCHAR(255) NOT NULL, + channel_id VARCHAR(255) NOT NULL, + ts VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (slack_team_id, channel_id, ts) +); + +CREATE INDEX index_slack_answered_message_created_at ON slack_answered_message (created_at); + +GRANT ALL ON slack_answered_message TO windmill_admin; +GRANT ALL ON slack_answered_message TO windmill_user; +GRANT ALL ON slack_agent_channel TO windmill_admin; +GRANT ALL ON slack_agent_channel TO windmill_user; +GRANT ALL ON slack_thread_agent TO windmill_admin; +GRANT ALL ON slack_thread_agent TO windmill_user; diff --git a/backend/summarized_schema.txt b/backend/summarized_schema.txt index 43b3d591ea..2bf6b0188f 100644 --- a/backend/summarized_schema.txt +++ b/backend/summarized_schema.txt @@ -188,6 +188,11 @@ schedule: workspace_id(char), path(char), edited_by(char), edited_at(ts), schedu script: workspace_id(char), hash(bigint), path(char), parent_hashes(bigint[]), summary(text), description(text), content(text), created_by(char), created_at(ts), archived(bool), schema(json), deleted(bool), is_template(bool), extra_perms(jsonb), lock(text), lock_error_logs(text), language(script_lang), kind(script_kind), tag(char), draft_only(bool), envs(char), concurrent_limit(int), concurrency_time_window_s(int), cache_ttl(int), dedicated_worker(bool), ws_error_handler_muted(bool), priority(smallint), timeout(int), delete_after_use(bool), restart_unless_cancelled(bool), concurrency_key(char), visible_to_runner_only(bool), auto_kind(varchar), codebase(char), has_preprocessor(bool), schema_validation(bool), assets(jsonb), debounce_key(char), debounce_delay_s(int), cache_ignore_s3_path(bool), runnable_settings_handle(bigint), labels(text[]), on_behalf_of(varchar), on_behalf_of_email(text), job_token_scopes(text[]) FK: (workspace_id) -> workspace(id) skip_workspace_diff_tally: workspace_id(char), added_at(ts) +slack_agent_channel: slack_team_id(char), channel_id(char), channel_name(char), workspace_id(char), agent_path(char), is_default(bool) + FK: (workspace_id, agent_path) -> resource(workspace_id, path) +slack_answered_message: slack_team_id(char), channel_id(char), ts(char), created_at(timestamptz) +slack_thread_agent: slack_team_id(char), channel_id(char), thread_ts(char), workspace_id(char), agent_path(char), created_at(timestamptz) + FK: (workspace_id, agent_path) -> resource(workspace_id, path) sqs_trigger: path(char), queue_url(char), aws_resource_path(char), message_attributes(text[]), script_path(char), is_flow(bool), workspace_id(char), edited_by(char), email(char), edited_at(ts), extra_perms(jsonb), error(text), server_id(char), last_server_ping(ts), aws_auth_resource_type(aws_auth_resource_type), error_handler_path(char), error_handler_args(jsonb), retry(jsonb), mode(trigger_mode), labels(text[]) FK: (workspace_id) -> workspace(id) trashbin: id(bigint), workspace_id(char), item_kind(char), item_path(char), item_data(jsonb), deleted_by(char), deleted_at(ts), expires_at(ts) diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index eb00c4106d..0c70946c58 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -1611,10 +1611,9 @@ async fn edit_slack_command( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(es): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let mut tx = db.begin().await?; if es.slack_command_script.is_some() { @@ -1981,10 +1980,9 @@ async fn edit_webhook( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(ew): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; if *CLOUD_HOSTED { return Err(Error::BadRequest( @@ -2098,10 +2096,9 @@ async fn edit_dbt_warehouses( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(new_config): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let new_config = new_config.dbt_warehouses; if let Some(map) = new_config.as_ref() { for (name, cfg) in map.iter() { @@ -2172,10 +2169,9 @@ async fn edit_large_file_storage_config( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(new_config): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let mut tx = db.begin().await?; @@ -4127,10 +4123,9 @@ async fn edit_ducklake_config( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, email, .. }: ApiAuthed, Json(new_config): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let is_superadmin = require_super_admin(&db, &authed).await.is_ok(); // Lake names end up interpolated in `ATTACH 'ducklake://'`, @@ -4256,8 +4251,8 @@ async fn edit_ducklake_config( &w_id, &new_config.settings.ducklakes, &old_ducklakes, - &username, - &email, + &authed.username, + &authed.email, ) .await?; @@ -4285,10 +4280,9 @@ async fn edit_datatable_config( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(mut new_config): Json, ) -> JsonResult { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let is_superadmin = require_super_admin(&db, &authed).await.is_ok(); let mut tx = db.begin().await?; @@ -5023,10 +5017,9 @@ async fn edit_git_sync_config( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(new_config): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; check_git_sync_access(&db, &w_id).await?; let mut tx = db.begin().await?; @@ -5277,10 +5270,9 @@ async fn edit_git_sync_repository( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(mut new_config): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; check_git_sync_access(&db, &w_id).await?; // Validate the resource path format @@ -5500,10 +5492,9 @@ async fn delete_git_sync_repository( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(request): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; // No check_git_sync_access here — admins should always be able to delete/clean up repos if request.git_repo_resource_path.is_empty() { @@ -5653,10 +5644,9 @@ async fn edit_deploy_ui_config( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(new_config): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let mut tx = db.begin().await?; let args_for_audit = format!("{:?}", new_config.deploy_ui_settings); @@ -5872,10 +5862,9 @@ async fn edit_default_scripts( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(new_config): Json>, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let mut tx = db.begin().await?; @@ -5946,7 +5935,6 @@ async fn edit_default_app( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(new_config): Json, ) -> Result { #[cfg(not(feature = "enterprise"))] @@ -5957,7 +5945,7 @@ async fn edit_default_app( )); } - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let mut tx = db.begin().await?; @@ -6039,10 +6027,9 @@ async fn edit_error_handler( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(ee): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; // Normalize to new format (handles both old CLI and new CLI requests) let ee = ee.into_normalized(); @@ -11012,10 +10999,9 @@ async fn edit_workspace( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(ew): Json, ) -> Result { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; let mut tx = db.begin().await?; sqlx::query!( "UPDATE workspace SET name = $1, owner = $2 WHERE id = $3", @@ -15325,26 +15311,19 @@ pub async fn apply_settings_edit( body: serde_json::Value, ) -> Result { use SettingsEdit::*; - let a = authed.clone(); + let a = authed; let (d, p) = (Extension(db), Path(w_id)); match edit { - Webhook => edit_webhook(a, d, p, authed, settings_edit_body(edit, body)?).await?, + Webhook => edit_webhook(a, d, p, settings_edit_body(edit, body)?).await?, AutoInvite => edit_auto_invite(a, d, p, settings_edit_body(edit, body)?).await?, InstanceGroups => edit_instance_groups(a, d, p, settings_edit_body(edit, body)?).await?, - ErrorHandler => { - edit_error_handler(a, d, p, authed, settings_edit_body(edit, body)?).await? - } + ErrorHandler => edit_error_handler(a, d, p, settings_edit_body(edit, body)?).await?, SuccessHandler => edit_success_handler(a, d, p, settings_edit_body(edit, body)?).await?, LargeFileStorage => { - edit_large_file_storage_config(a, d, p, authed, settings_edit_body(edit, body)?).await? + edit_large_file_storage_config(a, d, p, settings_edit_body(edit, body)?).await? } - GitSync => edit_git_sync_config(a, d, p, authed, settings_edit_body(edit, body)?).await?, - DefaultScripts => { - edit_default_scripts(a, d, p, authed, settings_edit_body(edit, body)?).await? - } - #[cfg(feature = "enterprise")] - DefaultApp => edit_default_app(a, d, p, authed, settings_edit_body(edit, body)?).await?, - #[cfg(not(feature = "enterprise"))] + GitSync => edit_git_sync_config(a, d, p, settings_edit_body(edit, body)?).await?, + DefaultScripts => edit_default_scripts(a, d, p, settings_edit_body(edit, body)?).await?, DefaultApp => edit_default_app(a, d, p, settings_edit_body(edit, body)?).await?, Color => change_workspace_color(a, p, d, settings_edit_body(edit, body)?).await?, OperatorSettings => { @@ -15352,20 +15331,16 @@ pub async fn apply_settings_edit( } Datatable => { let Json(result) = - edit_datatable_config(a, d, p, authed, settings_edit_body(edit, body)?).await?; + edit_datatable_config(a, d, p, settings_edit_body(edit, body)?).await?; return serde_json::to_value(result).map_err(|e| Error::internal_err(e.to_string())); } - SlackCommand => { - edit_slack_command(a, d, p, authed, settings_edit_body(edit, body)?).await? - } + SlackCommand => edit_slack_command(a, d, p, settings_edit_body(edit, body)?).await?, SetSlackOAuth => set_slack_oauth_config(a, d, p, settings_edit_body(edit, body)?).await?, DeleteSlackOAuth => delete_slack_oauth_config(a, d, p).await?, - Ducklake => edit_ducklake_config(a, d, p, authed, settings_edit_body(edit, body)?).await?, - DbtWarehouses => { - edit_dbt_warehouses(a, d, p, authed, settings_edit_body(edit, body)?).await? - } + Ducklake => edit_ducklake_config(a, d, p, settings_edit_body(edit, body)?).await?, + DbtWarehouses => edit_dbt_warehouses(a, d, p, settings_edit_body(edit, body)?).await?, #[cfg(feature = "enterprise")] - DeployUi => edit_deploy_ui_config(a, d, p, authed, settings_edit_body(edit, body)?).await?, + DeployUi => edit_deploy_ui_config(a, d, p, settings_edit_body(edit, body)?).await?, #[cfg(not(feature = "enterprise"))] DeployUi => edit_deploy_ui_config(a, d, p).await?, GuestAccess => edit_guest_access(a, d, p, settings_edit_body(edit, body)?).await?, diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 28cef74ef1..00617d262a 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -13646,6 +13646,188 @@ paths: items: $ref: "#/components/schemas/FlowConversation" + /w/{workspace}/slack_agents/channels: + get: + summary: list the Slack channels this workspace's agents are shared in + operationId: listSlackAgentChannels + tags: + - slack_agents + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: each agent shared in a channel, with whether it is the channel's default + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SlackAgentChannel" + + /w/{workspace}/slack_agents/available_channels: + get: + summary: list the connected Slack workspace's public channels + operationId: listAvailableSlackChannels + tags: + - slack_agents + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: cursor + description: the next_cursor of the previous page + in: query + schema: + type: string + responses: + "200": + description: a page of public channels + content: + application/json: + schema: + type: object + properties: + channels: + type: array + items: + type: object + properties: + id: + type: string + name: + type: string + required: + - id + - name + next_cursor: + type: string + required: + - channels + + /w/{workspace}/slack_agents/status: + get: + summary: whether agents can answer in Slack on this instance + operationId: getSlackAgentsStatus + tags: + - slack_agents + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: the instance's readiness for agents in Slack + content: + application/json: + schema: + type: object + properties: + signing_secret_set: + type: boolean + description: agents answer in Slack only when the server has the Slack app's signing secret (SLACK_SIGNING_SECRET) + required: + - signing_secret_set + + /w/{workspace}/slack_agents/agent_channels/{path}: + get: + summary: the Slack channels an agent is shared in, and whether the caller can share it + operationId: getAgentSlackChannels + tags: + - slack_agents + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/Path" + responses: + "200": + description: the agent's Slack channels + content: + application/json: + schema: + type: object + properties: + slack_team_name: + type: string + description: the connected Slack workspace; absent when Slack is not connected + signing_secret_set: + type: boolean + description: agents answer in Slack only when the server has the Slack app's signing secret (SLACK_SIGNING_SECRET) + bot_name: + type: string + description: the bot's Slack handle; absent when Slack can't be reached + missing_scopes: + type: array + items: + type: string + description: agent scopes the workspace's Slack connection lacks, so it must be reconnected with AI agents enabled + runs_as: + type: string + description: who the agent runs as (its on_behalf_of); absent unless it runs on behalf of someone + anyone: + type: boolean + description: whether anyone in its channels can ask it (its slack_anyone, kept only while it runs on behalf of someone), rather than workspace members only + can_share: + type: boolean + description: whether the caller can change the agent's channels, as anyone who can edit it can + channels: + type: array + items: + $ref: "#/components/schemas/SlackAgentChannel" + required: + - channels + - signing_secret_set + - missing_scopes + - anyone + - can_share + post: + summary: share an agent in a Slack channel, or change how it answers there + description: the workspace members in the channel whose Slack email matches and who can read the agent can then ask it, or anyone there when its settings say so (slack_anyone, with run_on_behalf_of). Needs edit access to the agent; making it the channel's default takes an admin. + operationId: shareAgentInSlackChannel + tags: + - slack_agents + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/Path" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + channel_id: + type: string + channel_name: + type: string + is_default: + type: boolean + description: whether the agent answers bot mentions in the channel that name no agent + required: + - channel_id + - channel_name + responses: + "200": + description: agent shared + content: + text/plain: + schema: + type: string + delete: + summary: stop sharing an agent in a Slack channel + operationId: unshareAgentFromSlackChannel + tags: + - slack_agents + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/Path" + - name: channel_id + in: query + required: true + schema: + type: string + responses: + "200": + description: agent no longer shared there + content: + text/plain: + schema: + type: string + /w/{workspace}/flow_conversations/update/{conversation_id}: post: summary: rename flow conversation @@ -29944,6 +30126,24 @@ components: definition_changed: type: boolean + SlackAgentChannel: + type: object + properties: + channel_id: + type: string + channel_name: + type: string + agent_path: + type: string + is_default: + type: boolean + description: whether the agent answers bot mentions in the channel that name no agent + required: + - channel_id + - channel_name + - agent_path + - is_default + FlowConversation: type: object required: diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index ebd83a52a5..bec7180f19 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -46,14 +46,29 @@ pub(crate) async fn run_agent( Query(run_query): Query, Json(args): Json>>, ) -> Result<(StatusCode, String)> { - #[cfg(feature = "enterprise")] - crate::jobs::check_license_key_valid().await?; - let path = path.to_path(); check_scopes(&authed, || format!("jobs:run:agents:{path}"))?; + let uuid = run_agent_as(&authed, &db, &user_db, &w_id, path, &run_query, &args).await?; + Ok((StatusCode::CREATED, uuid.to_string())) +} + +/// [`run_agent`] for a caller already authenticated, such as the identity of an agent shared in a +/// Slack channel. +pub(crate) async fn run_agent_as( + authed: &ApiAuthed, + db: &DB, + user_db: &UserDB, + w_id: &str, + path: &str, + run_query: &RunJobQuery, + args: &HashMap>, +) -> Result { + #[cfg(feature = "enterprise")] + crate::jobs::check_license_key_valid().await?; + // Read through the caller's own permissions: reading the agent is what allows running it. - let mut tx = user_db.clone().begin(&authed).await?; + let mut tx = user_db.clone().begin(authed).await?; let value = sqlx::query_scalar!( "SELECT value AS \"value: sqlx::types::Json\" FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", @@ -68,11 +83,14 @@ pub(crate) async fn run_agent( "Agent {path} has no configuration" ))); }; - // Who the agent runs as, not one of its inputs: its identity when it opts in, as a deployed - // flow does. + // Who the agent runs as and who can ask it in Slack, not inputs: its identity when it opts + // in, as a deployed flow does. let obj = value.as_object_mut(); let (agent_obo, run_obo) = obj - .map(|o| (o.remove("on_behalf_of"), o.remove("run_on_behalf_of"))) + .map(|o| { + o.remove("slack_anyone"); + (o.remove("on_behalf_of"), o.remove("run_on_behalf_of")) + }) .unwrap_or_default(); let agent_obo = agent_obo .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) @@ -97,8 +115,7 @@ pub(crate) async fn run_agent( )?; let on_behalf_of = - windmill_common::on_behalf_of_from_permissioned_as(agent_obo.as_deref(), &w_id, &db) - .await?; + windmill_common::on_behalf_of_from_permissioned_as(agent_obo.as_deref(), w_id, db).await?; // As `run_flow` picks the identity of a deployed flow: the agent's own when it has one, the // caller's otherwise, which lends nobody's permissions. let (email, permissioned_as, push_authed, isolation) = if let Some(obo) = on_behalf_of.as_ref() @@ -130,20 +147,20 @@ pub(crate) async fn run_agent( ))); } #[cfg(all(feature = "parquet", feature = "private"))] - check_attachments_readable(&db, &authed, &w_id, &args).await?; + check_attachments_readable(db, authed, w_id, args).await?; } - let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?; - let end_user_email = run_end_user_email(&db, &w_id, &authed, None).await?; + let scope_ceiling = windmill_api_auth::caller_scope_ceiling(db, authed).await?; + let end_user_email = run_end_user_email(db, w_id, authed, None).await?; let (uuid, mut tx) = push( - &db, + db, isolation, - &w_id, + w_id, JobPayload::RawFlow { value: flow_value, path: Some(run_path.clone()), restarted_from: None, }, - PushArgs::from(&args), + PushArgs::from(args), authed.display_username(), email, permissioned_as, @@ -172,7 +189,7 @@ pub(crate) async fn run_agent( ) .await?; - if let Some(memory_id) = run_query.memory_key(&w_id, &run_path) { + if let Some(memory_id) = run_query.memory_key(w_id, &run_path) { set_flow_memory_id(&mut tx, uuid, memory_id).await?; } if chat { @@ -180,20 +197,20 @@ pub(crate) async fn run_agent( // agent as deployed, not a draft under test. handle_chat_conversation_messages( &mut tx, - &authed, - &w_id, + authed, + w_id, &run_path, - &run_query, + run_query, args.get("user_message"), uuid, false, - &args, + args, ) .await?; } tx.commit().await?; - Ok((StatusCode::CREATED, uuid.to_string())) + Ok(uuid) } /// The step fetches the message's files with its job's token, so a run as the agent's identity diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 732675e78f..3bf21463eb 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -164,6 +164,9 @@ mod scim_oss; mod scripts; mod secret_backend_ext; mod service_logs; +// Answering in Slack is only reached from the EE Slack event handlers. +#[cfg_attr(not(all(feature = "oauth2", feature = "private")), allow(dead_code))] +mod slack_agents; mod slack_approvals; #[cfg(all(feature = "smtp", feature = "private"))] pub mod smtp_server_ee; @@ -258,6 +261,11 @@ lazy_static::lazy_static! { .unwrap_or_else(|_| "commands,chat:write,chat:write.public,channels:join,files:write,app_mentions:read,im:history,im:read".to_string()); } +/// Added to `SLACK_OAUTH_SCOPES` when a workspace connects with AI agents enabled: whether a +/// message's sender is a person of the team and, for agents that run as their asker, their email, +/// and the channel picker. Opt-in, as a Slack app must declare every scope it is asked for. +pub const SLACK_AGENT_SCOPES: &[&str] = &["users:read", "users:read.email", "channels:read"]; + // Compliance with cloud events spec. pub async fn add_webhook_allowed_origin( req: axum::extract::Request, @@ -682,6 +690,7 @@ pub async fn run_server( .nest("/embeddings", embeddings::workspaced_service()) .nest("/favorites", favorite::workspaced_service()) .nest("/flows", flows::workspaced_service()) + .nest("/slack_agents", slack_agents::workspaced_service()) .nest("/runnables", runnables::workspaced_service()) .nest( "/workspace_dependencies", diff --git a/backend/windmill-api/src/slack_agents.rs b/backend/windmill-api/src/slack_agents.rs new file mode 100644 index 0000000000..6945955bcb --- /dev/null +++ b/backend/windmill-api/src/slack_agents.rs @@ -0,0 +1,1106 @@ +//! AI agents answering in Slack. +//! +//! An agent answers only in the Slack channels it is shared in, to the workspace members whose +//! email matches the asker's Slack email, as Windmill would run it for them: through their own +//! permissions, so only if they can read it. With `slack_anyone`, set in its settings and kept +//! only while it runs on behalf of an identity, it answers anyone in those channels instead: the +//! channel is the trust boundary, as Slack decides who is in it, and everyone runs it as that +//! identity, who agreed to it by deploying the agent so. Who may share it is then only who may +//! edit it. A message reaches an agent when it names it (`+name` or `~name`), when its thread was +//! started with it, or, for a mention, when it is its channel's default. Anything else goes to the workspace's +//! command script as before, or, where there is none, is answered with the agents shared there. +//! One Slack thread is one conversation per person: a run's tool results are its asker's to see, +//! and a shared conversation would hand them to whoever replies next. + +use std::collections::HashMap; + +use axum::{ + extract::{Path, Query}, + routing::get, + Extension, Json, Router, +}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use uuid::Uuid; +use windmill_api_auth::{ + fetch_api_authed, fetch_api_authed_from_permissioned_as, require_is_writer, +}; +use windmill_common::{ + error::{Error, JsonResult, Result}, + oauth2::WORKSPACE_SLACK_BOT_TOKEN_PATH, + utils::{calculate_hash, StripPath}, + variables::{get_secret_value_as_admin, get_workspace_key}, + BASE_URL, +}; + +use crate::{ + agent_runs::run_agent_as, + db::{ApiAuthed, DB}, + jobs::RunJobQuery, + HTTP_CLIENT, +}; +use windmill_common::db::UserDB; + +/// How long the reply waits for the agent before pointing at the run instead. +const MAX_WAIT_SECS: u64 = 3600; +/// Under the 12,000 characters Slack takes in a markdown block. +const MAX_REPLY_CHARS: usize = 11_000; + +pub fn workspaced_service() -> Router { + Router::new() + .route("/channels", get(list_workspace_channels)) + .route("/available_channels", get(list_available_channels)) + .route( + "/agent_channels/{*path}", + get(get_agent_slack).post(share_agent).delete(unshare_agent), + ) + .route("/status", get(status)) +} + +#[derive(Serialize)] +struct SlackAgentsStatus { + signing_secret_set: bool, +} + +async fn status(_authed: ApiAuthed) -> Json { + Json(SlackAgentsStatus { signing_secret_set: signing_secret_set() }) +} + +/// Agents answer only when the server verifies Slack's request signatures. +fn signing_secret_set() -> bool { + #[cfg(feature = "oauth2")] + { + crate::SLACK_SIGNING_SECRET.is_some() + } + #[cfg(not(feature = "oauth2"))] + { + false + } +} + +#[derive(Serialize)] +struct SharedChannel { + channel_id: String, + channel_name: String, + agent_path: String, + is_default: bool, +} + +/// Listed through the caller's permissions: an agent they cannot read stays unnamed. +async fn list_workspace_channels( + authed: ApiAuthed, + Extension(user_db): Extension, + Path(w_id): Path, +) -> JsonResult> { + let mut tx = user_db.begin(&authed).await?; + let rows = sqlx::query_as!( + SharedChannel, + "SELECT c.channel_id, c.channel_name, c.agent_path, c.is_default + FROM slack_agent_channel c + JOIN resource r ON r.workspace_id = c.workspace_id AND r.path = c.agent_path + WHERE c.workspace_id = $1 ORDER BY c.channel_name, c.agent_path", + w_id + ) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + Ok(Json(rows)) +} + +#[derive(Serialize)] +struct AgentSlack { + /// The connected Slack workspace's name; `None` when Slack is not connected. + slack_team_name: Option, + /// Agents answer only when the instance verifies Slack's request signatures. + signing_secret_set: bool, + /// The bot's Slack handle, what people mention; `None` when Slack can't be reached. + bot_name: Option, + /// Agent scopes the workspace's connection lacks: it was made without AI agents enabled. + missing_scopes: Vec, + /// Who the agent runs as, in Slack and elsewhere; `None` unless it runs on behalf of someone. + runs_as: Option, + /// Whether anyone in its channels can ask it, rather than workspace members only. + anyone: bool, + /// Whether the caller can change its channels: anyone who can edit it. + can_share: bool, + channels: Vec, +} + +/// The agent's identity when it runs on behalf of one, and whether anyone in its channels can +/// ask it; the agent is read with the caller's permissions, so one they cannot read is not found. +async fn agent_identity( + authed: &ApiAuthed, + user_db: &UserDB, + w_id: &str, + path: &str, +) -> Result<(Option, bool)> { + let mut tx = user_db.clone().begin(authed).await?; + let row = sqlx::query!( + "SELECT value->'run_on_behalf_of' = 'true'::jsonb AS run_on_behalf_of, + value->>'on_behalf_of' AS on_behalf_of, + value->'slack_anyone' = 'true'::jsonb AS slack_anyone + FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent'", + w_id, + path + ) + .fetch_optional(&mut *tx) + .await?; + tx.commit().await?; + let row = row.ok_or_else(|| Error::NotFound(format!("Agent {path} not found")))?; + let runs_as = row + .on_behalf_of + .filter(|_| row.run_on_behalf_of == Some(true)); + let anyone = runs_as.is_some() && row.slack_anyone == Some(true); + Ok((runs_as, anyone)) +} + +async fn is_writer(authed: &ApiAuthed, db: &DB, w_id: &str, path: &str) -> Result { + Ok(require_is_writer( + authed, + path, + w_id, + db.clone(), + "SELECT extra_perms FROM resource WHERE path = $1 AND workspace_id = $2", + "resource", + ) + .await + .is_ok()) +} + +async fn get_agent_slack( + authed: ApiAuthed, + Extension(db): Extension, + Extension(user_db): Extension, + Path((w_id, path)): Path<(String, StripPath)>, +) -> JsonResult { + let path = path.to_path(); + let (runs_as, anyone) = agent_identity(&authed, &user_db, &w_id, path).await?; + let can_share = is_writer(&authed, &db, &w_id, path).await?; + let slack_team_name = sqlx::query_scalar!( + "SELECT COALESCE(slack_name, slack_team_id) FROM workspace_settings + WHERE workspace_id = $1 AND slack_team_id IS NOT NULL", + w_id + ) + .fetch_optional(&db) + .await? + .flatten(); + let channels = sqlx::query_as!( + SharedChannel, + "SELECT channel_id, channel_name, agent_path, is_default + FROM slack_agent_channel WHERE workspace_id = $1 AND agent_path = $2 ORDER BY channel_name", + w_id, + path + ) + .fetch_all(&db) + .await?; + let (bot_name, missing_scopes) = match slack_team_name { + Some(_) => bot_identity(&db, &w_id).await.unzip(), + None => (None, None), + }; + Ok(Json(AgentSlack { + slack_team_name, + signing_secret_set: signing_secret_set(), + bot_name, + missing_scopes: missing_scopes.unwrap_or_default(), + runs_as, + anyone, + can_share, + channels, + })) +} + +/// The bot's handle and the agent scopes its token lacks; `None` when Slack can't be reached. +async fn bot_identity(db: &DB, w_id: &str) -> Option<(String, Vec)> { + let token = bot_token(db, w_id).await.ok()?; + let call = async { + let res = HTTP_CLIENT + .post("https://slack.com/api/auth.test") + .bearer_auth(&token) + .send() + .await + .ok()?; + // Slack lists the token's scopes in this header on every Web API response. + let granted = res + .headers() + .get("x-oauth-scopes") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .collect::>(); + let body: serde_json::Value = res.json().await.ok()?; + let name = body["user"].as_str()?.to_string(); + let missing = crate::SLACK_AGENT_SCOPES + .iter() + .filter(|s| !granted.iter().any(|g| g == *s)) + .map(|s| s.to_string()) + .collect(); + Some((name, missing)) + }; + // On every agent page load: a slow Slack must not hold the page for the client's 20s timeout. + tokio::time::timeout(std::time::Duration::from_secs(3), call) + .await + .ok()? +} + +#[derive(Deserialize)] +struct ShareAgent { + channel_id: String, + channel_name: String, + #[serde(default)] + is_default: bool, +} + +/// Shares the agent in a channel, or changes how it answers there. +async fn share_agent( + authed: ApiAuthed, + Extension(db): Extension, + Extension(user_db): Extension, + Path((w_id, path)): Path<(String, StripPath)>, + Json(body): Json, +) -> Result { + let path = path.to_path(); + agent_identity(&authed, &user_db, &w_id, path).await?; + if !is_writer(&authed, &db, &w_id, path).await? { + return Err(Error::PermissionDenied(format!( + "Only those who can edit {path} can share it." + ))); + } + let team_id = connected_team(&db, &w_id).await?; + + if body.is_default { + // A channel belongs to the Slack team, which several workspaces may share: one agent + // must not take over the default another one holds. + let current = sqlx::query!( + "SELECT workspace_id, agent_path FROM slack_agent_channel + WHERE slack_team_id = $1 AND channel_id = $2 AND is_default", + team_id, + body.channel_id + ) + .fetch_optional(&db) + .await?; + match current { + Some(c) if c.workspace_id == w_id && c.agent_path == path => {} + Some(c) => { + return Err(Error::BadRequest(format!( + "{} already answers in #{} without being named. Make it stop there first.", + c.agent_path, body.channel_name + ))); + } + // It takes the channel's unnamed messages from the command script an admin set up. + None if !authed.is_admin => { + return Err(Error::PermissionDenied( + "Only workspace admins can make an agent answer a channel without being named." + .to_string(), + )); + } + None => {} + } + } + sqlx::query!( + "INSERT INTO slack_agent_channel + (slack_team_id, channel_id, channel_name, workspace_id, agent_path, is_default) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (slack_team_id, channel_id, workspace_id, agent_path) DO UPDATE + SET channel_name = EXCLUDED.channel_name, is_default = EXCLUDED.is_default", + team_id, + body.channel_id, + body.channel_name, + w_id, + path, + body.is_default + ) + .execute(&db) + .await?; + Ok(format!("{path} is shared in #{}", body.channel_name)) +} + +#[derive(Deserialize)] +struct UnshareQuery { + channel_id: String, +} + +/// Taking an agent out of a channel lends nothing, so anyone who can edit it can. +async fn unshare_agent( + authed: ApiAuthed, + Extension(db): Extension, + Path((w_id, path)): Path<(String, StripPath)>, + Query(q): Query, +) -> Result { + let path = path.to_path(); + if !is_writer(&authed, &db, &w_id, path).await? { + return Err(Error::PermissionDenied(format!( + "Only those who can edit {path} can stop sharing it." + ))); + } + sqlx::query!( + "DELETE FROM slack_agent_channel + WHERE workspace_id = $1 AND agent_path = $2 AND channel_id = $3", + w_id, + path, + q.channel_id + ) + .execute(&db) + .await?; + Ok(format!("{path} is no longer shared there")) +} + +#[derive(Serialize)] +struct SlackChannel { + id: String, + name: String, +} + +#[derive(Deserialize)] +struct ChannelsQuery { + cursor: Option, +} + +#[derive(Serialize)] +struct SlackChannels { + channels: Vec, + next_cursor: Option, +} + +/// The team's public channels, a page at a time, for picking one. Private channels stay out: +/// their names are for their members only. +async fn list_available_channels( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Query(q): Query, +) -> JsonResult { + if authed.is_operator { + return Err(Error::PermissionDenied( + "Operators can't share agents in Slack".to_string(), + )); + } + let token = bot_token(&db, &w_id).await?; + let mut form = vec![ + ("types", "public_channel".to_string()), + ("exclude_archived", "true".to_string()), + ("limit", "200".to_string()), + ]; + if let Some(cursor) = q.cursor.filter(|c| !c.is_empty()) { + form.push(("cursor", cursor)); + } + let res = slack_call(&token, "conversations.list", &form) + .await + .map_err(|e| Error::BadRequest(e.to_string()))?; + let channels = res["channels"] + .as_array() + .map(|cs| { + cs.iter() + .filter_map(|c| { + Some(SlackChannel { + id: c["id"].as_str()?.to_string(), + name: c["name"].as_str()?.to_string(), + }) + }) + .collect() + }) + .unwrap_or_default(); + let next_cursor = res["response_metadata"]["next_cursor"] + .as_str() + .filter(|c| !c.is_empty()) + .map(str::to_string); + Ok(Json(SlackChannels { channels, next_cursor })) +} + +async fn connected_team(db: &DB, w_id: &str) -> Result { + sqlx::query_scalar!( + "SELECT slack_team_id FROM workspace_settings WHERE workspace_id = $1", + w_id + ) + .fetch_optional(db) + .await? + .flatten() + .ok_or_else(|| Error::BadRequest("Slack is not connected to this workspace".to_string())) +} + +async fn bot_token(db: &DB, w_id: &str) -> Result { + get_secret_value_as_admin(db, w_id, WORKSPACE_SLACK_BOT_TOKEN_PATH).await +} + +/// A Slack Web API call, form-encoded since read methods such as `users.info` take no JSON. +/// Slack answers 200 with `ok: false` on failure; that is returned as the error. +async fn slack_call( + token: &str, + method: &str, + form: &[(&str, String)], +) -> anyhow::Result { + let res: serde_json::Value = HTTP_CLIENT + .post(format!("https://slack.com/api/{method}")) + .bearer_auth(token) + .form(form) + .send() + .await? + .json() + .await?; + if res["ok"].as_bool() != Some(true) { + let error = res["error"].as_str().unwrap_or("unknown_error"); + let needed = res["needed"].as_str().unwrap_or_default(); + anyhow::bail!("{method}: {error} {needed}"); + } + Ok(res) +} + +/// A message addressed to Windmill: a bot mention or a direct message. +pub struct SlackMessage { + pub team_id: String, + pub channel_id: String, + pub user_id: String, + /// With the bot mention stripped, still escaped the way Slack sends it. + pub text: String, + pub ts: String, + pub thread_ts: Option, + /// Whether this request's Slack signature was verified. Carried from the check rather than + /// re-read from the setting, which can be enabled between the two. + pub signed: bool, +} + +enum Route { + Agent(String), + /// No agent to run: say which ones are shared here, after `note` when there is one. + Help { + note: Option, + }, +} + +struct SharedHere { + workspace_id: String, + agent_path: String, + is_default: bool, +} + +/// Whether an agent answers this message; if so, the answer is under way when this returns. +/// `false` leaves the message to the workspace's command script. +pub async fn try_answer(db: &DB, msg: SlackMessage) -> Result { + // Without it the Slack endpoints take unsigned requests, and anyone could post as a channel. + if !msg.signed { + return Ok(false); + } + let text = decode_entities(&msg.text); + let (name, question) = split_agent_name(&text); + let thread_root = msg.thread_ts.clone().unwrap_or_else(|| msg.ts.clone()); + + // Only a workspace still connected to the team answers: disconnecting keeps its bot token. + let shared = sqlx::query_as!( + SharedHere, + "SELECT c.workspace_id, c.agent_path, c.is_default FROM slack_agent_channel c + JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id + AND ws.slack_team_id = c.slack_team_id + WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path", + msg.team_id, + msg.channel_id + ) + .fetch_all(db) + .await?; + let thread = sqlx::query!( + "SELECT workspace_id, agent_path FROM slack_thread_agent + WHERE slack_team_id = $1 AND channel_id = $2 AND thread_ts = $3", + msg.team_id, + msg.channel_id, + thread_root + ) + .fetch_optional(db) + .await? + // A thread's agent answers only while it is still shared here. + .and_then(|t| { + shared + .iter() + .find(|s| s.workspace_id == t.workspace_id && s.agent_path == t.agent_path) + }); + + let named = name.filter(|_| !shared.is_empty()).map(|name| { + let matches = shared + .iter() + .filter(|s| s.agent_path == name || s.agent_path.ends_with(&format!("/{name}"))) + .collect::>(); + (name, matches) + }); + let (here, route, source) = match named { + Some((_, matches)) if matches.len() == 1 => ( + matches[0], + Route::Agent(matches[0].agent_path.clone()), + "mention", + ), + Some((name, matches)) => { + let note = if matches.is_empty() { + format!("No agent named *{name}* is shared in this channel.") + } else { + format!("Several agents shared here are named *{name}*, use the whole path.") + }; + (&shared[0], Route::Help { note: Some(note) }, "help") + } + None => match thread.or_else(|| shared.iter().find(|s| s.is_default)) { + Some(s) => ( + s, + Route::Agent(s.agent_path.clone()), + if thread.is_some() { + "thread" + } else { + "channel_default" + }, + ), + None => match workspace_without_command_script(db, &msg.team_id).await? { + Some(w_id) => { + return start_answer( + db, + w_id, + Route::Help { note: None }, + "help", + question, + msg, + ) + .await; + } + None => return Ok(false), + }, + }, + }; + let w_id = here.workspace_id.clone(); + + // Recorded before answering, so a follow-up sent while the first answer is on its way + // already finds its agent. + if let Route::Agent(path) = &route { + if let Err(e) = + record_thread_agent(db, &msg.team_id, &msg.channel_id, &thread_root, &w_id, path).await + { + tracing::warn!("Could not record the Slack thread's agent: {e:#}"); + } + } + start_answer(db, w_id, route, source, question, msg).await +} + +async fn start_answer( + db: &DB, + w_id: String, + route: Route, + source: &str, + question: &str, + msg: SlackMessage, +) -> Result { + let first = sqlx::query_scalar!( + "INSERT INTO slack_answered_message (slack_team_id, channel_id, ts) + VALUES ($1, $2, $3) ON CONFLICT DO NOTHING RETURNING true", + msg.team_id, + msg.channel_id, + msg.ts + ) + .fetch_optional(db) + .await? + .is_some(); + if !first { + return Ok(true); + } + if matches!(route, Route::Agent(_)) { + windmill_common::feature_usage::log_feature_usage("slack_agent", "invoked", source); + } + let db = db.clone(); + let question = question.to_string(); + // ponytail: the reply waits in this API process, so a restart mid-run loses the reply (not + // the run, which still shows in Windmill); a job-completion hook would make it durable. + tokio::spawn(async move { + prune(&db).await; + if let Err(e) = answer(&db, &w_id, route, &question, msg).await { + tracing::error!("Slack agent answer failed: {e:#}"); + } + }); + Ok(true) +} + +async fn record_thread_agent( + db: &DB, + team_id: &str, + channel_id: &str, + thread_ts: &str, + w_id: &str, + agent_path: &str, +) -> Result<()> { + sqlx::query!( + "INSERT INTO slack_thread_agent (slack_team_id, channel_id, thread_ts, workspace_id, agent_path) + VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING", + team_id, + channel_id, + thread_ts, + w_id, + agent_path + ) + .execute(db) + .await?; + Ok(()) +} + +/// Best effort: a message already marked answered must still be answered if this fails. +async fn prune(db: &DB) { + let res = sqlx::query!( + "WITH a AS (DELETE FROM slack_answered_message WHERE created_at < now() - interval '1 day') + DELETE FROM slack_thread_agent WHERE created_at < now() - interval '90 days'" + ) + .execute(db) + .await; + if let Err(e) = res { + tracing::warn!("Could not prune Slack agent routing: {e:#}"); + } +} + +/// `+name rest` or `~name rest` → (name, rest). +fn split_agent_name(text: &str) -> (Option<&str>, &str) { + let text = text.trim(); + let Some(after) = text.strip_prefix('+').or_else(|| text.strip_prefix('~')) else { + return (None, text); + }; + let (name, rest) = after.split_once(char::is_whitespace).unwrap_or((after, "")); + if name.is_empty() + || !name + .chars() + .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '/' | '.')) + { + return (None, text); + } + (Some(name), rest.trim()) +} + +/// Slack escapes these three in message text. +fn decode_entities(text: &str) -> String { + text.replace("<", "<") + .replace(">", ">") + .replace("&", "&") +} + +/// The team's workspace when no workspace of the team has a command script to take the message: +/// the only one connected to it. +async fn workspace_without_command_script(db: &DB, team_id: &str) -> Result> { + let rows = sqlx::query!( + "SELECT workspace_id, slack_command_script IS NOT NULL AS \"has_script!\" + FROM workspace_settings WHERE slack_team_id = $1 + ORDER BY slack_command_script IS NOT NULL DESC LIMIT 2", + team_id + ) + .fetch_all(db) + .await?; + Ok(match rows.as_slice() { + [only] if !only.has_script => Some(only.workspace_id.clone()), + _ => None, + }) +} + +/// The agents shared in the message's channel, and how to ask one. +async fn help_text(db: &DB, msg: &SlackMessage, note: Option) -> Result { + let agents = sqlx::query_scalar!( + "SELECT c.agent_path FROM slack_agent_channel c + JOIN workspace_settings ws ON ws.workspace_id = c.workspace_id + AND ws.slack_team_id = c.slack_team_id + WHERE c.slack_team_id = $1 AND c.channel_id = $2 ORDER BY c.agent_path LIMIT 11", + msg.team_id, + msg.channel_id + ) + .fetch_all(db) + .await?; + let note = note.map(|n| format!("{n}\n\n")).unwrap_or_default(); + let Some(first) = agents.first() else { + let text = if msg.channel_id.starts_with('D') { + "Agents answer in the Slack channels they're shared in, not in direct messages." + } else { + "No agent is shared in this channel. Anyone who can edit an agent in Windmill can share it here from its settings." + }; + return Ok(format!("{note}{text}")); + }; + let handle = |p: &str| p.rsplit('/').next().unwrap_or(p).to_string(); + let mut list = agents + .iter() + .take(10) + .map(|p| format!("• `+{}` ({p})", handle(p))) + .collect::>() + .join("\n"); + if agents.len() > 10 { + list.push_str("\n• …"); + } + Ok(format!( + "{note}Start your message with an agent's name, for example `+{} what can you do?`\n\nAgents shared in this channel:\n{list}", + handle(first) + )) +} + +/// Who sent a message, as far as agents are concerned. +enum Asker { + /// With their Slack email, `None` when Slack hides it or the connection lacks the scope. + Person { email: Option }, + /// A bot or a workflow: never answered, so two bots cannot keep each other talking, and an + /// agent's identity is never lent to something no person typed. + Bot, + /// Someone from another Slack organization, in a channel shared with it. + Outsider, +} + +async fn asker(token: &str, msg: &SlackMessage) -> anyhow::Result { + if msg.user_id.is_empty() || msg.user_id == "USLACKBOT" { + return Ok(Asker::Bot); + } + let info = match slack_call(token, "users.info", &[("user", msg.user_id.clone())]).await { + Ok(info) => info, + // Slack hides some external users from the team's token. + Err(e) if e.to_string().contains("user_not_found") => return Ok(Asker::Outsider), + Err(e) => return Err(e), + }; + let user = &info["user"]; + if user["is_bot"].as_bool() == Some(true) { + return Ok(Asker::Bot); + } + if user["is_stranger"].as_bool() == Some(true) + || user["team_id"].as_str() != Some(msg.team_id.as_str()) + { + return Ok(Asker::Outsider); + } + Ok(Asker::Person { email: user["profile"]["email"].as_str().map(str::to_string) }) +} + +async fn answer( + db: &DB, + w_id: &str, + route: Route, + question: &str, + msg: SlackMessage, +) -> anyhow::Result<()> { + let token = bot_token(db, w_id).await?; + let channel = msg.channel_id.clone(); + + let asker = match asker(&token, &msg).await { + Ok(asker) => asker, + Err(e) if e.to_string().contains("missing_scope") => { + tracing::warn!("Slack agents in {w_id} need the connection's users:read scope: {e:#}"); + return Ok(()); + } + Err(e) => return Err(e), + }; + if matches!(asker, Asker::Bot) { + return Ok(()); + } + + let thread_root = msg.thread_ts.clone().unwrap_or_else(|| msg.ts.clone()); + let reply = Reply::start(&token, &channel, &thread_root).await?; + + let email = match asker { + Asker::Person { email } => email, + _ => { + return reply + .send( + "Agents answer only people from this Slack workspace.".to_string(), + None, + ) + .await; + } + }; + let agent_path = match route { + Route::Help { note } => return reply.send(help_text(db, &msg, note).await?, None).await, + Route::Agent(path) => path, + }; + + if question.is_empty() { + return reply + .send(format!("What would you like to ask `{agent_path}`?"), None) + .await; + } + + // Read at each message: who can ask follows the agent's last deploy. + let share = sqlx::query!( + "SELECT COALESCE(r.value->'run_on_behalf_of' = 'true'::jsonb + AND r.value->'slack_anyone' = 'true'::jsonb, false) AS \"anyone!\", + r.value->>'on_behalf_of' AS on_behalf_of + FROM slack_agent_channel c + JOIN resource r ON r.workspace_id = c.workspace_id AND r.path = c.agent_path + WHERE c.slack_team_id = $1 AND c.channel_id = $2 AND c.workspace_id = $3 + AND c.agent_path = $4 AND r.resource_type = 'ai_agent'", + msg.team_id, + channel, + w_id, + agent_path + ) + .fetch_optional(db) + .await?; + let members_only = share.as_ref().is_some_and(|s| !s.anyone); + let authed = match share { + None => { + return reply + .send( + format!("`{agent_path}` is no longer shared in this channel."), + None, + ) + .await; + } + Some(share) if !share.anyone => { + let Some(email) = email else { + return reply.send( + "Windmill can't read your Slack email. A workspace admin needs to reconnect Slack in the workspace settings to grant it.".to_string(), + None, + ) + .await; + }; + let member = sqlx::query!( + "SELECT username, email FROM usr + WHERE workspace_id = $1 AND lower(email) = lower($2) AND NOT disabled", + w_id, + email + ) + .fetch_optional(db) + .await?; + let Some(member) = member else { + return reply.send( + format!( + "Your Slack email isn't a member of the Windmill workspace *{w_id}*. Ask an admin to invite you." + ), + None, + ) + .await; + }; + fetch_api_authed(member.username, member.email, w_id, db, None).await? + } + Some(share) => { + let on_behalf_of = windmill_common::on_behalf_of_from_permissioned_as( + share.on_behalf_of.as_deref(), + w_id, + db, + ) + .await?; + let Some(on_behalf_of) = on_behalf_of else { + return reply + .send( + format!( + "`{agent_path}` doesn't run on behalf of anyone, so it can't answer in Slack." + ), + None, + ) + .await; + }; + fetch_api_authed_from_permissioned_as( + on_behalf_of.permissioned_as, + on_behalf_of.email, + w_id, + db, + None, + ) + .await? + } + }; + let user_db = UserDB::new(db.clone()); + + // Keyed with the workspace's secret: anyone who can read the agent's runs could rebuild the + // plain thread and user ids and load this person's conversation, tool results included. + let workspace_key = get_workspace_key(w_id, db).await?; + let run_query = RunJobQuery { + memory_id: Some(calculate_hash(&format!( + "{workspace_key}:slack:{}:{}:{}:{}", + msg.team_id, channel, thread_root, msg.user_id + ))), + ..Default::default() + }; + let args: HashMap> = [( + "user_message".to_string(), + windmill_common::worker::to_raw_value(&question), + )] + .into(); + let job_id = + match run_agent_as(&authed, db, &user_db, w_id, &agent_path, &run_query, &args).await { + Ok(id) => id, + Err(Error::NotFound(_)) if members_only => { + return reply + .send( + format!("You don't have access to `{agent_path}` in Windmill."), + None, + ) + .await; + } + Err(e) => { + return reply + .send(format!("`{agent_path}` couldn't start: {e}"), None) + .await; + } + }; + + let run_link = format!( + "<{}/run/{job_id}?workspace={w_id}|View run> · `{agent_path}`", + BASE_URL.load() + ); + let thinking = reply.keep_thinking(); + let result = wait_for_result(db, w_id, job_id).await; + if let Some(thinking) = thinking { + thinking.abort(); + } + let text = match result? { + Some((result, true)) => answer_text(&result), + Some((result, false)) => format!("The agent failed: {}", error_text(&result)), + None => "Still working, follow it in the run.".to_string(), + }; + reply.send(text, Some(run_link)).await +} + +async fn wait_for_result( + db: &DB, + w_id: &str, + job_id: Uuid, +) -> Result> { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(MAX_WAIT_SECS); + while std::time::Instant::now() < deadline { + let row = sqlx::query!( + "SELECT result AS \"result: sqlx::types::Json\", + status = 'success' AS \"success!\" + FROM v2_job_completed WHERE id = $1 AND workspace_id = $2", + job_id, + w_id + ) + .fetch_optional(db) + .await?; + if let Some(row) = row { + return Ok(Some(( + row.result.map(|r| r.0).unwrap_or_default(), + row.success, + ))); + } + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + } + Ok(None) +} + +/// The agent step's `output`: its text, or a structured output as a JSON block. +fn answer_text(result: &serde_json::Value) -> String { + match &result["output"] { + serde_json::Value::String(s) if !s.trim().is_empty() => s.clone(), + serde_json::Value::Null => "The agent returned no answer.".to_string(), + other => format!( + "```\n{}\n```", + serde_json::to_string_pretty(other).unwrap_or_default() + ), + } +} + +fn error_text(result: &serde_json::Value) -> String { + result["error"]["message"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| result.to_string()) +} + +/// The bot's reply in a thread. While it is being worked out the thread shows the bot as thinking, +/// or, where Slack refuses that status, a placeholder message the reply then replaces. +#[derive(Clone)] +struct Reply { + token: String, + channel: String, + thread_ts: String, + placeholder: Option, +} + +impl Reply { + async fn start(token: &str, channel: &str, thread_ts: &str) -> anyhow::Result { + let mut reply = Reply { + token: token.to_string(), + channel: channel.to_string(), + thread_ts: thread_ts.to_string(), + placeholder: None, + }; + if let Err(e) = reply.set_status("is thinking…").await { + tracing::debug!("Slack refused the thinking status, posting a placeholder: {e:#}"); + let posted = slack_call( + token, + "chat.postMessage", + &[ + ("channel", channel.to_string()), + ("thread_ts", thread_ts.to_string()), + ("text", "Thinking…".to_string()), + ], + ) + .await?; + reply.placeholder = posted["ts"].as_str().map(str::to_string); + } + Ok(reply) + } + + async fn set_status(&self, status: &str) -> anyhow::Result<()> { + slack_call( + &self.token, + "assistant.threads.setStatus", + &[ + ("channel_id", self.channel.clone()), + ("thread_ts", self.thread_ts.clone()), + ("status", status.to_string()), + ], + ) + .await + .map(|_| ()) + } + + /// Slack drops the status after two minutes without a reply, so a long run renews it. + fn keep_thinking(&self) -> Option> { + if self.placeholder.is_some() { + return None; + } + let reply = self.clone(); + Some(tokio::spawn(async move { + loop { + tokio::time::sleep(std::time::Duration::from_secs(90)).await; + let _ = reply.set_status("is thinking…").await; + } + })) + } + + async fn send(&self, text: String, footer: Option) -> anyhow::Result<()> { + let (text, blocks) = reply_blocks(&text, footer)?; + let mut form = vec![ + ("channel", self.channel.clone()), + ("text", text), + ("blocks", blocks), + ]; + match &self.placeholder { + Some(ts) => { + form.push(("ts", ts.clone())); + slack_call(&self.token, "chat.update", &form).await?; + } + None => { + form.push(("thread_ts", self.thread_ts.clone())); + slack_call(&self.token, "chat.postMessage", &form).await?; + let _ = self.set_status("").await; + } + } + Ok(()) + } +} + +/// The reply's notification text and its blocks: the answer as markdown, and an optional footer. +fn reply_blocks(text: &str, footer: Option) -> anyhow::Result<(String, String)> { + let text = if text.chars().count() > MAX_REPLY_CHARS { + let cut: String = text.chars().take(MAX_REPLY_CHARS).collect(); + format!("{cut}\n\n_The answer is cut short here; the run has all of it._") + } else { + text.to_string() + }; + let mut blocks = vec![serde_json::json!({ "type": "markdown", "text": text })]; + if let Some(footer) = footer { + blocks.push(serde_json::json!({ + "type": "context", + "elements": [{ "type": "mrkdwn", "text": footer }] + })); + } + let fallback: String = text.chars().take(300).collect(); + Ok((fallback, serde_json::to_string(&blocks)?)) +} + +#[cfg(test)] +mod tests { + use super::split_agent_name; + + #[test] + fn agent_name_prefix() { + assert_eq!( + split_agent_name("+sql_analyst how many?"), + (Some("sql_analyst"), "how many?") + ); + assert_eq!( + split_agent_name("~f/data/sql_analyst hi"), + (Some("f/data/sql_analyst"), "hi") + ); + assert_eq!(split_agent_name("+helper"), (Some("helper"), "")); + assert_eq!(split_agent_name("what is +x"), (None, "what is +x")); + assert_eq!(split_agent_name("+ spaced"), (None, "+ spaced")); + } +} diff --git a/backend/windmill-api/src/token.rs b/backend/windmill-api/src/token.rs index ab22f2d15b..7428e586d6 100644 --- a/backend/windmill-api/src/token.rs +++ b/backend/windmill-api/src/token.rs @@ -105,6 +105,12 @@ fn build_standard_scope_domains() -> Vec { "AI agent eval datasets and standalone runs", false, ), + ( + "slack_agents", + "Slack Agents", + "AI agents answering in Slack channels", + false, + ), ( "agent_workers", "Agent Workers", diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index 22ba1de6c6..f83ffcb4e8 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -1613,8 +1613,7 @@ async fn execute(authed: &ApiAuthed, db: &DB, w_id: &str, write: Write) -> Resul } Target::AiConfig => { let body = serde_json::from_value(write.body).map_err(body_err)?; - let _ = - crate::workspaces::edit_copilot_config(a, d, p, authed.clone(), Json(body)).await?; + let _ = crate::workspaces::edit_copilot_config(a, d, p, Json(body)).await?; Ok(Value::Null) } #[cfg(feature = "enterprise")] @@ -1628,7 +1627,7 @@ async fn execute(authed: &ApiAuthed, db: &DB, w_id: &str, write: Write) -> Resul #[cfg(feature = "private")] Target::TeamsCommand => { let body = serde_json::from_value(write.body).map_err(body_err)?; - crate::teams_ee::edit_teams_command(a, d, p, authed.clone(), Json(body)).await?; + crate::teams_ee::edit_teams_command(a, d, p, Json(body)).await?; Ok(Value::Null) } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-api/src/workspaces.rs b/backend/windmill-api/src/workspaces.rs index e5b5cf3e72..6edf18ff07 100644 --- a/backend/windmill-api/src/workspaces.rs +++ b/backend/windmill-api/src/workspaces.rs @@ -94,10 +94,9 @@ pub(crate) async fn edit_copilot_config( authed: ApiAuthed, Extension(db): Extension, Path(w_id): Path, - ApiAuthed { is_admin, username, .. }: ApiAuthed, Json(ai_config): Json, ) -> JsonResult { - require_admin(is_admin, &username)?; + require_admin(authed.is_admin, &authed.username)?; if let Some(ref custom_prompts) = ai_config.custom_prompts { for (mode, prompt) in custom_prompts.iter() { diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index 35f4497fac..2f58485896 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -291,6 +291,7 @@ pub enum ScopeDomain { OAuth, AI, AiEvals, // AI agent eval datasets + SlackAgents, // AI agents answering in Slack channels Indexer, Teams, // Microsoft Teams integration @@ -351,6 +352,7 @@ impl ScopeDomain { Self::OAuth => "oauth", Self::AI => "ai", Self::AiEvals => "ai_evals", + Self::SlackAgents => "slack_agents", Self::Capture => "capture", Self::Drafts => "drafts", Self::Favorites => "favorites", @@ -406,6 +408,7 @@ impl ScopeDomain { "oauth" => Some(Self::OAuth), "ai" => Some(Self::AI), "ai_evals" => Some(Self::AiEvals), + "slack_agents" => Some(Self::SlackAgents), "indexer" | "srch" => Some(Self::Indexer), "teams" => Some(Self::Teams), "native_triggers" => Some(Self::NativeTriggers), diff --git a/frontend/src/lib/components/DateTimeInput.svelte b/frontend/src/lib/components/DateTimeInput.svelte index ac95a1a566..55e1dbc0e1 100644 --- a/frontend/src/lib/components/DateTimeInput.svelte +++ b/frontend/src/lib/components/DateTimeInput.svelte @@ -8,6 +8,7 @@ import { twMerge } from 'tailwind-merge' import { createDispatcherIfMounted } from '$lib/createDispatcherIfMounted' import TextInput from './text_input/TextInput.svelte' + import { parseDateTime } from './dateTimeInput' // import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' interface Props { @@ -45,7 +46,7 @@ // let format: 'local' | 'utc' = 'local' function parseValue(value: string | null | undefined = undefined) { - let dateFromValue: Date | undefined = value ? new Date(value) : undefined + let dateFromValue: Date | undefined = value ? parseDateTime(value, timezone) : undefined if (!isValidDate(dateFromValue)) { date = undefined time = '12:00' diff --git a/frontend/src/lib/components/OAuthSetting.svelte b/frontend/src/lib/components/OAuthSetting.svelte index 59cbb9247e..0aa1de0025 100644 --- a/frontend/src/lib/components/OAuthSetting.svelte +++ b/frontend/src/lib/components/OAuthSetting.svelte @@ -9,6 +9,9 @@ import TextInput from './text_input/TextInput.svelte' import Password from './Password.svelte' import SettingCard from './instanceSettings/SettingCard.svelte' + import CopyableCodeBlock from './details/CopyableCodeBlock.svelte' + import { slackAppManifest } from './common/slack/slackAppManifest' + import { yaml } from 'svelte-highlight/languages' interface Props { name: string @@ -203,16 +206,21 @@ {:else if name == 'slack'} -
- To use Slack OAuth, create a new Slack app in slack API console - - . Pick "From a manifest", then YAML and paste manifest template found on - Windmill docs and then paste Client ID and Client Secret here. +
+ + Create a Slack app in the Slack API console : pick "From a manifest", then YAML, and paste the manifest below. Then copy the + Client ID and Client Secret here. Socket Mode and token rotation must stay off. For AI + agents to answer in Slack, set the app's Signing Secret as the server's + SLACK_SIGNING_SECRET environment variable. More in the + Windmill docs . + +
+ +
{:else if name == 'microsoft'} diff --git a/frontend/src/lib/components/common/slack/slackAppManifest.ts b/frontend/src/lib/components/common/slack/slackAppManifest.ts new file mode 100644 index 0000000000..deaaebfdd7 --- /dev/null +++ b/frontend/src/lib/components/common/slack/slackAppManifest.ts @@ -0,0 +1,55 @@ +/** Requested on top of the usual ones when a workspace connects with AI agents enabled. */ +export const SLACK_AGENT_SCOPES = ['users:read', 'users:read.email', 'channels:read'] + +/** + * The Slack app manifest Windmill expects, for `baseUrl` (the instance's public URL). It declares + * the agent scopes too: an app may declare more than a connection asks for, never fewer. + */ +export function slackAppManifest(baseUrl: string): string { + return `display_information: + name: Windmill + description: Run Windmill scripts, flows and AI agents from Slack + background_color: '#3b82f6' +features: + app_home: + home_tab_enabled: true + messages_tab_enabled: true + messages_tab_read_only_enabled: false + bot_user: + display_name: Windmill + always_online: true + slash_commands: + - command: /windmill + url: ${baseUrl}/api/oauth/slack_command + description: Trigger the script set in your workspace settings for Slack + usage_hint: the text that will be passed to the script + should_escape: false +oauth_config: + redirect_urls: + - ${baseUrl}/oauth/callback_slack + - ${baseUrl}/oauth/callback_slack/instance + scopes: + bot: + - chat:write + - chat:write.public + - channels:join + - files:write + - commands + - app_mentions:read + - im:history + - im:read +${SLACK_AGENT_SCOPES.map((s) => ` - ${s}`).join('\n')} +settings: + event_subscriptions: + request_url: ${baseUrl}/api/oauth/slack_events + bot_events: + - app_mention + - message.im + interactivity: + is_enabled: true + request_url: ${baseUrl}/api/slack + org_deploy_enabled: false + socket_mode_enabled: false + token_rotation_enabled: false +` +} diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index 9f1c1d610e..d3c61d24b1 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -995,7 +995,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{:else if message.needsConfirmation} - {@render confirmFooter('py-1 font-main')} + {@render confirmFooter('py-1')} {/if}
{:else} @@ -373,8 +375,8 @@ toolCallId={message.tool_call_id} rejectIcon={XCircle} rejectDestructive - confirmLabel="Run" - confirmIcon={Play} + confirmLabel={confirmAction.label} + confirmIcon={confirmAction.icon} /> diff --git a/frontend/src/lib/components/copilot/chat/api/apiTools.ts b/frontend/src/lib/components/copilot/chat/api/apiTools.ts index 1063bd97e3..b0466f77de 100644 --- a/frontend/src/lib/components/copilot/chat/api/apiTools.ts +++ b/frontend/src/lib/components/copilot/chat/api/apiTools.ts @@ -109,6 +109,7 @@ export function createApiTools( def: chatTool, planModeSafe: !!endpoint && ['GET', 'HEAD', 'OPTIONS'].includes(method), requiresConfirmation: needsConfirmation, + confirmAction: method === 'DELETE' ? 'delete' : 'confirm', confirmationMessage: `Run ${toolName}`, showDetails: true, showFade: true, diff --git a/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts b/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts index c093b450c3..6e5ec4f8a7 100644 --- a/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts +++ b/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts @@ -213,6 +213,7 @@ export function getDatatableMigrationTools(): SessionTool<{}>[] { requires: RUN_PREVIEW, def: getCreateMigrationToolDef(), requiresConfirmation: true, + confirmAction: (args) => (args?.apply === false ? 'create' : 'apply'), confirmationMessage: (args) => `${args?.version === undefined ? 'Create' : 'Rewrite'}${args?.apply === false ? '' : ' and apply'} data table migration`, queuedLabel: (args) => `Write migration "${args?.name ?? ''}"`, @@ -341,6 +342,7 @@ export function getDatatableMigrationTools(): SessionTool<{}>[] { requires: RUN_PREVIEW, def: getRunMigrationsToolDef(), requiresConfirmation: true, + confirmAction: 'apply', confirmationMessage: 'Apply pending data table migrations', queuedLabel: (args) => `Apply migrations on "${args?.datatable_name ?? 'datatable'}"`, showDetails: true, @@ -376,6 +378,7 @@ export function getDatatableMigrationTools(): SessionTool<{}>[] { requires: RUN_PREVIEW, def: getRollbackMigrationToolDef(), requiresConfirmation: true, + confirmAction: 'rollback', confirmationMessage: (args) => `Roll back data table migration ${args?.version ?? ''}`, queuedLabel: (args) => `Roll back migration ${args?.version ?? ''}`, showDetails: true, diff --git a/frontend/src/lib/components/copilot/chat/datatableTools.ts b/frontend/src/lib/components/copilot/chat/datatableTools.ts index e05b2e4325..097d64d06e 100644 --- a/frontend/src/lib/components/copilot/chat/datatableTools.ts +++ b/frontend/src/lib/components/copilot/chat/datatableTools.ts @@ -344,6 +344,7 @@ export function getDatatableTools(): SessionTool<{}>[] { requires: RUN_PREVIEW, def: getExecDatatableSqlToolDef(), requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: 'Execute SQL on datatable', queuedLabel: (args) => `Execute SQL on "${args?.datatable_name ?? 'datatable'}"`, showDetails: true, diff --git a/frontend/src/lib/components/copilot/chat/flow/core.ts b/frontend/src/lib/components/copilot/chat/flow/core.ts index 4adbe1634b..39be790f3e 100644 --- a/frontend/src/lib/components/copilot/chat/flow/core.ts +++ b/frontend/src/lib/components/copilot/chat/flow/core.ts @@ -441,6 +441,7 @@ export const flowTools: Tool[] = [ return def }, requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: 'Run a test of the current flow', showDetails: true, autoCollapseDetails: false @@ -486,6 +487,7 @@ export const flowTools: Tool[] = [ }) }, requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: (args) => `Run a test of step "${args?.stepId ?? ''}"`, showDetails: true, autoCollapseDetails: false diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index a830d4d404..3414ef6185 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -4134,6 +4134,7 @@ export const globalTools: SessionTool<{}>[] = [ 'Create a new shared folder (addressable as f//) in the workspace. The current user is added as an owner.' ), requiresConfirmation: true, + confirmAction: 'create', confirmationMessage: 'Create folder', showDetails: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { @@ -4568,6 +4569,7 @@ export const globalTools: SessionTool<{}>[] = [ showDetails: true, showFade: true, requiresConfirmation: true, + confirmAction: 'deploy', confirmationMessage: 'Deploy draft to workspace', fn: async (ctx) => { const parsed = deployWorkspaceItemSchema.parse(ctx.args) @@ -4650,6 +4652,7 @@ export const globalTools: SessionTool<{}>[] = [ showDetails: true, showFade: true, requiresConfirmation: true, + confirmAction: 'delete', confirmationMessage: 'Delete workspace item', validateBeforeConfirmation: validateDeleteWorkspaceItemTarget, fn: async (ctx) => { @@ -4669,6 +4672,7 @@ export const globalTools: SessionTool<{}>[] = [ showDetails: true, showFade: true, requiresConfirmation: true, + confirmAction: 'discard', confirmationMessage: 'Discard draft', fn: async (ctx) => { const parsed = discardLocalDraftSchema.parse(ctx.args) @@ -4764,6 +4768,7 @@ export const globalTools: SessionTool<{}>[] = [ ), showDetails: true, requiresConfirmation: true, + confirmAction: 'create', confirmationMessage: 'Create resource type', fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = createResourceTypeSchema.parse(args) @@ -4944,6 +4949,7 @@ export const globalTools: SessionTool<{}>[] = [ return testRunAppRunnable(parsed, ctx) }, requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: (args) => `Run the backend runnable "${args?.key ?? ''}" of ${pathLeaf(args?.path, 'the app')}`, queuedLabel: (args) => `Test runnable "${args?.key ?? ''}" of ${args?.path ?? 'the app'}`, diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index 620e5a86ea..e1da0fb624 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -366,6 +366,7 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo ? { planModeSafe: true } : { requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: (args: any) => `Call ${args?.tool ?? ''} on ${args?.server ?? ''}` }), fn: async ({ args, workspace, toolId, toolCallbacks }) => { diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts b/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts index d63b75343f..1f37eb9300 100644 --- a/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts @@ -105,6 +105,7 @@ export const workspaceSettingsTools: SessionTool<{}>[] = [ 'Change workspace settings. Keys the yaml omits are left as they are. The user reviews the changes before they apply. Read get_instructions subject "workspace_settings" before your first change.' ), requiresConfirmation: true, + confirmAction: 'apply', confirmationMessage: 'Change workspace settings', cancellationMessage: 'The user declined: no setting was changed.', showDetails: true, diff --git a/frontend/src/lib/components/copilot/chat/pipeline/core.ts b/frontend/src/lib/components/copilot/chat/pipeline/core.ts index 8d71b00279..abd403206d 100644 --- a/frontend/src/lib/components/copilot/chat/pipeline/core.ts +++ b/frontend/src/lib/components/copilot/chat/pipeline/core.ts @@ -568,6 +568,7 @@ export const pipelineTools: SessionTool[] = [ requires: RUN_PREVIEW, def: testPipelineNodeToolDef, requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: 'Run pipeline node', showDetails: true, autoCollapseDetails: false, diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index b732e00c05..93ad12ff67 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -1007,6 +1007,7 @@ export const testRunScriptTool: Tool = { }) }, requiresConfirmation: true, + confirmAction: 'run', confirmationMessage: 'Run a test of the current script', showDetails: true, autoCollapseDetails: false diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index a6ce735230..71ef91a0b7 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -642,6 +642,16 @@ export type ToolCodeDiff = { beforeLang?: string } +export type ToolConfirmAction = + | 'run' + | 'deploy' + | 'create' + | 'apply' + | 'delete' + | 'discard' + | 'rollback' + | 'confirm' + export type ToolDisplayMessage = { role: 'tool' tool_call_id: string @@ -657,6 +667,8 @@ export type ToolDisplayMessage = { isQueued?: boolean error?: string needsConfirmation?: boolean + /** What the confirm button says the call will do. */ + confirmAction?: ToolConfirmAction showDetails?: boolean autoCollapseDetails?: boolean isStreamingArguments?: boolean @@ -1103,6 +1115,8 @@ export async function processToolCall({ typeof tool?.confirmationMessage === 'function' ? tool.confirmationMessage(args) : tool?.confirmationMessage + const confirmAction = + typeof tool?.confirmAction === 'function' ? tool.confirmAction(args) : tool?.confirmAction // preAction fires at promotion, not stream time, so its "-ing" label covers // only the execution window — queued cards keep their imperative header. @@ -1111,7 +1125,7 @@ export async function processToolCall({ toolCallbacks.setToolStatus(toolCall.id, { ...(requiresConfirmation - ? { content: confirmationContent ?? 'Waiting for confirmation...' } + ? { content: confirmationContent ?? 'Waiting for confirmation...', confirmAction } : {}), parameters: args, isLoading: true, @@ -1287,6 +1301,8 @@ export interface Tool { /** Header shown on the confirmation card before the tool runs. Pass a function * to derive it from the parsed arguments (e.g. name the script being tested). */ confirmationMessage?: string | ((args: any) => string) + /** The verb on the confirm button; `confirm` when omitted. */ + confirmAction?: ToolConfirmAction | ((args: any) => ToolConfirmAction) /** Only when a card gates the call, so `fn` must not rely on it. Not awaited, so it may * not throw, and must be safe for a call the user then declines. */ onConfirmationRequested?: (p: { args: any; toolCallbacks: ToolCallbacks; toolId: string }) => void diff --git a/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts b/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts new file mode 100644 index 0000000000..52f5d546e8 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts @@ -0,0 +1,13 @@ +import { Check, Play, Plus, Save, Trash2, Undo2 } from 'lucide-svelte' +import type { ToolConfirmAction } from './shared' + +export const TOOL_CONFIRM_ACTIONS: Record = { + run: { label: 'Run', icon: Play }, + deploy: { label: 'Deploy', icon: Save }, + create: { label: 'Create', icon: Plus }, + apply: { label: 'Apply', icon: Check }, + delete: { label: 'Delete', icon: Trash2 }, + discard: { label: 'Discard', icon: Trash2 }, + rollback: { label: 'Roll back', icon: Undo2 }, + confirm: { label: 'Confirm', icon: Check } +} diff --git a/frontend/src/lib/components/copilot/chat/workspaceTools.ts b/frontend/src/lib/components/copilot/chat/workspaceTools.ts index 18c3687701..7590f3b686 100644 --- a/frontend/src/lib/components/copilot/chat/workspaceTools.ts +++ b/frontend/src/lib/components/copilot/chat/workspaceTools.ts @@ -309,6 +309,7 @@ function setToolError(toolCallbacks: ToolCallbacks, toolId: string, error: unkno const createScheduleTool: Tool = { def: createScheduleToolDef, requiresConfirmation: true, + confirmAction: 'create', confirmationMessage: 'Create schedule', showDetails: true, showFade: true, @@ -418,6 +419,7 @@ async function resolveEmailTriggerAvailability(): Promise = { def: createTriggerToolDef, requiresConfirmation: true, + confirmAction: 'create', confirmationMessage: 'Create trigger', showDetails: true, showFade: true, diff --git a/frontend/src/lib/components/dateTimeInput.test.ts b/frontend/src/lib/components/dateTimeInput.test.ts new file mode 100644 index 0000000000..8a466ee5cf --- /dev/null +++ b/frontend/src/lib/components/dateTimeInput.test.ts @@ -0,0 +1,14 @@ +import { expect, it } from 'vitest' +import { parseDateTime } from './dateTimeInput' + +it('reads a zone-less naive value as its digits, outside UTC too', () => { + const tz = process.env.TZ + process.env.TZ = 'Europe/Paris' + try { + expect(parseDateTime('2027-09-09T10:00', 'naive').getUTCHours()).toBe(10) + expect(parseDateTime('2027-09-09T10:00', 'local').getUTCHours()).toBe(8) + } finally { + if (tz === undefined) delete process.env.TZ + else process.env.TZ = tz + } +}) diff --git a/frontend/src/lib/components/dateTimeInput.ts b/frontend/src/lib/components/dateTimeInput.ts new file mode 100644 index 0000000000..7ed8517321 --- /dev/null +++ b/frontend/src/lib/components/dateTimeInput.ts @@ -0,0 +1,5 @@ +/** A naive value's digits are its time: `Date` would read a zone-less date-time as local time */ +export function parseDateTime(value: string, timezone: 'naive' | 'local'): Date { + const zoneless = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(value) + return new Date(timezone === 'naive' && zoneless ? value.replace(' ', 'T') + 'Z' : value) +} diff --git a/frontend/src/lib/components/details/CopyableCodeBlock.svelte b/frontend/src/lib/components/details/CopyableCodeBlock.svelte index e99089bbbd..1e2145fc8a 100644 --- a/frontend/src/lib/components/details/CopyableCodeBlock.svelte +++ b/frontend/src/lib/components/details/CopyableCodeBlock.svelte @@ -46,7 +46,7 @@ diff --git a/frontend/src/lib/components/details/DetailPageLayout.svelte b/frontend/src/lib/components/details/DetailPageLayout.svelte index 131d4c9f38..b78b796f9a 100644 --- a/frontend/src/lib/components/details/DetailPageLayout.svelte +++ b/frontend/src/lib/components/details/DetailPageLayout.svelte @@ -129,7 +129,13 @@ {#snippet content()}
- + + {@render form?.({ graphInline: false })} diff --git a/frontend/src/lib/components/flows/agentResourceUtils.ts b/frontend/src/lib/components/flows/agentResourceUtils.ts index bf6668a4f1..054cb96d54 100644 --- a/frontend/src/lib/components/flows/agentResourceUtils.ts +++ b/frontend/src/lib/components/flows/agentResourceUtils.ts @@ -120,6 +120,9 @@ export interface AIAgentConfig { tools?: AgentTool[] /** Runs from the agent's page take its `on_behalf_of` rather than the caller's identity. */ run_on_behalf_of?: boolean + /** Anyone in the Slack channels it is shared in can ask it, not only workspace members. Kept + * only with `run_on_behalf_of`: everyone there runs it as that identity. */ + slack_anyone?: boolean } /** Extract the static brain values from a step's input_transforms into a flat agent config. */ diff --git a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte index 58c47bbb20..f3ee578050 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte @@ -56,6 +56,8 @@ onClose?: (deployed: boolean) => void /** Ran after every successful deploy, with the path written. */ onDeployed?: (path: string) => void + /** Open on the settings, as a link to them does. */ + startInSettings?: boolean } let { @@ -64,7 +66,8 @@ onRenamed = undefined, layout = 'modal', onClose = undefined, - onDeployed = undefined + onDeployed = undefined, + startInSettings = false }: Props = $props() // Every target names the surface that opened it, and only a flow step or a resource row can: @@ -182,6 +185,14 @@ else settingsDrawer?.openDrawer() } + let openedSettings = false + $effect(() => { + if (startInSettings && draft?.state && settingsDrawer && !openedSettings) { + openedSettings = true + untrack(openSettings) + } + }) + /** The unsaved edits, in the shape the server builds from a deployed config * (`ai_evals/run.rs` `config_to_draft`), so a draft run's hash can be recognised as equal to * the version it is later deployed as. */ diff --git a/frontend/src/lib/components/flows/content/AgentSettings.svelte b/frontend/src/lib/components/flows/content/AgentSettings.svelte index ec7d0edb7c..9d02183812 100644 --- a/frontend/src/lib/components/flows/content/AgentSettings.svelte +++ b/frontend/src/lib/components/flows/content/AgentSettings.svelte @@ -1,6 +1,6 @@ {#if draft.state} -
- - {#if readOnly} - {#if draft.state.labels?.length} -
- {#each draft.state.labels as label (label)} - {label} - {/each} -
- {/if} - {:else} - - {/if} - -
-
{/if} diff --git a/frontend/src/lib/components/flows/content/AgentSlackSettings.svelte b/frontend/src/lib/components/flows/content/AgentSlackSettings.svelte new file mode 100644 index 0000000000..5e1e4f020d --- /dev/null +++ b/frontend/src/lib/components/flows/content/AgentSlackSettings.svelte @@ -0,0 +1,258 @@ + + +{#if draft.state} +
+ +
+ Channels +
+ {#if draft.noDeployed} + Deploy the agent to share it in Slack channels. + {:else if slack.loading && !slack.current} + Loading… + {:else if !slack.current?.slack_team_name} + + Slack isn't connected to the workspace. + {#if isAdmin} + Connect it with AI agents enabled. + {/if} + + {:else} + {#if channels.length === 0 && !adding} + Not shared in any channel. + {/if} + {#each channels as channel (channel.channel_id)} +
+ + share(channel.channel_id, channel.channel_name, e.detail)} + options={{ + right: 'Default', + rightTooltip: + 'Answers bot mentions in this channel that name no agent. Admins only.' + }} + /> + {#if !readOnly} +
+ {/each} + {#if canPick} + {#if adding} +
+ setDraft(e.target.value)} disabled={chat.status === 'submitted' || chat.status === 'streaming'} /> + +
+ ) +}` +} + +export function sdkExample(t: AgentApiTarget): string { + return `import { createChat } from '@windmill-labs/chat-sdk' + +const API = '${t.api}' +const TOKEN = '${t.token}' + +const chat = createChat(${sdkOptions(t, '')}) + +// Called now and on every change: messages stream in as they are written. This is the Svelte +// store contract, so in Svelte $chat works as is. +chat.subscribe(({ messages, status }) => console.log(status, messages.at(-1)?.content)) // your UI here +await chat.sendMessage('Hello') +// Also chat.stop(), and the conversations: chat.newConversation(), chat.selectConversation(id)` +} + +/** A brief for a coding assistant asked to integrate the agent. It reads the token from `WINDMILL_TOKEN`. */ +export function integrationPrompt(t: AgentApiTarget): string { + const conversation = t.chat + ? ` +## Conversations + +The agent keeps the conversation. Pass \`memory_id\` as a query parameter on every run: any +string names a conversation, a UUID is best. Reuse it for follow-ups; a new one starts over. +Without it each message is answered on its own. + +Windmill also keeps each conversation, as the token's owner's. One token shared by all your +users makes every conversation theirs, so keep your users' conversation ids in your own app. +Reading them back needs a token with the \`flow_conversations:read\` scope (\`:write\` to delete): +- \`GET ${t.api}/flow_conversations/list?flow_path=${t.agentPath}.chat\` (\`page\`, \`per_page\`). + A conversation's \`id\` is the \`memory_id\` when that was a UUID. +- \`GET ${t.api}/flow_conversations/{id}/messages\`: its latest messages, oldest first. +- \`DELETE ${t.api}/flow_conversations/delete/{id}\`. + +In TypeScript or JavaScript, prefer the \`@windmill-labs/chat-sdk\` package (npm, source at +https://github.com/windmill-labs/windmill/tree/main/chat-sdk): it does all of this, streaming included. +\`createChat\` from \`@windmill-labs/chat-sdk\` works with any framework (or none); use the adapter that +matches the project when there is one: \`useWindmillChat\` from \`@windmill-labs/chat-sdk/react\`, the Vercel +AI SDK transport (\`@windmill-labs/chat-sdk/ai-sdk\`) or the assistant-ui runtime +(\`@windmill-labs/chat-sdk/assistant-ui\`). Point it at the +agent with \`flowPath: '${t.agentPath}.chat'\` and a \`run(args, { conversationId, signal })\` option +that POSTs \`args\` to the run endpoint with \`memory_id=conversationId\` and returns the job id. +` + : '' + return `Integrate the Windmill AI agent \`${t.agentPath}\` into this project. + +## Authentication + +Every request sends \`Authorization: Bearer \`. Read the token from the \`WINDMILL_TOKEN\` +environment variable (or the project's secret store under that name), never hardcode it: the agent +runs as the token's owner, with their permissions. Keep it on the server, unless it is an +agent-specific token (scope \`jobs:run:agents:${t.agentPath}\`): that one can only run this agent, so a +browser app may read it from the bundler's public variable (\`VITE_WINDMILL_TOKEN\`, +\`NEXT_PUBLIC_WINDMILL_TOKEN\`, ...). + +## Sending a message + +\`POST ${runUrl(t)}\` with the JSON body \`{"user_message": "..."}\` starts a run and returns its +job id as plain text. An error is a non-2xx status with the reason as text. +${conversation} +## Streaming the answer + +\`GET ${t.api}/jobs_u/getupdate_sse/{job_id}?fast=true&only_result=true\` is a server-sent events +stream of JSON objects: +- \`new_result_stream\`: text to append to a buffer holding one JSON event per line. A chunk can + stop mid-line, so parse complete lines only. Event types: \`token_delta\` (\`content\`: answer text), + \`reasoning_token_delta\`, \`tool_call\`, \`tool_call_arguments\`, \`tool_execution\`, \`tool_result\` + (\`call_id\`, \`function_name\`, \`result\`, \`success\`). +- \`stream_offset\`: how far the stream has been read. The server closes the stream now and then; + reconnect with \`&stream_offset=\` and never run the agent again for the same message. +- \`completed: true\` ends it. \`only_result.output\` is the full answer, or \`only_result.error.message\` + when the run failed. + +Without streaming, poll \`GET ${t.api}/jobs_u/completed/get_result_maybe/{job_id}\` until +\`completed\` is true; the answer is \`result.output\`. + +To stop a run: \`POST ${t.api}/jobs_u/queue/cancel/{job_id}\` with \`{"reason": "..."}\`. +` +} diff --git a/frontend/src/lib/components/flows/conversations/FlowConversationsSidebar.svelte b/frontend/src/lib/components/flows/conversations/FlowConversationsSidebar.svelte index 8c6a102fef..8ab69377e2 100644 --- a/frontend/src/lib/components/flows/conversations/FlowConversationsSidebar.svelte +++ b/frontend/src/lib/components/flows/conversations/FlowConversationsSidebar.svelte @@ -306,7 +306,7 @@