Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🗃️ feat(database): add user_connectors.visibility and resolve connectors by visibility (#22996)

Lobehub Coder706574538bba
diff --git a/docs/development/database-schema.dbml b/docs/development/database-schema.dbml
index 9e321585caf..ad396aa7eae 100644
--- a/docs/development/database-schema.dbml
+++ b/docs/development/database-schema.dbml
@@ -1657,6 +1657,7 @@ table user_connectors {
credentials text
token_expires_at "timestamp with time zone"
metadata jsonb
+ visibility text [not null, default: 'public']
accessed_at "timestamp with time zone" [not null, default: `now()`]
created_at "timestamp with time zone" [not null, default: `now()`]
updated_at "timestamp with time zone" [not null, default: `now()`]
diff --git a/packages/database/migrations/0215_user_connectors_add_visibility.sql b/packages/database/migrations/0215_user_connectors_add_visibility.sql
new file mode 100644
index 00000000000..6233e63798c
--- /dev/null
+++ b/packages/database/migrations/0215_user_connectors_add_visibility.sql
@@ -0,0 +1 @@
+ALTER TABLE "user_connectors" ADD COLUMN IF NOT EXISTS "visibility" text DEFAULT 'public' NOT NULL;
diff --git a/packages/database/migrations/meta/0205_snapshot.json b/packages/database/migrations/meta/0215_snapshot.json
similarity index 96%
rename from packages/database/migrations/meta/0205_snapshot.json
rename to packages/database/migrations/meta/0215_snapshot.json
index 72290d57e8a..c7f42b77023 100644
--- a/packages/database/migrations/meta/0205_snapshot.json
+++ b/packages/database/migrations/meta/0215_snapshot.json
@@ -6,9 +6,9 @@
},
"dialect": "postgresql",
"enums": {},
- "id": "62c4182f-5344-4639-b52c-21d0b1e61ea1",
+ "id": "7cbe8fa4-a70b-4460-89b2-8ba138152fc6",
"policies": {},
- "prevId": "f22d5caf-0104-4f65-9ab8-8f6823ea199e",
+ "prevId": "3ad7c485-f325-43ae-80bf-417a3e451b33",
"roles": {},
"schemas": {},
"sequences": {
@@ -132,6 +132,12 @@
"primaryKey": false,
"notNull": false
},
+ "review_mark_id": {
+ "name": "review_mark_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
"client_id": {
"name": "client_id",
"type": "text",
@@ -300,6 +306,21 @@
"concurrently": false,
"method": "btree",
"with": {}
+ },
+ "acceptance_comments_review_mark_id_idx": {
+ "name": "acceptance_comments_review_mark_id_idx",
+ "columns": [
+ {
+ "expression": "review_mark_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
}
},
"foreignKeys": {
@@ -366,6 +387,15 @@
"onDelete": "set null",
"onUpdate": "no action"
},
+ "acceptance_comments_review_mark_id_acceptance_review_marks_id_fk": {
+ "name": "acceptance_comments_review_mark_id_acceptance_review_marks_id_fk",
+ "tableFrom": "acceptance_comments",
+ "tableTo": "acceptance_review_marks",
+ "columnsFrom": ["review_mark_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
"acceptance_comments_resolved_by_user_id_users_id_fk": {
"name": "acceptance_comments_resolved_by_user_id_users_id_fk",
"tableFrom": "acceptance_comments",
@@ -741,6 +771,450 @@
"checkConstraints": {},
"isRLSEnabled": false
},
+ "public.acceptance_review_marks": {
+ "name": "acceptance_review_marks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "review_id": {
+ "name": "review_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "route_key": {
+ "name": "route_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_meta": {
+ "name": "page_meta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rect_document": {
+ "name": "rect_document",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rect_viewport": {
+ "name": "rect_viewport",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scroll": {
+ "name": "scroll",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "viewport": {
+ "name": "viewport",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "regions": {
+ "name": "regions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "region_refs": {
+ "name": "region_refs",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "targets": {
+ "name": "targets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sketch": {
+ "name": "sketch",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context": {
+ "name": "context",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "screenshot_file_id": {
+ "name": "screenshot_file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "acceptance_review_marks_review_id_client_id_unique": {
+ "name": "acceptance_review_marks_review_id_client_id_unique",
+ "columns": [
+ {
+ "expression": "review_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptance_review_marks_review_id_seq_unique": {
+ "name": "acceptance_review_marks_review_id_seq_unique",
+ "columns": [
+ {
+ "expression": "review_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptance_review_marks_route_key_review_id_idx": {
+ "name": "acceptance_review_marks_route_key_review_id_idx",
+ "columns": [
+ {
+ "expression": "route_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "review_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "acceptance_review_marks_review_id_acceptance_reviews_id_fk": {
+ "name": "acceptance_review_marks_review_id_acceptance_reviews_id_fk",
+ "tableFrom": "acceptance_review_marks",
+ "tableTo": "acceptance_reviews",
+ "columnsFrom": ["review_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "acceptance_review_marks_screenshot_file_id_files_id_fk": {
+ "name": "acceptance_review_marks_screenshot_file_id_files_id_fk",
+ "tableFrom": "acceptance_review_marks",
+ "tableTo": "files",
+ "columnsFrom": ["screenshot_file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.acceptance_reviews": {
+ "name": "acceptance_reviews",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_mark_seq": {
+ "name": "last_mark_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "submitted_at": {
+ "name": "submitted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "acceptance_reviews_site_id_created_at_idx": {
+ "name": "acceptance_reviews_site_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptance_reviews_task_id_idx": {
+ "name": "acceptance_reviews_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptance_reviews_user_id_idx": {
+ "name": "acceptance_reviews_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptance_reviews_workspace_id_idx": {
+ "name": "acceptance_reviews_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptance_reviews_one_draft_per_user_unique": {
+ "name": "acceptance_reviews_one_draft_per_user_unique",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"acceptance_reviews\".\"status\" = 'draft'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "acceptance_reviews_site_id_project_sites_id_fk": {
+ "name": "acceptance_reviews_site_id_project_sites_id_fk",
+ "tableFrom": "acceptance_reviews",
+ "tableTo": "project_sites",
+ "columnsFrom": ["site_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "acceptance_reviews_user_id_users_id_fk": {
+ "name": "acceptance_reviews_user_id_users_id_fk",
+ "tableFrom": "acceptance_reviews",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "acceptance_reviews_workspace_id_workspaces_id_fk": {
+ "name": "acceptance_reviews_workspace_id_workspaces_id_fk",
+ "tableFrom": "acceptance_reviews",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "acceptance_reviews_project_id_projects_id_fk": {
+ "name": "acceptance_reviews_project_id_projects_id_fk",
+ "tableFrom": "acceptance_reviews",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "acceptance_reviews_task_id_tasks_id_fk": {
+ "name": "acceptance_reviews_task_id_tasks_id_fk",
+ "tableFrom": "acceptance_reviews",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
"public.agents": {
"name": "agents",
"schema": "",
@@ -1610,6 +2084,13 @@
"notNull": false,
"default": "'{}'::jsonb"
},
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
"revoked_at": {
"name": "revoked_at",
"type": "timestamp with time zone",
@@ -5354,6 +5835,21 @@
"method": "btree",
"with": {}
},
+ "agent_inbox_messages_topic_id_idx": {
+ "name": "agent_inbox_messages_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
"agent_inbox_messages_user_id_idx": {
"name": "agent_inbox_messages_user_id_idx",
"columns": [
@@ -7361,6 +7857,27 @@
"method": "btree",
"with": {}
},
+ "agent_operations_workspace_id_created_at_idx": {
+ "name": "agent_operations_workspace_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
"agent_operations_metadata_idx": {
"name": "agent_operations_metadata_idx",
"columns": [
@@ -11301,6 +11818,12 @@
"primaryKey": false,
"notNull": false
},
+ "wake": {
+ "name": "wake",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
"manifest": {
"name": "manifest",
"type": "jsonb",
@@ -12581,6 +13104,12 @@
"primaryKey": false,
"notNull": false
},
+ "peer_user_id": {
+ "name": "peer_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
"title": {
"name": "title",
"type": "text",
@@ -12766,6 +13295,15 @@
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
+ },
+ "channels_peer_user_id_users_id_fk": {
+ "name": "channels_peer_user_id_users_id_fk",
+ "tableFrom": "channels",
+ "tableTo": "users",
+ "columnsFrom": ["peer_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -13520,6 +14058,13 @@
"primaryKey": false,
"notNull": false
},
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
"accessed_at": {
"name": "accessed_at",
"type": "timestamp with time zone",
@@ -13833,8 +14378,8 @@
"checkConstraints": {},
"isRLSEnabled": false
},
- "public.dashboard_items": {
- "name": "dashboard_items",
+ "public.user_contact_requests": {
+ "name": "user_contact_requests",
"schema": "",
"columns": {
"id": {
@@ -13844,42 +14389,36 @@
"notNull": true,
"default": "gen_random_uuid()"
},
- "dashboard_id": {
- "name": "dashboard_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": true
- },
- "widget_id": {
- "name": "widget_id",
- "type": "uuid",
+ "requester_id": {
+ "name": "requester_id",
+ "type": "text",
"primaryKey": false,
"notNull": true
},
- "user_id": {
- "name": "user_id",
+ "addressee_id": {
+ "name": "addressee_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "workspace_id": {
- "name": "workspace_id",
+ "message": {
+ "name": "message",
"type": "text",
"primaryKey": false,
"notNull": false
},
- "layout": {
- "name": "layout",
- "type": "jsonb",
+ "status": {
+ "name": "status",
+ "type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": true,
+ "default": "'pending'"
},
- "sort_order": {
- "name": "sort_order",
- "type": "integer",
+ "responded_at": {
+ "name": "responded_at",
+ "type": "timestamp with time zone",
"primaryKey": false,
- "notNull": true,
- "default": 0
+ "notNull": false
},
"accessed_at": {
"name": "accessed_at",
@@ -13904,38 +14443,39 @@
}
},
"indexes": {
- "dashboard_items_dashboard_id_widget_id_unique": {
- "name": "dashboard_items_dashboard_id_widget_id_unique",
+ "user_contact_requests_pending_unique": {
+ "name": "user_contact_requests_pending_unique",
"columns": [
{
- "expression": "dashboard_id",
+ "expression": "requester_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
- "expression": "widget_id",
+ "expression": "addressee_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
+ "where": "\"user_contact_requests\".\"status\" = 'pending'",
"concurrently": false,
"method": "btree",
"with": {}
},
- "dashboard_items_dashboard_id_sort_order_idx": {
- "name": "dashboard_items_dashboard_id_sort_order_idx",
+ "user_contact_requests_addressee_status_idx": {
+ "name": "user_contact_requests_addressee_status_idx",
"columns": [
{
- "expression": "dashboard_id",
+ "expression": "addressee_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
- "expression": "sort_order",
+ "expression": "status",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -13946,11 +14486,17 @@
"method": "btree",
"with": {}
},
- "dashboard_items_widget_id_idx": {
- "name": "dashboard_items_widget_id_idx",
+ "user_contact_requests_requester_status_idx": {
+ "name": "user_contact_requests_requester_status_idx",
"columns": [
{
- "expression": "widget_id",
+ "expression": "requester_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -13960,12 +14506,117 @@
"concurrently": false,
"method": "btree",
"with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_contact_requests_requester_id_users_id_fk": {
+ "name": "user_contact_requests_requester_id_users_id_fk",
+ "tableFrom": "user_contact_requests",
+ "tableTo": "users",
+ "columnsFrom": ["requester_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
},
- "dashboard_items_user_id_idx": {
- "name": "dashboard_items_user_id_idx",
+ "user_contact_requests_addressee_id_users_id_fk": {
+ "name": "user_contact_requests_addressee_id_users_id_fk",
+ "tableFrom": "user_contact_requests",
+ "tableTo": "users",
+ "columnsFrom": ["addressee_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "user_contact_requests_not_self_check": {
+ "name": "user_contact_requests_not_self_check",
+ "value": "\"user_contact_requests\".\"requester_id\" <> \"user_contact_requests\".\"addressee_id\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.user_contact_tag_assignments": {
+ "name": "user_contact_tag_assignments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "contact_id": {
+ "name": "contact_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_contact_tag_assignments_tag_id_contact_id_unique": {
+ "name": "user_contact_tag_assignments_tag_id_contact_id_unique",
"columns": [
{
- "expression": "user_id",
+ "expression": "tag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "contact_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_contact_tag_assignments_contact_id_idx": {
+ "name": "user_contact_tag_assignments_contact_id_idx",
+ "columns": [
+ {
+ "expression": "contact_id",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -13976,11 +14627,11 @@
"method": "btree",
"with": {}
},
- "dashboard_items_workspace_id_idx": {
- "name": "dashboard_items_workspace_id_idx",
+ "user_contact_tag_assignments_user_id_idx": {
+ "name": "user_contact_tag_assignments_user_id_idx",
"columns": [
{
- "expression": "workspace_id",
+ "expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -13993,41 +14644,32 @@
}
},
"foreignKeys": {
- "dashboard_items_dashboard_id_dashboards_id_fk": {
- "name": "dashboard_items_dashboard_id_dashboards_id_fk",
- "tableFrom": "dashboard_items",
- "tableTo": "dashboards",
- "columnsFrom": ["dashboard_id"],
+ "user_contact_tag_assignments_tag_id_user_contact_tags_id_fk": {
+ "name": "user_contact_tag_assignments_tag_id_user_contact_tags_id_fk",
+ "tableFrom": "user_contact_tag_assignments",
+ "tableTo": "user_contact_tags",
+ "columnsFrom": ["tag_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
- "dashboard_items_widget_id_widgets_id_fk": {
- "name": "dashboard_items_widget_id_widgets_id_fk",
- "tableFrom": "dashboard_items",
- "tableTo": "widgets",
- "columnsFrom": ["widget_id"],
+ "user_contact_tag_assignments_contact_id_user_contacts_id_fk": {
+ "name": "user_contact_tag_assignments_contact_id_user_contacts_id_fk",
+ "tableFrom": "user_contact_tag_assignments",
+ "tableTo": "user_contacts",
+ "columnsFrom": ["contact_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
- "dashboard_items_user_id_users_id_fk": {
- "name": "dashboard_items_user_id_users_id_fk",
- "tableFrom": "dashboard_items",
+ "user_contact_tag_assignments_user_id_users_id_fk": {
+ "name": "user_contact_tag_assignments_user_id_users_id_fk",
+ "tableFrom": "user_contact_tag_assignments",
"tableTo": "users",
"columnsFrom": ["user_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
- },
- "dashboard_items_workspace_id_workspaces_id_fk": {
- "name": "dashboard_items_workspace_id_workspaces_id_fk",
- "tableFrom": "dashboard_items",
- "tableTo": "workspaces",
- "columnsFrom": ["workspace_id"],
- "columnsTo": ["id"],
- "onDelete": "cascade",
- "onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -14036,8 +14678,8 @@
"checkConstraints": {},
"isRLSEnabled": false
},
- "public.dashboards": {
- "name": "dashboards",
+ "public.user_contact_tags": {
+ "name": "user_contact_tags",
"schema": "",
"columns": {
"id": {
@@ -14053,38 +14695,14 @@
"primaryKey": false,
"notNull": true
},
- "workspace_id": {
- "name": "workspace_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "project_id": {
- "name": "project_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "agent_id": {
- "name": "agent_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "title": {
- "name": "title",
+ "name": {
+ "name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "description": {
- "name": "description",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "icon": {
- "name": "icon",
+ "color": {
+ "name": "color",
"type": "text",
"primaryKey": false,
"notNull": false
@@ -14096,31 +14714,548 @@
"notNull": true,
"default": 0
},
- "metadata": {
- "name": "metadata",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": false
- },
- "visibility": {
- "name": "visibility",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'public'"
- },
- "deleted_at": {
- "name": "deleted_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "is_deleted": {
- "name": "is_deleted",
- "type": "boolean",
- "primaryKey": false,
- "notNull": false
- },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_contact_tags_user_id_name_unique": {
+ "name": "user_contact_tags_user_id_name_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_contact_tags_user_id_users_id_fk": {
+ "name": "user_contact_tags_user_id_users_id_fk",
+ "tableFrom": "user_contact_tags",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_contacts": {
+ "name": "user_contacts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "contact_user_id": {
+ "name": "contact_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remark": {
+ "name": "remark",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "phones": {
+ "name": "phones",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_contacts_user_unique": {
+ "name": "user_contacts_user_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "contact_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"user_contacts\".\"contact_user_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_contacts_agent_unique": {
+ "name": "user_contacts_agent_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"user_contacts\".\"agent_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_contacts_contact_user_id_idx": {
+ "name": "user_contacts_contact_user_id_idx",
+ "columns": [
+ {
+ "expression": "contact_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_contacts_agent_id_idx": {
+ "name": "user_contacts_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_contacts_user_id_users_id_fk": {
+ "name": "user_contacts_user_id_users_id_fk",
+ "tableFrom": "user_contacts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_contacts_contact_user_id_users_id_fk": {
+ "name": "user_contacts_contact_user_id_users_id_fk",
+ "tableFrom": "user_contacts",
+ "tableTo": "users",
+ "columnsFrom": ["contact_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_contacts_agent_id_agents_id_fk": {
+ "name": "user_contacts_agent_id_agents_id_fk",
+ "tableFrom": "user_contacts",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboard_items": {
+ "name": "dashboard_items",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "widget_id": {
+ "name": "widget_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "layout": {
+ "name": "layout",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "dashboard_items_dashboard_id_widget_id_unique": {
+ "name": "dashboard_items_dashboard_id_widget_id_unique",
+ "columns": [
+ {
+ "expression": "dashboard_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "widget_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dashboard_items_dashboard_id_sort_order_idx": {
+ "name": "dashboard_items_dashboard_id_sort_order_idx",
+ "columns": [
+ {
+ "expression": "dashboard_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sort_order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dashboard_items_widget_id_idx": {
+ "name": "dashboard_items_widget_id_idx",
+ "columns": [
+ {
+ "expression": "widget_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dashboard_items_user_id_idx": {
+ "name": "dashboard_items_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dashboard_items_workspace_id_idx": {
+ "name": "dashboard_items_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "dashboard_items_dashboard_id_dashboards_id_fk": {
+ "name": "dashboard_items_dashboard_id_dashboards_id_fk",
+ "tableFrom": "dashboard_items",
+ "tableTo": "dashboards",
+ "columnsFrom": ["dashboard_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboard_items_widget_id_widgets_id_fk": {
+ "name": "dashboard_items_widget_id_widgets_id_fk",
+ "tableFrom": "dashboard_items",
+ "tableTo": "widgets",
+ "columnsFrom": ["widget_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboard_items_user_id_users_id_fk": {
+ "name": "dashboard_items_user_id_users_id_fk",
+ "tableFrom": "dashboard_items",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboard_items_workspace_id_workspaces_id_fk": {
+ "name": "dashboard_items_workspace_id_workspaces_id_fk",
+ "tableFrom": "dashboard_items",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
"accessed_at": {
"name": "accessed_at",
"type": "timestamp with time zone",
@@ -18417,6 +19552,12 @@
"primaryKey": false,
"notNull": false
},
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
"visibility": {
"name": "visibility",
"type": "text",
@@ -22836,100 +23977,927 @@
}
},
"indexes": {
- "linear_sync_rules_project_id_idx": {
- "name": "linear_sync_rules_project_id_idx",
+ "linear_sync_rules_project_id_idx": {
+ "name": "linear_sync_rules_project_id_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "linear_sync_rules_connection_id_idx": {
+ "name": "linear_sync_rules_connection_id_idx",
+ "columns": [
+ {
+ "expression": "connection_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "linear_sync_rules_user_id_idx": {
+ "name": "linear_sync_rules_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "linear_sync_rules_workspace_id_idx": {
+ "name": "linear_sync_rules_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "linear_sync_rules_project_id_projects_id_fk": {
+ "name": "linear_sync_rules_project_id_projects_id_fk",
+ "tableFrom": "linear_sync_rules",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "linear_sync_rules_connection_id_linear_connections_id_fk": {
+ "name": "linear_sync_rules_connection_id_linear_connections_id_fk",
+ "tableFrom": "linear_sync_rules",
+ "tableTo": "linear_connections",
+ "columnsFrom": ["connection_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "linear_sync_rules_user_id_users_id_fk": {
+ "name": "linear_sync_rules_user_id_users_id_fk",
+ "tableFrom": "linear_sync_rules",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "linear_sync_rules_workspace_id_workspaces_id_fk": {
+ "name": "linear_sync_rules_workspace_id_workspaces_id_fk",
+ "tableFrom": "linear_sync_rules",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.llm_generation_tracing": {
+ "name": "llm_generation_tracing",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "scenario": {
+ "name": "scenario",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_version": {
+ "name": "prompt_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_hash": {
+ "name": "prompt_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "schema_name": {
+ "name": "schema_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_tracing_id": {
+ "name": "parent_tracing_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "success": {
+ "name": "success",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_detail": {
+ "name": "error_detail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "validation_failed": {
+ "name": "validation_failed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "input_hash": {
+ "name": "input_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_hint": {
+ "name": "input_hint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "latency_ms": {
+ "name": "latency_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "numeric(12, 8)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storage_key": {
+ "name": "storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_signal": {
+ "name": "feedback_signal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_score": {
+ "name": "feedback_score",
+ "type": "numeric(3, 2)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_source": {
+ "name": "feedback_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_data": {
+ "name": "feedback_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_updated_at": {
+ "name": "feedback_updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trace_id": {
+ "name": "trace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "span_id": {
+ "name": "span_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "llm_generation_tracing_scenario_idx": {
+ "name": "llm_generation_tracing_scenario_idx",
+ "columns": [
+ {
+ "expression": "scenario",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_prompt_version_idx": {
+ "name": "llm_generation_tracing_prompt_version_idx",
+ "columns": [
+ {
+ "expression": "prompt_version",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_user_id_idx": {
+ "name": "llm_generation_tracing_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_agent_id_idx": {
+ "name": "llm_generation_tracing_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_topic_id_idx": {
+ "name": "llm_generation_tracing_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_workspace_id_idx": {
+ "name": "llm_generation_tracing_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_provider_idx": {
+ "name": "llm_generation_tracing_provider_idx",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_model_idx": {
+ "name": "llm_generation_tracing_model_idx",
+ "columns": [
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_success_idx": {
+ "name": "llm_generation_tracing_success_idx",
+ "columns": [
+ {
+ "expression": "success",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_error_code_idx": {
+ "name": "llm_generation_tracing_error_code_idx",
+ "columns": [
+ {
+ "expression": "error_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_validation_failed_idx": {
+ "name": "llm_generation_tracing_validation_failed_idx",
+ "columns": [
+ {
+ "expression": "validation_failed",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_feedback_signal_idx": {
+ "name": "llm_generation_tracing_feedback_signal_idx",
+ "columns": [
+ {
+ "expression": "feedback_signal",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_created_at_idx": {
+ "name": "llm_generation_tracing_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "llm_generation_tracing_workspace_id_workspaces_id_fk": {
+ "name": "llm_generation_tracing_workspace_id_workspaces_id_fk",
+ "tableFrom": "llm_generation_tracing",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.meeting_minutes": {
+ "name": "meeting_minutes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "meeting_id": {
+ "name": "meeting_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chapters": {
+ "name": "chapters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "decisions": {
+ "name": "decisions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "action_items": {
+ "name": "action_items",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "keywords": {
+ "name": "keywords",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "meeting_minutes_meeting_id_unique": {
+ "name": "meeting_minutes_meeting_id_unique",
+ "columns": [
+ {
+ "expression": "meeting_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "meeting_minutes_document_id_idx": {
+ "name": "meeting_minutes_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "meeting_minutes_meeting_id_meetings_id_fk": {
+ "name": "meeting_minutes_meeting_id_meetings_id_fk",
+ "tableFrom": "meeting_minutes",
+ "tableTo": "meetings",
+ "columnsFrom": ["meeting_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "meeting_minutes_document_id_documents_id_fk": {
+ "name": "meeting_minutes_document_id_documents_id_fk",
+ "tableFrom": "meeting_minutes",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.meeting_segments": {
+ "name": "meeting_segments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "meeting_id": {
+ "name": "meeting_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "speaker_id": {
+ "name": "speaker_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "start_ms": {
+ "name": "start_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_ms": {
+ "name": "end_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "meeting_segments_meeting_id_source_seq_unique": {
+ "name": "meeting_segments_meeting_id_source_seq_unique",
+ "columns": [
+ {
+ "expression": "meeting_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "meeting_segments_meeting_id_source_start_ms_idx": {
+ "name": "meeting_segments_meeting_id_source_start_ms_idx",
+ "columns": [
+ {
+ "expression": "meeting_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "start_ms",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "meeting_segments_speaker_id_idx": {
+ "name": "meeting_segments_speaker_id_idx",
+ "columns": [
+ {
+ "expression": "speaker_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "meeting_segments_meeting_id_meetings_id_fk": {
+ "name": "meeting_segments_meeting_id_meetings_id_fk",
+ "tableFrom": "meeting_segments",
+ "tableTo": "meetings",
+ "columnsFrom": ["meeting_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "meeting_segments_speaker_id_meeting_speakers_id_fk": {
+ "name": "meeting_segments_speaker_id_meeting_speakers_id_fk",
+ "tableFrom": "meeting_segments",
+ "tableTo": "meeting_speakers",
+ "columnsFrom": ["speaker_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.meeting_speakers": {
+ "name": "meeting_speakers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "meeting_id": {
+ "name": "meeting_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "meeting_speakers_meeting_id_label_unique": {
+ "name": "meeting_speakers_meeting_id_label_unique",
"columns": [
{
- "expression": "project_id",
+ "expression": "meeting_id",
"isExpression": false,
"asc": true,
"nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "linear_sync_rules_connection_id_idx": {
- "name": "linear_sync_rules_connection_id_idx",
- "columns": [
- {
- "expression": "connection_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "linear_sync_rules_user_id_idx": {
- "name": "linear_sync_rules_user_id_idx",
- "columns": [
- {
- "expression": "user_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "linear_sync_rules_workspace_id_idx": {
- "name": "linear_sync_rules_workspace_id_idx",
- "columns": [
+ },
{
- "expression": "workspace_id",
+ "expression": "label",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
- "isUnique": false,
+ "isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
- "linear_sync_rules_project_id_projects_id_fk": {
- "name": "linear_sync_rules_project_id_projects_id_fk",
- "tableFrom": "linear_sync_rules",
- "tableTo": "projects",
- "columnsFrom": ["project_id"],
- "columnsTo": ["id"],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "linear_sync_rules_connection_id_linear_connections_id_fk": {
- "name": "linear_sync_rules_connection_id_linear_connections_id_fk",
- "tableFrom": "linear_sync_rules",
- "tableTo": "linear_connections",
- "columnsFrom": ["connection_id"],
- "columnsTo": ["id"],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "linear_sync_rules_user_id_users_id_fk": {
- "name": "linear_sync_rules_user_id_users_id_fk",
- "tableFrom": "linear_sync_rules",
- "tableTo": "users",
- "columnsFrom": ["user_id"],
- "columnsTo": ["id"],
- "onDelete": "cascade",
- "onUpdate": "no action"
- },
- "linear_sync_rules_workspace_id_workspaces_id_fk": {
- "name": "linear_sync_rules_workspace_id_workspaces_id_fk",
- "tableFrom": "linear_sync_rules",
- "tableTo": "workspaces",
- "columnsFrom": ["workspace_id"],
+ "meeting_speakers_meeting_id_meetings_id_fk": {
+ "name": "meeting_speakers_meeting_id_meetings_id_fk",
+ "tableFrom": "meeting_speakers",
+ "tableTo": "meetings",
+ "columnsFrom": ["meeting_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
@@ -22941,8 +24909,8 @@
"checkConstraints": {},
"isRLSEnabled": false
},
- "public.llm_generation_tracing": {
- "name": "llm_generation_tracing",
+ "public.meetings": {
+ "name": "meetings",
"schema": "",
"columns": {
"id": {
@@ -22952,193 +24920,106 @@
"notNull": true,
"default": "gen_random_uuid()"
},
- "scenario": {
- "name": "scenario",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "prompt_version": {
- "name": "prompt_version",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "prompt_hash": {
- "name": "prompt_hash",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "schema_name": {
- "name": "schema_name",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "agent_id": {
- "name": "agent_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "topic_id": {
- "name": "topic_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
"workspace_id": {
"name": "workspace_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
- "trigger": {
- "name": "trigger",
+ "title": {
+ "name": "title",
"type": "text",
"primaryKey": false,
- "notNull": false
- },
- "parent_tracing_id": {
- "name": "parent_tracing_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": false
+ "notNull": true
},
- "provider": {
- "name": "provider",
+ "status": {
+ "name": "status",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": true,
+ "default": "'recording'"
},
- "model": {
- "name": "model",
+ "platform": {
+ "name": "platform",
"type": "text",
"primaryKey": false,
- "notNull": false
- },
- "success": {
- "name": "success",
- "type": "boolean",
- "primaryKey": false,
"notNull": true
},
- "error_code": {
- "name": "error_code",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "error_detail": {
- "name": "error_detail",
+ "realtime_provider": {
+ "name": "realtime_provider",
"type": "text",
"primaryKey": false,
- "notNull": false
- },
- "validation_failed": {
- "name": "validation_failed",
- "type": "boolean",
- "primaryKey": false,
- "notNull": true,
- "default": false
+ "notNull": true
},
- "input_hash": {
- "name": "input_hash",
+ "refine_provider": {
+ "name": "refine_provider",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": true
},
- "input_hint": {
- "name": "input_hint",
+ "language": {
+ "name": "language",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": true,
+ "default": "'auto'"
},
- "latency_ms": {
- "name": "latency_ms",
- "type": "integer",
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
"primaryKey": false,
- "notNull": false
+ "notNull": true,
+ "default": "now()"
},
- "input_tokens": {
- "name": "input_tokens",
- "type": "integer",
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
- "output_tokens": {
- "name": "output_tokens",
+ "duration_ms": {
+ "name": "duration_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
- "cost_usd": {
- "name": "cost_usd",
- "type": "numeric(12, 8)",
- "primaryKey": false,
- "notNull": false
- },
- "storage_key": {
- "name": "storage_key",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "feedback_signal": {
- "name": "feedback_signal",
+ "audio_file_id": {
+ "name": "audio_file_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
- "feedback_score": {
- "name": "feedback_score",
- "type": "numeric(3, 2)",
- "primaryKey": false,
- "notNull": false
- },
- "feedback_source": {
- "name": "feedback_source",
+ "local_audio_path": {
+ "name": "local_audio_path",
"type": "text",
"primaryKey": false,
"notNull": false
},
- "feedback_data": {
- "name": "feedback_data",
+ "error": {
+ "name": "error",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
- "feedback_updated_at": {
- "name": "feedback_updated_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "trace_id": {
- "name": "trace_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "span_id": {
- "name": "span_id",
+ "visibility": {
+ "name": "visibility",
"type": "text",
"primaryKey": false,
- "notNull": false
+ "notNull": true,
+ "default": "'private'"
},
- "metadata": {
- "name": "metadata",
- "type": "jsonb",
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
"primaryKey": false,
- "notNull": false,
- "default": "'{}'::jsonb"
+ "notNull": true,
+ "default": "now()"
},
"created_at": {
"name": "created_at",
@@ -23146,149 +25027,33 @@
"primaryKey": false,
"notNull": true,
"default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
}
},
"indexes": {
- "llm_generation_tracing_scenario_idx": {
- "name": "llm_generation_tracing_scenario_idx",
- "columns": [
- {
- "expression": "scenario",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_prompt_version_idx": {
- "name": "llm_generation_tracing_prompt_version_idx",
- "columns": [
- {
- "expression": "prompt_version",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_user_id_idx": {
- "name": "llm_generation_tracing_user_id_idx",
+ "meetings_user_id_workspace_id_created_at_idx": {
+ "name": "meetings_user_id_workspace_id_created_at_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_agent_id_idx": {
- "name": "llm_generation_tracing_agent_id_idx",
- "columns": [
- {
- "expression": "agent_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_topic_id_idx": {
- "name": "llm_generation_tracing_topic_id_idx",
- "columns": [
- {
- "expression": "topic_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_workspace_id_idx": {
- "name": "llm_generation_tracing_workspace_id_idx",
- "columns": [
+ },
{
"expression": "workspace_id",
"isExpression": false,
"asc": true,
"nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_provider_idx": {
- "name": "llm_generation_tracing_provider_idx",
- "columns": [
- {
- "expression": "provider",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_model_idx": {
- "name": "llm_generation_tracing_model_idx",
- "columns": [
- {
- "expression": "model",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_success_idx": {
- "name": "llm_generation_tracing_success_idx",
- "columns": [
- {
- "expression": "success",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_error_code_idx": {
- "name": "llm_generation_tracing_error_code_idx",
- "columns": [
+ },
{
- "expression": "error_code",
+ "expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -23299,26 +25064,17 @@
"method": "btree",
"with": {}
},
- "llm_generation_tracing_validation_failed_idx": {
- "name": "llm_generation_tracing_validation_failed_idx",
+ "meetings_workspace_id_created_at_idx": {
+ "name": "meetings_workspace_id_created_at_idx",
"columns": [
{
- "expression": "validation_failed",
+ "expression": "workspace_id",
"isExpression": false,
"asc": true,
"nulls": "last"
- }
- ],
- "isUnique": false,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
- "llm_generation_tracing_feedback_signal_idx": {
- "name": "llm_generation_tracing_feedback_signal_idx",
- "columns": [
+ },
{
- "expression": "feedback_signal",
+ "expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -23329,11 +25085,11 @@
"method": "btree",
"with": {}
},
- "llm_generation_tracing_created_at_idx": {
- "name": "llm_generation_tracing_created_at_idx",
+ "meetings_audio_file_id_idx": {
+ "name": "meetings_audio_file_id_idx",
"columns": [
{
- "expression": "created_at",
+ "expression": "audio_file_id",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -23346,14 +25102,32 @@
}
},
"foreignKeys": {
- "llm_generation_tracing_workspace_id_workspaces_id_fk": {
- "name": "llm_generation_tracing_workspace_id_workspaces_id_fk",
- "tableFrom": "llm_generation_tracing",
+ "meetings_user_id_users_id_fk": {
+ "name": "meetings_user_id_users_id_fk",
+ "tableFrom": "meetings",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "meetings_workspace_id_workspaces_id_fk": {
+ "name": "meetings_workspace_id_workspaces_id_fk",
+ "tableFrom": "meetings",
"tableTo": "workspaces",
"columnsFrom": ["workspace_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
+ },
+ "meetings_audio_file_id_files_id_fk": {
+ "name": "meetings_audio_file_id_files_id_fk",
+ "tableFrom": "meetings",
+ "tableTo": "files",
+ "columnsFrom": ["audio_file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -47884,6 +49658,13 @@
"primaryKey": false,
"notNull": false
},
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
"joined_at": {
"name": "joined_at",
"type": "timestamp with time zone",
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index 9a1b58cca32..a714be295ca 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -1505,6 +1505,13 @@
"when": 1794757089562,
"tag": "0214_user_contacts",
"breakpoints": true
+ },
+ {
+ "idx": 215,
+ "version": "7",
+ "when": 1794770338614,
+ "tag": "0215_user_connectors_add_visibility",
+ "breakpoints": true
}
],
"version": "6"
diff --git a/packages/database/src/models/__tests__/connectorVisibility.test.ts b/packages/database/src/models/__tests__/connectorVisibility.test.ts
new file mode 100644
index 00000000000..d4c9d5dd7c8
--- /dev/null
+++ b/packages/database/src/models/__tests__/connectorVisibility.test.ts
@@ -0,0 +1,731 @@
+import { RequestTrigger } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ chatGroups,
+ topics,
+ topicShares,
+ userConnectors,
+ userConnectorTools,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { CHANNEL_TOPIC_TRIGGER } from '../../utils/topicVisibility';
+import { ConnectorModel } from '../connector';
+import { ConnectorToolModel } from '../connectorTool';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const owner = 'cv-owner';
+const mate = 'cv-mate';
+const workspaceId = 'cv-ws';
+const privateAgent = 'cv-agent-private';
+const workspaceAgent = 'cv-agent-workspace';
+const matePrivateAgent = 'cv-agent-mate-private';
+const privateTopic = 'cv-topic-private';
+const workspaceAgentTopic = 'cv-topic-workspace-agent';
+
+const insertConnector = async (row: {
+ agentId?: string | null;
+ identifier: string;
+ metadata?: Record<string, unknown> | null;
+ name?: string;
+ userId?: string;
+ visibility?: 'private' | 'public';
+ workspaceId?: string | null;
+}) => {
+ const [created] = await serverDB
+ .insert(userConnectors)
+ .values({
+ agentId: row.agentId ?? null,
+ identifier: row.identifier,
+ mcpConnectionType: 'http',
+ mcpServerUrl: `https://${row.identifier}.example.com/mcp`,
+ metadata: row.metadata ?? null,
+ name: row.name ?? row.identifier,
+ sourceType: 'custom',
+ status: 'connected',
+ userId: row.userId ?? owner,
+ visibility: row.visibility ?? 'public',
+ workspaceId: row.workspaceId === undefined ? workspaceId : row.workspaceId,
+ })
+ .returning();
+ return created;
+};
+
+const insertTopic = async (row: {
+ agentId?: string;
+ groupId?: string;
+ id: string;
+ senderId?: string;
+ trigger?: string;
+ userId?: string;
+}) => {
+ await serverDB.insert(topics).values({
+ agentId: row.agentId ?? privateAgent,
+ groupId: row.groupId,
+ id: row.id,
+ senderId: row.senderId,
+ trigger: row.trigger,
+ userId: row.userId ?? owner,
+ workspaceId,
+ });
+};
+
+/**
+ * The connector identifiers a run resolves, sorted. Each fixture row uses a
+ * distinct identifier unless a test is about collisions.
+ */
+const resolvedIdentifiers = async (
+ model: ConnectorModel,
+ target: { agentId?: string; topicId?: string },
+) => (await model.resolveAll(target)).map((row) => row.identifier).sort();
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: owner }, { id: mate }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: owner, slug: 'cv-ws' });
+ await serverDB.insert(agents).values([
+ { id: privateAgent, userId: owner, visibility: 'private', workspaceId },
+ { id: workspaceAgent, userId: owner, visibility: 'public', workspaceId },
+ { id: matePrivateAgent, userId: mate, visibility: 'private', workspaceId },
+ ]);
+ await insertTopic({ id: privateTopic });
+ await insertTopic({ agentId: workspaceAgent, id: workspaceAgentTopic });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+/** Workspace shared + the owner's private + the owner's personal, plus a teammate's private. */
+const seedConnectors = async () => {
+ await insertConnector({ identifier: 'ws-shared-linear', userId: mate });
+ await insertConnector({ identifier: 'owner-private-notion', visibility: 'private' });
+ await insertConnector({ identifier: 'owner-personal-gmail', workspaceId: null });
+ await insertConnector({ identifier: 'mate-private-slack', userId: mate, visibility: 'private' });
+ await insertConnector({ identifier: 'mate-personal-github', userId: mate, workspaceId: null });
+};
+
+describe('connector visibility — management view', () => {
+ it('lists the shared rows plus only the caller’s own private rows', async () => {
+ await seedConnectors();
+
+ const ownerList = (await new ConnectorModel(serverDB, owner, workspaceId).query())
+ .map((row) => row.identifier)
+ .sort();
+ const mateList = (await new ConnectorModel(serverDB, mate, workspaceId).query())
+ .map((row) => row.identifier)
+ .sort();
+
+ expect(ownerList).toEqual(['owner-private-notion', 'ws-shared-linear']);
+ expect(mateList).toEqual(['mate-private-slack', 'ws-shared-linear']);
+ });
+
+ it('hides a private row from a teammate looking it up by id', async () => {
+ const privateRow = await insertConnector({ identifier: 'notion', visibility: 'private' });
+
+ expect(
+ await new ConnectorModel(serverDB, mate, workspaceId).findById(privateRow.id),
+ ).toBeNull();
+ expect(
+ (await new ConnectorModel(serverDB, owner, workspaceId).findById(privateRow.id))?.id,
+ ).toBe(privateRow.id);
+ });
+});
+
+describe('connector visibility — runtime resolution', () => {
+ it('gives a private agent the shared rows plus its owner’s private and personal rows', async () => {
+ await seedConnectors();
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(
+ await resolvedIdentifiers(model, { agentId: privateAgent, topicId: privateTopic }),
+ ).toEqual(['owner-personal-gmail', 'owner-private-notion', 'ws-shared-linear']);
+ });
+
+ it('gives a workspace agent the shared rows only', async () => {
+ await seedConnectors();
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(
+ await resolvedIdentifiers(model, { agentId: workspaceAgent, topicId: workspaceAgentTopic }),
+ ).toEqual(['ws-shared-linear']);
+ });
+
+ it('keeps private rows out when the run names no topic', async () => {
+ await seedConnectors();
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(await resolvedIdentifiers(model, { agentId: privateAgent })).toEqual([
+ 'ws-shared-linear',
+ ]);
+ expect(await resolvedIdentifiers(model, {})).toEqual(['ws-shared-linear']);
+ });
+
+ it.each([
+ ['a group topic', { groupId: 'cv-group' }],
+ ['a channel run topic', { trigger: CHANNEL_TOPIC_TRIGGER }],
+ ['a bot topic', { trigger: RequestTrigger.Bot }],
+ ['an agent-share topic', { trigger: RequestTrigger.AgentShare }],
+ ['a share visitor topic', { senderId: 'visitor-1' }],
+ ['a topic of another agent', { agentId: workspaceAgent }],
+ ])('keeps private rows out of %s', async (_label, topic) => {
+ await serverDB
+ .insert(chatGroups)
+ .values({ id: 'cv-group', title: 'Group', userId: owner, workspaceId });
+ await insertTopic({ id: 'cv-topic-shared-surface', ...topic });
+ await seedConnectors();
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(
+ await resolvedIdentifiers(model, {
+ agentId: privateAgent,
+ topicId: 'cv-topic-shared-surface',
+ }),
+ ).toEqual(['ws-shared-linear']);
+ });
+
+ it('keeps private rows out of a topic shared by link, and only while it is', async () => {
+ await seedConnectors();
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ const run = { agentId: privateAgent, topicId: privateTopic };
+ const ownerRows = ['owner-personal-gmail', 'owner-private-notion', 'ws-shared-linear'];
+ const setShare = (visibility: 'link' | 'private') =>
+ serverDB
+ .insert(topicShares)
+ .values({ topicId: privateTopic, userId: owner, visibility, workspaceId })
+ .onConflictDoUpdate({ set: { visibility }, target: topicShares.topicId });
+
+ // An owner-only share is read by the owner alone, so the topic stays private.
+ await setShare('private');
+ expect(await resolvedIdentifiers(model, run)).toEqual(ownerRows);
+
+ // Anyone holding the link reads the live transcript.
+ await setShare('link');
+ expect(await resolvedIdentifiers(model, run)).toEqual(['ws-shared-linear']);
+
+ await setShare('private');
+ expect(await resolvedIdentifiers(model, run)).toEqual(ownerRows);
+ });
+
+ it('never resolves the owner’s private rows for anyone else', async () => {
+ await seedConnectors();
+ // A teammate naming the owner's private agent and topic gets nothing private:
+ // the agent and topic must belong to the caller.
+ const mateModel = new ConnectorModel(serverDB, mate, workspaceId);
+
+ expect(
+ await resolvedIdentifiers(mateModel, { agentId: privateAgent, topicId: privateTopic }),
+ ).toEqual(['ws-shared-linear']);
+ });
+
+ it('gives a teammate’s private agent the teammate’s private rows, not the owner’s', async () => {
+ await insertTopic({ agentId: matePrivateAgent, id: 'cv-topic-mate', userId: mate });
+ await seedConnectors();
+ const mateModel = new ConnectorModel(serverDB, mate, workspaceId);
+
+ expect(
+ await resolvedIdentifiers(mateModel, { agentId: matePrivateAgent, topicId: 'cv-topic-mate' }),
+ ).toEqual(['mate-personal-github', 'mate-private-slack', 'ws-shared-linear']);
+ });
+
+ it('does not resolve a private row mounted by a workspace agent', async () => {
+ await insertConnector({
+ identifier: 'notion',
+ metadata: { mountedByAgentId: workspaceAgent },
+ visibility: 'private',
+ });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(
+ await resolvedIdentifiers(model, { agentId: workspaceAgent, topicId: workspaceAgentTopic }),
+ ).toEqual([]);
+ });
+
+ it('leaves personal-mode resolution unchanged', async () => {
+ await seedConnectors();
+ const personal = new ConnectorModel(serverDB, owner);
+
+ expect(await resolvedIdentifiers(personal, {})).toEqual(['owner-personal-gmail']);
+ });
+
+ it('keeps agentless identifier lookups to the shared rows', async () => {
+ await insertConnector({ identifier: 'notion', visibility: 'private' });
+ const shared = await insertConnector({ identifier: 'notion', userId: mate });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect((await model.queryByIdentifiers(['notion'])).map((row) => row.id)).toEqual([shared.id]);
+ expect((await model.queryReferencesByIdentifiers(['notion'])).map((row) => row.id)).toEqual([
+ shared.id,
+ ]);
+ });
+});
+
+describe('connector visibility — agent configuration', () => {
+ const availableIdentifiers = async (model: ConnectorModel, agentId?: string) =>
+ (await model.queryAvailableForAgent(agentId)).map((row) => row.identifier).sort();
+
+ it('offers a private agent its owner’s private and personal rows without a topic', async () => {
+ // Regression: validation ran the topic-free runtime scope, so Agent Builder
+ // refused to enable the owner's private connector on their private agent.
+ await seedConnectors();
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(await availableIdentifiers(model, privateAgent)).toEqual([
+ 'owner-personal-gmail',
+ 'owner-private-notion',
+ 'ws-shared-linear',
+ ]);
+ });
+
+ it('offers a workspace agent, or a teammate naming the private agent, the shared rows only', async () => {
+ await seedConnectors();
+ const ownerModel = new ConnectorModel(serverDB, owner, workspaceId);
+ const mateModel = new ConnectorModel(serverDB, mate, workspaceId);
+
+ expect(await availableIdentifiers(ownerModel, workspaceAgent)).toEqual(['ws-shared-linear']);
+ expect(await availableIdentifiers(mateModel, privateAgent)).toEqual(['ws-shared-linear']);
+ expect(await availableIdentifiers(ownerModel)).toEqual(['ws-shared-linear']);
+ });
+
+ it('reports the row the agent’s own conversation ranks first, without credentials', async () => {
+ await insertConnector({ identifier: 'notion', userId: mate });
+ const privateRow = await insertConnector({ identifier: 'notion', visibility: 'private' });
+ await serverDB
+ .update(userConnectors)
+ .set({ isEnabled: false })
+ .where(eq(userConnectors.id, privateRow.id));
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(await model.queryAvailableForAgent(privateAgent)).toEqual([
+ { identifier: 'notion', isEnabled: false, status: 'connected' },
+ ]);
+ });
+});
+
+describe('connector visibility — priority within one identifier', () => {
+ it('prefers the owner’s workspace-private row, then personal, then shared', async () => {
+ const shared = await insertConnector({ identifier: 'gmail', userId: mate });
+ const personal = await insertConnector({ identifier: 'gmail', workspaceId: null });
+ const workspacePrivate = await insertConnector({ identifier: 'gmail', visibility: 'private' });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ const target = { agentId: privateAgent, topicId: privateTopic };
+
+ expect((await model.resolveByIdentifiers(['gmail'], target)).map((r) => r.id)).toEqual([
+ workspacePrivate.id,
+ ]);
+
+ await serverDB.delete(userConnectors).where(eq(userConnectors.id, workspacePrivate.id));
+ expect((await model.resolveByIdentifiers(['gmail'], target)).map((r) => r.id)).toEqual([
+ personal.id,
+ ]);
+
+ await serverDB.delete(userConnectors).where(eq(userConnectors.id, personal.id));
+ expect((await model.resolveByIdentifiers(['gmail'], target)).map((r) => r.id)).toEqual([
+ shared.id,
+ ]);
+ });
+
+ it('lets an agent binding outrank whose connection it is', async () => {
+ await insertConnector({ identifier: 'gmail', visibility: 'private' });
+ const agentOwned = await insertConnector({ agentId: privateAgent, identifier: 'gmail' });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(
+ (
+ await model.resolveByIdentifiers(['gmail'], {
+ agentId: privateAgent,
+ topicId: privateTopic,
+ })
+ ).map((r) => r.id),
+ ).toEqual([agentOwned.id]);
+ });
+
+ it('breaks a tie by id, not by physical row order', async () => {
+ const [first, second] = [
+ await insertConnector({ identifier: 'gmail', userId: mate }),
+ await insertConnector({ identifier: 'gmail', userId: owner }),
+ ].sort((a, b) => a.id.localeCompare(b.id));
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ // Touch the lower id so it moves to the end of the heap.
+ await serverDB
+ .update(userConnectors)
+ .set({ name: 'touched' })
+ .where(eq(userConnectors.id, first.id));
+
+ const [picked] = await model.resolveByIdentifiers(['gmail'], {
+ agentId: privateAgent,
+ topicId: privateTopic,
+ });
+
+ expect(picked.id).toBe(first.id);
+ expect(picked.id).not.toBe(second.id);
+ });
+});
+
+describe('connector visibility — write paths', () => {
+ it('looks up the idempotency row within one visibility', async () => {
+ const shared = await insertConnector({ identifier: 'notion', userId: mate });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect((await model.findScopedByIdentifier('notion'))?.id).toBe(shared.id);
+ expect(
+ await model.findScopedByIdentifier('notion', undefined, undefined, 'private'),
+ ).toBeNull();
+
+ const mine = await insertConnector({ identifier: 'notion', visibility: 'private' });
+ expect(
+ (await model.findScopedByIdentifier('notion', undefined, undefined, 'private'))?.id,
+ ).toBe(mine.id);
+ // A teammate's private row of the same identifier is never "mine".
+ await insertConnector({ identifier: 'slack', userId: mate, visibility: 'private' });
+ expect(await model.findScopedByIdentifier('slack', undefined, undefined, 'private')).toBeNull();
+ });
+
+ it('targets the row holding the Composio account a write names', async () => {
+ const composio = (connectedAccountId: string) => ({ composio: { connectedAccountId } });
+ const shared = await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-shared'),
+ userId: mate,
+ });
+ const mine = await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-mine'),
+ visibility: 'private',
+ });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ // Removing or refreshing the shared account (Settings lists it) must not
+ // land on the caller's private connection of the same app.
+ expect((await model.findManageableByIdentifier('gmail', undefined, 'acc-shared'))?.id).toBe(
+ shared.id,
+ );
+ expect((await model.findManageableByIdentifier('gmail', undefined, 'acc-mine'))?.id).toBe(
+ mine.id,
+ );
+ // A new connection (no account yet) keeps the private row first.
+ expect((await model.findManageableByIdentifier('gmail'))?.id).toBe(mine.id);
+ // An account no row holds is a legacy, workspace-wide connection: it lands
+ // on the shared row, never in the caller's private one.
+ expect((await model.findManageableByIdentifier('gmail', undefined, 'acc-legacy'))?.id).toBe(
+ shared.id,
+ );
+ });
+
+ it('never adopts a legacy Composio account into the caller’s private row', async () => {
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-mine' } },
+ visibility: 'private',
+ });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+
+ // No shared row yet: the write creates one under the shared policy.
+ expect(await model.findManageableByIdentifier('gmail', undefined, 'acc-legacy')).toBeNull();
+ });
+
+ it('tells when a Composio account sits on a teammate’s private connector', async () => {
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-mate' } },
+ userId: mate,
+ visibility: 'private',
+ });
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-shared' } },
+ userId: mate,
+ });
+ const ownerModel = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(await ownerModel.isComposioAccountPrivateToTeammate('acc-mate')).toBe(true);
+ expect(await ownerModel.isComposioAccountPrivateToTeammate('acc-shared')).toBe(false);
+ // The teammate's own row is not "a teammate's" to them, and nothing is
+ // private outside a workspace.
+ expect(
+ await new ConnectorModel(serverDB, mate, workspaceId).isComposioAccountPrivateToTeammate(
+ 'acc-mate',
+ ),
+ ).toBe(false);
+ expect(
+ await new ConnectorModel(serverDB, owner).isComposioAccountPrivateToTeammate('acc-mate'),
+ ).toBe(false);
+ });
+
+ it('finds a Composio account by the account alone, whatever identifier a write names', async () => {
+ // ROOT CAUSE:
+ //
+ // The private-account check also matched on the identifier the request
+ // named. A member who read a teammate's private account id from the
+ // workspace-wide projection sent it with another identifier, the check
+ // missed the teammate's row, and the remote account was deleted.
+ const matePrivate = await insertConnector({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-mate' } },
+ userId: mate,
+ visibility: 'private',
+ });
+ // A member's own row may name any account: its metadata is client-written.
+ const forged = await insertConnector({
+ identifier: 'github',
+ metadata: { composio: { connectedAccountId: 'acc-mate' } },
+ visibility: 'private',
+ });
+ await serverDB
+ .insert(workspaces)
+ .values({ id: 'cv-ws-other', name: 'Other', primaryOwnerId: mate, slug: 'cv-ws-other' });
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-mate' } },
+ userId: mate,
+ workspaceId: 'cv-ws-other',
+ });
+ const ownerModel = new ConnectorModel(serverDB, owner, workspaceId);
+
+ expect(await ownerModel.isComposioAccountPrivateToTeammate('acc-mate')).toBe(true);
+ // Both rows of this workspace that name the account, the teammate's private
+ // one included; another workspace's row is out of scope.
+ expect(
+ (await ownerModel.queryComposioAccountHolders('acc-mate')).map((row) => row.id).toSorted(),
+ ).toEqual([matePrivate.id, forged.id].toSorted());
+ expect(await ownerModel.queryComposioAccountHolders('acc-unknown')).toEqual([]);
+ });
+
+ it('writes a personal row resolved in a workspace run through its personal scope', async () => {
+ const personal = await insertConnector({ identifier: 'gmail', workspaceId: null });
+ const workspaceModel = new ConnectorModel(serverDB, owner, workspaceId);
+
+ // The workspace model alone cannot reach the personal row.
+ await workspaceModel.update(personal.id, { name: 'via workspace' });
+ expect(
+ (await serverDB.select().from(userConnectors).where(eq(userConnectors.id, personal.id)))[0]
+ .name,
+ ).toBe('gmail');
+
+ await workspaceModel.forRow(personal).update(personal.id, { name: 'via home scope' });
+ expect(
+ (await serverDB.select().from(userConnectors).where(eq(userConnectors.id, personal.id)))[0]
+ .name,
+ ).toBe('via home scope');
+ });
+
+ it('never re-homes a teammate’s or a workspace row', async () => {
+ const workspaceModel = new ConnectorModel(serverDB, owner, workspaceId);
+ const matePersonal = await insertConnector({
+ identifier: 'github',
+ userId: mate,
+ workspaceId: null,
+ });
+ const shared = await insertConnector({ identifier: 'linear' });
+
+ expect(workspaceModel.forRow(matePersonal)).toBe(workspaceModel);
+ expect(workspaceModel.forRow(shared)).toBe(workspaceModel);
+ });
+});
+
+describe('connector visibility — legacy Composio projection', () => {
+ const composio = (connectedAccountId: string, linkedByUserId?: string) => ({
+ composio: { connectedAccountId, ...(linkedByUserId && { linkedByUserId }) },
+ });
+ /** The owner's legacy connection, as the workspace-wide plugin projection holds it. */
+ const legacy = { connectedAccountId: 'acc-legacy', identifier: 'gmail', ownerUserId: owner };
+ const legacyFor = (userId: string) =>
+ new ConnectorModel(serverDB, userId, workspaceId).pickLegacyComposioMirrors([legacy]);
+
+ it('keeps a teammate’s legacy connection when a member adds a private connector of the app', async () => {
+ // ROOT CAUSE:
+ //
+ // Any connector row of the identifier counted as the projection's connector,
+ // so a member's private row — added without the shared connector policy —
+ // took the legacy connection away from every other member.
+ await insertConnector({ identifier: 'gmail', userId: mate, visibility: 'private' });
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-mate', mate),
+ userId: mate,
+ visibility: 'private',
+ });
+
+ expect(await legacyFor(owner)).toEqual([legacy]);
+ expect(await legacyFor(mate)).toEqual([legacy]);
+ });
+
+ it('keeps it when a member writes the legacy account id into their own row', async () => {
+ // Every member reads the projection's account ids, and a connector's
+ // metadata is client-written: an account id alone proves nothing.
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-legacy'),
+ userId: mate,
+ visibility: 'private',
+ });
+ await insertConnector({
+ agentId: matePrivateAgent,
+ identifier: 'gmail',
+ metadata: composio('acc-legacy'),
+ userId: mate,
+ });
+
+ expect(await legacyFor(mate)).toEqual([legacy]);
+ });
+
+ it('withholds the mirror of a connector its creator made private', async () => {
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-legacy', owner),
+ visibility: 'private',
+ });
+
+ expect(await legacyFor(mate)).toEqual([]);
+ });
+
+ it('withholds a private connection copied into a projection row of another app', async () => {
+ // ROOT CAUSE:
+ //
+ // Only connector rows of the mirror's identifier were compared, and every
+ // member can write a projection row under any app. Copying a teammate's
+ // privatized account and entity under another identifier made it pass as
+ // a legacy connection, and Composio runs any tool on it.
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-legacy', owner),
+ visibility: 'private',
+ });
+ const forged = { ...legacy, identifier: 'notion' };
+
+ expect(
+ await new ConnectorModel(serverDB, mate, workspaceId).pickLegacyComposioMirrors([forged]),
+ ).toEqual([]);
+ // Another app's account, or the same account under another entity, is not
+ // this connection.
+ const unrelated = [
+ { ...forged, connectedAccountId: 'acc-other' },
+ { ...forged, ownerUserId: mate },
+ ];
+ expect(
+ await new ConnectorModel(serverDB, mate, workspaceId).pickLegacyComposioMirrors(unrelated),
+ ).toEqual(unrelated);
+ });
+
+ it('withholds the mirror of an account an agent row now runs', async () => {
+ await insertConnector({
+ agentId: workspaceAgent,
+ identifier: 'gmail',
+ metadata: composio('acc-legacy'),
+ });
+
+ expect(await legacyFor(mate)).toEqual([]);
+ });
+
+ it('withholds the previous account while its linker reconnects the app', async () => {
+ // The private row already holds the new, still pending account; the
+ // projection rows of other members still carry the previous one.
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-reconnecting', owner),
+ visibility: 'private',
+ });
+
+ expect(await legacyFor(mate)).toEqual([]);
+ // A mirror of another app, or linked by someone else, is unaffected.
+ expect(
+ await new ConnectorModel(serverDB, mate, workspaceId).pickLegacyComposioMirrors([
+ { ...legacy, identifier: 'slack' },
+ { ...legacy, ownerUserId: mate },
+ ]),
+ ).toEqual([
+ { ...legacy, identifier: 'slack' },
+ { ...legacy, ownerUserId: mate },
+ ]);
+ });
+
+ it('looks at the caller’s own rows outside a workspace', async () => {
+ await insertConnector({
+ identifier: 'gmail',
+ metadata: composio('acc-legacy', owner),
+ workspaceId: null,
+ });
+
+ expect(await new ConnectorModel(serverDB, owner).pickLegacyComposioMirrors([legacy])).toEqual(
+ [],
+ );
+ expect(
+ await new ConnectorModel(serverDB, mate).pickLegacyComposioMirrors([
+ { ...legacy, ownerUserId: mate },
+ ]),
+ ).toEqual([{ ...legacy, ownerUserId: mate }]);
+ });
+});
+
+describe('connector visibility — tool rows of a resolved personal connector', () => {
+ const insertTool = async (connector: {
+ id: string;
+ userId: string;
+ workspaceId: string | null;
+ }) =>
+ serverDB.insert(userConnectorTools).values({
+ crudType: 'read',
+ permission: 'auto',
+ toolName: 'search',
+ userConnectorId: connector.id,
+ userId: connector.userId,
+ workspaceId: connector.workspaceId,
+ });
+
+ it('lets the workspace run read the caller’s own personal connector tools by id', async () => {
+ const personal = await insertConnector({ identifier: 'gmail', workspaceId: null });
+ await insertTool(personal);
+ const toolModel = new ConnectorToolModel(serverDB, owner, workspaceId, { agentRun: true });
+
+ expect((await toolModel.queryAllByConnectorIds([personal.id])).map((t) => t.toolName)).toEqual([
+ 'search',
+ ]);
+ expect((await toolModel.queryByConnector(personal.id)).map((t) => t.toolName)).toEqual([
+ 'search',
+ ]);
+ // Name lookups without a resolved connector stay strictly scoped.
+ expect(await toolModel.findByToolName('search')).toBeUndefined();
+ });
+
+ it('never reads a teammate’s personal connector tools', async () => {
+ const matePersonal = await insertConnector({
+ identifier: 'github',
+ userId: mate,
+ workspaceId: null,
+ });
+ await insertTool(matePersonal);
+ const toolModel = new ConnectorToolModel(serverDB, owner, workspaceId, { agentRun: true });
+
+ expect(await toolModel.queryAllByConnectorIds([matePersonal.id])).toEqual([]);
+ });
+
+ it('hides a teammate’s private connector tools', async () => {
+ const matePrivate = await insertConnector({
+ identifier: 'slack',
+ userId: mate,
+ visibility: 'private',
+ });
+ await insertTool(matePrivate);
+
+ expect(
+ await new ConnectorToolModel(serverDB, owner, workspaceId, {
+ agentRun: true,
+ }).queryByConnector(matePrivate.id),
+ ).toEqual([]);
+ expect(
+ (
+ await new ConnectorToolModel(serverDB, mate, workspaceId, {
+ agentRun: true,
+ }).queryByConnector(matePrivate.id)
+ ).length,
+ ).toBe(1);
+ });
+});
diff --git a/packages/database/src/models/__tests__/plugin.test.ts b/packages/database/src/models/__tests__/plugin.test.ts
index 30cc0c2548e..4d18c5edc8e 100644
--- a/packages/database/src/models/__tests__/plugin.test.ts
+++ b/packages/database/src/models/__tests__/plugin.test.ts
@@ -195,6 +195,63 @@ describe('PluginModel', () => {
});
});
+ describe('Composio projection in a workspace', () => {
+ const workspaceId = 'plugin-composio-ws';
+ const composio = (connectedAccountId: string) => ({
+ composio: { appSlug: 'GMAIL', authConfigId: 'cfg', connectedAccountId, status: 'ACTIVE' },
+ });
+
+ beforeEach(async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId });
+ // One projection row per member for the same app, plus a non-Composio plugin.
+ await new PluginModel(serverDB, userId, workspaceId).create({
+ customParams: composio('acc-legacy'),
+ identifier: 'gmail',
+ type: 'plugin',
+ });
+ await new PluginModel(serverDB, '456', workspaceId).create({
+ customParams: composio('acc-private'),
+ identifier: 'gmail',
+ type: 'plugin',
+ });
+ await new PluginModel(serverDB, userId, workspaceId).create({
+ identifier: 'search',
+ type: 'plugin',
+ });
+ });
+
+ it('lists every member’s Composio rows with who wrote them', async () => {
+ const rows = await new PluginModel(serverDB, '456', workspaceId).queryComposioMirrors([
+ 'gmail',
+ 'search',
+ ]);
+
+ expect(
+ rows.map((row) => [row.userId, row.customParams?.composio?.connectedAccountId]).sort(),
+ ).toEqual([
+ ['456', 'acc-private'],
+ [userId, 'acc-legacy'],
+ ]);
+ expect(await new PluginModel(serverDB, '456', workspaceId).queryComposioMirrors([])).toEqual(
+ [],
+ );
+ });
+
+ it('removes only the rows mirroring one account', async () => {
+ await new PluginModel(serverDB, '456', workspaceId).deleteComposioMirrors(
+ 'gmail',
+ 'acc-private',
+ );
+
+ const rows = await new PluginModel(serverDB, userId, workspaceId).queryComposioMirrors();
+ expect(rows.map((row) => row.customParams?.composio?.connectedAccountId)).toEqual([
+ 'acc-legacy',
+ ]);
+ });
+ });
+
describe('update', () => {
it('should update an installed plugin', async () => {
await serverDB.insert(userInstalledPlugins).values({
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index 9abd62fe643..5b9aa446ed5 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -1,11 +1,35 @@
+import type { ConnectorVisibility } from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
+import pMap from 'p-map';
import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';
import { agentEvalDatasets, ConnectorStatus, userConnectors, userConnectorTools } from '../schemas';
import type { LobeChatDatabase } from '../type';
-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+import {
+ buildWorkspacePayload,
+ buildWorkspaceWhere,
+ normalizeWorkspaceId,
+} from '../utils/workspace';
import { EvalConnectorUpdateError, normalizeEvalConnectorPatch } from './connectorEval';
-import { connectorAccessScope } from './connectorScope';
+import {
+ connectorAccessScope,
+ connectorAgentConfigScope,
+ connectorRunScope,
+ type ConnectorRunTarget,
+} from './connectorScope';
+
+export type { ConnectorRunTarget } from './connectorScope';
+
+/**
+ * What a runtime resolution runs as: a {@link ConnectorRunTarget}, or an agent
+ * id alone — that agent's run without a topic, which resolves the workspace's
+ * shared rows only (see {@link connectorRunScope}).
+ */
+export type ConnectorRunTargetInput = ConnectorRunTarget | string;
+
+const toRunTarget = (target: ConnectorRunTargetInput = {}): ConnectorRunTarget =>
+ typeof target === 'string' ? { agentId: target } : target;
interface GateKeeper {
decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;
@@ -52,6 +76,21 @@ export interface ComposioConnectorReference extends ConnectorReference {
};
}
+/**
+ * A Composio account held by the legacy plugin projection
+ * (`user_installed_plugins.customParams.composio`).
+ */
+export interface ComposioPluginMirror {
+ connectedAccountId: string;
+ identifier: string;
+ /**
+ * The Composio user entity the projection runs the account as
+ * (`linkedByUserId`, else the projection row's user), the same owner the
+ * runtime passes to Composio.
+ */
+ ownerUserId: string;
+}
+
type CreateConnectorParams = Omit<NewUserConnector, 'userId' | 'id' | 'createdAt' | 'updatedAt'>;
type UpdateConnectorParams = Partial<
@@ -103,6 +142,21 @@ export class ConnectorModel {
*/
private baseScope = () => and(this.ownership(), isNull(userConnectors.agentId));
+ /**
+ * Base rows an agentless runtime lookup may use. In a workspace that is the
+ * shared rows only: a member's private connector serves their private agents
+ * and nothing else (not a client-side call without an agent, not a dashboard
+ * read another member can see). The management view ({@link baseScope}) also
+ * lists the caller's own private rows.
+ */
+ private sharedBaseScope = () =>
+ and(
+ this.evaluationDatasetId
+ ? this.ownership()
+ : connectorRunScope(this.db, { userId: this.userId, workspaceId: this.workspaceId }, {}),
+ isNull(userConnectors.agentId),
+ );
+
/**
* Deterministic connector order for runtime resolution: by identifier, then id
* so rows sharing an identifier have a stable tie-break. Resolved connectors
@@ -131,8 +185,10 @@ export class ConnectorModel {
};
/**
- * Candidate rows for agent-aware resolution within the current scope. For an
- * agent this is:
+ * Candidate rows for agent-aware resolution. The base rows come from
+ * {@link connectorRunScope}: a workspace run sees the shared rows, and a
+ * private agent's run in its own topic also sees its owner's private and
+ * personal rows. On top of that, for an agent:
* - agent-OWNED rows (`agent_id = agentId`) — the Copy / Connect-new flows;
* - base rows (`agent_id IS NULL`) that are either MOUNTED by this agent
* (`metadata.mountedByAgentId = agentId`, the Linked flow) or free (not
@@ -140,8 +196,23 @@ export class ConnectorModel {
* A base row mounted (locked) by *another* agent is excluded, so a mounted
* connector can serve only its one agent. Without an agent, only free base
* rows are candidates.
+ *
+ * An evaluation model keeps its own Dataset scope ({@link ownership}).
*/
- private scopePredicate = (agentId?: string) => {
+ private scopePredicate = (target: ConnectorRunTarget) =>
+ this.agentNarrowing(
+ this.evaluationDatasetId
+ ? this.ownership()
+ : connectorRunScope(
+ this.db,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ target,
+ ),
+ target.agentId,
+ );
+
+ /** The agent-owned / mounted / free narrowing of {@link scopePredicate} over `base`. */
+ private agentNarrowing = (base: SQL | undefined, agentId?: string) => {
// COALESCE'd to a sentinel rather than null-tested: `->> … IS NULL` in a
// WHERE clause is one bm25 index on `user_connectors` away from taking every
// caller down at plan time. See the note on `TopicModel`. `''` is a safe
@@ -150,10 +221,10 @@ export class ConnectorModel {
// Private Dataset imports are usable only through an exact evaluation binding.
// Exclude them before priority selection and credential decryption in ordinary chat.
if (!agentId) {
- return and(this.ownership(), isNull(userConnectors.agentId), sql`${mountedBy} = ''`);
+ return and(base, isNull(userConnectors.agentId), sql`${mountedBy} = ''`);
}
return and(
- this.ownership(),
+ base,
or(
eq(userConnectors.agentId, agentId),
and(
@@ -165,17 +236,38 @@ export class ConnectorModel {
};
/**
- * Reduce candidate rows to at most one per identifier by priority within the
- * current scope: agent-OWNED (2) > MOUNTED by this agent (1) > free base (0).
- * Resolution never crosses the base scope: a workspace run resolves within the
- * workspace, a personal run within personal — no cross-scope personal fallback.
+ * Reduce candidate rows to at most one per identifier. Rows are ranked by
+ * binding first, then by whose connection it is:
+ *
+ * 1. binding — agent-OWNED by this agent > MOUNTED by this agent > free base;
+ * 2. within a binding — the owner's private row in this workspace > the
+ * owner's personal row > the workspace's shared row. A private agent's
+ * owner chose their own connection for their own agent, so it shadows
+ * the shared one; a row made inside this workspace beats one carried
+ * over from personal space.
+ *
+ * Equal ranks keep the first row in {@link resolutionOrder} (identifier,
+ * then id), so the pick never follows the physical row order. The result
+ * drives the order of the model's tool schema array.
+ *
+ * Only a private agent's run in its own topic can see private or personal
+ * rows at all (see {@link connectorRunScope}); every other run only ranks
+ * shared rows here.
*/
private pickByPriority = (rows: UserConnectorItem[], agentId?: string): UserConnectorItem[] => {
- const rank = (row: UserConnectorItem): number => {
+ const workspaceId = normalizeWorkspaceId(this.workspaceId);
+ const bindingRank = (row: UserConnectorItem): number => {
if (agentId && row.agentId === agentId) return 2;
if (agentId && row.metadata?.mountedByAgentId === agentId) return 1;
return 0;
};
+ const ownershipRank = (row: UserConnectorItem): number => {
+ if (!workspaceId) return 0;
+ if (row.workspaceId === workspaceId && row.visibility === 'private') return 2;
+ if (row.workspaceId === null) return 1;
+ return 0;
+ };
+ const rank = (row: UserConnectorItem) => bindingRank(row) * 3 + ownershipRank(row);
const byIdentifier = new Map<string, UserConnectorItem>();
for (const row of rows) {
const current = byIdentifier.get(row.identifier);
@@ -184,6 +276,28 @@ export class ConnectorModel {
return [...byIdentifier.values()];
};
+ /**
+ * The model for a resolved row's own scope. A private agent's workspace run
+ * can resolve its owner's personal rows (`workspace_id IS NULL`), which this
+ * workspace-scoped model cannot write; follow-up writes on such a row (a
+ * rotated OAuth token, a status change) go through the personal scope.
+ * Every other row is already in this model's scope.
+ */
+ forRow = (
+ row: Pick<UserConnectorItem, 'userId' | 'workspaceId'>,
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
+ ): ConnectorModel => {
+ if (
+ !this.evaluationDatasetId &&
+ normalizeWorkspaceId(this.workspaceId) &&
+ row.workspaceId === null &&
+ row.userId === this.userId
+ ) {
+ return new ConnectorModel(this.db, this.userId, undefined, gateKeeper);
+ }
+ return this;
+ };
+
create = async (
params: CreateConnectorParams,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
@@ -366,8 +480,9 @@ export class ConnectorModel {
};
/**
- * Base (non-agent) rows for the given identifiers. Excludes agent-scoped rows;
- * use {@link resolveByIdentifiers} for agent-aware runtime resolution.
+ * Base (non-agent) shared rows for the given identifiers (see
+ * {@link sharedBaseScope}). Excludes agent-scoped rows; use
+ * {@link resolveByIdentifiers} for agent-aware runtime resolution.
*/
queryByIdentifiers = async (
identifiers: string[],
@@ -378,7 +493,7 @@ export class ConnectorModel {
const rows = await this.db
.select()
.from(userConnectors)
- .where(and(this.baseScope(), inArray(userConnectors.identifier, identifiers)))
+ .where(and(this.sharedBaseScope(), inArray(userConnectors.identifier, identifiers)))
.orderBy(...this.resolutionOrder());
return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));
@@ -386,9 +501,14 @@ export class ConnectorModel {
/**
* Agent-aware runtime resolution. For each identifier returns at most one
- * connector, preferring the agent-owned row (`agent_id = agentId`) over the
- * base row (Agent > Workspace/Personal). When `agentId` is omitted this is
- * equivalent to {@link queryByIdentifiers} (base rows only).
+ * connector, ranked by {@link pickByPriority} (agent-owned > mounted > free
+ * base, then the owner's private > personal > shared). Without an `agentId`
+ * this resolves the free base rows only.
+ *
+ * `runTarget` decides the base rows (see {@link connectorRunScope}): pass
+ * the run's `topicId` so a private agent can load its owner's private
+ * connectors; any other caller, an agent id alone included, resolves the
+ * workspace's shared ones.
*
* This is the single entry point runtime paths (aiAgent manifest build,
* connector exec, MCP call gate, Composio account resolution) must use in
@@ -397,37 +517,74 @@ export class ConnectorModel {
*/
resolveByIdentifiers = async (
identifiers: string[],
- agentId?: string,
+ runTarget: ConnectorRunTargetInput = {},
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<DecryptedConnector[]> => {
if (identifiers.length === 0) return [];
+ const target = toRunTarget(runTarget);
const rows = await this.db
.select()
.from(userConnectors)
- .where(and(this.scopePredicate(agentId), inArray(userConnectors.identifier, identifiers)))
+ .where(and(this.scopePredicate(target), inArray(userConnectors.identifier, identifiers)))
.orderBy(...this.resolutionOrder());
- return Promise.all(this.pickByPriority(rows, agentId).map((r) => decryptRow(r, gateKeeper)));
+ return pMap(this.pickByPriority(rows, target.agentId), (r) => decryptRow(r, gateKeeper), {
+ concurrency: 5,
+ });
};
/**
- * Agent-aware variant of {@link query}: every resolvable connector in the
- * current scope, deduped by identifier with the agent-owned row winning. Used
- * to enumerate connectors for a run (e.g. Composio manifest building) where
- * the agent's own connector should shadow the base one.
+ * Agent-aware variant of {@link query}: every connector the run may resolve,
+ * deduped by identifier with {@link pickByPriority}. Used to enumerate
+ * connectors for a run (e.g. Composio manifest building) where the agent's
+ * own connector should shadow the base one.
*/
resolveAll = async (
- agentId?: string,
+ runTarget: ConnectorRunTargetInput = {},
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<DecryptedConnector[]> => {
+ const target = toRunTarget(runTarget);
+ const rows = await this.db
+ .select()
+ .from(userConnectors)
+ .where(this.scopePredicate(target))
+ .orderBy(...this.resolutionOrder());
+
+ return pMap(this.pickByPriority(rows, target.agentId), (r) => decryptRow(r, gateKeeper), {
+ concurrency: 5,
+ });
+ };
+
+ /**
+ * The connectors an agent's configuration may name, one per identifier,
+ * ranked as {@link resolveAll} ranks them in the agent's own conversation —
+ * without credentials. It needs no topic (see {@link connectorAgentConfigScope}):
+ * pinning a plugin id on an agent checks what the agent can load, so an owner
+ * can enable their private connector on their private agent. Use it to
+ * validate a configuration, never to run a tool.
+ */
+ queryAvailableForAgent = async (
+ agentId?: string,
+ ): Promise<Pick<UserConnectorItem, 'identifier' | 'isEnabled' | 'status'>[]> => {
+ const base = this.evaluationDatasetId
+ ? this.ownership()
+ : connectorAgentConfigScope(
+ this.db,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentId,
+ );
const rows = await this.db
.select()
.from(userConnectors)
- .where(this.scopePredicate(agentId))
+ .where(this.agentNarrowing(base, agentId))
.orderBy(...this.resolutionOrder());
- return Promise.all(this.pickByPriority(rows, agentId).map((r) => decryptRow(r, gateKeeper)));
+ return this.pickByPriority(rows, agentId).map(({ identifier, isEnabled, status }) => ({
+ identifier,
+ isEnabled,
+ status,
+ }));
};
/**
@@ -437,12 +594,23 @@ export class ConnectorModel {
* {@link resolveByIdentifiers} it does NOT fall back across scopes, so
* creating an agent connector never updates the personal/workspace row and
* vice versa.
+ *
+ * In a workspace a base row is looked up within one visibility: the shared
+ * row (default), or the caller's own private row. Adding a private
+ * connector therefore never rewrites the shared one of the same identifier.
*/
findScopedByIdentifier = async (
identifier: string,
agentId?: string,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
+ visibility: ConnectorVisibility = 'public',
): Promise<DecryptedConnector | null> => {
+ const sameVisibility =
+ !agentId && normalizeWorkspaceId(this.workspaceId)
+ ? visibility === 'private'
+ ? and(eq(userConnectors.visibility, 'private'), eq(userConnectors.userId, this.userId))
+ : eq(userConnectors.visibility, 'public')
+ : undefined;
const [row] = await this.db
.select()
.from(userConnectors)
@@ -451,6 +619,7 @@ export class ConnectorModel {
this.ownership(),
eq(userConnectors.identifier, identifier),
agentId ? eq(userConnectors.agentId, agentId) : isNull(userConnectors.agentId),
+ sameVisibility,
),
)
.limit(1);
@@ -459,6 +628,206 @@ export class ConnectorModel {
return decryptRow(row, gateKeeper);
};
+ /**
+ * The row a connector write should update for this identifier: the caller's
+ * binding in ANY visibility. {@link findScopedByIdentifier} pins the lookup to
+ * one visibility so a create never rewrites the sibling row; a refresh already
+ * owns a row and must find it either way, otherwise switching a connector to
+ * private makes the next refresh miss it and create a second, public row for
+ * the same account — republishing it to the workspace.
+ *
+ * A write for a known Composio account (a refresh, a removal) targets the
+ * row holding that account: the caller may keep a private row and see a
+ * shared one of the same identifier, and the account names which of the two
+ * the write is about. An account no row holds is a legacy connection, which
+ * lives in the workspace-wide plugin projection: it belongs to the shared
+ * scope, so the write targets the shared row (or creates one) under the
+ * shared connector policy, and never adopts the account into the caller's
+ * private row, where it would vanish from every other member. A new
+ * connection (no account yet) prefers the caller's own private row over the
+ * shared one, matching {@link pickByPriority}.
+ */
+ findManageableByIdentifier = async (
+ identifier: string,
+ agentId?: string,
+ composioAccountId?: string,
+ ): Promise<{
+ agentId: string | null;
+ id: string;
+ metadata: UserConnectorItem['metadata'];
+ userId: string;
+ visibility: ConnectorVisibility;
+ } | null> => {
+ const rows = await this.db
+ .select({
+ agentId: userConnectors.agentId,
+ id: userConnectors.id,
+ metadata: userConnectors.metadata,
+ userId: userConnectors.userId,
+ visibility: userConnectors.visibility,
+ })
+ .from(userConnectors)
+ .where(
+ and(
+ this.ownership(),
+ eq(userConnectors.identifier, identifier),
+ agentId ? eq(userConnectors.agentId, agentId) : isNull(userConnectors.agentId),
+ ),
+ )
+ .orderBy(asc(userConnectors.id));
+
+ if (rows.length === 0) return null;
+ if (composioAccountId) {
+ const holdsAccount = rows.find(
+ (row) => row.metadata?.composio?.connectedAccountId === composioAccountId,
+ );
+ return holdsAccount ?? rows.find((row) => row.visibility !== 'private') ?? null;
+ }
+ return rows.find((row) => row.visibility === 'private') ?? rows[0];
+ };
+
+ /**
+ * Every Composio connector row in scope that names this account: in a
+ * workspace any member's row, in any visibility and under any identifier,
+ * bound to an agent or not; outside a workspace the caller's personal rows.
+ *
+ * A write naming an account is judged on these rows, never on the identifier
+ * it also names. Every member reads the account ids of the workspace-wide
+ * plugin projection, so the identifier is theirs to choose, and a lookup
+ * keyed by it misses the row that actually runs the account. An account id
+ * in a row is no proof of ownership either: a connector's metadata is
+ * client-written, so a member can name a teammate's account in a row of
+ * their own.
+ */
+ queryComposioAccountHolders = async (
+ composioAccountId: string,
+ ): Promise<
+ {
+ agentId: string | null;
+ id: string;
+ identifier: string;
+ userId: string;
+ visibility: ConnectorVisibility;
+ }[]
+ > => {
+ const workspaceId = normalizeWorkspaceId(this.workspaceId);
+
+ return this.db
+ .select({
+ agentId: userConnectors.agentId,
+ id: userConnectors.id,
+ identifier: userConnectors.identifier,
+ userId: userConnectors.userId,
+ visibility: userConnectors.visibility,
+ })
+ .from(userConnectors)
+ .where(
+ and(
+ workspaceId
+ ? eq(userConnectors.workspaceId, workspaceId)
+ : and(eq(userConnectors.userId, this.userId), isNull(userConnectors.workspaceId)),
+ sql`${userConnectors.metadata} -> 'composio' ->> 'connectedAccountId' = ${composioAccountId}`,
+ ),
+ )
+ .orderBy(asc(userConnectors.id));
+ };
+
+ /**
+ * Whether a teammate's private connector in this workspace holds this
+ * Composio account, under any identifier (see
+ * {@link queryComposioAccountHolders}). The legacy plugin projection is
+ * workspace-wide, so every member can still read a privatized connection's
+ * account id from it; a write naming that account must not reach the
+ * account through a row the caller can see instead (deleting the remote
+ * account, or copying it onto a shared row). Always false outside a
+ * workspace, where nothing is private.
+ */
+ isComposioAccountPrivateToTeammate = async (composioAccountId: string): Promise<boolean> => {
+ if (!normalizeWorkspaceId(this.workspaceId)) return false;
+
+ const holders = await this.queryComposioAccountHolders(composioAccountId);
+ return holders.some((row) => row.visibility === 'private' && row.userId !== this.userId);
+ };
+
+ /**
+ * The plugin-projection accounts that are still legacy connections: no
+ * Composio connector row anywhere in this workspace (or, outside a
+ * workspace, in the caller's personal scope) is the connector they mirror.
+ *
+ * Runtime resolution deliberately narrows to what the run may see, so a
+ * connection can resolve to nothing while its connector row still exists —
+ * a private connector read by someone else, another agent's row. The
+ * projection is a mirror of that row, and serving it would resurrect the
+ * very connection the run is not allowed to use. A mirror belongs to a
+ * Composio row, in any visibility, that:
+ *
+ * - runs the same account as the same Composio entity
+ * (`linkedByUserId`, else the row creator — what the runtime passes to
+ * Composio), under any identifier and whatever agent it is bound to; or
+ * - is a base row of the mirror's identifier created or linked by the
+ * mirror's entity: that user connected this app again, so the account
+ * still in the projection is the connection's past (a reconnect not
+ * finished yet), not a legacy connection to hand to the workspace.
+ *
+ * Both tests rest on server-owned attribution. The identifier, and an
+ * account id alone, prove nothing: any member can add a private connector
+ * of a supported identifier without passing the shared connector policy,
+ * and write any account id into its metadata (every member reads the
+ * projection's account ids), and that row must not take a teammate's
+ * legacy connection away from the rest of the workspace. Nor can the
+ * projection's own identifier be trusted: a member can file a projection
+ * row under any app, copying a teammate's account and entity, and the
+ * runtime hands Composio only those two — so the account test spans every
+ * identifier, or a privatized connection filed under another app would
+ * pass as legacy.
+ */
+ pickLegacyComposioMirrors = async <T extends ComposioPluginMirror>(
+ mirrors: T[],
+ ): Promise<T[]> => {
+ if (mirrors.length === 0) return [];
+
+ const workspaceId = normalizeWorkspaceId(this.workspaceId);
+ // In a workspace the whole workspace counts, including rows other members
+ // keep private: the projection is workspace-wide.
+ const scope = workspaceId
+ ? eq(userConnectors.workspaceId, workspaceId)
+ : and(eq(userConnectors.userId, this.userId), isNull(userConnectors.workspaceId));
+
+ const accountId = sql<
+ string | null
+ >`${userConnectors.metadata} -> 'composio' ->> 'connectedAccountId'`;
+ const rows = await this.db
+ .select({
+ agentId: userConnectors.agentId,
+ connectedAccountId: accountId,
+ identifier: userConnectors.identifier,
+ linkedByUserId: sql<
+ string | null
+ >`${userConnectors.metadata} -> 'composio' ->> 'linkedByUserId'`,
+ userId: userConnectors.userId,
+ })
+ .from(userConnectors)
+ .where(
+ and(
+ scope,
+ or(
+ inArray(userConnectors.identifier, [...new Set(mirrors.map((m) => m.identifier))]),
+ inArray(accountId, [...new Set(mirrors.map((m) => m.connectedAccountId))]),
+ ),
+ sql`COALESCE(${accountId}, '') <> ''`,
+ ),
+ );
+
+ const isMirrorOf = (mirror: ComposioPluginMirror, row: (typeof rows)[number]) =>
+ (row.connectedAccountId === mirror.connectedAccountId &&
+ (row.linkedByUserId ?? row.userId) === mirror.ownerUserId) ||
+ (row.identifier === mirror.identifier &&
+ !row.agentId &&
+ (row.userId === mirror.ownerUserId || row.linkedByUserId === mirror.ownerUserId));
+
+ return mirrors.filter((mirror) => !rows.some((row) => isMirrorOf(mirror, row)));
+ };
+
queryReferencesByIdentifiers = async (identifiers: string[]): Promise<ConnectorReference[]> => {
if (identifiers.length === 0) return [];
@@ -469,7 +838,7 @@ export class ConnectorModel {
status: userConnectors.status,
})
.from(userConnectors)
- .where(and(this.baseScope(), inArray(userConnectors.identifier, identifiers)));
+ .where(and(this.sharedBaseScope(), inArray(userConnectors.identifier, identifiers)));
};
queryComposioReferencesByIdentifiers = async (
@@ -486,7 +855,7 @@ export class ConnectorModel {
userId: userConnectors.userId,
})
.from(userConnectors)
- .where(and(this.baseScope(), inArray(userConnectors.identifier, identifiers)));
+ .where(and(this.sharedBaseScope(), inArray(userConnectors.identifier, identifiers)));
return rows.map(toComposioConnectorReference);
};
diff --git a/packages/database/src/models/connectorScope.ts b/packages/database/src/models/connectorScope.ts
index 6f46f7b68e9..0bcfd275aaa 100644
--- a/packages/database/src/models/connectorScope.ts
+++ b/packages/database/src/models/connectorScope.ts
@@ -1,10 +1,19 @@
-import { and, eq, exists, sql } from 'drizzle-orm';
+import { RequestTrigger } from '@lobechat/types';
+import { and, eq, exists, isNull, ne, notExists, notInArray, or, sql } from 'drizzle-orm';
-import { agentEvalDatasets, userConnectors } from '../schemas';
+import { agentEvalDatasets, agents, topics, topicShares, userConnectors } from '../schemas';
import type { LobeChatDatabase } from '../type';
-import { buildWorkspaceWhere } from '../utils/workspace';
+import { CHANNEL_TOPIC_TRIGGER } from '../utils/topicVisibility';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../utils/workspace';
-/** Shared by connection rows and their tool rows; default access is ordinary-only. */
+/**
+ * Shared by connection rows and their tool rows; default access is ordinary-only.
+ *
+ * Visibility-aware in a workspace (`buildWorkspaceWhere` reads
+ * `user_connectors.visibility`): every member sees the shared rows, and only
+ * the creator sees a private one. This is the management view; runtime
+ * resolution uses {@link connectorRunScope}.
+ */
export const connectorAccessScope = (
db: LobeChatDatabase,
scope: { userId: string; workspaceId?: string },
@@ -27,5 +36,161 @@ export const connectorAccessScope = (
),
),
)
- : sql`COALESCE(${userConnectors.metadata} ->> 'agentEval', '') = ''`,
+ : ordinaryConnection(),
);
+
+const ordinaryConnection = () => sql`COALESCE(${userConnectors.metadata} ->> 'agentEval', '') = ''`;
+
+/**
+ * What a runtime resolution runs as: the agent whose tools are being built and
+ * the topic its results are written into.
+ */
+export interface ConnectorRunTarget {
+ agentId?: string;
+ /**
+ * The conversation the run writes into. A private agent loads its owner's
+ * private connectors only when this is the agent's own direct topic; without
+ * it the run resolves the workspace's shared connectors only.
+ */
+ topicId?: string;
+}
+
+/**
+ * Topic triggers whose transcript is read by people other than the run's
+ * user: a Channel run publishes its reply to the channel, a bot run posts into
+ * an IM chat, and a share run is read by the share visitor.
+ */
+const NON_PRIVATE_TOPIC_TRIGGERS: string[] = [
+ CHANNEL_TOPIC_TRIGGER,
+ RequestTrigger.AgentShare,
+ RequestTrigger.Bot,
+];
+
+const personalRows = (userId: string) =>
+ and(eq(userConnectors.userId, userId), isNull(userConnectors.workspaceId), ordinaryConnection());
+
+const sharedRows = (workspaceId: string) =>
+ and(eq(userConnectors.workspaceId, workspaceId), eq(userConnectors.visibility, 'public'));
+
+/**
+ * The caller's private rows in this workspace and their personal rows, when
+ * `agentId` is the caller's own private agent in this workspace. Checked in SQL
+ * (an uncorrelated EXISTS, evaluated once per query), so a caller cannot widen
+ * the scope by naming an agent it does not own.
+ */
+const ownersPrivateRows = (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string,
+ agentId: string,
+) =>
+ and(
+ eq(userConnectors.userId, userId),
+ or(
+ and(eq(userConnectors.workspaceId, workspaceId), eq(userConnectors.visibility, 'private')),
+ isNull(userConnectors.workspaceId),
+ ),
+ exists(
+ db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, agentId),
+ eq(agents.workspaceId, workspaceId),
+ eq(agents.userId, userId),
+ eq(agents.visibility, 'private'),
+ ),
+ ),
+ ),
+ );
+
+/**
+ * Base connector rows (before the agent-owned / mount narrowing) a run may
+ * resolve. Tool visibility follows the agent, never whoever is speaking:
+ *
+ * - Personal run: the user's personal rows.
+ * - Workspace run, any agent: the workspace's shared (`public`) rows.
+ * - Workspace run of a PRIVATE agent, by its owner, inside the agent's own
+ * direct topic: also the owner's private rows in this workspace and the
+ * owner's personal rows (`workspace_id IS NULL`).
+ *
+ * "Own direct topic" means the topic belongs to this agent and this user, is
+ * not a group topic, is not a channel / bot / share transcript, and has no
+ * share link (`topic_shares.visibility` other than the owner-only `private`:
+ * a link visitor reads the live transcript, later tool results included). A private
+ * agent can still be pulled into conversations other members read (a group
+ * supervisor dispatch, `callAgent` from a shared agent, a topic of another
+ * agent); there the topic proof fails and the private rows stay out, so a
+ * private connector's results never land in a shared conversation. Without a
+ * `topicId` the run gets the shared rows only.
+ *
+ * Every check is in SQL (uncorrelated subqueries, evaluated once per query), so
+ * a caller cannot widen the scope by passing an agent or topic it does not own.
+ */
+export const connectorRunScope = (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string },
+ target: ConnectorRunTarget,
+) => {
+ const workspaceId = normalizeWorkspaceId(scope.workspaceId);
+ if (!workspaceId) return personalRows(scope.userId);
+
+ const { agentId, topicId } = target;
+ if (!agentId || !topicId) return and(sharedRows(workspaceId), ordinaryConnection());
+
+ const ownDirectTopic = db
+ .select({ id: topics.id })
+ .from(topics)
+ .where(
+ and(
+ eq(topics.id, topicId),
+ eq(topics.agentId, agentId),
+ eq(topics.userId, scope.userId),
+ eq(topics.workspaceId, workspaceId),
+ isNull(topics.groupId),
+ isNull(topics.senderId),
+ or(isNull(topics.trigger), notInArray(topics.trigger, NON_PRIVATE_TOPIC_TRIGGERS)),
+ ),
+ );
+
+ const linkShare = db
+ .select({ id: topicShares.id })
+ .from(topicShares)
+ .where(and(eq(topicShares.topicId, topicId), ne(topicShares.visibility, 'private')));
+
+ return and(
+ or(
+ sharedRows(workspaceId),
+ and(
+ ownersPrivateRows(db, scope.userId, workspaceId, agentId),
+ exists(ownDirectTopic),
+ notExists(linkShare),
+ ),
+ ),
+ ordinaryConnection(),
+ );
+};
+
+/**
+ * Base connector rows an agent's CONFIGURATION may name: what the agent loads
+ * in its own direct topic (see {@link connectorRunScope}), so an owner can pin
+ * their private connector on their private agent. Nothing runs and no result is
+ * written under this scope, which is why it needs no topic proof; a run still
+ * resolves through {@link connectorRunScope}, and in a group, channel or another
+ * agent's topic the private rows stay out.
+ */
+export const connectorAgentConfigScope = (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string },
+ agentId?: string,
+) => {
+ const workspaceId = normalizeWorkspaceId(scope.workspaceId);
+ if (!workspaceId) return personalRows(scope.userId);
+ if (!agentId) return and(sharedRows(workspaceId), ordinaryConnection());
+
+ return and(
+ or(sharedRows(workspaceId), ownersPrivateRows(db, scope.userId, workspaceId, agentId)),
+ ordinaryConnection(),
+ );
+};
diff --git a/packages/database/src/models/connectorTool.ts b/packages/database/src/models/connectorTool.ts
index eb3c24d9c64..adfe4425296 100644
--- a/packages/database/src/models/connectorTool.ts
+++ b/packages/database/src/models/connectorTool.ts
@@ -1,4 +1,4 @@
-import { and, asc, eq, exists, inArray, ne, notInArray, sql } from 'drizzle-orm';
+import { and, asc, eq, exists, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';
import type {
ConnectorToolPermission,
@@ -12,7 +12,11 @@ import {
userConnectorTools,
} from '../schemas';
import type { LobeChatDatabase } from '../type';
-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+import {
+ buildWorkspacePayload,
+ buildWorkspaceWhere,
+ normalizeWorkspaceId,
+} from '../utils/workspace';
import { connectorAccessScope } from './connectorScope';
export interface SyncToolInput {
@@ -29,11 +33,23 @@ export interface SyncToolInput {
toolName: string;
}
+export interface ConnectorToolModelOptions {
+ /**
+ * For agent runs and their tool calls. Besides the scoped rows, by-connector
+ * reads also reach the tools of the caller's own personal connectors: a
+ * private agent's workspace run resolves its owner's personal connectors
+ * (`ConnectorModel.resolveByIdentifiers`), and their tool rows live in the
+ * personal scope. Management reads and every write keep the strict scope.
+ */
+ agentRun?: boolean;
+}
+
export class ConnectorToolModel {
private userId: string;
private db: LobeChatDatabase;
private workspaceId?: string;
private evaluationDatasetId?: string;
+ private readsOwnPersonalTools: boolean;
static forEvaluation(
db: LobeChatDatabase,
@@ -47,10 +63,16 @@ export class ConnectorToolModel {
return model;
}
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ options: ConnectorToolModelOptions = {},
+ ) {
this.db = db;
this.userId = userId;
this.workspaceId = workspaceId;
+ this.readsOwnPersonalTools = !!options.agentRun;
}
private ownership = () =>
@@ -76,6 +98,39 @@ export class ConnectorToolModel {
),
);
+ /**
+ * Scope for by-connector reads. A run model (`agentRun`) in a workspace
+ * also reads the tools of the caller's own personal connectors; reading
+ * one's own personal tool list grants nothing the personal scope does not.
+ */
+ private resolvedReadScope = () => {
+ if (
+ !this.readsOwnPersonalTools ||
+ this.evaluationDatasetId ||
+ !normalizeWorkspaceId(this.workspaceId)
+ ) {
+ return this.ownership();
+ }
+ return or(
+ this.ownership(),
+ and(
+ eq(userConnectorTools.userId, this.userId),
+ isNull(userConnectorTools.workspaceId),
+ exists(
+ this.db
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(
+ and(
+ eq(userConnectors.id, userConnectorTools.userConnectorId),
+ connectorAccessScope(this.db, { userId: this.userId }),
+ ),
+ ),
+ ),
+ ),
+ );
+ };
+
/**
* Deterministic tool order: grouped by connector, sorted by toolName within it.
* Tool lists feed the model's tool schema array, so they must not follow the
@@ -188,7 +243,7 @@ export class ConnectorToolModel {
return this.db
.select()
.from(userConnectorTools)
- .where(and(eq(userConnectorTools.userConnectorId, userConnectorId), this.ownership()))
+ .where(and(eq(userConnectorTools.userConnectorId, userConnectorId), this.resolvedReadScope()))
.orderBy(...this.toolOrder());
};
@@ -204,7 +259,7 @@ export class ConnectorToolModel {
.from(userConnectorTools)
.where(
and(
- this.ownership(),
+ this.resolvedReadScope(),
inArray(userConnectorTools.userConnectorId, connectorIds),
ne(userConnectorTools.permission, Permission.disabled),
),
@@ -222,7 +277,9 @@ export class ConnectorToolModel {
return this.db
.select()
.from(userConnectorTools)
- .where(and(this.ownership(), inArray(userConnectorTools.userConnectorId, connectorIds)))
+ .where(
+ and(this.resolvedReadScope(), inArray(userConnectorTools.userConnectorId, connectorIds)),
+ )
.orderBy(...this.toolOrder());
};
diff --git a/packages/database/src/models/plugin.ts b/packages/database/src/models/plugin.ts
index 2352f5e7b63..e087e2c788c 100644
--- a/packages/database/src/models/plugin.ts
+++ b/packages/database/src/models/plugin.ts
@@ -1,5 +1,5 @@
import type { LobeTool } from '@lobechat/types';
-import { and, desc, eq, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, sql } from 'drizzle-orm';
import type { InstalledPluginItem, NewInstalledPlugin } from '../schemas';
import { userInstalledPlugins } from '../schemas';
@@ -67,6 +67,25 @@ export class PluginModel {
.where(and(eq(userInstalledPlugins.identifier, id), this.visible()));
};
+ /**
+ * Remove the projection rows that mirror one Composio account, leaving the
+ * app's other projection rows. In a workspace every member's projection row
+ * is in scope, and a private connection is one member's: deleting by
+ * identifier ({@link delete}) would also drop a teammate's legacy
+ * connection of the same app.
+ */
+ deleteComposioMirrors = async (identifier: string, connectedAccountId: string) => {
+ return this.db
+ .delete(userInstalledPlugins)
+ .where(
+ and(
+ eq(userInstalledPlugins.identifier, identifier),
+ this.visible(),
+ sql`${userInstalledPlugins.customParams} -> 'composio' ->> 'connectedAccountId' = ${connectedAccountId}`,
+ ),
+ );
+ };
+
deleteAll = async () => {
return this.db.delete(userInstalledPlugins).where(this.ownership());
};
@@ -93,6 +112,32 @@ export class PluginModel {
}));
};
+ /**
+ * The Composio projection rows in scope, newest first, with the user who
+ * wrote each. A workspace keeps one projection row per member for the same
+ * app, so a lookup by identifier ({@link findById}) picks an arbitrary one.
+ */
+ queryComposioMirrors = async (identifiers?: string[]) => {
+ if (identifiers?.length === 0) return [];
+
+ return this.db
+ .select({
+ customParams: userInstalledPlugins.customParams,
+ identifier: userInstalledPlugins.identifier,
+ manifest: userInstalledPlugins.manifest,
+ userId: userInstalledPlugins.userId,
+ })
+ .from(userInstalledPlugins)
+ .where(
+ and(
+ this.visible(),
+ sql`COALESCE(jsonb_exists(${userInstalledPlugins.customParams}, 'composio'), false)`,
+ identifiers ? inArray(userInstalledPlugins.identifier, identifiers) : undefined,
+ ),
+ )
+ .orderBy(desc(userInstalledPlugins.createdAt), userInstalledPlugins.userId);
+ };
+
findById = async (id: string) => {
return this.db.query.userInstalledPlugins.findFirst({
where: and(eq(userInstalledPlugins.identifier, id), this.visible()),
diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.ts
index 0ddb7cffc8f..c9bbb088f0b 100644
--- a/packages/database/src/schemas/connector.ts
+++ b/packages/database/src/schemas/connector.ts
@@ -1,4 +1,4 @@
-import type { CustomPluginParams, ToolManifest } from '@lobechat/types';
+import type { ConnectorVisibility, CustomPluginParams, ToolManifest } from '@lobechat/types';
import { sql } from 'drizzle-orm';
import {
boolean,
@@ -240,6 +240,18 @@ export const userConnectors = pgTable(
/** Safe non-sensitive metadata for display and future extensibility */
metadata: jsonb('metadata').$type<ConnectorMetadata>(),
+ /**
+ * Visibility WITHIN a workspace (same contract as devices / agents, filtered
+ * by `buildWorkspaceWhere`):
+ * - 'public' → shared with the workspace; every member sees it and every
+ * agent in the workspace may load it.
+ * - 'private' → the creator's own; only `user_id` sees it, and only that
+ * member's private agents load it.
+ * Defaults to 'public' so rows that predate the column keep their shared
+ * behaviour. Ignored for personal rows (`workspace_id IS NULL`).
+ */
+ visibility: text('visibility').$type<ConnectorVisibility>().default('public').notNull(),
+
...timestamps,
},
(t) => [
diff --git a/packages/types/src/apiKey.ts b/packages/types/src/apiKey.ts
index 75cb9eab54d..d5bdd4d2f73 100644
--- a/packages/types/src/apiKey.ts
+++ b/packages/types/src/apiKey.ts
@@ -45,3 +45,16 @@ export type WorkspaceApiKeyMemberCreation = 'admins_only' | 'all_members';
* member's stored credentials stays with that creator and the workspace owner.
*/
export type WorkspaceConnectorMemberManage = 'admins_only' | 'all_members';
+
+/**
+ * Who may see and use a workspace connector (`user_connectors.visibility`),
+ * mirroring devices / agents:
+ * - `public` — shared with the workspace: every member sees it and every agent
+ * in the workspace may load it.
+ * - `private` — the creator's own (私人): only the creator sees it, and only the
+ * creator's private agents load it.
+ * Ignored for personal connectors (`workspace_id IS NULL`), which are
+ * implicitly private to their owner.
+ */
+export const CONNECTOR_VISIBILITIES = ['private', 'public'] as const;
+export type ConnectorVisibility = (typeof CONNECTOR_VISIBILITIES)[number];