Compare commits

...
28 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 d807f1f328 Bump version to 0.28.24
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-06 11:13:30 +01:00
tbenandClaude Opus 5.5 a94cccfd28 List Cloudflare AI models from ai/models/search
Cloudflare's OpenAI-compatible /ai/v1 has no /models route (7001 GET not
supported), so a provider on it never synced. Read the list from the
account's ai/models/search instead, paged, with the task deciding the
modalities and function_calling deciding tools.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 11:13:30 +01:00
tbenandClaude Opus 5.5 422d1a78fe Open a routine's edit modal over the list when its name is clicked
The bot's routines modal now opens the shared RoutineEditModal on top
of the list (from the row's name or its Edit item) instead of swapping
the list for the form; /admin/routines opens it from the name too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 07:34:56 +01:00
tbenandClaude Opus 5.5 507c9dce5c Bump version to 0.28.23
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-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
tbenandClaude Opus 5.5 f7ac9dbb08 Bump version to 0.28.18
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 05:06:13 +01:00
tbenandClaude Opus 5.5 a8e2c891a4 List the whole crew in the coordinator's Crew tab on a workspace page
The tab read the page's crew, which in a workspace is only that
workspace's bots, so a bot needing the user elsewhere went unlisted.
In a workspace it now reads the whole crew itself (useWholeCrew) and
keeps it current from face pushes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 05:03:10 +01:00
tbenandClaude Opus 5.5 8a75bb2a43 Open a session of its own for each started task hand-over, with the result reported back
A started hand-over (delegate_task with a new brief, or a task handed over with
start: true) used to queue its run in whatever session the target bot was on.
It now goes through startHandOverRun: a new session titled from the work, and,
when a bot handed it over, a bot_asks row of kind hand_over (no gate, the
user's quote is the say-so). The target gets the back bar, update_requester
and answer_requester, and its report goes back to and wakes the bot that
handed it over, as a crew request's answer does. Hand-overs don't count
toward the open-request cap, aren't stopped with the run that handed them
over, and show the task's own working row. The thread no longer calls a
hand-over's opening brief unanswered while its task is queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:56:40 +01:00
tbenandClaude Opus 5.5 f98b9391b0 Archive a consistent database snapshot instead of the live file in data backups
tar exited 1 with "./db/cobble: file changed as we read it" on every
production export. The database now goes in as a VACUUM INTO copy, the
live file and its journal are left out, and tar's exit 1 (a file changed
mid-read, archive still whole) counts as success.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:24:48 +01:00
tbenandClaude Opus 5.5 9cc7359334 Add a Crew tab to the coordinator's panel linking bots that need you to their chat
Faces now record the workspace of the job that set them
(bot_user_faces.workspace_id), so each worker that needs the user or is
working links to the right chat: its workspace conversation or its own.
Existing faces are placed at boot from each bot's latest job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:11:59 +01:00
tbenandClaude Opus 5.5 05d8f9e9da Show the bot's id in its panel header
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:31:52 +01:00
tbenandClaude Opus 5.5 a9fe487cbd Bump version to 0.28.17
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 02:04:26 +01:00
tbenandClaude Opus 5.5 435e080c06 Fix plan last steps, task hand-offs, card retries and failure notices from production
- A plan's last step ends with its report alone: the review no longer asks
  for a "Finish the plan" card that contradicted complete_plan_step.
- Retry on a failed plan step resumes the plan and re-runs that step.
- A task run handing work on is no longer refused against its own job.
- "handed to [bot:N]" status lines no longer read as work under way.
- A refused card gets its own note, keeps the message written beside it,
  and gets one more turn once it goes up; ask_user reads {label} options
  and JSON-string questions.
- Failure notices name the closing failure instead of blaming the review.
- A reply claiming the plan is over while the record disagrees is sent back.
- A provider's content-filter refusal fails the run at once with a clear
  message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:04:26 +01:00
232 changed files with 7962 additions and 911 deletions
+17 -14
View File
File diff suppressed because one or more lines are too long
+237 -1
View File
@@ -52,7 +52,7 @@ import {
CustomToolKinds,
CustomToolStatuses,
} from "@/src/dict/custom-tool-dict";
import { AskStatuses } from "@/src/dict/ask-dict";
import { AskKinds, AskStatuses } from "@/src/dict/ask-dict";
import {
TaskAuthors,
TaskMediaKinds,
@@ -402,6 +402,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The asked bot's session before the request opened one of its own, so its conversation can offer the way back. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "kind",
fieldDescription: `What opened it: \`ask\` (ask_bot, through the coordinator's gate) or \`hand_over\` (a task handed over and started on the user's own words, so no gate)`,
dataType: "TEXT",
options: AskKinds.map((k) => k.value),
defaultValue: "ask",
},
],
indexes: [
{
@@ -2675,6 +2682,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Short status sentence, e.g. "Waiting on you"`,
dataType: "TEXT",
},
{
fieldName: "workspace_id",
fieldDescription: `The workspace of the conversation whose job set this face, null for the bot's own chat (or a face no job set). Not a foreign key: it only says which chat the coordinator's Crew list links to`,
dataType: "INTEGER",
},
],
uniqueConstraints: [
{
@@ -4020,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`,
+127 -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",
@@ -336,6 +341,10 @@ export type BUN_SQLITE_COBBLE_BOT_ASKS = {
* The asked bot's session before the request opened one of its own, so its conversation can offer the way back. Not a foreign key
*/
previous_session_id?: number | "";
/**
* What opened it: `ask` (ask_bot, through the coordinator's gate) or `hand_over` (a task handed over and started on the user's own words, so no gate)
*/
kind?: "ask" | "hand_over" | "";
}
export type BUN_SQLITE_COBBLE_BOT_SESSIONS = {
@@ -1683,6 +1692,10 @@ export type BUN_SQLITE_COBBLE_BOT_USER_FACES = {
* Short status sentence, e.g. "Waiting on you"
*/
status_line?: string;
/**
* The workspace of the conversation whose job set this face, null for the bot's own chat (or a face no job set). Not a foreign key: it only says which chat the coordinator's Crew list links to
*/
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA = {
@@ -2517,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.
@@ -3526,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.16",
"version": "0.28.24",
"module": "index.ts",
"type": "module",
"private": true,
@@ -0,0 +1,47 @@
import { describe, expect, test } from "bun:test";
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
import planFinishedClaimNote from "./plan-finished-claim-note";
const paused = { id: 2, status: "paused", current_step: 2, total_steps: 3 };
const active_last = { id: 2, status: "active", current_step: 2, total_steps: 3 };
describe("planFinishedClaimNote", () => {
test("a paused plan claimed as finished is sent back (job 810)", () => {
const note = planFinishedClaimNote({
plan: paused,
text: "**All tasks complete.** Plan #2 finished.",
tool_uses: [{ name: "complete_plan_step", ok: false }],
});
expect(note).toContain("Plan #2 is over");
expect(note).toContain("paused, at step 3 of 3");
expect(note).toContain("update_plan");
});
test("the run that ticked the last step may say the plan is finished", () => {
expect(
planFinishedClaimNote({
plan: active_last,
text: "Plan #2 is now complete.",
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toBeNull();
});
test("a step's completion is not the plan's", () => {
expect(
planFinishedClaimNote({ plan: paused, text: "Plan #2 Step 3 (cross-task wrap-up) complete.", tool_uses: [] }),
).toBeNull();
});
test("a message that claims nothing about the plan, or a run with no plan, passes", () => {
expect(planFinishedClaimNote({ plan: paused, text: "Task #8 is done.", tool_uses: [] })).toBeNull();
expect(planFinishedClaimNote({ plan: null, text: "Plan #2 finished.", tool_uses: [] })).toBeNull();
});
test("the fault note promises no work of its own", () => {
const note = planFinishedClaimNote({ plan: paused, text: "The plan is finished.", tool_uses: [] })!;
expect(claimsWorkUnderWay({ text: note })).toBe(false);
});
});
@@ -0,0 +1,50 @@
import type { HarnessToolUse } from "@/src/harness/types";
type Params = {
/**
* The plan this run sits in, as it stood when the run began: the one it
* was queued for, or the one open in its conversation.
*/
plan: { id: number; status: string; current_step: number | null; total_steps: number } | null;
text: string;
tool_uses: HarnessToolUse[];
};
/**
* "Plan #2 finished", "the plan is now complete": the plan itself claimed
* as over, never one of its steps ("Plan #2 Step 3 complete").
*/
const FinishedClaim =
/\b(?:the\s+)?plan(?:\s*#\d+)?(?:\s+(?:is|has\s+been|was|marked))?(?:\s+now)?\s+(?:finished|completed?|done)\b/i;
/**
* Sends back a reply that says the plan is over when the app's record says
* it isn't. Job 810 wrote "All tasks complete. Plan #2 finished." right
* after `complete_plan_step` refused it ("Plan #2 is paused"), and the
* conversation said the plan was done while its card said paused.
*
* A run that finished the plan's last step itself has made the claim true.
* A plan already done is not open, so it never reaches here.
*/
export default function planFinishedClaimNote({ plan, text, tool_uses }: Params) {
if (!plan || plan.status == "done") return null;
if (!FinishedClaim.test(text.replace(/[*_`]/g, ""))) return null;
const ticked = tool_uses.some((use) => use.ok && use.name == "complete_plan_step");
const on_last = plan.current_step != null && plan.current_step + 1 >= plan.total_steps;
if (ticked && on_last && plan.status == "active") return null;
const where =
plan.current_step == null
? `${plan.status}`
: `${plan.status}, at step ${plan.current_step + 1} of ${plan.total_steps}`;
const fix =
plan.status == "paused"
? `To finish it, the user resumes it on its card (or asks you to, and you use update_plan with status "active"), and its step is then worked and ticked with complete_plan_step.`
: `Finish its current step with complete_plan_step first, or write where it really stands.`;
return `Your message says Plan #${plan.id} is over, but the app's record has it ${where}. Write where the plan really stands. ${fix}`;
}
+17 -8
View File
@@ -29,16 +29,25 @@ describe("planStepReviewNote", () => {
expect(note({ uses })).toBeNull();
});
test("the last step's card offers to finish the plan", () => {
test("ticking the last step finishes the plan, so its report needs no card (jobs 809, 811)", () => {
const last = { ...plan, current_step: 2 };
const ticked = [{ name: "complete_plan_step", ok: true }];
expect(
planStepReviewNote({
plan: last,
on_step: true,
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toContain("Finish the plan");
expect(planStepReviewNote({ plan: last, on_step: true, tool_uses: ticked, status: "done" })).toBeNull();
expect(planStepReviewNote({ plan: last, on_step: false, tool_uses: ticked, status: "done" })).toBeNull();
});
test("the last step left unfinished is sent back to finish it, without asking for a card", () => {
const fault = planStepReviewNote({
plan: { ...plan, current_step: 2 },
on_step: true,
tool_uses: [{ name: "write_file", ok: true }],
});
expect(fault).toContain("its last step");
expect(fault).toContain("complete_plan_step");
expect(fault).toContain("no card goes with this report");
expect(fault).not.toContain("Finish the plan");
});
test("a failed finish does not pass", () => {
+16 -2
View File
@@ -61,7 +61,21 @@ export default function planStepReviewNote({ plan, on_step, tool_uses, status }:
const next = step + 1;
const last_step = next > plan.total_steps;
/**
* Ticking the last step finishes the plan (`completeBotPlanStep` sets it
* `done`), so there is nothing left for a card to move on to: the report
* alone ends it, as `complete_plan_step` tells the bot. Asking for a
* "Finish the plan" card there contradicted that answer, and every
* rewrite was refused until the job failed and the finished plan was
* paused again (jobs 809 and 811, Plan #2).
*/
if (last_step && ticked) return null;
if (last_step) {
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}"), its last step, and ended without finishing it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. That finishes the plan, so no card goes with this report. If it needs the user for something first, ask that with ask_user and say the plan is holding at this step. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it.`;
}
return on_step
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "Continue to step ${next}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "Continue to step ${next}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
}
+24 -4
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,
@@ -146,10 +148,13 @@ export default async function processBotJob({
* it to idle, and a late `working` or `asleep` would push over that and
* leave a bot that shows work with nothing behind it.
*/
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id">) => {
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id" | "workspace_id">) => {
if (!user_id || unattended || controller.signal.aborted) return;
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
await pushBotNotice({
bot_id,
bot: await setBotFace({ bot_id, user_id, workspace_id: job.workspace_id || null, ...face }),
});
};
/**
@@ -485,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" &&
@@ -493,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);
+11 -3
View File
@@ -86,6 +86,7 @@ import stripAppRecords from "@/src/utils/strip-app-records";
import hasUnansweredMessage from "./has-unanswered-message";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import planFinishedClaimNote from "./plan-finished-claim-note";
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
@@ -498,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 });
@@ -730,7 +735,10 @@ export default async function runBotReply({
reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id, plan_mode })({ text, tool_uses, status }).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
return (
planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status }) ??
planFinishedClaimNote({ plan, text, tool_uses })
);
});
const result = await runTextLoop({
@@ -793,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()}.`,
]
+7 -2
View File
@@ -96,6 +96,7 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
import BotJobFatalError from "./bot-job-fatal-error";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import planFinishedClaimNote from "./plan-finished-claim-note";
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -785,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");
@@ -847,6 +848,7 @@ export default async function runBotTask({
session_id,
computers,
message_id: job.message_id || undefined,
job_id: job.id,
run_kind: browser_run_kind,
plan_id: on_plan_step ? plan?.id : null,
}),
@@ -915,7 +917,10 @@ export default async function runBotTask({
}).then((note) => {
if (note) return note;
return planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status });
return (
planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status }) ??
planFinishedClaimNote({ plan: plan ?? session_plan, text, tool_uses })
);
}),
/**
* A report goes out only through `send_reply`, so it can't say
+34 -1
View File
@@ -1,5 +1,16 @@
import { describe, expect, test } from "bun:test";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import {
closingNoTextNote,
closingToolGoneNote,
replyCardFailedNote,
replyCardOnlyFailedNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
} from "@/src/data/harness-prompts";
import planStepReviewNote from "./plan-step-review";
import unsentAnswerMessage from "./unsent-answer-message";
/**
@@ -29,6 +40,28 @@ describe("unsentAnswerMessage", () => {
);
});
test("closing failures name the call that failed, never the review (jobs 680, 694, 700)", () => {
expect(unsentAnswerMessage({ note: replyClosingFailedNote })).toContain("call that sends the message");
expect(unsentAnswerMessage({ note: replyClosingRequiredNote })).toContain("never sent the message");
expect(unsentAnswerMessage({ note: replyClosingMixedNote })).toContain("other work");
expect(unsentAnswerMessage({ note: replyCardOnlyFailedNote({ tools: ["ask_user"] }) })).toContain("card");
expect(unsentAnswerMessage({ note: replyCardFailedNote({ tools: ["suggest_next_steps"] }) })).toContain("card");
for (const note of [replyClosingFailedNote, replyClosingRequiredNote, replyCardOnlyFailedNote({ tools: ["ask_user"] })]) {
expect(unsentAnswerMessage({ note })).not.toContain("app's record");
}
});
test("a plan step that ended wrong says so", () => {
const note = planStepReviewNote({
plan: { id: 2, title: "Finish", current_step: 0, total_steps: 3 },
on_step: true,
tool_uses: [],
});
expect(unsentAnswerMessage({ note: note! })).toContain("plan step");
});
test("a check against the record keeps saying so", () => {
expect(unsentAnswerMessage({ note: "It names task #16, and no such task exists." })).toBe(
`The answer didn't hold up against the app's record, so it wasn't sent.`,
+51 -4
View File
@@ -1,4 +1,14 @@
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import {
closingFailedNote,
closingMixedNote,
closingNoTextNote,
closingToolGoneNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
} from "@/src/data/harness-prompts";
type Params = {
/**
@@ -9,8 +19,21 @@ type Params = {
};
/**
* The failure notice a run that never sent its answer leaves. The note
* the loop returned picks the line, so an empty close is not called a lie.
* The openings of the notes built per call (`replyCardFailedNote`,
* `replyCardOnlyFailedNote`, `planStepReviewNote`, `unfinishedAnswerText`):
* their tails name tools or steps, so they are told apart by how they start.
*/
const CardRefusedOpenings = ["The card was not put up", "send_reply went through and your message is kept"];
const PlanStepOpenings = ["This reply works step", "This reply finished step"];
const UnfinishedOpening = "The message stops ";
/**
* The failure notice a run that never sent its answer leaves. The note the
* loop returned picks the line, so a run that failed for its own mechanics
* is never called a lie: "didn't hold up against the app's record" is only
* for an answer the review actually checked and refused. Before, every
* closing failure fell through to that line (jobs 680, 694, 700), and the
* user read five failures as a bot caught out when none was.
*/
export default function unsentAnswerMessage({ note }: Params) {
if (note === replyNoTextNote) {
@@ -29,5 +52,29 @@ export default function unsentAnswerMessage({ note }: Params) {
return `The run's last turn called a tool it no longer had, so its message wasn't sent.`;
}
if (note === replyClosingFailedNote) {
return `The call that sends the message kept being refused, so the message wasn't sent.`;
}
if (note === replyClosingRequiredNote) {
return `The reply put its card up but never sent the message with it, so it wasn't sent.`;
}
if (note === replyClosingMixedNote || note === closingMixedNote) {
return `The reply kept doing other work in the turn meant to send its message, so it wasn't sent.`;
}
if (note === closingFailedNote || CardRefusedOpenings.some((opening) => note.startsWith(opening))) {
return `The card under the message kept being refused, so the message wasn't sent.`;
}
if (PlanStepOpenings.some((opening) => note.startsWith(opening))) {
return `The reply didn't end its plan step the way the plan needs, so it wasn't sent.`;
}
if (note.startsWith(UnfinishedOpening)) {
return `The message stopped part-way through (an unclosed table, list or code block), so it wasn't sent.`;
}
return `The answer didn't hold up against the app's record, so it wasn't sent.`;
}
}
+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>
+15 -1
View File
@@ -15,6 +15,10 @@ type Props = {
busy?: boolean;
onToggle: () => void;
onEdit: () => void;
/**
* What clicking its name does: opens it for editing, over the list.
*/
onOpen?: () => void;
onDelete: () => void;
/**
* Hand it to another bot where it runs.
@@ -33,7 +37,16 @@ type Props = {
* latest run left its messages in), Chat, Pause or Resume, Edit, Hand
* over and Delete.
*/
export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete, onHandOver, compact }: Props) {
export default function RoutineRow({
cron_job,
busy,
onToggle,
onEdit,
onOpen,
onDelete,
onHandOver,
compact,
}: Props) {
const title = cron_job.title || `Routine ${cron_job.id}`;
const done = Boolean(cron_job.max_runs && Number(cron_job.run_count || 0) >= cron_job.max_runs);
const chat_url = conversationHref({
@@ -58,6 +71,7 @@ export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete,
/>
}
title={title}
onOpen={onOpen}
badge={cron_job.enabled ? undefined : done ? "Done" : "Paused"}
subtitle={routineSubtitle({
cron_job,
+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
+7 -2
View File
@@ -345,8 +345,13 @@ describe("plan notes", () => {
expect(note).toContain('"Pause the plan"');
});
test("the last step's card offers to finish the plan", () => {
expect(PlanStepNote({ plan: { ...plan, current_step: 2 } })).toContain('"Finish the plan"');
test("the last step ends the plan with its report alone, no card", () => {
const note = PlanStepNote({ plan: { ...plan, current_step: 2 } });
expect(note).toContain("This is the last step");
expect(note).toContain("no card");
expect(note).not.toContain("Finish the plan");
expect(note).not.toContain("Every finished step ends on a card");
});
test("lists the steps with where each one stands and what it produced", () => {
+56 -11
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.
@@ -385,7 +411,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
* `bot_id` is the coordinator itself, so the ref example it copies is its
* own rather than a worker's.
*/
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). Each started run opens a session of its own in their conversation, they can send you a word on the way, and their report comes back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
/**
* Added to the coordinator's chat prompt instead while it has no workers,
@@ -406,7 +432,7 @@ export const workspaceAdminNote = ({
members: { id?: number | "" }[];
}) => `# Leading ${workspace_name}
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); each started run opens a session of its own in their conversation here, they can send you a word on the way, and their report comes back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
/**
* Added to a workspace member's prompt while the workspace has an admin,
@@ -655,6 +681,14 @@ export const replyClosingFailedNote = `send_reply did not go through (its error
export const replyCardFailedNote = ({ tools }: { tools: string[] }) =>
`send_reply went through and your message is kept. The card call did not: ${tools.join(" and ")} refused (its error is above). Fix those arguments, or drop the card, and call send_reply again in the same turn with the same message.`;
/**
* Told when a card was refused in a turn that never called `send_reply`:
* the card's error is what to fix. Telling the model `send_reply` failed
* there sent it after a status error that never happened (job 694).
*/
export const replyCardOnlyFailedNote = ({ tools }: { tools: string[] }) =>
`The card was not put up: ${tools.join(" and ")} refused its arguments (the error is above), so nothing reached the user. Fix those arguments exactly as the error says and call it again, with send_reply in the same turn carrying your message (the message you wrote beside the card is kept for it). Or drop the card and answer with send_reply alone.`;
/**
* Put under an answer the review kept faulting once its unsupported parts
* were taken out (`repairAnswerText`): the user is told part of it is gone
@@ -1146,7 +1180,15 @@ export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
const index = plan.current_step ?? 0;
const step = plan.steps[index];
const next = index + 2;
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
const last_step = next > plan.steps.length;
/**
* The last step's tick finishes the plan, so its report ends the plan
* on its own: a "Finish the plan" card would move nothing on, and the
* review used to demand one while the tool said none was needed.
*/
const ending = last_step
? `- **This is the last step.** complete_plan_step finishes the plan, so the report goes out with send_reply alone and no card: there is no next step to continue to.`
: `- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "Continue to step ${next}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.`;
return `# Your plan, step ${index + 1} of ${plan.steps.length}
@@ -1156,10 +1198,10 @@ ${planStepLines({ plan })}
This run works step ${index + 1} only: ${step?.text || ""}
- One step per run. The next step starts when the user answers this report's card, so don't start it now and don't do two.
- One step per run.${last_step ? "" : " The next step starts when the user answers this report's card, so don't start it now and don't do two."}
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "${next_label}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan${last_step ? "" : " and the step after this one"}, so repeating it only makes the reply longer than it needs to be.
${ending}
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask that question on the card, and say the plan is holding at this step.
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same run, and say what changed.`;
};
@@ -1175,7 +1217,10 @@ export const PlanActiveNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mod
const index = plan.current_step;
const step = index == null ? null : plan.steps[index];
const next = (index ?? 0) + 2;
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
const work_step =
next > plan.steps.length
? `finish it with complete_plan_step in this run. It is the last step, so that finishes the plan and the report goes out alone, with no card.`
: `finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "Continue to step ${next}", second "Pause the plan"). A report that ticked the step without that card is sent back.`;
return `# The plan in this conversation
@@ -1187,7 +1232,7 @@ ${
plan_mode
? `- This reply runs in Plan mode: the plan is yours to pick up and refine here, not to work. When what they say bears on the steps, rewrite them with update_plan (the whole list, done steps first and unchanged), as many times as the conversation asks, and say in a line what changed. Don't work or tick a step, and don't pause or resume the plan: that waits until the mode is off.`
: `- Its steps are normally worked one per reply, each ending on a card the user answers to start the next one. This reply isn't a step the app queued: answer whatever the user asked first.
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "${next_label}", second "Pause the plan"). A report that ticked the step without that card is sent back.
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: ${work_step}
- If they asked something else, answer that and leave the plan where it is: it carries on from there. Don't work a step as a side errand.
- If the user's answer to the plan's card was typed rather than a click, it is theirs to read here: carry on with the step when it says to, and park the plan with update_plan and status "paused" when it says to wait.
- Only pause or resume when they asked, with update_plan and its status. Never end a plan on your own: cancelling is theirs. The steps are theirs to change on the card too; if the work moved on from one of them, update_plan and say what changed.`
+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:
+23 -1
View File
@@ -85,4 +85,26 @@ export const AskAnswerJobTitle = "Crew request";
* requests one place keeps (`AppData.AskKeepDays`, `AskMaxPerPlace`).
*/
export const AskKeepDaysSettingKey = "ask_keep_days";
export const AskMaxPerPlaceSettingKey = "ask_max_per_place";
export const AskMaxPerPlaceSettingKey = "ask_max_per_place";
/**
* What opened a request. `ask` is `ask_bot`, which goes through the
* coordinator's gate. `hand_over` is a task one bot handed another and
* started because the user said so (`delegate_task`, `hand_over_task`): no
* gate, but the same thread of its own, interim updates and result back.
*/
export const AskKinds = [
{
title: "Crew request",
value: "ask",
},
{
title: "Hand-over",
value: "hand_over",
},
] as const;
export type AskKind = (typeof AskKinds)[number]["value"];
export function isHandOverAsk({ kind }: { kind?: string | null }) {
return kind == "hand_over";
}
+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",
@@ -0,0 +1,34 @@
import { Database } from "bun:sqlite";
type Params = {
/**
* The live database file.
*/
source: string;
/**
* Where the copy goes. Must not exist yet.
*/
target: string;
};
/**
* Copies a live SQLite database into one consistent file with
* `VACUUM INTO`, which reads the whole database inside one read
* transaction, so writes made while it runs are either all in the copy or
* none of them. A data archive used to tar the live file, which the app
* writes every few seconds, so tar failed with "file changed as we read
* it" and the copy it kept was torn anyway.
*
* Its own read-only connection, so it needs no extension loaded (the
* vec0 tables' rows are plain shadow tables) and never touches the app's.
*/
export default function snapshotDatabaseFile({ source, target }: Params) {
const db = new Database(source, { readonly: true });
try {
db.run("PRAGMA busy_timeout = 5000;");
db.run("VACUUM INTO ?", [target]);
} finally {
db.close();
}
}
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import { Database } from "bun:sqlite";
import writeDataBackupArchive from "./write-data-backup-archive";
const dirs: string[] = [];
@@ -25,6 +26,24 @@ function write({ root, relative, content = "x" }: { root: string; relative: stri
fs.writeFileSync(target, content);
}
/**
* A real database at `db/cobble`: the archive snapshots it, so a stand-in
* file would not open.
*/
function writeDatabase({ root, rows = 1 }: { root: string; rows?: number }) {
fs.mkdirSync(path.join(root, "db"), { recursive: true });
const db = new Database(path.join(root, "db", "cobble"), { create: true });
db.run("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)");
db.transaction(() => {
for (let i = 0; i < rows; i++) db.run("INSERT INTO notes (body) VALUES (?)", [`note ${i}`]);
})();
return db;
}
afterEach(() => {
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
@@ -44,7 +63,7 @@ describe("writeDataBackupArchive", () => {
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
writeDatabase({ root: data_dir }).close();
write({ root: data_dir, relative: "db/.backups/cobble-1" });
write({ root: data_dir, relative: ".bun-sqlite/.tmp/temp.db" });
write({ root: data_dir, relative: "computers/1/bots/3/users/1/work.txt" });
@@ -91,11 +110,53 @@ describe("writeDataBackupArchive", () => {
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
writeDatabase({ root: data_dir }).close();
write({ root: archive_dir, relative: "cobble-data-1.tar.gz" });
const created = await writeDataBackupArchive();
expect(fs.existsSync(created.path)).toBe(true);
});
});
test("archives a consistent copy of the database while it is being written", async () => {
const data_dir = makeRoot();
const archive_dir = makeRoot();
const extract_dir = makeRoot();
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
const db = writeDatabase({ root: data_dir, rows: 2000 });
// An open write transaction leaves a journal beside the file,
// which tar would otherwise read half-written.
db.run("BEGIN");
db.run("INSERT INTO notes (body) VALUES ('uncommitted')");
const created = await writeDataBackupArchive();
db.run("ROLLBACK");
db.close();
const root = created.name.replace(/\.tar\.gz$/, "");
const members = new TextDecoder()
.decode(Bun.spawnSync(["tar", "-tzf", created.path]).stdout)
.split("\n")
.filter(Boolean);
expect(members).toContain(`${root}/db/cobble`);
expect(members.some((member) => member.includes(".snapshot"))).toBe(false);
expect(members.some((member) => member.endsWith("-journal"))).toBe(false);
Bun.spawnSync(["tar", "-xzf", created.path, "-C", extract_dir]);
const copy = new Database(path.join(extract_dir, root, "db", "cobble"), { readonly: true });
const { n } = copy.query("SELECT count(*) AS n FROM notes").get() as { n: number };
const { integrity_check } = copy.query("PRAGMA integrity_check").get() as { integrity_check: string };
copy.close();
expect(integrity_check).toBe("ok");
expect(n).toBe(2000);
});
});
@@ -6,6 +6,14 @@ import grabDirNames from "@/src/utils/grab-dir-names";
import grabBackupArchiveDir from "@/src/utils/grab-backup-archive-dir";
import grabDataBackups from "./grab-data-backups";
import listArchiveExclusions from "./list-archive-exclusions";
import snapshotDatabaseFile from "./snapshot-database-file";
import BunSQLiteConfig from "@/bun-sqlite.config";
/**
* The live database's sidecars: the rollback journal, or WAL and its
* index. The snapshot replaces all of them.
*/
const DatabaseSidecarSuffixes = ["", "-journal", "-wal", "-shm"];
export type CreatedDataBackup = {
name: string;
@@ -17,9 +25,15 @@ export type CreatedDataBackup = {
* bot and workspace files, MCP installs, Chrome profiles) into
* `BACKUP_ARCHIVE_DIR` and keeps only the newest
* `AppData.DataBackupsKept`. Every entry sits under one root folder named
* after the archive, so extracting it lands one folder. The SQLite file
* inside is only as consistent as the moment tar read it; `db/.backups` is
* for consistent snapshots.
* after the archive, so extracting it lands one folder.
*
* The database is never tarred live: the app writes it every few seconds,
* so tar exited 1 with "./db/cobble: file changed as we read it" and kept
* a torn copy. A `VACUUM INTO` snapshot (`snapshotDatabaseFile`) goes in
* at `db/<db_name>` instead, and the live file and its journal are left
* out. Anything else changing mid-read (a bot saving a file, Chrome
* writing its cookies) is only tar's exit 1, which still means a whole
* archive, so that is a success; 2 and up fail the run.
*
* It leaves out what is rebuilt on demand or kept elsewhere
* (`listArchiveExclusions`): a computer's own folders, Chrome profile
@@ -41,10 +55,27 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
const part_path = `${archive_path}.part`;
const excl_dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
const excl_path = path.join(excl_dir, "exclude.txt");
const db_file = path.join(DATA_DIR, "db", BunSQLiteConfig.db_name);
const has_db = fs.existsSync(db_file);
// Staged under a name of its own: the live file's member path is
// excluded, and tar would drop a staged file of the same name too.
const snapshot_member = `./db/${BunSQLiteConfig.db_name}.snapshot`;
try {
const exclusions = await listArchiveExclusions({ data_dir: DATA_DIR });
if (has_db) {
for (const suffix of DatabaseSidecarSuffixes) {
exclusions.push(`./db/${BunSQLiteConfig.db_name}${suffix}`);
}
fs.mkdirSync(path.join(excl_dir, "db"), { recursive: true });
snapshotDatabaseFile({
source: db_file,
target: path.join(excl_dir, snapshot_member),
});
}
fs.writeFileSync(excl_path, exclusions.map((line) => `${line}\n`).join(""));
const proc = Bun.spawn(
@@ -58,8 +89,14 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
// Two expressions: the root `.` itself and every `./`
// member, so the whole archive sits under one folder named
// after it and an extract drops a single folder.
// The database snapshot first takes the live file's
// place (`db/<db_name>`).
"--transform",
`s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
`s,^\\./db/${BunSQLiteConfig.db_name}\\.snapshot$,${archive_root}/db/${BunSQLiteConfig.db_name},;s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
// A file written while tar reads it (a bot's save, a
// Chrome profile) is exit 1, not a broken archive.
"--warning=no-file-changed",
"--warning=no-file-removed",
// The exclusions are exact member paths
// (`listArchiveExclusions`), never patterns: a folder a
// bot named `node_modules!` or `Cache*` must not take a
@@ -69,6 +106,7 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
"-C",
DATA_DIR,
".",
...(has_db ? ["-C", excl_dir, snapshot_member] : []),
],
{
cwd: process.cwd(),
@@ -85,7 +123,9 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
proc.exited,
]);
if (exit_code !== 0) {
// GNU tar: 1 is "some files differ" (changed while read), and the
// archive is still whole; 2 is a fatal error.
if (exit_code !== 0 && exit_code !== 1) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
@@ -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": {
@@ -49,4 +49,15 @@ describe("askOutcomeMessage", () => {
test("names an unnamed request without empty quotes", () => {
expect(askOutcomeMessage({ ask: { ...ask, title: "" }, status: "refused" })).toContain("your crew request");
});
test("a hand-over's report says it was work handed over, not a request the coordinator passed on", () => {
const handed = { ...ask, kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
const text = askOutcomeMessage({ ask: handed, status: "answered", outcome: "Shipped." });
expect(text).toBe('[bot:12] finished "Cite the sheet" [ask:3], which you handed over. Their report:\n\nShipped.');
expect(askOutcomeMessage({ ask: handed, status: "failed", outcome: "No computer." })).toContain(
"couldn't finish",
);
expect(askOutcomeMessage({ ask: handed, status: "stopped" })).not.toContain("coordinator");
});
});
@@ -1,5 +1,5 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import type { AskStatus } from "@/src/dict/ask-dict";
import { isHandOverAsk, type AskStatus } from "@/src/dict/ask-dict";
import askRef from "@/src/utils/ask-ref";
import botRef from "@/src/utils/bot-ref";
@@ -20,6 +20,20 @@ export default function askOutcomeMessage({ ask, status, outcome }: Params) {
const pill = ask.id ? ` ${askRef({ id: ask.id })}` : "";
const target = ask.target_bot_id ? botRef({ id: ask.target_bot_id }) : "the crew";
if (isHandOverAsk({ kind: ask.kind })) {
const handed = ask.title ? `"${ask.title}"` : "the work";
if (status == "stopped") {
return `${handed}${pill}, which you handed to ${target}, was stopped: ${outcome || "the user stopped it."}`;
}
if (status == "failed" || status == "refused") {
return `${target} couldn't finish ${handed}${pill}, which you handed over:\n\n${outcome || "No reason was given."}`;
}
return `${target} finished ${handed}${pill}, which you handed over. Their report:\n\n${outcome || ""}`;
}
if (status == "refused") {
return `The coordinator turned down ${title}${pill}:\n\n${ask.gate_note || outcome || "No reason was given."}`;
}
@@ -1,5 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import botRef from "@/src/utils/bot-ref";
import { isHandOverAsk } from "@/src/dict/ask-dict";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -21,6 +22,18 @@ export default function askRequestMessage({ ask, requester_name, place }: Params
const requester = ask.requester_bot_id ? botRef({ id: ask.requester_bot_id }) : `"${requester_name}"`;
const where = place ? `, from the ${place} workspace` : "";
/**
* A task handed over on the user's word: the work is this run's, and
* its result goes back to the bot that handed it over on its own.
*/
if (isHandOverAsk({ kind: ask.kind })) {
return `${requester} handed this over to you (hand-over #${ask.id}${where}):
> ${(ask.request || "").trim().replace(/\n/g, "\n> ")}
Work it in this conversation. Your report goes back to ${requester} when the run ends; update_requester sends it a word meanwhile.`;
}
return `The coordinator passed on a request from ${requester} (ask #${ask.id}${where}):
> ${(ask.request || "").trim().replace(/\n/g, "\n> ")}
@@ -1,6 +1,7 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import askRef from "@/src/utils/ask-ref";
import botRef from "@/src/utils/bot-ref";
import { isHandOverAsk } from "@/src/dict/ask-dict";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -36,9 +37,10 @@ export default function askUpdateMessage({ ask, text, failed, ended }: Params) {
? `${target} couldn't finish one piece of ${title}${pill}:`
: `${target} sent a response on ${title}${pill}:`;
const what = isHandOverAsk({ kind: ask.kind }) ? "hand-over" : "request";
const tail = ended
? `_The request had already ended; this is the answer, sent afterwards._`
: `_The request is still open - more may follow._`;
? `_The ${what} had already ended; this is the answer, sent afterwards._`
: `_The ${what} is still open - more may follow._`;
return `${head}\n\n${text}\n\n${tail}`;
}
@@ -12,7 +12,8 @@ type Params = {
export default async function countOpenAsks({ user_id, requester_bot_id }: Params) {
const res = await BunSQLite.sql<{ n: number }>({
sql: `SELECT COUNT(*) AS n FROM bot_asks
WHERE user_id = ? AND requester_bot_id = ? AND status IN ('pending', 'working')`,
WHERE user_id = ? AND requester_bot_id = ? AND status IN ('pending', 'working')
AND COALESCE(kind, 'ask') = 'ask'`,
values: [Number(user_id), Number(requester_bot_id)],
});
@@ -34,7 +34,9 @@ export type ConversationAsk = {
* The crew request the bot is answering for this user, if one is open. The
* answer runs in the bot's own conversation, and stays `working` while any
* run it started is still open, so the row under the last message reads this
* to say who it's answering for as long as the work is under way.
* to say who it's answering for as long as the work is under way. A
* hand-over is a task run, so its thread shows the task's own working row
* (with its progress) instead.
*/
export default async function grabConversationAsk({
user_id,
@@ -52,7 +54,8 @@ export default async function grabConversationAsk({
FROM bot_asks a
LEFT JOIN bots b ON b.id = a.requester_bot_id
LEFT JOIN workspaces w ON w.id = a.workspace_id
WHERE a.user_id = ? AND a.target_bot_id = ? AND a.status = 'working' ${place}
WHERE a.user_id = ? AND a.target_bot_id = ? AND a.status = 'working'
AND COALESCE(a.kind, 'ask') = 'ask' ${place}
ORDER BY a.id DESC
LIMIT 1`,
values,
@@ -169,6 +169,24 @@ describe("onAskJobEnded - the answer reply", () => {
});
});
describe("onAskJobEnded - a hand-over's run", () => {
test("its report ends the hand-over answered", async () => {
ask = { ...workingAsk(), kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: answerJob(), text: real_answer });
expect(finished).toEqual([{ status: "answered", outcome: real_answer }]);
});
test("a failed run passes on why it failed", async () => {
ask = { ...workingAsk(), kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: answerJob(), text: "The computer is down.", failed: true });
expect(finished).toEqual([{ status: "failed", outcome: "The computer is down." }]);
});
});
describe("onAskJobEnded - a run the answer handed the work to", () => {
test("a result while more work is open is relayed as an update and keeps the request open", async () => {
open_work = true;
@@ -4,7 +4,7 @@ import parseJobJson from "@/src/bots-queue/parse-job-json";
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
import { WorkStartingTools } from "@/src/utils/reply-claim-problems";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import { AskStages } from "@/src/dict/ask-dict";
import { AskStages, isHandOverAsk } from "@/src/dict/ask-dict";
import hasOpenWork from "../bots-queue/has-open-work";
import deleteEmptyAskSession from "../bot-sessions/delete-empty-ask-session";
import askUpdateMessage from "./ask-update-message";
@@ -139,7 +139,13 @@ export default async function onAskJobEnded({ job, text, failed, tool_uses = []
await finishAsk({
ask,
status: "failed",
outcome: "The bot it was passed to couldn't answer. Try again, or ask another bot.",
/**
* A hand-over's run is the work itself: why it failed is what
* the bot that handed it over needs to hear.
*/
outcome: isHandOverAsk({ kind: ask.kind })
? (text || "").trim() || "The run failed."
: "The bot it was passed to couldn't answer. Try again, or ask another bot.",
});
return;
@@ -0,0 +1,218 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS, BUN_SQLITE_COBBLE_BOTS, BunSQLiteTables } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { AskStages } from "@/src/dict/ask-dict";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import AppError from "@/src/utils/app-error";
import askPreviousSessionId from "@/src/utils/ask-previous-session-id";
import { truncateText } from "@/src/utils/truncate-text";
import grabActiveBotSession from "../bot-sessions/grab-active-bot-session";
import startBotSession from "../bot-sessions/start-bot-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabOpenHandOverRun from "../bots-queue/grab-open-hand-over-run";
import insertBotMessage from "../bots/insert-bot-message";
import insertUserMessage from "../bots/insert-user-message";
import grabWorkspaceName from "../workspaces/grab-workspace-name";
import askRequestMessage from "./ask-request-message";
import grabOpenAskBySession from "./grab-open-ask-by-session";
type Params = {
/**
* The user the work runs for.
*/
user_id: number | string;
/**
* The bot taking the work, and where it runs (null: its own chat).
*/
bot: BUN_SQLITE_COBBLE_BOTS;
workspace_id: number | null;
title: string;
brief: string;
/**
* The tracker task this run works, when a task is handed over.
*/
tracker_task_id?: number | null;
computer_id?: number | null;
/**
* The bot handing it over and the session it did from. None when a user
* hands a task over from the UI.
*/
requested_by_bot_id?: number | string | null;
requested_by_session_id?: number | string | null;
/**
* Who hands it over, for the line that opens the session when no
* hand-over record is made.
*/
notice: string;
task_ids?: number[];
};
export type HandOverRun = {
job_id: number;
session_id: number;
/**
* The hand-over's record (`bot_asks`, kind `hand_over`), when a bot
* handed the work over.
*/
ask_id: number | null;
};
/**
* Starts work handed to a bot the way `ask_bot`'s answer starts: in a
* session of its own (`startBotSession`), titled from the work, so it never
* lands in whatever the bot's conversation was on. When a bot handed it
* over, the session is a hand-over's (`bot_asks` with kind `hand_over`, no
* gate: the user asked for it in their own words), so its thread leads back
* to the session before it, the run (and any reply there while it is open)
* can send that bot a word with `update_requester`, its report goes back and
* wakes that bot (`onAskJobEnded`), and a late answer goes with
* `answer_requester`. Handed over from inside a crew request's answer, the
* run carries that request instead, so its result still reaches the bot
* that asked.
*/
export default async function startHandOverRun({
user_id,
bot,
workspace_id,
title,
brief,
tracker_task_id,
computer_id,
requested_by_bot_id,
requested_by_session_id,
notice,
task_ids,
}: Params): Promise<HandOverRun> {
const bot_id = Number(bot.id);
const open = await grabOpenHandOverRun({
user_id,
bot_id,
tracker_task_id,
title,
requested_by_session_id,
});
if (open) {
throw new AppError(
`${bot.name} already has "${open.title || title}" ${open.status == "pending" ? "queued" : "under way"} (run #${open.id}). Don't hand it over again; its result comes back when it ends.`,
);
}
const parent = requested_by_session_id
? await grabOpenAskBySession({ session_id: requested_by_session_id, user_id }).catch(() => null)
: null;
const previous = await grabActiveBotSession({ user_id, bot_id, workspace_id });
const session = await startBotSession({ user_id, bot_id, workspace_id });
const session_id = Number(session.id);
/**
* Titled from the work, so the sessions list says what it is before the
* bot writes anything (`nameBotSession` renames it later).
*/
await BunSQLite.sql({
sql: "UPDATE bot_sessions SET title = ? WHERE id = ? AND title IS NULL",
values: [title.slice(0, 120), session_id],
}).catch(() => null);
const requested = {
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
};
const tracker = tracker_task_id ? { tracker_task_id: Number(tracker_task_id) } : {};
if (!requested_by_bot_id || parent?.id) {
const job_id = Number(
await enqueueBotJob({
user_id,
bot_id,
session_id,
title,
instructions: brief,
params: { ...tracker, ...(parent?.id ? { ask_id: Number(parent.id) } : {}) },
computer_id: computer_id || undefined,
...requested,
}),
);
await pushBotNotice({
bot_id,
message: await insertBotMessage({ bot_id, session_id, workspace_id, text: notice, task_ids }),
});
return { job_id, session_id, ask_id: null };
}
const ask_row: BUN_SQLITE_COBBLE_BOT_ASKS = {
user_id: Number(user_id),
workspace_id: workspace_id || undefined,
requester_bot_id: Number(requested_by_bot_id),
target_bot_id: bot_id,
origin_session_id: Number(requested_by_session_id) || undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: brief.trim(), max: AppData.AskBriefMaxChars }),
status: "working",
kind: "hand_over",
session_id,
previous_session_id: askPreviousSessionId({ previous_session_id: previous?.id, session_id }) || undefined,
};
const inserted = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_ASKS, (typeof BunSQLiteTables)[number]>({
table: "bot_asks",
data: [ask_row],
});
const ask_id = Number(inserted.postInsertReturn?.insertId) || 0;
if (!inserted.success || !ask_id) {
throw new Error(`Couldn't record the hand-over: ${inserted.msg}`);
}
const ask = { ...ask_row, id: ask_id };
const message = await insertUserMessage({
bot_id,
session_id,
workspace_id,
text: askRequestMessage({ ask, requester_name: "", place: await grabWorkspaceName({ workspace_id }) }),
from_ask_id: ask_id,
});
await pushBotNotice({ bot_id, message });
let job_id: number;
try {
job_id = Number(
await enqueueBotJob({
user_id,
bot_id,
session_id,
title,
instructions: brief,
params: { ...tracker, ask_id, stage: AskStages.answer },
computer_id: computer_id || undefined,
...requested,
}),
);
} catch (error) {
/**
* Nothing will work it: the tool call fails and says why, so the
* record ends without waking anyone.
*/
await BunSQLite.sql({
sql: `UPDATE bot_asks SET status = 'failed', outcome = ?, updated_at = ? WHERE id = ?`,
values: ["It couldn't be started.", Date.now(), ask_id],
}).catch(() => null);
throw error;
}
await BunSQLite.sql({
sql: `UPDATE bot_asks SET job_id = ?, updated_at = ? WHERE id = ?`,
values: [job_id, Date.now(), ask_id],
});
return { job_id, session_id, ask_id };
}
+4 -1
View File
@@ -25,6 +25,9 @@ type Params = {
* Stops every request a bot made from a run the user just stopped: the ask
* ends as `stopped` (the asking bot is told, but not woken, since its run is
* the one that was stopped) and whatever run was working it is cancelled.
* A hand-over is left alone: the user asked for that work themselves, and
* stopping the bot that handed it over (often still writing its reply when
* Stop is pressed) is not stopping the work; its report still comes back.
*/
export default async function stopAsks({ user_id, requester_bot_id, job_ids, session_ids }: Params) {
if (!job_ids.length && !session_ids.length) return [];
@@ -41,7 +44,7 @@ export default async function stopAsks({ user_id, requester_bot_id, job_ids, ses
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `SELECT * FROM bot_asks WHERE user_id = ? AND requester_bot_id = ?
AND (${match}) AND status IN ('pending', 'working')`,
AND (${match}) AND status IN ('pending', 'working') AND COALESCE(kind, 'ask') = 'ask'`,
values: [
Number(user_id),
Number(requester_bot_id),
@@ -36,13 +36,20 @@ export default async function tellAskRequester({ ask, text, wake = true }: Param
const origin = await grabUserBotSession({ session_id: ask.origin_session_id!, user_id: Number(ask.user_id)! });
/**
* The asking bot's own place: the origin's, which a hand-over from the
* coordinator's own chat into a workspace doesn't share with the request
* (`ask.workspace_id` is where the work runs).
*/
const workspace_id = origin ? Number(origin.workspace_id) || null : Number(ask.workspace_id) || null;
const session =
origin?.status == "active"
? origin
: await ensureBotSession({
user_id: Number(ask.user_id)!,
bot_id: requester.id,
workspace_id: Number(ask.workspace_id) || null,
workspace_id,
});
if (!session?.id) {
@@ -52,7 +59,7 @@ export default async function tellAskRequester({ ask, text, wake = true }: Param
const message = await insertUserMessage({
bot_id: requester.id,
session_id: session.id,
workspace_id: Number(ask.workspace_id) || null,
workspace_id: Number(session.workspace_id) || null,
text,
from_ask_id: Number(ask.id),
});
@@ -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({
@@ -17,10 +17,10 @@ type Params = {
export default async function answeringAskFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
}: Params): Promise<{ face: BotFace; status_line: string; workspace_id: number | null } | null> {
const running = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT q.id FROM bots_queue q
await BunSQLite.sql<{ id: number; workspace_id: number | null }>({
sql: `SELECT q.id, q.workspace_id FROM bots_queue q
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ask_id IS NOT NULL)
LIMIT 1`,
@@ -28,5 +28,7 @@ export default async function answeringAskFace({
})
).payload?.[0];
return running ? { face: "working", status_line: BotReplyJobTitle } : null;
return running
? { face: "working", status_line: BotReplyJobTitle, workspace_id: Number(running.workspace_id) || null }
: null;
}
@@ -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 }));
}
@@ -223,6 +223,7 @@ export default async function completeBotJob({
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
workspace_id: job.workspace_id || null,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
@@ -1,38 +1,16 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import openBotTaskSql from "./open-bot-task-sql";
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* Only a task with this title. Without it, any open task.
*/
title?: string;
/**
* Only a task on this computer.
*/
computer_id?: number | string | null;
};
type Params = Parameters<typeof openBotTaskSql>[0];
/**
* The bot's latest task in this session that's still queued or working
* (with this title, on this computer, when given), if any, so the same
* work isn't started twice.
* work isn't started twice. The run asking (`exclude_job_id`) is never its
* own obstacle.
*/
export default async function grabOpenBotTask({ bot_id, session_id, title, computer_id }: Params) {
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
${computer_id ? `AND computer_id = ?` : ""}
ORDER BY id DESC LIMIT 1`,
values: [
bot_id,
session_id,
...(title != undefined ? [title] : []),
...(computer_id ? [Number(computer_id)] : []),
],
});
export default async function grabOpenBotTask(params: Params) {
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>(openBotTaskSql(params));
return res.payload?.[0] || null;
}
@@ -0,0 +1,60 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
bot_id: number | string;
/**
* The tracker task being handed over: one run of it at a time, whichever
* session it opened.
*/
tracker_task_id?: number | string | null;
/**
* A new brief's title and the conversation it was handed over from: the
* same work handed over twice from there.
*/
title?: string;
requested_by_session_id?: number | string | null;
};
/**
* The bot's open run of work already handed to it, if any. Every started
* hand-over opens a session of its own, so the per-session check
* (`grabOpenBotTask`) would never see the first one: this reads every
* session of the user's with that bot.
*/
export default async function grabOpenHandOverRun({
user_id,
bot_id,
tracker_task_id,
title,
requested_by_session_id,
}: Params) {
const task_id = Number(tracker_task_id) || 0;
const from = Number(requested_by_session_id) || 0;
if (!task_id && !(title && from)) return null;
const match = [
task_id ? `json_extract(COALESCE(params, '{}'), '$.tracker_task_id') = ?` : "",
title && from ? `(requested_by_session_id = ? AND lower(trim(title)) = lower(trim(?)))` : "",
]
.filter(Boolean)
.join(" OR ");
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND kind = 'task' AND status IN ('pending', 'processing')
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ?)
AND (${match})
ORDER BY id DESC LIMIT 1`,
values: [
Number(bot_id),
Number(user_id),
Number(bot_id),
...(task_id ? [task_id] : []),
...(title && from ? [from, title] : []),
],
});
return res.payload?.[0] || null;
}
@@ -16,16 +16,16 @@ type Params = {
* The face a bot should show one user while other jobs for them are
* still running: thinking while a reply runs (it's short, and its chat
* needs the row), else working on a task (in its workspace, if it runs in
* one). Null when none is running. Work in a crew request's hidden session
* one), with the workspace of that job's conversation. Null when none is running. Work in a crew request's hidden session
* or a silent hook's thread never counts: it shows there, never on the face.
*/
export default async function grabRunningBotJobFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
}: Params): Promise<{ face: BotFace; status_line: string; workspace_id: number | null } | null> {
const jobs = (
await BunSQLite.sql<{ kind: string; workspace_name: string | null }>({
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
await BunSQLite.sql<{ kind: string; workspace_id: number | null; workspace_name: string | null }>({
sql: `SELECT q.kind, q.workspace_id, w.name AS workspace_name FROM bots_queue q
LEFT JOIN workspaces w ON w.id = q.workspace_id
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
@@ -34,11 +34,21 @@ export default async function grabRunningBotJobFace({
})
).payload || [];
if (jobs.some((job) => job.kind == "reply")) return { face: "working", status_line: BotReplyJobTitle };
const reply = jobs.find((job) => job.kind == "reply");
if (reply) {
return { face: "working", status_line: BotReplyJobTitle, workspace_id: Number(reply.workspace_id) || null };
}
const task = jobs.find((job) => job.kind == "task");
if (task) return { face: "working", status_line: taskStatusLine({ workspace_name: task.workspace_name }) };
if (task) {
return {
face: "working",
status_line: taskStatusLine({ workspace_name: task.workspace_name }),
workspace_id: Number(task.workspace_id) || null,
};
}
return null;
}
@@ -116,6 +116,7 @@ export default async function notifyBotJobFailed({
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
workspace_id: job.workspace_id || null,
})
: null;
@@ -0,0 +1,60 @@
import { Database } from "bun:sqlite";
import { beforeEach, describe, expect, test } from "bun:test";
import openBotTaskSql from "./open-bot-task-sql";
const db = new Database(":memory:");
beforeEach(() => {
db.run(`CREATE TABLE IF NOT EXISTS bots_queue (
id INTEGER PRIMARY KEY,
status TEXT,
kind TEXT,
bot_id INTEGER,
session_id INTEGER,
computer_id INTEGER,
title TEXT
)`);
db.run(`DELETE FROM bots_queue`);
});
function insert(row: { id: number; status: string; title?: string; computer_id?: number }) {
db.run(
`INSERT INTO bots_queue (id, status, kind, bot_id, session_id, computer_id, title) VALUES (?, ?, 'task', 3, 95, ?, ?)`,
[row.id, row.status, row.computer_id ?? 1, row.title ?? "Fix baseline"],
);
}
function found(params: Partial<Parameters<typeof openBotTaskSql>[0]>) {
const query = openBotTaskSql({ bot_id: 3, session_id: 95, ...params });
return (db.query(query.sql).all(...query.values) as { id: number }[]).map((row) => row.id);
}
describe("openBotTaskSql", () => {
test("finds the open run on the computer", () => {
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1 })).toEqual([680]);
});
test("a task run handing work on is not its own obstacle (jobs 680, 700)", () => {
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([]);
expect(found({ title: "Fix baseline", exclude_job_id: 680 })).toEqual([]);
});
test("another open run still counts when the asking run is left out", () => {
insert({ id: 679, status: "pending" });
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([679]);
});
test("finished runs and other computers never count", () => {
insert({ id: 1, status: "completed" });
insert({ id: 2, status: "processing", computer_id: 2 });
expect(found({ computer_id: 1 })).toEqual([]);
});
});
@@ -0,0 +1,45 @@
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* Only a task with this title. Without it, any open task.
*/
title?: string;
/**
* Only a task on this computer.
*/
computer_id?: number | string | null;
/**
* The run asking: a task run handing its work on is not the open run
* that work would wait behind. Without it, a task report's `send_reply`
* with `work` was refused against its own job (jobs 680 and 700), and a
* finished report was thrown away.
*/
exclude_job_id?: number | string | null;
};
/**
* The bot's latest task in this session that's still queued or working
* (with this title, on this computer, when given), leaving out the run
* that asks.
*/
export default function openBotTaskSql({ bot_id, session_id, title, computer_id, exclude_job_id }: Params) {
const exclude = Number(exclude_job_id) || 0;
return {
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
${computer_id ? `AND computer_id = ?` : ""}
${exclude ? `AND id != ?` : ""}
ORDER BY id DESC LIMIT 1`,
values: [
bot_id,
session_id,
...(title != undefined ? [title] : []),
...(computer_id ? [Number(computer_id)] : []),
...(exclude ? [exclude] : []),
],
};
}
@@ -7,6 +7,8 @@ import type {
import insertBotMessage from "../bots/insert-bot-message";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import { AskStages } from "@/src/dict/ask-dict";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -34,6 +36,12 @@ export default async function relayJobToRequester({ job, text, failed, task_ids
return null;
}
/**
* A hand-over's run is its request's answer: `onAskJobEnded` reports it
* back (and wakes the bot that handed it over), so it isn't told twice.
*/
if (parseJobJson({ text: job.params })?.stage == AskStages.answer) return null;
const worker = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOTS>({
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
@@ -8,15 +8,20 @@ type Params = {
/**
* A bot's face and status line as one user sees it: idle when it has
* none for them.
* none for them, and the workspace of the conversation that set it
* (`face_workspace_id`, null for its own chat).
*/
export default async function grabBotFace({ bot_id, user_id }: Params) {
const row = (
await BunSQLite.sql<{ face: BotFace; status_line: string }>({
sql: `SELECT face, status_line FROM bot_user_faces WHERE bot_id = ? AND user_id = ? LIMIT 1`,
await BunSQLite.sql<{ face: BotFace; status_line: string; workspace_id: number | null }>({
sql: `SELECT face, status_line, workspace_id FROM bot_user_faces WHERE bot_id = ? AND user_id = ? LIMIT 1`,
values: [bot_id, user_id],
})
).payload?.[0];
return { face: (row?.face || "idle") as BotFace, status_line: row?.status_line || "" };
return {
face: (row?.face || "idle") as BotFace,
status_line: row?.status_line || "",
face_workspace_id: Number(row?.workspace_id) || null,
};
}
@@ -0,0 +1,25 @@
import BunSQLite from "@moduletrace/bun-sqlite";
/**
* Faces set before `bot_user_faces.workspace_id` existed say nothing of the
* chat they came from, so a bot that needed the user in a workspace linked
* to its own chat from the coordinator's Crew tab. A face that needs the
* user or shows work takes the workspace of that bot's latest job for that
* user. Faces set since then carry their own; one whose latest job was in
* the bot's own chat stays null, so running it again changes nothing.
*/
export default async function migrateFaceWorkspaces() {
const res = await BunSQLite.sql({
sql: `UPDATE bot_user_faces SET workspace_id = (
SELECT q.workspace_id FROM bots_queue q
JOIN bot_sessions s ON s.id = q.session_id
WHERE q.bot_id = bot_user_faces.bot_id AND s.user_id = bot_user_faces.user_id
ORDER BY q.id DESC LIMIT 1
)
WHERE workspace_id IS NULL AND face IN ('needs-you', 'working')`,
});
if (!res.success) {
throw new Error(`Couldn't place the existing bot faces: ${res.error}`);
}
}
+15 -6
View File
@@ -9,6 +9,12 @@ type Params = {
user_id: number | string;
face: BotFace;
status_line?: string;
/**
* The workspace of the conversation the job is in, null for the bot's
* own chat: where the coordinator's Crew list links a bot that needs
* the user or is working.
*/
workspace_id?: number | string | null;
};
export type BotFaceChange = {
@@ -16,27 +22,30 @@ export type BotFaceChange = {
user_id: number;
face: BotFace;
status_line: string;
workspace_id: number | null;
};
/**
* Sets a bot's face (its status) and status line as one user sees it
* (`bot_user_faces`). Other users keep their own. Callers must check the
* bot first.
* bot first. A face set without `workspace_id` reads as the bot's own chat.
*/
export default async function setBotFace({
bot_id,
user_id,
face,
status_line = "",
workspace_id = null,
}: Params): Promise<BotFaceChange> {
const now = Date.now();
const place = Number(workspace_id) || null;
await BunSQLite.sql({
sql: `INSERT INTO bot_user_faces (created_at, updated_at, bot_id, user_id, face, status_line)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET face = excluded.face, status_line = excluded.status_line, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, face, status_line],
sql: `INSERT INTO bot_user_faces (created_at, updated_at, bot_id, user_id, face, status_line, workspace_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET face = excluded.face, status_line = excluded.status_line, workspace_id = excluded.workspace_id, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, face, status_line, place],
});
return { id: Number(bot_id), user_id: Number(user_id), face, status_line };
return { id: Number(bot_id), user_id: Number(user_id), face, status_line, workspace_id: place };
}
@@ -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,
};
@@ -4,9 +4,8 @@ import AppError from "@/src/utils/app-error";
import handOverPlace from "@/src/utils/hand-over-place";
import grabUserConversation from "../bot-sessions/grab-user-conversation";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabOpenBotTask from "../bots-queue/grab-open-bot-task";
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import startHandOverRun from "../asks/start-hand-over-run";
import grabOpenHandOverRun from "../bots-queue/grab-open-hand-over-run";
import grabBotById from "../bots/grab-bot-by-id";
import insertBotMessage from "../bots/insert-bot-message";
import grabBotComputers from "../computers/grab-bot-computers";
@@ -64,6 +63,10 @@ export type HandedOverTask = {
* The job doing the work; null when it wasn't started.
*/
job_id: number | string | null;
/**
* The session the run opened; null when it wasn't started.
*/
session_id: number | null;
bot_name: string;
workspace_id: number | null;
/**
@@ -79,9 +82,13 @@ export type HandedOverTask = {
* it to be worked, so by default it only moves: the task goes to the new
* bot's list as to do, no job is queued and the notice says so. With
* `start` true (the user asked for the work to begin now) the task goes to
* doing, its log says who handed it over, and a job is queued in the new
* bot's conversation with the task's brief and `params.tracker_task_id`, so
* the bot moves this same task along and the job's end is noted on it.
* doing, its log says who handed it over, and a job is queued with the
* task's brief and `params.tracker_task_id`, so the bot moves this same task
* along and the job's end is noted on it. That run gets a session of its own
* (`startHandOverRun`), as a crew request's answer does: handed over by a
* bot, its report goes back to that bot and the run can send it a word on
* the way. A task that only moves leaves its notice in the conversation the
* new bot is in, since nothing runs yet.
*/
export default async function handOverTask({
user_id,
@@ -122,13 +129,12 @@ export default async function handOverTask({
* The user must reach the bot there: its own chat, or the workspace.
*/
const conversation = await grabUserConversation({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const title = (task.title || "Task").slice(0, 80);
const open = start ? await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title }) : null;
const open = start ? await grabOpenHandOverRun({ user_id, bot_id: bot.id, tracker_task_id: task.id }) : null;
if (open) {
throw new AppError(
`${bot.name} already has "${title}" ${open.status == "pending" ? "queued" : "under way"} (job #${open.id}).`,
`${bot.name} already has "${title}" ${open.status == "pending" ? "queued" : "under way"} (run #${open.id}).`,
);
}
@@ -147,28 +153,22 @@ export default async function handOverTask({
.filter(Boolean)
.join("\n\n");
/**
* When the hand-over comes from a crew request being answered, the run
* carries the ask_id too, so its result goes back to the bot that asked.
*/
const ask =
start && requested_by_session_id
? await grabOpenAskBySession({ session_id: requested_by_session_id, user_id })
: null;
const job_id = start
? await enqueueBotJob({
const run = start
? await startHandOverRun({
user_id,
bot_id: bot.id,
session_id: Number(session.id),
bot,
workspace_id: run_workspace_id,
title,
instructions: brief,
params: { tracker_task_id: Number(task.id), ...(ask?.id ? { ask_id: Number(ask.id) } : {}) },
computer_id: computers[0]?.id || undefined,
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
brief,
tracker_task_id: Number(task.id),
computer_id: computers[0]?.id || null,
requested_by_bot_id,
requested_by_session_id,
notice: `${handed_by} handed me task #${task.id}: **${title}**`,
task_ids: [Number(task.id)],
})
: null;
const job_id = run?.job_id ?? null;
const status = start ? "doing" : "todo";
await updateTask({
@@ -185,20 +185,25 @@ export default async function handOverTask({
bot_id: requested_by_bot_id || null,
});
await pushBotNotice({
bot_id: bot.id,
message: await insertBotMessage({
if (!start) {
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
await pushBotNotice({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**${start ? "" : ". It's on my list; I'll start when you say."}`,
task_ids: [Number(task.id)],
}),
});
message: await insertBotMessage({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**. It's on my list; I'll start when you say.`,
task_ids: [Number(task.id)],
}),
});
}
return {
task: { ...moved, status },
job_id,
session_id: run?.session_id ?? null,
bot_name: conversation.bot.name || bot.name || "The bot",
workspace_id: run_workspace_id,
joined,
@@ -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);
}

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