Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
507c9dce5c | ||
|
|
da9672c3e5 | ||
|
|
c0777fb596 | ||
|
|
8d5c76ebd6 | ||
|
|
9fb91d2db6 | ||
|
|
48cc14407c | ||
|
|
c072e9c0bc | ||
|
|
e01114ce63 | ||
|
|
d9ac0daf45 | ||
|
|
99622e620d | ||
|
|
54ba0e845d | ||
|
|
1da980e243 |
+224
@@ -4032,6 +4032,230 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "connector_routers",
|
||||
tableDescription: `A router on one connection: a named set of that connection's apps that a run reaches through a few search, schema and execute tools rather than every app tool, so adding apps doesn't fill a bot's context. Given like an app: every bot (all_bots), a workspace (workspace_connector_routers) or a bot for one user (bot_connector_routers). Super admins make and edit them`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "connection_id",
|
||||
fieldDescription: `The connector_connections row whose apps it picks from`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connector_connections",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "connector_routers_connections_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "name",
|
||||
fieldDescription: `Shown, e.g. Work apps`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "slug",
|
||||
fieldDescription: `Unique across the install, for logs and the run's note`,
|
||||
dataType: "TEXT",
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
fieldName: "description",
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "all_bots",
|
||||
fieldDescription: `0 or 1: every bot, every user, each with the accounts their run reaches`,
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
fieldName: "enabled",
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 1,
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `Who made it. Never reach`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "connector_router_apps",
|
||||
tableDescription: `The apps one router reaches. Only apps of the router's own connection`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "router_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connector_routers",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "connector_router_apps_routers_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "connector_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connectors",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "connector_router_apps_connectors_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "all_accounts",
|
||||
fieldDescription: `1: every account a run reaches for the app, as for an app given directly. 0: only the accounts picked in connector_router_accounts, which reach every run the router reaches`,
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 1,
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_app_per_router",
|
||||
constraintName: "A router lists an app once",
|
||||
constraintTableFields: [{ value: "router_id" }, { value: "connector_id" }],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_connector_router_apps_connector_id",
|
||||
indexTableFields: ["connector_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_connector_routers",
|
||||
tableDescription: `One user's own attachment of a router to a bot: it reaches that user's runs on that bot and nobody else's`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bots",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_connector_routers_bots_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `Whose attachment it is, and the only user whose runs get it. Not a foreign key: deleting a user deletes these explicitly`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "router_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connector_routers",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_connector_routers_routers_fk",
|
||||
},
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_router_attachment_per_bot_user",
|
||||
constraintName: "A user attaches a router to a bot once",
|
||||
constraintTableFields: [{ value: "bot_id" }, { value: "user_id" }, { value: "router_id" }],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_connector_routers_router_id",
|
||||
indexTableFields: ["router_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "connector_router_accounts",
|
||||
tableDescription: `The accounts a router uses for an app whose connector_router_apps.all_accounts is 0. Each reaches every run the router reaches, acting as its owner`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "router_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connector_routers",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "connector_router_accounts_routers_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "account_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connector_accounts",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "connector_router_accounts_accounts_fk",
|
||||
},
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_account_per_router",
|
||||
constraintName: "A router lists an account once",
|
||||
constraintTableFields: [{ value: "router_id" }, { value: "account_id" }],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_connector_router_accounts_account_id",
|
||||
indexTableFields: ["account_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "workspace_connector_routers",
|
||||
tableDescription: `Every run in the workspace reaches the router, with every connected account of its apps, as a workspace's app does. Super admins only`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "workspaces",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_connector_routers_workspaces_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "router_id",
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "connector_routers",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_connector_routers_routers_fk",
|
||||
},
|
||||
},
|
||||
],
|
||||
uniqueConstraints: [
|
||||
{
|
||||
alias: "one_router_per_workspace",
|
||||
constraintName: "A workspace gets a router once",
|
||||
constraintTableFields: [{ value: "workspace_id" }, { value: "router_id" }],
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_workspace_connector_routers_router_id",
|
||||
indexTableFields: ["router_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "connector_accounts",
|
||||
tableDescription: `One user's sign-in to a connector, as the provider keeps it: their work Gmail and their personal one are two rows. A run only ever acts through its own user's accounts, and the value never reaches the model`,
|
||||
|
||||
+119
-1
@@ -60,6 +60,11 @@ export const BunSQLiteTables = [
|
||||
"connectors",
|
||||
"bot_connectors",
|
||||
"workspace_connectors",
|
||||
"connector_routers",
|
||||
"connector_router_apps",
|
||||
"bot_connector_routers",
|
||||
"connector_router_accounts",
|
||||
"workspace_connector_routers",
|
||||
"connector_accounts",
|
||||
"connector_account_workspaces",
|
||||
"connector_account_bots",
|
||||
@@ -2525,6 +2530,119 @@ export type BUN_SQLITE_COBBLE_WORKSPACE_CONNECTORS = {
|
||||
connector_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
/**
|
||||
* The connector_connections row whose apps it picks from
|
||||
*/
|
||||
connection_id?: number | "";
|
||||
/**
|
||||
* Shown, e.g. Work apps
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* Unique across the install, for logs and the run's note
|
||||
*/
|
||||
slug?: string;
|
||||
description?: string;
|
||||
/**
|
||||
* 0 or 1: every bot, every user, each with the accounts their run reaches
|
||||
*/
|
||||
all_bots?: number | "";
|
||||
enabled?: number | "";
|
||||
/**
|
||||
* Who made it. Never reach
|
||||
*/
|
||||
user_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_CONNECTOR_ROUTER_APPS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
router_id?: number | "";
|
||||
connector_id?: number | "";
|
||||
/**
|
||||
* 1: every account a run reaches for the app, as for an app given directly. 0: only the accounts picked in connector_router_accounts, which reach every run the router reaches
|
||||
*/
|
||||
all_accounts?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_CONNECTOR_ROUTERS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* Whose attachment it is, and the only user whose runs get it. Not a foreign key: deleting a user deletes these explicitly
|
||||
*/
|
||||
user_id?: number | "";
|
||||
router_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_CONNECTOR_ROUTER_ACCOUNTS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
router_id?: number | "";
|
||||
account_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_WORKSPACE_CONNECTOR_ROUTERS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
workspace_id?: number | "";
|
||||
router_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -3534,4 +3652,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_BOT_ASKS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_BOT_JOB_TRACES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_PLANS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HOST_DIRECTORIES & BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS & BUN_SQLITE_COBBLE_HOST_DIRECTORY_GRANTS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CONNECTOR_CONNECTIONS & BUN_SQLITE_COBBLE_CONNECTORS & BUN_SQLITE_COBBLE_BOT_CONNECTORS & BUN_SQLITE_COBBLE_WORKSPACE_CONNECTORS & BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNT_WORKSPACES & BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNT_BOTS & BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS & BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_BOT_ASKS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_BOT_JOB_TRACES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_PLANS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HOST_DIRECTORIES & BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS & BUN_SQLITE_COBBLE_HOST_DIRECTORY_GRANTS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CONNECTOR_CONNECTIONS & BUN_SQLITE_COBBLE_CONNECTORS & BUN_SQLITE_COBBLE_BOT_CONNECTORS & BUN_SQLITE_COBBLE_WORKSPACE_CONNECTORS & BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS & BUN_SQLITE_COBBLE_CONNECTOR_ROUTER_APPS & BUN_SQLITE_COBBLE_BOT_CONNECTOR_ROUTERS & BUN_SQLITE_COBBLE_CONNECTOR_ROUTER_ACCOUNTS & BUN_SQLITE_COBBLE_WORKSPACE_CONNECTOR_ROUTERS & BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNT_WORKSPACES & BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNT_BOTS & BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS & BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.20",
|
||||
"version": "0.28.23",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -16,6 +16,8 @@ import recordBotHookFailure from "@/src/functions/backend/db/bot-hooks/record-bo
|
||||
import isUnattendedHookSession from "@/src/functions/backend/db/bot-hooks/is-unattended-hook-session";
|
||||
import recordCronJobFailure from "@/src/functions/backend/db/cron-jobs/record-cron-job-failure";
|
||||
import scheduledRunRetryAt from "@/src/utils/scheduled-run-retry-at";
|
||||
import providerRetryAt from "@/src/utils/provider-retry-at";
|
||||
import grabModelRestMs from "@/src/harness/resolve/grab-model-rest-ms";
|
||||
import {
|
||||
BotComputerBusyStatusLine,
|
||||
BotReplyJobTitle,
|
||||
@@ -488,7 +490,10 @@ export default async function processBotJob({
|
||||
}
|
||||
|
||||
/**
|
||||
* A retry no sooner than the provider said to come back.
|
||||
* A retry no sooner than the provider said to come back, but no
|
||||
* later than the model rest: its models are benched no longer
|
||||
* than that, and a quota reset days away would otherwise hold the
|
||||
* job for `AppData.HarnessMaxCooldownMs`.
|
||||
*/
|
||||
if (
|
||||
failed?.status == "pending" &&
|
||||
@@ -496,7 +501,19 @@ export default async function processBotJob({
|
||||
error.retryable &&
|
||||
error.retry_at
|
||||
) {
|
||||
await deferBotJob({ job_id, worker, until: error.retry_at });
|
||||
await deferBotJob({
|
||||
job_id,
|
||||
worker,
|
||||
until: providerRetryAt({ retry_at: error.retry_at, rest_ms: await grabModelRestMs() }),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Waiting for its retry, the bot isn't working: a face left on
|
||||
* `working` read as a run stuck mid-step until the retry came.
|
||||
*/
|
||||
if (failed?.status == "pending") {
|
||||
await setFace({ face: "asleep", status_line: BotWaitingStatusLine }).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
clearInterval(heartbeat);
|
||||
|
||||
@@ -499,12 +499,16 @@ export default async function runBotReply({
|
||||
attended,
|
||||
taken: [...tools, ...extensions.tools, ...browsers.tools].map((tool) => tool.name),
|
||||
onMissingAccount: attended
|
||||
? async ({ connector }) => {
|
||||
? async ({ connector, account }) => {
|
||||
// A lapsed sign-in of the user's own is reconnected in
|
||||
// place, so the card doesn't add a second account beside
|
||||
// the one that stopped working.
|
||||
const request = await createConnectorRequest({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session_id),
|
||||
connector,
|
||||
...(account ? { account_id: account.id, label: account.label } : {}),
|
||||
});
|
||||
const ref = connectRef({ id: request.id });
|
||||
|
||||
@@ -797,7 +801,7 @@ export default async function runBotReply({
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
extensions.note,
|
||||
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "",
|
||||
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines, routers: connectors.routers, direct: connectors.direct }) : "",
|
||||
knowledge_context,
|
||||
`Now: ${new Date().toUTCString()}.`,
|
||||
]
|
||||
|
||||
@@ -786,7 +786,7 @@ export default async function runBotTask({
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
extensions.note,
|
||||
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "",
|
||||
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines, routers: connectors.routers, direct: connectors.direct }) : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
@@ -99,12 +100,18 @@ export default function HookDetailModal({ hook, can_manage = false, onClose, onE
|
||||
{runner?.configured ? (
|
||||
<>
|
||||
<TaskFactRow label="Runner">
|
||||
{runner.running
|
||||
? `Up since ${relativeTime({ at: Number(hook.runner_started_at) || Date.now() })}`
|
||||
: "Down"}
|
||||
{runner.running ? (
|
||||
`Up since ${relativeTime({ at: Number(hook.runner_started_at) || Date.now() })}`
|
||||
) : (
|
||||
<Tag color="error" variant="outlined" className="px-1.5 py-0 text-[11px] font-bold leading-4">
|
||||
Down
|
||||
</Tag>
|
||||
)}
|
||||
</TaskFactRow>
|
||||
{runner.error ? (
|
||||
<TaskFactRow label="Check failed">{runner.error}</TaskFactRow>
|
||||
<TaskFactRow label="Check failed">
|
||||
<Span className="text-error break-words min-w-0">{runner.error}</Span>
|
||||
</TaskFactRow>
|
||||
) : null}
|
||||
<TaskFactRow label="Last checked">
|
||||
{hook.runner_checked_at
|
||||
@@ -136,7 +143,11 @@ export default function HookDetailModal({ hook, can_manage = false, onClose, onE
|
||||
<TaskFactRow label="Last called">
|
||||
{hook.last_called_at ? relativeTime({ at: Number(hook.last_called_at) }) : "Never"}
|
||||
</TaskFactRow>
|
||||
{hook.last_error ? <TaskFactRow label="Last error">{hook.last_error}</TaskFactRow> : null}
|
||||
{hook.last_error ? (
|
||||
<TaskFactRow label="Last error">
|
||||
<Span className="text-error break-words min-w-0">{hook.last_error}</Span>
|
||||
</TaskFactRow>
|
||||
) : null}
|
||||
</Stack>
|
||||
{hook.instructions ? <HookCallAnswer label="Brief" text={hook.instructions} boxed /> : null}
|
||||
{status ? <SettingsStatus status={status} /> : null}
|
||||
|
||||
@@ -289,7 +289,7 @@ export default function HookForm({
|
||||
autoComplete="off"
|
||||
placeholder="whatsapp"
|
||||
defaultValue={hook?.runner_dir || ""}
|
||||
info={`Where it starts, relative to the bot's folder (/home/cb-<bot>/workspace), not to a run's ~: "whatsapp" is /home/cb-<bot>/workspace/whatsapp, while a folder a bot made at ~/whatsapp is "users/<user>/whatsapp". Empty starts in the bot's folder itself.`}
|
||||
info={`Where it starts, relative: "whatsapp" is looked for in your own folder in the bot's (/home/cb-<bot>/workspace/users/<you>, a run's ~) first, then in the bot's folder (/home/cb-<bot>/workspace), and the first one there is used. Empty starts in the bot's folder itself.`}
|
||||
onChange={(e) => setRunnerDir(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
|
||||
@@ -59,6 +59,7 @@ export default function HookRow({ hook, busy, onOpen, onToggle, onEdit, onCalls,
|
||||
title={title}
|
||||
onOpen={onOpen}
|
||||
badge={badge}
|
||||
badge_tone={badge == "Runner down" ? "error" : undefined}
|
||||
subtitle={hookSubtitle({ hook, show_bot: !compact, show_workspace: !compact })}
|
||||
>
|
||||
<SettingsRowMenu title={`${title} menu`} disabled={busy}>
|
||||
|
||||
@@ -2,11 +2,13 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import syncConnector from "@/src/functions/backend/db/connectors/sync-connector";
|
||||
import syncConnectorAccounts from "@/src/functions/backend/db/connectors/sync-connector-accounts";
|
||||
import syncConnectorConnection from "@/src/functions/backend/db/connectors/sync-connector-connection";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
|
||||
/**
|
||||
* Keeps every connection's app list current, reads the tools of the apps
|
||||
* someone actually gave to a bot or workspace (never all of them: a
|
||||
* provider lists hundreds), and keeps accounts in line with the provider:
|
||||
* someone actually gave to a bot or workspace, directly, through a router
|
||||
* given out, or through an account given out (never all of them: a provider lists hundreds), and
|
||||
* keeps accounts in line with the provider:
|
||||
* the ones a sign-in left waiting, and connected ones an hour later, so an
|
||||
* account deleted at the provider shows as revoked (and offers Reconnect)
|
||||
* without waiting for a run to fail.
|
||||
@@ -32,7 +34,22 @@ export default async function syncConnectors() {
|
||||
WHERE c.enabled = 1
|
||||
AND (c.all_bots = 1
|
||||
OR c.id IN (SELECT connector_id FROM bot_connectors)
|
||||
OR c.id IN (SELECT connector_id FROM workspace_connectors))`,
|
||||
OR c.id IN (SELECT connector_id FROM workspace_connectors)
|
||||
OR c.id IN (
|
||||
SELECT ra.connector_id FROM connector_router_apps ra
|
||||
JOIN connector_routers r ON r.id = ra.router_id AND r.enabled = 1
|
||||
WHERE r.all_bots = 1
|
||||
OR r.id IN (SELECT router_id FROM bot_connector_routers)
|
||||
OR r.id IN (SELECT router_id FROM workspace_connector_routers)
|
||||
)
|
||||
OR c.id IN (
|
||||
SELECT a.connector_id FROM connector_accounts a
|
||||
WHERE a.status = 'connected' AND (
|
||||
a.all_bots = 1
|
||||
OR EXISTS (SELECT 1 FROM connector_account_bots ab WHERE ab.account_id = a.id)
|
||||
OR EXISTS (SELECT 1 FROM connector_account_workspaces aw WHERE aw.account_id = a.id)
|
||||
)
|
||||
))`,
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
@@ -56,9 +73,20 @@ export default async function syncConnectors() {
|
||||
).payload || [];
|
||||
|
||||
for (const request of waiting) {
|
||||
// One user's refused listing mustn't stop the others, but it is
|
||||
// logged: a sync that fails quietly every 15 minutes is how an
|
||||
// expired account stays "connected" for weeks.
|
||||
await syncConnectorAccounts({
|
||||
user_id: request.user_id,
|
||||
connector_id: request.connector_id,
|
||||
}).catch(() => {});
|
||||
}).catch((error: unknown) =>
|
||||
logError({
|
||||
title: "Connector account sync failed",
|
||||
category: "system",
|
||||
error,
|
||||
user_id: Number(request.user_id),
|
||||
metadata: { connector_id: request.connector_id },
|
||||
}).catch(() => {}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -933,6 +933,27 @@ export const AppData = {
|
||||
* hold thousands, so the page never reads them all at once.
|
||||
*/
|
||||
ConnectorAppsPageSize: 24,
|
||||
/**
|
||||
* How many matches `connectors_search_tools` returns unless asked for
|
||||
* fewer, and the most it ever returns: each is a line of the prompt.
|
||||
*/
|
||||
ConnectorSearchDefaultResults: 8,
|
||||
ConnectorSearchMaxResults: 25,
|
||||
/**
|
||||
* How many schemas `connectors_get_tool_schemas` reads in one call. A
|
||||
* schema can run to a few thousand characters.
|
||||
*/
|
||||
ConnectorSchemasMaxPerCall: 8,
|
||||
/**
|
||||
* How many tool calls one `connectors_execute` runs together. Each is
|
||||
* still one action against `ConnectorActionsPerRun`.
|
||||
*/
|
||||
ConnectorExecuteMaxCalls: 10,
|
||||
/**
|
||||
* Characters of a tool's description a search result shows: enough to
|
||||
* tell two tools apart, never the whole manual.
|
||||
*/
|
||||
ConnectorSearchDescriptionChars: 180,
|
||||
/**
|
||||
* Listing an MCP server's tools pages at most this many times and keeps
|
||||
* at most this many tools (M11): a server that keeps handing back a
|
||||
|
||||
@@ -242,11 +242,37 @@ You have runbooks (skills): load_skill lists them, with the one line each says a
|
||||
|
||||
/**
|
||||
* Added to every run that reaches a connector (`openBotConnectors`): the
|
||||
* accounts it can use, and what its tools are called.
|
||||
* accounts it can use, and how to reach their tools: through a router's
|
||||
* search, schema and execute tools, or, for an app given to the bot
|
||||
* directly, as deferred tools of the run's own.
|
||||
*/
|
||||
export const ConnectorsNote = ({ lines }: { lines: string[] }) => `# Connectors
|
||||
export const ConnectorsNote = ({
|
||||
lines,
|
||||
routers = [],
|
||||
direct = true,
|
||||
}: {
|
||||
lines: string[];
|
||||
routers?: string[];
|
||||
direct?: boolean;
|
||||
}) => `# Connectors
|
||||
|
||||
The user connected these apps themselves, through Settings > Connectors. Their tools are deferred: load the ones you need with load_tools first (an app's tools all share its prefix, e.g. names ["gmail*"]).
|
||||
The user connected these apps themselves, through Settings > Connectors.${
|
||||
routers.length
|
||||
? `
|
||||
|
||||
Apps marked "through" a router (${routers.join(", ")}) are reached with three tools of your own, never called by name:
|
||||
1. connectors_search_tools finds the tools that can do what you need ("send an email", "list open issues"), across every app or one (app: "gmail").
|
||||
2. connectors_get_tool_schemas reads the arguments of the ones you picked. Read a schema before the first call of a tool: don't guess its arguments.
|
||||
3. connectors_execute runs them by the names the search gave (e.g. gmail__GMAIL_SEND_EMAIL); several calls that don't depend on each other go in one execute.
|
||||
Searching and reading schemas cost nothing; each executed call is one action the provider bills.`
|
||||
: ""
|
||||
}${
|
||||
direct
|
||||
? `
|
||||
|
||||
${routers.length ? "The other apps' tools" : "Their tools"} are deferred: load the ones you need with load_tools first (an app's tools all share its prefix, e.g. names ["gmail*"]).`
|
||||
: ""
|
||||
}
|
||||
|
||||
- This is the user's own account. Read and send only what the request is about, and nothing else in it.
|
||||
- An app that answers with a preview (the rest was cut, or saved somewhere you can't open) gave you a truncated sample: it is never the total and never an empty result. Ask again for a smaller page (fewer results, no message payload, or ids only) and never report a count from a preview.
|
||||
|
||||
@@ -9,7 +9,7 @@ export const HookRunnerProtocol = 1;
|
||||
* Bump with every change to `HookRunnerScript`: every runner restarts once
|
||||
* with the new script.
|
||||
*/
|
||||
export const HookRunnerVersion = "2";
|
||||
export const HookRunnerVersion = "3";
|
||||
|
||||
/**
|
||||
* The process keeper the app runs on a computer for a hook's runner
|
||||
@@ -134,14 +134,15 @@ def stop(runner_id, state, stop_ms):
|
||||
|
||||
def start(runner, env, log_max):
|
||||
runner_id = runner["id"]
|
||||
cwd = runner["cwd"]
|
||||
if not os.path.isdir(cwd):
|
||||
cwds = runner.get("cwds") or [runner["cwd"]]
|
||||
cwd = next((folder for folder in cwds if os.path.isdir(folder)), None)
|
||||
if cwd is None:
|
||||
return {
|
||||
"id": runner_id,
|
||||
"pid": None,
|
||||
"running": False,
|
||||
"started_at": None,
|
||||
"error": "Its folder isn't there: %s" % cwd,
|
||||
"error": "Its folder isn't there: %s" % " or ".join(cwds),
|
||||
}
|
||||
log = log_path(runner_id)
|
||||
try:
|
||||
|
||||
@@ -124,6 +124,10 @@ export const JobStepToolLabels: Record<string, string> = {
|
||||
update_instructions: "Updating instructions",
|
||||
load_skill: "Reading a skill",
|
||||
load_tools: "Loading tools",
|
||||
connectors_search_tools: "Looking through connected apps",
|
||||
connectors_get_tool_schemas: "Reading a connected app's tools",
|
||||
connectors_execute: "Using a connected app",
|
||||
connectors_connect: "Asking you to connect an app",
|
||||
send_message: "Sending a message",
|
||||
create_graphic: "Drawing a graphic",
|
||||
update_graphic: "Redrawing a graphic",
|
||||
|
||||
@@ -164,3 +164,11 @@ export const ConnectorAppFilters = [
|
||||
] as const;
|
||||
|
||||
export type ConnectorAppFilter = (typeof ConnectorAppFilters)[number]["value"];
|
||||
|
||||
/**
|
||||
* The router's tools (`connectorRouterTools`).
|
||||
*/
|
||||
export const ConnectorSearchToolsToolName = "connectors_search_tools";
|
||||
export const ConnectorGetToolSchemasToolName = "connectors_get_tool_schemas";
|
||||
export const ConnectorExecuteToolName = "connectors_execute";
|
||||
export const ConnectorConnectToolName = "connectors_connect";
|
||||
|
||||
@@ -58,6 +58,10 @@ export type CustomToolScriptLanguage = (typeof CustomToolScriptLanguages)[number
|
||||
*/
|
||||
export const ReservedToolNames = [
|
||||
"add_bot_to_workspace",
|
||||
"connectors_connect",
|
||||
"connectors_execute",
|
||||
"connectors_get_tool_schemas",
|
||||
"connectors_search_tools",
|
||||
"ask_user",
|
||||
"ask_user_to_take_over",
|
||||
"assign_computer",
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
export type GeneralSettingsFieldKind =
|
||||
| "steps"
|
||||
| "actions"
|
||||
| "tokens"
|
||||
| "characters"
|
||||
| "mb"
|
||||
@@ -160,6 +161,17 @@ export const GeneralSettingsSections: GeneralSettingsSection[] = [
|
||||
citable: true,
|
||||
fields: [{ key: "max_chars", title: "Longest message", kind: "characters" }],
|
||||
},
|
||||
{
|
||||
key: "connectors",
|
||||
title: "Connectors",
|
||||
description: "How many actions one run may take in the apps people connected. A provider bills each action.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [
|
||||
{ key: "actions_per_run", title: "Connector actions per run", kind: "actions" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "skill-limits",
|
||||
title: "Skill limits",
|
||||
|
||||
@@ -7,6 +7,7 @@ import generalSettingsHref, {
|
||||
} from "@/src/dict/general-settings-dict";
|
||||
import settingValueLabel from "@/src/utils/setting-value-label";
|
||||
import grabAskRetention from "./grab-ask-retention";
|
||||
import grabConnectorSettingsOverview from "../connectors/grab-connector-settings-overview";
|
||||
import grabComputerWorkspaceQuotaOverview from "./grab-computer-workspace-quota-overview";
|
||||
import grabHookCallRetentionOverview from "./grab-hook-events-keep-days";
|
||||
import grabBotTraceRetentionOverview from "./grab-bot-trace-keep-days";
|
||||
@@ -29,7 +30,7 @@ type RawValues = Record<string, number | string | null>;
|
||||
* started shows its new number).
|
||||
*/
|
||||
export default async function grabGeneralSettingsValues(): Promise<GeneralSettingsSectionValues[]> {
|
||||
const [run_limits, skill_limits, hook_calls, run_traces, logs, asks, sessions, messages, storage, computer_workspace, appendix, install_name] =
|
||||
const [run_limits, skill_limits, hook_calls, run_traces, logs, asks, sessions, messages, storage, computer_workspace, appendix, install_name, connectors] =
|
||||
await Promise.all([
|
||||
grabRunLimitsOverview().catch(() => null),
|
||||
grabSkillLimitsOverview().catch(() => null),
|
||||
@@ -43,6 +44,7 @@ export default async function grabGeneralSettingsValues(): Promise<GeneralSettin
|
||||
grabComputerWorkspaceQuotaOverview().catch(() => null),
|
||||
grabSystemPromptAppendOverview().catch(() => null),
|
||||
grabInstallName().catch(() => ""),
|
||||
grabConnectorSettingsOverview().catch(() => null),
|
||||
]);
|
||||
|
||||
const raw: Record<string, RawValues> = {
|
||||
@@ -54,6 +56,9 @@ export default async function grabGeneralSettingsValues(): Promise<GeneralSettin
|
||||
context_tokens: run_limits?.context_tokens ?? null,
|
||||
model_rest_seconds: run_limits?.model_rest_seconds ?? null,
|
||||
},
|
||||
connectors: {
|
||||
actions_per_run: connectors?.actions_per_run ?? null,
|
||||
},
|
||||
sessions: { max_messages: sessions?.max_messages ?? null },
|
||||
messages: { max_chars: messages?.max_chars ?? null },
|
||||
"skill-limits": {
|
||||
|
||||
@@ -8,7 +8,7 @@ import composeComputerEnvFiles from "@/src/harness/tools/computer/compose-comput
|
||||
import type { HookRunnerSync } from "@/src/types";
|
||||
import computerNotReadyMessage from "@/src/utils/computer-not-ready-message";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
import hookRunnerDir, { hookRunnerBaseDir, hookRunnerFile } from "@/src/utils/hook-runner-paths";
|
||||
import { hookRunnerBaseDir, hookRunnerDirs, hookRunnerFile } from "@/src/utils/hook-runner-paths";
|
||||
import hookRunnerVersion from "@/src/utils/hook-runner-version";
|
||||
import type { ComputerAddress } from "../computers/grab-computer-target";
|
||||
import grabComputerTarget from "../computers/grab-computer-target";
|
||||
@@ -189,7 +189,7 @@ async function runGroup({
|
||||
workspace_id,
|
||||
});
|
||||
const base = hookRunnerBaseDir({ dirs });
|
||||
const runners: { id: number; command: string; cwd: string; version: string }[] = [];
|
||||
const runners: { id: number; command: string; cwd: string; cwds: string[]; version: string }[] = [];
|
||||
const wanted = new Set<number>();
|
||||
|
||||
for (const hook of group.hooks) {
|
||||
@@ -203,7 +203,7 @@ async function runGroup({
|
||||
user_id: hook.user_id,
|
||||
workspace_id: hook.workspace_id,
|
||||
});
|
||||
const cwd = hookRunnerDir({ dirs: hook_dirs, runner_dir: hook.runner_dir });
|
||||
const cwds = hookRunnerDirs({ dirs: hook_dirs, runner_dir: hook.runner_dir });
|
||||
const envs = await grabComputerEnvs({
|
||||
computer_id: group.computer_id,
|
||||
bot_id: hook.bot_id,
|
||||
@@ -213,7 +213,7 @@ async function runGroup({
|
||||
const version = hookRunnerVersion({
|
||||
script_version: HookRunnerVersion,
|
||||
command: hook.runner_command,
|
||||
dir: cwd,
|
||||
dir: cwds.join("\n"),
|
||||
computer_id: group.computer_id,
|
||||
workspace_id: hook.workspace_id,
|
||||
envs,
|
||||
@@ -227,7 +227,7 @@ async function runGroup({
|
||||
run_as: hook_dirs.run_as,
|
||||
});
|
||||
|
||||
runners.push({ id: Number(hook.id), command: hook.runner_command, cwd, version });
|
||||
runners.push({ id: Number(hook.id), command: hook.runner_command, cwd: cwds[0]!, cwds, version });
|
||||
wanted.add(Number(hook.id));
|
||||
} catch (error) {
|
||||
await recordRunnerFailure({
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { expect, test } from "bun:test";
|
||||
import closeOrphanBotTasksSql from "./close-orphan-bot-tasks-sql";
|
||||
|
||||
/**
|
||||
* Only an active row whose job is gone or closed is closed. Run against
|
||||
* real SQLite.
|
||||
*/
|
||||
test("closes active rows with no open job", () => {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_tasks (id INTEGER PRIMARY KEY, status TEXT, updated_at INTEGER)`);
|
||||
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, task_id INTEGER, status TEXT)`);
|
||||
db.run(`INSERT INTO bot_tasks VALUES (1, 'active', 10), (2, 'active', 10), (3, 'active', 10),
|
||||
(4, 'active', 10), (5, 'done', 10), (6, 'active', 500)`);
|
||||
db.run(`INSERT INTO bots_queue (task_id, status) VALUES (2, 'failed'), (3, 'pending'), (4, 'processing')`);
|
||||
|
||||
const { sql, values } = closeOrphanBotTasksSql({ before: 100 });
|
||||
|
||||
db.query(sql).run(...values);
|
||||
|
||||
const rows = db.query(`SELECT id, status FROM bot_tasks ORDER BY id`).all();
|
||||
|
||||
expect(rows).toEqual([
|
||||
{ id: 1, status: "done" },
|
||||
{ id: 2, status: "done" },
|
||||
{ id: 3, status: "active" },
|
||||
{ id: 4, status: "active" },
|
||||
{ id: 5, status: "done" },
|
||||
{ id: 6, status: "active" },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
type Params = {
|
||||
/**
|
||||
* Rows touched after this (Unix ms) are left alone: a run being queued
|
||||
* creates its row before its job.
|
||||
*/
|
||||
before: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes every `bot_tasks` row still `active` with no open job behind it.
|
||||
* A failed run closes its own row now (`notifyBotJobFailed`), but rows
|
||||
* from before that stayed `active` for months (production: a Morning
|
||||
* Digest run failed on Nov 20 and a row from Oct 23 whose job was long
|
||||
* pruned), and an active row keeps its conversation polling for progress
|
||||
* that never comes.
|
||||
*/
|
||||
export default function closeOrphanBotTasksSql({ before }: Params) {
|
||||
return {
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ?
|
||||
WHERE status = 'active' AND updated_at < ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM bots_queue q
|
||||
WHERE q.task_id = bot_tasks.id AND q.status IN ('pending', 'processing')
|
||||
)`,
|
||||
values: [Date.now(), before],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import closeOrphanBotTasksSql from "./close-orphan-bot-tasks-sql";
|
||||
|
||||
/**
|
||||
* Closes `bot_tasks` rows left `active` with no open job, safe on every
|
||||
* start (`closeOrphanBotTasksSql`).
|
||||
*/
|
||||
export default async function closeOrphanBotTasks() {
|
||||
await BunSQLite.sql(closeOrphanBotTasksSql({ before: Date.now() - 10 * 60 * 1000 }));
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS } from "@/db/types/db";
|
||||
import type { ConnectorRouterApp, ConnectorRouterRecord } from "@/src/types";
|
||||
import grabRouterAccounts from "./grab-router-accounts";
|
||||
import parseConnectorRouterRow from "./parse-connector-router-row";
|
||||
|
||||
type Params = {
|
||||
rows: BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS[];
|
||||
/**
|
||||
* Whose own bot attachments to read. Left out, none are read.
|
||||
*/
|
||||
user_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Router rows with their apps (each with how many connected accounts it
|
||||
* has), the workspaces they are given to and the viewer's own bots.
|
||||
*/
|
||||
export default async function attachConnectorRouterDetails({ rows, user_id }: Params): Promise<ConnectorRouterRecord[]> {
|
||||
if (!rows.length) return [];
|
||||
|
||||
const ids = rows.map((row) => Number(row.id));
|
||||
const placeholders = ids.map(() => "?").join(", ");
|
||||
|
||||
const [apps, workspaces, bots, picked] = await Promise.all([
|
||||
BunSQLite.sql<Omit<ConnectorRouterApp, "all_accounts"> & { router_id: number; all_accounts: number }>({
|
||||
sql: `SELECT ra.router_id, ra.all_accounts, c.id, c.name, c.slug, c.logo,
|
||||
(SELECT count(*) FROM connector_accounts a WHERE a.connector_id = c.id AND a.status = 'connected') AS accounts
|
||||
FROM connector_router_apps ra
|
||||
JOIN connectors c ON c.id = ra.connector_id
|
||||
WHERE ra.router_id IN (${placeholders})
|
||||
ORDER BY c.name COLLATE NOCASE ASC`,
|
||||
values: ids,
|
||||
}),
|
||||
BunSQLite.sql<{ router_id: number; workspace_id: number }>({
|
||||
sql: `SELECT router_id, workspace_id FROM workspace_connector_routers WHERE router_id IN (${placeholders})`,
|
||||
values: ids,
|
||||
}),
|
||||
user_id
|
||||
? BunSQLite.sql<{ router_id: number; bot_id: number }>({
|
||||
sql: `SELECT router_id, bot_id FROM bot_connector_routers WHERE router_id IN (${placeholders}) AND user_id = ?`,
|
||||
values: [...ids, Number(user_id)],
|
||||
})
|
||||
: Promise.resolve({ payload: [] as { router_id: number; bot_id: number }[] }),
|
||||
grabRouterAccounts({
|
||||
where: `, ra.router_id FROM connector_router_accounts ra
|
||||
JOIN connector_accounts a ON a.id = ra.account_id
|
||||
LEFT JOIN users u ON u.id = a.user_id
|
||||
WHERE ra.router_id IN (${placeholders})`,
|
||||
values: ids,
|
||||
}),
|
||||
]);
|
||||
|
||||
return rows.map((row) => {
|
||||
const id = Number(row.id);
|
||||
|
||||
return parseConnectorRouterRow({
|
||||
row,
|
||||
apps: (apps.payload || [])
|
||||
.filter((app) => Number(app.router_id) == id)
|
||||
.map((app) => {
|
||||
const all_accounts = Number(app.all_accounts) != 0;
|
||||
|
||||
return {
|
||||
id: Number(app.id),
|
||||
name: app.name || "",
|
||||
slug: app.slug || "",
|
||||
logo: app.logo || "",
|
||||
accounts: Number(app.accounts) || 0,
|
||||
all_accounts,
|
||||
account_list: all_accounts
|
||||
? []
|
||||
: picked.filter(
|
||||
(account) => account.router_id == id && account.connector_id == Number(app.id),
|
||||
),
|
||||
};
|
||||
}),
|
||||
workspace_ids: (workspaces.payload || [])
|
||||
.filter((entry) => Number(entry.router_id) == id)
|
||||
.map((entry) => Number(entry.workspace_id)),
|
||||
bot_ids: (bots.payload || [])
|
||||
.filter((entry) => Number(entry.router_id) == id)
|
||||
.map((entry) => Number(entry.bot_id)),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
/**
|
||||
* The rows of these routers, children first: shared with deleting a whole
|
||||
* connection.
|
||||
*/
|
||||
export default async function deleteConnectorRouterRows({ router_ids }: { router_ids: number[] }) {
|
||||
if (!router_ids.length) return;
|
||||
|
||||
const placeholders = router_ids.map(() => "?").join(", ");
|
||||
|
||||
for (const table of ["connector_router_accounts", "connector_router_apps", "bot_connector_routers", "workspace_connector_routers"]) {
|
||||
await BunSQLite.sql({ sql: `DELETE FROM ${table} WHERE router_id IN (${placeholders})`, values: router_ids });
|
||||
}
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_routers WHERE id IN (${placeholders})`, values: router_ids });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assertSuperAdmin from "../access/assert-super-admin";
|
||||
import deleteConnectorRouterRows from "./delete-connector-router-rows";
|
||||
import grabConnectorRouter from "./grab-connector-router";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
router_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a router with its app list and every grant of it. Its apps and
|
||||
* their accounts stay: they belong to the connection, not the router.
|
||||
* Children go first and explicitly, since foreign keys are off outside the
|
||||
* server process.
|
||||
*/
|
||||
export default async function deleteConnectorRouter({ user_id, router_id }: Params) {
|
||||
await assertSuperAdmin({ user_id });
|
||||
|
||||
const router = await grabConnectorRouter({ router_id });
|
||||
|
||||
await deleteConnectorRouterRows({ router_ids: [router.id] });
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS } from "@/db/types/db";
|
||||
import type { ConnectorRouterRecord } from "@/src/types";
|
||||
import botConnectorRoutersSql from "@/src/utils/bot-connector-routers-sql";
|
||||
import attachConnectorRouterDetails from "./attach-connector-router-details";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
connection_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The routers of one connection a user could add to this bot from the
|
||||
* composer: switched on, and not already reaching the bot here.
|
||||
*/
|
||||
export default async function grabAttachableConnectorRouters({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
connection_id,
|
||||
}: Params): Promise<ConnectorRouterRecord[]> {
|
||||
const reach = botConnectorRoutersSql({ bot_id, user_id, workspace_id });
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS>({
|
||||
sql: `SELECT * FROM connector_routers
|
||||
WHERE connection_id = ? AND enabled = 1
|
||||
AND id NOT IN (SELECT id FROM (${reach.sql}))
|
||||
ORDER BY name COLLATE NOCASE ASC`,
|
||||
values: [Number(connection_id), ...reach.values],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
return attachConnectorRouterDetails({ rows, user_id });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS } from "@/db/types/db";
|
||||
import type { BotConnectorRouterEntry } from "@/src/types";
|
||||
import botConnectorRoutersSql from "@/src/utils/bot-connector-routers-sql";
|
||||
import attachConnectorRouterDetails from "./attach-connector-router-details";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
};
|
||||
|
||||
type RouterRow = BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS & { connection_name?: string };
|
||||
|
||||
/**
|
||||
* The routers a conversation's bot reaches for this user, for the
|
||||
* composer's Connectors section: the install's, this workspace's and the
|
||||
* user's own attachment, each saying which.
|
||||
*/
|
||||
export default async function grabBotConnectorRouters({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}: Params): Promise<BotConnectorRouterEntry[]> {
|
||||
const reach = botConnectorRoutersSql({ bot_id, user_id, workspace_id });
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<RouterRow>({
|
||||
sql: `SELECT r.*, cc.name AS connection_name
|
||||
FROM (${reach.sql}) r JOIN connector_connections cc ON cc.id = r.connection_id`,
|
||||
values: reach.values,
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
if (!rows.length) return [];
|
||||
|
||||
const routers = await attachConnectorRouterDetails({ rows, user_id });
|
||||
|
||||
return routers.map((router, index): BotConnectorRouterEntry => {
|
||||
const on_bot = router.bot_ids.includes(Number(bot_id));
|
||||
const via = router.all_bots
|
||||
? "global"
|
||||
: workspace_id && router.workspace_ids.includes(Number(workspace_id))
|
||||
? "workspace"
|
||||
: "bot";
|
||||
|
||||
return {
|
||||
router,
|
||||
connection_name: rows[index]?.connection_name || "",
|
||||
via,
|
||||
removable: on_bot,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import attachConnectorRouterDetails from "./attach-connector-router-details";
|
||||
|
||||
type Params = {
|
||||
router_id: number | string;
|
||||
/**
|
||||
* Whose own bot attachments to read with it.
|
||||
*/
|
||||
user_id?: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* One router with its apps and grants, or an error that it's gone.
|
||||
*/
|
||||
export default async function grabConnectorRouter({ router_id, user_id }: Params) {
|
||||
const row = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS>({
|
||||
sql: `SELECT * FROM connector_routers WHERE id = ?`,
|
||||
values: [Number(router_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row) throw new AppError(`That router doesn't exist.`);
|
||||
|
||||
const [router] = await attachConnectorRouterDetails({ rows: [row], user_id });
|
||||
|
||||
return router!;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS } from "@/db/types/db";
|
||||
import type { ConnectorRoutersPayload } from "@/src/types";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import attachConnectorRouterDetails from "./attach-connector-router-details";
|
||||
import grabRouterAppChoices from "./grab-router-app-choices";
|
||||
|
||||
type Params = {
|
||||
connection_id: number | string;
|
||||
/**
|
||||
* The viewer: their own bot attachments are read, and a super admin also
|
||||
* gets the apps a router may pick.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* One connection's routers for its page's Routers tab.
|
||||
*/
|
||||
export default async function grabConnectorRouters({ connection_id, user_id }: Params): Promise<ConnectorRoutersPayload> {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS>({
|
||||
sql: `SELECT * FROM connector_routers WHERE connection_id = ? ORDER BY name COLLATE NOCASE ASC, id ASC`,
|
||||
values: [Number(connection_id)],
|
||||
})
|
||||
).payload || [];
|
||||
const role = await grabCrewRole({ user_id });
|
||||
|
||||
return {
|
||||
routers: await attachConnectorRouterDetails({ rows, user_id }),
|
||||
choices: role == "super_admin" ? await grabRouterAppChoices({ connection_id }) : [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { ConnectorRouterAccount } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The SQL that picks the accounts (`a`), with its values.
|
||||
*/
|
||||
where: string;
|
||||
values: (number | string)[];
|
||||
};
|
||||
|
||||
type Row = ConnectorRouterAccount & { router_id?: number };
|
||||
|
||||
/**
|
||||
* Accounts as a router's settings show them: label, owner and status, with
|
||||
* the router they were picked for when the query joins one.
|
||||
*/
|
||||
export default async function grabRouterAccounts({ where, values }: Params): Promise<Row[]> {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<Row>({
|
||||
sql: `SELECT a.id, a.connector_id, a.label, a.status,
|
||||
trim(coalesce(u.first_name, '') || ' ' || coalesce(u.last_name, '')) AS owner_name ${where}
|
||||
ORDER BY a.label COLLATE NOCASE ASC, a.id ASC`,
|
||||
values,
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
connector_id: Number(row.connector_id),
|
||||
label: row.label || "",
|
||||
owner_name: row.owner_name || "",
|
||||
status: row.status || "",
|
||||
router_id: row.router_id === undefined ? undefined : Number(row.router_id),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { ConnectorRouterApp } from "@/src/types";
|
||||
import grabRouterAccounts from "./grab-router-accounts";
|
||||
|
||||
type Params = {
|
||||
connection_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The apps a router on this connection may pick: the enabled ones somebody
|
||||
* has a connected account for, each with those accounts, so a router can
|
||||
* take one account of an app rather than all of them. An app nobody signed in to would give a
|
||||
* router's runs nothing to call. Read whole: a connection holds thousands of
|
||||
* apps, but only the handful people connected.
|
||||
*/
|
||||
export default async function grabRouterAppChoices({ connection_id }: Params): Promise<ConnectorRouterApp[]> {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<Pick<ConnectorRouterApp, "id" | "name" | "slug" | "logo" | "accounts">>({
|
||||
sql: `SELECT c.id, c.name, c.slug, c.logo, count(a.id) AS accounts
|
||||
FROM connectors c
|
||||
JOIN connector_accounts a ON a.connector_id = c.id AND a.status = 'connected'
|
||||
WHERE c.connection_id = ? AND c.enabled = 1
|
||||
GROUP BY c.id
|
||||
ORDER BY c.name COLLATE NOCASE ASC`,
|
||||
values: [Number(connection_id)],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
const accounts = await grabRouterAccounts({
|
||||
where: `FROM connector_accounts a
|
||||
JOIN connectors c ON c.id = a.connector_id
|
||||
LEFT JOIN users u ON u.id = a.user_id
|
||||
WHERE c.connection_id = ? AND a.status = 'connected'`,
|
||||
values: [Number(connection_id)],
|
||||
});
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
name: row.name || "",
|
||||
slug: row.slug || "",
|
||||
logo: row.logo || "",
|
||||
accounts: Number(row.accounts) || 0,
|
||||
all_accounts: true,
|
||||
account_list: accounts.filter((account) => account.connector_id == Number(row.id)),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS } from "@/db/types/db";
|
||||
import type { ConnectorRouterApp, ConnectorRouterRecord } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
row: BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS;
|
||||
apps?: ConnectorRouterApp[];
|
||||
workspace_ids?: number[];
|
||||
bot_ids?: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A `connector_routers` row as the app reads it, with what is read beside it.
|
||||
*/
|
||||
export default function parseConnectorRouterRow({
|
||||
row,
|
||||
apps = [],
|
||||
workspace_ids = [],
|
||||
bot_ids = [],
|
||||
}: Params): ConnectorRouterRecord {
|
||||
return {
|
||||
id: Number(row.id),
|
||||
connection_id: Number(row.connection_id),
|
||||
name: row.name || "",
|
||||
slug: row.slug || "",
|
||||
description: row.description || "",
|
||||
all_bots: row.all_bots == 1,
|
||||
enabled: row.enabled != 0,
|
||||
user_id: Number(row.user_id),
|
||||
apps,
|
||||
workspace_ids,
|
||||
bot_ids,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS, BunSQLiteTables } from "@/db/types/db";
|
||||
import type { SaveConnectorRouterRequest } from "@/src/schemas/connector-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import connectorSlug from "@/src/utils/connector-slug";
|
||||
import assertSuperAdmin from "../access/assert-super-admin";
|
||||
import grabConnector from "../connectors/grab-connector";
|
||||
import grabConnectorConnection from "../connectors/grab-connector-connection";
|
||||
import syncConnector from "../connectors/sync-connector";
|
||||
import grabConnectorRouter from "./grab-connector-router";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
data: SaveConnectorRouterRequest;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes a router on a connection, or changes one: its name, what it is for,
|
||||
* whether it is on, which of the connection's apps it reaches and, per app,
|
||||
* either every account a run reaches or only the accounts picked (which then
|
||||
* reach every run the router reaches). Super admins only, who may give out
|
||||
* any account anyway. An app it newly reaches whose tools were never read is read
|
||||
* now, so the router's search has something to find on its first run.
|
||||
*/
|
||||
export default async function saveConnectorRouter({ user_id, data }: Params) {
|
||||
await assertSuperAdmin({ user_id });
|
||||
|
||||
const connection = await grabConnectorConnection({ connection_id: data.connection_id });
|
||||
const existing = data.router_id ? await grabConnectorRouter({ router_id: data.router_id }) : null;
|
||||
|
||||
if (existing && existing.connection_id != connection.id) {
|
||||
throw new AppError(`That router belongs to another connection.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* One entry per app: an app picked twice merges its accounts, and an
|
||||
* app picked with no accounts anywhere uses all of them.
|
||||
*/
|
||||
const picks = new Map<number, Set<number> | null>();
|
||||
|
||||
for (const app of data.apps) {
|
||||
const id = Number(app.connector_id);
|
||||
const known = picks.get(id);
|
||||
|
||||
if (known === null) continue;
|
||||
|
||||
if (!app.account_ids.length) {
|
||||
picks.set(id, null);
|
||||
continue;
|
||||
}
|
||||
|
||||
picks.set(id, new Set([...(known || []), ...app.account_ids.map(Number)]));
|
||||
}
|
||||
|
||||
const connector_ids = [...picks.keys()];
|
||||
const owned =
|
||||
(
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM connectors WHERE connection_id = ? AND id IN (${connector_ids.map(() => "?").join(", ")})`,
|
||||
values: [connection.id, ...connector_ids],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
if (owned.length != connector_ids.length) {
|
||||
throw new AppError(`A router only picks apps of its own connection (${connection.name}).`);
|
||||
}
|
||||
|
||||
const account_ids = [...picks.values()].flatMap((set) => [...(set || [])]);
|
||||
const accounts = account_ids.length
|
||||
? (
|
||||
await BunSQLite.sql<{ id: number; connector_id: number }>({
|
||||
sql: `SELECT id, connector_id FROM connector_accounts WHERE id IN (${account_ids.map(() => "?").join(", ")})`,
|
||||
values: account_ids,
|
||||
})
|
||||
).payload || []
|
||||
: [];
|
||||
|
||||
for (const [connector_id, set] of picks) {
|
||||
for (const account_id of set || []) {
|
||||
if (!accounts.some((row) => Number(row.id) == account_id && Number(row.connector_id) == connector_id)) {
|
||||
throw new AppError(`An account picked for an app isn't one of that app's accounts.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
let router_id = existing?.id || 0;
|
||||
|
||||
if (existing) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_routers SET name = ?, description = ?, enabled = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [data.name, data.description, data.enabled ? 1 : 0, now, existing.id],
|
||||
});
|
||||
} else {
|
||||
const taken = new Set(
|
||||
((await BunSQLite.sql<{ slug: string }>({ sql: `SELECT slug FROM connector_routers` })).payload || []).map(
|
||||
(row) => row.slug,
|
||||
),
|
||||
);
|
||||
const base = connectorSlug({ name: data.name, max: 24, fallback: "router" });
|
||||
let slug = base;
|
||||
|
||||
for (let suffix = 2; taken.has(slug); suffix++) slug = `${base.slice(0, 20)}-${suffix}`;
|
||||
|
||||
const created = await BunSQLite.insert<BUN_SQLITE_COBBLE_CONNECTOR_ROUTERS, (typeof BunSQLiteTables)[number]>({
|
||||
table: "connector_routers",
|
||||
data: [
|
||||
{
|
||||
connection_id: connection.id,
|
||||
name: data.name,
|
||||
slug,
|
||||
description: data.description,
|
||||
all_bots: 0,
|
||||
enabled: data.enabled ? 1 : 0,
|
||||
user_id: Number(user_id),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
router_id = Number(created.singleRes?.id || created.postInsertReturn?.insertId);
|
||||
|
||||
if (!created.success || !router_id) throw new AppError(`Couldn't make the router: ${created.msg}`);
|
||||
}
|
||||
|
||||
const before = new Set(existing?.apps.map((app) => app.id) || []);
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_router_accounts WHERE router_id = ?`, values: [router_id] });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_router_apps WHERE router_id = ?`, values: [router_id] });
|
||||
|
||||
for (const [connector_id, set] of picks) {
|
||||
await BunSQLite.sql({
|
||||
sql: `INSERT OR IGNORE INTO connector_router_apps (created_at, updated_at, router_id, connector_id, all_accounts) VALUES (?, ?, ?, ?, ?)`,
|
||||
values: [now, now, router_id, connector_id, set ? 0 : 1],
|
||||
});
|
||||
|
||||
for (const account_id of set || []) {
|
||||
await BunSQLite.sql({
|
||||
sql: `INSERT OR IGNORE INTO connector_router_accounts (created_at, updated_at, router_id, account_id) VALUES (?, ?, ?, ?)`,
|
||||
values: [now, now, router_id, account_id],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const connector_id of connector_ids.filter((id) => !before.has(id))) {
|
||||
const connector = await grabConnector({ connector_id });
|
||||
|
||||
if (!connector.tools.length) await syncConnector({ connector_id });
|
||||
}
|
||||
|
||||
return grabConnectorRouter({ router_id, user_id });
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import grabUserBot from "../bots/grab-user-bot";
|
||||
import grabConnectorRouter from "./grab-connector-router";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
router_id: number | string;
|
||||
/**
|
||||
* Shows it in the user's runs on the bot, or takes it away.
|
||||
*/
|
||||
attached: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* A user's own attachment of a router to a bot: its apps reach their runs
|
||||
* there, with the accounts those runs reach, and nobody else's.
|
||||
*/
|
||||
export default async function setBotConnectorRouter({ user_id, bot_id, router_id, attached }: Params) {
|
||||
const [bot, router] = await Promise.all([grabUserBot({ bot_id, user_id }), grabConnectorRouter({ router_id })]);
|
||||
|
||||
if (!bot) throw new AppError(`You don't reach that bot.`);
|
||||
|
||||
if (attached && !router.enabled) throw new AppError(`${router.name} is switched off.`);
|
||||
|
||||
const now = Date.now();
|
||||
const res = attached
|
||||
? await BunSQLite.sql({
|
||||
sql: `INSERT OR IGNORE INTO bot_connector_routers (created_at, updated_at, bot_id, user_id, router_id) VALUES (?, ?, ?, ?, ?)`,
|
||||
values: [now, now, Number(bot.id), Number(user_id), router.id],
|
||||
})
|
||||
: await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_connector_routers WHERE bot_id = ? AND user_id = ? AND router_id = ?`,
|
||||
values: [Number(bot.id), Number(user_id), router.id],
|
||||
});
|
||||
|
||||
if (!res.success) throw new Error(`Couldn't change the bot's routers: ${res.error}`);
|
||||
|
||||
return { bot, router };
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { SaveConnectorRouterAccessRequest } from "@/src/schemas/connector-schema";
|
||||
import assertSuperAdmin from "../access/assert-super-admin";
|
||||
import grabConnectorRouter from "./grab-connector-router";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
data: SaveConnectorRouterAccessRequest;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes a router reach every bot, or gives it to these workspaces. A super
|
||||
* admin's alone, as for an app: a bot attachment is a person's own and goes
|
||||
* through `setBotConnectorRouter`.
|
||||
*/
|
||||
export default async function setConnectorRouterAccess({ user_id, data }: Params) {
|
||||
await assertSuperAdmin({ user_id });
|
||||
|
||||
const router = await grabConnectorRouter({ router_id: data.router_id });
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM workspace_connector_routers WHERE router_id = ?`, values: [router.id] });
|
||||
|
||||
for (const workspace_id of new Set(data.workspace_ids)) {
|
||||
await BunSQLite.sql({
|
||||
sql: `INSERT OR IGNORE INTO workspace_connector_routers (created_at, updated_at, workspace_id, router_id)
|
||||
SELECT ?, ?, id, ? FROM workspaces WHERE id = ?`,
|
||||
values: [now, now, router.id, workspace_id],
|
||||
});
|
||||
}
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_routers SET all_bots = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [data.all_bots === undefined ? (router.all_bots ? 1 : 0) : data.all_bots ? 1 : 0, now, router.id],
|
||||
});
|
||||
|
||||
return grabConnectorRouter({ router_id: router.id, user_id });
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabConnectorProvider from "./grab-connector-provider";
|
||||
import grabConnectorConnection from "./grab-connector-connection";
|
||||
import deleteConnectorRouterRows from "../connector-routers/delete-connector-router-rows";
|
||||
|
||||
type Params = {
|
||||
connection_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes a connection with everything read from it: its apps' accounts,
|
||||
* sessions, sign-in requests and reach, then the apps, then the row. The
|
||||
* Removes a connection with everything read from it: its routers, its apps'
|
||||
* accounts, sessions, sign-in requests and reach, then the apps, then the
|
||||
* row. The
|
||||
* provider accounts are released first, best effort, since a key that was
|
||||
* already refused must not stop the delete.
|
||||
*/
|
||||
@@ -42,11 +44,27 @@ export default async function deleteConnectorConnection({ connection_id }: Param
|
||||
}
|
||||
}
|
||||
|
||||
const router_ids = (
|
||||
(
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM connector_routers WHERE connection_id = ?`,
|
||||
values: [connection.id],
|
||||
})
|
||||
).payload || []
|
||||
).map((row) => Number(row.id));
|
||||
|
||||
await deleteConnectorRouterRows({ router_ids });
|
||||
|
||||
if (ids.length) {
|
||||
const placeholders = ids.map(() => "?").join(", ");
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_sessions WHERE connector_id IN (${placeholders})`, values: ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_requests WHERE connector_id IN (${placeholders})`, values: ids });
|
||||
const account_scope = `SELECT id FROM connector_accounts WHERE connector_id IN (${placeholders})`;
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_account_bots WHERE account_id IN (${account_scope})`, values: ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_router_accounts WHERE account_id IN (${account_scope})`, values: ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_account_workspaces WHERE account_id IN (${account_scope})`, values: ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_accounts WHERE connector_id IN (${placeholders})`, values: ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_connectors WHERE connector_id IN (${placeholders})`, values: ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM workspace_connectors WHERE connector_id IN (${placeholders})`, values: ids });
|
||||
|
||||
@@ -31,6 +31,11 @@ export default async function disconnectConnectorAccount({ user_id, account_id }
|
||||
sql: `DELETE FROM connector_sessions WHERE connector_id = ? AND user_id = ? AND provider_account_id = ?`,
|
||||
values: [connector.id, Number(user_id), account.provider_account_id],
|
||||
});
|
||||
// Its grants go first: foreign keys are off outside the server process,
|
||||
// so a script's delete would leave them behind for the next db:schema.
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_account_bots WHERE account_id = ?`, values: [account.id] });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_router_accounts WHERE account_id = ?`, values: [account.id] });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_account_workspaces WHERE account_id = ?`, values: [account.id] });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM connector_accounts WHERE id = ?`, values: [account.id] });
|
||||
|
||||
if (account.is_default) {
|
||||
|
||||
@@ -37,15 +37,13 @@ export default async function grabAttachableConnectors({
|
||||
const search = `%${query.trim()}%`;
|
||||
const connection = Number(connection_id) ? Number(connection_id) : 0;
|
||||
const reach = botConnectorsSql({ bot_id, user_id, workspace_id });
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<Row>({
|
||||
const res = await BunSQLite.sql<Row>({
|
||||
sql: `SELECT c.*, cc.name AS connection_name
|
||||
FROM connectors c
|
||||
JOIN connector_connections cc ON cc.id = c.connection_id
|
||||
WHERE c.enabled = 1 AND (c.name LIKE ? OR c.app LIKE ?)
|
||||
AND (? = 0 OR c.connection_id = ?)
|
||||
AND c.id NOT IN (${reach.sql})
|
||||
AND c.id NOT IN (SELECT id FROM (${reach.sql}))
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM connector_accounts a
|
||||
WHERE a.connector_id = c.id AND a.status = 'connected' AND a.user_id = ?
|
||||
@@ -61,8 +59,16 @@ export default async function grabAttachableConnectors({
|
||||
Number(user_id),
|
||||
Limit,
|
||||
],
|
||||
})
|
||||
).payload || [];
|
||||
});
|
||||
|
||||
/**
|
||||
* A query that fails must say so: read as an empty list, a broken one
|
||||
* (`botConnectorsSql` selects every column, so it has to be wrapped to
|
||||
* be used with NOT IN) left the Add a connector modal blank.
|
||||
*/
|
||||
if (!res.success) throw new Error(`Couldn't read the apps to add: ${res.error || res.msg}`);
|
||||
|
||||
const rows = res.payload || [];
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { ConnectorSettingsOverview } from "@/src/types";
|
||||
import grabConnectorActionsPerRun from "./grab-connector-actions-per-run";
|
||||
|
||||
/**
|
||||
* The install's connector settings with the code's default and ceiling, for
|
||||
* Settings > General > Connectors and for a bot quoting them.
|
||||
*/
|
||||
export default async function grabConnectorSettingsOverview(): Promise<ConnectorSettingsOverview> {
|
||||
return {
|
||||
actions_per_run: await grabConnectorActionsPerRun(),
|
||||
default_actions_per_run: AppData.ConnectorActionsPerRun,
|
||||
max_actions_per_run: AppData.ConnectorActionsPerRunMax,
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
|
||||
import botConnectorRoutersSql from "@/src/utils/bot-connector-routers-sql";
|
||||
import connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
|
||||
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
|
||||
import parseConnectorAccountRow from "./parse-connector-account-row";
|
||||
@@ -26,6 +27,25 @@ export type RunConnector = {
|
||||
* with: the card asks them to connect one.
|
||||
*/
|
||||
accounts: ConnectorAccountRecord[];
|
||||
/**
|
||||
* The user's own sign-in for it that doesn't work right now (expired at
|
||||
* the provider, gone from it, or never finished), newest first: what the
|
||||
* run says instead of "no account", and the row a connect card
|
||||
* reconnects rather than adding a second card beside it.
|
||||
*/
|
||||
lapsed: ConnectorAccountRecord | null;
|
||||
/**
|
||||
* The routers that bring it to this run, by name. An app any router
|
||||
* reaches is run through the router's tools, even when it was also given
|
||||
* directly, so its own tools never fill the prompt.
|
||||
*/
|
||||
routers: string[];
|
||||
/**
|
||||
* True when every router bringing it picked its accounts and it wasn't
|
||||
* given directly: `accounts` are only those, and connecting another
|
||||
* account wouldn't add one.
|
||||
*/
|
||||
picked: boolean;
|
||||
};
|
||||
|
||||
type AccountRow = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string };
|
||||
@@ -35,18 +55,82 @@ type AccountRow = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string }
|
||||
* may act through: its own user's, never another person's unless that
|
||||
* account was given to this bot, this workspace or every bot, or its app was
|
||||
* given to this workspace. A connector reaches a run without any account; it
|
||||
* only becomes callable once there is one.
|
||||
* only becomes callable once there is one. Apps of the routers the run
|
||||
* reaches (`botConnectorRoutersSql`) are read beside the ones given directly.
|
||||
*/
|
||||
export default async function grabRunConnectors({ user_id, bot_id, workspace_id }: Params): Promise<RunConnector[]> {
|
||||
const found =
|
||||
const direct =
|
||||
(
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTORS>(
|
||||
botConnectorsSql({ bot_id, user_id, workspace_id }),
|
||||
)
|
||||
).payload || [];
|
||||
const reach = botConnectorRoutersSql({ bot_id, user_id, workspace_id });
|
||||
const router_apps =
|
||||
(
|
||||
await BunSQLite.sql<{ connector_id: number; router_name: string; router_id: number; all_accounts: number }>({
|
||||
sql: `SELECT ra.connector_id, ra.all_accounts, r.id AS router_id, r.name AS router_name
|
||||
FROM (${reach.sql}) r
|
||||
JOIN connector_router_apps ra ON ra.router_id = r.id
|
||||
ORDER BY r.id ASC, ra.id ASC`,
|
||||
values: reach.values,
|
||||
})
|
||||
).payload || [];
|
||||
const routed_ids = [...new Set(router_apps.map((row) => Number(row.connector_id)))].filter(
|
||||
(id) => !direct.some((row) => Number(row.id) == id),
|
||||
);
|
||||
const routed = routed_ids.length
|
||||
? (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTORS>({
|
||||
sql: `SELECT * FROM connectors WHERE enabled = 1 AND id IN (${routed_ids.map(() => "?").join(", ")}) ORDER BY id ASC`,
|
||||
values: routed_ids,
|
||||
})
|
||||
).payload || []
|
||||
: [];
|
||||
const found = [...direct, ...routed];
|
||||
|
||||
if (!found.length) return [];
|
||||
|
||||
/**
|
||||
* The accounts routers picked for their apps: each reaches every run the
|
||||
* router reaches, whoever owns it, as an account given out does.
|
||||
*/
|
||||
const router_ids = [...new Set(router_apps.map((row) => Number(row.router_id)))];
|
||||
const picked_rows = router_ids.length
|
||||
? (
|
||||
await BunSQLite.sql<{ router_id: number; account_id: number; connector_id: number }>({
|
||||
sql: `SELECT ra.router_id, ra.account_id, a.connector_id FROM connector_router_accounts ra
|
||||
JOIN connector_accounts a ON a.id = ra.account_id
|
||||
WHERE ra.router_id IN (${router_ids.map(() => "?").join(", ")})`,
|
||||
values: router_ids,
|
||||
})
|
||||
).payload || []
|
||||
: [];
|
||||
const picked_ids = [...new Set(picked_rows.map((row) => Number(row.account_id)))];
|
||||
|
||||
/**
|
||||
* Which accounts an app may use in this run: null for every account it
|
||||
* reaches (given directly, or a router taking all of them), else only
|
||||
* the ones its routers picked.
|
||||
*/
|
||||
const allowedFor = (connector_id: number): Set<number> | null => {
|
||||
if (direct.some((row) => Number(row.id) == connector_id)) return null;
|
||||
|
||||
const rows = router_apps.filter((row) => Number(row.connector_id) == connector_id);
|
||||
|
||||
if (rows.some((row) => Number(row.all_accounts) != 0)) return null;
|
||||
|
||||
return new Set(
|
||||
picked_rows
|
||||
.filter(
|
||||
(row) =>
|
||||
Number(row.connector_id) == connector_id &&
|
||||
rows.some((app) => Number(app.router_id) == Number(row.router_id)),
|
||||
)
|
||||
.map((row) => Number(row.account_id)),
|
||||
);
|
||||
};
|
||||
|
||||
const connectors = found.map((row) => parseConnectorRow({ row }));
|
||||
const ids = connectors.map((connector) => connector.id);
|
||||
const workspace_reach = connectorAccountReachSql({ workspace_id });
|
||||
@@ -64,9 +148,10 @@ export default async function grabRunConnectors({ user_id, bot_id, workspace_id
|
||||
OR EXISTS (SELECT 1 FROM connector_account_bots b WHERE b.account_id = a.id AND b.bot_id = ?)
|
||||
OR EXISTS (SELECT 1 FROM connector_account_workspaces w WHERE w.account_id = a.id AND w.workspace_id = ?)
|
||||
${workspace_reach.sql}
|
||||
${picked_ids.length ? `OR a.id IN (${picked_ids.map(() => "?").join(", ")})` : ""}
|
||||
)
|
||||
ORDER BY a.id ASC`,
|
||||
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0), ...workspace_reach.values],
|
||||
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0), ...workspace_reach.values, ...picked_ids],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
@@ -80,8 +165,37 @@ export default async function grabRunConnectors({ user_id, bot_id, workspace_id
|
||||
}),
|
||||
);
|
||||
|
||||
return connectors.map((connector) => ({
|
||||
connector,
|
||||
accounts: accounts.filter((account) => account.connector_id == connector.id),
|
||||
}));
|
||||
const lapsed_rows =
|
||||
(
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
sql: `SELECT * FROM connector_accounts
|
||||
WHERE connector_id IN (${ids.map(() => "?").join(", ")})
|
||||
AND user_id = ? AND status != 'connected'
|
||||
ORDER BY updated_at DESC, id DESC`,
|
||||
values: [...ids, Number(user_id)],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
return connectors.map((connector) => {
|
||||
const allowed = allowedFor(connector.id);
|
||||
const lapsed = lapsed_rows.find(
|
||||
(row) => Number(row.connector_id) == connector.id && (!allowed || allowed.has(Number(row.id))),
|
||||
);
|
||||
|
||||
return {
|
||||
connector,
|
||||
accounts: accounts.filter(
|
||||
(account) => account.connector_id == connector.id && (!allowed || allowed.has(account.id)),
|
||||
),
|
||||
lapsed: lapsed ? parseConnectorAccountRow({ row: lapsed }) : null,
|
||||
picked: Boolean(allowed),
|
||||
routers: [
|
||||
...new Set(
|
||||
router_apps
|
||||
.filter((row) => Number(row.connector_id) == connector.id)
|
||||
.map((row) => row.router_name),
|
||||
),
|
||||
],
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -97,6 +97,20 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
for (const account of accounts) {
|
||||
const provider_account_id = String(account.provider_account_id);
|
||||
const reconnect_id = reconnect_for.get(provider_account_id);
|
||||
const known = local.find((row) => String(row.provider_account_id || "") == provider_account_id);
|
||||
|
||||
/**
|
||||
* A row this install already has follows the provider's status on
|
||||
* every sync: an account that expired there says so here (and offers
|
||||
* Reconnect) instead of staying "connected" until a run fails on it,
|
||||
* and one an earlier listing missed comes back. Only the adoption
|
||||
* rules below are for accounts the install doesn't have yet, so a
|
||||
* known account never takes an id-less reconnect's slot either.
|
||||
*/
|
||||
if (known) {
|
||||
await refreshKnownAccount({ row: known, account, now });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
!shouldAdoptConnectorAccount({
|
||||
@@ -154,6 +168,27 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_id) });
|
||||
}
|
||||
|
||||
type RefreshParams = {
|
||||
row: BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS;
|
||||
account: ProviderAccount;
|
||||
now: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One known row brought in line with the provider. The label stays the
|
||||
* user's: they may have renamed it, and the provider's name for the account
|
||||
* is only a starting point.
|
||||
*/
|
||||
async function refreshKnownAccount({ row, account, now }: RefreshParams) {
|
||||
const connected_at =
|
||||
account.status == "connected" ? Number(row.connected_at) || now : row.connected_at ? Number(row.connected_at) : null;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_accounts SET status = ?, connected_at = ?, last_checked_at = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [account.status, connected_at, now, row.status == account.status ? Number(row.updated_at) || now : now, Number(row.id)],
|
||||
});
|
||||
}
|
||||
|
||||
export function pendingReconnectRow(requests: Array<{ account_id: number; provider_account_id: string }>) {
|
||||
const named = requests.find((row) => Number(row.account_id) != 0 && !row.provider_account_id);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BotExtensionsPayload } from "@/src/types";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import countBotConnectors from "../connectors/count-bot-connectors";
|
||||
import grabBotConnectors from "../connectors/grab-bot-connectors";
|
||||
import grabBotConnectorRouters from "../connector-routers/grab-bot-connector-routers";
|
||||
import grabExtensionsOverview from "./grab-extensions-overview";
|
||||
|
||||
type Params = {
|
||||
@@ -33,7 +34,7 @@ export default async function grabBotExtensionsOverview({
|
||||
BunSQLite.sql<{ kind: string }>({ sql: `SELECT kind FROM bots WHERE id = ?`, values: [bot_id] }),
|
||||
]);
|
||||
|
||||
const [overview, connector_count, connector_entries] = await Promise.all([
|
||||
const [overview, connector_count, connector_entries, router_entries] = await Promise.all([
|
||||
grabExtensionsOverview({
|
||||
can_manage: role == "super_admin" || (role == "admin" && bot.payload?.[0]?.kind != "coordinator"),
|
||||
bot_id,
|
||||
@@ -41,11 +42,13 @@ export default async function grabBotExtensionsOverview({
|
||||
}),
|
||||
countBotConnectors({ user_id, bot_id, workspace_id }),
|
||||
grabBotConnectors({ user_id, bot_id, workspace_id }),
|
||||
grabBotConnectorRouters({ user_id, bot_id, workspace_id }),
|
||||
]);
|
||||
|
||||
/**
|
||||
* One icon per app, for the ones a connected account actually reaches
|
||||
* here: a pending sign-in has nothing to use yet.
|
||||
* here, directly or through a router: a pending sign-in has nothing to
|
||||
* use yet.
|
||||
*/
|
||||
const connector_apps = connector_entries
|
||||
.filter((entry) => entry.accounts.some((account) => account.status == "connected"))
|
||||
@@ -55,5 +58,11 @@ export default async function grabBotExtensionsOverview({
|
||||
logo: entry.connector.logo,
|
||||
}));
|
||||
|
||||
return { ...overview, connector_count, connector_apps };
|
||||
for (const app of router_entries.flatMap((entry) => entry.router.apps)) {
|
||||
if (app.accounts && !connector_apps.some((known) => known.id == app.id)) {
|
||||
connector_apps.push({ id: app.id, name: app.name, logo: app.logo });
|
||||
}
|
||||
}
|
||||
|
||||
return { ...overview, connector_count: connector_count + router_entries.length, connector_apps };
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
|
||||
computers: new Map((computers?.payload || []).map((c) => [Number(c.id), c.name || ""])),
|
||||
bot_id: proposal.bot_id,
|
||||
bot_kind: bot.payload?.[0]?.kind || null,
|
||||
user_id: proposal.user_id,
|
||||
}),
|
||||
reason: proposal.reason,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import cleanTranscript from "./clean-transcript";
|
||||
|
||||
describe("cleanTranscript", () => {
|
||||
test("drops Fish Audio's speaker token and sound event", () => {
|
||||
expect(
|
||||
cleanTranscript({
|
||||
text: "<|speaker:0|> [the sound of the alarm] What's the latest on the U.S.-Iran war?",
|
||||
}),
|
||||
).toBe("What's the latest on the U.S.-Iran war?");
|
||||
});
|
||||
|
||||
test("keeps each speaker's line and closes the gaps markup left", () => {
|
||||
expect(
|
||||
cleanTranscript({
|
||||
text: "<|speaker:0|> Hello there [laughs] .\n<|speaker:1|> Hi!",
|
||||
}),
|
||||
).toBe("Hello there.\nHi!");
|
||||
});
|
||||
|
||||
test("a recording with only sounds comes back empty", () => {
|
||||
expect(cleanTranscript({ text: "[music] [applause]" })).toBe("");
|
||||
});
|
||||
|
||||
test("plain speech is left as it is", () => {
|
||||
expect(cleanTranscript({ text: "Send it to Sam (the designer), please." })).toBe(
|
||||
"Send it to Sam (the designer), please.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* A speech model's markup, never words anyone said: special tokens such as
|
||||
* Fish Audio's `<|speaker:0|>`, and the sound events in square brackets that
|
||||
* Fish Audio and ElevenLabs write beside the speech (`[the sound of the
|
||||
* alarm]`, `[laughs]`). Speech never comes out bracketed, so the brackets
|
||||
* are the model's annotations.
|
||||
*/
|
||||
const SpecialToken = /<\|[^|>]*\|>/g;
|
||||
const SoundEvent = /\[[^\]\n]*\]/g;
|
||||
|
||||
/**
|
||||
* The words alone, for the composer and for a bot reading a recording:
|
||||
* markup removed, the spaces it left behind closed up, line breaks between
|
||||
* speakers kept. A recording with no speech in it comes back empty.
|
||||
*/
|
||||
export default function cleanTranscript({ text }: { text: string }) {
|
||||
return text
|
||||
.replace(SpecialToken, " ")
|
||||
.replace(SoundEvent, " ")
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/[ \t]+/g, " ").replace(/ ([.,!?;:])/g, "$1").trim())
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import withCandidates from "../resolve/with-candidates";
|
||||
import type { HarnessAudioInput, HarnessUsage } from "../types";
|
||||
import buildUsageCall from "../usage/build-usage-call";
|
||||
import cleanTranscript from "./clean-transcript";
|
||||
import recordHarnessUsage from "../usage/record-harness-usage";
|
||||
|
||||
type Params = {
|
||||
@@ -28,7 +29,7 @@ type Params = {
|
||||
/**
|
||||
* Turns speech into text with the transcription harness: its
|
||||
* speech-to-text model gets the file, at `/audio/transcriptions` or, on
|
||||
* Alibaba's hosts, at their native multimodal route.
|
||||
* Alibaba's hosts and Vercel AI Gateway, at their own routes.
|
||||
*/
|
||||
export default async function transcribeAudio({
|
||||
audio,
|
||||
@@ -82,7 +83,12 @@ export default async function transcribeAudio({
|
||||
});
|
||||
}
|
||||
|
||||
return { text: text.trim(), usage };
|
||||
/**
|
||||
* Some models mark speakers and sounds in the text
|
||||
* (`<|speaker:0|> [the sound of the alarm] ...`); only the
|
||||
* words go to the composer or the bot.
|
||||
*/
|
||||
return { text: cleanTranscript({ text }), usage };
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import connectMcpServer from "../mcp/connect-mcp-server";
|
||||
import mcpResultToText from "../mcp/mcp-result-to-text";
|
||||
import type { HarnessToolOutput } from "../types";
|
||||
import type { ConnectorProvider } from "./connector-provider";
|
||||
import ensureConnectorEndpoint from "./ensure-connector-endpoint";
|
||||
import expandPreviewResult from "./expand-preview-result";
|
||||
|
||||
type Params = {
|
||||
connector: ConnectorRecord;
|
||||
provider: ConnectorProvider;
|
||||
/**
|
||||
* The account's own owner: the provider session and the sign-in belong
|
||||
* to whoever connected it, even when another person's run uses it.
|
||||
*/
|
||||
user_id: number;
|
||||
account: ConnectorAccountRecord;
|
||||
redact: (text: string) => string;
|
||||
/**
|
||||
* Counts one action against the run's cap, or throws saying what it is.
|
||||
*/
|
||||
takeAction: () => void;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type ConnectorAccountExecutor = {
|
||||
/**
|
||||
* Runs one of the app's tools (its provider name, e.g. GMAIL_SEND_EMAIL)
|
||||
* through this account, as one action.
|
||||
*/
|
||||
call: (params: { tool: string; args: Record<string, unknown>; signal: AbortSignal }) => Promise<HarnessToolOutput>;
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* How one connector account's tools are called, whatever the model sees of
|
||||
* them: its own tool per provider tool (`connectorAccountTools`), or the
|
||||
* router's `connectors_execute` naming one.
|
||||
*
|
||||
* The endpoint is the account's MCP session (`ensureConnectorEndpoint`),
|
||||
* connected on the first call and closed with the run; a provider that
|
||||
* can't pin an account to a session runs the same tool over REST with the
|
||||
* account named in the call.
|
||||
*/
|
||||
export default function connectorAccountExecutor({
|
||||
connector,
|
||||
provider,
|
||||
user_id,
|
||||
account,
|
||||
redact,
|
||||
takeAction,
|
||||
signal,
|
||||
}: Params): ConnectorAccountExecutor {
|
||||
let connection: Promise<Client> | undefined;
|
||||
|
||||
const client = async () => {
|
||||
const endpoint = await ensureConnectorEndpoint({ connector, provider, user_id, account });
|
||||
|
||||
if (endpoint.kind != "mcp") return null;
|
||||
|
||||
connection ||= connectMcpServer({ url: endpoint.url, headers: endpoint.headers, signal }).catch((error: unknown) => {
|
||||
connection = undefined;
|
||||
throw error;
|
||||
});
|
||||
|
||||
return connection;
|
||||
};
|
||||
|
||||
const viaRest = ({ tool, args }: { tool: string; args: Record<string, unknown> }) =>
|
||||
provider.execute({ tool, args, account: account.provider_account_id, user_id });
|
||||
|
||||
return {
|
||||
call: async ({ tool, args, signal: callSignal }) => {
|
||||
takeAction();
|
||||
|
||||
try {
|
||||
const connected = await client();
|
||||
|
||||
if (!connected) {
|
||||
const result = await viaRest({ tool, args });
|
||||
|
||||
// Already the provider's REST answer, so there is no
|
||||
// fuller call to ask for a cut result again.
|
||||
return redact(
|
||||
await expandPreviewResult({
|
||||
text: typeof result == "string" ? result : JSON.stringify(result, null, 2),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const { text, images } = mcpResultToText({
|
||||
result: await connected.callTool({ name: tool, arguments: args }, undefined, {
|
||||
signal: callSignal,
|
||||
timeout: AppData.ConnectorToolTimeoutMs,
|
||||
resetTimeoutOnProgress: true,
|
||||
}),
|
||||
});
|
||||
|
||||
// The MCP router answers a large result with a preview. The
|
||||
// provider's REST API returns the whole one, so a preview is
|
||||
// asked again there: one more action of the same tool,
|
||||
// counted as the one action this call made.
|
||||
const answer = redact(await expandPreviewResult({ text, retry: () => viaRest({ tool, args }) }));
|
||||
|
||||
if (!images.length) return answer;
|
||||
|
||||
return {
|
||||
text: answer,
|
||||
images: images.map(({ data, mime_type }) => ({
|
||||
url: `data:${mime_type};base64,${data}`,
|
||||
focus: `This came back from ${connector.name}. Describe what it shows and quote any text in it.`,
|
||||
redact,
|
||||
})),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) error.message = redact(error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
close: async () => {
|
||||
if (!connection) return;
|
||||
|
||||
await (await connection.catch(() => null))?.close().catch(() => {});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,25 +1,22 @@
|
||||
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import mcpToolName from "@/src/utils/mcp-tool-name";
|
||||
import connectMcpServer from "../mcp/connect-mcp-server";
|
||||
import mcpResultToText from "../mcp/mcp-result-to-text";
|
||||
import type { HarnessTool } from "../types";
|
||||
import type { ConnectorProvider } from "./connector-provider";
|
||||
import ensureConnectorEndpoint from "./ensure-connector-endpoint";
|
||||
import expandPreviewResult from "./expand-preview-result";
|
||||
import type { ConnectorAccountExecutor } from "./connector-account-executor";
|
||||
|
||||
type Params = {
|
||||
connector: ConnectorRecord;
|
||||
provider: ConnectorProvider;
|
||||
user_id: number;
|
||||
/**
|
||||
* The account to call through. Null when the connector is offered in a
|
||||
* reply the user follows but has no account yet: its tools exist so the
|
||||
* bot can ask, and calling one asks through `onMissingAccount` instead
|
||||
* of running.
|
||||
* The account the tools run through. Null when the connector is offered
|
||||
* in a reply the user follows but has no working account yet: its tools
|
||||
* exist so the bot can ask, and calling one asks through
|
||||
* `onMissingAccount` instead of running.
|
||||
*/
|
||||
account: ConnectorAccountRecord | null;
|
||||
/**
|
||||
* How a call runs through that account (`connectorAccountExecutor`).
|
||||
* Null exactly when `account` is.
|
||||
*/
|
||||
executor: ConnectorAccountExecutor | null;
|
||||
onMissingAccount?: () => Promise<string>;
|
||||
/**
|
||||
* The app's slug, or `<app slug>-<account slug>` once the user has more
|
||||
@@ -30,57 +27,24 @@ type Params = {
|
||||
* Names the run already uses: they win.
|
||||
*/
|
||||
names: Set<string>;
|
||||
redact: (text: string) => string;
|
||||
/**
|
||||
* Counts one action against the run's cap, or throws saying what it is.
|
||||
*/
|
||||
takeAction: () => void;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type ConnectorAccountTools = {
|
||||
tools: HarnessTool[];
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* One connector account's tools, as `<namespace>__<tool>`, all deferred.
|
||||
*
|
||||
* The endpoint is the account's MCP session (`ensureConnectorEndpoint`),
|
||||
* connected on the first call and closed with the run; a provider that
|
||||
* can't pin an account to a session runs the same tools over REST with the
|
||||
* account named in each call, so the model never sees a difference.
|
||||
* One connector account's tools, as `<namespace>__<tool>`, all deferred:
|
||||
* an app given to the bot directly, where every provider tool is a tool of
|
||||
* the run's own. An app reached through a router is named through
|
||||
* `connectors_search_tools` instead and kept out of the prompt.
|
||||
*/
|
||||
export default function connectorAccountTools({
|
||||
connector,
|
||||
provider,
|
||||
user_id,
|
||||
account,
|
||||
executor,
|
||||
onMissingAccount,
|
||||
namespace,
|
||||
names,
|
||||
redact,
|
||||
takeAction,
|
||||
signal,
|
||||
}: Params): ConnectorAccountTools {
|
||||
}: Params): HarnessTool[] {
|
||||
const listed = connector.tools.filter((tool) => !connector.excluded_tools.includes(tool.name));
|
||||
const tools: HarnessTool[] = [];
|
||||
let connection: Promise<Client> | undefined;
|
||||
|
||||
const client = async () => {
|
||||
if (!account) return null;
|
||||
|
||||
const endpoint = await ensureConnectorEndpoint({ connector, provider, user_id, account });
|
||||
|
||||
if (endpoint.kind != "mcp") return null;
|
||||
|
||||
connection ||= connectMcpServer({ url: endpoint.url, headers: endpoint.headers, signal }).catch((error: unknown) => {
|
||||
connection = undefined;
|
||||
throw error;
|
||||
});
|
||||
|
||||
return connection;
|
||||
};
|
||||
|
||||
for (const tool of listed) {
|
||||
const name = mcpToolName({ slug: namespace, name: tool.name });
|
||||
@@ -93,85 +57,18 @@ export default function connectorAccountTools({
|
||||
description: `${connector.name}${account ? ` (${account.label})` : ""}: ${tool.description || tool.name}`,
|
||||
parameters: tool.input_schema,
|
||||
deferred: true,
|
||||
run: async ({ args, signal: runSignal }) => {
|
||||
if (!account) {
|
||||
run: async ({ args, signal }) => {
|
||||
if (!executor) {
|
||||
throw new Error(
|
||||
(await onMissingAccount?.()) ||
|
||||
`No account is connected to ${connector.name}, so this didn't run. Connect one in Settings > Connectors.`,
|
||||
);
|
||||
}
|
||||
|
||||
takeAction();
|
||||
|
||||
try {
|
||||
const connected = await client();
|
||||
|
||||
if (!connected) {
|
||||
const result = await provider.execute({
|
||||
tool: tool.name,
|
||||
args,
|
||||
account: account.provider_account_id,
|
||||
user_id,
|
||||
});
|
||||
|
||||
// Already the provider's REST answer, so there is no
|
||||
// fuller call to ask for a cut result again.
|
||||
return redact(
|
||||
await expandPreviewResult({
|
||||
text: typeof result == "string" ? result : JSON.stringify(result, null, 2),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const { text, images } = mcpResultToText({
|
||||
result: await connected.callTool({ name: tool.name, arguments: args }, undefined, {
|
||||
signal: runSignal,
|
||||
timeout: AppData.ConnectorToolTimeoutMs,
|
||||
resetTimeoutOnProgress: true,
|
||||
}),
|
||||
});
|
||||
|
||||
// The MCP router answers a large result with a preview.
|
||||
// The provider's REST API returns the whole one, so a
|
||||
// preview is asked again there: one more action of the
|
||||
// same tool, counted as the one action this call made.
|
||||
const answer = redact(
|
||||
await expandPreviewResult({
|
||||
text,
|
||||
retry: () =>
|
||||
provider.execute({
|
||||
tool: tool.name,
|
||||
args,
|
||||
account: account.provider_account_id,
|
||||
user_id,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
if (!images.length) return answer;
|
||||
|
||||
return {
|
||||
text: answer,
|
||||
images: images.map(({ data, mime_type }) => ({
|
||||
url: `data:${mime_type};base64,${data}`,
|
||||
focus: `This came back from ${connector.name}. Describe what it shows and quote any text in it.`,
|
||||
redact,
|
||||
})),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) error.message = redact(error.message);
|
||||
throw error;
|
||||
}
|
||||
return executor.call({ tool: tool.name, args, signal });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
tools,
|
||||
close: async () => {
|
||||
if (!connection) return;
|
||||
|
||||
await (await connection.catch(() => null))?.close().catch(() => {});
|
||||
},
|
||||
};
|
||||
}
|
||||
return tools;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ConnectorAccountRecord, ConnectorRecord, McpToolInfo } from "@/src/types";
|
||||
import type { ConnectorAccountExecutor } from "./connector-account-executor";
|
||||
|
||||
/**
|
||||
* One tool of one connector account, as the router knows it: the name the
|
||||
* run calls it by (`<namespace>__<TOOL>`), the provider's own tool, and how
|
||||
* it runs. An app offered without a working account (a reply the user
|
||||
* follows) has entries with no executor: running one asks them to connect.
|
||||
*/
|
||||
export type ConnectorRouterEntry = {
|
||||
name: string;
|
||||
tool: McpToolInfo;
|
||||
connector: ConnectorRecord;
|
||||
account: ConnectorAccountRecord | null;
|
||||
/**
|
||||
* Whose account it is, when it isn't the run's own user's.
|
||||
*/
|
||||
owner_name?: string;
|
||||
/**
|
||||
* The tools' shared prefix, `gmail` or `gmail-work`.
|
||||
*/
|
||||
namespace: string;
|
||||
executor: ConnectorAccountExecutor | null;
|
||||
onMissingAccount?: () => Promise<string>;
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { ConnectorProviders } from "@/src/dict/connector-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import { decrypt, encrypt } from "@/src/utils/crypt";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import connectorAccountGoneMessage from "./connector-account-gone";
|
||||
@@ -157,10 +158,21 @@ export default async function ensureConnectorEndpoint({
|
||||
url = endpoint.url;
|
||||
headers = await encrypt(JSON.stringify(endpoint.headers || {}));
|
||||
expires_at = endpoint.expires_at || expires_at;
|
||||
} catch {
|
||||
} catch (error: unknown) {
|
||||
// A provider that can't pin one account to a session still executes
|
||||
// each tool with the account named, so the run loses nothing but the
|
||||
// session. The call itself reports whatever is really wrong.
|
||||
// session. The call itself reports whatever is really wrong, but the
|
||||
// fallback is logged: it lasts `ConnectorRestRetryMs`, and a session
|
||||
// that never opens (a refused key, a changed API) was otherwise
|
||||
// invisible behind tools that still half-worked.
|
||||
await logError({
|
||||
title: "Connector session fell back to REST",
|
||||
category: "system",
|
||||
error,
|
||||
user_id,
|
||||
metadata: { connector_id: connector.id, app: connector.app },
|
||||
}).catch(() => {});
|
||||
|
||||
session_id = "rest";
|
||||
expires_at = now + AppData.ConnectorRestRetryMs;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import missingRequiredArgs from "./missing-required-args";
|
||||
|
||||
describe("missingRequiredArgs", () => {
|
||||
const schema = { type: "object", properties: { to: {}, subject: {}, body: {} }, required: ["to", "subject"] };
|
||||
|
||||
test("names each required argument a call left out or left empty", () => {
|
||||
expect(missingRequiredArgs({ schema, args: { to: "[email protected]" } })).toEqual(["subject"]);
|
||||
expect(missingRequiredArgs({ schema, args: { to: "", subject: null } })).toEqual(["to", "subject"]);
|
||||
});
|
||||
|
||||
test("is satisfied by every required argument, and by a schema with none", () => {
|
||||
expect(missingRequiredArgs({ schema, args: { to: "[email protected]", subject: "Hi" } })).toEqual([]);
|
||||
expect(missingRequiredArgs({ schema: { type: "object" }, args: {} })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a false or zero value counts as given", () => {
|
||||
expect(missingRequiredArgs({ schema: { required: ["flag", "count"] }, args: { flag: false, count: 0 } })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
type Params = {
|
||||
schema: Record<string, unknown>;
|
||||
args: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The arguments a tool's schema requires that a call left out, so the
|
||||
* router can send the call back before it costs an action: the provider
|
||||
* would bill the call and then refuse it.
|
||||
*/
|
||||
export default function missingRequiredArgs({ schema, args }: Params): string[] {
|
||||
const required = Array.isArray(schema?.required) ? (schema.required as unknown[]) : [];
|
||||
|
||||
return required
|
||||
.filter((key): key is string => typeof key == "string")
|
||||
.filter((key) => args[key] === undefined || args[key] === null || args[key] === "");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* A provider's error field in words: Composio gives a string or an object
|
||||
* with a message, and an object read as text was "[object Object]".
|
||||
*/
|
||||
export default function composioReason({ error }: { error: unknown }): string {
|
||||
if (!error) return "it gave no reason";
|
||||
if (typeof error == "string") return error;
|
||||
|
||||
const object = error as { message?: unknown; error?: unknown };
|
||||
|
||||
if (typeof object.message == "string" && object.message) return object.message;
|
||||
if (typeof object.error == "string" && object.error) return object.error;
|
||||
|
||||
try {
|
||||
return JSON.stringify(error).slice(0, 500);
|
||||
} catch {
|
||||
return "it gave no reason";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import composioTime from "./composio-time";
|
||||
|
||||
/**
|
||||
* A session's expiry stored as Composio's raw ISO string read as NaN, so no
|
||||
* cached session was ever reused and every run opened a new one.
|
||||
*/
|
||||
describe("composioTime", () => {
|
||||
test("reads an ISO string as unix ms", () => {
|
||||
expect(composioTime({ value: "2027-01-01T00:00:00Z" })).toBe(Date.parse("2027-01-01T00:00:00Z"));
|
||||
});
|
||||
|
||||
test("takes unix ms as it is and unix seconds as ms", () => {
|
||||
expect(composioTime({ value: 1_800_000_000_000 })).toBe(1_800_000_000_000);
|
||||
expect(composioTime({ value: 1_800_000_000 })).toBe(1_800_000_000_000);
|
||||
});
|
||||
|
||||
test("leaves out what it can't read", () => {
|
||||
expect(composioTime({ value: undefined })).toBeUndefined();
|
||||
expect(composioTime({ value: "" })).toBeUndefined();
|
||||
expect(composioTime({ value: "soon" })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* A time Composio gives as an ISO string (or, sometimes, unix ms or
|
||||
* seconds) as unix ms, or undefined when it can't be read. A raw ISO string
|
||||
* stored as a session's expiry read as NaN, so no cached session was ever
|
||||
* reused and every run opened a new one.
|
||||
*/
|
||||
export default function composioTime({ value }: { value: unknown }): number | undefined {
|
||||
if (value == null || value === "") return undefined;
|
||||
|
||||
if (typeof value == "number" && Number.isFinite(value)) return value < 1e12 ? value * 1000 : value;
|
||||
|
||||
const parsed = Date.parse(String(value));
|
||||
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import type {
|
||||
ProviderAccountStatus,
|
||||
StartConnectParams,
|
||||
} from "../connector-provider";
|
||||
import composioReason from "./composio-reason";
|
||||
import composioTime from "./composio-time";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -275,7 +277,7 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
// ever reaches the provider, never a model.
|
||||
headers: { "x-api-key": key, ...(mcp.headers || {}) },
|
||||
session_id: answer.session_id || answer.id,
|
||||
expires_at: answer.expires_at || mcp.expires_at || undefined,
|
||||
expires_at: composioTime({ value: answer.expires_at || mcp.expires_at }),
|
||||
} satisfies ConnectorEndpoint;
|
||||
},
|
||||
|
||||
@@ -323,7 +325,7 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
url: answer.redirect_url,
|
||||
auth_config_id: config,
|
||||
provider_account_id: answer.connected_account_id ? String(answer.connected_account_id) : undefined,
|
||||
expires_at: answer.expires_at ? Date.parse(String(answer.expires_at)) : undefined,
|
||||
expires_at: composioTime({ value: answer.expires_at }),
|
||||
};
|
||||
},
|
||||
|
||||
@@ -371,7 +373,7 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
|
||||
if (answer.successful === false) {
|
||||
throw new AppError(
|
||||
`Composio failed ${tool}: ${answer.error || "it gave no reason"}`,
|
||||
`Composio failed ${tool}: ${composioReason({ error: answer.error })}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import rankConnectorTools, { type RankableConnectorTool } from "./rank-connector-tools";
|
||||
|
||||
const tool = ({ app, tool, description }: { app: string; tool: string; description: string }): RankableConnectorTool => ({
|
||||
name: `${app}__${tool}`,
|
||||
tool,
|
||||
app_name: app.charAt(0).toUpperCase() + app.slice(1),
|
||||
app_slug: app,
|
||||
description,
|
||||
});
|
||||
|
||||
const Tools = [
|
||||
tool({ app: "gmail", tool: "GMAIL_FETCH_EMAILS", description: "Fetch a list of email messages from the inbox." }),
|
||||
tool({ app: "gmail", tool: "GMAIL_SEND_EMAIL", description: "Send an email message to one or more recipients." }),
|
||||
tool({ app: "gmail", tool: "GMAIL_CREATE_EMAIL_DRAFT", description: "Create a draft email without sending it." }),
|
||||
tool({ app: "slack", tool: "SLACK_SEND_MESSAGE", description: "Post a message to a Slack channel." }),
|
||||
tool({ app: "github", tool: "GITHUB_CREATE_AN_ISSUE", description: "Create a new issue in a repository." }),
|
||||
];
|
||||
|
||||
describe("rankConnectorTools", () => {
|
||||
test("puts the tool whose name is the request first", () => {
|
||||
const found = rankConnectorTools({ tools: Tools, query: "send an email", limit: 3 });
|
||||
|
||||
expect(found[0]!.tool).toBe("GMAIL_SEND_EMAIL");
|
||||
});
|
||||
|
||||
test("reads plural and -ing forms as the plain word", () => {
|
||||
const found = rankConnectorTools({ tools: Tools, query: "fetching emails", limit: 1 });
|
||||
|
||||
expect(found[0]!.tool).toBe("GMAIL_FETCH_EMAILS");
|
||||
});
|
||||
|
||||
test("an app's name narrows the match", () => {
|
||||
const found = rankConnectorTools({ tools: Tools, query: "slack send message", limit: 2 });
|
||||
|
||||
expect(found[0]!.tool).toBe("SLACK_SEND_MESSAGE");
|
||||
});
|
||||
|
||||
test("a word inside an app's name still finds it", () => {
|
||||
const found = rankConnectorTools({ tools: Tools, query: "mail draft", limit: 1 });
|
||||
|
||||
expect(found[0]!.tool).toBe("GMAIL_CREATE_EMAIL_DRAFT");
|
||||
});
|
||||
|
||||
test("nothing that matches no word, and an empty query lists in order", () => {
|
||||
expect(rankConnectorTools({ tools: Tools, query: "calendar", limit: 5 })).toEqual([]);
|
||||
expect(rankConnectorTools({ tools: Tools, query: "", limit: 2 }).map((entry) => entry.tool)).toEqual([
|
||||
"GMAIL_FETCH_EMAILS",
|
||||
"GMAIL_SEND_EMAIL",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
export type RankableConnectorTool = {
|
||||
/**
|
||||
* The name the run calls it by: `<namespace>__<TOOL>`.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The provider's own tool name, e.g. GMAIL_SEND_EMAIL.
|
||||
*/
|
||||
tool: string;
|
||||
/**
|
||||
* The app's shown name and slug, e.g. Gmail and gmail.
|
||||
*/
|
||||
app_name: string;
|
||||
app_slug: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
type Params<T extends RankableConnectorTool> = {
|
||||
tools: T[];
|
||||
query: string;
|
||||
limit: number;
|
||||
};
|
||||
|
||||
const StopWords = new Set(["a", "an", "the", "to", "of", "in", "on", "for", "and", "or", "my", "me", "with", "from", "by", "is", "it"]);
|
||||
|
||||
/**
|
||||
* A word's plain form, so "emails", "sending" and "sent" meet the tool's
|
||||
* "email" and "send".
|
||||
*/
|
||||
function stem({ word }: { word: string }) {
|
||||
if (word == "sent") return "send";
|
||||
if (word.length > 5 && word.endsWith("ing")) return word.slice(0, -3);
|
||||
if (word.length > 4 && word.endsWith("es") && !word.endsWith("ses")) return word.slice(0, -2);
|
||||
if (word.length > 3 && word.endsWith("s") && !word.endsWith("ss")) return word.slice(0, -1);
|
||||
|
||||
return word;
|
||||
}
|
||||
|
||||
function words({ text }: { text: string }) {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.split(/[^a-z0-9]+/)
|
||||
.filter((word) => word.length > 1 && !StopWords.has(word))
|
||||
.map((word) => stem({ word }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The connector tools that fit a plain-words query, best first, for
|
||||
* `connectors_search_tools`. Read from the tools the app already stored, so
|
||||
* a search costs no provider call and no action.
|
||||
*
|
||||
* A word scores most when it is a whole part of the tool's name
|
||||
* (`send` in GMAIL_SEND_EMAIL), then when it names the app, then when it is
|
||||
* only inside the name (`mail` in gmail) or the description. A tool that
|
||||
* matches every word of the query ranks above one that matches more often
|
||||
* but not all of them. An empty query lists the tools in their order.
|
||||
*/
|
||||
export default function rankConnectorTools<T extends RankableConnectorTool>({ tools, query, limit }: Params<T>): T[] {
|
||||
const terms = [...new Set(words({ text: query }))];
|
||||
|
||||
if (!terms.length) return tools.slice(0, limit);
|
||||
|
||||
const scored = tools.map((entry, index) => {
|
||||
const name_parts = new Set(words({ text: entry.tool }));
|
||||
const app_parts = new Set([...words({ text: entry.app_name }), ...words({ text: entry.app_slug })]);
|
||||
const name_text = `${entry.tool} ${entry.app_name} ${entry.app_slug}`.toLowerCase();
|
||||
const description_parts = new Set(words({ text: entry.description }));
|
||||
let score = 0;
|
||||
let matched = 0;
|
||||
|
||||
for (const term of terms) {
|
||||
let term_score = 0;
|
||||
|
||||
if (name_parts.has(term)) term_score = 4;
|
||||
else if (app_parts.has(term)) term_score = 3;
|
||||
else if (term.length > 2 && name_text.includes(term)) term_score = 2;
|
||||
|
||||
if (description_parts.has(term)) term_score += 1;
|
||||
|
||||
if (term_score > 0) matched += 1;
|
||||
|
||||
score += term_score;
|
||||
}
|
||||
|
||||
if (matched == terms.length) score += 3;
|
||||
|
||||
return { entry, index, score, matched };
|
||||
});
|
||||
|
||||
return scored
|
||||
.filter((item) => item.score > 0)
|
||||
.sort((a, b) => b.matched - a.matched || b.score - a.score || a.index - b.index)
|
||||
.slice(0, limit)
|
||||
.map((item) => item.entry);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ConnectorRouterEntry } from "./connector-router-entry";
|
||||
|
||||
type Params = {
|
||||
entries: ConnectorRouterEntry[];
|
||||
/**
|
||||
* What the model named: the full `<namespace>__<TOOL>`, or the
|
||||
* provider's own name alone (GMAIL_SEND_EMAIL) when it left the
|
||||
* namespace off.
|
||||
*/
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type ResolvedConnectorRouterEntry = { entry: ConnectorRouterEntry } | { problem: string };
|
||||
|
||||
/**
|
||||
* The tool a router call means, or what to tell the model when it can't be
|
||||
* told apart. A provider name alone is accepted when only one account has
|
||||
* that tool; with two accounts the model has to say which one, since
|
||||
* guessing would act on the wrong mailbox.
|
||||
*/
|
||||
export default function resolveConnectorRouterEntry({ entries, name }: Params): ResolvedConnectorRouterEntry {
|
||||
const wanted = name.trim();
|
||||
const exact = entries.find((entry) => entry.name == wanted);
|
||||
|
||||
if (exact) return { entry: exact };
|
||||
|
||||
const by_tool = entries.filter((entry) => entry.tool.name.toLowerCase() == wanted.toLowerCase());
|
||||
|
||||
if (by_tool.length == 1) return { entry: by_tool[0]! };
|
||||
|
||||
if (by_tool.length > 1) {
|
||||
return {
|
||||
problem: `"${wanted}" is in more than one account. Name the one you mean: ${by_tool.map((entry) => entry.name).join(", ")}.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
problem: `There is no connector tool called "${wanted}". Find the right one with connectors_search_tools and use the name it gives.`,
|
||||
};
|
||||
}
|
||||
@@ -49,8 +49,13 @@ mock.module("@/src/harness/providers/grab-harness-adapter", () => ({
|
||||
},
|
||||
}),
|
||||
}));
|
||||
mock.module("@/src/harness/text/grab-chat-params", () => ({
|
||||
default: async () => ({ source: "default", paramsFor: () => ({}) }),
|
||||
/**
|
||||
* The setting under `grabChatParams`, not `grabChatParams` itself: Bun's
|
||||
* `mock.restore()` doesn't undo `mock.module`, so a stubbed
|
||||
* `grabChatParams` leaked into its own tests whenever this file ran first.
|
||||
*/
|
||||
mock.module("@/src/functions/backend/db/harness/grab-harness-setting", () => ({
|
||||
default: async () => ({ harness: "vision", fallback: true, enabled: true, options: {}, source: "default" }),
|
||||
}));
|
||||
mock.module("@/src/harness/usage/record-harness-usage", () => ({
|
||||
default: async () => {},
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* What the audio formats the browser records are called as MIME types.
|
||||
* Safari's `audio/mp4` recording arrives here as `m4a`, which no browser
|
||||
* spells as a MIME type.
|
||||
*/
|
||||
const AudioMimeTypes: Record<string, string> = {
|
||||
m4a: "audio/mp4",
|
||||
mp4: "audio/mp4",
|
||||
mp3: "audio/mpeg",
|
||||
ogg: "audio/ogg",
|
||||
opus: "audio/ogg",
|
||||
};
|
||||
|
||||
/**
|
||||
* The MIME type of a recording's format, for a provider that takes the
|
||||
* audio inline (a data URL or base64 with its media type).
|
||||
*/
|
||||
export default function audioMimeType({ format }: { format: string }) {
|
||||
const key = format.toLowerCase();
|
||||
|
||||
return AudioMimeTypes[key] || `audio/${key}`;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
|
||||
import audioMimeType from "./audio-mime-type";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
type Params = {
|
||||
@@ -10,19 +11,6 @@ type Params = {
|
||||
signal: AbortSignal;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the audio formats the browser records are called as MIME types.
|
||||
* DashScope takes a data URL, and Safari's `audio/mp4` recording arrives
|
||||
* here as `m4a`, which no browser spells as a MIME type.
|
||||
*/
|
||||
const AudioMimeTypes: Record<string, string> = {
|
||||
m4a: "audio/mp4",
|
||||
mp4: "audio/mp4",
|
||||
mp3: "audio/mpeg",
|
||||
ogg: "audio/ogg",
|
||||
opus: "audio/ogg",
|
||||
};
|
||||
|
||||
/**
|
||||
* Qwen-ASR on Alibaba's native multimodal route. The Token Plan host and the
|
||||
* workspace Model Studio hosts have no `/audio/transcriptions` at all: the
|
||||
@@ -43,7 +31,7 @@ export default async function transcribeNative({
|
||||
const { provider, model } = candidate;
|
||||
const name = provider.name || "Alibaba Cloud";
|
||||
const format = audio.format.toLowerCase();
|
||||
const mime_type = AudioMimeTypes[format] || `audio/${format}`;
|
||||
const mime_type = audioMimeType({ format });
|
||||
const data_url = `data:${mime_type};base64,${Buffer.from(audio.data).toString("base64")}`;
|
||||
const hint = languageHint({ language });
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ type Params = {
|
||||
* not under the provider's `/compatible-mode/v1` base).
|
||||
*/
|
||||
base_url?: string;
|
||||
/**
|
||||
* Sent beside the provider's own headers, for a route that reads its
|
||||
* model or protocol version from them (Vercel AI Gateway's `/v4/ai/*`).
|
||||
*/
|
||||
headers?: Record<string, string>;
|
||||
/**
|
||||
* Deadline for the whole body once the headers are in. Defaults to a
|
||||
* generous span so a streamed answer isn't cut off by the header timeout.
|
||||
@@ -50,12 +55,13 @@ export default async function providerRequest({
|
||||
timeout_ms = AppData.HarnessRequestTimeoutMs,
|
||||
body_timeout_ms = AppData.HarnessBodyTimeoutMs,
|
||||
base_url,
|
||||
headers: extra_headers,
|
||||
candidate_key,
|
||||
}: Params): Promise<Response> {
|
||||
const provider_name =
|
||||
provider.name || grabProviderPreset({ kind: provider.kind }).title;
|
||||
const url = `${(base_url || provider.base_url).replace(/\/+$/, "")}${path}`;
|
||||
const headers = grabProviderHeaders({ provider });
|
||||
const headers = { ...grabProviderHeaders({ provider }), ...extra_headers };
|
||||
|
||||
if (json !== undefined) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { HarnessAdapter } from "../../types";
|
||||
import HarnessError from "../../harness-error";
|
||||
import providerRequest from "./provider-request";
|
||||
import { isVercelGatewayHost } from "./vercel-gateway-hosts";
|
||||
import vercelGatewaySpeak from "./vercel-gateway-speak";
|
||||
|
||||
/**
|
||||
* `POST /audio/speech`. Resolves once the provider answers, with its
|
||||
* audio as a stream (providers send it in chunks as it's made).
|
||||
* `POST /audio/speech` (Vercel AI Gateway: its own route). Resolves once
|
||||
* the provider answers, with its audio as a stream (providers send it in
|
||||
* chunks as it's made).
|
||||
*/
|
||||
const speak: HarnessAdapter["speak"] = async ({
|
||||
candidate,
|
||||
@@ -13,6 +16,10 @@ const speak: HarnessAdapter["speak"] = async ({
|
||||
format = "mp3",
|
||||
signal,
|
||||
}) => {
|
||||
if (isVercelGatewayHost({ base_url: candidate.provider.base_url })) {
|
||||
return await vercelGatewaySpeak({ candidate, text, voice, format, signal });
|
||||
}
|
||||
|
||||
const res = await providerRequest({
|
||||
provider: candidate.provider,
|
||||
path: "/audio/speech",
|
||||
|
||||
@@ -120,6 +120,28 @@ describe("transcribe", () => {
|
||||
expect(request).toBeNull();
|
||||
});
|
||||
|
||||
test("Vercel AI Gateway is asked on its own route, not /v1/audio/transcriptions", async () => {
|
||||
payload = { text: " hello " };
|
||||
|
||||
const result = await transcribe({
|
||||
candidate: {
|
||||
...candidate,
|
||||
provider: { kind: "custom", base_url: "https://ai-gateway.vercel.sh/v1", name: "Vercel" },
|
||||
model: { slug: "openai/gpt-transcribe" },
|
||||
} as unknown as HarnessCandidate,
|
||||
audio: { data: new Uint8Array([1, 2, 3]), format: "m4a" },
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("hello");
|
||||
expect(request.base_url).toBe("https://ai-gateway.vercel.sh");
|
||||
expect(request.path).toBe("/v4/ai/transcription-model");
|
||||
expect(request.form).toBeUndefined();
|
||||
expect(request.headers["ai-model-id"]).toBe("openai/gpt-transcribe");
|
||||
expect(request.headers["ai-transcription-model-specification-version"]).toBe("4");
|
||||
expect(request.json).toEqual({ audio: "AQID", mediaType: "audio/mp4" });
|
||||
});
|
||||
|
||||
test("an ASR model on another provider keeps the OpenAI-style upload", async () => {
|
||||
payload = { text: "hello" };
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { HarnessAdapter } from "../../types";
|
||||
import { isDashScopeHost } from "./dashscope-hosts";
|
||||
import transcribeNative from "./dashscope-native-transcribe";
|
||||
import providerRequest from "./provider-request";
|
||||
import { isVercelGatewayHost } from "./vercel-gateway-hosts";
|
||||
import vercelGatewayTranscribe from "./vercel-gateway-transcribe";
|
||||
|
||||
/**
|
||||
* The native Qwen-ASR models: the only synchronous speech models Alibaba's
|
||||
@@ -18,8 +20,8 @@ const AsyncOnlyAsrModel = /filetrans|paraformer/i;
|
||||
|
||||
/**
|
||||
* `POST /audio/transcriptions` as an OpenAI-style file upload, which
|
||||
* OpenRouter, OpenAI, Groq and local servers all take. Alibaba's hosts have
|
||||
* no such route, so their ASR models go to the native call instead.
|
||||
* OpenRouter, OpenAI, Groq and local servers all take. Alibaba's hosts and
|
||||
* Vercel AI Gateway have no such route, so they get their own calls instead.
|
||||
*/
|
||||
const transcribe: HarnessAdapter["transcribe"] = async ({
|
||||
candidate,
|
||||
@@ -39,6 +41,10 @@ const transcribe: HarnessAdapter["transcribe"] = async ({
|
||||
return await transcribeNative({ candidate, audio, language, signal });
|
||||
}
|
||||
|
||||
if (isVercelGatewayHost({ base_url: candidate.provider.base_url })) {
|
||||
return await vercelGatewayTranscribe({ candidate, audio, signal });
|
||||
}
|
||||
|
||||
const form = new FormData();
|
||||
|
||||
form.append("model", candidate.model.slug);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Vercel AI Gateway. Its OpenAI-compatible API (`/v1`) has chat, embeddings
|
||||
* and images but no `/audio/*` routes: speech and transcription live on its
|
||||
* own `/v4/ai/*` API at the host root, with the model in a header.
|
||||
*/
|
||||
export function isVercelGatewayHost({ base_url }: { base_url?: string | null }) {
|
||||
if (!base_url) return false;
|
||||
|
||||
try {
|
||||
return new URL(base_url).hostname == "ai-gateway.vercel.sh";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The headers the gateway's `/v4/ai/*` routes read the call from: which
|
||||
* model, and which version of its protocol and the model's spec.
|
||||
*/
|
||||
export function vercelGatewayHeaders({
|
||||
model,
|
||||
spec,
|
||||
}: {
|
||||
model: string;
|
||||
spec: "transcription" | "speech";
|
||||
}): Record<string, string> {
|
||||
return {
|
||||
"ai-gateway-protocol-version": "0.0.1",
|
||||
[`ai-${spec}-model-specification-version`]: "4",
|
||||
"ai-model-id": model,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
|
||||
let payload: unknown = null;
|
||||
let request: any = null;
|
||||
|
||||
mock.module("./provider-request", () => ({
|
||||
default: async (args: any) => {
|
||||
request = args;
|
||||
|
||||
return { json: async () => payload, body: null, headers: new Headers() };
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: speak } = await import("./speak");
|
||||
|
||||
const candidate = {
|
||||
key: "speech:tts",
|
||||
provider: { kind: "custom", base_url: "https://ai-gateway.vercel.sh/v1", name: "Vercel" },
|
||||
model: { slug: "openai/tts-1" },
|
||||
source: "pinned",
|
||||
} as unknown as HarnessCandidate;
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
afterAll(() => mock.restore());
|
||||
beforeEach(() => {
|
||||
payload = null;
|
||||
request = null;
|
||||
});
|
||||
|
||||
describe("speak on Vercel AI Gateway", () => {
|
||||
test("asks the gateway's own route and streams the base64 audio it answers", async () => {
|
||||
payload = { audio: Buffer.from([1, 2, 3]).toString("base64"), warnings: [] };
|
||||
|
||||
const result = await speak({ candidate, text: "hi", voice: "alloy", signal });
|
||||
|
||||
expect(request.base_url).toBe("https://ai-gateway.vercel.sh");
|
||||
expect(request.path).toBe("/v4/ai/speech-model");
|
||||
expect(request.headers["ai-model-id"]).toBe("openai/tts-1");
|
||||
expect(request.headers["ai-speech-model-specification-version"]).toBe("4");
|
||||
expect(request.json).toEqual({ text: "hi", voice: "alloy", outputFormat: "mp3" });
|
||||
expect(result.media_type).toBe("audio/mpeg");
|
||||
expect([...new Uint8Array(await new Response(result.stream).arrayBuffer())]).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
test("an answer with no audio is a retryable failure", async () => {
|
||||
payload = { warnings: [] };
|
||||
|
||||
const error = await speak({ candidate, text: "hi", signal }).catch((thrown: unknown) => thrown);
|
||||
|
||||
expect(error).toBeInstanceOf(HarnessError);
|
||||
expect(error).toMatchObject({ retryable: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessAudioStream, HarnessSpeakParams } from "../../types";
|
||||
import providerRequest from "./provider-request";
|
||||
import { vercelGatewayHeaders } from "./vercel-gateway-hosts";
|
||||
|
||||
/**
|
||||
* Vercel AI Gateway's own speech route, `POST /v4/ai/speech-model` on the
|
||||
* host root: the model goes in `ai-model-id` and the audio comes back whole,
|
||||
* base64 in a JSON body, so it's handed on as a one-chunk stream. The
|
||||
* gateway's `/v1/audio/speech` doesn't exist (404).
|
||||
*/
|
||||
export default async function vercelGatewaySpeak({
|
||||
candidate,
|
||||
text,
|
||||
voice,
|
||||
format = "mp3",
|
||||
signal,
|
||||
}: HarnessSpeakParams): Promise<HarnessAudioStream> {
|
||||
const { provider, model } = candidate;
|
||||
|
||||
const res = await providerRequest({
|
||||
provider,
|
||||
base_url: new URL(provider.base_url).origin,
|
||||
path: "/v4/ai/speech-model",
|
||||
headers: vercelGatewayHeaders({ model: model.slug, spec: "speech" }),
|
||||
json: { text, ...(voice ? { voice } : {}), outputFormat: format },
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
const json = await res.json().catch(() => null);
|
||||
const audio = typeof json?.audio == "string" ? Buffer.from(json.audio, "base64") : null;
|
||||
|
||||
if (!audio?.length) {
|
||||
throw new HarnessError({
|
||||
message: `${provider.name || "Vercel AI Gateway"} returned no audio.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(audio);
|
||||
|
||||
return {
|
||||
stream: new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes);
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
media_type: `audio/${format == "mp3" ? "mpeg" : format}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
import audioMimeType from "./audio-mime-type";
|
||||
import providerRequest from "./provider-request";
|
||||
import { vercelGatewayHeaders } from "./vercel-gateway-hosts";
|
||||
|
||||
type Params = {
|
||||
candidate: HarnessCandidate;
|
||||
audio: { data: Uint8Array; format: string };
|
||||
signal: AbortSignal;
|
||||
};
|
||||
|
||||
/**
|
||||
* Vercel AI Gateway's own transcription route, `POST /v4/ai/transcription-model`
|
||||
* on the host root: the model goes in `ai-model-id`, the audio as base64 with
|
||||
* its media type, and the transcript comes back at `text`. The gateway's
|
||||
* `/v1/audio/transcriptions` doesn't exist (404).
|
||||
*/
|
||||
export default async function vercelGatewayTranscribe({
|
||||
candidate,
|
||||
audio,
|
||||
signal,
|
||||
}: Params): Promise<{ text: string }> {
|
||||
const { provider, model } = candidate;
|
||||
const name = provider.name || "Vercel AI Gateway";
|
||||
|
||||
const res = await providerRequest({
|
||||
provider,
|
||||
base_url: new URL(provider.base_url).origin,
|
||||
path: "/v4/ai/transcription-model",
|
||||
headers: vercelGatewayHeaders({ model: model.slug, spec: "transcription" }),
|
||||
json: {
|
||||
audio: Buffer.from(audio.data).toString("base64"),
|
||||
mediaType: audioMimeType({ format: audio.format }),
|
||||
},
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
const json = await res.json().catch(() => null);
|
||||
|
||||
if (json === null) {
|
||||
throw new HarnessError({
|
||||
message: `${name} returned an unreadable transcript.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
}
|
||||
|
||||
const text = String(json?.text ?? "").trim();
|
||||
|
||||
if (!text) {
|
||||
throw new HarnessError({
|
||||
message: `${name} returned an empty transcript.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
}
|
||||
|
||||
return { text };
|
||||
}
|
||||
@@ -68,8 +68,7 @@ export default function proposeHookTool({
|
||||
onPropose,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const dirs = computerRunDirs({ bot_id, bot_kind: is_coordinator ? "coordinator" : null, user_id, workspace_id });
|
||||
const home_relative = dirs.cwd.slice(dirs.bot_dir.length + 1);
|
||||
const runner_folder = `relative to your bot folder ${dirs.bot_dir}, NOT to your ~ (${dirs.cwd}): a folder you made at ~/whatsapp is "${home_relative}/whatsapp", and "whatsapp" alone is ${dirs.bot_dir}/whatsapp. Empty: ${dirs.bot_dir} itself`;
|
||||
const runner_folder = `relative: the app looks in your ~ (${dirs.cwd}) first, then in your bot folder (${dirs.bot_dir}), and starts in the first one that exists, so a folder you made at ~/whatsapp is just "whatsapp". Empty: ${dirs.bot_dir} itself`;
|
||||
const listed = computers.map((computer) => `${computer.id} (${computer.name || computer.kind})`).join(", ");
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import type { ConnectorAccountExecutor } from "../../connectors/connector-account-executor";
|
||||
import type { ConnectorRouterEntry } from "../../connectors/connector-router-entry";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import connectorRouterTools from "./connector-router-tools";
|
||||
|
||||
const gmail = { id: 1, name: "Gmail", slug: "gmail", app: "gmail" } as ConnectorRecord;
|
||||
const send = {
|
||||
name: "GMAIL_SEND_EMAIL",
|
||||
description: "Send an email message.",
|
||||
input_schema: { type: "object", properties: { to: {}, subject: {} }, required: ["to"] },
|
||||
};
|
||||
const fetchTool = { name: "GMAIL_FETCH_EMAILS", description: "Fetch emails from the inbox.", input_schema: { type: "object" } };
|
||||
|
||||
function account({ id, label }: { id: number; label: string }) {
|
||||
return { id, label, user_id: 1, owner_name: "" } as ConnectorAccountRecord;
|
||||
}
|
||||
|
||||
function executor({ calls }: { calls: string[] }): ConnectorAccountExecutor {
|
||||
return {
|
||||
call: async ({ tool, args }) => {
|
||||
calls.push(`${tool} ${JSON.stringify(args)}`);
|
||||
return `ran ${tool}`;
|
||||
},
|
||||
close: async () => {},
|
||||
};
|
||||
}
|
||||
|
||||
function entries({ calls }: { calls: string[] }): ConnectorRouterEntry[] {
|
||||
const work = account({ id: 1, label: "Work" });
|
||||
const home = account({ id: 2, label: "Home" });
|
||||
|
||||
return [
|
||||
{ name: "gmail-work__GMAIL_SEND_EMAIL", tool: send, connector: gmail, account: work, namespace: "gmail-work", executor: executor({ calls }) },
|
||||
{ name: "gmail-work__GMAIL_FETCH_EMAILS", tool: fetchTool, connector: gmail, account: work, namespace: "gmail-work", executor: executor({ calls }) },
|
||||
{ name: "gmail-home__GMAIL_SEND_EMAIL", tool: send, connector: gmail, account: home, namespace: "gmail-home", executor: executor({ calls }) },
|
||||
];
|
||||
}
|
||||
|
||||
function find({ tools, name }: { tools: HarnessTool[]; name: string }) {
|
||||
return tools.find((tool) => tool.name == name)!;
|
||||
}
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
describe("connectorRouterTools", () => {
|
||||
test("search names every account's tool with what it needs, without running anything", async () => {
|
||||
const calls: string[] = [];
|
||||
const tools = connectorRouterTools({ entries: entries({ calls }), connectable: [] });
|
||||
const text = String(await find({ tools, name: "connectors_search_tools" }).run({ args: { query: "send email" }, signal }));
|
||||
|
||||
expect(text).toContain("gmail-work__GMAIL_SEND_EMAIL: Gmail (Work)");
|
||||
expect(text).toContain("gmail-home__GMAIL_SEND_EMAIL: Gmail (Home)");
|
||||
expect(text).toContain("Needs: to.");
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
test("execute sends a call missing a required argument back unrun", async () => {
|
||||
const calls: string[] = [];
|
||||
const tools = connectorRouterTools({ entries: entries({ calls }), connectable: [] });
|
||||
const execute = find({ tools, name: "connectors_execute" });
|
||||
|
||||
await expect(
|
||||
execute.run({ args: { calls: [{ tool: "gmail-work__GMAIL_SEND_EMAIL", arguments: {} }] }, signal }),
|
||||
).rejects.toThrow("Not run (no action spent): to is required");
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
test("execute runs a single call given at the top level, arguments as JSON text too", async () => {
|
||||
const calls: string[] = [];
|
||||
const tools = connectorRouterTools({ entries: entries({ calls }), connectable: [] });
|
||||
const execute = find({ tools, name: "connectors_execute" });
|
||||
const answer = await execute.run({
|
||||
args: { tool: "gmail-work__GMAIL_SEND_EMAIL", arguments: `{"to":"[email protected]"}` },
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(answer).toBe("ran GMAIL_SEND_EMAIL");
|
||||
expect(calls).toEqual([`GMAIL_SEND_EMAIL {"to":"[email protected]"}`]);
|
||||
});
|
||||
|
||||
test("a provider name alone is refused when two accounts have it, and taken when one does", async () => {
|
||||
const calls: string[] = [];
|
||||
const tools = connectorRouterTools({ entries: entries({ calls }), connectable: [] });
|
||||
const execute = find({ tools, name: "connectors_execute" });
|
||||
const answer = String(
|
||||
await execute.run(
|
||||
{
|
||||
args: {
|
||||
calls: [
|
||||
{ tool: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]" } },
|
||||
{ tool: "GMAIL_FETCH_EMAILS", arguments: {} },
|
||||
],
|
||||
},
|
||||
signal,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
expect(answer).toContain("## GMAIL_SEND_EMAIL (failed)\nError: \"GMAIL_SEND_EMAIL\" is in more than one account");
|
||||
expect(answer).toContain("## gmail-work__GMAIL_FETCH_EMAILS\nran GMAIL_FETCH_EMAILS");
|
||||
expect(calls).toEqual(["GMAIL_FETCH_EMAILS {}"]);
|
||||
});
|
||||
|
||||
test("an app with no account asks to connect when run, and connectors_connect puts the card up", async () => {
|
||||
const asked: string[] = [];
|
||||
const connect = async () => {
|
||||
asked.push("gmail");
|
||||
return "Connect card [connect:7] is under your reply.";
|
||||
};
|
||||
const tools = connectorRouterTools({
|
||||
entries: [{ name: "gmail__GMAIL_FETCH_EMAILS", tool: fetchTool, connector: gmail, account: null, namespace: "gmail", executor: null, onMissingAccount: connect }],
|
||||
connectable: [{ connector: gmail, connect }],
|
||||
});
|
||||
|
||||
await expect(
|
||||
find({ tools, name: "connectors_execute" }).run({ args: { calls: [{ tool: "gmail__GMAIL_FETCH_EMAILS" }] }, signal }),
|
||||
).rejects.toThrow("[connect:7]");
|
||||
expect(await find({ tools, name: "connectors_connect" }).run({ args: { app: "gmail" }, signal })).toContain("[connect:7]");
|
||||
expect(asked).toEqual(["gmail", "gmail"]);
|
||||
});
|
||||
|
||||
test("no connect tool when every app has an account", () => {
|
||||
const tools = connectorRouterTools({ entries: entries({ calls: [] }), connectable: [] });
|
||||
|
||||
expect(tools.map((tool) => tool.name)).toEqual([
|
||||
"connectors_search_tools",
|
||||
"connectors_get_tool_schemas",
|
||||
"connectors_execute",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import {
|
||||
ConnectorConnectToolName,
|
||||
ConnectorExecuteToolName,
|
||||
ConnectorGetToolSchemasToolName,
|
||||
ConnectorSearchToolsToolName,
|
||||
} from "@/src/dict/connector-dict";
|
||||
import type { ConnectorRecord } from "@/src/types";
|
||||
import type { ConnectorRouterEntry } from "../../connectors/connector-router-entry";
|
||||
import missingRequiredArgs from "../../connectors/missing-required-args";
|
||||
import rankConnectorTools from "../../connectors/rank-connector-tools";
|
||||
import resolveConnectorRouterEntry from "../../connectors/resolve-connector-router-entry";
|
||||
import type { HarnessTool, HarnessToolImage, HarnessToolOutput } from "../../types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Every tool of every connector account the run reaches, plus the tools
|
||||
* of apps offered without an account in a reply the user follows.
|
||||
*/
|
||||
entries: ConnectorRouterEntry[];
|
||||
/**
|
||||
* Apps the run reaches with no working account, in a reply the user
|
||||
* follows: `connectors_connect` puts their connect card up.
|
||||
*/
|
||||
connectable: { connector: ConnectorRecord; connect: () => Promise<string> }[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A model sends `arguments` as an object, and now and then as the JSON text
|
||||
* of one: both are taken, and the text is read in `readCallArguments`.
|
||||
*/
|
||||
const ArgumentsSchema = z.union([z.record(z.string(), z.unknown()), z.string()]);
|
||||
|
||||
const CallSchema = z.object({
|
||||
tool: z.string().trim().min(1).describe(`The tool's name exactly as connectors_search_tools gave it, e.g. gmail__GMAIL_SEND_EMAIL`),
|
||||
arguments: ArgumentsSchema.optional().describe(`The tool's arguments, as its schema (connectors_get_tool_schemas) describes them`),
|
||||
});
|
||||
|
||||
type Call = z.infer<typeof CallSchema>;
|
||||
|
||||
/**
|
||||
* One `connectors_execute` takes `calls`; a single call written at the top
|
||||
* level (`tool`, `arguments`) is read as a list of one. Plain fields rather
|
||||
* than a transform, since the schema is sent to the provider as JSON schema.
|
||||
*/
|
||||
const ExecuteSchema = z.object({
|
||||
calls: z.array(CallSchema).min(1).max(AppData.ConnectorExecuteMaxCalls).optional(),
|
||||
tool: CallSchema.shape.tool.optional().describe(`A single call's tool, when you leave calls out`),
|
||||
arguments: CallSchema.shape.arguments,
|
||||
});
|
||||
|
||||
type ExecuteArgs = z.infer<typeof ExecuteSchema>;
|
||||
|
||||
function readCallArguments({ value }: { value: Call["arguments"] }): Record<string, unknown> | string {
|
||||
if (value == null) return {};
|
||||
if (typeof value != "string") return value;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
|
||||
if (parsed && typeof parsed == "object" && !Array.isArray(parsed)) return parsed as Record<string, unknown>;
|
||||
} catch {}
|
||||
|
||||
return `arguments must be a JSON object, not text.`;
|
||||
}
|
||||
|
||||
function entryLabel({ entry }: { entry: ConnectorRouterEntry }) {
|
||||
if (!entry.account) return `${entry.connector.name} (no account connected yet)`;
|
||||
|
||||
const owner = entry.owner_name ? `, ${entry.owner_name}'s account` : "";
|
||||
|
||||
return `${entry.connector.name} (${entry.account.label}${owner})`;
|
||||
}
|
||||
|
||||
function shortDescription({ text }: { text: string }) {
|
||||
const line = text.replace(/\s+/g, " ").trim();
|
||||
|
||||
return line.length > AppData.ConnectorSearchDescriptionChars
|
||||
? `${line.slice(0, AppData.ConnectorSearchDescriptionChars - 3).trimEnd()}...`
|
||||
: line;
|
||||
}
|
||||
|
||||
function requiredText({ entry }: { entry: ConnectorRouterEntry }) {
|
||||
const required = missingRequiredArgs({ schema: entry.tool.input_schema, args: {} });
|
||||
|
||||
return required.length ? ` Needs: ${required.join(", ")}.` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* One run's connector router: a few tools of the app's own in place of every
|
||||
* provider tool, so a bot with ten apps pays for three tool definitions, not
|
||||
* eight hundred. The model searches what the apps can do, reads the schemas
|
||||
* of the tools that fit, and runs them; each run is one action against the
|
||||
* run's cap, through the same account session the direct tools use.
|
||||
*/
|
||||
export default function connectorRouterTools({ entries, connectable }: Params): HarnessTool[] {
|
||||
const apps = [...new Set(entries.map((entry) => entry.namespace))];
|
||||
|
||||
const search: HarnessTool<{ query: string; app?: string; limit?: number }> = {
|
||||
name: ConnectorSearchToolsToolName,
|
||||
description: `Finds the tools of the user's connected apps (Gmail, Slack, GitHub, ...) that can do something, from a plain description ("send an email", "list open issues"). Costs no action. Then read the arguments of the ones that fit with ${ConnectorGetToolSchemasToolName} and run them with ${ConnectorExecuteToolName}. Apps and accounts: ${apps.join(", ")}.`,
|
||||
schema: z.object({
|
||||
query: z.string().trim().max(300).describe(`What you want to do, in plain words`),
|
||||
app: z
|
||||
.string()
|
||||
.trim()
|
||||
.optional()
|
||||
.describe(`Only this app or account, by its prefix (e.g. gmail or gmail-work) or its name`),
|
||||
limit: z.number().int().min(1).max(AppData.ConnectorSearchMaxResults).optional(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const app = args.app?.toLowerCase();
|
||||
const scoped = app
|
||||
? entries.filter(
|
||||
(entry) =>
|
||||
entry.namespace.toLowerCase() == app ||
|
||||
entry.connector.slug.toLowerCase() == app ||
|
||||
entry.connector.app.toLowerCase() == app ||
|
||||
entry.connector.name.toLowerCase() == app,
|
||||
)
|
||||
: entries;
|
||||
|
||||
if (app && !scoped.length) {
|
||||
return `No connected app or account is called "${args.app}". These are: ${apps.join(", ")}.`;
|
||||
}
|
||||
|
||||
const found = rankConnectorTools({
|
||||
tools: scoped.map((entry) => ({
|
||||
...entry,
|
||||
tool: entry.tool.name,
|
||||
app_name: entry.connector.name,
|
||||
app_slug: entry.connector.slug,
|
||||
description: entry.tool.description || "",
|
||||
entry,
|
||||
})),
|
||||
query: args.query,
|
||||
limit: args.limit || AppData.ConnectorSearchDefaultResults,
|
||||
});
|
||||
|
||||
if (!found.length) {
|
||||
return `No tool of ${app ? `"${args.app}"` : "the connected apps"} matches "${args.query}". Try other words (the action and the thing, e.g. "create issue"), or one app at a time. Apps and accounts: ${apps.join(", ")}.`;
|
||||
}
|
||||
|
||||
const lines = found.map(
|
||||
({ entry }) =>
|
||||
`- ${entry.name}: ${entryLabel({ entry })}: ${shortDescription({ text: entry.tool.description || entry.tool.name })}${requiredText({ entry })}`,
|
||||
);
|
||||
|
||||
return [
|
||||
`${found.length} tool${found.length == 1 ? "" : "s"} for "${args.query}", best first:`,
|
||||
...lines,
|
||||
"",
|
||||
`Read a tool's arguments with ${ConnectorGetToolSchemasToolName} before you run it with ${ConnectorExecuteToolName}.`,
|
||||
].join("\n");
|
||||
},
|
||||
};
|
||||
|
||||
const schemas: HarnessTool<{ tools: string[] }> = {
|
||||
name: ConnectorGetToolSchemasToolName,
|
||||
description: `Reads what connector tools take: each one's full description and the JSON schema of its arguments. Costs no action. Name them as ${ConnectorSearchToolsToolName} gave them.`,
|
||||
schema: z.object({
|
||||
tools: z.array(z.string().trim().min(1)).min(1).max(AppData.ConnectorSchemasMaxPerCall),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const sections = args.tools.map((name) => {
|
||||
const resolved = resolveConnectorRouterEntry({ entries, name });
|
||||
|
||||
if ("problem" in resolved) return `## ${name}\n${resolved.problem}`;
|
||||
|
||||
const { entry } = resolved;
|
||||
|
||||
return [
|
||||
`## ${entry.name}`,
|
||||
`${entryLabel({ entry })}: ${entry.tool.description || entry.tool.name}`,
|
||||
"Arguments (JSON schema):",
|
||||
JSON.stringify(entry.tool.input_schema || { type: "object", properties: {} }),
|
||||
].join("\n");
|
||||
});
|
||||
|
||||
return sections.join("\n\n");
|
||||
},
|
||||
};
|
||||
|
||||
const execute: HarnessTool<ExecuteArgs> = {
|
||||
name: ConnectorExecuteToolName,
|
||||
description: `Runs connector tools through the user's connected accounts: one call, or up to ${AppData.ConnectorExecuteMaxCalls} that don't depend on each other, run together. Each call is one action, and the provider bills each; a call missing a required argument is sent back unrun. Name each tool as ${ConnectorSearchToolsToolName} gave it and pass the arguments its schema describes.`,
|
||||
schema: ExecuteSchema,
|
||||
timeout_ms: AppData.ConnectorToolTimeoutMs + 60 * 1000,
|
||||
run: async ({ args, signal }) => {
|
||||
const calls: Call[] = args.calls?.length ? args.calls : args.tool ? [{ tool: args.tool, arguments: args.arguments }] : [];
|
||||
|
||||
if (!calls.length) throw new Error(`Give calls: [{ tool, arguments }], or one tool and its arguments.`);
|
||||
|
||||
const outcomes = await Promise.all(
|
||||
calls.map(async (call): Promise<{ name: string; ok: boolean; output: HarnessToolOutput }> => {
|
||||
const resolved = resolveConnectorRouterEntry({ entries, name: call.tool });
|
||||
|
||||
if ("problem" in resolved) return { name: call.tool, ok: false, output: resolved.problem };
|
||||
|
||||
const { entry } = resolved;
|
||||
|
||||
if (!entry.executor) {
|
||||
const text =
|
||||
(await entry.onMissingAccount?.()) ||
|
||||
`No account is connected to ${entry.connector.name}, so this didn't run. Connect one in Settings > Connectors.`;
|
||||
|
||||
return { name: entry.name, ok: false, output: text };
|
||||
}
|
||||
|
||||
const call_args = readCallArguments({ value: call.arguments });
|
||||
|
||||
if (typeof call_args == "string") return { name: entry.name, ok: false, output: `Not run: ${call_args}` };
|
||||
|
||||
const missing = missingRequiredArgs({ schema: entry.tool.input_schema, args: call_args });
|
||||
|
||||
if (missing.length) {
|
||||
return {
|
||||
name: entry.name,
|
||||
ok: false,
|
||||
output: `Not run (no action spent): ${missing.join(", ")} ${missing.length == 1 ? "is" : "are"} required. Read the schema with ${ConnectorGetToolSchemasToolName}.`,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return {
|
||||
name: entry.name,
|
||||
ok: true,
|
||||
output: await entry.executor.call({ tool: entry.tool.name, args: call_args, signal }),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (signal.aborted) throw error;
|
||||
|
||||
return {
|
||||
name: entry.name,
|
||||
ok: false,
|
||||
output: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (outcomes.every((outcome) => !outcome.ok)) {
|
||||
throw new Error(
|
||||
outcomes.length == 1
|
||||
? String(outcomes[0]!.output)
|
||||
: outcomes.map((outcome) => `${outcome.name}: ${String(outcome.output)}`).join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
if (outcomes.length == 1) return outcomes[0]!.output;
|
||||
|
||||
const images: HarnessToolImage[] = [];
|
||||
const text = outcomes
|
||||
.map((outcome) => {
|
||||
const output = outcome.output;
|
||||
const body = typeof output == "string" ? output : output.text;
|
||||
|
||||
if (typeof output != "string") images.push(...output.images);
|
||||
|
||||
return `## ${outcome.name}${outcome.ok ? "" : " (failed)"}\n${outcome.ok ? body : `Error: ${body}`}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
|
||||
return images.length ? { text, images } : text;
|
||||
},
|
||||
};
|
||||
|
||||
const tools: HarnessTool[] = [search, schemas, execute];
|
||||
|
||||
if (connectable.length) {
|
||||
const names = connectable.map(({ connector }) => connector.slug);
|
||||
|
||||
tools.push({
|
||||
name: ConnectorConnectToolName,
|
||||
description: `Asks the user to connect an app they have no working account for, with a Connect card under your reply. Use it when the request needs that app; never tell them to connect it in a sentence alone. Apps: ${names.join(", ")}.`,
|
||||
schema: z.object({ app: z.string().trim().min(1).describe(`The app's prefix, e.g. ${names[0]}`) }),
|
||||
run: async ({ args }: { args: { app: string } }) => {
|
||||
const wanted = args.app.toLowerCase();
|
||||
const found = connectable.find(
|
||||
({ connector }) =>
|
||||
connector.slug.toLowerCase() == wanted ||
|
||||
connector.app.toLowerCase() == wanted ||
|
||||
connector.name.toLowerCase() == wanted,
|
||||
);
|
||||
|
||||
if (!found) {
|
||||
throw new Error(`"${args.app}" isn't an app waiting to be connected here. These are: ${names.join(", ")}.`);
|
||||
}
|
||||
|
||||
return found.connect();
|
||||
},
|
||||
} satisfies HarnessTool<{ app: string }>);
|
||||
}
|
||||
|
||||
return tools;
|
||||
}
|
||||
@@ -3,11 +3,15 @@ import type { ConnectorProvider } from "@/src/harness/connectors/connector-provi
|
||||
import grabConnectorActionsPerRun from "@/src/functions/backend/db/connectors/grab-connector-actions-per-run";
|
||||
import grabRunConnectors from "@/src/functions/backend/db/connectors/grab-run-connectors";
|
||||
import grabRunEnvs from "@/src/functions/backend/db/extensions/grab-run-envs";
|
||||
import { ConnectorAccountSeparator } from "@/src/dict/connector-dict";
|
||||
import { ConnectorAccountSeparator, ConnectorConnectToolName, ConnectorSearchToolsToolName } from "@/src/dict/connector-dict";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import mcpToolName from "@/src/utils/mcp-tool-name";
|
||||
import connectorAccountExecutor from "../../connectors/connector-account-executor";
|
||||
import connectorAccountTools from "../../connectors/connector-account-tools";
|
||||
import type { ConnectorRouterEntry } from "../../connectors/connector-router-entry";
|
||||
import grabConnectorProvider from "@/src/functions/backend/db/connectors/grab-connector-provider";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import connectorRouterTools from "./connector-router-tools";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -26,11 +30,12 @@ type Params = {
|
||||
*/
|
||||
taken?: string[];
|
||||
/**
|
||||
* Called when a tool of a connector without an account is used, in an
|
||||
* attended run. It makes the connect request and returns the ref the
|
||||
* Called when a tool of a connector without a working account is used,
|
||||
* in an attended run. It makes the connect request (reconnecting
|
||||
* `account` when the user's own sign-in lapsed) and returns the ref the
|
||||
* message must carry, or whatever should be said instead.
|
||||
*/
|
||||
onMissingAccount?: (params: { connector: ConnectorRecord }) => Promise<string>;
|
||||
onMissingAccount?: (params: { connector: ConnectorRecord; account: ConnectorAccountRecord | null }) => Promise<string>;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
@@ -43,19 +48,46 @@ export type OpenBotConnectors = {
|
||||
tools: HarnessTool[];
|
||||
/**
|
||||
* For the run's prompt (`ConnectorsNote`): which accounts it can use
|
||||
* and how to load them, one line each.
|
||||
* and how to reach them, one line each.
|
||||
*/
|
||||
lines: string[];
|
||||
/**
|
||||
* The routers this run reaches, by name: their apps are reached through
|
||||
* the router's tools (`connectorRouterTools`). Empty when none.
|
||||
*/
|
||||
routers: string[];
|
||||
/**
|
||||
* Whether any app was given directly, so its tools are deferred tools
|
||||
* of the run's own.
|
||||
*/
|
||||
direct: boolean;
|
||||
connectors: OpenBotConnectorSummary[];
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why a connector's sign-in doesn't work right now, from the user's own
|
||||
* lapsed row (`grabRunConnectors`).
|
||||
*/
|
||||
function lapsedReason({ account }: { account: ConnectorAccountRecord | null }) {
|
||||
if (!account) return "no account connected";
|
||||
if (account.status == "pending") return `the sign-in "${account.label}" was never finished`;
|
||||
if (account.status == "expired") return `the account "${account.label}" needs reconnecting`;
|
||||
|
||||
return `the account "${account.label}" is no longer at the provider and needs reconnecting`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The connectors one run reaches, each account's tools named under its own
|
||||
* namespace (`gmail__...` for a single account, `gmail-work__...` for one of
|
||||
* several), all deferred so a turn that doesn't use them doesn't carry
|
||||
* their definitions. The endpoint is connected on the first call and
|
||||
* closed with the run.
|
||||
* several).
|
||||
*
|
||||
* An app a router brings (`connector_routers`) is reached through a few
|
||||
* tools of the app's own that search, describe and run its tools, so its
|
||||
* prompt carries none of them; an app given to the bot directly makes every
|
||||
* provider tool a deferred tool of its own. Both run through the same
|
||||
* per-account executor, connected on the first call and closed with the
|
||||
* run, and share the run's action cap.
|
||||
*/
|
||||
export default async function openBotConnectors({
|
||||
user_id,
|
||||
@@ -67,16 +99,19 @@ export default async function openBotConnectors({
|
||||
signal,
|
||||
}: Params): Promise<OpenBotConnectors> {
|
||||
const runConnectors = await grabRunConnectors({ user_id, bot_id, workspace_id });
|
||||
const routers = [...new Set(runConnectors.flatMap((entry) => entry.routers))];
|
||||
|
||||
if (!runConnectors.length) return { tools: [], lines: [], connectors: [], close: async () => {} };
|
||||
if (!runConnectors.length) return { tools: [], lines: [], routers: [], direct: false, connectors: [], close: async () => {} };
|
||||
|
||||
const envs = await grabRunEnvs({ bot_id, user_id, workspace_id });
|
||||
const secrets = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
const names = new Set(taken);
|
||||
const tools: HarnessTool[] = [];
|
||||
const closers: (() => Promise<void>)[] = [];
|
||||
const lines: string[] = [];
|
||||
const entries: ConnectorRouterEntry[] = [];
|
||||
const connectable: { connector: ConnectorRecord; connect: () => Promise<string> }[] = [];
|
||||
const direct: HarnessTool[] = [];
|
||||
const cap = await grabConnectorActionsPerRun();
|
||||
const namespaces = new Set<string>();
|
||||
let actions = 0;
|
||||
@@ -101,59 +136,80 @@ export default async function openBotConnectors({
|
||||
const takeAction = () => {
|
||||
if (actions >= cap) {
|
||||
throw new Error(
|
||||
`This run has already taken ${cap} connector actions, so it can't take another. A provider bills per action; a super admin can raise the limit in Settings > Connectors.`,
|
||||
`This run has already taken ${cap} connector actions, so it can't take another. A provider bills per action; the super admin can raise the limit in Settings > General > Connectors ([setting:connectors:actions_per_run]).`,
|
||||
);
|
||||
}
|
||||
|
||||
actions += 1;
|
||||
};
|
||||
|
||||
for (const { connector, accounts } of runConnectors) {
|
||||
const connected = accounts.filter((account) => account.status == "connected");
|
||||
/**
|
||||
* One account's tools (or, with no account, the app's tools that ask the
|
||||
* user to connect), as router entries or as tools of their own.
|
||||
*/
|
||||
const addAccount = ({
|
||||
routed,
|
||||
connector,
|
||||
account,
|
||||
namespace,
|
||||
executor,
|
||||
missing,
|
||||
}: {
|
||||
routed: boolean;
|
||||
connector: ConnectorRecord;
|
||||
account: ConnectorAccountRecord | null;
|
||||
namespace: string;
|
||||
executor: ReturnType<typeof connectorAccountExecutor> | null;
|
||||
missing?: () => Promise<string>;
|
||||
}) => {
|
||||
const listed = connector.tools.filter((tool) => !connector.excluded_tools.includes(tool.name));
|
||||
const shared = Boolean(account && account.user_id != Number(user_id) && account.owner_name);
|
||||
|
||||
if (!connected.length) {
|
||||
if (attended && onMissingAccount) {
|
||||
let provider: ConnectorProvider;
|
||||
if (!routed) {
|
||||
const built = connectorAccountTools({
|
||||
connector,
|
||||
account,
|
||||
executor,
|
||||
onMissingAccount: missing,
|
||||
namespace,
|
||||
names,
|
||||
});
|
||||
|
||||
try {
|
||||
provider = await grabConnectorProvider({ connector_id: connector.id });
|
||||
} catch (error: unknown) {
|
||||
lines.push(`${connector.name}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
continue;
|
||||
}
|
||||
direct.push(...built);
|
||||
return built.length;
|
||||
}
|
||||
|
||||
const built = connectorAccountTools({
|
||||
connector,
|
||||
provider,
|
||||
user_id: Number(user_id),
|
||||
account: null,
|
||||
onMissingAccount: () => onMissingAccount({ connector }),
|
||||
namespace: connector.slug,
|
||||
names,
|
||||
redact,
|
||||
takeAction,
|
||||
signal,
|
||||
});
|
||||
for (const tool of listed) {
|
||||
const name = mcpToolName({ slug: namespace, name: tool.name });
|
||||
|
||||
tools.push(...built.tools);
|
||||
closers.push(built.close);
|
||||
lines.push(
|
||||
`${connector.name}: no account connected yet. Calling one of its tools (${connector.slug}__*) asks the user to connect one, through the card under your reply; don't tell them to connect it in a sentence alone.`,
|
||||
);
|
||||
if (names.has(name)) continue;
|
||||
|
||||
continue;
|
||||
}
|
||||
names.add(name);
|
||||
entries.push({
|
||||
name,
|
||||
tool,
|
||||
connector,
|
||||
account,
|
||||
owner_name: shared ? account?.owner_name : undefined,
|
||||
namespace,
|
||||
executor,
|
||||
onMissingAccount: missing,
|
||||
});
|
||||
}
|
||||
|
||||
const status = accounts[0]?.status;
|
||||
const why =
|
||||
status == "pending"
|
||||
? "waiting for you to finish connecting"
|
||||
: status == "expired"
|
||||
? "needs reconnecting"
|
||||
: "no account connected";
|
||||
return listed.length;
|
||||
};
|
||||
|
||||
lines.push(`${connector.name}: ${why}, so its tools aren't available in this run.`);
|
||||
for (const { connector, accounts, lapsed, routers: via, picked } of runConnectors) {
|
||||
const routed = via.length > 0;
|
||||
const through = routed ? ` (through ${via.join(", ")})` : "";
|
||||
|
||||
if (!connector.tools.length) {
|
||||
// Its tools were never read (a sync that failed, or one still to
|
||||
// come): say so rather than leave the app out without a word.
|
||||
lines.push(
|
||||
`${connector.name}: its tools haven't been read from the provider yet${connector.last_error ? ` (${connector.last_error.slice(0, 200)})` : ""}, so it can't be used in this run. A super admin can sync it in Settings > Connectors.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -166,15 +222,47 @@ export default async function openBotConnectors({
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const account of connected) {
|
||||
if (!accounts.length && picked) {
|
||||
// The router names its accounts: a new sign-in wouldn't be one of
|
||||
// them, so there is nothing to ask the user to connect.
|
||||
lines.push(
|
||||
`${connector.name}${through}: the account${lapsed ? ` "${lapsed.label}"` : "s"} this router uses ${lapsed ? "isn't" : "aren't"} connected right now, so its tools aren't available in this run. A super admin can reconnect it or change the router's accounts in Settings > Connectors.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!accounts.length) {
|
||||
const why = lapsedReason({ account: lapsed });
|
||||
|
||||
if (attended && onMissingAccount) {
|
||||
const missing = () => onMissingAccount({ connector, account: lapsed });
|
||||
const namespace = freeNamespace({ base: connector.slug });
|
||||
|
||||
addAccount({ routed, connector, account: null, namespace, executor: null, missing });
|
||||
if (routed) connectable.push({ connector, connect: missing });
|
||||
lines.push(
|
||||
routed
|
||||
? `${connector.name}${through}: ${why} yet. When the request needs it, call ${ConnectorConnectToolName} with app "${connector.slug}": it puts a Connect card under your reply. Don't tell them to connect it in a sentence alone.`
|
||||
: `${connector.name}: ${why} yet. Calling one of its tools (${namespace}__*) asks the user to connect one, through the card under your reply; don't tell them to connect it in a sentence alone.`,
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
lines.push(`${connector.name}: ${why}, so its tools aren't available in this run.`);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const account of accounts) {
|
||||
const namespace = freeNamespace({
|
||||
base:
|
||||
connected.length > 1
|
||||
accounts.length > 1
|
||||
? `${connector.slug}${ConnectorAccountSeparator}${account.slug}`
|
||||
: connector.slug,
|
||||
});
|
||||
const shared = account.user_id != Number(user_id) && Boolean(account.owner_name);
|
||||
const built = connectorAccountTools({
|
||||
const executor = connectorAccountExecutor({
|
||||
connector,
|
||||
provider,
|
||||
/**
|
||||
@@ -184,29 +272,39 @@ export default async function openBotConnectors({
|
||||
*/
|
||||
user_id: account.user_id,
|
||||
account,
|
||||
namespace,
|
||||
names,
|
||||
redact,
|
||||
takeAction,
|
||||
signal,
|
||||
});
|
||||
const count = addAccount({ routed, connector, account, namespace, executor });
|
||||
|
||||
if (!built.tools.length) continue;
|
||||
if (!count) continue;
|
||||
|
||||
closers.push(executor.close);
|
||||
|
||||
const who = `${account.label}${shared ? `, ${account.owner_name}'s account` : ""}`;
|
||||
|
||||
tools.push(...built.tools);
|
||||
closers.push(built.close);
|
||||
lines.push(
|
||||
`${connector.name} (${account.label}${shared ? `, ${account.owner_name}'s account` : ""}): call its tools as ${namespace}__*, listing ${built.tools.length} tool${built.tools.length == 1 ? "" : "s"} you load with load_tools first.`,
|
||||
routed
|
||||
? `${connector.name} (${who})${through}: ${count} tool${count == 1 ? "" : "s"} under ${namespace}__*, reached with connectors_search_tools.`
|
||||
: `${connector.name} (${who}): call its tools as ${namespace}__*, listing ${count} tool${count == 1 ? "" : "s"} you load with load_tools first.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const router_tools =
|
||||
(entries.length || connectable.length) && !taken.includes(ConnectorSearchToolsToolName)
|
||||
? connectorRouterTools({ entries, connectable }).filter((tool) => !taken.includes(tool.name))
|
||||
: [];
|
||||
|
||||
return {
|
||||
tools,
|
||||
tools: [...router_tools, ...direct],
|
||||
lines,
|
||||
routers: router_tools.length ? routers : [],
|
||||
direct: direct.length > 0,
|
||||
connectors: runConnectors,
|
||||
close: async () => {
|
||||
await Promise.all(closers.map(async (close) => close().catch(() => {})));
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectorGetToolSchemasToolName, ConnectorSearchToolsToolName } from "@/src/dict/connector-dict";
|
||||
import { ReadKnowledgebaseDocumentToolName, SearchKnowledgebaseToolName } from "@/src/dict/knowledgebase-dict";
|
||||
|
||||
/**
|
||||
@@ -32,6 +33,8 @@ export const RepeatableToolNames: readonly string[] = [
|
||||
"search_past_sessions",
|
||||
"read_past_session",
|
||||
"search_computers",
|
||||
ConnectorSearchToolsToolName,
|
||||
ConnectorGetToolSchemasToolName,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -56,4 +56,24 @@ describe("unknownToolMessage", () => {
|
||||
expect(text).toContain("only exist in a task on a computer");
|
||||
expect(text).not.toContain("slug");
|
||||
});
|
||||
|
||||
/**
|
||||
* The connector router keeps an app's tools out of the run's own, and a
|
||||
* model that read `gmail__GMAIL_SEND_EMAIL` in a search result calls it
|
||||
* by name: it is pointed at connectors_execute, not told it doesn't exist.
|
||||
*/
|
||||
test("points a connector tool called by name at connectors_execute", () => {
|
||||
const text = unknownToolMessage({
|
||||
name: "gmail-work__GMAIL_SEND_EMAIL",
|
||||
tools: [{ name: "send_reply" }, { name: "connectors_execute" }],
|
||||
});
|
||||
|
||||
expect(text).toContain(`run it with connectors_execute, {"tool": "gmail-work__GMAIL_SEND_EMAIL"`);
|
||||
});
|
||||
|
||||
test("leaves the plain message when the run has no router", () => {
|
||||
const text = unknownToolMessage({ name: "gmail__GMAIL_SEND_EMAIL", tools: [{ name: "send_reply" }] });
|
||||
|
||||
expect(text).toStartWith(`Error: There is no tool called "gmail__GMAIL_SEND_EMAIL".`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,8 @@ type Params = {
|
||||
*/
|
||||
const ComputerToolPattern = /^(?:computer_|browser_)/;
|
||||
const WantsBrowserPattern = /(?:^|__)browser_/;
|
||||
/** A connector tool's name: `<namespace>__<PROVIDER_TOOL>`. */
|
||||
const ConnectorToolPattern = /^[a-z0-9-]+__[A-Z0-9_]+(?:_[0-9a-f]{8})?$/;
|
||||
/** A user's own browser's tool, named under the browser's slug. */
|
||||
const SlugBrowserPattern = /__browser_/;
|
||||
|
||||
@@ -38,6 +40,15 @@ export default function unknownToolMessage({ name, tools }: Params) {
|
||||
return `Error: There is no tool called "${name}". Your browser tools carry the browser's slug, e.g. "${own.name}". ${available}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The connector router keeps an app's tools out of the run's own, so a
|
||||
* model that saw `gmail__GMAIL_SEND_EMAIL` in a search result and called
|
||||
* it by name is told how it runs instead of that it doesn't exist.
|
||||
*/
|
||||
if (ConnectorToolPattern.test(name) && tools.some((t) => t.name == "connectors_execute")) {
|
||||
return `Error: "${name}" is a connected app's tool, not one of yours: run it with connectors_execute, {"tool": "${name}", "arguments": {...}}, after reading its arguments with connectors_get_tool_schemas. Nothing ran.`;
|
||||
}
|
||||
|
||||
if (!ComputerToolPattern.test(name)) {
|
||||
return `Error: There is no tool called "${name}". ${available}`;
|
||||
}
|
||||
|
||||
@@ -7,10 +7,12 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotConnectorEntry, ConnectorAppIcon } from "@/src/types";
|
||||
import type { BotConnectorEntry, BotConnectorRouterEntry, ConnectorAppIcon } from "@/src/types";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import ComposerConnectorPicker from "./composer-connector-picker";
|
||||
import ComposerConnectorRow from "./composer-connector-row";
|
||||
import ComposerRouterPicker from "./composer-router-picker";
|
||||
import ComposerRouterRow from "./composer-router-row";
|
||||
|
||||
type Props = {
|
||||
bot_id: number;
|
||||
@@ -36,7 +38,8 @@ type Props = {
|
||||
* The connectors this bot can use for the person chatting, shown under the
|
||||
* tools in the composer's modal. Apps given to the bot by the workspace or
|
||||
* the install, and the ones this user attached, with the accounts that
|
||||
* reach there. Sign-in itself lives in Settings > Connectors.
|
||||
* reach there, then the routers reaching it. Sign-in itself lives in
|
||||
* Settings > Connectors.
|
||||
*/
|
||||
export default function ComposerConnectorsSection({
|
||||
bot_id,
|
||||
@@ -49,7 +52,8 @@ export default function ComposerConnectorsSection({
|
||||
const [error, setError] = useState<string>();
|
||||
const [notice, setNotice] = useState<string>();
|
||||
const [tick, setTick] = useState(0);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [adding, setAdding] = useState<"app" | "router">();
|
||||
const [routers, setRouters] = useState<BotConnectorRouterEntry[]>([]);
|
||||
|
||||
const reload = useCallback((msg?: string) => {
|
||||
if (msg) setNotice(msg);
|
||||
@@ -70,6 +74,20 @@ export default function ComposerConnectorsSection({
|
||||
reload(`${entry.connector.name} is no longer on this bot.`);
|
||||
};
|
||||
|
||||
const removeRouter = async ({ entry }: { entry: BotConnectorRouterEntry }) => {
|
||||
const res = await postAdminApi({
|
||||
path: "connectors/set-bot-router",
|
||||
body: { router_id: entry.router.id, bot_id, attached: false },
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || `Couldn't remove ${entry.router.name}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
reload(`${entry.router.name} is no longer on this bot.`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
@@ -81,12 +99,16 @@ export default function ComposerConnectorsSection({
|
||||
setError(undefined);
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<BotConnectorEntry[]>
|
||||
>(`/api/admin/connectors/bot?${params.toString()}`, {
|
||||
method: "GET",
|
||||
});
|
||||
const [res, router_res] = await Promise.all([
|
||||
fetchApi<Record<string, unknown>, APIResponseObject<BotConnectorEntry[]>>(
|
||||
`/api/admin/connectors/bot?${params.toString()}`,
|
||||
{ method: "GET" },
|
||||
),
|
||||
fetchApi<Record<string, unknown>, APIResponseObject<{ routers: BotConnectorRouterEntry[] }>>(
|
||||
`/api/admin/connectors/bot-routers?${params.toString()}`,
|
||||
{ method: "GET" },
|
||||
).catch(() => null),
|
||||
]);
|
||||
|
||||
if (!live) return;
|
||||
|
||||
@@ -96,20 +118,31 @@ export default function ComposerConnectorsSection({
|
||||
}
|
||||
|
||||
const entries = res.singleRes || [];
|
||||
const router_entries = router_res?.success ? router_res.singleRes?.routers || [] : [];
|
||||
/**
|
||||
* The icons on the tools button: apps with a connected account
|
||||
* reaching here, directly or through a router, each once.
|
||||
*/
|
||||
const icons = new Map<number, ConnectorAppIcon>();
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.accounts.some((account) => account.status == "connected")) continue;
|
||||
|
||||
icons.set(Number(entry.connector.id), {
|
||||
id: Number(entry.connector.id),
|
||||
name: entry.connector.name,
|
||||
logo: entry.connector.logo,
|
||||
});
|
||||
}
|
||||
|
||||
for (const app of router_entries.flatMap((entry) => entry.router.apps)) {
|
||||
if (app.accounts && !icons.has(app.id)) icons.set(app.id, { id: app.id, name: app.name, logo: app.logo });
|
||||
}
|
||||
|
||||
setItems(entries);
|
||||
onCount?.(entries.length);
|
||||
onApps?.(
|
||||
entries
|
||||
.filter((entry) =>
|
||||
entry.accounts.some((account) => account.status == "connected"),
|
||||
)
|
||||
.map((entry) => ({
|
||||
id: Number(entry.connector.id),
|
||||
name: entry.connector.name,
|
||||
logo: entry.connector.logo,
|
||||
})),
|
||||
);
|
||||
setRouters(router_entries);
|
||||
onCount?.(entries.length + router_entries.length);
|
||||
onApps?.([...icons.values()]);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
@@ -124,18 +157,26 @@ export default function ComposerConnectorsSection({
|
||||
Connectors
|
||||
</Span>
|
||||
<Button
|
||||
title={
|
||||
adding
|
||||
? "Stop adding a connector"
|
||||
: "Add a connector to this bot"
|
||||
}
|
||||
title="Add a router to this bot"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={<Plus size={12} aria-hidden />}
|
||||
className="shrink-0 gap-1! px-1.5! py-0.5! text-[12px] leading-4"
|
||||
onClick={() => setAdding((value) => !value)}
|
||||
onClick={() => setAdding("router")}
|
||||
>
|
||||
Router
|
||||
</Button>
|
||||
<Button
|
||||
title="Add a connector to this bot"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={<Plus size={12} aria-hidden />}
|
||||
className="shrink-0 gap-1! px-1.5! py-0.5! text-[12px] leading-4"
|
||||
onClick={() => setAdding("app")}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
@@ -158,8 +199,15 @@ export default function ComposerConnectorsSection({
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Reading connectors...
|
||||
</Span>
|
||||
) : items.length ? (
|
||||
) : items.length || routers.length ? (
|
||||
<Stack className="w-full py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface">
|
||||
{routers.map((entry) => (
|
||||
<ComposerRouterRow
|
||||
key={`router-${entry.router.id}`}
|
||||
entry={entry}
|
||||
onRemove={entry.removable ? () => void removeRouter({ entry }) : undefined}
|
||||
/>
|
||||
))}
|
||||
{items.map((entry) => (
|
||||
<ComposerConnectorRow
|
||||
key={entry.connector.id}
|
||||
@@ -185,19 +233,31 @@ export default function ComposerConnectorsSection({
|
||||
</Span>
|
||||
)}
|
||||
|
||||
{adding ? (
|
||||
{adding == "app" ? (
|
||||
<ComposerConnectorPicker
|
||||
bot_id={bot_id}
|
||||
workspace_id={workspace_id}
|
||||
onAdded={(msg) => {
|
||||
setAdding(false);
|
||||
setAdding(undefined);
|
||||
reload(msg);
|
||||
}}
|
||||
onCancel={() => setAdding(false)}
|
||||
onCancel={() => setAdding(undefined)}
|
||||
onError={setError}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{adding == "router" ? (
|
||||
<ComposerRouterPicker
|
||||
bot_id={bot_id}
|
||||
workspace_id={workspace_id}
|
||||
onAdded={(msg) => {
|
||||
setAdding(undefined);
|
||||
reload(msg);
|
||||
}}
|
||||
onCancel={() => setAdding(undefined)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Span variant="faded" size="smaller">
|
||||
Manage connectors{" "}
|
||||
<Link
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import ConnectorLogo from "@/src/pages/admin/settings/connectors/(partials)/connector-logo";
|
||||
import type { ConnectorRouterApp } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
app: ConnectorRouterApp;
|
||||
};
|
||||
|
||||
/**
|
||||
* One app a router brings, listed under the router in the composer's tools
|
||||
* modal, so the apps the bot reaches through it read as apps rather than as
|
||||
* a line of names: its logo, its name, and the accounts it uses.
|
||||
*/
|
||||
export default function ComposerRouterAppRow({ app }: Props) {
|
||||
const accounts = app.all_accounts
|
||||
? app.accounts
|
||||
? "Your accounts, and any given here"
|
||||
: "No account connected yet"
|
||||
: app.account_list.map((account) => account.label).join(", ") || "No account left";
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-2.5! flex-nowrap items-center pl-8 pr-3 py-1.5">
|
||||
<ConnectorLogo logo={app.logo} name={app.name} />
|
||||
<Stack className="grow min-w-0 gap-0!">
|
||||
<Span className="text-sm leading-5 truncate text-ink">{app.name}</Span>
|
||||
<Span title={accounts} className="text-xs leading-4 truncate w-full text-ink-secondary">
|
||||
{accounts}
|
||||
</Span>
|
||||
</Stack>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Check } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { ConnectorRouterRecord } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
router: ConnectorRouterRecord;
|
||||
picked: boolean;
|
||||
onPick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One router the composer's router picker lists: its name and its apps.
|
||||
*/
|
||||
export default function ComposerRouterOption({ router, picked, onPick }: Props) {
|
||||
const apps = router.apps.map((app) => app.name).join(", ");
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={router.name}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
onClick={onPick}
|
||||
className={twMerge("w-full justify-start! rounded-none! px-3! py-1.5!", picked && "bg-sunken!")}
|
||||
>
|
||||
<Row className="w-full gap-2.5! flex-nowrap items-center">
|
||||
<Stack className="grow min-w-0 items-start gap-0!">
|
||||
<Span className="text-sm leading-5 truncate w-full text-left text-ink">{router.name}</Span>
|
||||
<Span className="text-xs leading-4 truncate w-full text-left text-ink-secondary">
|
||||
{apps || "No apps"}
|
||||
</Span>
|
||||
</Stack>
|
||||
{picked ? <Check size={14} aria-hidden /> : null}
|
||||
</Row>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ConnectorConnectionRecord, ConnectorConnectionsPayload, ConnectorRouterRecord } from "@/src/types";
|
||||
import ComposerRouterOption from "./composer-router-option";
|
||||
|
||||
type Props = {
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
onAdded: (msg: string) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a router to this bot for the person chatting: pick the connection,
|
||||
* then one of its routers not already reaching the bot here. Its apps then
|
||||
* reach their runs on the bot through the router's tools, with the accounts
|
||||
* those runs reach.
|
||||
*/
|
||||
export default function ComposerRouterPicker({ bot_id, workspace_id, onAdded, onCancel }: Props) {
|
||||
const [connections, setConnections] = useState<ConnectorConnectionRecord[]>();
|
||||
const [connection_id, setConnectionId] = useState(0);
|
||||
const [items, setItems] = useState<ConnectorRouterRecord[]>();
|
||||
const [router_id, setRouterId] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<Record<string, unknown>, APIResponseObject<ConnectorConnectionsPayload>>(
|
||||
"/api/admin/connectors/connections",
|
||||
{ method: "GET" },
|
||||
);
|
||||
|
||||
if (!live) return;
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't read the connections.");
|
||||
return;
|
||||
}
|
||||
|
||||
const all = res.singleRes?.connections || [];
|
||||
setConnections(all);
|
||||
setConnectionId(Number(all[0]?.id) || 0);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!connection_id) return;
|
||||
|
||||
let live = true;
|
||||
const params = new URLSearchParams({ bot_id: String(bot_id), connection_id: String(connection_id) });
|
||||
|
||||
if (workspace_id) params.set("workspace_id", String(workspace_id));
|
||||
|
||||
setItems(undefined);
|
||||
setRouterId(0);
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<{ attachable: ConnectorRouterRecord[] }>
|
||||
>(`/api/admin/connectors/bot-routers?${params.toString()}`, { method: "GET" });
|
||||
|
||||
if (!live) return;
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't read that connection's routers.");
|
||||
return;
|
||||
}
|
||||
|
||||
setItems(res.singleRes?.attachable || []);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [bot_id, workspace_id, connection_id]);
|
||||
|
||||
const add = async () => {
|
||||
const router = items?.find((item) => item.id == router_id);
|
||||
|
||||
if (!router) {
|
||||
setError("Pick a router first.");
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await postAdminApi({
|
||||
path: "connectors/set-bot-router",
|
||||
body: { bot_id, router_id: router.id, attached: true },
|
||||
});
|
||||
|
||||
setBusy(false);
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || `Couldn't add ${router.name}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
onAdded(`${router.name} is now on this bot, for your runs.`);
|
||||
};
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => {
|
||||
if (!next) onCancel();
|
||||
}}
|
||||
title="Add a router"
|
||||
description="A router reaches several connected apps through a few tools instead of each app's own, so the bot's context stays small."
|
||||
>
|
||||
<Form submitHandler={() => void add()} className="w-full flex-col gap-3! items-stretch">
|
||||
<SearchSelect
|
||||
id="composer-router-connection"
|
||||
title="Connection"
|
||||
options={(connections || []).map((connection) => ({
|
||||
title: connection.name,
|
||||
value: String(connection.id),
|
||||
}))}
|
||||
defaultValues={connection_id ? [String(connection_id)] : []}
|
||||
changeHandler={(value) => {
|
||||
const picked = Array.isArray(value) ? value[0] : value;
|
||||
setConnectionId(Number(picked) || 0);
|
||||
}}
|
||||
/>
|
||||
|
||||
{items === undefined ? (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">Reading routers...</Span>
|
||||
) : items.length ? (
|
||||
<Stack className="w-full max-h-52 overflow-y-auto py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface">
|
||||
{items.map((router) => (
|
||||
<ComposerRouterOption
|
||||
key={router.id}
|
||||
router={router}
|
||||
picked={router.id == router_id}
|
||||
onPick={() => setRouterId(router.id)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Nothing to add: this connection has no router, or every one already reaches this bot. A super
|
||||
admin makes routers in Settings > Connectors.
|
||||
</Span>
|
||||
)}
|
||||
|
||||
<AddFormActions submit_label="Add" loading={busy} error={error} onCancel={onCancel} />
|
||||
</Form>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import { Route, X } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import type { BotConnectorRouterEntry } from "@/src/types";
|
||||
import ComposerRouterAppRow from "./composer-router-app-row";
|
||||
|
||||
type Props = {
|
||||
entry: BotConnectorRouterEntry;
|
||||
/**
|
||||
* Takes this user's own attachment off the bot. Not given for a
|
||||
* workspace's or the install's.
|
||||
*/
|
||||
onRemove?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One router in the composer's tools modal: its name, its connection, where
|
||||
* it comes from and a way to take it off the bot, then each app it brings
|
||||
* as a row of its own (the tools button draws their logos, so the list must
|
||||
* name them too).
|
||||
*/
|
||||
export default function ComposerRouterRow({ entry, onRemove }: Props) {
|
||||
const { router } = entry;
|
||||
const via = entry.via == "global" ? "Every bot" : entry.via == "workspace" ? "From this workspace" : "Only you";
|
||||
const count = `${router.apps.length} ${router.apps.length == 1 ? "app" : "apps"}`;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch pb-1 border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<Row className="w-full gap-2.5! flex-nowrap items-center px-3 py-2">
|
||||
<IconTile Icon={Route} />
|
||||
<Stack className="grow min-w-0 gap-0.5!">
|
||||
<Row className="w-full gap-1.5! flex-nowrap items-center min-w-0">
|
||||
<Span title={router.description} className="text-sm leading-5 truncate text-ink">
|
||||
{router.name}
|
||||
</Span>
|
||||
{entry.connection_name ? (
|
||||
<Tag color="success" className="shrink-0">
|
||||
{entry.connection_name}
|
||||
</Tag>
|
||||
) : null}
|
||||
<Tag variant="outlined" color="gray" className="shrink-0">
|
||||
Router
|
||||
</Tag>
|
||||
</Row>
|
||||
<Span className="text-xs leading-4 truncate w-full text-ink-secondary">
|
||||
{`${via} · ${count}, reached through the router's search`}
|
||||
</Span>
|
||||
</Stack>
|
||||
{onRemove ? (
|
||||
<Button
|
||||
title={`Remove ${router.name}`}
|
||||
aria-label={`Remove ${router.name}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="shrink-0 p-1!"
|
||||
onClick={onRemove}
|
||||
>
|
||||
<X size={14} aria-hidden />
|
||||
</Button>
|
||||
) : null}
|
||||
</Row>
|
||||
{router.apps.map((app) => (
|
||||
<ComposerRouterAppRow key={app.id} app={app} />
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import grabRunLimitsOverview from "@/src/functions/backend/db/app-settings/grab-
|
||||
import grabSkillLimitsOverview from "@/src/functions/backend/db/app-settings/grab-skill-limits";
|
||||
import grabHookCallRetentionOverview from "@/src/functions/backend/db/app-settings/grab-hook-events-keep-days";
|
||||
import grabBotTraceRetentionOverview from "@/src/functions/backend/db/app-settings/grab-bot-trace-keep-days";
|
||||
import grabConnectorSettingsOverview from "@/src/functions/backend/db/connectors/grab-connector-settings-overview";
|
||||
import grabLogRetentionOverview from "@/src/functions/backend/db/app-settings/grab-logs-keep-days";
|
||||
import grabAskRetention from "@/src/functions/backend/db/app-settings/grab-ask-retention";
|
||||
import grabSessionLengthOverview from "@/src/functions/backend/db/app-settings/grab-bot-session-max-messages";
|
||||
@@ -59,6 +60,7 @@ export default async function grabSettingsServerProps({ req }: Params) {
|
||||
skill_limits: await grabSkillLimitsOverview().catch(() => null),
|
||||
hook_call_retention: await grabHookCallRetentionOverview().catch(() => null),
|
||||
bot_trace_retention: await grabBotTraceRetentionOverview().catch(() => null),
|
||||
connector_settings: await grabConnectorSettingsOverview().catch(() => null),
|
||||
log_retention: await grabLogRetentionOverview().catch(() => null),
|
||||
ask_retention: await grabAskRetention().catch(() => null),
|
||||
session_length: await grabSessionLengthOverview().catch(() => null),
|
||||
|
||||
@@ -5,6 +5,8 @@ import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
avatar: ReactNode;
|
||||
@@ -21,6 +23,11 @@ type Props = {
|
||||
* A word beside the title, e.g. "Default" or "You".
|
||||
*/
|
||||
badge?: string;
|
||||
/**
|
||||
* `error`: the badge is a fault (a runner that is down), drawn as an
|
||||
* outlined error tag instead of a quiet word.
|
||||
*/
|
||||
badge_tone?: "error";
|
||||
/**
|
||||
* A mark right after the title, e.g. a workspace admin's shield.
|
||||
*/
|
||||
@@ -48,6 +55,7 @@ export default function SettingsListRow({
|
||||
href,
|
||||
onOpen,
|
||||
badge,
|
||||
badge_tone,
|
||||
title_icon,
|
||||
subtitle,
|
||||
selected,
|
||||
@@ -58,7 +66,17 @@ export default function SettingsListRow({
|
||||
<Span className="block text-sm font-bold leading-5 text-ink truncate w-full">
|
||||
{title}
|
||||
{title_icon ? <Span className="ml-1.5 inline-flex align-middle">{title_icon}</Span> : null}
|
||||
{badge ? <Span className="ml-2 text-[11px] font-bold leading-4 text-ink-secondary">{badge}</Span> : null}
|
||||
{badge && badge_tone == "error" ? (
|
||||
<Tag
|
||||
color="error"
|
||||
variant="outlined"
|
||||
className={twMerge("ml-2 inline-flex align-middle", "px-1.5 py-0 text-[11px] font-bold leading-4")}
|
||||
>
|
||||
{badge}
|
||||
</Tag>
|
||||
) : badge ? (
|
||||
<Span className="ml-2 text-[11px] font-bold leading-4 text-ink-secondary">{badge}</Span>
|
||||
) : null}
|
||||
</Span>
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { ConnectorRoutersPayload } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
connection_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One connection's routers, read when the Routers tab opens and again after
|
||||
* each change.
|
||||
*/
|
||||
export default function useConnectorRouters({ connection_id }: Params) {
|
||||
const [payload, setPayload] = useState<ConnectorRoutersPayload>();
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!connection_id) return;
|
||||
|
||||
setError(undefined);
|
||||
|
||||
const res = await fetchApi<Record<string, unknown>, APIResponseObject<ConnectorRoutersPayload>>(
|
||||
`/api/admin/connectors/routers?connection_id=${connection_id}`,
|
||||
{ method: "GET" },
|
||||
).catch(() => null);
|
||||
|
||||
if (!res?.success || !res.singleRes) {
|
||||
setError(res?.msg || "Couldn't read this connection's routers.");
|
||||
return;
|
||||
}
|
||||
|
||||
setPayload(res.singleRes);
|
||||
}, [connection_id]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { payload, error, refresh };
|
||||
}
|
||||
@@ -5,17 +5,17 @@ import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type {
|
||||
ConnectorAccess,
|
||||
ConnectorRecord,
|
||||
ExtensionTargets,
|
||||
} from "@/src/types";
|
||||
import type { ExtensionTargets } from "@/src/types";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import Spacer from "@moduletrace/twui/layout/Spacer";
|
||||
|
||||
type Props = {
|
||||
connector: ConnectorRecord;
|
||||
access: ConnectorAccess | undefined;
|
||||
/**
|
||||
* What is being given: an app, or a router of apps. Each has its own
|
||||
* routes, with the same three tiers.
|
||||
*/
|
||||
subject: { kind: "connector" | "router"; id: number; name: string; all_bots: boolean };
|
||||
access: { bot_ids: number[]; workspace_ids: number[] } | undefined;
|
||||
targets: ExtensionTargets;
|
||||
/**
|
||||
* The bots the viewer reaches, for their own runs there.
|
||||
@@ -26,19 +26,21 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Where one connector reaches. A bot picked here is personal: only the runs
|
||||
* of whoever picked it see the connector there. Workspaces and every bot
|
||||
* Where one connector app or router reaches. A bot picked here is personal:
|
||||
* only the runs of whoever picked it see it there. Workspaces and every bot
|
||||
* are the install's, so a super admin sets those.
|
||||
*/
|
||||
export default function ConnectorAccessModal({
|
||||
connector,
|
||||
subject,
|
||||
access,
|
||||
targets,
|
||||
bots,
|
||||
onSaved,
|
||||
onCancel,
|
||||
}: Props) {
|
||||
const [all_bots, setAllBots] = useState(Boolean(connector.all_bots));
|
||||
const [all_bots, setAllBots] = useState(Boolean(subject.all_bots));
|
||||
const router = subject.kind == "router";
|
||||
const id_body = router ? { router_id: subject.id } : { connector_id: subject.id };
|
||||
const [bot_ids, setBotIds] = useState<number[]>(access?.bot_ids || []);
|
||||
const [workspace_ids, setWorkspaceIds] = useState<number[]>(
|
||||
access?.workspace_ids || [],
|
||||
@@ -54,8 +56,8 @@ export default function ConnectorAccessModal({
|
||||
|
||||
if (targets.can_edit) {
|
||||
const saved = await postAdminApi({
|
||||
path: "connectors/set-access",
|
||||
body: { connector_id: connector.id, workspace_ids, all_bots },
|
||||
path: router ? "connectors/set-router-access" : "connectors/set-access",
|
||||
body: { ...id_body, workspace_ids, all_bots },
|
||||
});
|
||||
|
||||
if (!saved.success) {
|
||||
@@ -78,10 +80,10 @@ export default function ConnectorAccessModal({
|
||||
|
||||
for (const change of changes) {
|
||||
const res = await postAdminApi({
|
||||
path: "connectors/set-bot",
|
||||
path: router ? "connectors/set-bot-router" : "connectors/set-bot",
|
||||
body: {
|
||||
...id_body,
|
||||
bot_id: change.bot_id,
|
||||
connector_id: connector.id,
|
||||
attached: change.attached,
|
||||
},
|
||||
});
|
||||
@@ -95,7 +97,7 @@ export default function ConnectorAccessModal({
|
||||
|
||||
setLoading(false);
|
||||
|
||||
onSaved(`Saved where ${connector.name} reaches.`);
|
||||
onSaved(`Saved where ${subject.name} reaches.`);
|
||||
};
|
||||
|
||||
const ids = (value: unknown) =>
|
||||
@@ -105,9 +107,11 @@ export default function ConnectorAccessModal({
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => !next && onCancel()}
|
||||
title={`Who gets ${connector.name}`}
|
||||
title={`Who gets ${subject.name}`}
|
||||
description={
|
||||
"A bot picked here is yours: it reaches the connector only in your runs there, with your own accounts. A workspace reaches everyone working in it, with every account connected for this connector. Every bot reaches the whole install, each user with their own accounts."
|
||||
router
|
||||
? "A bot picked here is yours: it reaches the router's apps only in your runs there, with your own accounts. A workspace reaches everyone working in it, with every account connected for those apps. Every bot reaches the whole install, each user with their own accounts."
|
||||
: "A bot picked here is yours: it reaches the connector only in your runs there, with your own accounts. A workspace reaches everyone working in it, with every account connected for this connector. Every bot reaches the whole install, each user with their own accounts."
|
||||
}
|
||||
>
|
||||
<Form
|
||||
@@ -115,7 +119,7 @@ export default function ConnectorAccessModal({
|
||||
onSubmit={submit}
|
||||
>
|
||||
<SearchSelect
|
||||
id={`connector-${connector.id}-my-bots`}
|
||||
id={`${subject.kind}-${subject.id}-my-bots`}
|
||||
title="Your bots"
|
||||
label="Your bots"
|
||||
showLabel
|
||||
@@ -139,7 +143,7 @@ export default function ConnectorAccessModal({
|
||||
/>
|
||||
<Spacer className="h-4" />
|
||||
<SearchSelect
|
||||
id={`connector-${connector.id}-workspaces`}
|
||||
id={`${subject.kind}-${subject.id}-workspaces`}
|
||||
title="Workspaces"
|
||||
label="Workspaces"
|
||||
showLabel
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import { Cable } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
|
||||
type Props = {
|
||||
logo: string;
|
||||
name: string;
|
||||
/**
|
||||
* The small mark inside a tag (a router's apps), rather than a list
|
||||
* row's avatar.
|
||||
*/
|
||||
small?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -13,17 +19,24 @@ type Props = {
|
||||
* icons. The tile stays put while the picture loads, and an app whose logo
|
||||
* is missing or broken shows the connector icon instead.
|
||||
*/
|
||||
export default function ConnectorLogo({ logo, name }: Props) {
|
||||
export default function ConnectorLogo({ logo, name, small }: Props) {
|
||||
if (!logo && small) return <Cable size={14} aria-hidden className="shrink-0" />;
|
||||
|
||||
if (!logo) return <IconTile Icon={Cable} />;
|
||||
|
||||
return (
|
||||
<Span className="size-8 shrink-0 flex items-center justify-center overflow-hidden rounded-default-sm border border-solid border-hairline bg-paper p-1">
|
||||
<Span
|
||||
className={twMerge(
|
||||
"size-8 shrink-0 flex items-center justify-center overflow-hidden rounded-default-sm border border-solid border-hairline bg-paper p-1",
|
||||
small && "size-4 p-0 border-0 bg-transparent",
|
||||
)}
|
||||
>
|
||||
<Img
|
||||
src={logo}
|
||||
alt={name}
|
||||
className="size-full object-contain"
|
||||
imgErrComp={<Cable size={16} aria-hidden />}
|
||||
imgErrComp={<Cable size={small ? 12 : 16} aria-hidden />}
|
||||
/>
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import type { ConnectorRouterAccount } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
account: ConnectorRouterAccount;
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One account the Add app modal offers: its label, whose it is, and its
|
||||
* status when it isn't connected.
|
||||
*/
|
||||
export default function ConnectorRouterAccountCheck({ account, checked, onChange }: Props) {
|
||||
const label = `${account.label}${account.owner_name ? ` · ${account.owner_name}` : ""}${account.status == "connected" ? "" : ` (${account.status})`}`;
|
||||
|
||||
return <Checkbox title={label} label={label} checked={checked} clickDispatchHandler={onChange} />;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { ConnectorRouterApp } from "@/src/types";
|
||||
import ConnectorLogo from "./connector-logo";
|
||||
|
||||
type Props = {
|
||||
app: ConnectorRouterApp;
|
||||
};
|
||||
|
||||
/**
|
||||
* One app of a router, as its row lists it: logo and name (with the
|
||||
* accounts it uses, when it picked some), faded when no account for it is
|
||||
* connected any more (its tools have nothing to run
|
||||
* through until someone signs in again).
|
||||
*/
|
||||
export default function ConnectorRouterAppTag({ app }: Props) {
|
||||
const picked = app.all_accounts ? "" : app.account_list.map((account) => account.label).join(", ");
|
||||
const title = app.all_accounts
|
||||
? app.accounts
|
||||
? `${app.name}: every account (${app.accounts} connected)`
|
||||
: `${app.name}: no account connected`
|
||||
: `${app.name}: ${picked || "no account left"}`;
|
||||
|
||||
return (
|
||||
<Row
|
||||
title={title}
|
||||
className={twMerge(
|
||||
"gap-1.5! flex-nowrap items-center rounded-default border border-solid border-hairline px-2 py-0.5",
|
||||
(app.all_accounts ? !app.accounts : !app.account_list.some((account) => account.status == "connected")) &&
|
||||
"opacity-60",
|
||||
)}
|
||||
>
|
||||
<ConnectorLogo logo={app.logo} name={app.name} small />
|
||||
<Span className="text-xs leading-4 text-ink">{picked ? `${app.name} · ${picked}` : app.name}</Span>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useState } from "react";
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Plus } from "lucide-react";
|
||||
import Textarea from "@moduletrace/twui/form/Textarea";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ConnectorRouterApp, ConnectorRouterRecord } from "@/src/types";
|
||||
import {
|
||||
routerAppCatalog,
|
||||
routerPicksFromApps,
|
||||
setRouterPick,
|
||||
type RouterPick,
|
||||
} from "@/src/utils/router-pick-options";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import ConnectorRouterPickModal from "./connector-router-pick-modal";
|
||||
import ConnectorRouterPickRow from "./connector-router-pick-row";
|
||||
|
||||
type Props = {
|
||||
connection_id: number;
|
||||
connection_name: string;
|
||||
/**
|
||||
* The router being changed; left out, a new one is made.
|
||||
*/
|
||||
router?: ConnectorRouterRecord;
|
||||
/**
|
||||
* The connection's connected apps a router may pick.
|
||||
*/
|
||||
choices: ConnectorRouterApp[];
|
||||
onSaved: (msg: string) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes or changes a router: a name, what it is for, and which of the
|
||||
* connection's connected apps it reaches, each with every account or
|
||||
* particular ones (added one app at a time through Add app). A bot given the router gets four
|
||||
* tools that search, describe and run those apps' tools, instead of every
|
||||
* tool of every app.
|
||||
*/
|
||||
export default function ConnectorRouterModal({
|
||||
connection_id,
|
||||
connection_name,
|
||||
router,
|
||||
choices,
|
||||
onSaved,
|
||||
onCancel,
|
||||
}: Props) {
|
||||
const [name, setName] = useState(router?.name || "");
|
||||
const [description, setDescription] = useState(router?.description || "");
|
||||
const [enabled, setEnabled] = useState(router ? router.enabled : true);
|
||||
const [picks, setPicks] = useState<RouterPick[]>(routerPicksFromApps({ apps: router?.apps || [] }));
|
||||
/**
|
||||
* The Add app modal: `0` to add one, an app's id to change its accounts.
|
||||
*/
|
||||
const [picking, setPicking] = useState<number>();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
const catalog = routerAppCatalog({ choices, held: router?.apps });
|
||||
|
||||
const submit = async () => {
|
||||
if (loading) return;
|
||||
|
||||
if (!picks.length) {
|
||||
setError("Add at least one app.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window.confirm(router ? `Save the changes to ${router.name}?` : `Make the router ${name.trim() || ""}?`)) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await postAdminApi({
|
||||
path: "connectors/save-router",
|
||||
body: {
|
||||
router_id: router?.id,
|
||||
connection_id,
|
||||
name,
|
||||
description,
|
||||
enabled,
|
||||
apps: picks,
|
||||
},
|
||||
});
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't save the router.");
|
||||
return;
|
||||
}
|
||||
|
||||
onSaved(res.msg || `Saved ${name}.`);
|
||||
};
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => !next && onCancel()}
|
||||
title={router ? `Edit ${router.name}` : "New router"}
|
||||
description={`A router reaches several of ${connection_name}'s connected apps through four tools: search, read arguments, run, and connect. Its apps' own tools never fill a bot's prompt, however many there are.`}
|
||||
>
|
||||
<Form className="w-full gap-4! items-stretch pt-4" onSubmit={submit}>
|
||||
<Input
|
||||
id="router-name"
|
||||
title="Name"
|
||||
label="Name"
|
||||
showLabel
|
||||
placeholder="Work apps"
|
||||
defaultValue={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
<Textarea
|
||||
id="router-description"
|
||||
title="What it is for"
|
||||
label="What it is for"
|
||||
showLabel
|
||||
rows={2}
|
||||
placeholder="Email, calendar and docs for the team's day-to-day work."
|
||||
defaultValue={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
/>
|
||||
<Stack className="w-full gap-1.5! items-stretch">
|
||||
<Row className="w-full items-center gap-2!">
|
||||
<Span className="grow text-sm leading-5 font-bold text-ink">Apps</Span>
|
||||
<Button
|
||||
title="Add an app to this router"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={<Plus size={12} aria-hidden />}
|
||||
className="shrink-0 gap-1! text-[12px] leading-4"
|
||||
onClick={() => setPicking(0)}
|
||||
>
|
||||
Add app
|
||||
</Button>
|
||||
</Row>
|
||||
{picks.length ? (
|
||||
<Stack className="w-full py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface">
|
||||
{picks.map((pick) => (
|
||||
<ConnectorRouterPickRow
|
||||
key={pick.connector_id}
|
||||
pick={pick}
|
||||
app={catalog.find((app) => app.id == pick.connector_id)}
|
||||
onEdit={() => setPicking(pick.connector_id)}
|
||||
onRemove={() =>
|
||||
setPicks((current) =>
|
||||
current.filter((entry) => entry.connector_id != pick.connector_id),
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
No apps yet. Add one, with every account or particular ones.
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
<Checkbox title="On" label="On: bots it is given to reach it" checked={enabled} changeHandler={setEnabled} />
|
||||
<AddFormActions submit_label={router ? "Save" : "Make router"} loading={loading} onCancel={onCancel} />
|
||||
<SettingsStatus status={error ? { error: true, msg: error } : undefined} />
|
||||
</Form>
|
||||
{picking !== undefined ? (
|
||||
<ConnectorRouterPickModal
|
||||
catalog={catalog}
|
||||
picks={picks}
|
||||
connector_id={picking || undefined}
|
||||
onPick={(pick) => {
|
||||
setPicks((current) => setRouterPick({ picks: current, pick }));
|
||||
setPicking(undefined);
|
||||
setError(undefined);
|
||||
}}
|
||||
onCancel={() => setPicking(undefined)}
|
||||
/>
|
||||
) : null}
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useState } from "react";
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import type { ConnectorRouterApp } from "@/src/types";
|
||||
import type { RouterPick } from "@/src/utils/router-pick-options";
|
||||
import ConnectorRouterAccountCheck from "./connector-router-account-check";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* Every app the router can name, with its accounts.
|
||||
*/
|
||||
catalog: ConnectorRouterApp[];
|
||||
/**
|
||||
* What the form holds already: picking an app it has starts from its
|
||||
* current accounts, and the choice replaces them.
|
||||
*/
|
||||
picks: RouterPick[];
|
||||
/**
|
||||
* Opens on this app (changing one already in the form).
|
||||
*/
|
||||
connector_id?: number;
|
||||
onPick: (pick: RouterPick) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds one app to a router, or changes the accounts of one it holds: pick
|
||||
* the app, then every account (whoever runs the bot uses what they reach,
|
||||
* as for an app given directly) or particular accounts (which then reach
|
||||
* every run the router reaches, acting as their owners).
|
||||
*/
|
||||
export default function ConnectorRouterPickModal({ catalog, picks, connector_id: start, onPick, onCancel }: Props) {
|
||||
const startPick = (id: number) => picks.find((pick) => pick.connector_id == id);
|
||||
const [connector_id, setConnectorId] = useState(start || 0);
|
||||
const [all, setAll] = useState(start ? !startPick(start)?.account_ids.length : true);
|
||||
const [account_ids, setAccountIds] = useState<number[]>(start ? startPick(start)?.account_ids || [] : []);
|
||||
const [error, setError] = useState<string>();
|
||||
const app = catalog.find((entry) => entry.id == connector_id);
|
||||
|
||||
const chooseApp = (id: number) => {
|
||||
const held = startPick(id);
|
||||
|
||||
setConnectorId(id);
|
||||
setAll(!held?.account_ids.length);
|
||||
setAccountIds(held?.account_ids || []);
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const submit = () => {
|
||||
if (!app) {
|
||||
setError("Pick an app.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!all && !account_ids.length) {
|
||||
setError("Pick at least one account, or every account.");
|
||||
return;
|
||||
}
|
||||
|
||||
onPick({ connector_id: app.id, account_ids: all ? [] : account_ids });
|
||||
};
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => !next && onCancel()}
|
||||
title={start ? `${app?.name || "App"} in this router` : "Add an app"}
|
||||
description="Pick an app, then every account or particular ones. Particular accounts reach every run the router reaches, acting as whoever connected them."
|
||||
>
|
||||
<Form className="w-full gap-4! items-stretch pt-4" onSubmit={submit}>
|
||||
{start ? null : (
|
||||
<SearchSelect
|
||||
id="router-pick-app"
|
||||
title="App"
|
||||
label="App"
|
||||
showLabel
|
||||
placeholder="Pick an app"
|
||||
options={catalog.map((entry) => ({
|
||||
value: String(entry.id),
|
||||
title: picks.some((pick) => pick.connector_id == entry.id)
|
||||
? `${entry.name} (in this router)`
|
||||
: entry.name,
|
||||
}))}
|
||||
defaultValues={connector_id ? [String(connector_id)] : []}
|
||||
info={
|
||||
catalog.length
|
||||
? "Only apps somebody has connected an account for."
|
||||
: "No app of this connection has a connected account yet: connect one on the Apps tab first."
|
||||
}
|
||||
changeHandler={(value) => chooseApp(Number(Array.isArray(value) ? value[0] : value) || 0)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{app ? (
|
||||
<Stack className="w-full gap-2! items-stretch">
|
||||
<Span className="text-xs leading-4 font-bold text-ink">Accounts</Span>
|
||||
<Checkbox
|
||||
title="Every account"
|
||||
label="Every account: each run uses the accounts it reaches, as for an app given directly"
|
||||
checked={all}
|
||||
clickDispatchHandler={setAll}
|
||||
/>
|
||||
{all ? null : app.account_list.length ? (
|
||||
app.account_list.map((account) => (
|
||||
<ConnectorRouterAccountCheck
|
||||
key={account.id}
|
||||
account={account}
|
||||
checked={account_ids.includes(account.id)}
|
||||
onChange={(checked) =>
|
||||
setAccountIds((ids) =>
|
||||
checked ? [...ids, account.id] : ids.filter((id) => id != account.id),
|
||||
)
|
||||
}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
{app.name} has no connected account to pick.
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
<AddFormActions
|
||||
submit_label={start ? "Done" : "Add"}
|
||||
loading={false}
|
||||
error={error}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</Form>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Pencil, X } from "lucide-react";
|
||||
import type { ConnectorRouterApp } from "@/src/types";
|
||||
import type { RouterPick } from "@/src/utils/router-pick-options";
|
||||
import ConnectorLogo from "./connector-logo";
|
||||
|
||||
type Props = {
|
||||
pick: RouterPick;
|
||||
/**
|
||||
* The app it names, from the form's catalog; missing only for an app
|
||||
* that no longer exists.
|
||||
*/
|
||||
app?: ConnectorRouterApp;
|
||||
onEdit: () => void;
|
||||
onRemove: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One app in the router form: its logo and name, whether it takes every
|
||||
* account or which ones, and ways to change or drop it.
|
||||
*/
|
||||
export default function ConnectorRouterPickRow({ pick, app, onEdit, onRemove }: Props) {
|
||||
const name = app?.name || `App #${pick.connector_id}`;
|
||||
const accounts = pick.account_ids.map((id) => {
|
||||
const account = app?.account_list.find((entry) => entry.id == id);
|
||||
|
||||
if (!account) return `Account #${id}`;
|
||||
|
||||
return `${account.label}${account.owner_name ? ` (${account.owner_name})` : ""}${account.status == "connected" ? "" : `, ${account.status}`}`;
|
||||
});
|
||||
const detail = accounts.length ? accounts.join(", ") : "Every account";
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-2.5! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<ConnectorLogo logo={app?.logo || ""} name={name} />
|
||||
<Stack className="grow min-w-0 gap-0!">
|
||||
<Span className="text-sm leading-5 truncate text-ink">{name}</Span>
|
||||
<Span title={detail} className="text-xs leading-4 truncate w-full text-ink-secondary">
|
||||
{detail}
|
||||
</Span>
|
||||
</Stack>
|
||||
<Button
|
||||
title={`Change ${name}'s accounts`}
|
||||
aria-label={`Change ${name}'s accounts`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="shrink-0 p-1!"
|
||||
onClick={onEdit}
|
||||
>
|
||||
<Pencil size={14} aria-hidden />
|
||||
</Button>
|
||||
<Button
|
||||
title={`Remove ${name}`}
|
||||
aria-label={`Remove ${name}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="shrink-0 p-1!"
|
||||
onClick={onRemove}
|
||||
>
|
||||
<X size={14} aria-hidden />
|
||||
</Button>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useState } from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Pencil, Route, Trash2, Users } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ConnectorRouterApp, ConnectorRouterRecord, ExtensionTargets } from "@/src/types";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import ConnectorAccessModal from "./connector-access-modal";
|
||||
import ConnectorRouterAppTag from "./connector-router-app-tag";
|
||||
import ConnectorRouterModal from "./connector-router-modal";
|
||||
|
||||
type Props = {
|
||||
router: ConnectorRouterRecord;
|
||||
connection_name: string;
|
||||
choices: ConnectorRouterApp[];
|
||||
targets: ExtensionTargets;
|
||||
bots: { id: number; name: string }[];
|
||||
onChanged: (msg: string) => void | Promise<void>;
|
||||
onError: (msg: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One router of a connection: its apps, where it reaches, and (for a super
|
||||
* admin) editing and deleting it. Anyone may give it to their own runs on a
|
||||
* bot.
|
||||
*/
|
||||
export default function ConnectorRouterRow({
|
||||
router,
|
||||
connection_name,
|
||||
choices,
|
||||
targets,
|
||||
bots,
|
||||
onChanged,
|
||||
onError,
|
||||
}: Props) {
|
||||
const [open, setOpen] = useState<"access" | "edit">();
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
const saved = async (msg: string) => {
|
||||
setOpen(undefined);
|
||||
await onChanged(msg);
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
if (!window.confirm(`Delete ${router.name}? Bots it was given to lose its apps, unless they reach them another way.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDeleting(true);
|
||||
|
||||
const res = await postAdminApi({ path: "connectors/delete-router", body: { router_id: router.id } });
|
||||
|
||||
setDeleting(false);
|
||||
|
||||
if (!res.success) {
|
||||
onError(res.msg || "Couldn't delete the router.");
|
||||
return;
|
||||
}
|
||||
|
||||
await onChanged(res.msg || `Deleted ${router.name}.`);
|
||||
};
|
||||
|
||||
const reaches = [
|
||||
router.all_bots ? "Every bot, every user" : "",
|
||||
router.workspace_ids.length
|
||||
? `${router.workspace_ids.length} ${router.workspace_ids.length == 1 ? "workspace" : "workspaces"}`
|
||||
: "",
|
||||
router.bot_ids.length ? `Your runs on ${router.bot_ids.length} ${router.bot_ids.length == 1 ? "bot" : "bots"}` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2! items-stretch border-0 border-b border-solid border-hairline pb-3 last:border-b-0">
|
||||
<SettingsListRow
|
||||
avatar={<IconTile Icon={Route} />}
|
||||
title={router.name}
|
||||
badge={router.enabled ? undefined : "Off"}
|
||||
onOpen={targets.can_edit ? () => setOpen("edit") : undefined}
|
||||
subtitle={[
|
||||
`${router.apps.length} ${router.apps.length == 1 ? "app" : "apps"}`,
|
||||
reaches || "Not given to a bot yet",
|
||||
router.description,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<SettingsRowMenu title={`${router.name} menu`}>
|
||||
<SettingsRowMenuPanel>
|
||||
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Trash2} title="Delete" loading={deleting} onClick={() => void remove()} />
|
||||
) : null}
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
|
||||
{router.apps.length ? (
|
||||
<Row className="w-full gap-1.5! flex-wrap pl-14">
|
||||
{router.apps.map((app) => (
|
||||
<ConnectorRouterAppTag key={app.id} app={app} />
|
||||
))}
|
||||
</Row>
|
||||
) : null}
|
||||
|
||||
{open == "access" ? (
|
||||
<ConnectorAccessModal
|
||||
subject={{ kind: "router", id: router.id, name: router.name, all_bots: router.all_bots }}
|
||||
access={{ bot_ids: router.bot_ids, workspace_ids: router.workspace_ids }}
|
||||
targets={targets}
|
||||
bots={bots}
|
||||
onSaved={saved}
|
||||
onCancel={() => setOpen(undefined)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{open == "edit" ? (
|
||||
<ConnectorRouterModal
|
||||
connection_id={router.connection_id}
|
||||
connection_name={connection_name}
|
||||
router={router}
|
||||
choices={choices}
|
||||
onSaved={saved}
|
||||
onCancel={() => setOpen(undefined)}
|
||||
/>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -138,7 +138,7 @@ export default function ConnectorRow({
|
||||
/>
|
||||
{open == "access" ? (
|
||||
<ConnectorAccessModal
|
||||
connector={connector}
|
||||
subject={{ kind: "connector", id: connector.id, name: connector.name, all_bots: connector.all_bots }}
|
||||
access={access}
|
||||
targets={targets}
|
||||
bots={bots}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import { useContext, useState } from "react";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Pagination from "@moduletrace/twui/elements/Pagination";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { ConnectorAppFilters, type ConnectorAppFilter } from "@/src/dict/connector-dict";
|
||||
import TabButton from "@/src/components/general/tab-button";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { ConnectorAppsPagePayload } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import SettingsList from "../../(partials)/settings-list";
|
||||
import SettingsShell from "../../(partials)/settings-shell";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import useConnectorApps from "../(hooks)/use-connector-apps";
|
||||
import ConnectorRow from "../(partials)/connector-row";
|
||||
@@ -20,7 +16,7 @@ import ConnectorRow from "../(partials)/connector-row";
|
||||
type Status = { error?: boolean; success?: boolean; msg?: string };
|
||||
|
||||
/**
|
||||
* One connection's apps, a page at a time. A connection can hold thousands
|
||||
* One connection's apps, a page at a time: the Apps tab of its page. A connection can hold thousands
|
||||
* (Composio listed 1,842), so nothing here renders them all: search narrows
|
||||
* them, and each row is one app to give to bots or workspaces.
|
||||
*/
|
||||
@@ -73,17 +69,10 @@ export default function ConnectorAppsSection() {
|
||||
payload?.access.find((entry) => entry.connector_id == connector_id);
|
||||
|
||||
return (
|
||||
<SettingsShell
|
||||
title={connection.name}
|
||||
description={`The apps ${connection.name} offers. Give one to every bot, to a workspace, or to your own runs on a bot; a workspace uses every account connected for that app, whoever connected it.`}
|
||||
>
|
||||
<Row className="w-full items-center gap-2!">
|
||||
<Link href="/admin/settings/connectors" className="text-sm">
|
||||
<ArrowLeft size={14} aria-hidden className="mr-1 inline" />
|
||||
All connectors
|
||||
</Link>
|
||||
</Row>
|
||||
<SettingsGroup title="Apps">
|
||||
<SettingsGroup
|
||||
title="Apps"
|
||||
description={`The apps ${connection.name} offers. Give one to every bot, to a workspace, or to your own runs on a bot; a workspace uses every account connected for that app, whoever connected it. A bot gets every tool of an app given to it.`}
|
||||
>
|
||||
<Row role="tablist" aria-label="Which apps" className="w-full gap-1! flex-nowrap mb-2">
|
||||
{ConnectorAppFilters.map((entry) => (
|
||||
<TabButton
|
||||
@@ -159,6 +148,5 @@ export default function ConnectorAppsSection() {
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</SettingsGroup>
|
||||
</SettingsShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useContext, useState } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import TabButton from "@/src/components/general/tab-button";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { ConnectorAppsPagePayload } from "@/src/types";
|
||||
import SettingsShell from "../../(partials)/settings-shell";
|
||||
import ConnectorAppsSection from "./connector-apps-section";
|
||||
import ConnectorRoutersSection from "./connector-routers-section";
|
||||
import Spacer from "@moduletrace/twui/layout/Spacer";
|
||||
|
||||
type Tab = ConnectorAppsPagePayload["tab"];
|
||||
|
||||
const Tabs: { value: Tab; title: string }[] = [
|
||||
{ value: "apps", title: "Apps" },
|
||||
{ value: "routers", title: "Routers" },
|
||||
];
|
||||
|
||||
/**
|
||||
* One connection's page: its apps, and its routers (named sets of its
|
||||
* connected apps a bot reaches through a few search and run tools). The tab
|
||||
* is kept in the address (`?tab=routers`), so a reload or a shared link
|
||||
* opens the same one.
|
||||
*/
|
||||
export default function ConnectorConnectionSection() {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const page = pageProps?.connector_apps_page as
|
||||
| ConnectorAppsPagePayload
|
||||
| undefined;
|
||||
const [tab, setTab] = useState<Tab>(page?.tab || "apps");
|
||||
|
||||
if (!page) return null;
|
||||
|
||||
const pick = (next: Tab) => {
|
||||
setTab(next);
|
||||
|
||||
const url = new URL(window.location.href);
|
||||
|
||||
if (next == "apps") url.searchParams.delete("tab");
|
||||
else url.searchParams.set("tab", next);
|
||||
|
||||
window.history.replaceState(window.history.state, "", url.toString());
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsShell
|
||||
title={page.connection.name}
|
||||
description={`What ${page.connection.name} offers: its apps, and routers that reach several of its connected apps through a few tools.`}
|
||||
>
|
||||
<Row className="w-full items-center gap-2!">
|
||||
<Link href="/admin/settings/connectors" className="text-sm">
|
||||
<ArrowLeft size={14} aria-hidden className="mr-1 inline" />
|
||||
All connectors
|
||||
</Link>
|
||||
</Row>
|
||||
|
||||
<Spacer className="h-4" />
|
||||
|
||||
<Row
|
||||
role="tablist"
|
||||
aria-label="Apps or routers"
|
||||
className="w-full gap-1! flex-nowrap"
|
||||
>
|
||||
{Tabs.map((entry) => (
|
||||
<TabButton
|
||||
key={entry.value}
|
||||
title={entry.title}
|
||||
active={entry.value == tab}
|
||||
onPick={() => pick(entry.value)}
|
||||
/>
|
||||
))}
|
||||
</Row>
|
||||
{tab == "routers" ? (
|
||||
<ConnectorRoutersSection />
|
||||
) : (
|
||||
<ConnectorAppsSection />
|
||||
)}
|
||||
</SettingsShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useContext, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import { Plus } from "lucide-react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { ConnectorAppsPagePayload } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import SettingsList from "../../(partials)/settings-list";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import useConnectorRouters from "../(hooks)/use-connector-routers";
|
||||
import ConnectorRouterModal from "../(partials)/connector-router-modal";
|
||||
import ConnectorRouterRow from "../(partials)/connector-router-row";
|
||||
|
||||
type Status = { error?: boolean; success?: boolean; msg?: string };
|
||||
|
||||
/**
|
||||
* One connection's routers: the Routers tab of its page. A router is a named
|
||||
* set of the connection's connected apps that a bot reaches through four
|
||||
* tools (search, read arguments, run, connect), so ten apps with 80 tools
|
||||
* each cost a bot's prompt four tool definitions instead of 800.
|
||||
*/
|
||||
export default function ConnectorRoutersSection() {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const page = pageProps?.connector_apps_page as ConnectorAppsPagePayload | undefined;
|
||||
const { payload, error, refresh } = useConnectorRouters({ connection_id: page?.connection.id || 0 });
|
||||
const [status, setStatus] = useState<Status>();
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
if (!page) return null;
|
||||
|
||||
const { connection, targets, my_bots } = page;
|
||||
const routers = payload?.routers || [];
|
||||
const choices = payload?.choices || [];
|
||||
|
||||
const changed = async (msg: string) => {
|
||||
setAdding(false);
|
||||
setStatus({ success: true, msg });
|
||||
await refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Routers"
|
||||
description={`A router reaches several of ${connection.name}'s connected apps through four tools of its own instead of every app's tools: the bot searches for the tool it needs, reads its arguments and runs it. Give it to every bot, to a workspace, or to your own runs on a bot, as for an app. An app a bot reaches through a router never lists its own tools there, even when it was also given directly.`}
|
||||
>
|
||||
{targets.can_edit ? (
|
||||
<Row className="w-full justify-end">
|
||||
<Button
|
||||
title="New router"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
beforeIcon={<Plus size={14} aria-hidden />}
|
||||
onClick={() => setAdding(true)}
|
||||
>
|
||||
New router
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsList
|
||||
is_empty={Boolean(payload) && !routers.length}
|
||||
empty={
|
||||
targets.can_edit
|
||||
? "No routers yet. Make one to reach several connected apps through a few tools."
|
||||
: "No routers yet. A super admin makes them."
|
||||
}
|
||||
>
|
||||
{routers.map((router) => (
|
||||
<ConnectorRouterRow
|
||||
key={router.id}
|
||||
router={router}
|
||||
connection_name={connection.name}
|
||||
choices={choices}
|
||||
targets={targets}
|
||||
bots={my_bots}
|
||||
onChanged={changed}
|
||||
onError={(msg) => setStatus({ error: true, msg })}
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
<SettingsStatus status={error ? { error: true, msg: error } : status} />
|
||||
{adding ? (
|
||||
<ConnectorRouterModal
|
||||
connection_id={connection.id}
|
||||
connection_name={connection.name}
|
||||
choices={choices}
|
||||
onSaved={changed}
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,7 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
|
||||
connection,
|
||||
targets,
|
||||
my_bots: bots.map((bot) => ({ id: Number(bot.id), name: String(bot.name || "") })),
|
||||
tab: new URL(params.req.url).searchParams.get("tab") == "routers" ? "routers" : "apps",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import ConnectorAppsSection from "../(sections)/connector-apps-section";
|
||||
import ConnectorConnectionSection from "../(sections)/connector-connection-section";
|
||||
import settingsConnectorPageMeta from "../(functions)/settings-connector-page-meta";
|
||||
|
||||
export default function AdminSettingsConnectorPage() {
|
||||
return <ConnectorAppsSection />;
|
||||
return <ConnectorConnectionSection />;
|
||||
}
|
||||
|
||||
export const meta = settingsConnectorPageMeta();
|
||||
export const meta = settingsConnectorPageMeta();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user