Compare commits

..
17 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 507c9dce5c Bump version to 0.28.23
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 07:05:29 +01:00
tbenandClaude Opus 5.5 da9672c3e5 Add connector routers and fix silent connector failures
Routers: a named set of one connection's apps, made on the connection
page's Routers tab and given like an app (every bot, workspaces, or a
user's own runs on a bot). An app a router brings is reached only through
connectors_search_tools, connectors_get_tool_schemas, connectors_execute
and connectors_connect, so its tools never fill the prompt; an app given
directly keeps its own deferred tools. A router can take every account of
an app or particular ones, added through the router form's Add app modal.
The composer's Connectors section lists routers and their apps and adds
one for the user's own runs. Settings > General > Connectors keeps only
the actions-per-run limit.

Fixes: known accounts now follow the provider's status on every sync,
Composio's ISO expiry times are read, the REST fallback and account sync
failures are logged, apps whose tools were never read are named instead
of dropped, a lapsed sign-in is reconnected in place, the cron reads tools
of apps reached through accounts given out, account grants are deleted
explicitly, and the Add a connector modal's query (which failed and read
as an empty list) works again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 07:05:29 +01:00
tbenandClaude Opus 5.5 c0777fb596 Drop speaker tokens and sound events from transcripts
Fish Audio's transcribe models (and ElevenLabs' Scribe) write markup into
the text, such as <|speaker:0|> and [the sound of the alarm]. transcribeAudio
now cleans every transcript, so only the words reach the composer or a bot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 06:24:58 +01:00
tbenandClaude Opus 5.5 8d5c76ebd6 Send Vercel AI Gateway transcription and speech to its own /v4/ai routes
The gateway has no /v1/audio/transcriptions or /v1/audio/speech, so every
call 404'd. Transcription and speech now go to /v4/ai/transcription-model
and /v4/ai/speech-model on the host root, with the model in ai-model-id
and the audio as base64 JSON.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 06:19:20 +01:00
tbenandClaude Opus 5.5 9fb91d2db6 Open a provider's edit form in a modal, like Add a provider
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 06:11:51 +01:00
tbenandClaude Opus 5.5 48cc14407c Stop read-image's test leaking a stubbed grabChatParams into its own tests
CI / check (push) Canceled after 0s
Bun's mock.restore() doesn't undo mock.module, so CI failed grabChatParams
whenever read-image.test.ts ran first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:18:38 +01:00
tbenandClaude Opus 5.5 c072e9c0bc Bump version to 0.28.22
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:14:03 +01:00
tbenandClaude Opus 5.5 e01114ce63 Close bot_tasks rows left active with no open job at boot
Rows from before a failed run closed its own row stayed active for months
and kept their conversations polling for progress that never came.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:14:03 +01:00
tbenandClaude Opus 5.5 d9ac0daf45 Reflow describeSkillProposal
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:14:03 +01:00
tbenandClaude Opus 5.5 99622e620d Hold a failed job's retry to the model rest and show it waiting
A quota resetting in nine days held a routine's retry a full day while its
models were benched for 30 seconds, with the face still on working and the
next day's run skipped behind it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:09:25 +01:00
tbenandClaude Opus 5.5 54ba0e845d Bump version to 0.28.21
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:40:27 +01:00
tbenandClaude Opus 5.5 1da980e243 Look for a hook runner's folder in the owner's ~ first, and show runner faults in error colours
A relative runner_dir is now tried in users/<owner> inside the bot's
folder (the run's ~, where a bot builds a bridge) and then in the bot's
folder, so "whatsapp" finds ~/whatsapp and folders given the old way
still work. The keeper script takes the candidates in order (version 3).
Runner down, Down, Check failed and Last error now use the error colour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:40:27 +01:00
tbenandClaude Opus 5.5 66bdcff208 Bump version to 0.28.20
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:12 +01:00
tbenandClaude Opus 5.5 d2d250e426 Render bot- and user-written markdown everywhere instead of raw text
TaskMarkdown becomes the shared MarkdownText (with a boxed, scrolling
variant). Proposal briefs, runbooks and prompts, card reasons and
research, plan goals and steps, questions, a hook's brief and the bot
panel's instructions and memory now render through it; code-like values
stay word for word.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:06 +01:00
tbenandClaude Opus 5.5 a569483456 Show the absolute folder a hook's runner starts in
runner_dir is relative to the bot's folder, not a run's ~, and a bare
"whatsapp" led a bot to point its runner at a folder that never
existed. The proposal card, list_hooks and propose_hook now give the
full path (hookRunnerStartPath, resolved like syncHookRunners), and the
form's help text explains the difference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:06 +01:00
tbenandClaude Opus 5.5 ef0237ecf0 Bump version to 0.28.19
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:25:57 +01:00
tbenandClaude Opus 5.5 02c49a3c9b Show why a hook's runner check failed, to the user and to the bot
The hook row and modal name the failure and when the runner was last
checked, and list_hooks describes the runner, its folder (inside the
bot's folder, not ~) and a failed check, pointing at propose_hook rather
than a process started by hand. Also reword Run silently: every hook has
its own thread, the setting is whether a run takes the conversation over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:25:57 +01:00
152 changed files with 5528 additions and 541 deletions
+7 -6
View File
File diff suppressed because one or more lines are too long
+224
View File
@@ -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
View File
@@ -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
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.18",
"version": "0.28.23",
"module": "index.ts",
"type": "module",
"private": true,
+19 -2
View File
@@ -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);
+6 -2
View File
@@ -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()}.`,
]
+1 -1
View File
@@ -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");
+9 -18
View File
@@ -1,34 +1,25 @@
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import linkComputerRefs from "@/src/utils/link-computer-refs";
/**
* Kept module-level: a new array on every render makes `react-markdown`
* parse the message again.
*/
const RemarkPlugins = [remarkGfm];
import MarkdownText from "./markdown-text";
type Props = {
label: string;
text: string;
/**
* Long text (a hook's brief): kept to a box that scrolls.
*/
boxed?: boolean;
};
/**
* What a hook call's run answered, rendered like a chat message (raw HTML
* never).
* Markdown about a hook under its label (what a call's run answered, the
* hook's brief), rendered like a chat message (raw HTML never).
*/
export default function HookCallAnswer({ label, text }: Props) {
export default function HookCallAnswer({ label, text, boxed }: Props) {
return (
<Stack className="w-full gap-0.5! items-stretch">
<Span className="text-[11px] leading-4 text-ink-secondary">{label}</Span>
<Stack className="w-full gap-2.5! items-start break-words">
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
</Stack>
<MarkdownText text={text} boxed={boxed} />
</Stack>
);
}
+25 -6
View File
@@ -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";
@@ -11,7 +12,7 @@ import type { BotHookWithNames } from "@/src/types";
import conversationHref from "@/src/utils/conversation-href";
import hookRunnerState from "@/src/utils/hook-runner-state";
import relativeTime from "@/src/utils/relative-time";
import HookCallText from "./hook-call-text";
import HookCallAnswer from "./hook-call-answer";
import HookCalls from "./hook-calls";
import TaskFactRow from "./task-fact-row";
@@ -99,9 +100,23 @@ 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() })}`
: hook.runner_last_error || "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">
<Span className="text-error break-words min-w-0">{runner.error}</Span>
</TaskFactRow>
) : null}
<TaskFactRow label="Last checked">
{hook.runner_checked_at
? relativeTime({ at: Number(hook.runner_checked_at) })
: "Not yet"}
</TaskFactRow>
{hook.runner_command ? (
<TaskFactRow label="Runner command">
@@ -128,9 +143,13 @@ 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 ? <HookCallText label="Brief" text={hook.instructions} full /> : null}
{hook.instructions ? <HookCallAnswer label="Brief" text={hook.instructions} boxed /> : null}
{status ? <SettingsStatus status={status} /> : null}
<Row className="w-full gap-2! justify-end">
{can_manage && runner?.configured ? (
+2 -2
View File
@@ -289,7 +289,7 @@ export default function HookForm({
autoComplete="off"
placeholder="whatsapp"
defaultValue={hook?.runner_dir || ""}
info={`Where it starts, inside the bot's folder: "whatsapp" is the bot's whatsapp folder. 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
@@ -317,7 +317,7 @@ export default function HookForm({
) : null}
<Checkbox
title="Run silently"
label="Keep its runs in the hook's own thread: they never take over the conversation or notify me. Read them from the hook, or in the bot's sessions."
label="Run without taking over the conversation: its thread stays out of the rail, its runs don't notify me or change the bot's face. Unchecked, each run makes its thread the conversation's active session."
checked={silent}
changeHandler={setSilent}
labelProps={{ className: "w-full" }}
+1
View File
@@ -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}>
@@ -1,10 +1,10 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import TaskMarkdown from "./task-markdown";
import MarkdownText from "./markdown-text";
describe("TaskMarkdown", () => {
describe("MarkdownText", () => {
test("renders the markdown, not as written", () => {
const html = renderToString(<TaskMarkdown text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
const html = renderToString(<MarkdownText text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
expect(html).not.toContain("## Steps");
expect(html).not.toContain("**Check**");
@@ -13,7 +13,7 @@ describe("TaskMarkdown", () => {
});
test("opens links in a new tab, bare ones too", () => {
const html = renderToString(<TaskMarkdown text={"See [the docs](https://example.com) or https://example.org"} />);
const html = renderToString(<MarkdownText text={"See [the docs](https://example.com) or https://example.org"} />);
expect(html).toContain('href="https://example.com"');
expect(html).toContain('href="https://example.org"');
@@ -22,7 +22,7 @@ describe("TaskMarkdown", () => {
});
test("shows refs as chips", () => {
const html = renderToString(<TaskMarkdown text={"Ask [bot:2] about [task:20]."} />);
const html = renderToString(<MarkdownText text={"Ask [bot:2] about [task:20]."} />);
expect(html).not.toContain("[bot:2]");
expect(html).toContain("bot 2");
@@ -30,7 +30,7 @@ describe("TaskMarkdown", () => {
});
test("never renders raw HTML", () => {
const html = renderToString(<TaskMarkdown text={"<script>alert(1)</script> <b>hi</b>"} />);
const html = renderToString(<MarkdownText text={"<script>alert(1)</script> <b>hi</b>"} />);
expect(html).not.toContain("<script>");
expect(html).not.toContain("<b>");
@@ -17,17 +17,25 @@ const RemarkPlugins = [remarkGfm];
type Props = {
text: string;
/**
* Long text (a brief, a runbook, a memory): kept to a sunken box that
* scrolls, so it never pushes the rest of a card out of sight.
*/
boxed?: boolean;
className?: string;
};
/**
* A task's description or a note on it, rendered like a bot's message
* (raw HTML never rendered, links in a new tab, refs as their chips). The
* crew the chips link to is the page's own when no conversation around it
* gives one. The message elements reach this file again through the task
* chip, so they're read when it renders, never at load.
* Bot- or user-written markdown anywhere outside a message (a task's
* description and notes, a hook's or routine's brief, a skill's runbook,
* a card's reason, a bot's instructions and memory), rendered like a bot's
* message: raw HTML never rendered, links in a new tab, refs as their
* chips. Never show such text raw. The crew the chips link to is the
* page's own when no conversation around it gives one. The message
* elements reach this file again through the chips and cards, so they're
* read when it renders, never at load.
*/
export default function TaskMarkdown({ text, className }: Props) {
export default function MarkdownText({ text, boxed, className }: Props) {
const { pageProps } = useContext(AppContext);
const crew_bots = useContext(CrewBotsContext);
const crew_workspaces = useContext(CrewWorkspacesContext);
@@ -37,7 +45,13 @@ export default function TaskMarkdown({ text, className }: Props) {
return (
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
<Stack className={twMerge("w-full min-w-0 gap-2! items-stretch", className)}>
<Stack
className={twMerge(
"w-full min-w-0 gap-2! items-stretch break-words",
boxed && "max-h-80 overflow-y-auto rounded-default-xs bg-sunken px-3 py-2",
className,
)}
>
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
+2 -2
View File
@@ -17,7 +17,7 @@ import TaskNoteRow from "@/src/components/general/task-note-row";
import TaskSubtaskRow from "@/src/components/general/task-subtask-row";
import TaskSubtasksModal from "@/src/components/general/task-subtasks-modal";
import SubtaskLinkForm from "@/src/components/general/subtask-link-form";
import TaskMarkdown from "@/src/components/general/task-markdown";
import MarkdownText from "@/src/components/general/markdown-text";
import type { BotFace } from "@/src/dict/bot-dict";
import { AppContext } from "@/src/pages/__root";
import { AppData } from "@/src/data/app-data";
@@ -474,7 +474,7 @@ export default function TaskDetailPanel({
<Span className="text-[13px] leading-[18px] text-ink">{`Waiting on you: ${task.blocked_reason}`}</Span>
) : null}
{task.description ? <TaskMarkdown text={task.description} /> : null}
{task.description ? <MarkdownText text={task.description} /> : null}
{task.workspace_id && !task.bot_id ? (
<Stack className="w-full gap-1! items-stretch">
+2 -2
View File
@@ -3,7 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { TaskNote } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import TaskMarkdown from "./task-markdown";
import MarkdownText from "./markdown-text";
type Props = {
note: TaskNote;
@@ -26,7 +26,7 @@ export default function TaskNoteRow({ note }: Props) {
</Span>
) : null}
</Row>
{note.text ? <TaskMarkdown text={note.text} /> : null}
{note.text ? <MarkdownText text={note.text} /> : null}
</Stack>
);
}
+32 -4
View File
@@ -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(() => {}),
);
}
}
+21
View File
@@ -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
+29 -3
View File
@@ -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.
+5 -4
View File
@@ -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:
+4
View File
@@ -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",
+8
View File
@@ -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";
+4
View File
@@ -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",
+12
View File
@@ -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 };
}
@@ -25,7 +25,7 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
) as number[];
const [bot, workspace, computers] = await Promise.all([
BunSQLite.sql<{ name: string }>({ sql: `SELECT name FROM bots WHERE id = ?`, values: [proposal.bot_id] }),
BunSQLite.sql<{ name: string; kind: string | null }>({ sql: `SELECT name, kind FROM bots WHERE id = ?`, values: [proposal.bot_id] }),
proposal.workspace_id
? BunSQLite.sql<{ name: string }>({ sql: `SELECT name FROM workspaces WHERE id = ?`, values: [proposal.workspace_id] })
: null,
@@ -56,6 +56,9 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
current,
workspace_name: workspace?.payload?.[0]?.name || null,
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.",
);
});
});
+24
View File
@@ -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");
}
+8 -2
View File
@@ -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(() => {});
},
};
}
+21 -124
View File
@@ -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;
}
+5 -3
View File
@@ -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.`,
};
}
+7 -2
View File
@@ -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 };
}
@@ -56,7 +56,7 @@ export default function grabBotHookTools({
pauseHookTool({ user_id, bot_id, is_coordinator, workspace_id }),
deleteHookTool({ user_id, bot_id, is_coordinator, workspace_id }),
...(session_id && onPropose
? [proposeHookTool({ user_id, bot_id, session_id, workspace_id, computers, onPropose })]
? [proposeHookTool({ user_id, bot_id, session_id, workspace_id, computers, is_coordinator, onPropose })]
: []),
];
}
@@ -4,6 +4,7 @@ import { AppData } from "@/src/data/app-data";
import { BotHookSources, type BotHookSource } from "@/src/dict/bot-hook-dict";
import createHookProposal from "@/src/functions/backend/db/hook-proposals/create-hook-proposal";
import grabHookProposalView from "@/src/functions/backend/db/hook-proposals/grab-hook-proposal-view";
import computerRunDirs from "@/src/utils/computer-work-dirs";
import hookProposalRef from "@/src/utils/hook-proposal-ref";
import type { HarnessTool } from "../../../types";
import describeHookProposalForBot from "./describe-hook-proposal-for-bot";
@@ -23,6 +24,11 @@ type Params = {
* The bot's computers where it runs, the current one first.
*/
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
/**
* The coordinator's folder is in the computer's workspace, a worker's
* in its own home: the runner folder is explained with the real paths.
*/
is_coordinator?: boolean;
/**
* Called with the proposal's ref, so the reply always carries its card.
*/
@@ -58,8 +64,11 @@ export default function proposeHookTool({
session_id,
workspace_id,
computers,
is_coordinator,
onPropose,
}: Params): HarnessTool<Args> {
const dirs = computerRunDirs({ bot_id, bot_kind: is_coordinator ? "coordinator" : null, user_id, workspace_id });
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 {
@@ -68,7 +77,7 @@ export default function proposeHookTool({
workspace_id ? "in this workspace" : "in your own chat"
}, with what the caller sent attached as data, in the hook's own thread: results never come back to this chat, the user reads them by opening the hook. Runs carry the brief out without asking the user, so write it as a full brief for a future you with no memory of this chat, saying exactly what to do with each call, and lay it out as the plan the run follows: the steps in order, each naming what it produces. ${
computers.length ? `Your computers here: ${listed}.` : `You have no computer here, so it can't watch one.`
} To change one of your hooks (ids from list_hooks), give hook_id and only what changes: title, instructions, watch_filter, enabled true to switch a paused one back on, or its runner; what calls it and where it runs can't change. A hook whose caller is a process on your computer (a bridge started there) can keep it running: give runner_command, the command the app runs for it, runner_dir (a folder inside the bot's folder, such as whatsapp) and, if not the bot's own, runner_computer_id. The app starts it again by itself within five minutes of it dying, and when the computer restarts, so it must stay in the foreground and not go into the background with &. It runs as the bot's account, and the card shows the command word for word: only a crew manager can confirm a runner, so if the user isn't one, tell them an admin has to. Nothing is saved until the user presses Confirm on the card. A new hook's URL is shown to the user on the card, once: you never see it, never ask for it, and never set a signing secret (the user adds one from the Hooks menu). Check list_hooks first: if a hook already does the job, propose a change to it instead. When the user tells you to handle a hook's calls differently (often in reply to a run's report), tell them the hook's brief has to change for that and propose the new brief. Runs follow the brief over your memory, so don't save it to your memory or promise to do it from now on instead: neither changes what the next call does.`,
} To change one of your hooks (ids from list_hooks), give hook_id and only what changes: title, instructions, watch_filter, enabled true to switch a paused one back on, or its runner; what calls it and where it runs can't change. A hook whose caller is a process on your computer (a bridge started there) can keep it running: give runner_command, the command the app runs for it, runner_dir (the folder it starts in, ${runner_folder}; the card shows the full path) and, if not the bot's own, runner_computer_id. The app starts it again by itself within five minutes of it dying, and when the computer restarts, so it must stay in the foreground and not go into the background with &. It runs as the bot's account, and the card shows the command word for word: only a crew manager can confirm a runner, so if the user isn't one, tell them an admin has to. Nothing is saved until the user presses Confirm on the card. A new hook's URL is shown to the user on the card, once: you never see it, never ask for it, and never set a signing secret (the user adds one from the Hooks menu). Check list_hooks first: if a hook already does the job, propose a change to it instead. When the user tells you to handle a hook's calls differently (often in reply to a run's report), tell them the hook's brief has to change for that and propose the new brief. Runs follow the brief over your memory, so don't save it to your memory or promise to do it from now on instead: neither changes what the next call does.`,
schema: z.object({
hook_id: z.number().int().positive().optional().describe("The hook to change; leave out for a new one"),
title: z.string().trim().min(1).max(80).optional().describe(`A short name, e.g. "GitHub pushes"`),
@@ -92,7 +101,7 @@ export default function proposeHookTool({
.trim()
.max(AppData.BotHookRunnerDirMaxLength)
.optional()
.describe(`The folder it starts in, inside the bot's folder, e.g. "whatsapp". Empty: the bot's folder`),
.describe(`The folder it starts in, ${runner_folder}`),
runner_computer_id: z
.number()
.int()
@@ -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".`);
});
});
+11
View File
@@ -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}`;
}
@@ -251,13 +251,13 @@ export default function BotPanel({
<BotReadOnlyBlock
title="Instructions"
content={system_prompt || ""}
className="h-52"
className="max-h-52"
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotReadOnlyBlock
title="Memory"
content={memory || ""}
className="h-52"
className="max-h-52"
/>
{workspace_id ? (
<>
@@ -269,7 +269,7 @@ export default function BotPanel({
.instructions
?.memory || ""
}
className="h-40"
className="max-h-40"
/>
</>
) : null}
@@ -1,4 +1,5 @@
import { useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import { twMerge } from "tailwind-merge";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
@@ -93,7 +94,7 @@ export default function BotPlanCard({ plan_id }: Props) {
<Span className="text-[12px] leading-4 text-ink-secondary">{botPlanStatusLine({ view })}</Span>
{view.goal ? (
<Span className="text-[13px] leading-5 text-ink-secondary">{view.goal}</Span>
<MarkdownText text={view.goal} className="text-ink-secondary" />
) : null}
<Span className="flex w-full flex-col gap-1.5 pt-0.5">
@@ -1,4 +1,5 @@
import Span from "@moduletrace/twui/layout/Span";
import MarkdownText from "@/src/components/general/markdown-text";
import { twMerge } from "tailwind-merge";
import { Circle, CircleCheck, CircleSlash, CircleDot } from "lucide-react";
import type { BotPlanStep } from "@/src/types";
@@ -40,11 +41,11 @@ export default function BotPlanStepRow({ step, current }: Props) {
(done || skipped) && "text-ink-secondary",
)}
>
{step.text}
<MarkdownText text={step.text} />
</Span>
{step.note ? (
<Span className="text-[12px] leading-4 text-ink-secondary">{step.note}</Span>
<MarkdownText text={step.note} className="text-ink-secondary" />
) : current ? (
<Span className="text-[12px] leading-4 text-ink-secondary">Working on this now.</Span>
) : null}
@@ -1,4 +1,5 @@
import Input from "@moduletrace/twui/form/Input";
import MarkdownText from "@/src/components/general/markdown-text";
import Radios from "@moduletrace/twui/form/Radios";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
@@ -54,9 +55,7 @@ export default function BotQuestionField({
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>{`${index + 1}. ${single ? "Pick one" : "Pick any"}`}</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 font-bold text-ink break-words">
{item.question}
</Span>
<MarkdownText text={item.question} className="font-bold" />
{open ? (
<Stack className="mt-2 w-full gap-2! items-stretch">
@@ -1,25 +1,29 @@
import CodeEditor from "@/src/components/general/code-editor";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import MarkdownText from "@/src/components/general/markdown-text";
type BotReadOnlyBlockProps = {
title: string;
content: string;
/**
* The box's height cap (a `max-h-*`), so a long memory scrolls.
*/
className?: string;
};
/** A block of a bot's own text its panel shows a user read-only. */
export default function BotReadOnlyBlock({
title,
content,
className,
}: BotReadOnlyBlockProps) {
/**
* A block of a bot's own text (its instructions, a memory) its panel shows
* a user read-only: markdown, rendered, never the raw text.
*/
export default function BotReadOnlyBlock({ title, content, className }: BotReadOnlyBlockProps) {
return (
<CodeEditor
title={title}
content={content || "Nothing yet."}
mode="markdown"
className={className}
readOnly
onChange={() => {}}
/>
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[12px] leading-4 text-ink-secondary">{title}</Span>
{content.trim() ? (
<MarkdownText text={content} boxed className={className} />
) : (
<Span className="text-[13px] leading-5 text-ink-secondary">Nothing yet.</Span>
)}
</Stack>
);
}
}
@@ -74,7 +74,7 @@ export default function BotUserMemory({
<BotReadOnlyBlock
title="About you"
content={memory}
className="h-32"
className="max-h-32"
/>
</>
);
@@ -91,7 +91,7 @@ export default function BotUserMemory({
mode="markdown"
placeholder="What it should keep in mind about you..."
info="Markdown, replaced whole. Only this bot, and only when it works with you."
className="h-32"
className="max-h-32"
onChange={(value) => {
setText(value);
setSaved(false);
@@ -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 &gt; 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>
);
}
@@ -1,4 +1,5 @@
import { useContext, useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
@@ -89,7 +90,7 @@ export default function HookProposalCard({ view, onDecided, onDone }: Props) {
) : null}
<MessageDetailsHeading>Why (written by the bot)</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.reason}</Span>
<MarkdownText text={view.reason || ""} />
{view.outcome ? <Span className="mt-4 text-[13px] leading-5 text-ink">{view.outcome}</Span> : null}
@@ -1,4 +1,5 @@
import { useContext, useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
@@ -84,7 +85,7 @@ export default function ProposalCard({ view, onDecided }: Props) {
<MessageDetailsHeading>
{is_skill ? "Review (written by the bot)" : "Background check (written by the bot)"}
</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.research}</Span>
<MarkdownText text={view.research || ""} />
<Stack className="mt-1 w-full gap-0! items-stretch">
{view.sources.length ? (
view.sources.map((url) => <ProposalSourceRow key={url} url={url} />)
@@ -0,0 +1,21 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import ProposalDetailRow from "./proposal-detail-row";
describe("ProposalDetailRow", () => {
test("renders a markdown brief instead of showing it raw", () => {
const html = renderToString(
<ProposalDetailRow label="Brief" value={"## Steps\n\n1. **Read** the call"} block markdown />,
);
expect(html).toContain("<li");
expect(html).not.toContain("## Steps");
expect(html).not.toContain("**Read**");
});
test("keeps a code-like value word for word", () => {
const html = renderToString(<ProposalDetailRow label="Keeps running" value="./run.sh --flag **x**" block />);
expect(html).toContain("./run.sh --flag **x**");
});
});
@@ -1,24 +1,30 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { twMerge } from "tailwind-merge";
import MarkdownText from "@/src/components/general/markdown-text";
import type { ExtensionProposalDetail } from "@/src/types";
/**
* One line of what a proposed server or tool would do, as the app read it
* from the config: a label, and its value, code-like ones as a block.
* from the config: a label, and its value, code-like ones as a block and
* markdown ones (a brief, a runbook) rendered.
*/
export default function ProposalDetailRow({ label, value, block }: ExtensionProposalDetail) {
export default function ProposalDetailRow({ label, value, block, markdown }: ExtensionProposalDetail) {
return (
<Row className="w-full py-2 gap-3! flex-nowrap items-baseline border-0 border-b border-solid border-hairline last:border-b-0">
<Span className="w-28 shrink-0 text-[12px] leading-4 text-ink-secondary">{label}</Span>
<Span
className={twMerge(
"grow min-w-0 text-[13px] leading-5 text-ink break-words",
block && "max-h-48 overflow-auto whitespace-pre-wrap rounded-default-xs bg-sunken px-2 py-1 font-mono text-[12px]",
)}
>
{value}
</Span>
{markdown ? (
<MarkdownText text={value} boxed={block} className="grow text-[13px] leading-5" />
) : (
<Span
className={twMerge(
"grow min-w-0 text-[13px] leading-5 text-ink break-words",
block && "max-h-48 overflow-auto whitespace-pre-wrap rounded-default-xs bg-sunken px-2 py-1 font-mono text-[12px]",
)}
>
{value}
</Span>
)}
</Row>
);
}
@@ -1,4 +1,5 @@
import { useContext, useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import Input from "@moduletrace/twui/form/Input";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
@@ -113,11 +114,11 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>What it is</MessageDetailsHeading>
<Span className="text-[13px] leading-5 text-ink break-words">{view.description}</Span>
<MarkdownText text={view.description || ""} />
<Span className="mt-1 text-[12px] leading-4 text-ink-secondary">{`Saved as ${view.key}, for your runs of ${view.bot_name} only.`}</Span>
<MessageDetailsHeading>Why (written by the bot)</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.reason}</Span>
<MarkdownText text={view.reason || ""} />
{open ? (
<Stack className="mt-5 w-full gap-2! items-stretch">

Some files were not shown because too many files have changed in this diff Show More