mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-30 00:07:30 +00:00
Merge remote-tracking branch 'origin/unify-ai-session-home-chatbox' into home-items-tabs
# Conflicts: # backend/ee-repo-ref.txt
This commit is contained in:
+12
@@ -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"
|
||||
}
|
||||
+16
@@ -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"
|
||||
}
|
||||
+30
@@ -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"
|
||||
}
|
||||
+40
@@ -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"
|
||||
}
|
||||
+14
@@ -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"
|
||||
}
|
||||
+35
@@ -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"
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT result AS \"result: sqlx::types::Json<serde_json::Value>\",\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<serde_json::Value>",
|
||||
"type_info": "Jsonb"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "success!",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e"
|
||||
}
|
||||
+19
@@ -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"
|
||||
}
|
||||
+41
@@ -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"
|
||||
}
|
||||
+35
@@ -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"
|
||||
}
|
||||
+29
@@ -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"
|
||||
}
|
||||
+31
@@ -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"
|
||||
}
|
||||
+23
@@ -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"
|
||||
}
|
||||
+24
@@ -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"
|
||||
}
|
||||
+18
@@ -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"
|
||||
}
|
||||
+29
@@ -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"
|
||||
}
|
||||
+22
@@ -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"
|
||||
}
|
||||
+22
@@ -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"
|
||||
}
|
||||
+28
@@ -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"
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
a00bc02d4cf16a14d13cb6d2e86c55bf42129348
|
||||
4871a58b74a8a24029b63826013f565fc23ea5be
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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)
|
||||
|
||||
@@ -1611,10 +1611,9 @@ async fn edit_slack_command(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(es): Json<EditCommandScript>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(ew): Json<EditWebhook>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(new_config): Json<EditDbtWarehouses>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(new_config): Json<EditLargeFileStorageConfig>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, email, .. }: ApiAuthed,
|
||||
Json(new_config): Json<EditDucklakeConfig>,
|
||||
) -> Result<String> {
|
||||
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://<name>'`,
|
||||
@@ -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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(mut new_config): Json<EditDataTableConfig>,
|
||||
) -> JsonResult<EditDataTableConfigResult> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(new_config): Json<EditGitSyncConfig>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(mut new_config): Json<EditGitSyncRepository>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(request): Json<DeleteGitSyncRepositoryRequest>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(new_config): Json<EditDeployUIConfig>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(new_config): Json<Option<serde_json::Value>>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(new_config): Json<EditDefaultApp>,
|
||||
) -> Result<String> {
|
||||
#[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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(ee): Json<EditErrorHandler>,
|
||||
) -> Result<String> {
|
||||
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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(ew): Json<EditWorkspace>,
|
||||
) -> Result<String> {
|
||||
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<serde_json::Value> {
|
||||
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?,
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -46,14 +46,29 @@ pub(crate) async fn run_agent(
|
||||
Query(run_query): Query<RunJobQuery>,
|
||||
Json(args): Json<HashMap<String, Box<RawValue>>>,
|
||||
) -> 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<String, Box<RawValue>>,
|
||||
) -> Result<uuid::Uuid> {
|
||||
#[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<serde_json::Value>\"
|
||||
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
|
||||
|
||||
@@ -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",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -105,6 +105,12 @@ fn build_standard_scope_domains() -> Vec<ScopeDomain> {
|
||||
"AI agent eval datasets and standalone runs",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"slack_agents",
|
||||
"Slack Agents",
|
||||
"AI agents answering in Slack channels",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"agent_workers",
|
||||
"Agent Workers",
|
||||
|
||||
@@ -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"))]
|
||||
|
||||
@@ -94,10 +94,9 @@ pub(crate) async fn edit_copilot_config(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
ApiAuthed { is_admin, username, .. }: ApiAuthed,
|
||||
Json(ai_config): Json<AIConfig>,
|
||||
) -> JsonResult<EditCopilotConfigResponse> {
|
||||
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() {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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 @@
|
||||
</CollapseLink>
|
||||
{:else if name == 'slack'}
|
||||
<CollapseLink text="Set up slack">
|
||||
<div class="text-xs text-primary rounded-md">
|
||||
To use Slack OAuth, create a new Slack app <a
|
||||
href="https://api.slack.com/apps?new_app=1"
|
||||
target="_blank"
|
||||
>in slack API console
|
||||
<ExternalLink size={12} class="inline-block" />
|
||||
</a>. Pick "From a manifest", then YAML and paste manifest template found on
|
||||
<a href="https://www.windmill.dev/docs/misc/setup_oauth#slack" target="_blank"
|
||||
>Windmill docs <ExternalLink size={12} class="inline-block" /></a
|
||||
> and then paste Client ID and Client Secret here.
|
||||
<div class="flex flex-col gap-2 text-xs text-primary">
|
||||
<span>
|
||||
Create a Slack app <a href="https://api.slack.com/apps?new_app=1" target="_blank"
|
||||
>in the Slack API console <ExternalLink size={12} class="inline-block" /></a
|
||||
>: 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
|
||||
<code>SLACK_SIGNING_SECRET</code> environment variable. More in the
|
||||
<a href="https://www.windmill.dev/docs/misc/setup_oauth#slack" target="_blank"
|
||||
>Windmill docs <ExternalLink size={12} class="inline-block" /></a
|
||||
>.
|
||||
</span>
|
||||
<div class="flex flex-col max-h-80 [&>div]:min-h-0">
|
||||
<CopyableCodeBlock code={slackAppManifest(window.location.origin)} language={yaml} />
|
||||
</div>
|
||||
</div>
|
||||
</CollapseLink>
|
||||
{:else if name == 'microsoft'}
|
||||
|
||||
@@ -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
|
||||
`
|
||||
}
|
||||
@@ -995,7 +995,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
<div class="absolute -top-10 w-full flex flex-row justify-center gap-2">
|
||||
<Button
|
||||
startIcon={{ icon: CheckIcon }}
|
||||
size="xs"
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
btnClasses="bg-green-500 hover:bg-green-600 text-white hover:text-white"
|
||||
onclick={() => {
|
||||
@@ -1007,7 +1007,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
|
||||
<div class="rounded bg-surface">
|
||||
<Button
|
||||
startIcon={{ icon: XIcon }}
|
||||
size="xs"
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
btnClasses="dark:opacity-50 opacity-60 hover:opacity-100"
|
||||
onclick={() => {
|
||||
|
||||
@@ -34,10 +34,11 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class={twMerge('flex flex-row items-center justify-end gap-2', className)}>
|
||||
<!-- font-main: the tool cards around it are font-mono, which reads as bold on a button label. -->
|
||||
<div class={twMerge('flex flex-row items-center justify-end gap-2 font-main', className)}>
|
||||
<Button
|
||||
variant="default"
|
||||
size="xs"
|
||||
unifiedSize="sm"
|
||||
destructive={rejectDestructive}
|
||||
startIcon={rejectIcon ? { icon: rejectIcon } : undefined}
|
||||
on:click={() => respond(false)}
|
||||
@@ -46,7 +47,7 @@
|
||||
</Button>
|
||||
<Button
|
||||
variant="accent"
|
||||
size="xs"
|
||||
unifiedSize="sm"
|
||||
startIcon={confirmIcon ? { icon: confirmIcon } : undefined}
|
||||
on:click={() => respond(true)}
|
||||
>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
Loader2,
|
||||
ChevronRight,
|
||||
XCircle,
|
||||
Play,
|
||||
ClipboardList,
|
||||
Check,
|
||||
CircleMinus,
|
||||
@@ -43,6 +42,7 @@
|
||||
import RunScriptCard from './RunScriptCard.svelte'
|
||||
import ToolDiffCard from './ToolDiffCard.svelte'
|
||||
import { hasToolCodeDiff } from './toolCodeDiff'
|
||||
import { TOOL_CONFIRM_ACTIONS } from './toolConfirmAction'
|
||||
import WebSearchSourcesDisplay from './WebSearchSourcesDisplay.svelte'
|
||||
import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte'
|
||||
import McpServerIcon from '$lib/components/mcp/McpServerIcon.svelte'
|
||||
@@ -92,6 +92,8 @@
|
||||
// The preview pane's renderers, so a model-written link opens in a new tab either way.
|
||||
const planPlugins = [gfmPlugin(), { renderer: { pre: CodeDisplay, a: LinkRenderer } }]
|
||||
|
||||
const confirmAction = $derived(TOOL_CONFIRM_ACTIONS[message.confirmAction ?? 'confirm'])
|
||||
|
||||
const hasParameters = $derived(
|
||||
message.parameters !== undefined && Object.keys(message.parameters).length > 0
|
||||
)
|
||||
@@ -118,7 +120,7 @@
|
||||
// stream, while it waits on the user, and once it has an error or details to keep in view.
|
||||
// The user's toggle lives in state keyed by call id: the `message` prop is replaced on every
|
||||
// chat update, so an override written onto a derived would be recomputed away. A pending
|
||||
// confirmation wins over it, since the Run/Reject footer renders inside the card.
|
||||
// confirmation wins over it, since the confirm/reject footer renders inside the card.
|
||||
let toggled = $state<{ id: string | undefined; open: boolean } | undefined>(undefined)
|
||||
const isExpanded = $derived(
|
||||
Boolean(message.isLoading && message.needsConfirmation) ||
|
||||
@@ -285,7 +287,7 @@
|
||||
</div>
|
||||
<!-- Collapsed: the buttons stand on their own rather than boxing empty space. -->
|
||||
{:else if message.needsConfirmation}
|
||||
{@render confirmFooter('py-1 font-main')}
|
||||
{@render confirmFooter('py-1')}
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
@@ -373,8 +375,8 @@
|
||||
toolCallId={message.tool_call_id}
|
||||
rejectIcon={XCircle}
|
||||
rejectDestructive
|
||||
confirmLabel="Run"
|
||||
confirmIcon={Play}
|
||||
confirmLabel={confirmAction.label}
|
||||
confirmIcon={confirmAction.icon}
|
||||
/>
|
||||
|
||||
<!-- Logs and Result - hide while streaming -->
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -441,6 +441,7 @@ export const flowTools: Tool<FlowAIChatHelpers>[] = [
|
||||
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<FlowAIChatHelpers>[] = [
|
||||
})
|
||||
},
|
||||
requiresConfirmation: true,
|
||||
confirmAction: 'run',
|
||||
confirmationMessage: (args) => `Run a test of step "${args?.stepId ?? ''}"`,
|
||||
showDetails: true,
|
||||
autoCollapseDetails: false
|
||||
|
||||
@@ -4134,6 +4134,7 @@ export const globalTools: SessionTool<{}>[] = [
|
||||
'Create a new shared folder (addressable as f/<name>/) 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'}`,
|
||||
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -568,6 +568,7 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [
|
||||
requires: RUN_PREVIEW,
|
||||
def: testPipelineNodeToolDef,
|
||||
requiresConfirmation: true,
|
||||
confirmAction: 'run',
|
||||
confirmationMessage: 'Run pipeline node',
|
||||
showDetails: true,
|
||||
autoCollapseDetails: false,
|
||||
|
||||
@@ -1007,6 +1007,7 @@ export const testRunScriptTool: Tool<ScriptChatHelpers> = {
|
||||
})
|
||||
},
|
||||
requiresConfirmation: true,
|
||||
confirmAction: 'run',
|
||||
confirmationMessage: 'Run a test of the current script',
|
||||
showDetails: true,
|
||||
autoCollapseDetails: false
|
||||
|
||||
@@ -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<T>({
|
||||
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<T>({
|
||||
|
||||
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<T> {
|
||||
/** 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
|
||||
|
||||
@@ -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<ToolConfirmAction, { label: string; icon: any }> = {
|
||||
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 }
|
||||
}
|
||||
@@ -309,6 +309,7 @@ function setToolError(toolCallbacks: ToolCallbacks, toolId: string, error: unkno
|
||||
const createScheduleTool: Tool<any> = {
|
||||
def: createScheduleToolDef,
|
||||
requiresConfirmation: true,
|
||||
confirmAction: 'create',
|
||||
confirmationMessage: 'Create schedule',
|
||||
showDetails: true,
|
||||
showFade: true,
|
||||
@@ -418,6 +419,7 @@ async function resolveEmailTriggerAvailability(): Promise<EmailTriggerAvailabili
|
||||
const createTriggerTool: Tool<any> = {
|
||||
def: createTriggerToolDef,
|
||||
requiresConfirmation: true,
|
||||
confirmAction: 'create',
|
||||
confirmationMessage: 'Create trigger',
|
||||
showDetails: true,
|
||||
showFade: true,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
@@ -46,7 +46,7 @@
|
||||
<Highlight
|
||||
{language}
|
||||
{code}
|
||||
class="{copyOnClick ? 'pointer-events-none' : 'select-text'} {wrap ? 'whitespace-pre-wrap break-all pr-8' : ''}"
|
||||
class="{copyOnClick ? 'pointer-events-none' : 'select-text'} {wrap ? 'whitespace-pre-wrap [overflow-wrap:anywhere] pr-8' : ''}"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -129,7 +129,13 @@
|
||||
|
||||
{#snippet content()}
|
||||
<div class="grow min-h-0 overflow-y-auto">
|
||||
<TabContent value="form" class="flex flex-col flex-1 h-full">
|
||||
<!-- The chat holds its open conversation, running turns and draft in component
|
||||
state, so leaving the tab must not unmount it. -->
|
||||
<TabContent
|
||||
value="form"
|
||||
alwaysMounted={isChatMode}
|
||||
class="flex flex-col flex-1 h-full"
|
||||
>
|
||||
{@render form?.({ graphInline: false })}
|
||||
</TabContent>
|
||||
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { resource } from 'runed'
|
||||
import { Badge } from '$lib/components/common'
|
||||
import { Badge, Section } from '$lib/components/common'
|
||||
import Label from '$lib/components/Label.svelte'
|
||||
import LabelsInput from '$lib/components/LabelsInput.svelte'
|
||||
import Path from '$lib/components/Path.svelte'
|
||||
@@ -8,7 +8,9 @@
|
||||
import ResourcePathHint from '$lib/components/ResourcePathHint.svelte'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import PermissionedAsLine from '$lib/components/triggers/PermissionedAsLine.svelte'
|
||||
import AgentSlackSettings from './AgentSlackSettings.svelte'
|
||||
import { WorkspaceService } from '$lib/gen'
|
||||
import { userStore } from '$lib/stores'
|
||||
import type { AgentDraftHandle, AgentRunAs } from '../agentDraft.svelte'
|
||||
|
||||
/** An agent's own settings, laid out as the top of the resource editor: what it is saved as
|
||||
@@ -27,6 +29,15 @@
|
||||
let { draft, path, workspace, error = $bindable(), onRunAsChange = undefined }: Props = $props()
|
||||
|
||||
let readOnly = $derived(!draft.canWrite)
|
||||
// As the deploy resolves it: the deployer, unless one who may keep another picked them.
|
||||
let pickedRunAs = $state<AgentRunAs | undefined>(undefined)
|
||||
let nextRunAs = $derived(
|
||||
pickedRunAs?.preserve && pickedRunAs.permissionedAs
|
||||
? pickedRunAs.permissionedAs
|
||||
: $userStore?.username
|
||||
? `u/${$userStore.username}`
|
||||
: undefined
|
||||
)
|
||||
// Only a workspace that deploys somewhere has anything to keep an agent out of.
|
||||
const deployTo = resource(
|
||||
() => workspace,
|
||||
@@ -36,74 +47,91 @@
|
||||
</script>
|
||||
|
||||
{#if draft.state}
|
||||
<div class="flex flex-col gap-6">
|
||||
<Label label="Path">
|
||||
<ResourcePathHint />
|
||||
<Path
|
||||
bind:path={
|
||||
() => draft.state?.path,
|
||||
(v) => {
|
||||
if (draft.state && v !== undefined) draft.state.path = v
|
||||
}
|
||||
}
|
||||
bind:error
|
||||
initialPath={draft.noDeployed ? '' : path}
|
||||
checkInitialPathExistence={draft.noDeployed}
|
||||
namePlaceholder="agent"
|
||||
kind="resource"
|
||||
workspaceOverride={workspace}
|
||||
autofocus={false}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</Label>
|
||||
{#if readOnly}
|
||||
{#if draft.state.labels?.length}
|
||||
<div class="-mt-4 inline-flex items-center gap-1">
|
||||
{#each draft.state.labels as label (label)}
|
||||
<Badge color="blue" small>{label}</Badge>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<LabelsInput bind:labels={draft.state.labels} {workspace} class="-mt-4" />
|
||||
{/if}
|
||||
<!-- The identity exists only while the toggle is on, resolved on deploy as a flow's
|
||||
on-behalf-of identity is. -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label
|
||||
label="Run on behalf of"
|
||||
tooltip="Runs from the agent's page and the API take the permissions of whoever deploys it, or of the user an admin picks. Otherwise they take the caller's."
|
||||
>
|
||||
<Toggle
|
||||
bind:checked={
|
||||
() => draft.state?.args.run_on_behalf_of ?? false,
|
||||
(v) => {
|
||||
if (draft.state) draft.state.args.run_on_behalf_of = v || undefined
|
||||
<div class="flex flex-col gap-8">
|
||||
<Section label="General">
|
||||
<div class="flex flex-col gap-6">
|
||||
<Label label="Path">
|
||||
<ResourcePathHint />
|
||||
<Path
|
||||
bind:path={
|
||||
() => draft.state?.path,
|
||||
(v) => {
|
||||
if (draft.state && v !== undefined) draft.state.path = v
|
||||
}
|
||||
}
|
||||
}
|
||||
disabled={readOnly}
|
||||
bind:error
|
||||
initialPath={draft.noDeployed ? '' : path}
|
||||
checkInitialPathExistence={draft.noDeployed}
|
||||
namePlaceholder="agent"
|
||||
kind="resource"
|
||||
workspaceOverride={workspace}
|
||||
autofocus={false}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</Label>
|
||||
{#if readOnly}
|
||||
{#if draft.state.labels?.length}
|
||||
<div class="-mt-4 inline-flex items-center gap-1">
|
||||
{#each draft.state.labels as label (label)}
|
||||
<Badge color="blue" small>{label}</Badge>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<LabelsInput bind:labels={draft.state.labels} {workspace} class="-mt-4" />
|
||||
{/if}
|
||||
<ResourceDescriptionField
|
||||
bind:description={draft.state.description}
|
||||
label="Description"
|
||||
placeholder="Describe what this agent does"
|
||||
canWrite={!readOnly}
|
||||
/>
|
||||
</Label>
|
||||
{#if draft.state.args.run_on_behalf_of}
|
||||
<PermissionedAsLine
|
||||
permissionedAs={draft.onBehalfOf}
|
||||
path={draft.state.path}
|
||||
disabled={readOnly}
|
||||
onPermissionedAsChange={(permissionedAs, preserve) =>
|
||||
onRunAsChange?.({ permissionedAs, preserve })}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{#if deployTo.current}
|
||||
<Label label="Workspace specific" tooltip="Keeps this agent out of deploys to prod/staging.">
|
||||
<Toggle bind:checked={draft.state.wsSpecific} disabled={readOnly} />
|
||||
</Label>
|
||||
{/if}
|
||||
<ResourceDescriptionField
|
||||
bind:description={draft.state.description}
|
||||
label="Description"
|
||||
placeholder="Describe what this agent does"
|
||||
canWrite={!readOnly}
|
||||
/>
|
||||
{#if deployTo.current}
|
||||
<Label
|
||||
label="Workspace specific"
|
||||
tooltip="Keeps this agent out of deploys to prod/staging."
|
||||
>
|
||||
<Toggle bind:checked={draft.state.wsSpecific} disabled={readOnly} />
|
||||
</Label>
|
||||
{/if}
|
||||
</div>
|
||||
</Section>
|
||||
<Section label="Permissions">
|
||||
<!-- The identity exists only while the toggle is on, resolved on deploy as a flow's
|
||||
on-behalf-of identity is. -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label
|
||||
label="Run on behalf of"
|
||||
tooltip="Runs from the agent's page, the API and Slack take the permissions of whoever deploys it, or of the user an admin picks. Otherwise they take the caller's."
|
||||
>
|
||||
<Toggle
|
||||
bind:checked={
|
||||
() => draft.state?.args.run_on_behalf_of ?? false,
|
||||
(v) => {
|
||||
if (!draft.state) return
|
||||
draft.state.args.run_on_behalf_of = v || undefined
|
||||
// Lending the identity to anyone in Slack needs one to lend.
|
||||
if (!v) draft.state.args.slack_anyone = undefined
|
||||
}
|
||||
}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</Label>
|
||||
{#if draft.state.args.run_on_behalf_of}
|
||||
<PermissionedAsLine
|
||||
permissionedAs={draft.onBehalfOf}
|
||||
path={draft.state.path}
|
||||
disabled={readOnly}
|
||||
onPermissionedAsChange={(permissionedAs, preserve) => {
|
||||
pickedRunAs = { permissionedAs, preserve }
|
||||
onRunAsChange?.(pickedRunAs)
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</Section>
|
||||
<Section label="Slack">
|
||||
<AgentSlackSettings {draft} {path} {workspace} {nextRunAs} />
|
||||
</Section>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
<script lang="ts">
|
||||
import { Plus, X } from 'lucide-svelte'
|
||||
import { resource } from 'runed'
|
||||
import { Button } from '$lib/components/common'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import Label from '$lib/components/Label.svelte'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import { SlackAgentsService, type SlackAgentChannel } from '$lib/gen'
|
||||
import { userStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import type { AgentDraftHandle } from '../agentDraft.svelte'
|
||||
|
||||
/** Who can ask the agent in Slack, saved with it, and the channels it is shared in, which take
|
||||
* effect at once: they belong to one Slack workspace, not to the agent's definition. */
|
||||
interface Props {
|
||||
draft: AgentDraftHandle
|
||||
/** The deployed path; channels are shared for an agent that exists. */
|
||||
path: string
|
||||
workspace: string | undefined
|
||||
/** Who the next deploy makes the agent run as, when it runs on behalf of someone. */
|
||||
nextRunAs: string | undefined
|
||||
}
|
||||
|
||||
let { draft, path, workspace, nextRunAs }: Props = $props()
|
||||
|
||||
let readOnly = $derived(!draft.canWrite)
|
||||
let obo = $derived(!!draft.state?.args.run_on_behalf_of)
|
||||
let runsAs = $derived(
|
||||
readOnly
|
||||
? (draft.onBehalfOf ?? 'its run-as user')
|
||||
: !nextRunAs || nextRunAs === `u/${$userStore?.username}`
|
||||
? 'you'
|
||||
: nextRunAs
|
||||
)
|
||||
let isAdmin = $derived(!!$userStore?.is_admin)
|
||||
|
||||
const slack = resource(
|
||||
() => ({ ws: workspace, path, deployed: !draft.noDeployed }),
|
||||
async ({ ws, path, deployed }) =>
|
||||
ws && deployed
|
||||
? await SlackAgentsService.getAgentSlackChannels({ workspace: ws, path })
|
||||
: undefined
|
||||
)
|
||||
let channels = $derived(slack.current?.channels ?? [])
|
||||
let canPick = $derived(
|
||||
!readOnly &&
|
||||
!!slack.current?.slack_team_name &&
|
||||
!!slack.current?.bot_name &&
|
||||
slack.current.missing_scopes.length === 0
|
||||
)
|
||||
|
||||
type Choice = { label: string; value: string; name: string }
|
||||
let adding = $state(false)
|
||||
let saving = $state(false)
|
||||
|
||||
// Read again whenever the channels change, so a channel just added or removed moves between
|
||||
// the list and the picker.
|
||||
const available = resource(
|
||||
() => ({ ws: adding && canPick ? workspace : undefined, channels }),
|
||||
async ({ ws, channels }) => (ws ? await listChoices(ws, channels) : [])
|
||||
)
|
||||
|
||||
async function listChoices(ws: string, shared: SlackAgentChannel[]): Promise<Choice[]> {
|
||||
try {
|
||||
const all: Choice[] = []
|
||||
let cursor: string | undefined = undefined
|
||||
// ponytail: stops at 10 pages of 200 channels; search on the server if a team has more.
|
||||
for (let page = 0; page < 10; page++) {
|
||||
const res = await SlackAgentsService.listAvailableSlackChannels({ workspace: ws, cursor })
|
||||
for (const c of res.channels) {
|
||||
if (shared.some((s) => s.channel_id === c.id)) continue
|
||||
all.push({ value: c.id, name: c.name, label: `#${c.name}` })
|
||||
}
|
||||
cursor = res.next_cursor
|
||||
if (!cursor) break
|
||||
}
|
||||
return all
|
||||
} catch (e) {
|
||||
sendUserToast(`Couldn't list the Slack channels: ${e.body ?? e.message}`, true)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function share(channelId: string, channelName: string, isDefault: boolean) {
|
||||
if (!workspace) return
|
||||
saving = true
|
||||
try {
|
||||
await SlackAgentsService.shareAgentInSlackChannel({
|
||||
workspace,
|
||||
path,
|
||||
requestBody: { channel_id: channelId, channel_name: channelName, is_default: isDefault }
|
||||
})
|
||||
adding = false
|
||||
} catch (e) {
|
||||
sendUserToast(e.body ?? e.message, true)
|
||||
} finally {
|
||||
saving = false
|
||||
// Also on failure, so a default toggle flipped in vain flips back.
|
||||
slack.refetch()
|
||||
}
|
||||
}
|
||||
|
||||
async function unshare(channel: SlackAgentChannel) {
|
||||
if (!workspace) return
|
||||
try {
|
||||
await SlackAgentsService.unshareAgentFromSlackChannel({
|
||||
workspace,
|
||||
path,
|
||||
channelId: channel.channel_id
|
||||
})
|
||||
slack.refetch()
|
||||
} catch (e) {
|
||||
sendUserToast(e.body ?? e.message, true)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if draft.state}
|
||||
<div class="flex flex-col gap-4">
|
||||
<Label label="Who can ask in its channels">
|
||||
<ToggleButtonGroup
|
||||
bind:selected={
|
||||
() => (obo && draft.state?.args.slack_anyone ? 'anyone' : 'members'),
|
||||
(v) => {
|
||||
if (!draft.state) return
|
||||
draft.state.args.slack_anyone = v === 'anyone' || undefined
|
||||
// Anyone there runs it as its identity, so there must be one.
|
||||
if (v === 'anyone') draft.state.args.run_on_behalf_of = true
|
||||
}
|
||||
}
|
||||
disabled={readOnly}
|
||||
noWFull
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
value="members"
|
||||
label={obo ? `Workspace members, as ${runsAs}` : 'Workspace members, as themselves'}
|
||||
tooltip={`Members who can read the agent, matched by their Slack email. ${obo ? `They run it as ${runsAs}, as they would in Windmill.` : 'Each runs it with their own permissions, as they would in Windmill.'}`}
|
||||
showTooltipIcon
|
||||
{item}
|
||||
small
|
||||
/>
|
||||
<ToggleButton
|
||||
value="anyone"
|
||||
label="Anyone, as {runsAs}"
|
||||
tooltip={`Everyone in these channels, people without a Windmill account included, runs it as ${runsAs}. ${obo ? '' : 'Turns on Run on behalf of, which also applies to runs from Windmill and the API. '}Applies when you deploy.`}
|
||||
showTooltipIcon
|
||||
{item}
|
||||
small
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</Label>
|
||||
<div class="flex flex-col gap-2 rounded-md border p-3">
|
||||
<span class="text-xs font-semibold text-emphasis">Channels</span>
|
||||
<div class="flex flex-col gap-2">
|
||||
{#if draft.noDeployed}
|
||||
<span class="text-2xs text-hint">Deploy the agent to share it in Slack channels.</span>
|
||||
{:else if slack.loading && !slack.current}
|
||||
<span class="text-2xs text-hint">Loading…</span>
|
||||
{:else if !slack.current?.slack_team_name}
|
||||
<span class="text-2xs text-hint">
|
||||
Slack isn't connected to the workspace.
|
||||
{#if isAdmin}
|
||||
<a href="/workspace_settings?tab=slack&agents=true">Connect it</a> with AI agents enabled.
|
||||
{/if}
|
||||
</span>
|
||||
{:else}
|
||||
{#if channels.length === 0 && !adding}
|
||||
<span class="text-2xs text-hint">Not shared in any channel.</span>
|
||||
{/if}
|
||||
{#each channels as channel (channel.channel_id)}
|
||||
<div class="flex items-center gap-2 w-full">
|
||||
<TextInput
|
||||
class="flex-1"
|
||||
inputProps={{ readonly: true }}
|
||||
value="#{channel.channel_name}"
|
||||
/>
|
||||
<Toggle
|
||||
size="xs"
|
||||
checked={channel.is_default}
|
||||
disabled={readOnly || (!isAdmin && !channel.is_default) || saving}
|
||||
on:change={(e) => 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}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
iconOnly
|
||||
destructive
|
||||
startIcon={{ icon: X }}
|
||||
title="Stop sharing in #{channel.channel_name}"
|
||||
onClick={() => unshare(channel)}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if canPick}
|
||||
{#if adding}
|
||||
<div class="flex items-center gap-2 w-full">
|
||||
<Select
|
||||
class="flex-1"
|
||||
items={available.current ?? []}
|
||||
bind:value={
|
||||
() => undefined,
|
||||
(v) => {
|
||||
const choice = available.current?.find((c) => c.value === v)
|
||||
if (choice) share(choice.value, choice.name, false)
|
||||
}
|
||||
}
|
||||
loading={available.loading || saving}
|
||||
disabled={saving}
|
||||
placeholder="Pick a public channel"
|
||||
noItemsMsg="No other public channel"
|
||||
open
|
||||
/>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="md"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
title="Cancel"
|
||||
onClick={() => (adding = false)}
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex justify-start">
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: Plus }}
|
||||
onClick={() => (adding = true)}
|
||||
>
|
||||
Share in a channel
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
<span class="text-2xs text-hint"
|
||||
>Channels are not saved with the agent: changes apply directly.</span
|
||||
>
|
||||
{:else if !readOnly}
|
||||
<span class="text-2xs text-hint">
|
||||
Slack can't be reached or was connected without AI agents; the agent's page says why.
|
||||
</span>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,306 @@
|
||||
<script lang="ts">
|
||||
import { Copy } from 'lucide-svelte'
|
||||
import CollapseLink from '$lib/components/CollapseLink.svelte'
|
||||
import { bash, markdown, typescript } from 'svelte-highlight/languages'
|
||||
import { Alert, Badge, Button, CopyButton, Tab, TabContent, Tabs } from '$lib/components/common'
|
||||
import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte'
|
||||
import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte'
|
||||
import Label from '$lib/components/Label.svelte'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import Tooltip from '$lib/components/Tooltip.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import UserSettings from '$lib/components/UserSettings.svelte'
|
||||
import type { SlackAgentChannel } from '$lib/gen'
|
||||
import { userStore } from '$lib/stores'
|
||||
import { copyToClipboard, generateRandomString } from '$lib/utils'
|
||||
import { apiBaseUrl } from '$lib/apiBaseUrl.svelte'
|
||||
import {
|
||||
curlExample,
|
||||
fetchExample,
|
||||
integrationPrompt,
|
||||
runUrl,
|
||||
sdkExample,
|
||||
sdkReactExample
|
||||
} from './agentApiExamples'
|
||||
|
||||
/**
|
||||
* The ways to use an agent outside its page: in the Slack channels it is shared in, set in its
|
||||
* settings and summed up here, and over the API.
|
||||
*/
|
||||
let {
|
||||
agentPath,
|
||||
workspace,
|
||||
isAdmin,
|
||||
chat,
|
||||
slackLoading,
|
||||
slackTeamName,
|
||||
botName,
|
||||
missingScopes,
|
||||
signingSecretSet,
|
||||
runsAs,
|
||||
anyone,
|
||||
canShare,
|
||||
channels
|
||||
}: {
|
||||
agentPath: string
|
||||
workspace: string
|
||||
isAdmin: boolean
|
||||
/** Whether the agent keeps the conversation. Slack is offered only then: a thread is one. */
|
||||
chat: boolean
|
||||
/** Whether the workspace's Slack connection is still being read. */
|
||||
slackLoading: boolean
|
||||
/** Unset when Slack is not connected to the workspace. */
|
||||
slackTeamName: string | undefined
|
||||
/** Unset when Slack can't be reached with the workspace's bot token. */
|
||||
botName: string | undefined
|
||||
/** Agent scopes the connection lacks: Slack was connected without AI agents enabled. */
|
||||
missingScopes: string[]
|
||||
/** Agents answer in Slack only when the instance verifies Slack's request signatures. */
|
||||
signingSecretSet: boolean
|
||||
/** Who the agent runs as; unset unless it runs on behalf of someone. */
|
||||
runsAs: string | undefined
|
||||
/** Whether anyone in its channels can ask it, rather than workspace members only. */
|
||||
anyone: boolean
|
||||
/** Whether the user can change its Slack settings: anyone who can edit it. */
|
||||
canShare: boolean
|
||||
channels: SlackAgentChannel[]
|
||||
} = $props()
|
||||
|
||||
let pickedTab = $state('api')
|
||||
let tab = $derived(chat ? pickedTab : 'api')
|
||||
let handle = $derived(`+${agentPath.split('/').pop()}`)
|
||||
|
||||
let userSettings: UserSettings | undefined = $state(undefined)
|
||||
let token = $state('')
|
||||
let target = $derived({
|
||||
api: `${apiBaseUrl()}/api/w/${workspace}`,
|
||||
agentPath,
|
||||
chat,
|
||||
token
|
||||
})
|
||||
let body = JSON.stringify({ user_message: 'Hello' }, null, 2)
|
||||
let headers = $derived(
|
||||
JSON.stringify(
|
||||
{ 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
null,
|
||||
2
|
||||
)
|
||||
)
|
||||
let apiTab = $state('prompt')
|
||||
let tsFlavor = $state('react')
|
||||
</script>
|
||||
|
||||
<UserSettings
|
||||
bind:this={userSettings}
|
||||
on:tokenCreated={(e) => (token = e.detail)}
|
||||
newTokenWorkspace={workspace}
|
||||
newTokenLabel={`agent-${$userStore?.username ?? 'superadmin'}-${generateRandomString(4)}`}
|
||||
scopes={[`jobs:run:agents:${agentPath}`]}
|
||||
/>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<Tabs bind:selected={() => tab, (t) => (pickedTab = t)} wrapperClass="flex-none w-full">
|
||||
<Tab value="api" label="API" />
|
||||
{#if chat}
|
||||
<Tab value="slack" label="Slack" />
|
||||
{/if}
|
||||
|
||||
{#snippet content()}
|
||||
<div class="min-h-0 grow overflow-y-auto">
|
||||
<TabContent value="slack" class="flex flex-col gap-6 p-4">
|
||||
{#if slackLoading}
|
||||
<span class="text-xs text-hint">Loading…</span>
|
||||
{:else if !slackTeamName}
|
||||
<span class="text-xs text-secondary">
|
||||
Connect Slack to the workspace, with AI agents enabled, to ask this agent from Slack,
|
||||
by its name or as a channel's default.
|
||||
</span>
|
||||
{#if isAdmin}
|
||||
<div>
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="md"
|
||||
href="/workspace_settings?tab=slack&agents=true"
|
||||
>
|
||||
Connect Slack
|
||||
</Button>
|
||||
</div>
|
||||
{:else}
|
||||
<span class="text-2xs text-hint">A workspace admin can connect it.</span>
|
||||
{/if}
|
||||
{:else}
|
||||
{#if !signingSecretSet}
|
||||
<Alert type="warning" title="Agents can't answer in Slack yet" size="xs">
|
||||
The server needs the Slack app's signing secret, so Windmill can tell who sent a
|
||||
message. An instance admin sets it as the <code>SLACK_SIGNING_SECRET</code> environment
|
||||
variable.
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if !botName}
|
||||
<Alert type="warning" title="Windmill can't reach Slack" size="xs">
|
||||
Slack refused the workspace's bot token or couldn't be reached, so agents can't
|
||||
answer there.
|
||||
{#if isAdmin}
|
||||
<a href="/workspace_settings?tab=slack&agents=true">Reconnect Slack</a> to fix it.
|
||||
{:else}
|
||||
A workspace admin can reconnect Slack to fix it.
|
||||
{/if}
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if botName && missingScopes.length > 0}
|
||||
<Alert type="warning" title="Slack was connected without AI agents" size="xs">
|
||||
The connection lacks {missingScopes.join(', ')}, so agents can't check who is
|
||||
asking.
|
||||
{#if isAdmin}
|
||||
<a href="/workspace_settings?tab=slack&agents=true">Disconnect Slack</a>, then
|
||||
connect it again with AI agents enabled.
|
||||
{:else}
|
||||
A workspace admin can reconnect Slack with AI agents enabled.
|
||||
{/if}
|
||||
</Alert>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold text-emphasis">Ask it in Slack</span>
|
||||
{#if canShare}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
href="/agents/edit/{agentPath}?settings=true"
|
||||
>
|
||||
Edit in settings
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
{#if channels.length === 0}
|
||||
<span class="text-2xs text-hint">Not shared in any channel of {slackTeamName}.</span
|
||||
>
|
||||
{:else}
|
||||
<div class="flex items-center gap-2">
|
||||
<code
|
||||
class="text-2xs font-mono text-emphasis bg-surface-secondary rounded px-2 py-1"
|
||||
>@{botName ?? '<Slack app name>'} {handle} your question</code
|
||||
>
|
||||
<CopyButton value={handle} title="Copy {handle}" />
|
||||
<Tooltip>
|
||||
{handle} matches the last part of the agent's path. Use the whole path,
|
||||
<code>+{agentPath}</code>, when two agents shared in a channel have that name.
|
||||
Replies in the thread that mention the bot go to the same agent, no name needed.
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-1">
|
||||
<span class="text-2xs text-hint">in</span>
|
||||
{#each channels as channel (channel.channel_id)}
|
||||
<Badge small
|
||||
>#{channel.channel_name}{channel.is_default ? ' · default' : ''}</Badge
|
||||
>
|
||||
{/each}
|
||||
</div>
|
||||
<span class="text-2xs text-hint">
|
||||
{#if anyone}
|
||||
Anyone in these channels can ask it, with {runsAs}'s permissions.
|
||||
{:else if runsAs}
|
||||
Workspace members can ask it, with {runsAs}'s permissions.
|
||||
{:else}
|
||||
Workspace members can ask it, with their own permissions.
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</TabContent>
|
||||
|
||||
<TabContent value="api" class="flex flex-col gap-6 p-4">
|
||||
<Label label="Token">
|
||||
<div class="flex flex-col gap-2">
|
||||
<TextInput
|
||||
bind:value={token}
|
||||
inputProps={{ placeholder: 'Paste your token here once created' }}
|
||||
class="!text-xs !font-normal"
|
||||
/>
|
||||
<div>
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
onClick={() => userSettings?.openDrawer()}
|
||||
>
|
||||
Create an agent-specific token
|
||||
<Tooltip light>
|
||||
The token can only run this agent. It is safe to share as it cannot be used to
|
||||
impersonate you.
|
||||
</Tooltip>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Label>
|
||||
<div class="flex flex-col">
|
||||
<Tabs bind:selected={apiTab}>
|
||||
<Tab value="prompt" label="AI prompt" />
|
||||
<Tab value="ts" label="TypeScript" />
|
||||
<Tab value="http" label="HTTP" />
|
||||
{#snippet content()}
|
||||
<TabContent value="ts" class="flex flex-col gap-2 mt-2">
|
||||
{#if chat}
|
||||
<ToggleButtonGroup bind:selected={tsFlavor} noWFull>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="react" label="React" {item} small />
|
||||
<ToggleButton value="any" label="Any framework" {item} small />
|
||||
<ToggleButton value="fetch" label="No SDK" {item} small />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
{/if}
|
||||
<CopyableCodeBlock
|
||||
code={!chat || tsFlavor === 'fetch'
|
||||
? fetchExample(target)
|
||||
: tsFlavor === 'react'
|
||||
? sdkReactExample(target)
|
||||
: sdkExample(target)}
|
||||
language={typescript}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value="http" class="flex flex-col gap-6 mt-2">
|
||||
<Label label="Url">
|
||||
<ClipboardPanel
|
||||
content={runUrl(target) + (chat ? '?memory_id=<conversation id>' : '')}
|
||||
/>
|
||||
</Label>
|
||||
<Label label="Body"><ClipboardPanel content={body} /></Label>
|
||||
<Label label="Headers"><ClipboardPanel content={headers} /></Label>
|
||||
<Label label="Curl">
|
||||
<span class="text-xs text-secondary">
|
||||
Runs the agent and waits for its answer. The TypeScript tab streams it
|
||||
instead.
|
||||
</span>
|
||||
<CopyableCodeBlock code={curlExample(target)} language={bash} />
|
||||
</Label>
|
||||
</TabContent>
|
||||
<TabContent value="prompt" class="flex flex-col gap-2 mt-2">
|
||||
<span class="text-xs text-secondary">
|
||||
Share this with your coding assistant. It assumes your token is in <code
|
||||
>WINDMILL_TOKEN</code
|
||||
>.
|
||||
</span>
|
||||
<div>
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: Copy }}
|
||||
onClick={() => copyToClipboard(integrationPrompt(target))}
|
||||
>
|
||||
Copy prompt
|
||||
</Button>
|
||||
</div>
|
||||
<CollapseLink text="Show prompt">
|
||||
<CopyableCodeBlock code={integrationPrompt(target)} language={markdown} wrap />
|
||||
</CollapseLink>
|
||||
</TabContent>
|
||||
{/snippet}
|
||||
</Tabs>
|
||||
</div>
|
||||
</TabContent>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Tabs>
|
||||
</div>
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* The code an agent's API tab offers to copy. Every example is meant to run as copied once the
|
||||
* token is filled in, so each one is exercised against a live agent before it changes here.
|
||||
*/
|
||||
export type AgentApiTarget = {
|
||||
/** `https://host/api/w/<workspace>`, base path included. */
|
||||
api: string
|
||||
agentPath: string
|
||||
/** Whether the agent keeps the conversation: only then is `memory_id` worth sending. */
|
||||
chat: boolean
|
||||
token: string
|
||||
}
|
||||
|
||||
export function runUrl({ api, agentPath }: AgentApiTarget): string {
|
||||
return `${api}/jobs/run/agent/${agentPath}`
|
||||
}
|
||||
|
||||
export function curlExample(t: AgentApiTarget): string {
|
||||
const conversation = t.chat
|
||||
? `# Any string names a conversation: reuse it for follow-ups, pick a new one to start over.
|
||||
CONVERSATION=$(uuidgen)
|
||||
`
|
||||
: ''
|
||||
return `TOKEN='${t.token}'
|
||||
${conversation}JOB=$(curl -s -X POST "${runUrl(t)}${t.chat ? '?memory_id=$CONVERSATION' : ''}" \\
|
||||
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \\
|
||||
-d '{"user_message": "Hello"}')
|
||||
|
||||
while true; do
|
||||
RES=$(curl -s "${t.api}/jobs_u/completed/get_result_maybe/$JOB" -H "Authorization: Bearer $TOKEN")
|
||||
if [ "$(echo "$RES" | jq .completed)" = "true" ]; then
|
||||
echo "$RES" | jq -r '.result.output // .result.error.message'
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done`
|
||||
}
|
||||
|
||||
export function fetchExample(t: AgentApiTarget): string {
|
||||
const usage = t.chat
|
||||
? `export async function main() {
|
||||
// Any string names a conversation: reuse it for follow-ups, pick a new one to start over.
|
||||
const conversation = crypto.randomUUID();
|
||||
await ask('Hello', conversation, (text) => console.log(text));
|
||||
return await ask('What did I just say?', conversation, (text) => console.log(text));
|
||||
}`
|
||||
: `export async function main() {
|
||||
return await ask('Hello', (text) => console.log(text));
|
||||
}`
|
||||
return `const API = '${t.api}';
|
||||
const HEADERS = { Authorization: 'Bearer ${t.token}' };
|
||||
|
||||
${usage}
|
||||
|
||||
/** Runs the agent and streams its answer to \`onText\` as it is written; resolves to the full answer. */
|
||||
async function ask(message${t.chat ? ', conversation' : ''}, onText) {
|
||||
const run = await fetch(\`\${API}/jobs/run/agent/${t.agentPath}${t.chat ? '?memory_id=${conversation}' : ''}\`, {
|
||||
method: 'POST',
|
||||
headers: { ...HEADERS, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user_message: message })
|
||||
});
|
||||
if (!run.ok) throw new Error(await run.text());
|
||||
const job = (await run.text()).trim();
|
||||
|
||||
// The server closes the stream now and then: reconnect from the last offset, never rerun.
|
||||
let offset = 0;
|
||||
let pending = '';
|
||||
for (;;) {
|
||||
const res = await fetch(
|
||||
\`\${API}/jobs_u/getupdate_sse/\${job}?fast=true&only_result=true&stream_offset=\${offset}\`,
|
||||
{ headers: HEADERS }
|
||||
);
|
||||
let buffer = '';
|
||||
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
|
||||
buffer += chunk;
|
||||
let end;
|
||||
while ((end = buffer.indexOf('\\n\\n')) >= 0) {
|
||||
const frame = buffer.slice(0, end);
|
||||
buffer = buffer.slice(end + 2);
|
||||
if (!frame.startsWith('data:')) continue;
|
||||
const update = JSON.parse(frame.slice(5));
|
||||
if (update.new_result_stream) {
|
||||
// One JSON event per line; a chunk can stop mid-line.
|
||||
pending += update.new_result_stream;
|
||||
offset = update.stream_offset;
|
||||
const lines = pending.split('\\n');
|
||||
pending = lines.pop();
|
||||
for (const line of lines) {
|
||||
const event = JSON.parse(line);
|
||||
if (event.type === 'token_delta') onText(event.content);
|
||||
// Also: reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result
|
||||
}
|
||||
}
|
||||
if (update.completed) {
|
||||
const result = update.only_result;
|
||||
if (result?.error) throw new Error(result.error.message);
|
||||
return result?.output;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
}
|
||||
|
||||
function sdkOptions(t: AgentApiTarget, indent: string): string {
|
||||
return `{
|
||||
baseUrl: '${t.api.replace(/\/api\/w\/[^/]+$/, '')}',
|
||||
workspace: '${t.api.split('/').pop()}',
|
||||
token: TOKEN,
|
||||
// What the agent's conversations are filed under. With a token, history stays in this
|
||||
// browser; history: 'server' also needs the token's flow_conversations:write scope.
|
||||
flowPath: '${t.agentPath}.chat',
|
||||
// Runs the agent for each turn; the conversation id is its memory.
|
||||
run: async (args, { conversationId, signal }) => {
|
||||
const res = await fetch(\`\${API}/jobs/run/agent/${t.agentPath}?memory_id=\${conversationId}\`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: \`Bearer \${TOKEN}\`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(args),
|
||||
signal
|
||||
})
|
||||
if (!res.ok) throw new Error(await res.text())
|
||||
return (await res.text()).trim()
|
||||
}
|
||||
}`.replaceAll('\n', '\n' + indent)
|
||||
}
|
||||
|
||||
export function sdkReactExample(t: AgentApiTarget): string {
|
||||
return `import { useState } from 'react'
|
||||
// On the Vercel AI SDK or assistant-ui? Use @windmill-labs/chat-sdk/ai-sdk or /assistant-ui instead:
|
||||
// https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme
|
||||
import { useWindmillChat } from '@windmill-labs/chat-sdk/react'
|
||||
|
||||
const API = '${t.api}'
|
||||
const TOKEN = '${t.token}'
|
||||
|
||||
export function AgentChat() {
|
||||
const chat = useWindmillChat(${sdkOptions(t, ' ')})
|
||||
const [draft, setDraft] = useState('')
|
||||
// Also chat.stop(), and the conversations: chat.conversations, chat.selectConversation(id), chat.newConversation()
|
||||
return (
|
||||
<div>
|
||||
{chat.messages.map((m) => <p key={m.id}><b>{m.role}</b> {m.content}</p>)}
|
||||
<form onSubmit={(e) => { e.preventDefault(); chat.sendMessage(draft); setDraft('') }}>
|
||||
<input value={draft} onChange={(e) => setDraft(e.target.value)} disabled={chat.status === 'submitted' || chat.status === 'streaming'} />
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}`
|
||||
}
|
||||
|
||||
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 <token>\`. 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=<last value>\` 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": "..."}\`.
|
||||
`
|
||||
}
|
||||
@@ -306,7 +306,7 @@
|
||||
<div class="p-1">
|
||||
<Button
|
||||
unifiedSize="md"
|
||||
startIcon={{ icon: MessageCircle }}
|
||||
startIcon={{ icon: MessageCircle, classes: 'ml-[2px]' }}
|
||||
onClick={() => (expanded = true)}
|
||||
title="{items.length} conversation{items.length !== 1 ? 's' : ''}{totalUnread > 0
|
||||
? `, ${totalUnread} unread`
|
||||
|
||||
@@ -20,15 +20,18 @@ export const clampRows: Action<HTMLElement, ClampRowsOptions> = (node, initial)
|
||||
for (const item of items) item.hidden = false
|
||||
if (toggle) toggle.hidden = true
|
||||
|
||||
const lines = [...new Set(items.map((item) => item.offsetTop))].sort((a, b) => a - b)
|
||||
// Every position is read before any item is hidden: reading one after a write forces a
|
||||
// layout per item, quadratic in the number of chips.
|
||||
const tops = items.map((item) => item.offsetTop)
|
||||
const lines = [...new Set(tops)].sort((a, b) => a - b)
|
||||
if (lines.length <= options.rows || !toggle) return
|
||||
toggle.hidden = false
|
||||
if (options.expanded) return
|
||||
|
||||
const lastLine = lines[options.rows - 1]
|
||||
for (const item of items) {
|
||||
if (item.offsetTop > lastLine && !item.hasAttribute('data-selected')) item.hidden = true
|
||||
}
|
||||
items.forEach((item, i) => {
|
||||
if (tops[i] > lastLine && !item.hasAttribute('data-selected')) item.hidden = true
|
||||
})
|
||||
const hideable = items.filter((item) => !item.hidden && !item.hasAttribute('data-selected'))
|
||||
while (toggle.offsetTop > lastLine && hideable.length) hideable.pop()!.hidden = true
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@
|
||||
let loading = $state(false)
|
||||
let drawerLoading = $state(true)
|
||||
let showLoading = $state(false)
|
||||
let initialConfig: Record<string, any> | undefined = undefined
|
||||
let initialConfig = $state<Record<string, any> | undefined>(undefined)
|
||||
let extraPerms: Record<string, boolean> = $state({})
|
||||
// Path the permissions above were loaded for — the verdict is about the schedule as
|
||||
// stored, not about a rename being typed into the form. `undefined` until a config has
|
||||
@@ -281,7 +281,7 @@
|
||||
schedule = s?.schedule ?? '0 0 12 * *'
|
||||
initialSchedule = schedule
|
||||
timezone = s?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
paused_until = s?.paused_until ?? undefined
|
||||
paused_until = asPicked(s?.paused_until)
|
||||
showPauseUntil = paused_until !== undefined
|
||||
summary = s?.summary ?? ''
|
||||
labels = s?.labels ?? undefined
|
||||
@@ -372,6 +372,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
// The draft check compares as text and the picker writes `.000Z`: spell the stored time
|
||||
// the same, or a time changed and changed back reads as unsaved (`…:00Z` vs `…:00.000Z`).
|
||||
function asPicked(time: string | null | undefined): string | undefined {
|
||||
return time ? new Date(time).toISOString() : undefined
|
||||
}
|
||||
|
||||
async function loadScheduleCfg(cfg: Record<string, any>): Promise<void> {
|
||||
loading = true
|
||||
|
||||
@@ -382,7 +388,7 @@
|
||||
schedule = cfg.schedule
|
||||
initialSchedule = schedule
|
||||
timezone = cfg.timezone
|
||||
paused_until = cfg.paused_until
|
||||
paused_until = asPicked(cfg.paused_until)
|
||||
showPauseUntil = paused_until !== undefined
|
||||
summary = cfg.summary ?? ''
|
||||
labels = cfg.labels ?? undefined
|
||||
|
||||
@@ -47,6 +47,8 @@ export interface TriggerDraftSyncOptions {
|
||||
/**
|
||||
* The deployed baseline the editor's dirty check compares against —
|
||||
* `originalConfig` for TriggerCrud editors, `initialConfig` for Schedule.
|
||||
* Must read `$state`: the baseline is cached, so a plain `let` set by a later
|
||||
* open stays stale and the "unsaved changes" banner never shows.
|
||||
*/
|
||||
deployed: () => Cfg | undefined
|
||||
}
|
||||
@@ -61,8 +63,8 @@ export interface TriggerDraftSync {
|
||||
*/
|
||||
readonly hasDraft: boolean
|
||||
/**
|
||||
* Whether a deployed baseline exists (banner can appear). Reactive, unlike
|
||||
* reading `deployed` directly (a plain `let`), so callers can reserve its slot.
|
||||
* Whether a deployed baseline exists (banner can appear), so callers can
|
||||
* reserve its slot.
|
||||
*/
|
||||
readonly hasBaseline: boolean
|
||||
/** The deployed baseline the dirty check compares against. */
|
||||
@@ -172,8 +174,7 @@ export function useTriggerDraftSync(opts: TriggerDraftSyncOptions): TriggerDraft
|
||||
!opts.drawerLoading() && baseline != null && cfgDiffers(opts.getCfg() as Cfg, baseline as Cfg)
|
||||
)
|
||||
|
||||
// Reactive "banner is possible" — depends on `drawerLoading()` so it
|
||||
// re-evaluates (and re-reads the plain-`let` baseline) once the load settles.
|
||||
// "Banner is possible" — false until the load settles.
|
||||
const hasBaseline = $derived(!opts.drawerLoading() && opts.deployed() != null)
|
||||
|
||||
/** `auto: true` marks a discard from the reactive persist-effect (not an
|
||||
@@ -313,8 +314,7 @@ export function useTriggerDraftSync(opts: TriggerDraftSyncOptions): TriggerDraft
|
||||
const deployed = opts.deployed()
|
||||
if (deployed == null) return
|
||||
// The deployed object too, so `resetToDeployed` restores the new value;
|
||||
// `settledBaseline` because it shadows the deployed object and is the
|
||||
// reactive side (an editor's `deployed` may be a plain `let`).
|
||||
// `settledBaseline` because it shadows the deployed object.
|
||||
Object.assign(deployed, patch)
|
||||
settledBaseline = { ...snapshotCfg(settledBaseline ?? deployed), ...patch }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<script lang="ts">
|
||||
import { resource } from 'runed'
|
||||
import { Badge } from '$lib/components/common'
|
||||
import SettingCard from '$lib/components/instanceSettings/SettingCard.svelte'
|
||||
import Cell from '$lib/components/table/Cell.svelte'
|
||||
import DataTable from '$lib/components/table/DataTable.svelte'
|
||||
import Head from '$lib/components/table/Head.svelte'
|
||||
import Row from '$lib/components/table/Row.svelte'
|
||||
import { SlackAgentsService } from '$lib/gen'
|
||||
|
||||
/** The channels the workspace's agents are shared in, workspace-wide. */
|
||||
let { workspace }: { workspace: string } = $props()
|
||||
|
||||
const channels = resource(
|
||||
() => workspace,
|
||||
async (workspace) => await SlackAgentsService.listSlackAgentChannels({ workspace })
|
||||
)
|
||||
</script>
|
||||
|
||||
{#if channels.current?.length}
|
||||
<SettingCard
|
||||
label="Agents shared in Slack"
|
||||
description="Bot mentions that name no agent go to the channel's default agent. Share an agent or change its channels from its settings."
|
||||
>
|
||||
<DataTable>
|
||||
<Head>
|
||||
<tr>
|
||||
<Cell head first>Channel</Cell>
|
||||
<Cell head>Agent</Cell>
|
||||
<Cell head last></Cell>
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody class="divide-y bg-surface-tertiary">
|
||||
{#each channels.current as channel (channel.channel_id + channel.agent_path)}
|
||||
<Row>
|
||||
<Cell first>#{channel.channel_name}</Cell>
|
||||
<Cell><a href="/agents/get/{channel.agent_path}">{channel.agent_path}</a></Cell>
|
||||
<Cell last class="w-24">
|
||||
{#if channel.is_default}
|
||||
<Badge small>Default</Badge>
|
||||
{/if}
|
||||
</Cell>
|
||||
</Row>
|
||||
{/each}
|
||||
</tbody>
|
||||
</DataTable>
|
||||
</SettingCard>
|
||||
{/if}
|
||||
@@ -332,6 +332,8 @@
|
||||
const sessionsSwitchShown = $derived(
|
||||
globalAiEnabled && sessionsAllowed && !$copilotInfo.workspaceDisabled
|
||||
)
|
||||
// The rail's top row; the nav below it pads to the page header's height when it is absent.
|
||||
const switchRowShown = $derived(!embedded && sessionsSwitchShown)
|
||||
const askAiShown = $derived(
|
||||
(!globalAiEnabled || !sessionsAllowed) && !$copilotInfo.workspaceDisabled
|
||||
)
|
||||
@@ -1258,7 +1260,7 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
<!-- Top row: the workspace ⇄ sessions switch, level with the page header's own
|
||||
row so the two read as one band. The workspace picker itself lives in that
|
||||
header, which is why nothing names the workspace here. -->
|
||||
{#if !embedded && sessionsSwitchShown}
|
||||
{#if switchRowShown}
|
||||
<div
|
||||
class="flex-shrink-0 px-2 gap-1 flex {collapsed
|
||||
? 'flex-col items-center py-2'
|
||||
@@ -1287,8 +1289,10 @@ outside this layout, and their shortcut must reopen the URL that is their creden
|
||||
Search / workspace items / instance settings) are spaced by the
|
||||
scroll area's gap rather than each scrolling on its own. -->
|
||||
<SidebarScrollArea color={darkMode ? SIDEBAR_BG_DARK : SIDEBAR_BG}>
|
||||
<!-- Section 1: Home/Runs + Favorites + Search -->
|
||||
<div class="px-2 pt-1 flex flex-col gap-1">
|
||||
<!-- Section 1: Home/Runs + Favorites + Search. Without the switch row above,
|
||||
Home is the top row and pt-2 centers its h-8 in the page header's h-12
|
||||
beside the docked rail. -->
|
||||
<div class="px-2 flex flex-col gap-1 {switchRowShown ? 'pt-1' : 'pt-2'}">
|
||||
{@render quickLinks(collapsed)}
|
||||
<Menubar class="flex flex-col gap-1">
|
||||
{#snippet children({ createMenu })}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
layout="page"
|
||||
enableAi={$copilotInfo.enabled}
|
||||
owns={(t) => t.host === undefined}
|
||||
startInSettings={page.url.searchParams.get('settings') === 'true'}
|
||||
onClose={(deployed) => goto(deployed ? `/agents/get/${path}` : `/?kind=agent`)}
|
||||
onDeployed={(saved) =>
|
||||
// Replaced, not pushed, when this URL stopped naming what it opens: Back would otherwise
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state'
|
||||
import { FlaskConical, FormInput, MessageSquare, Pen } from 'lucide-svelte'
|
||||
import { Pane, Splitpanes } from 'svelte-splitpanes'
|
||||
import { resource } from 'runed'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { copilotInfo } from '$lib/aiStore'
|
||||
import AgentEvalsModal from '$lib/components/flows/content/AgentEvalsModal.svelte'
|
||||
import AgentUsePanel from '$lib/components/flows/content/AgentUsePanel.svelte'
|
||||
import { SlackAgentsService } from '$lib/gen'
|
||||
import DetailPageHeader from '$lib/components/details/DetailPageHeader.svelte'
|
||||
import OnBehalfOfBadge from '$lib/components/details/OnBehalfOfBadge.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
@@ -45,6 +48,13 @@
|
||||
let history: AgentHistory | undefined = $state(undefined)
|
||||
let deleteOpen = $state(false)
|
||||
let evalsModal: AgentEvalsModal | undefined = $state(undefined)
|
||||
let clientWidth = $state(window.innerWidth)
|
||||
|
||||
const slack = resource(
|
||||
() => ({ workspace: ws, path }),
|
||||
async ({ workspace, path }) =>
|
||||
workspace ? await SlackAgentsService.getAgentSlackChannels({ workspace, path }) : undefined
|
||||
)
|
||||
let runForm: RunForm | undefined = $state(undefined)
|
||||
let isValid = $state(true)
|
||||
|
||||
@@ -197,39 +207,64 @@
|
||||
{/if}
|
||||
{/snippet}
|
||||
</DetailPageHeader>
|
||||
<div class="flex-1 min-h-0">
|
||||
{#key `${ws}:${path}:${reloaded}`}
|
||||
<AgentEditorHost
|
||||
bind:this={host}
|
||||
{path}
|
||||
workspace={ws}
|
||||
enableAi={$copilotInfo.enabled}
|
||||
view
|
||||
onOpenConfig={() => configModal?.open()}
|
||||
>
|
||||
{#snippet viewForm({ schema, run, loading, actions })}
|
||||
{#if config && !chatAvailable}
|
||||
<Alert type="info" size="xs" title="Managed memory is off" class="mb-4">
|
||||
Each run is answered on its own inputs, so this agent has no chat. That suits reusing
|
||||
it as a step in a flow.{canEdit
|
||||
? ' Turn on managed memory in its configuration to chat with it.'
|
||||
: ''}
|
||||
</Alert>
|
||||
{/if}
|
||||
<RunForm
|
||||
runnable={{ schema, path }}
|
||||
runAction={run}
|
||||
schedulable={false}
|
||||
detailed={false}
|
||||
autofocus
|
||||
{loading}
|
||||
{actions}
|
||||
bind:isValid
|
||||
bind:this={runForm}
|
||||
<div class="flex-1 min-h-0" bind:clientWidth>
|
||||
<Splitpanes>
|
||||
<Pane size={65} minSize={50}>
|
||||
{#key `${ws}:${path}:${reloaded}`}
|
||||
<AgentEditorHost
|
||||
bind:this={host}
|
||||
{path}
|
||||
workspace={ws}
|
||||
enableAi={$copilotInfo.enabled}
|
||||
view
|
||||
onOpenConfig={() => configModal?.open()}
|
||||
>
|
||||
{#snippet viewForm({ schema, run, loading, actions })}
|
||||
{#if config && !chatAvailable}
|
||||
<Alert type="info" size="xs" title="Managed memory is off" class="mb-4">
|
||||
Each run is answered on its own inputs, so this agent has no chat. That suits
|
||||
reusing it as a step in a flow.{canEdit
|
||||
? ' Turn on managed memory in its configuration to chat with it.'
|
||||
: ''}
|
||||
</Alert>
|
||||
{/if}
|
||||
<RunForm
|
||||
runnable={{ schema, path }}
|
||||
runAction={run}
|
||||
schedulable={false}
|
||||
detailed={false}
|
||||
autofocus
|
||||
{loading}
|
||||
{actions}
|
||||
bind:isValid
|
||||
bind:this={runForm}
|
||||
/>
|
||||
{/snippet}
|
||||
</AgentEditorHost>
|
||||
{/key}
|
||||
</Pane>
|
||||
<!-- ponytail: no panel below `lg`, where the split would squeeze the chat; give it a tab
|
||||
there, as a script's page does, once people use it from small screens. -->
|
||||
{#if ws && config && clientWidth >= 1024}
|
||||
<Pane size={35} minSize={15}>
|
||||
<AgentUsePanel
|
||||
agentPath={path}
|
||||
workspace={ws}
|
||||
isAdmin={!!($userStore?.is_admin || $userStore?.is_super_admin)}
|
||||
chat={chatAvailable}
|
||||
slackLoading={slack.loading && !slack.current}
|
||||
slackTeamName={slack.current?.slack_team_name}
|
||||
botName={slack.current?.bot_name}
|
||||
missingScopes={slack.current?.missing_scopes ?? []}
|
||||
signingSecretSet={slack.current?.signing_secret_set ?? true}
|
||||
runsAs={slack.current?.runs_as}
|
||||
anyone={slack.current?.anyone ?? false}
|
||||
canShare={slack.current?.can_share ?? false}
|
||||
channels={slack.current?.channels ?? []}
|
||||
/>
|
||||
{/snippet}
|
||||
</AgentEditorHost>
|
||||
{/key}
|
||||
</Pane>
|
||||
{/if}
|
||||
</Splitpanes>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
import { WORKSPACE_SHOW_SLACK_CMD, WORKSPACE_SHOW_WEBHOOK_CLI_SYNC } from '$lib/consts'
|
||||
import {
|
||||
OauthService,
|
||||
SlackAgentsService,
|
||||
WorkspaceService,
|
||||
SettingService,
|
||||
type AIConfig,
|
||||
@@ -53,6 +54,7 @@
|
||||
|
||||
import PremiumInfo from '$lib/components/settings/PremiumInfo.svelte'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import SlackChannelAgents from '$lib/components/workspaceSettings/SlackChannelAgents.svelte'
|
||||
|
||||
import ChangeWorkspaceName from '$lib/components/settings/ChangeWorkspaceName.svelte'
|
||||
import ChangeWorkspaceId from '$lib/components/settings/ChangeWorkspaceId.svelte'
|
||||
@@ -70,6 +72,7 @@
|
||||
import GitSyncSection from '$lib/components/git_sync/GitSyncSection.svelte'
|
||||
import Trashbin from '$lib/components/settings/Trashbin.svelte'
|
||||
import { untrack } from 'svelte'
|
||||
import { resource } from 'runed'
|
||||
import DbtSettings, {
|
||||
convertDbtSettingsFromBackend,
|
||||
type DbtSettingsType
|
||||
@@ -167,7 +170,18 @@
|
||||
await goto('/user/workspaces')
|
||||
}
|
||||
let useCustomSlackApp: boolean = $state(false)
|
||||
// Opt-in: Slack refuses a connection asking for a scope its app doesn't declare. An agent's page
|
||||
// links here with `agents=true`.
|
||||
let slackAgents = $state($page.url.searchParams.get('agents') === 'true')
|
||||
let slackAppType: 'instance' | 'workspace' = $state('instance')
|
||||
// Agents verify Slack's requests with the server's signing secret, which only the instance's
|
||||
// Slack app is signed with, so the toggle is offered for that app alone.
|
||||
let slackAgentsScopes = $derived(slackAgents && slackAppType === 'instance')
|
||||
const slackAgentsStatus = resource(
|
||||
() => (slackAgentsScopes ? $workspaceStore : undefined),
|
||||
async (workspace) =>
|
||||
workspace ? await SlackAgentsService.getSlackAgentsStatus({ workspace }) : undefined
|
||||
)
|
||||
|
||||
// Keep slackAppType and useCustomSlackApp in sync
|
||||
$effect(() => {
|
||||
@@ -1719,7 +1733,7 @@
|
||||
}
|
||||
}}
|
||||
onSelect={editSlackCommand}
|
||||
connectHref="/api/oauth/connect_slack"
|
||||
connectHref="/api/oauth/connect_slack{slackAgentsScopes ? '?agents=true' : ''}"
|
||||
createScriptHref="/scripts/add?hub=hub%2F28071%2Fslack%2Fexample_of_responding_to_a_slack_command_slack"
|
||||
createFlowHref="/flows/add?hub=28"
|
||||
documentationLink="https://www.windmill.dev/docs/integrations/slack"
|
||||
@@ -1732,27 +1746,45 @@
|
||||
{#snippet workspaceConfig()}
|
||||
<!-- Workspace OAuth Configuration Section -->
|
||||
{#if !slack_team_name}
|
||||
<div class="flex flex-col gap-1">
|
||||
<!-- Show toggle buttons for app type selection -->
|
||||
<ToggleButtonGroup bind:selected={slackAppType}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="instance"
|
||||
label="Instance specific Slack app"
|
||||
/>
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="workspace"
|
||||
label="Workspace specific Slack app"
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
<div class="text-2xs text-hint"
|
||||
>Use the Slack app configured at the instance level if you want to use
|
||||
the same Slack app for all workspaces. Configure your Slack app here if
|
||||
you want to use a specific Slack app for this workspace.</div
|
||||
>
|
||||
<div class="flex flex-col gap-4 pb-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<ToggleButtonGroup bind:selected={slackAppType}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="instance"
|
||||
label="Instance specific Slack app"
|
||||
/>
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="workspace"
|
||||
label="Workspace specific Slack app"
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
<div class="text-2xs text-hint"
|
||||
>Use the Slack app configured at the instance level if you want to use
|
||||
the same Slack app for all workspaces. Configure your Slack app here
|
||||
if you want to use a specific Slack app for this workspace.</div
|
||||
>
|
||||
</div>
|
||||
{#if slackAppType === 'instance'}
|
||||
<Toggle
|
||||
size="xs"
|
||||
bind:checked={slackAgents}
|
||||
options={{
|
||||
right: 'Let AI agents answer in Slack',
|
||||
rightTooltip:
|
||||
'Lets editors share agents in Slack channels, where people ask them by mentioning the bot. Needs users:read, users:read.email and channels:read on the Slack app.'
|
||||
}}
|
||||
/>
|
||||
{#if slackAgentsStatus.current?.signing_secret_set === false}
|
||||
<Alert type="warning" size="xs" title="Agents won't answer yet">
|
||||
An instance admin needs to set the Slack app's signing secret as the
|
||||
<code>SLACK_SIGNING_SECRET</code> environment variable.
|
||||
</Alert>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if slackOAuthConfigLoaded}
|
||||
@@ -1833,6 +1865,9 @@
|
||||
{/if}
|
||||
{/snippet}
|
||||
</ConnectionSection>
|
||||
{#if slack_team_name && $workspaceStore}
|
||||
<SlackChannelAgents workspace={$workspaceStore} />
|
||||
{/if}
|
||||
{:else if slack_tabs === 'teams_commands'}
|
||||
{#if !$enterpriseLicense}
|
||||
<div class="pt-4"></div>
|
||||
|
||||
Reference in New Issue
Block a user