Compare commits

...
29 Commits
Author SHA1 Message Date
tben a5dbde1da7 Release 0.27.8
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-22 18:04:53 +01:00
tben 51747c069f Let a connector given to a workspace reach every account connected for it
A workspace's connector gave every member its tools but no account, so a
member with no sign-in of their own was told nothing was connected while
the super admin's account sat unused. Account reach now follows the
workspace grant, whoever connected the account, and the run names them.

The Composio listing also filtered on `user_id`, which it ignores, so one
person's sync adopted the whole project's accounts: it takes `user_ids`.
2026-11-22 18:04:48 +01:00
tben 3f551e7352 Release 0.27.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 17:24:14 +01:00
tben fdd1e8a757 Let a Composio toolkit sign in with its own scheme, and stop adopting a replaced app's leftovers 2026-11-22 17:20:41 +01:00
tben 60022d8220 Split the bot panel into Settings, Memory and Tools
The drawer held only the bot's profile. Its memory and everything it works
with now have tabs of their own, the last one sharing the composer's own
list of tools and knowledgebases.

- Memory: core memory, plus the workspace's memory for the bot when the
  conversation is in one. New `update-bot-memory` route; the workspace
  request's fields are optional so a memory-only save cannot blank the
  instructions there.
- Tools: computer, tools/skills/MCPs with connectors and browsers, and
  knowledgebases.
2026-11-22 16:49:44 +01:00
tben 4837bf325e Reconnect the row the request names, and check a cached session's account 2026-11-22 16:28:36 +01:00
tben 383ef82400 Release 0.27.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 16:00:46 +01:00
tben 7e1135beb1 Start a folder at the top and never show the last one's entries
A folder opened from the popup kept the previous folder's rows, trail and name until its own listing arrived, and it kept that listing's scroll offset, so a folder opened part-way down or at its bottom. The listing is now handed back only for the volume and path it belongs to, shows a loading line meanwhile, and is keyed by folder and search so each one starts at the top. The trail is built from the path at once instead of waiting for the listing, and the file preview header puts the size and full path on their own line so a phone no longer squeezes them into a character column.
2026-11-22 15:56:19 +01:00
tben b30d6118fe Transcribe on Alibaba's native route, and card the composer error
The Token Plan host has no /audio/transcriptions: its ASR model is served at the DashScope host root, with the audio inline as a data URL and the model's own format and language hints. Async-only slugs (filetrans, paraformer) are refused with the synchronous model to pick instead. The image helpers that recognise those hosts move to one shared module.

A failed send, or a failed dictation, now shows as a dismissible card under the composer in the error or warning tint rather than a line of grey text.
2026-11-22 15:51:38 +01:00
tben 35b9808d97 Close a phone panel with the swipe back off its edge
An open panel now answers the swipe that undoes the one which opened it: a left drag closes the rail's drawer, a right drag the bot panel, through a panel-local listener sharing swipe-gesture.ts with the page swipes. SidePanel carries the bot panel's phone width (420px, at most 92vw) for both, and field detection moves to touch-in-field.ts so both hooks ignore a touch in a field.
2026-11-22 15:36:07 +01:00
tben 7460163287 Keep suggested next steps inside their chips on a phone 2026-11-22 15:30:41 +01:00
tben da6a73f740 Release 0.27.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 12:35:22 +01:00
tben 2afe35954c Size runs to the model's own window, and stop a run reading notes instead of answers
The working context was 70% of the model's window, and a model whose
catalog never declared one got 70% of a guessed 131,072: a chat on a
custom provider was told it had 91,750 tokens, then had every tool result
trimmed to a bare note, including a 14-character shell answer, and spent
its remaining steps reading nothing.

- workingContextTokens: the declared window less the room the answer
  needs (max_output_tokens, else a tenth clamped to 8,000-64,000),
  capped by grabContextBudgetTokens when an install sets one.
- An undeclared window is assumed to be 1,000,000, and the guess is not
  silent: the picker marks such a model and the Models page says what a
  run works to. A provider that refuses the prompt for size stops the
  run with its own limit (fatal: no fallback, no rest, no retry).
- fitTranscriptToContext: a result under 2,000 characters is never cut,
  a trimmed one keeps its start and its end, and the newest turn's
  results are cut last. over_budget says whether the static prompt or
  the request is over; the static case stops the run at once instead of
  trimming every turn.
- Built-in tools are deferred by family (groupTools, ToolGroups) on a
  model short of window; load_tools takes a family name or a prefix.
  Wrap-up tools, closing tools and load_tools are never deferred.
- Usage reports what the app's own prompt and tools took before the
  conversation did.
2026-11-22 12:35:17 +01:00
tben 5ea9b608be Refuse a connector account the provider no longer has, and stop adopting duplicates
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 10:56:35 +01:00
tben 7c92d0b4be Release 0.27.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 10:27:05 +01:00
tben 319eb74a23 Give a runner that exits at once a moment to be seen 2026-11-22 10:26:10 +01:00
tben c745f58991 Overlap the connector icons on the tools button 2026-11-22 10:26:10 +01:00
tben b046e90958 Show connector apps on the tools button 2026-11-22 10:20:49 +01:00
tben 4a02035f33 Reconnect an account in place, and keep its card readable 2026-11-22 10:13:09 +01:00
tben f8a7b0f2e7 Keep every connector account a second sign-in adds
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 09:32:54 +01:00
tben fdaa5649ef Release 0.27.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-22 08:35:27 +01:00
tben 94b999aef1 Take twui 0.1.15 and keep lodash out of the form hook
twui 0.1.15 stops importing lodash for omit and merge, so a page that
renders a twui component no longer carries the library, and the form hook
takes a shallow copy instead of cloneDeep: EJSON serialises it anyway, and
lodash was putting the conversation page 8 KB over its bundle budget.
2026-11-22 08:35:23 +01:00
tben 70fd37e707 Take twui 0.1.14 and one copy of tailwind-merge
twui 0.1.14 depends on tailwind-merge 3.7.0, so the app moves to the same
version and the lock keeps a single copy instead of one nested under twui.
2026-11-22 08:21:47 +01:00
tben 1ae360cffd Expand a connector's cut result instead of reading it as the total
Composio's hosted MCP router answers a large tool result with a preview:
data becomes data_preview holding two of the ten messages, a "...8 more
items" marker, and next_steps telling the run to parse a saved response the
app never receives (ComposioHQ/composio#5025). A Gmail fetch of a primary
inbox therefore reached the model as "only 2 emails": a reply told the user
that, and then spent turns looking for the file.

A preview is now recognised wherever it sits in the answer (preview-result),
measured by the biggest cut in it, and rewritten to say that 2 of 10 items
are here and the other 8 were cut, with structure_info, next_steps and
log_id dropped. A connector tool asks the provider's REST API again for the
same tool and arguments, which returns the whole result, and falls back to
that note when it can't (expand-preview-result). ConnectorsNote tells a run
that a preview is never the total and never an empty result.
2026-11-22 08:21:43 +01:00
tben 85af8ac4e9 Focus an ask_user card's typed answer as soon as it opens
An "Other" box on a question card is the one thing waiting on the user, so
it takes the cursor instead of needing a click first.
2026-11-22 08:01:29 +01:00
tben 9202e80331 Keep passwords out of what a bot reads, and fill env templates in tool arguments
A coordinator leaked a mailbox password and then told its user an env was
empty. The value came from Chrome's saved-login vault in the browser
profile, which the run could read and printed in a snapshot; the env it
wanted was set all along, and the {{env.KEY}} it was told to write arrived
as literal text in a custom tool's arguments.

A password-named field's value, and that value inside its container's
accessible label, now become [hidden] in every browser tool result
(maskPasswordFieldValues), and a reply, an ask_user card, a suggested step,
a send_message and a task report are redacted through it plus redactSecrets
before they are stored. The profile keeps no saved logins: pruneProfileSecrets
removes the login and autofill stores at every Chrome start, and the managed
policy turns off the password manager, autofill and browser sign-in (site
cookies stay, so sessions stay signed in). SecretsNote says [KEY] means set
and hidden, never empty, and that a page credential is never repeated.

A custom tool's arguments are now filled too (fillEnvArgs on
build-custom-tool, with arg_envs = the computer's envs and the run's, the
run's winning): http and script tools get the value, a prompt tool the
[KEY] marker, and an unset key throws the same Settings > Environment
message as a config template. A filled value is redacted from the result.

The computer image is 1.4.5 (the agent changed), so AppData.ComputerImage
moves with it.
2026-11-22 08:01:24 +01:00
tben b088050577 Add connectors: apps each person signs in to, given to bots and workspaces 2026-11-22 07:32:39 +01:00
tben a2149e2397 Paste and copy extensions between installs from their JSON
An Add form's Paste JSON button opens a modal that reads one item's JSON, a whole export or a raw config, fills the form and says what the export left out and which documents come with it.

Each existing row's menu copies that item's export-shaped JSON, and a pasted knowledgebase's documents are written when it is saved.
2026-11-21 20:52:40 +01:00
tben 71bb4d517f Check the CI run after a release, not just before it 2026-11-21 20:22:47 +01:00
249 changed files with 14239 additions and 505 deletions
+16 -10
View File
File diff suppressed because one or more lines are too long
+4 -6
View File
@@ -9,7 +9,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.13",
"@moduletrace/twui": "^0.1.15",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -39,7 +39,7 @@
"remark-gfm": "^4.0.1",
"sanitize-html": "^2.18.1",
"sharp": "^0.35.3",
"tailwind-merge": "^3.6.0",
"tailwind-merge": "^3.7.0",
"turndown": "^7.2.4",
"unpdf": "^1.8.0",
"use-sync-external-store": "file:./packages/use-sync-external-store-esm",
@@ -280,7 +280,7 @@
"@moduletrace/bunext": ["@moduletrace/[email protected]", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.5/bunext-1.3.5.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-Es59Dvq3/eF726+SOHPiKtlJ87UFmyJZI4gpeciW/fA/3ZwOWws2Mm3oD6eZnOj9BP/zlBKOWA9DPTl35IP3lg=="],
"@moduletrace/twui": ["@moduletrace/[email protected]3", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.13/twui-0.1.13.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-5Upw848jq0ZQaDBdBpQEmoU738D/koIaUHV4EI6BkhnQYzBlRRidnZSW/BiAREGIbaac1VKyb6rOUKOqTq5bmQ=="],
"@moduletrace/twui": ["@moduletrace/[email protected]5", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.15/twui-0.1.15.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-PDduBp/P/ryLZ+SQ+ovu9E0iACIejXmpzMf9TdJKvErLQznYVDkJzqWXKFzeRL+Fv2g09eFwNQEFCEvqPe4Lwg=="],
"@next/mdx": ["@next/[email protected]", "", { "dependencies": { "source-map": "^0.7.0" }, "peerDependencies": { "@mdx-js/loader": ">=0.15.0", "@mdx-js/react": ">=0.15.0" }, "optionalPeers": ["@mdx-js/loader", "@mdx-js/react"] }, "sha512-Vpfuf928ACvx4AOdDXWx/cj13Ak6xlvMn3QCkjvfQMmLnQWCesQTeY01CPDbIyZvjY+NOwP7bvbvJ2ghkj/3GA=="],
@@ -1498,7 +1498,7 @@
"supports-preserve-symlinks-flag": ["[email protected]", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
"tailwind-merge": ["tailwind-merge@3.6.0", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
"tailwind-merge": ["tailwind-merge@3.7.0", "", {}, "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA=="],
"tailwindcss": ["[email protected]", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],
@@ -1608,8 +1608,6 @@
"@moduletrace/bunext/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"@moduletrace/twui/tailwind-merge": ["[email protected]", "", {}, "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA=="],
"@tailwindcss/node/source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],
@@ -0,0 +1,82 @@
import { afterEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pruneProfileSecrets from "./prune-profile-secrets";
/**
* A profile is mounted so a computer keeps its cookies and extensions, and
* this runs at every start: a file wrongly listed here logs the user out of
* every site, one wrongly left out keeps a saved password within a bot's
* reach.
*/
const dirs: string[] = [];
function profile() {
const dir = mkdtempSync(path.join(tmpdir(), "cobble-profile-secrets-"));
dirs.push(dir);
return dir;
}
function write({ root, relative }: { root: string; relative: string }) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, "x");
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe("pruneProfileSecrets", () => {
test("removes the saved-password stores of every profile", () => {
const root = profile();
write({ root, relative: "Default/Login Data" });
write({ root, relative: "Default/Login Data-journal" });
write({ root, relative: "Default/Login Data For Account" });
write({ root, relative: "Default/Account Web Data" });
write({ root, relative: "Default/Web Data" });
write({ root, relative: "Profile 1/Login Data" });
expect(pruneProfileSecrets({ profile_dir: root })).toBe(6);
expect(existsSync(path.join(root, "Default/Login Data"))).toBe(false);
expect(existsSync(path.join(root, "Default/Login Data For Account"))).toBe(false);
expect(existsSync(path.join(root, "Default/Account Web Data"))).toBe(false);
expect(existsSync(path.join(root, "Default/Web Data"))).toBe(false);
expect(existsSync(path.join(root, "Profile 1/Login Data"))).toBe(false);
});
test("keeps what signs the user in to their sites", () => {
const root = profile();
write({ root, relative: "Default/Cookies" });
write({ root, relative: "Default/Cookies-journal" });
write({ root, relative: "Local State" });
write({ root, relative: "Default/History" });
write({ root, relative: "Default/Preferences" });
write({ root, relative: "Default/Extensions/abc/1.0/manifest.json" });
expect(pruneProfileSecrets({ profile_dir: root })).toBe(0);
expect(existsSync(path.join(root, "Default/Cookies"))).toBe(true);
expect(existsSync(path.join(root, "Local State"))).toBe(true);
expect(existsSync(path.join(root, "Default/History"))).toBe(true);
expect(existsSync(path.join(root, "Default/Extensions/abc/1.0/manifest.json"))).toBe(true);
});
test("leaves a folder that isn't a profile alone", () => {
const root = profile();
write({ root, relative: "Crashpad/metrics/Login Data" });
expect(pruneProfileSecrets({ profile_dir: root })).toBe(0);
expect(existsSync(path.join(root, "Crashpad/metrics/Login Data"))).toBe(true);
});
test("counts nothing when there is no profile yet", () => {
expect(pruneProfileSecrets({ profile_dir: path.join(profile(), "missing") })).toBe(0);
});
});
+84
View File
@@ -0,0 +1,84 @@
import { readdirSync, rmSync, statSync } from "node:fs";
import path from "node:path";
import log from "./log";
/**
* Where a browser profile keeps the passwords it has saved, in the profile
* folder and in each profile's own folder (`Default`, `Profile 1`, ...):
* the login database, its journal and backup, plus the web data file that
* holds the account-wide copies Chrome syncs. Deleting these at every start
* is what keeps a password out of a bot's reach: a browser here holds the
* user's own logins (Gmail among them) as cookies, and it never needs a
* saved password for that.
*/
const SecretProfileFiles = [
"Login Data",
"Login Data For Account",
"Account Web Data",
"Web Data",
];
/**
* The side files SQLite leaves beside a database.
*/
const SideSuffixes = ["-journal", "-wal", "-shm", ""];
/**
* Deletes the saved-password stores from a browser profile.
*
* A page's login form can be filled from here by Chrome itself, and the
* result reaches a model as page text (a snapshot reported a mailbox
* password in the clear, and it was repeated in a message and a question).
* Site cookies, history, extensions and site permissions are not touched:
* deleting these files signs the browser out of no site.
*
* Only called while no browser runs (a file deleted under a live Chrome is
* still open, and Chrome writes it back when it exits). Returns how many
* files it removed.
*/
export default function pruneProfileSecrets({ profile_dir }: { profile_dir: string }) {
let removed = 0;
for (const profile of safeReadDir({ target: profile_dir })) {
if (!/^(Default|Profile \d+|System Profile)$/.test(profile)) continue;
for (const name of SecretProfileFiles) {
for (const suffix of SideSuffixes) {
const target = path.join(profile_dir, profile, `${name}${suffix}`);
if (!isFile({ target })) continue;
try {
rmSync(target, { force: true });
removed++;
} catch {
/**
* One that can't be removed (a permission problem) is
* left for the next start; the browser comes up either
* way.
*/
}
}
}
}
if (removed > 0) log({ name: "browser", message: `removed ${removed} saved login file${removed == 1 ? "" : "s"}` });
return removed;
}
function isFile({ target }: { target: string }) {
try {
return statSync(target).isFile();
} catch {
return false;
}
}
function safeReadDir({ target }: { target: string }) {
try {
return readdirSync(target);
} catch {
return [];
}
}
+5 -1
View File
@@ -9,6 +9,7 @@ import findBrowserBinary from "./find-browser-binary";
import isPortAnswering from "./is-port-answering";
import log from "./log";
import pruneProfileCache from "./prune-profile-cache";
import pruneProfileSecrets from "./prune-profile-secrets";
import superviseProcess, { type Supervised } from "./supervise-process";
import userEnv from "./user-env";
import waitUntil from "./wait-until";
@@ -95,9 +96,12 @@ export default async function startServices({ parking }: { parking: BrowserParki
clearProfileLocks({ profile_dir: AgentConfig.ProfileDir });
/**
* No browser runs now (this is its start): the caches it built
* last time are free to go, so the profile stops growing.
* last time are free to go, so the profile stops growing, and
* so are the passwords it saved, which a bot must never read
* off a page (`prune-profile-secrets`).
*/
pruneProfileCache({ profile_dir: AgentConfig.ProfileDir });
pruneProfileSecrets({ profile_dir: AgentConfig.ProfileDir });
return browserArgs({
profile_dir: AgentConfig.ProfileDir,
+538
View File
File diff suppressed because it is too large Load Diff
+314 -1
View File
@@ -56,6 +56,15 @@ export const BunSQLiteTables = [
"mcp_servers",
"browsers",
"browser_access",
"connector_connections",
"connectors",
"bot_connectors",
"workspace_connectors",
"connector_accounts",
"connector_account_workspaces",
"connector_account_bots",
"connector_sessions",
"connector_requests",
"custom_tools",
"skills",
"extension_proposals",
@@ -2326,6 +2335,310 @@ export type BUN_SQLITE_COBBLE_BROWSER_ACCESS = {
is_default?: 0 | 1 | "";
}
export type BUN_SQLITE_COBBLE_CONNECTOR_CONNECTIONS = {
/**
* 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 | "";
/**
* Shown, e.g. Composio Work. Names the connection's apps and distinguishes two of the same provider
*/
name?: string;
/**
* Which provider (Composio, ...). Several connections may use the same one
*/
provider?: "composio" | "";
/**
* The provider's key for this connection, encrypted: a provider project or org key, so two connections are two separate accounts (Composio Personal, Composio Work). Never read out of the database except to build a provider adapter
*/
api_key?: string;
/**
* untested before the first sync, ready when the provider listed its apps, error when it refused
*/
status?: "untested" | "ready" | "error" | "";
/**
* Why the last sync failed, secrets blanked out
*/
last_error?: string;
/**
* Unix ms of the last app listing
*/
last_synced_at?: number | "";
/**
* The super admin who connected it, and the person to tell when the provider refuses its key
*/
user_id?: number | "";
}
export type BUN_SQLITE_COBBLE_CONNECTORS = {
/**
* 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 | "";
/**
* Who hosts the app and its sign-in. Its adapter lives under src/harness/connectors/providers/
*/
provider?: "composio" | "";
/**
* Which connector_connections row this app was read from. A connection's apps are its own, so two Composio connections each have their own Gmail
*/
connection_id?: number | "";
/**
* The provider's own app id, e.g. gmail. One row per connection and app
*/
app?: string;
/**
* Shown, e.g. Gmail
*/
name?: string;
/**
* Prefixes its tools' names (<slug>__<tool>). Unique on the install
*/
slug?: string;
/**
* What the app is for, so a user knows whether to attach it
*/
description?: string;
/**
* The app's logo URL as the provider lists it, for the app list
*/
logo?: string;
/**
* The provider's sign-in config to start a connect with, when it keeps more than one per app
*/
auth_config_id?: string;
/**
* What signing in asks for, as the provider lists it
*/
scopes?: string;
/**
* The app's tools as last listed ([{name, description, input_schema}]). Runs build their tools from it and call the provider on demand
*/
tools_cache?: string;
/**
* Tool names (the provider's own) bots don't get
*/
excluded_tools?: string;
/**
* 1 makes it global: every run of every user reaches it. Super admins only. Unlike an extension's all_bots, which only seeds new bots, this is live reach
*/
all_bots?: 0 | 1 | "";
enabled?: 0 | 1 | "";
status?: "untested" | "ready" | "error" | "";
last_error?: string;
/**
* Unix ms of the last tool listing
*/
last_synced_at?: number | "";
/**
* Who added it, and the person to tell when the provider refuses its key. Never reach: a connector reaches a run through the three tiers
*/
user_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_CONNECTORS = {
/**
* 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 | "";
connector_id?: number | "";
}
export type BUN_SQLITE_COBBLE_WORKSPACE_CONNECTORS = {
/**
* 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 | "";
connector_id?: number | "";
}
export type BUN_SQLITE_COBBLE_CONNECTOR_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 | "";
connector_id?: number | "";
/**
* The owner. Not a foreign key: deleting a user deletes these explicitly
*/
user_id?: number | "";
/**
* What the user calls it, e.g. Work Gmail. Shown to the bot, which is how it knows which account to use
*/
label?: string;
/**
* The account's part of its tools' names when the user has more than one for the app (gmail-work__...). Unique per connector and user
*/
slug?: string;
/**
* The provider's own id for it (Composio's connected_account_id)
*/
provider_account_id?: string;
status?: "pending" | "connected" | "expired" | "revoked" | "";
/**
* 0 or 1, at most one per connector and user: the account a connect card offers first
*/
is_default?: 0 | 1 | "";
/**
* 0 or 1: every run may use this account, whoever it belongs to. Off by default, so an account is its owner's alone until it is given out
*/
all_bots?: 0 | 1 | "";
connected_at?: number | "";
last_checked_at?: number | "";
last_error?: string;
}
export type BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNT_WORKSPACES = {
/**
* 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 | "";
account_id?: number | "";
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNT_BOTS = {
/**
* 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 | "";
account_id?: number | "";
bot_id?: number | "";
}
export type BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS = {
/**
* 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 | "";
connector_id?: number | "";
user_id?: number | "";
provider_account_id?: string;
/**
* The provider's session id, when it gives one
*/
session_id?: string;
mcp_url?: string;
/**
* Encrypted JSON of the headers that endpoint wants (a provider key). Never a value a run or a page may read
*/
headers?: string;
/**
* Unix ms. Past it the row is replaced, never reused
*/
expires_at?: number | "";
}
export type BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS = {
/**
* 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 | "";
connector_id?: number | "";
user_id?: number | "";
/**
* The bot whose conversation raised it, for the message that wakes it when the link is done. Not a foreign key
*/
bot_id?: number | "";
/**
* The conversation the card sits in, which the wake message goes to. Not a foreign key
*/
bot_session_id?: number | "";
/**
* The account this link reconnects, 0 for a new one. A finished sign-in updates that row in place, so a dead account keeps its label and namespace
*/
account_id?: number | "";
/**
* The account label the user typed, or the one the card suggested
*/
label?: string;
/**
* The provider's connect link. A flow link for this user only, never put in a message's text
*/
url?: string;
provider_account_id?: string;
status?: "pending" | "connected" | "expired" | "cancelled" | "";
expires_at?: number | "";
}
export type BUN_SQLITE_COBBLE_CUSTOM_TOOLS = {
/**
* The unique identifier of the record.
@@ -3186,4 +3499,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_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_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
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.26.0",
"version": "0.27.8",
"module": "index.ts",
"type": "module",
"private": true,
@@ -46,7 +46,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.13",
"@moduletrace/twui": "^0.1.15",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -76,7 +76,7 @@
"remark-gfm": "^4.0.1",
"sanitize-html": "^2.18.1",
"sharp": "^0.35.3",
"tailwind-merge": "^3.6.0",
"tailwind-merge": "^3.7.0",
"turndown": "^7.2.4",
"unpdf": "^1.8.0",
"use-sync-external-store": "file:./packages/use-sync-external-store-esm",
+11
View File
@@ -38,4 +38,15 @@ describe("composeEnvsNote", () => {
test("says so when nothing is set", () => {
expect(composeEnvsNote({ on_computer: [], tools_only: [], has_computer: false })).toContain("No envs are set");
});
test("says a custom tool fills {{env.KEY}} in its arguments", () => {
const note = composeEnvsNote({
on_computer: [{ key: "A", description: "" }],
tools_only: [{ key: "B", description: "" }],
has_computer: true,
});
expect(note).toContain("{{env.KEY}} in a custom tool's arguments");
expect(note).toContain("{{env.KEY}} in a custom tool's settings");
});
});
+3 -3
View File
@@ -50,12 +50,12 @@ export default function composeEnvsNote({ on_computer, tools_only, has_computer
}
return [
`# Your envs\n\nThese are already set for you here (keys and descriptions; you never see values). Don't ask the user for them, and don't call show_secret or run printenv to check them: this list is the check. A workspace, computer or install-wide env reaches every bot there the same way, so it never needs setting again per bot.`,
`# Your envs\n\nThese are already set for you here (keys and descriptions; you never see values). Don't ask the user for them, and don't call show_secret or run printenv to check them: this list is the check. A workspace, computer or install-wide env reaches every bot there the same way, so it never needs setting again per bot. Wherever a tool reads one, write {{env.KEY}}: the app fills the value in before the tool runs, and it never reaches you.`,
on_computer.length
? `On your computer, as $KEY in a task's shell and code (started with send_reply's work in a reply, or start_task inside a task run; search_computers doesn't load them):\n${list(on_computer)}`
? `On your computer, as $KEY in a task's shell and code (started with send_reply's work in a reply, or start_task inside a task run; search_computers doesn't load them), or as {{env.KEY}} in a custom tool's arguments:\n${list(on_computer)}`
: "",
tools_only.length
? `${has_computer ? "Only in tools" : "In tools"}, as {{env.KEY}}${has_computer ? " (not set on computers)" : ""}:\n${list(tools_only)}`
? `${has_computer ? "Only in tools" : "In tools"}, as {{env.KEY}} in a custom tool's settings and the arguments you send it${has_computer ? ", not set on computers" : ""}:\n${list(tools_only)}`
: "",
]
.filter(Boolean)
+57 -5
View File
@@ -9,6 +9,7 @@ import {
passedOnRequestNote,
SecretsNote,
SettingsNote,
ConnectorsNote,
GraphicsNote,
botFilesNote,
chatReplyNote,
@@ -44,10 +45,14 @@ import runTextLoop from "@/src/harness/text/run-text-loop";
import type { HarnessTool } from "@/src/harness/types";
import grabBotChatTools from "@/src/harness/tools/bot/grab-bot-chat-tools";
import gatePlanModeTools from "@/src/harness/tools/bot/plan-mode-tools";
import groupTools from "@/src/harness/tools/group-tools";
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes";
import openBotBrowsers from "@/src/harness/tools/browsers/open-bot-browsers";
import openBotConnectors from "@/src/harness/tools/connectors/open-bot-connectors";
import createConnectorRequest from "@/src/functions/backend/db/connectors/create-connector-request";
import connectRef from "@/src/utils/connect-ref";
import openBotExtensions from "@/src/harness/tools/extensions/open-bot-extensions";
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
@@ -64,6 +69,8 @@ import composeBrowsersNote from "./compose-browsers-note";
import composeComputersNote from "./compose-computers-note";
import composeEnvsNote from "./compose-envs-note";
import grabReachableEnvs from "@/src/functions/backend/db/envs/grab-reachable-envs";
import redactSecrets from "@/src/utils/redact-secrets";
import maskPasswordFieldValues from "@/src/utils/mask-password-field-values";
import grabSessionCarryOver from "./grab-session-carry-over";
import continueInNewSessionTool from "@/src/harness/tools/bot/continue-in-new-session-tool";
import searchPastSessionsTool from "@/src/harness/tools/bot/sessions/search-past-sessions-tool";
@@ -243,6 +250,16 @@ export default async function runBotReply({
computer_id: computers[0]?.id || null,
});
/**
* A password can reach a model by ways the app never sees, a page that
* had one filled in being the one that did (a snapshot reported the
* login form's value, and the bot put it in a question): what it sends
* out is read here, so a secret env's value and a password field's
* value never reach the user.
*/
const reply_secrets = [...envs.on_computer, ...envs.tools_only].filter((env) => env.secret);
const redact_reply = (text: string) => redactSecrets({ text: maskPasswordFieldValues({ text }), secrets: reply_secrets });
/**
* A summary that can't be written now (no model free) is left out
* rather than holding up the reply.
@@ -429,13 +446,41 @@ export default async function runBotReply({
signal,
});
/**
* The user's connected apps: one tool set per account, and, in a reply
* the user follows, the card that asks them to connect one they haven't.
*/
const connectors = await openBotConnectors({
user_id,
bot_id: bot.id,
workspace_id,
attended,
taken: [...tools, ...extensions.tools, ...browsers.tools].map((tool) => tool.name),
onMissingAccount: attended
? async ({ connector }) => {
const request = await createConnectorRequest({
user_id,
bot_id: bot.id,
session_id: Number(session_id),
connector,
});
const ref = connectRef({ id: request.id });
proposals.push(ref);
return `No account is connected to ${connector.name} yet, so this didn't run. The Connect card ${ref} is under your reply: tell the user in one sentence to connect it there, and ask them to say when they have.`;
}
: undefined,
signal,
});
/**
* The run's skills: one `load_skill` tool and the lines that name them.
*/
const skills = openBotSkills({
skills: extensions.skills,
shown_chars: await grabSkillBodyShownChars(),
taken: [...tools, ...extensions.tools, ...browsers.tools].map((tool) => tool.name),
taken: [...tools, ...extensions.tools, ...browsers.tools, ...connectors.tools].map((tool) => tool.name),
});
/**
@@ -445,7 +490,7 @@ export default async function runBotReply({
*/
const knowledge = openBotKnowledgebases({
knowledgebases: extensions.knowledgebases,
taken: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools].map((tool) => tool.name),
taken: [...tools, ...extensions.tools, ...browsers.tools, ...connectors.tools, ...skills.tools].map((tool) => tool.name),
});
const knowledge_context = await grabKnowledgebaseContext({
knowledgebases: extensions.knowledgebases,
@@ -493,7 +538,7 @@ export default async function runBotReply({
*/
const reply_tools: HarnessTool[] = [
...tools,
sendMessageTool({ bot_id: bot.id, session_id: Number(session_id), workspace_id }),
sendMessageTool({ bot_id: bot.id, session_id: Number(session_id), workspace_id, redact: redact_reply }),
...(ask_id_for_updates
? [
updateRequesterTool({
@@ -547,6 +592,7 @@ export default async function runBotReply({
*/
plan_mode,
onAsk: ({ ref }) => proposals.push(ref),
redact: redact_reply,
}),
suggestNextStepsTool({
user_id,
@@ -554,6 +600,7 @@ export default async function runBotReply({
session_id,
workspace_id,
onSuggest: ({ ref }) => shown.push(ref),
redact: redact_reply,
}),
]
: []),
@@ -591,6 +638,7 @@ export default async function runBotReply({
}),
...extensions.tools,
...browsers.tools,
...connectors.tools,
...skills.tools,
...knowledge.tools,
];
@@ -660,13 +708,16 @@ export default async function runBotReply({
skills.note,
knowledge.note,
extensions.note,
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "",
knowledge_context,
`Now: ${new Date().toUTCString()}.`,
]
.filter(Boolean)
.join("\n\n"),
messages: await messagesToTurns({ messages: history, user_id }),
tools: plan_mode ? gatePlanModeTools({ tools: reply_tools }) : reply_tools,
tools: plan_mode
? gatePlanModeTools({ tools: groupTools({ tools: reply_tools }) })
: groupTools({ tools: reply_tools }),
max_steps: reply_max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
@@ -709,7 +760,7 @@ export default async function runBotReply({
throw new BotJobFatalError(unsentAnswerMessage({ note: result.review_note }));
}
const answer_text = stripAppRecords({ text: result.text }).trim();
const answer_text = redact_reply(stripAppRecords({ text: result.text })).trim();
/**
* Nothing said is nothing to send: an empty message lands in the
@@ -771,6 +822,7 @@ export default async function runBotReply({
} finally {
await extensions.close();
await browsers.close();
await connectors.close();
}
}
+42 -7
View File
@@ -12,6 +12,7 @@ import {
SettingsNote,
GraphicsNote,
botFilesNote,
ConnectorsNote,
ComputerFilesNote,
ScheduledRunNote,
ScheduledPlanNote,
@@ -40,14 +41,17 @@ import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import runTextLoop from "@/src/harness/text/run-text-loop";
import redactTrace from "@/src/harness/trace/redact-trace";
import maskPasswordFieldValues from "@/src/utils/mask-password-field-values";
import { isUnlimitedLimit, smallerRunLimit } from "@/src/utils/run-limit";
import openComputerTools from "@/src/harness/tools/computer/open-computer-tools";
import openBotBrowsers, { type OpenBotBrowsers } from "@/src/harness/tools/browsers/open-bot-browsers";
import openBotConnectors, { type OpenBotConnectors } from "@/src/harness/tools/connectors/open-bot-connectors";
import { BrowserRunKinds, type BrowserRunKind } from "@/src/dict/browser-dict";
import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/extensions/open-bot-extensions";
import openBotSkills, { type OpenBotSkills } from "@/src/harness/tools/skills/open-bot-skills";
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
import groupTools from "@/src/harness/tools/group-tools";
import grabCoordinatorKnowledgebaseTools from "@/src/harness/tools/bot/knowledgebases/grab-coordinator-knowledgebase-tools";
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
@@ -175,9 +179,17 @@ export default async function runBotTask({
})
: null;
/**
* A password can reach a model by ways the app never sees, a page that
* had one filled in being the one that did: what a task sends out is
* read here too, so a password field's value never reaches the user.
*/
const redact_text = (text: string) => maskPasswordFieldValues({ text: computer ? computer.redact(text) : text });
let extensions: OpenBotExtensions | undefined;
let browsers: OpenBotBrowsers | undefined;
let skills: OpenBotSkills | undefined;
let connectors: OpenBotConnectors | undefined;
try {
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
@@ -376,6 +388,7 @@ export default async function runBotTask({
workspace_id,
in_task: true,
onAsk: ({ ref }) => take_overs.push(ref),
redact: redact_text,
}),
suggestNextStepsTool({
user_id,
@@ -383,6 +396,7 @@ export default async function runBotTask({
session_id,
workspace_id,
onSuggest: ({ ref }) => suggestions.push(ref),
redact: redact_text,
}),
]
: []),
@@ -488,15 +502,31 @@ export default async function runBotTask({
signal,
});
/**
* A task works with the accounts that already work: nobody is
* waiting on this run to be asked to connect one, so a connector
* without an account gets no tools (it is named in the note).
*/
connectors = await openBotConnectors({
user_id,
bot_id: bot.id,
workspace_id,
attended: false,
taken: [...tools, ...extensions.tools, ...browsers.tools].map((tool) => tool.name),
signal,
});
skills = openBotSkills({
skills: extensions.skills,
shown_chars: await grabSkillBodyShownChars(),
taken: [...tools, ...extensions.tools, ...browsers.tools].map((tool) => tool.name),
taken: [...tools, ...extensions.tools, ...browsers.tools, ...connectors.tools].map((tool) => tool.name),
});
const knowledge = openBotKnowledgebases({
knowledgebases: extensions.knowledgebases,
taken: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools].map((tool) => tool.name),
taken: [...tools, ...extensions.tools, ...browsers.tools, ...connectors.tools, ...skills.tools].map(
(tool) => tool.name,
),
});
/**
@@ -632,6 +662,7 @@ export default async function runBotTask({
skills.note,
knowledge.note,
extensions.note,
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "",
]
.filter(Boolean)
.join("\n\n");
@@ -666,7 +697,8 @@ export default async function runBotTask({
const result = await runTextLoop({
system,
messages: opening,
tools: [
tools: groupTools({
tools: [
...tools,
/**
* A task report ends with `send_reply`, the same protocol a
@@ -694,9 +726,11 @@ export default async function runBotTask({
}),
...extensions.tools,
...browsers.tools,
...connectors.tools,
...skills.tools,
...knowledge.tools,
],
],
}),
max_steps,
max_prompt_tokens: await grabRunMaxPromptTokens(),
context_budget: await grabContextBudgetTokens(),
@@ -704,7 +738,7 @@ export default async function runBotTask({
workspace_id,
signal,
onStep: (step) =>
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
report({ ...step, text: step.text ? redact_text(step.text) : step.text }),
/**
* The trace also holds a computer's own secrets: what the bot
* captured mid-run (`capture_secret`) never reaches the
@@ -756,7 +790,7 @@ export default async function runBotTask({
});
if (failure) {
throw new ScheduledRunFailedError(computer ? computer.redact(failure) : failure);
throw new ScheduledRunFailedError(redact_text(failure));
}
/**
@@ -805,7 +839,7 @@ export default async function runBotTask({
return {
...withTakeOverRefs({
text: computer ? computer.redact(text) : text,
text: redact_text(text),
refs: take_overs,
shown: [...shown, ...suggestions],
}),
@@ -821,6 +855,7 @@ export default async function runBotTask({
} finally {
await extensions?.close();
await browsers?.close();
await connectors?.close();
await computer?.close();
}
}
@@ -1,4 +1,4 @@
import Button from "@moduletrace/twui/layout/Button";
import TabButton from "@/src/components/general/tab-button";
type Props = {
title: string;
@@ -10,22 +10,5 @@ type Props = {
* One mode in a computer view's toolbar (`ComputerViewModes`).
*/
export default function ComputerViewModeButton({ title, active, onPick }: Props) {
return (
<Button
type="button"
title={title}
role="tab"
aria-selected={active}
variant="ghost"
color="text"
onClick={onPick}
className={`px-3! py-1.5! text-[13px] leading-[18px] rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink ${
active
? "bg-sunken dark:bg-sunken text-ink dark:text-ink font-bold"
: "text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken"
}`}
>
{title}
</Button>
);
}
return <TabButton title={title} active={active} onPick={onPick} />;
}
+33 -33
View File
@@ -84,44 +84,44 @@ export default function FilePreviewModal({
}}
className="max-w-[95vw]! w-[95vw] h-[90vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Stack className="min-w-0 grow gap-0! items-start">
<Stack className="w-full min-w-0 gap-1! items-stretch pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Row className="w-full gap-3! flex-wrap sm:flex-nowrap items-center">
<H2
title={name}
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate min-w-0 w-full sm:w-auto sm:grow"
>
{base_name}
</H2>
<FilePreviewDetails size={size} full_path={full_path} />
</Stack>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
title={`Download ${base_name}`}
className={ActionClassName}
>
<Download size={16} aria-hidden />
<Span className="hidden sm:inline">Download</Span>
</Link>
<Link
href={url}
target="_blank"
rel="noopener noreferrer"
title="Open in a new tab"
aria-label="Open in a new tab"
className={ActionClassName}
>
<SquareArrowOutUpRight size={16} aria-hidden />
</Link>
</Row>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
title={`Download ${base_name}`}
className={ActionClassName}
>
<Download size={16} aria-hidden />
<Span className="hidden sm:inline">Download</Span>
</Link>
<Link
href={url}
target="_blank"
rel="noopener noreferrer"
title="Open in a new tab"
aria-label="Open in a new tab"
className={ActionClassName}
>
<SquareArrowOutUpRight size={16} aria-hidden />
</Link>
</Row>
<FilePreviewDetails size={size} full_path={full_path} />
</Stack>
<Stack className="relative grow min-h-0 gap-0! items-stretch w-full">
<FilePreviewBody
key={url}
@@ -11,7 +11,12 @@ import useStorageFolder from "@/src/hooks/use-storage-folder";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
import {
storageBreadcrumbs,
storagePathName,
storageSpecHref,
type StorageSpec,
} from "@/src/utils/storage-volumes";
import FilesBreadcrumbRow from "./files-breadcrumb-row";
import FilesSearchInput from "./files-search-input";
import StorageEntryRow from "./storage-entry-row";
@@ -38,8 +43,14 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
const [search, set_search] = useState("");
const query = useDebouncedValue({ value: search.trim() });
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
const crumbs = useMemo(
() => storageBreadcrumbs({ spec, path }),
[spec.volume, spec.owner_id, path],
);
const name =
crumbs.at(-1)?.name ||
folder?.label ||
storagePathName({ volume: spec.volume, path });
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
@@ -69,7 +80,7 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
{name}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{folderSummary({ folder })}
{folderSummary({ folder, loading })}
</Span>
</Stack>
<Link
@@ -82,10 +93,13 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
</Link>
</Row>
<Stack className="w-full gap-0! items-stretch px-5">
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
<FilesBreadcrumbRow crumbs={crumbs} onOpenFolder={openFolder} />
<FilesSearchInput value={search} onChange={set_search} />
</Stack>
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
<Stack
key={`${path}|${query}`}
className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4"
>
{folder?.entries.length ? (
folder.entries.map((entry) => (
<StorageEntryRow
@@ -98,10 +112,10 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
))
) : (
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
{emptyFolderText({ folder, search, loading, error })}
{emptyFolderText({ folder, search: query, loading, error })}
</Span>
)}
</Stack>
</Modal>
);
}
}
@@ -54,6 +54,17 @@ describe("SidePanel", () => {
expect(html.match(/data-no-swipe/g)?.length).toBe(2);
});
test("the rail's drawer and the bot panel open to the same phone width", () => {
const html = renderToString(
<SidePanel side="left" open onClose={onClose} label="Bots">
<p>crew</p>
</SidePanel>,
);
expect(html).toContain("w-[420px]");
expect(html).toContain("max-w-[92vw]");
});
test("a panel that is also part of the page is never inert", () => {
const html = renderToString(
<SidePanel
+17 -3
View File
@@ -1,8 +1,10 @@
"use client";
import type { ReactNode } from "react";
import { useRef, type ReactNode, type RefObject } from "react";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import useSwipeToClose from "@/src/hooks/use-swipe-to-close";
import sidePanelCloseSwipe from "@/src/utils/side-panel-close-swipe";
type Props = {
/** Which edge it slides in from. */
@@ -34,7 +36,10 @@ const Edges = {
* to wait on a timer for an exit to play.
*
* The panel carries `data-no-swipe`, so a phone's sideways swipes never
* start on it or on its backdrop: what is open stays the one on top.
* start on it or on its backdrop: what is open stays the one on top. An
* open panel closes on the one swipe it does answer, a drag back towards the
* edge it slid in from (`useSwipeToClose`), which is the way back out of the
* swipe that opened it.
*/
export default function SidePanel({
side,
@@ -48,6 +53,14 @@ export default function SidePanel({
}: Props) {
const edge = Edges[side];
const hidden = !open && inertWhenClosed;
const panel_ref = useRef<HTMLDivElement>(null);
useSwipeToClose({
panel_ref,
enabled: open,
direction: sidePanelCloseSwipe({ side }),
on_close: onClose,
});
return (
<>
@@ -64,8 +77,9 @@ export default function SidePanel({
aria-hidden={hidden || undefined}
inert={hidden}
data-no-swipe
componentRef={panel_ref as RefObject<HTMLDivElement>}
className={twMerge(
"fixed inset-y-0 z-40 w-[280px] max-w-[85vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
"fixed inset-y-0 z-40 w-[420px] max-w-[92vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
edge.place,
open ? "translate-x-0" : edge.closed,
className,
+37
View File
@@ -0,0 +1,37 @@
import Button from "@moduletrace/twui/layout/Button";
import { twMerge } from "tailwind-merge";
type Props = {
title: string;
active: boolean;
onPick: () => void;
className?: string;
};
/**
* One tab in the app's small segmented row: a ghost button that sits on the
* sunken surface while it is the one showing. The same tab the computer
* viewer's modes use, so every segmented row in the app reads alike.
*/
export default function TabButton({ title, active, onPick, className }: Props) {
return (
<Button
type="button"
title={title}
role="tab"
aria-selected={active}
variant="ghost"
color="text"
onClick={onPick}
className={twMerge(
"px-3! py-1.5! text-[13px] leading-[18px] rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink",
active
? "bg-sunken dark:bg-sunken text-ink dark:text-ink font-bold"
: "text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken",
className,
)}
>
{title}
</Button>
);
}
+15
View File
@@ -15,6 +15,8 @@ import cronSyncHarnessModels from "./sync-harness-models";
import syncComputers from "./sync-computers";
import cronSyncAppNetworks from "./sync-app-networks";
import syncMcpServers from "./sync-mcp-servers";
import syncConnectors from "./sync-connectors";
import pruneConnectorRequests from "./prune-connector-requests";
import runCronJobs from "./run-cron-jobs";
import ingestPendingFiles from "./ingest-pending-files";
import registerCronJob from "./register-cron-job";
@@ -58,6 +60,19 @@ export default function cron() {
task: pruneBotTraces,
});
registerCronJob({
title: "sync-connectors",
schedule: "*/15 * * * *",
task: syncConnectors,
quiet: true,
});
registerCronJob({
title: "prune-connector-requests",
schedule: "@daily",
task: pruneConnectorRequests,
});
registerCronJob({
title: "prune-asks",
schedule: "@daily",
@@ -0,0 +1,20 @@
import BunSQLite from "@moduletrace/bun-sqlite";
const KeepMs = 7 * 24 * 60 * 60 * 1000;
const PendingGraceMs = 24 * 60 * 60 * 1000;
/**
* Deletes old connect requests: anything ended a week ago, and a pending
* one a day past the link's expiry. The accounts themselves stay; a
* request is only the sign-in that made one.
*/
export default async function pruneConnectorRequests() {
const now = Date.now();
await BunSQLite.sql({
sql: `DELETE FROM connector_requests
WHERE (status != 'pending' AND created_at < ?)
OR (status = 'pending' AND expires_at < ?)`,
values: [now - KeepMs, now - PendingGraceMs],
});
}
+64
View File
@@ -0,0 +1,64 @@
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";
/**
* 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:
* 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.
* Each connection is synced with its own key, so a refused one only affects
* the apps it read.
*/
export default async function syncConnectors() {
const connections =
(
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM connector_connections`,
})
).payload || [];
for (const connection of connections) {
await syncConnectorConnection({ connection_id: connection.id });
}
const assigned =
(
await BunSQLite.sql<{ id: number }>({
sql: `SELECT c.id FROM connectors c
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))`,
})
).payload || [];
for (const connector of assigned) {
await syncConnector({ connector_id: connector.id });
}
const now = Date.now();
const stale_after = now - 60 * 60 * 1000;
const waiting =
(
await BunSQLite.sql<{ connector_id: number; user_id: number }>({
sql: `SELECT connector_id, user_id FROM connector_requests WHERE status = 'pending' AND expires_at > ?
UNION
SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected'
UNION
SELECT connector_id, user_id FROM connector_accounts
WHERE status = 'connected' AND (last_checked_at IS NULL OR last_checked_at < ?)`,
values: [now, stale_after],
})
).payload || [];
for (const request of waiting) {
await syncConnectorAccounts({
user_id: request.user_id,
connector_id: request.connector_id,
}).catch(() => {});
}
}
+72 -17
View File
@@ -124,7 +124,7 @@ export const AppData = {
* `computer/` (the release workflow builds that tag), and bump
* `ComputerWorkspaceLayout` too when existing computers must move to it.
*/
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.4",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.5",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
@@ -545,15 +545,15 @@ export const AppData = {
HarnessAutoMinContext: 32_000,
/**
* The window a run assumes for a model whose catalog never said
* (`run-text-loop.ts`): a custom provider lists ids and nothing else,
* and at 32000 the base prompt alone (system and tool definitions,
* ~25000 tokens here) was already past the 70% working window, so every
* turn trimmed the output the run was reading. 70% of this is the
* widest such a model is ever given, whatever
* `harness_context_budget_tokens` asks for, so it must stay at or above
* that budget.
* (`run-text-loop.ts`): a custom provider lists ids and nothing else.
* It is a guess, and the provider has the last word: a model that is
* smaller refuses a prompt past its real window, and that refusal
* stops the run with the provider's own message, which names the
* limit to set on the model (`Settings > Models`). Never learn a
* smaller window into this: a run that quietly assumed 131072 here
* gave a model a 91,750-token working context and went blind.
*/
HarnessUnknownContextWindow: 131_072,
HarnessUnknownContextWindow: 1_000_000,
/**
* A provider's declared window (`harness_providers.context_length`),
* handed to the models it lists without one of their own: the least and
@@ -694,15 +694,17 @@ export const AppData = {
*/
HarnessReplyDraftsMax: 2,
/**
* The working context: how many tokens (estimated) of system prompt,
* tool definitions and transcript a run sends per turn before old tool
* output is trimmed, whatever the model's window. Every turn resends
* all of it, so a run that only trims at a 1M window pays for its whole
* history on every step. The install may save its own
* (`harness_context_budget_tokens`), read through
* `grabContextBudgetTokens`.
* An optional tighter cap on the working context: how many tokens
* (estimated) of system prompt, tool definitions and transcript a run
* sends per turn before old tool output is trimmed. Unlimited by
* default, so the model's own window decides (minus the reserve it
* needs for its answer, `workingContextTokens`): an install that
* saved `harness_context_budget_tokens` asks for less, for a model
* whose window it pays for by the token. Every turn resends all of
* it, so a run that only trims at a 1M window pays for its whole
* history on every step; that is what this setting is for.
*/
HarnessContextBudgetTokens: 200_000,
HarnessContextBudgetTokens: UnlimitedLimit,
/**
* The least a saved working context may be: below it a run would trim
* the output it is reading right now (one full tool result is ~20000
@@ -733,6 +735,21 @@ export const AppData = {
* pass this many characters; below it they're simply all given.
*/
HarnessDeferToolsMinChars: 6000,
/**
* The bot's own tools (tasks, schedules, hooks, files, plans, crew,
* knowledgebases, graphics) are deferred the same way, but only when
* they are both this large and past `HarnessDeferBuiltinToolsShare` of
* the working context: at 25 tools they were ~33k tokens of every
* turn, which on a 131k-window model left the conversation about 50k
* to work in. Deferring costs a turn to load them, so a model with a
* window that holds them comfortably keeps them inline.
*/
HarnessDeferBuiltinToolsMinChars: 20_000,
/**
* Share of the working context the bot's own tool definitions must
* pass before they are deferred rather than sent every turn.
*/
HarnessDeferBuiltinToolsShare: 0.1,
/**
* How much of a deferred tool's description its line in the list
* shows.
@@ -844,6 +861,44 @@ export const AppData = {
* One MCP tool call gives up after this long without progress.
*/
McpToolTimeoutMs: 5 * 60 * 1000,
/**
* One connector tool call gives up after this long. A provider bills per
* action, so this sits beside the per-run cap rather than in place of it.
*/
ConnectorToolTimeoutMs: 5 * 60 * 1000,
/**
* How many connector actions one run may take, to any provider, before
* its calls are refused: a search loop in Gmail is billed per call and
* would otherwise run to the step limit.
*/
ConnectorActionsPerRun: 50,
/**
* The most an install may raise that to: a provider bills per action, so
* the ceiling is what one run can cost.
*/
ConnectorActionsPerRunMax: 500,
/**
* How long a connect link stays good. The card in its message says it
* expired after this, and a new call makes another.
*/
ConnectorRequestTtlMs: 15 * 60 * 1000,
/**
* How long a provider session (one MCP endpoint per account) is kept
* before it is made again. Providers expire them on their own schedule;
* this only keeps the cache from outliving the truth.
*/
ConnectorSessionTtlMs: 25 * 60 * 1000,
/**
* When a provider can't pin one account to a session, its tools run
* through REST instead. This is how long that is remembered before a
* session is tried again.
*/
ConnectorRestRetryMs: 60 * 60 * 1000,
/**
* How many of a connection's apps one page lists. One connection can
* hold thousands, so the page never reads them all at once.
*/
ConnectorAppsPageSize: 24,
/**
* 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
+54 -9
View File
@@ -206,6 +206,19 @@ You have runbooks (skills): load_skill lists them, with the one line each says a
- Load one only when it applies to what you're doing; loading everything fills your context with instructions you don't need.
- If a skill turns out to be wrong or out of date for the job, follow it as written and tell the user in your reply, so they can fix it in Settings, under Skills.`;
/**
* Added to every run that reaches a connector (`openBotConnectors`): the
* accounts it can use, and what its tools are called.
*/
export const ConnectorsNote = ({ lines }: { lines: string[] }) => `# 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*"]).
- 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.
${lines.map((line) => `- ${line}`).join("\n")}
`;
/**
* Told to a run that reaches a knowledgebase (`openBotKnowledgebases`).
*/
@@ -244,7 +257,9 @@ Anything you read or write goes to your model provider, so secret values (passwo
- Never ask the user to type or paste a secret into the chat. Use request_secret: they type it into a masked card, and it reaches your computers as $KEY.
- If they paste one anyway, don't repeat it; tell them to remove it from the message and use the card you send with request_secret instead.
- Never print, cat or echo a secret on a computer. To show one to the user, use show_secret for an env you have, or in a task on a computer capture it with capture_secret: either gives you a [secret:ID] ref to put in your message.
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected.`;
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected, and it means the env is set, never that it's empty.
- A password you find on a page is that page's, not yours to repeat: a login form a browser had filled in can show its value (a browser tool reports a password field's value as [hidden]), and it must never appear in a message, a question, a suggestion, a task brief or a tool call. Never type a credential into ask_user or into the chat: request_secret is the only way one comes to you.
- A browser here keeps no saved logins, so a filled-in password field is never a credential you have: read it as [hidden] and move on, don't read it out and don't reuse it.`;
/**
* Added to every reply and task: the app's own limits are the user's to
@@ -562,20 +577,50 @@ export const repairedAnswerNote = `_Part of this answer was left out: it describ
/**
* Told once, when the prompt no longer fits the working context even after
* everything trimmable was trimmed: what is left is what the user wrote,
* which the app never cuts. A run that keeps reading whole files into the
* conversation only makes the next turn larger, and its answer is paid for
* out of whatever room is left. Told rather than trimming the request: the
* model has to know it may not be seeing all of a pasted brief, so it says
* what it could not reach instead of inventing the rest.
* everything trimmable was trimmed. What is left is the conversation, most
* of it what the user wrote, which the app never cuts, and the app's own
* instructions and tool definitions, which it cannot cut either. A run that
* keeps reading whole files into the conversation only makes the next turn
* larger, and its answer is paid for out of whatever room is left. Told
* rather than trimming the request: the model has to know it may not be
* seeing all of a pasted brief, so it says what it could not reach instead
* of inventing the rest.
*/
export const oversizedRequestNote = ({ budget }: { budget: number }) =>
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and none of what is over is yours to trim: the app cuts tool output, never what the user wrote. Every turn resends all of it, so reading more makes the next one worse.
export const oversizedRequestNote = ({ budget, base, conversation }: { budget: number; base: number; conversation: number }) =>
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and everything the app is allowed to cut has been cut. Of what is left, about ${base.toLocaleString("en-US")} tokens are the app's own instructions and tool definitions, and about ${conversation.toLocaleString("en-US")} are the conversation itself. Every turn resends all of it, so reading more makes the next one worse.
From here: stop pulling whole files, whole pages or entire command outputs into the conversation. Work from what you already have, read only the piece you need (a line range, a filter, grep), write what must be kept to a file rather than into a message, and answer on this turn.
If what you need sits in a part of the request you cannot reach in one piece, say plainly what you could and could not read, and ask the user to attach it as a file, put it in a knowledgebase, or point you at a path. A guess presented as a reading of it is worse than saying it was too long.`;
/**
* The failure a run stops on when its instructions and tool definitions
* alone are past the working context (`fitTranscriptToContext`'s
* `over_budget: "static"`). Nothing can be trimmed into that room, so a
* run that went on trimmed every tool result of every turn and answered
* from nothing: one read a 14-character shell answer as "Trimmed: 14
* characters" for thirty steps. The user is told the arithmetic and where
* to fix it, instead of watching a bot go blind.
*/
export const staticPromptOverBudgetNote = ({
working,
window,
assumed,
base,
system,
tools,
}: {
working: number;
window: number;
assumed: boolean;
base: number;
system: number;
tools: number;
}) =>
`This run stopped before its first answer: the model's working context is about ${working.toLocaleString("en-US")} tokens${assumed ? " (the model declares no context window, so the app assumed one)" : ` (a ${window.toLocaleString("en-US")} token window)`}, and this run's own instructions and tool definitions already take about ${base.toLocaleString("en-US")} of them (system prompt about ${system.toLocaleString("en-US")}, tools about ${tools.toLocaleString("en-US")}), which leaves no room for the conversation. Nothing was trimmed, because trimming could not have helped.
If the model's real window is bigger than that, set it on its provider in Settings > Models. If it is not, choose a model with a larger window for this bot, or give it fewer extensions (MCP servers, browsers and connectors add tool definitions to every turn).`;
/**
* Told when the app has had to trim earlier tool output from the transcript
* (`fitTranscriptToContext`'s `trimmed` count, every
+8
View File
@@ -182,7 +182,15 @@ def start(runner, env, log_max):
"version": runner.get("version") or "",
},
)
# A login shell can still be reading its profiles when the first look
# happens, so give a process that exits soon a moment to be seen doing
# it: another 1.2s costs nothing here and keeps a dead runner from
# being reported as running.
deadline = time.time() + 1.2
code = child.poll()
while code is None and time.time() < deadline:
time.sleep(0.1)
code = child.poll()
if code is not None:
tail = log_tail(runner_id, 400)
try:
+166
View File
@@ -0,0 +1,166 @@
/**
* Who hosts a connector's app and its sign-in. Composio is the first: it
* holds the OAuth apps (Gmail, Slack, ...) and the accounts users connect,
* and hands a run an MCP endpoint per account. A provider is one file under
* `src/harness/connectors/providers/` plus an entry here.
*
* The key is not here: one provider can be connected several times
* (`connector_connections`), each with its own key (a personal account and a
* work one), and each lists the apps that key holds.
*
* A connection's paradigm is this provider: it decides how that connection's
* apps are reached. Composio is the first; another paradigm adds a file here
* and an entry below.
*/
export const ConnectorProviders = [
{
title: "Composio",
value: "composio",
/**
* Its catalog and its sessions answer here.
*/
base_url: "https://backend.composio.dev/api/v3.1",
/**
* Where the account's project key is made. Shown beside the key field
* so nobody has to guess which key a connection wants.
*/
key_url: "https://dashboard.composio.dev/~/project/settings/api-keys",
key_url_title: "Get a Composio project API key",
/**
* What kind of key it takes, said in the add form. A consumer key
* (`ck_...`) works only for the hosted MCP at connect.composio.dev,
* whose router signs everyone in as the key's owner, so it can't
* back a connector that keeps one account per person.
*/
key_help: "Paste a project API key (ak_...), not a key made for connect.composio.dev/mcp: that one belongs to the hosted MCP and can't keep an account per person.",
},
] as const;
export type ConnectorProviderId = (typeof ConnectorProviders)[number]["value"];
/**
* Where a connector applies. Global and workspace reach everyone; a bot
* row is always personal to the user who made it.
*/
export const ConnectorTiers = [
{
title: "This bot, for me",
value: "bot",
},
{
title: "A workspace",
value: "workspace",
},
{
title: "Every bot",
value: "global",
},
] as const;
export type ConnectorTier = (typeof ConnectorTiers)[number]["value"];
/**
* A connector's own state: never synced from its provider yet, ready (its
* tools were listed), or an error the row's `last_error` explains.
*/
export const ConnectorStatuses = [
{
title: "Not synced yet",
value: "untested",
},
{
title: "Ready",
value: "ready",
},
{
title: "Error",
value: "error",
},
] as const;
export type ConnectorStatus = (typeof ConnectorStatuses)[number]["value"];
/**
* One user's connection to an app: waiting for them to finish signing in,
* connected, expired (the provider's token lapsed, so they reconnect), or
* disconnected by them.
*/
export const ConnectorAccountStatuses = [
{
title: "Waiting for you",
value: "pending",
},
{
title: "Connected",
value: "connected",
},
{
title: "Needs reconnecting",
value: "expired",
},
{
title: "Disconnected",
value: "revoked",
},
] as const;
export type ConnectorAccountStatus = (typeof ConnectorAccountStatuses)[number]["value"];
/**
* A connect link's state: waiting for the user to finish, connected,
* expired before they did, or cancelled by them.
*/
export const ConnectorRequestStatuses = [
{
title: "Waiting for you",
value: "pending",
},
{
title: "Connected",
value: "connected",
},
{
title: "Expired",
value: "expired",
},
{
title: "Cancelled",
value: "cancelled",
},
] as const;
export type ConnectorRequestStatus = (typeof ConnectorRequestStatuses)[number]["value"];
/**
* What separates a connector's slug from an account's in a tool name, when
* a user has more than one account for that app:
* `gmail-work__GMAIL_SEND_EMAIL`.
*/
export const ConnectorAccountSeparator = "-";
/**
* The app setting that holds how many connector actions one run may take,
* saved as a number of steps (`connectors_actions_per_run`).
*/
export const ConnectorActionsPerRunSettingKey = "connectors_actions_per_run";
/**
* How a connection's apps are filtered. An app counts as connected when the
* viewer can see a connected account for it, so the list leads with the apps
* that are ready to use.
*/
export const ConnectorAppFilters = [
{
title: "All",
value: "all",
},
{
title: "Connected",
value: "connected",
},
{
title: "Unconnected",
value: "unconnected",
},
] as const;
export type ConnectorAppFilter = (typeof ConnectorAppFilters)[number]["value"];
+2
View File
@@ -1,6 +1,7 @@
import {
BookOpen,
Bot,
Cable,
Compass,
CpuAi,
Database,
@@ -69,6 +70,7 @@ export const SettingsPages: SettingsPage[] = [
},
{ title: "Secrets", url: "/admin/settings/secrets", Icon: LockKeyhole },
{ title: "Browsers", url: "/admin/settings/browsers", Icon: Compass },
{ title: "Connectors", url: "/admin/settings/connectors", Icon: Cable },
{ title: "Bots", url: "/admin/settings/bots", Icon: Bot, can_view: canManageCrew },
{ title: "Workspaces", url: "/admin/settings/workspaces", Icon: Layers, can_view: canManageCrew },
{
@@ -0,0 +1,18 @@
import AppError from "@/src/utils/app-error";
import grabCrewRole from "./grab-crew-role";
type Params = {
user_id: number | string;
};
/**
* Throws unless the user is the install's super admin. Global and workspace
* access to connectors is theirs alone.
*/
export default async function assertSuperAdmin({ user_id }: Params) {
const role = await grabCrewRole({ user_id });
if (role != "super_admin") throw new AppError(`Only a super admin can do that.`);
return role;
}
@@ -70,8 +70,9 @@ export async function grabRunMaxPromptTokens() {
/**
* The working context a run keeps per turn, in estimated tokens: the
* install's own (`harness_context_budget_tokens`), else
* `AppData.HarnessContextBudgetTokens`. Unlimited keeps the model's whole
* window.
* `AppData.HarnessContextBudgetTokens`. Unlimited (the default) keeps the
* model's own window, less the reserve its answer needs
* (`workingContextTokens`), so this is only a way to hold runs below that.
*/
export async function grabContextBudgetTokens() {
return readRunLimit({
@@ -0,0 +1,44 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
account_ids: number[];
};
export type ConnectorAccountScopes = {
workspace_ids: number[];
bot_ids: number[];
};
/**
* Where each account has been given to, read beside its row: a workspace or
* a bot whose every run may use it, not only the owner's.
*/
export default async function attachConnectorAccountScopes({
account_ids,
}: Params): Promise<Map<number, ConnectorAccountScopes>> {
const scopes = new Map<number, ConnectorAccountScopes>();
if (!account_ids.length) return scopes;
for (const id of account_ids) scopes.set(id, { workspace_ids: [], bot_ids: [] });
const marks = account_ids.map(() => "?").join(", ");
const workspaces =
(
await BunSQLite.sql<{ account_id: number; workspace_id: number }>({
sql: `SELECT account_id, workspace_id FROM connector_account_workspaces WHERE account_id IN (${marks}) ORDER BY workspace_id ASC`,
values: account_ids,
})
).payload || [];
const bots =
(
await BunSQLite.sql<{ account_id: number; bot_id: number }>({
sql: `SELECT account_id, bot_id FROM connector_account_bots WHERE account_id IN (${marks}) ORDER BY bot_id ASC`,
values: account_ids,
})
).payload || [];
for (const row of workspaces) scopes.get(Number(row.account_id))?.workspace_ids.push(Number(row.workspace_id));
for (const row of bots) scopes.get(Number(row.account_id))?.bot_ids.push(Number(row.bot_id));
return scopes;
}
@@ -0,0 +1,22 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
type Params = {
user_id: number | string;
bot_id: number | string;
workspace_id?: number | string | null;
};
/**
* How many apps this person's runs on this bot can reach, so the composer's
* tools count includes connectors without reading them all.
*/
export default async function countBotConnectors({ user_id, bot_id, workspace_id }: Params): Promise<number> {
const { sql, values } = botConnectorsSql({ user_id, bot_id, workspace_id });
const res = await BunSQLite.sql<{ total: number }>({
sql: `SELECT COUNT(*) AS total FROM (${sql}) x`,
values,
});
return Number(res.payload?.[0]?.total || 0);
}
@@ -0,0 +1,108 @@
import AppError from "@/src/utils/app-error";
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS, BunSQLiteTables } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import type { ConnectorRecord } from "@/src/types";
import grabConnectorProvider from "./grab-connector-provider";
type Params = {
user_id: number;
/**
* The bot whose conversation asked, null outside one.
*/
bot_id?: number | null;
/**
* The conversation to wake once the account is connected, null when
* the request came from Settings.
*/
session_id?: number | null;
connector: ConnectorRecord;
label?: string;
/**
* The account being reconnected, 0 or absent for a new one.
*/
account_id?: number;
};
export type ConnectorRequest = {
id: number;
url: string;
expires_at: number;
};
/**
* A connect link for one user and one connector, either the open one or a
* new one. A second call while the first card still stands returns the
* same link, so a bot that reports the missing account twice never sends the
* user two links (one of which the provider would have already spent).
*/
export default async function createConnectorRequest({
user_id,
bot_id,
session_id,
connector,
label,
account_id,
}: Params): Promise<ConnectorRequest> {
const now = Date.now();
const name = label || connector.name;
const open = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS>({
sql: `SELECT * FROM connector_requests WHERE connector_id = ? AND user_id = ? AND label = ? AND account_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id DESC LIMIT 1`,
values: [connector.id, user_id, name, Number(account_id || 0), now],
})
).payload?.[0];
if (open?.url) return { id: Number(open.id), url: open.url, expires_at: Number(open.expires_at) };
const provider = await grabConnectorProvider({ connector_id: connector.id });
const started = await provider.startConnect({
app: connector.app,
user_id,
label: name,
auth_config_id: connector.auth_config_id,
});
if (started.auth_config_id && started.auth_config_id != connector.auth_config_id) {
await BunSQLite.sql({
sql: `UPDATE connectors SET auth_config_id = ?, updated_at = ? WHERE id = ?`,
values: [started.auth_config_id, now, connector.id],
});
}
const provided_expiry = Number(started.expires_at || 0);
const expires_at =
provided_expiry > now ? Math.min(now + AppData.ConnectorRequestTtlMs, provided_expiry) : now + AppData.ConnectorRequestTtlMs;
await BunSQLite.sql({
sql: `UPDATE connector_requests SET status = 'cancelled' WHERE connector_id = ? AND user_id = ? AND status = 'pending'`,
values: [connector.id, user_id],
});
const created = await BunSQLite.insert<
BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS,
(typeof BunSQLiteTables)[number]
>({
table: "connector_requests",
data: [
{
connector_id: connector.id,
user_id,
bot_id: bot_id ?? undefined,
bot_session_id: session_id ?? undefined,
label: name,
account_id: Number(account_id || 0),
url: started.url,
provider_account_id: started.provider_account_id || undefined,
status: "pending",
expires_at,
},
],
});
const id = Number(created.singleRes?.id || created.postInsertReturn?.insertId);
if (!created.success || !id) throw new AppError(`Couldn't store the connect request: ${created.msg}`);
return { id, url: started.url, expires_at };
}
@@ -0,0 +1,59 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import grabConnectorProvider from "./grab-connector-provider";
import grabConnectorConnection from "./grab-connector-connection";
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
* provider accounts are released first, best effort, since a key that was
* already refused must not stop the delete.
*/
export default async function deleteConnectorConnection({ connection_id }: Params) {
const connection = await grabConnectorConnection({ connection_id });
const ids = (
(
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM connectors WHERE connection_id = ?`,
values: [connection.id],
})
).payload || []
).map((row) => Number(row.id));
for (const connector_id of ids) {
try {
const provider = await grabConnectorProvider({ connector_id });
const accounts =
(
await BunSQLite.sql<{ provider_account_id: string }>({
sql: `SELECT provider_account_id FROM connector_accounts WHERE connector_id = ?`,
values: [connector_id],
})
).payload || [];
for (const account of accounts) {
if (account.provider_account_id) await provider.revoke({ account: account.provider_account_id });
}
} catch {
// The key may already be refused; the rows still go.
}
}
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 });
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 });
await BunSQLite.sql({ sql: `DELETE FROM connectors WHERE connection_id = ?`, values: [connection.id] });
}
await BunSQLite.sql({ sql: `DELETE FROM connector_connections WHERE id = ?`, values: [connection.id] });
return { name: connection.name, apps: ids.length };
}
@@ -0,0 +1,29 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
bot_id: number | string;
connector_id: number | string;
};
/**
* Takes a connector off one bot for this user: their own bot attachment,
* and their own account given to this bot alone. A workspace's, the
* install's or an account given to every bot is untouched, since they
* reach here for reasons this user doesn't own.
*/
export default async function detachConnectorFromBot({ user_id, bot_id, connector_id }: Params) {
await BunSQLite.sql({
sql: `DELETE FROM bot_connectors WHERE bot_id = ? AND user_id = ? AND connector_id = ?`,
values: [Number(bot_id), Number(user_id), Number(connector_id)],
});
await BunSQLite.sql({
sql: `DELETE FROM connector_account_bots
WHERE bot_id = ? AND account_id IN (
SELECT id FROM connector_accounts
WHERE connector_id = ? AND user_id = ? AND all_bots = 0
)`,
values: [Number(bot_id), Number(connector_id), Number(user_id)],
});
}
@@ -0,0 +1,53 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import grabConnectorProvider from "./grab-connector-provider";
import grabConnector from "./grab-connector";
import grabConnectorAccount from "./grab-connector-account";
type Params = {
user_id: number | string;
account_id: number | string;
};
/**
* Forgets one of the user's accounts: the provider's own record first (best
* effort), then the local row and any cached session built on it. Another
* connected account takes over as the default, so a run keeps working.
*/
export default async function disconnectConnectorAccount({ user_id, account_id }: Params) {
const account = await grabConnectorAccount({ account_id, user_id });
const connector = await grabConnector({ connector_id: account.connector_id });
try {
const provider = await grabConnectorProvider({ connector_id: connector.id });
if (account.provider_account_id) await provider.revoke({ account: account.provider_account_id });
} catch {
// A provider that won't answer mustn't keep an account the user removed.
}
const now = Date.now();
await BunSQLite.sql({
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],
});
await BunSQLite.sql({ sql: `DELETE FROM connector_accounts WHERE id = ?`, values: [account.id] });
if (account.is_default) {
const next = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' ORDER BY id ASC LIMIT 1`,
values: [connector.id, Number(user_id)],
})
).payload?.[0];
if (next) {
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET is_default = 1, updated_at = ? WHERE id = ?`,
values: [now, next.id],
});
}
}
return { connector, account };
}
@@ -0,0 +1,76 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
import type { AttachableConnector } from "@/src/types";
type Params = {
user_id: number | string;
bot_id: number | string;
query?: string;
connection_id?: number | string;
workspace_id?: number | string;
};
type Row = BUN_SQLITE_COBBLE_CONNECTORS & {
connection_name?: string;
attached?: number;
};
const Limit = 20;
/**
* Apps this user can still add to this bot themselves: enabled apps of every
* connection (or of the one named) with a connected account of their own.
* An app this user already attached to this bot is left out (the app itself
* is already there); an account already given here is left out of the app's
* accounts by `grabConnectorOwnAccounts`, not out of this list.
*/
export default async function grabAttachableConnectors({
user_id,
bot_id,
query = "",
connection_id,
workspace_id,
}: Params): Promise<AttachableConnector[]> {
const search = `%${query.trim()}%`;
const connection = Number(connection_id) ? Number(connection_id) : 0;
const workspace = Number(workspace_id) ? Number(workspace_id) : 0;
const rows =
(
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 NOT EXISTS (
SELECT 1 FROM bot_connectors bc
WHERE bc.bot_id = ? AND bc.user_id = ? AND bc.connector_id = c.id
)
AND EXISTS (
SELECT 1 FROM connector_accounts a
WHERE a.connector_id = c.id AND a.status = 'connected' AND a.user_id = ?
)
ORDER BY c.name ASC
LIMIT ?`,
values: [
search,
search,
connection,
connection,
Number(bot_id),
Number(user_id),
Number(user_id),
Limit,
],
})
).payload || [];
return rows.map((row) => ({
id: Number(row.id),
name: row.name || "",
app: row.app || "",
logo: row.logo || "",
connection_name: row.connection_name || "",
attached: false,
}));
}
@@ -0,0 +1,128 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
import type { BotConnectorEntry, ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
import botConnectorsSql from "@/src/utils/bot-connectors-sql";
import connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import parseConnectorAccountRow from "./parse-connector-account-row";
import parseConnectorRow from "./parse-connector-row";
type Params = {
user_id: number | string;
bot_id: number | string;
workspace_id?: number | string | null;
};
type AccountRow = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string };
type ConnectorRow = BUN_SQLITE_COBBLE_CONNECTORS & { connection_name?: string };
/**
* The connectors a conversation's bot can use for this user, with the
* accounts that reach there: this user's own (whatever their status, so a
* pending sign-in still shows), every connected account of a connector given
* to this workspace, and any connected account given to this bot, this
* workspace or every bot, named with its owner. Each app says where it comes
* from: the install, this workspace, this user's own attachment, or an
* account given here.
*/
export default async function grabBotConnectors({
user_id,
bot_id,
workspace_id,
}: Params): Promise<BotConnectorEntry[]> {
const reach = botConnectorsSql({ bot_id, user_id, workspace_id });
const found =
(
await BunSQLite.sql<ConnectorRow>({
sql: `SELECT c.*, cc.name AS connection_name
FROM (${reach.sql}) c JOIN connector_connections cc ON cc.id = c.connection_id`,
values: reach.values,
})
).payload || [];
if (!found.length) return [];
const connectors = found.map((row) => parseConnectorRow({ row }));
const connection_names = new Map(found.map((row) => [Number(row.id), row.connection_name || ""]));
const ids = connectors.map((connector) => connector.id);
const placeholders = ids.map(() => "?").join(", ");
const workspace_reach = connectorAccountReachSql({ workspace_id });
const [account_res, workspace_res, bot_res] = await Promise.all([
BunSQLite.sql<AccountRow>({
sql: `SELECT a.*, trim(coalesce(u.first_name, '') || ' ' || coalesce(u.last_name, '')) AS owner_name
FROM connector_accounts a
LEFT JOIN users u ON u.id = a.user_id
WHERE a.connector_id IN (${placeholders}) AND (
a.user_id = ?
OR (
a.status = 'connected' AND (
a.all_bots = 1
OR EXISTS (SELECT 1 FROM connector_account_bots ab WHERE ab.account_id = a.id AND ab.bot_id = ?)
${workspace_id ? `OR EXISTS (SELECT 1 FROM connector_account_workspaces aw WHERE aw.account_id = a.id AND aw.workspace_id = ?)` : ""}
${workspace_reach.sql}
)
)
)
ORDER BY a.id ASC`,
values: [
...ids,
Number(user_id),
Number(bot_id),
...(workspace_id ? [Number(workspace_id)] : []),
...workspace_reach.values,
],
}),
BunSQLite.sql<{ connector_id: number }>({
sql: `SELECT connector_id FROM workspace_connectors WHERE connector_id IN (${placeholders})`,
values: [...ids],
}),
BunSQLite.sql<{ connector_id: number }>({
sql: `SELECT connector_id FROM bot_connectors WHERE connector_id IN (${placeholders}) AND bot_id = ? AND user_id = ?`,
values: [...ids, Number(bot_id), Number(user_id)],
}),
]);
const account_rows = account_res.payload || [];
const scopes = await attachConnectorAccountScopes({
account_ids: account_rows.map((row) => Number(row.id)),
});
const accounts = account_rows.map((row) =>
parseConnectorAccountRow({
row,
workspace_ids: scopes.get(Number(row.id))?.workspace_ids || [],
bot_ids: scopes.get(Number(row.id))?.bot_ids || [],
owner_name: row.owner_name || "",
}),
);
const in_workspace = new Set((workspace_res.payload || []).map((row) => Number(row.connector_id)));
const on_bot = new Set((bot_res.payload || []).map((row) => Number(row.connector_id)));
return connectors.map((connector): BotConnectorEntry => {
const via = connector.all_bots
? "global"
: in_workspace.has(connector.id)
? "workspace"
: on_bot.has(connector.id)
? "bot"
: "account";
const own = accounts.filter((account) => account.connector_id == connector.id);
return {
connector,
connection_name: connection_names.get(connector.id) || "",
via,
accounts: own,
removable:
via == "bot" ||
(via == "account" &&
own.some(
(account) =>
Number(account.user_id) == Number(user_id) &&
!account.all_bots &&
account.bot_ids.map(Number).includes(Number(bot_id)),
)),
};
});
}
@@ -0,0 +1,19 @@
import connectorProviderFor from "@/src/harness/connectors/connector-provider-for";
import type { ConnectorProvider } from "@/src/harness/connectors/connector-provider";
import grabConnectorConnection from "./grab-connector-connection";
type Params = {
connection_id: number | string;
};
/**
* The provider adapter for a connection on its own, before any of its apps
* are stored: what the Connect action lists the catalog with.
*/
export default async function grabConnectionProvider({ connection_id }: Params): Promise<ConnectorProvider> {
const connection = await grabConnectorConnection({ connection_id });
return connectorProviderFor({
connection: { provider: connection.provider, name: connection.name, api_key: connection.api_key },
});
}
@@ -0,0 +1,33 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import parseConnectorAccountRow from "./parse-connector-account-row";
type Params = {
account_id: number | string;
/**
* Only this user's accounts are returned, unless `any_owner` asks for
* the row whoever connected it (a super admin scoping it, say): an id
* from a stale page still can't reach someone else's credential.
*/
user_id: number | string;
any_owner?: boolean;
};
/**
* One connected account, the user's own by default.
*/
export default async function grabConnectorAccount({ account_id, user_id, any_owner = false }: Params) {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: any_owner
? `SELECT * FROM connector_accounts WHERE id = ? LIMIT 1`
: `SELECT * FROM connector_accounts WHERE id = ? AND user_id = ? LIMIT 1`,
values: any_owner ? [Number(account_id)] : [Number(account_id), Number(user_id)],
});
const row = res.payload?.[0];
if (!row) throw new AppError(`That account isn't connected here.`);
return parseConnectorAccountRow({ row });
}
@@ -0,0 +1,18 @@
import { AppData } from "@/src/data/app-data";
import { ConnectorActionsPerRunSettingKey } from "@/src/dict/connector-dict";
import readStepLimit from "@/src/utils/read-step-limit";
import grabAppSetting from "../app-settings/grab-app-setting";
/**
* How many connector actions one run may take, to any provider: the
* install's own number (Settings > Connectors), else
* `AppData.ConnectorActionsPerRun`. A provider bills per action, so a run
* that searches in a loop costs money per call.
*/
export default async function grabConnectorActionsPerRun() {
return readStepLimit({
saved: await grabAppSetting({ key: ConnectorActionsPerRunSettingKey }),
fallback: AppData.ConnectorActionsPerRun,
max: AppData.ConnectorActionsPerRunMax,
});
}
@@ -0,0 +1,206 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type {
BUN_SQLITE_COBBLE_CONNECTORS,
BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS,
} from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import grabBots from "../bots/grab-bots";
import grabCrewRole from "../access/grab-crew-role";
import grabUserWorkspaces from "../workspaces/grab-user-workspaces";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import type {
ConnectorAccess,
ConnectorAccountRecord,
ConnectorAppsPayload,
ConnectorRecord,
} from "@/src/types";
import type { ConnectorAppFilter } from "@/src/dict/connector-dict";
import parseConnectorAccountRow from "./parse-connector-account-row";
import parseConnectorRow from "./parse-connector-row";
type Params = {
/**
* Who's looking: the accounts and the bot attachments are theirs alone.
*/
user_id: number | string;
connection_id: number | string;
/**
* What to search for, over the app's name, slug and description.
*/
query?: string;
/**
* All apps, only those with a connected account the viewer can see, or
* only those without one.
*/
filter?: ConnectorAppFilter;
page?: number;
page_size?: number;
};
/**
* One page of a connection's apps, the viewer's own accounts for those
* apps, and where each is attached for them. A connection can hold
* thousands of apps, so the page asks for a slice and a search rather than
* everything at once. Apps with a connected account come first, and the
* tabs' counts come back with the page.
*/
export default async function grabConnectorApps({
user_id,
connection_id,
query = "",
filter = "all",
page = 1,
page_size = AppData.ConnectorAppsPageSize,
}: Params): Promise<ConnectorAppsPayload> {
const id = Number(user_id);
const connection = Number(connection_id);
const needle = query.trim();
const like = `%${needle}%`;
const size = Math.min(Math.max(Math.trunc(page_size) || AppData.ConnectorAppsPageSize, 1), 100);
/**
* The accounts this viewer may see, and the values that decide it. Used
* both for the connected filter and for the accounts on the page.
*/
const scope = await accountVisibility({ user_id: id });
const connected = `EXISTS (SELECT 1 FROM connector_accounts a WHERE a.connector_id = c.id AND a.status = 'connected' AND ${scope.sql})`;
const matches = needle
? `c.connection_id = ? AND (c.name LIKE ? OR c.app LIKE ? OR c.description LIKE ?)`
: `c.connection_id = ?`;
const match_values = needle ? [connection, like, like, like] : [connection];
const filter_sql =
filter == "connected"
? ` AND ${connected}`
: filter == "unconnected"
? ` AND NOT ${connected}`
: "";
const counts_res = await BunSQLite.sql<{ total: number; connected: number }>({
sql: `SELECT COUNT(*) AS total, SUM(CASE WHEN ${connected} THEN 1 ELSE 0 END) AS connected
FROM connectors c WHERE ${matches}`,
values: [...scope.values, ...match_values],
});
const counts = {
all: Number(counts_res.payload?.[0]?.total || 0),
connected: Number(counts_res.payload?.[0]?.connected || 0),
unconnected: 0,
};
counts.unconnected = counts.all - counts.connected;
const total =
filter == "connected" ? counts.connected : filter == "unconnected" ? counts.unconnected : counts.all;
const pages = Math.max(1, Math.ceil(total / size));
const current = Math.min(Math.max(Math.trunc(page) || 1, 1), pages);
const offset = (current - 1) * size;
const rows_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTORS>({
sql: `SELECT c.* FROM connectors c WHERE ${matches}${filter_sql}
ORDER BY ${connected} DESC, c.name ASC LIMIT ? OFFSET ?`,
values: [...match_values, ...scope.values, size, offset],
});
const rows = rows_res.payload || [];
const ids = rows.map((row) => Number(row.id));
const placeholders = ids.map(() => "?").join(", ");
/**
* The accounts this viewer may see on these apps: their own, and one
* given out (to everyone, or to a workspace or bot they reach). A super
* admin sees every account of the app.
*/
const [accounts, botLinks, workspaceLinks] = await Promise.all([
ids.length
? BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name: string }>({
sql: `SELECT a.*, trim(coalesce(u.first_name, '') || ' ' || coalesce(u.last_name, '')) AS owner_name
FROM connector_accounts a LEFT JOIN users u ON u.id = a.user_id
WHERE a.connector_id IN (${placeholders}) AND ${scope.sql}
ORDER BY a.id ASC`,
values: [...ids, ...scope.values],
})
: Promise.resolve({ payload: [] as (BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name: string })[] }),
ids.length
? BunSQLite.sql<{ connector_id: number; bot_id: number }>({
sql: `SELECT connector_id, bot_id FROM bot_connectors WHERE user_id = ? AND connector_id IN (${placeholders}) ORDER BY connector_id ASC`,
values: [id, ...ids],
})
: Promise.resolve({ payload: [] as { connector_id: number; bot_id: number }[] }),
ids.length
? BunSQLite.sql<{ connector_id: number; workspace_id: number }>({
sql: `SELECT connector_id, workspace_id FROM workspace_connectors WHERE connector_id IN (${placeholders}) ORDER BY connector_id ASC`,
values: [...ids],
})
: Promise.resolve({ payload: [] as { connector_id: number; workspace_id: number }[] }),
]);
const access = new Map<number, { bot_ids: number[]; workspace_ids: number[] }>();
function accessFor(connector_id: number) {
let entry = access.get(connector_id);
if (!entry) {
entry = { bot_ids: [], workspace_ids: [] };
access.set(connector_id, entry);
}
return entry;
}
for (const row of botLinks.payload || []) {
accessFor(Number(row.connector_id)).bot_ids.push(Number(row.bot_id));
}
for (const row of workspaceLinks.payload || []) {
accessFor(Number(row.connector_id)).workspace_ids.push(Number(row.workspace_id));
}
const account_rows = accounts.payload || [];
const scopes = await attachConnectorAccountScopes({
account_ids: account_rows.map((row) => Number(row.id)),
});
return {
items: rows.map((row): ConnectorRecord => parseConnectorRow({ row })),
total,
page: current,
page_size: size,
query: needle,
filter,
counts,
accounts: account_rows.map((row): ConnectorAccountRecord => {
const shared = scopes.get(Number(row.id));
return parseConnectorAccountRow({
row,
workspace_ids: shared?.workspace_ids || [],
bot_ids: shared?.bot_ids || [],
owner_name: row.owner_name || "",
});
}),
access: rows.map((row): ConnectorAccess => ({
connector_id: Number(row.id),
...(access.get(Number(row.id)) || { bot_ids: [], workspace_ids: [] }),
})),
};
}
/**
* The SQL that decides which accounts of these apps the viewer may see, and
* the values it needs after the connector ids.
*/
async function accountVisibility({ user_id }: { user_id: number }) {
if ((await grabCrewRole({ user_id })) == "super_admin") {
return { sql: `1 = 1`, values: [] as number[] };
}
const workspace_ids = (await grabUserWorkspaces({ user_id })).map((workspace) => Number(workspace.id));
const bot_ids = (await grabBots({ user_id })).map((bot) => Number(bot.id));
const workspaces = workspace_ids.length ? workspace_ids.map(() => "?").join(", ") : "0";
const bots = bot_ids.length ? bot_ids.map(() => "?").join(", ") : "0";
return {
sql: `(a.user_id = ? OR a.all_bots = 1
OR EXISTS (SELECT 1 FROM connector_account_workspaces w WHERE w.account_id = a.id AND w.workspace_id IN (${workspaces}))
OR EXISTS (SELECT 1 FROM connector_account_bots b WHERE b.account_id = a.id AND b.bot_id IN (${bots})))`,
values: [user_id, ...workspace_ids, ...bot_ids],
};
}
@@ -0,0 +1,57 @@
import AppError from "@/src/utils/app-error";
import BunSQLite from "@moduletrace/bun-sqlite";
import type { ConnectorProviderId, ConnectorStatus } from "@/src/dict/connector-dict";
type Params = {
connection_id: number | string;
};
export type ConnectorConnectionRow = {
id: number;
provider: ConnectorProviderId;
name: string;
/**
* Encrypted; only `connectorProviderFor` decrypts it.
*/
api_key: string;
status: ConnectorStatus;
last_error: string;
last_synced_at: number | null;
user_id: number;
};
/**
* One provider connection, as stored: two of the same provider (Composio
* Personal, Composio Work) are told apart by their row, and each has its
* own key.
*/
export default async function grabConnectorConnection({ connection_id }: Params): Promise<ConnectorConnectionRow> {
const row = (
await BunSQLite.sql<{
id: number;
provider: string;
name: string;
api_key: string;
status: string;
last_error: string;
last_synced_at: number;
user_id: number;
}>({
sql: `SELECT id, provider, name, api_key, status, last_error, last_synced_at, user_id FROM connector_connections WHERE id = ?`,
values: [Number(connection_id)],
})
).payload?.[0];
if (!row) throw new AppError(`That connector connection doesn't exist.`);
return {
id: Number(row.id),
provider: (row.provider || "composio") as ConnectorProviderId,
name: row.name || "",
api_key: row.api_key || "",
status: (row.status || "untested") as ConnectorStatus,
last_error: row.last_error || "",
last_synced_at: typeof row.last_synced_at == "number" ? row.last_synced_at : null,
user_id: Number(row.user_id),
};
}
@@ -0,0 +1,52 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { ConnectorProviderId, ConnectorStatus } from "@/src/dict/connector-dict";
import type { ConnectorConnectionRecord, ConnectorConnectionsPayload } from "@/src/types";
/**
* The install's provider connections, with how many apps each has and how
* many of those are given out. The apps themselves stay off this read: one
* connection can hold thousands, and the page only lists connections.
*/
export default async function grabConnectorConnections(): Promise<ConnectorConnectionsPayload> {
const res = await BunSQLite.sql<{
id: number;
provider: string;
name: string;
api_key: string;
status: string;
last_error: string;
last_synced_at: number;
app_count: number;
apps_given: number;
}>({
sql: `SELECT c.id, c.provider, c.name, c.api_key, c.status, c.last_error, c.last_synced_at,
(SELECT COUNT(*) FROM connectors x WHERE x.connection_id = c.id) AS app_count,
(SELECT COUNT(*) FROM connectors x
WHERE x.connection_id = c.id
AND (x.all_bots = 1
OR EXISTS (SELECT 1 FROM bot_connectors b WHERE b.connector_id = x.id)
OR EXISTS (SELECT 1 FROM workspace_connectors w WHERE w.connector_id = x.id))) AS apps_given
FROM connector_connections c
ORDER BY c.name ASC`,
});
return {
connections: (res.payload || []).map(
(row): ConnectorConnectionRecord => ({
id: Number(row.id),
provider: (row.provider || "composio") as ConnectorProviderId,
name: row.name || "",
status: (row.status || "untested") as ConnectorStatus,
last_error: row.last_error || "",
last_synced_at: typeof row.last_synced_at == "number" ? row.last_synced_at : null,
/**
* The key is encrypted at rest and never sent to a page, so
* this only says whether one is stored.
*/
has_key: Boolean(String(row.api_key || "").trim()),
app_count: Number(row.app_count || 0),
apps_given: Number(row.apps_given || 0),
}),
),
};
}
@@ -0,0 +1,63 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS } from "@/db/types/db";
import type { ConnectorAccountRecord } from "@/src/types";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import parseConnectorAccountRow from "./parse-connector-account-row";
type Params = {
user_id: number | string;
connector_id: number | string;
bot_id?: number | string;
workspace_id?: number | string;
};
type Row = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string };
/**
* This user's own accounts of one app that are not given here yet, whatever
* their state, with where each one may be used. The tools modal lists them so
* an account can be given to the bot right where it is picked; one already
* given to this bot, to every bot or to this workspace is left out.
*/
export default async function grabConnectorOwnAccounts({
user_id,
connector_id,
bot_id,
workspace_id,
}: Params): Promise<ConnectorAccountRecord[]> {
const bot = Number(bot_id) || 0;
const workspace = Number(workspace_id) || 0;
const rows =
(
await BunSQLite.sql<Row>({
sql: `SELECT a.*, trim(coalesce(u.first_name, '') || ' ' || coalesce(u.last_name, '')) AS owner_name
FROM connector_accounts a
LEFT JOIN users u ON u.id = a.user_id
WHERE a.connector_id = ? AND a.user_id = ?
AND a.all_bots = 0
AND NOT EXISTS (
SELECT 1 FROM connector_account_bots ab
WHERE ab.account_id = a.id AND ab.bot_id = ?
)
AND NOT EXISTS (
SELECT 1 FROM connector_account_workspaces aw
WHERE aw.account_id = a.id AND aw.workspace_id = ?
)
ORDER BY a.id ASC`,
values: [Number(connector_id), Number(user_id), bot, workspace],
})
).payload || [];
const scopes = await attachConnectorAccountScopes({ account_ids: rows.map((row) => Number(row.id)) });
return rows.map((row) => {
const scope = scopes.get(Number(row.id));
return parseConnectorAccountRow({
row,
workspace_ids: scope?.workspace_ids || [],
bot_ids: scope?.bot_ids || [],
owner_name: row.owner_name || "",
});
});
}
@@ -0,0 +1,29 @@
import AppError from "@/src/utils/app-error";
import BunSQLite from "@moduletrace/bun-sqlite";
import connectorProviderFor from "@/src/harness/connectors/connector-provider-for";
import type { ConnectorProvider } from "@/src/harness/connectors/connector-provider";
type Params = {
connector_id: number | string;
};
/**
* The provider adapter for one app's connection: its own key, so the
* catalog, the sign-ins and the tools belong to the connection the app was
* read from (Composio Personal's Gmail, not Composio Work's).
*/
export default async function grabConnectorProvider({ connector_id }: Params): Promise<ConnectorProvider> {
const row = (
await BunSQLite.sql<{ provider: string; name: string; api_key: string }>({
sql: `SELECT k.provider, k.name, k.api_key
FROM connectors c
JOIN connector_connections k ON k.id = c.connection_id
WHERE c.id = ?`,
values: [Number(connector_id)],
})
).payload?.[0];
if (!row) throw new AppError(`That connector doesn't exist.`);
return connectorProviderFor({ connection: { provider: row.provider, name: row.name, api_key: row.api_key } });
}
@@ -0,0 +1,80 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS, BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import parseConnectorAccountRow from "./parse-connector-account-row";
import grabConnector from "./grab-connector";
type Params = {
request_id: number | string;
/**
* The user the card belongs to: a request never shows another's.
*/
user_id: number | string;
};
/**
* A connect request as its card shows it. A pending one past its time is
* marked expired here, so the card says what happened instead of offering a
* link that no longer works.
*/
export default async function grabConnectorRequestView({ request_id, user_id }: Params) {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS>({
sql: `SELECT * FROM connector_requests WHERE id = ? AND user_id = ? LIMIT 1`,
values: [Number(request_id), Number(user_id)],
});
const row = res.payload?.[0];
if (!row) throw new AppError(`That connect request doesn't exist.`);
const connector = await grabConnector({ connector_id: Number(row.connector_id) });
const now = Date.now();
let status = row.status || "pending";
if (status == "pending" && Number(row.expires_at || 0) <= now) {
status = "expired";
await BunSQLite.sql({
sql: `UPDATE connector_requests SET status = 'expired', updated_at = ? WHERE id = ?`,
values: [now, Number(row.id)],
});
}
const request_account = String(row.provider_account_id || "");
// Only the account this request made counts: any connected one would
// close a second sign-in with the first account's label, which is how a
// second Gmail account looked already connected.
const accountRows = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: request_account
? `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' AND provider_account_id = ? LIMIT 1`
: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' AND created_at >= ? ORDER BY id ASC LIMIT 1`,
values: request_account
? [connector.id, Number(user_id), request_account]
: [connector.id, Number(user_id), Number(row.created_at || 0)],
})
).payload || [];
const matching = accountRows[0] || null;
if (status == "pending" && matching) {
status = "connected";
await BunSQLite.sql({
sql: `UPDATE connector_requests SET status = 'connected', provider_account_id = ?, updated_at = ? WHERE id = ?`,
values: [String(matching.provider_account_id || ""), now, Number(row.id)],
});
}
return {
id: Number(row.id),
connector_id: connector.id,
connector_name: connector.name,
label: row.label || "",
status,
url: row.url || "",
expires_at: Number(row.expires_at || 0),
account: matching ? parseConnectorAccountRow({ row: matching }) : null,
};
}
@@ -0,0 +1,24 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import parseConnectorRow from "./parse-connector-row";
type Params = {
connector_id: number | string;
};
/**
* One connector, wherever it's attached.
*/
export default async function grabConnector({ connector_id }: Params) {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTORS>({
sql: `SELECT * FROM connectors WHERE id = ? LIMIT 1`,
values: [Number(connector_id)],
});
const row = res.payload?.[0];
if (!row) throw new AppError(`That connector doesn't exist.`);
return parseConnectorRow({ row });
}
@@ -0,0 +1,87 @@
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 connectorAccountReachSql from "@/src/utils/connector-account-reach-sql";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import parseConnectorAccountRow from "./parse-connector-account-row";
import parseConnectorRow from "./parse-connector-row";
type Params = {
/**
* The user the run is for: their own accounts, and the ones given to
* this place.
*/
user_id: number | string;
bot_id: number | string;
workspace_id?: number | string | null;
};
export type RunConnector = {
connector: ConnectorRecord;
/**
* The accounts the run may use for it: the user's own, every connected
* account of a connector given to this workspace, and every one given to
* this bot, this workspace or every bot. Empty means nothing to call
* with: the card asks them to connect one.
*/
accounts: ConnectorAccountRecord[];
};
type AccountRow = BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS & { owner_name?: string };
/**
* The connectors one run reaches (`botConnectorsSql`) with the accounts it
* 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.
*/
export default async function grabRunConnectors({ user_id, bot_id, workspace_id }: Params): Promise<RunConnector[]> {
const found =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTORS>(
botConnectorsSql({ bot_id, user_id, workspace_id }),
)
).payload || [];
if (!found.length) return [];
const connectors = found.map((row) => parseConnectorRow({ row }));
const ids = connectors.map((connector) => connector.id);
const workspace_reach = connectorAccountReachSql({ workspace_id });
const rows =
(
await BunSQLite.sql<AccountRow>({
sql: `SELECT a.*, trim(coalesce(u.first_name, '') || ' ' || coalesce(u.last_name, '')) AS owner_name
FROM connector_accounts a
LEFT JOIN users u ON u.id = a.user_id
WHERE a.connector_id IN (${ids.map(() => "?").join(", ")})
AND a.status = 'connected'
AND (
a.user_id = ?
OR a.all_bots = 1
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}
)
ORDER BY a.id ASC`,
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0), ...workspace_reach.values],
})
).payload || [];
const scopes = await attachConnectorAccountScopes({ account_ids: rows.map((row) => Number(row.id)) });
const accounts = rows.map((row) =>
parseConnectorAccountRow({
row,
workspace_ids: scopes.get(Number(row.id))?.workspace_ids || [],
bot_ids: scopes.get(Number(row.id))?.bot_ids || [],
owner_name: row.owner_name || "",
}),
);
return connectors.map((connector) => ({
connector,
accounts: accounts.filter((account) => account.connector_id == connector.id),
}));
}
@@ -0,0 +1,41 @@
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS } from "@/db/types/db";
import type { ConnectorAccountStatus } from "@/src/dict/connector-dict";
import type { ConnectorAccountRecord } from "@/src/types";
type Params = {
row: BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS;
/**
* Where it has been given to, read beside the row.
*/
workspace_ids?: number[];
bot_ids?: number[];
owner_name?: string;
};
/**
* A `connector_accounts` row as the app reads it. The account's credential
* stays at the provider; this is only which of the user's accounts it is.
*/
export default function parseConnectorAccountRow({
row,
workspace_ids = [],
bot_ids = [],
owner_name = "",
}: Params): ConnectorAccountRecord {
return {
id: Number(row.id),
connector_id: Number(row.connector_id),
user_id: Number(row.user_id),
label: row.label || "",
slug: row.slug || "",
provider_account_id: row.provider_account_id || "",
status: (row.status || "pending") as ConnectorAccountStatus,
is_default: row.is_default == 1,
all_bots: row.all_bots == 1,
workspace_ids,
bot_ids,
owner_name,
connected_at: typeof row.connected_at == "number" ? row.connected_at : null,
last_error: row.last_error || "",
};
}
@@ -0,0 +1,35 @@
import type { BUN_SQLITE_COBBLE_CONNECTORS } from "@/db/types/db";
import type { ConnectorProviderId, ConnectorStatus } from "@/src/dict/connector-dict";
import type { ConnectorRecord, McpToolInfo } from "@/src/types";
import parseJsonColumn from "../extensions/parse-json-column";
type Params = {
row: BUN_SQLITE_COBBLE_CONNECTORS;
};
/**
* A `connectors` row with its JSON columns read. Nothing here is secret:
* the account is what signs in, and the key belongs to its connection row.
*/
export default function parseConnectorRow({ row }: Params): ConnectorRecord {
return {
id: Number(row.id),
provider: (row.provider || "composio") as ConnectorProviderId,
connection_id: Number(row.connection_id),
app: row.app || "",
name: row.name || "",
slug: row.slug || "",
description: row.description || "",
logo: row.logo || "",
auth_config_id: row.auth_config_id || null,
scopes: parseJsonColumn<string[]>({ text: row.scopes, fallback: [] }),
excluded_tools: parseJsonColumn<string[]>({ text: row.excluded_tools, fallback: [] }),
tools: parseJsonColumn<McpToolInfo[]>({ text: row.tools_cache, fallback: [] }),
all_bots: row.all_bots == 1,
enabled: row.enabled != 0,
status: (row.status || "untested") as ConnectorStatus,
last_error: row.last_error || "",
last_synced_at: typeof row.last_synced_at == "number" ? row.last_synced_at : null,
user_id: Number(row.user_id),
};
}
@@ -0,0 +1,101 @@
import { describe, expect, test } from "bun:test";
import planConnectorSync from "./plan-connector-sync";
type AppParams = {
app: string;
name?: string;
description?: string;
logo?: string;
scopes?: string[] | null;
};
const app = ({ app, name = "", description = "", logo = "", scopes = null }: AppParams) => ({
app,
name,
description,
logo,
scopes,
});
const connection = { id: 3, provider: "composio" as const, name: "Composio Work" };
describe("planConnectorSync", () => {
test("stores an app the connection doesn't have, with a lowercase slug", () => {
const plan = planConnectorSync({
connection,
apps: [app({ app: "gmail", name: "Gmail", description: "Mail", logo: "https://x/g.png", scopes: ["mail"] })],
existing: [],
taken: [],
});
expect(plan.inserts).toEqual([
{
provider: "composio",
connection_id: 3,
app: "gmail",
name: "Gmail",
slug: "gmail",
description: "Mail",
logo: "https://x/g.png",
scopes: ["mail"],
user_id: 0,
},
]);
expect(plan.updates).toEqual([]);
});
test("names the app after its connection when another one already took the slug", () => {
const plan = planConnectorSync({
connection,
apps: [app({ app: "gmail", name: "Gmail" })],
existing: [],
taken: ["gmail"],
});
expect(plan.inserts[0]!.slug).toBe("gmail-composio-work");
});
test("two apps of the same name in one sync get different slugs", () => {
const plan = planConnectorSync({
connection,
apps: [app({ app: "gmail", name: "Gmail" }), app({ app: "gmail-work", name: "Gmail" })],
existing: [],
taken: [],
});
expect(plan.inserts.map((row) => row.slug)).toEqual(["gmail", "gmail-composio-work"]);
});
test("an app already stored only updates when its wording moved", () => {
const plan = planConnectorSync({
connection,
apps: [
app({ app: "slack", name: "Slack", description: "Chat" }),
app({ app: "gmail", name: "Gmail", description: "Mail" }),
],
existing: [
{ app: "slack", name: "Slack", description: "Chat", logo: "" },
{ app: "gmail", name: "Gmail", description: "Old", logo: "" },
],
taken: [],
});
expect(plan.inserts).toEqual([]);
expect(plan.updates).toEqual([{ app: "gmail", name: "Gmail", description: "Mail", logo: "" }]);
});
test("falls back to the app's id for its name and stores no scopes as empty", () => {
const plan = planConnectorSync({
connection,
apps: [app({ app: "stripe" })],
existing: [],
taken: [],
});
expect(plan.inserts[0]!.name).toBe("stripe");
expect(plan.inserts[0]!.slug).toBe("stripe");
expect(plan.inserts[0]!.scopes).toEqual([]);
expect(plan.inserts[0]!.user_id).toBe(0);
expect(plan.inserts[0]!.connection_id).toBe(3);
});
});
@@ -0,0 +1,133 @@
import type { ConnectorApp } from "@/src/harness/connectors/connector-provider";
import type { ConnectorProviderId } from "@/src/dict/connector-dict";
import connectorSlug from "@/src/utils/connector-slug";
type Connection = {
id: number;
provider: ConnectorProviderId;
name: string;
};
type ExistingRow = {
app: string;
name: string;
description: string;
logo: string;
};
type Params = {
connection: Connection;
apps: ConnectorApp[];
existing: ExistingRow[];
/**
* Every slug the install already uses, so a new app never takes one.
*/
taken: string[];
};
/**
* One row to insert for an app the connection offers that isn't stored yet.
*/
export type PlannedConnector = {
provider: ConnectorProviderId;
connection_id: number;
app: string;
name: string;
slug: string;
description: string;
logo: string;
scopes: string[];
user_id: number;
};
export type ConnectorSyncPlan = {
/**
* Apps this connection doesn't have yet, each with the slug its tools
* use.
*/
inserts: PlannedConnector[];
/**
* Stored apps whose name, description or logo the provider changed.
* Their slug, reach, accounts and tools stay as they are.
*/
updates: ExistingRow[];
};
/**
* What a provider sync changes: the apps to store for the first time, and
* the stored ones whose wording moved. Pure, so the merge is tested without
* a database.
*
* The same app through two connections is two rows: the second never takes
* the slug the first one's tools already use, so it gets its connection in
* the name (`gmail-work`) and only then a number.
*/
export default function planConnectorSync({ connection, apps, existing, taken }: Params): ConnectorSyncPlan {
const stored = new Map(existing.map((row) => [row.app, row]));
const used = new Set(taken);
const inserts: PlannedConnector[] = [];
const updates: ExistingRow[] = [];
const connection_slug = connectorSlug({ name: connection.name });
for (const app of apps) {
const row = stored.get(app.app);
if (!row) {
const name = app.name || app.app;
const base = connectorSlug({ name });
inserts.push({
provider: connection.provider,
connection_id: connection.id,
app: app.app,
name,
slug: freeSlug({ base, connection_slug, used }),
description: app.description,
logo: app.logo,
scopes: app.scopes || [],
user_id: 0,
});
continue;
}
if (row.name != app.name || row.description != app.description || row.logo != app.logo) {
updates.push({ app: app.app, name: app.name, description: app.description, logo: app.logo });
}
}
return { inserts, updates };
}
type SlugParams = {
base: string;
connection_slug: string;
used: Set<string>;
};
/**
* A slug for one of the connection's apps. When another connector already
* took the app's own name, the connection names it (`gmail-work`), and a
* number after that only when even that is used.
*/
function freeSlug({ base, connection_slug, used }: SlugParams) {
const candidates = [base, `${base}-${connection_slug}`];
const first_free = candidates.find((candidate) => !used.has(candidate));
if (first_free) {
used.add(first_free);
return first_free;
}
const stem = base.slice(0, 12);
for (let index = 2; index < 1000; index++) {
const candidate = `${stem}-${index}`;
if (!used.has(candidate)) {
used.add(candidate);
return candidate;
}
}
throw new Error(`Too many connectors share the name ${base}.`);
}
@@ -0,0 +1,56 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { SaveConnectorAccountRequest } from "@/src/schemas/connector-schema";
import AppError from "@/src/utils/app-error";
import connectorSlug from "@/src/utils/connector-slug";
import grabCrewRole from "../access/grab-crew-role";
import grabConnectorAccount from "./grab-connector-account";
type Params = {
user_id: number | string;
data: SaveConnectorAccountRequest;
};
/**
* Renames one sign-in: what the bot calls it, which is how a person tells
* their two accounts apart. The owner does it; a super admin may do it on
* anyone's account.
*/
export default async function saveConnectorAccount({ user_id, data }: Params) {
const account = await grabConnectorAccount({
account_id: data.account_id,
user_id: Number(user_id),
any_owner: true,
});
const role = await grabCrewRole({ user_id });
if (role != "super_admin" && account.user_id != Number(user_id)) {
throw new AppError(`Only the account's owner or a super admin can rename it.`);
}
const label = data.label.trim().slice(0, 80);
if (!label) throw new AppError(`Give the account a name, e.g. Work Gmail.`);
const taken =
(
await BunSQLite.sql<{ slug: string }>({
sql: `SELECT slug FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND id != ?`,
values: [account.connector_id, account.user_id, account.id],
})
).payload || [];
const used = new Set(taken.map((row) => row.slug).filter(Boolean));
const base = connectorSlug({ name: label });
let slug = base;
let suffix = 2;
while (used.has(slug)) {
slug = `${base.slice(0, 12)}-${suffix}`;
suffix += 1;
}
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET label = ?, slug = ?, updated_at = ? WHERE id = ?`,
values: [label, slug, Date.now(), account.id],
});
return { ...account, label, slug };
}
@@ -0,0 +1,84 @@
import AppError from "@/src/utils/app-error";
import BunSQLite from "@moduletrace/bun-sqlite";
import { ConnectorProviders, type ConnectorProviderId } from "@/src/dict/connector-dict";
import { encrypt } from "@/src/utils/crypt";
type Params = {
/**
* The row to change; left out to add a connection.
*/
connection_id?: number | null;
provider: string;
name: string;
/**
* A new key. Left out when editing keeps the stored one, which is never
* sent back to the page.
*/
api_key?: string;
user_id: number | string;
};
export type SavedConnectorConnection = {
id: number;
provider: ConnectorProviderId;
name: string;
};
/**
* Adds or renames a provider connection, with its own key: Composio
* Personal and Composio Work are two rows, so each lists the apps its key
* holds. The key is encrypted before it is stored and never read back to a
* page.
*/
export default async function saveConnectorConnection({ connection_id, provider, name, api_key, user_id }: Params): Promise<SavedConnectorConnection> {
const preset = ConnectorProviders.find((entry) => entry.value == provider);
if (!preset) throw new AppError(`This install has no connector provider called "${provider}".`);
const clean_name = name.trim().slice(0, 80);
if (!clean_name) throw new AppError(`Give the connection a name, e.g. ${preset.title} Work.`);
const taken = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM connector_connections WHERE name = ? COLLATE NOCASE AND id != ?`,
values: [clean_name, Number(connection_id || 0)],
})
).payload?.[0];
if (taken) throw new AppError(`A connection called "${clean_name}" already exists.`);
if (connection_id) {
await BunSQLite.sql({
sql: api_key
? `UPDATE connector_connections SET name = ?, api_key = ?, status = 'untested', last_error = '', updated_at = ? WHERE id = ?`
: `UPDATE connector_connections SET name = ?, updated_at = ? WHERE id = ?`,
values: api_key
? [clean_name, await encrypt(api_key.trim()), Date.now(), Number(connection_id)]
: [clean_name, Date.now(), Number(connection_id)],
});
return { id: Number(connection_id), provider: preset.value, name: clean_name };
}
if (!api_key?.trim()) throw new AppError(`Paste the ${preset.title} key this connection uses.`);
const now = Date.now();
await BunSQLite.sql({
sql: `INSERT INTO connector_connections (created_at, updated_at, name, provider, api_key, status, last_error, user_id)
VALUES (?, ?, ?, ?, ?, 'untested', '', ?)`,
values: [now, now, clean_name, preset.value, await encrypt(api_key.trim()), Number(user_id)],
});
const created = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM connector_connections WHERE name = ?`,
values: [clean_name],
})
).payload?.[0];
const id = Number(created?.id || 0);
if (!id) throw new AppError(`Couldn't store the connection.`);
return { id, provider: preset.value, name: clean_name };
}
@@ -0,0 +1,46 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import grabUserBot from "../bots/grab-user-bot";
import grabConnector from "./grab-connector";
import syncConnector from "./sync-connector";
type Params = {
user_id: number | string;
bot_id: number | string;
connector_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 connector to a bot: it shows in their runs
* there and in nobody else's. Shared reach is a workspace or global
* connector, which only a super admin sets.
*/
export default async function setBotConnector({ user_id, bot_id, connector_id, attached }: Params) {
const [bot, connector] = await Promise.all([
grabUserBot({ bot_id, user_id }),
grabConnector({ connector_id }),
]);
if (!bot) throw new AppError(`You don't reach that bot.`);
const now = Date.now();
const res = attached
? await BunSQLite.sql({
sql: `INSERT OR IGNORE INTO bot_connectors (created_at, updated_at, bot_id, user_id, connector_id) VALUES (?, ?, ?, ?, ?)`,
values: [now, now, Number(bot.id), Number(user_id), connector.id],
})
: await BunSQLite.sql({
sql: `DELETE FROM bot_connectors WHERE bot_id = ? AND user_id = ? AND connector_id = ?`,
values: [Number(bot.id), Number(user_id), connector.id],
});
if (!res.success) throw new Error(`Couldn't change the bot's connectors: ${res.error}`);
if (attached && !connector.tools.length) await syncConnector({ connector_id: connector.id });
return { bot, connector };
}
@@ -0,0 +1,47 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { SaveConnectorAccessRequest } from "@/src/schemas/connector-schema";
import assertSuperAdmin from "../access/assert-super-admin";
import grabConnector from "./grab-connector";
import syncConnector from "./sync-connector";
type Params = {
user_id: number | string;
data: SaveConnectorAccessRequest;
};
/**
* Makes a connector global (every bot, every user) or gives it to these
* workspaces. A super admin's alone: a bot attachment is a person's own and
* goes through `setBotConnector`, so bot rows are never touched here.
*/
export default async function setConnectorAccess({ user_id, data }: Params) {
await assertSuperAdmin({ user_id });
const connector = await grabConnector({ connector_id: data.connector_id });
const now = Date.now();
await BunSQLite.sql({ sql: `DELETE FROM workspace_connectors WHERE connector_id = ?`, values: [connector.id] });
for (const workspace_id of new Set(data.workspace_ids)) {
await BunSQLite.sql({
sql: `INSERT OR IGNORE INTO workspace_connectors (created_at, updated_at, workspace_id, connector_id)
SELECT ?, ?, id, ? FROM workspaces WHERE id = ?`,
values: [now, now, connector.id, workspace_id],
});
}
if (data.all_bots !== undefined) {
await BunSQLite.sql({
sql: `UPDATE connectors SET all_bots = ?, updated_at = ? WHERE id = ?`,
values: [data.all_bots ? 1 : 0, now, connector.id],
});
} else {
await BunSQLite.sql({ sql: `UPDATE connectors SET updated_at = ? WHERE id = ?`, values: [now, connector.id] });
}
if ((data.all_bots || data.workspace_ids.length) && !connector.tools.length) {
await syncConnector({ connector_id: connector.id });
}
return grabConnector({ connector_id: connector.id });
}
@@ -0,0 +1,86 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { SaveConnectorAccountAccessRequest } from "@/src/schemas/connector-schema";
import assertSuperAdmin from "../access/assert-super-admin";
import grabCrewRole from "../access/grab-crew-role";
import grabUserBot from "../bots/grab-user-bot";
import grabUserWorkspace from "../workspaces/grab-user-workspace";
import attachConnectorAccountScopes from "./attach-connector-account-scopes";
import grabConnector from "./grab-connector";
import grabConnectorAccount from "./grab-connector-account";
import syncConnector from "./sync-connector";
type Params = {
user_id: number | string;
data: SaveConnectorAccountAccessRequest;
};
/**
* Where one sign-in may be used: its owner's runs always, and every run in
* these workspaces or on these bots, or everywhere. The owner sets it, and
* a super admin may set it on anyone's account. A member can only give an
* account to places they reach themselves.
*/
export default async function setConnectorAccountAccess({ user_id, data }: Params) {
const account = await grabConnectorAccount({ account_id: data.account_id, user_id: Number(user_id), any_owner: true });
const role = await grabCrewRole({ user_id });
if (role != "super_admin" && account.user_id != Number(user_id)) {
throw new Error(`Only the account's owner or a super admin can change where it is used.`);
}
const workspace_ids = [...new Set(data.workspace_ids.map((id) => Number(id)))];
const bot_ids = [...new Set(data.bot_ids.map((id) => Number(id)))];
if (role != "super_admin") {
for (const workspace_id of workspace_ids) {
await grabUserWorkspace({ user_id, workspace_id });
}
for (const bot_id of bot_ids) {
await grabUserBot({ user_id, bot_id });
}
}
const now = Date.now();
await BunSQLite.sql({
sql: `DELETE FROM connector_account_workspaces WHERE account_id = ?`,
values: [account.id],
});
await BunSQLite.sql({ sql: `DELETE FROM connector_account_bots WHERE account_id = ?`, values: [account.id] });
for (const workspace_id of workspace_ids) {
await BunSQLite.sql({
sql: `INSERT OR IGNORE INTO connector_account_workspaces (created_at, updated_at, account_id, workspace_id)
SELECT ?, ?, ?, id FROM workspaces WHERE id = ?`,
values: [now, now, account.id, workspace_id],
});
}
for (const bot_id of bot_ids) {
await BunSQLite.sql({
sql: `INSERT OR IGNORE INTO connector_account_bots (created_at, updated_at, account_id, bot_id)
SELECT ?, ?, ?, id FROM bots WHERE id = ?`,
values: [now, now, account.id, bot_id],
});
}
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET all_bots = ?, updated_at = ? WHERE id = ?`,
values: [data.all_bots ? 1 : 0, now, account.id],
});
const connector = await grabConnector({ connector_id: account.connector_id });
if (!connector.tools.length) {
await syncConnector({ connector_id: account.connector_id });
}
const updated = await grabConnectorAccount({ account_id: account.id, user_id: account.user_id });
const scopes = await attachConnectorAccountScopes({ account_ids: [account.id] });
return {
...updated,
workspace_ids: scopes.get(account.id)?.workspace_ids || [],
bot_ids: scopes.get(account.id)?.bot_ids || [],
};
}
@@ -0,0 +1,64 @@
import { describe, expect, test } from "bun:test";
import shouldAdoptConnectorAccount from "@/src/functions/backend/db/connectors/should-adopt-connector-account";
describe("shouldAdoptConnectorAccount", () => {
test("adopts a connected account into the app's free card", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: true })).toBe(
true,
);
});
test("leaves a second connected account at the provider once the card is taken", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: false })).toBe(
false,
);
});
test("adopts a connected account a request here started, even with no free card", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true, free_slot: false })).toBe(
true,
);
});
test("adopts a pending account a request here started", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true, free_slot: false })).toBe(
true,
);
});
test("adopts a pending account that reconnects a row", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false, free_slot: false })).toBe(
true,
);
});
test("skips a pending account nothing here started", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false, free_slot: true })).toBe(
false,
);
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false, free_slot: true })).toBe(
false,
);
});
test("skips a stranger once the provider lists none of the app's accounts", () => {
expect(
shouldAdoptConnectorAccount({
status: "connected",
reconnect: false,
claimed: false,
free_slot: true,
wiped: true,
}),
).toBe(false);
expect(
shouldAdoptConnectorAccount({
status: "connected",
reconnect: false,
claimed: true,
free_slot: true,
wiped: true,
}),
).toBe(true);
});
});
@@ -0,0 +1,41 @@
import type { ProviderAccountStatus } from "@/src/harness/connectors/connector-provider";
type Params = {
status: ProviderAccountStatus;
/** A pending request is reconnecting this very account. */
reconnect: boolean;
/** A pending request here started this sign-in. */
claimed: boolean;
/**
* Whether the app has no live account here yet: one card per app is
* filled by the provider's account, and any other account arrives through
* its own sign-in (claimed).
*/
free_slot: boolean;
/**
* The provider lists none of the accounts the app knows: they were
* replaced there, so no stranger takes their place (the cards offer
* Reconnect instead).
*/
wiped?: boolean;
};
/**
* Whether a provider account becomes a local row. One a request here started
* (or is reconnecting) always does. A connected one the app doesn't know
* gets the app's one free card, so leftovers from earlier sign-ins at the
* provider can't pile up as four rows of the same mailbox; a second account
* appears by signing in again, which claims its own row.
*/
export default function shouldAdoptConnectorAccount({
status,
reconnect,
claimed,
free_slot,
wiped = false,
}: Params) {
if (reconnect || claimed) return true;
if (wiped) return false;
return status == "connected" && free_slot;
}
@@ -0,0 +1,67 @@
import type { ConnectorAccountRecord, ConnectorRequestPayload } from "@/src/types";
import AppError from "@/src/utils/app-error";
import createConnectorRequest from "./create-connector-request";
import grabConnector from "./grab-connector";
import grabConnectorRequestView from "./grab-connector-request-view";
import syncConnectorAccounts from "./sync-connector-accounts";
type Params = {
user_id: number | string;
connector_id: number | string;
/**
* What the user calls the account they're connecting, e.g. Work Gmail.
*/
label?: string;
/**
* The account this sign-in reconnects, when one went dead. Its row is
* updated in place once the provider lists the new sign-in, so it keeps
* its label and its tool namespace.
*/
account_id?: number | string;
bot_id?: number | string;
session_id?: number | string;
};
type Result = {
/**
* The sign-in link. Always made: a person can keep several accounts on
* one app (a work Gmail beside a personal one), so an account already
* connected never stands in for the new one.
*/
request: ConnectorRequestPayload | null;
accounts: ConnectorAccountRecord[];
};
/**
* Starts a sign-in for one connector. The request outlives the page that
* made it, so the card under a reply and Settings > Connectors both read it
* the same way.
*/
export default async function startConnectorConnection({
user_id,
connector_id,
label,
account_id,
bot_id,
session_id,
}: Params): Promise<Result> {
const connector = await grabConnector({ connector_id });
if (!connector.enabled) throw new AppError(`${connector.name} is turned off, so it can't be connected right now.`);
const accounts = await syncConnectorAccounts({ user_id, connector_id: connector.id, label });
const request = await createConnectorRequest({
user_id: Number(user_id),
connector,
label,
account_id: account_id ? Number(account_id) : undefined,
bot_id: bot_id ? Number(bot_id) : undefined,
session_id: session_id ? Number(session_id) : undefined,
});
return {
request: await grabConnectorRequestView({ request_id: request.id, user_id }),
accounts,
};
}
@@ -0,0 +1,21 @@
/**
* The row an id-less reconnect replaces. The production fault this pins:
* 0.27.6 fell back to the one dead row with the requested name, so a new
* mailbox that arrived while a dead row existed took that row's label and
* namespace. Only a pending request that names a row may hand it over.
*/
import { expect, test } from "bun:test";
import { pendingReconnectRow } from "./sync-connector-accounts";
test("an id-less reconnect names the row its request does", () => {
expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "" }])).toBe(5);
});
test("a reconnect the provider gave an id for is not an id-less one", () => {
expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "ca_new" }])).toBeNull();
});
test("a plain sign-in (no row) and no request name nothing", () => {
expect(pendingReconnectRow([])).toBeNull();
expect(pendingReconnectRow([{ account_id: 0, provider_account_id: "" }])).toBeNull();
});
@@ -0,0 +1,344 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS } from "@/db/types/db";
import grabConnectorProvider from "./grab-connector-provider";
import type { ProviderAccount } from "@/src/harness/connectors/connector-provider";
import type { ConnectorAccountRecord } from "@/src/types";
import connectorSlug from "@/src/utils/connector-slug";
import grabConnector from "./grab-connector";
import parseConnectorAccountRow from "./parse-connector-account-row";
import shouldAdoptConnectorAccount from "./should-adopt-connector-account";
type Params = {
user_id: number | string;
connector_id: number | string;
/**
* The name the user typed for the account when they started the
* sign-in, used only when the provider gives none.
*/
label?: string;
};
/**
* Reads the user's accounts for a connector at its provider and brings the
* local rows in line: new sign-ins are added (the first connected one is the
* default), ones the provider reports expired say so, and ones it no longer
* lists are marked revoked without losing their label. Pending connect
* requests are closed as soon as the account they made is connected.
*
* One card per app unless the user signed in again: an account the provider
* holds but no request here made fills the app's free card once and is left
* at the provider after that, so a pile of earlier sign-ins cannot arrive as
* four rows of the same mailbox.
*/
export default async function syncConnectorAccounts({ user_id, connector_id, label }: Params) {
const connector = await grabConnector({ connector_id });
const provider = await grabConnectorProvider({ connector_id: connector.id });
const accounts = await provider.accounts({ app: connector.app, user_id: Number(user_id) });
const local = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? ORDER BY id ASC`,
values: [connector.id, Number(user_id)],
})
).payload || [];
const requests = (
await BunSQLite.sql<{ account_id: number; provider_account_id: string }>({
sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending'`,
values: [connector.id, Number(user_id)],
})
).payload || [];
const reconnect_for = new Map(
requests
.filter((row) => Number(row.account_id) != 0 && row.provider_account_id)
.map((row) => [String(row.provider_account_id), Number(row.account_id)]),
);
let reconnect_row = pendingReconnectRow(requests);
// A row disconnected since is no target: that sign-in arrives as a new one.
if (reconnect_row && !local.some((row) => Number(row.id) == reconnect_row)) reconnect_row = null;
/**
* A sign-in only becomes a row once it is connected, or while the request
* that started it is still open. A pending account nothing here asked for
* is an abandoned or replaced sign-in at the provider (Composio keeps one
* `INITIALIZING` per abandoned link), and adopting it would put a second,
* never connected account beside the one a reconnect replaced.
*/
const claimed = new Set(requests.map((row) => String(row.provider_account_id || "")).filter(Boolean));
const seen = new Set(accounts.map((account) => account.provider_account_id));
const now = Date.now();
/**
* The provider lists none of the accounts the app knows: they were
* replaced there (a sign-in made outside the app), so its leftover takes
* no card and the known ones offer Reconnect.
*/
const wiped = local.length > 0 && !local.some((row) => seen.has(String(row.provider_account_id || "")));
/**
* The app's one free card: a live row still listed by the provider holds
* it. An account arriving without a sign-in here (an older attempt at
* the provider) may fill it once, never pile up beside it.
*/
let free_slot = !local.some((row) => row.status == "connected" && seen.has(String(row.provider_account_id || "")));
/**
* A listing that names no account is the provider unable to answer, not
* every account deleted there: revoking them all would put Reconnect on
* cards that are fine.
*/
if (accounts.length) {
for (const row of local) {
if (seen.has(String(row.provider_account_id || ""))) continue;
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
values: [now, now, Number(row.id)],
});
}
}
let firstConnected: number | null = free_slot ? 0 : null;
for (const account of accounts) {
const provider_account_id = String(account.provider_account_id);
const reconnect_id = reconnect_for.get(provider_account_id);
if (
!shouldAdoptConnectorAccount({
status: account.status,
reconnect: Boolean(reconnect_id) || (account.status == "connected" && Boolean(reconnect_row)),
claimed: claimed.has(provider_account_id),
free_slot,
wiped,
})
)
continue;
await upsertAccount({
connector_id: connector.id,
user_id: Number(user_id),
account,
fallback_label: label,
reconnect_id,
reconnect_row: account.status == "connected" ? reconnect_row : null,
});
if (account.status == "connected" && reconnect_row) reconnect_row = null;
if (account.status != "connected") continue;
if (free_slot) free_slot = false;
if (firstConnected === 0) {
const created = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`,
values: [connector.id, Number(user_id), account.provider_account_id],
})
).payload?.[0];
if (created) firstConnected = created.id;
}
}
if (firstConnected && firstConnected > 0) {
await BunSQLite.sql({ sql: `UPDATE connector_accounts SET is_default = 1 WHERE id = ?`, values: [firstConnected] });
}
const connected_ids = accounts
.filter((account) => account.status == "connected")
.map((account) => account.provider_account_id)
.filter(Boolean);
if (connected_ids.length) {
await settleRequests({
connector_id: connector.id,
user_id: Number(user_id),
provider_account_ids: connected_ids,
});
}
return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_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);
return Number(named?.account_id || 0) || null;
}
type UpsertParams = {
connector_id: number;
user_id: number;
account: ProviderAccount;
fallback_label?: string;
/**
* The row a reconnect replaces: its provider id is gone, so the new
* sign-in takes its place instead of arriving as a second account.
*/
reconnect_id?: number;
/**
* That row when the provider gave the sign-in no id at all: the request
* names it, so it's never guessed from a name or a sole dead row, which
* would hand a new mailbox the dead one's label and namespace.
*/
reconnect_row?: number | null;
};
async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id, reconnect_row }: UpsertParams) {
const now = Date.now();
if (reconnect_id) {
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ?
WHERE id = ? AND connector_id = ? AND user_id = ?`,
values: [
account.provider_account_id,
account.status,
account.status == "connected" ? now : null,
now,
now,
reconnect_id,
connector_id,
user_id,
],
});
return;
}
const existing = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`,
values: [connector_id, user_id, account.provider_account_id],
})
).payload?.[0];
if (existing) {
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = ?, label = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? WHERE id = ?`,
values: [
account.status,
account.label || String(existing.label || ""),
account.status == "connected"
? Number(existing.connected_at) || now
: existing.connected_at
? Number(existing.connected_at)
: null,
now,
now,
Number(existing.id),
],
});
return;
}
/**
* An id-less reconnect lands on the row it replaces, named by its request.
* A row that is merely dead is not it: a new mailbox that arrives while
* one dead row exists would otherwise take that row's name and namespace.
* Only a connected account takes it, since an abandoned link at the
* provider stays pending, and only once.
*/
if (reconnect_row) {
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ?
WHERE id = ? AND connector_id = ? AND user_id = ?`,
values: [
account.provider_account_id,
account.status,
account.status == "connected" ? now : null,
now,
now,
reconnect_row,
connector_id,
user_id,
],
});
return;
}
const taken = (
await BunSQLite.sql<{ slug: string }>({
sql: `SELECT slug FROM connector_accounts WHERE connector_id = ? AND user_id = ?`,
values: [connector_id, user_id],
})
).payload?.map((row) => row.slug) || [];
const display_name = account.label || fallback_label || "Account";
let slug = connectorSlug({ name: display_name, max: 12, fallback: "account" });
for (let index = 2; taken.includes(slug); index++) {
slug = `${connectorSlug({ name: display_name, max: 8, fallback: "account" })}-${index}`;
}
await BunSQLite.sql({
sql: `INSERT INTO connector_accounts
(created_at, updated_at, connector_id, user_id, label, slug, provider_account_id, status, is_default, connected_at, last_checked_at, last_error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, '')`,
values: [
now,
now,
connector_id,
user_id,
display_name,
slug,
account.provider_account_id,
account.status,
account.status == "connected" ? now : null,
now,
],
});
}
type SettleParams = {
connector_id: number;
user_id: number;
provider_account_ids: string[];
};
/**
* A connect request is done only when the account it made is connected: a
* second sign-in must not be closed by the first account that was already
* there (`provider_account_id` is what the provider returned for this link).
* A request the provider gave no id for falls back to an account created
* after the request.
*/
async function settleRequests({ connector_id, user_id, provider_account_ids }: SettleParams) {
const now = Date.now();
const placeholders = provider_account_ids.map(() => "?").join(", ");
await BunSQLite.sql({
sql: `UPDATE connector_requests SET status = 'connected', updated_at = ?
WHERE connector_id = ? AND user_id = ? AND status = 'pending'
AND expires_at > ?
AND (
(provider_account_id != '' AND provider_account_id IN (${placeholders}))
OR (provider_account_id == '' AND EXISTS (
SELECT 1 FROM connector_accounts a
WHERE a.connector_id = connector_requests.connector_id
AND a.user_id = connector_requests.user_id
AND a.status = 'connected'
AND (a.created_at >= connector_requests.created_at OR a.id = connector_requests.account_id)
))
)`,
values: [now, connector_id, user_id, now, ...provider_account_ids],
});
}
type GrabParams = {
connector_id: number;
user_id: number;
};
async function grabUserAccounts({ connector_id, user_id }: GrabParams): Promise<ConnectorAccountRecord[]> {
const rows = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? ORDER BY id ASC`,
values: [connector_id, user_id],
})
).payload || [];
return rows.map((row) => parseConnectorAccountRow({ row }));
}
@@ -0,0 +1,141 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { ConnectorProviderId } from "@/src/dict/connector-dict";
import redactSecrets from "@/src/utils/redact-secrets";
import grabRunEnvs from "../extensions/grab-run-envs";
import grabConnectorConnection from "./grab-connector-connection";
import grabConnectionProvider from "./grab-connection-provider";
import planConnectorSync from "./plan-connector-sync";
type Params = {
connection_id: number | string;
/**
* The super admin syncing it, kept as the connection's owner. A cron
* sync leaves it out and the existing owner stays.
*/
user_id?: number | string;
};
type ExistingRow = {
app: string;
name: string;
description: string;
logo: string;
};
/**
* Connects a provider: reads its apps and stores them as connectors, so
* every app it offers shows in Settings > Connectors without anyone adding
* one. The connection row keeps the outcome for the page and the cron. An
* app already stored keeps its slug, its reach and its accounts; only its
* name, description and logo follow the provider.
*
* A connection is one provider account with its own key, so two Composio
* connections list two separate sets of apps, and each app row belongs to
* the connection it was read from.
*/
export default async function syncConnectorConnection({ connection_id, user_id }: Params) {
const now = Date.now();
const connection = await grabConnectorConnection({ connection_id });
try {
const provider = await grabConnectionProvider({ connection_id: connection.id });
const apps = await provider.listApps();
await storeApps({ connection, apps, now });
await BunSQLite.sql({
sql: `UPDATE connector_connections SET status = 'ready', last_error = '', last_synced_at = ?, updated_at = ?, user_id = ? WHERE id = ?`,
values: [now, now, user_id ? Number(user_id) : connection.user_id, connection.id],
});
return { ok: true as const, app_count: apps.length };
} catch (error: unknown) {
const envs = await grabRunEnvs();
const message = redactSecrets({
text: error instanceof Error ? error.message : String(error),
secrets: envs.filter((env) => env.secret),
}).slice(0, 4000);
await BunSQLite.sql({
sql: `UPDATE connector_connections SET status = 'error', last_error = ?, last_synced_at = ?, updated_at = ? WHERE id = ?`,
values: [message, now, now, connection.id],
});
return { ok: false as const, error: message, app_count: 0 };
}
}
type StoreParams = {
connection: { id: number; provider: ConnectorProviderId; name: string };
apps: Awaited<ReturnType<Awaited<ReturnType<typeof grabConnectionProvider>>["listApps"]>>;
now: number;
};
/**
* Writes the connection's apps as connectors: a new one gets a slug no other
* connector has, and an existing one only takes the provider's current
* name, description and logo. Several hundred rows go in chunks, in one
* statement each.
*/
async function storeApps({ connection, apps, now }: StoreParams) {
const existing =
(
await BunSQLite.sql<ExistingRow>({
sql: `SELECT app, name, description, logo FROM connectors WHERE connection_id = ?`,
values: [connection.id],
})
).payload || [];
const taken =
(
await BunSQLite.sql<{ slug: string }>({
sql: `SELECT slug FROM connectors`,
})
).payload?.map((row) => row.slug) || [];
const plan = planConnectorSync({
connection,
apps,
existing,
taken,
});
for (let index = 0; index < plan.inserts.length; index += 40) {
const chunk = plan.inserts.slice(index, index + 40);
const values: (string | number)[] = [];
for (const row of chunk) {
values.push(
now,
now,
row.provider,
row.connection_id,
row.app,
row.name,
row.slug,
row.description,
row.logo,
JSON.stringify(row.scopes),
0,
1,
"untested",
"",
row.user_id,
);
}
await BunSQLite.sql({
sql: `INSERT OR IGNORE INTO connectors
(created_at, updated_at, provider, connection_id, app, name, slug, description, logo, scopes, all_bots, enabled, status, last_error, user_id)
VALUES ${chunk.map(() => "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}`,
values,
});
}
for (const app of plan.updates) {
await BunSQLite.sql({
sql: `UPDATE connectors SET name = ?, description = ?, logo = ?, updated_at = ? WHERE connection_id = ? AND app = ?`,
values: [app.name || app.app, app.description, app.logo, now, connection.id, app.app],
});
}
}
@@ -0,0 +1,45 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import grabConnectorProvider from "./grab-connector-provider";
import redactSecrets from "@/src/utils/redact-secrets";
import grabRunEnvs from "../extensions/grab-run-envs";
import grabConnector from "./grab-connector";
type Params = {
connector_id: number | string;
};
/**
* Lists the app's tools at its provider and saves them, which is what runs
* build their tools from. Saves the outcome on the connector (`status`,
* `last_error`, secrets blanked out) and returns it; never throws for the
* provider's own failure.
*/
export default async function syncConnector({ connector_id }: Params) {
const connector = await grabConnector({ connector_id });
const envs = await grabRunEnvs();
const now = Date.now();
try {
const provider = await grabConnectorProvider({ connector_id: connector.id });
const tools = await provider.listTools({ app: connector.app });
await BunSQLite.sql({
sql: `UPDATE connectors SET tools_cache = ?, status = 'ready', last_error = '', last_synced_at = ? WHERE id = ?`,
values: [JSON.stringify(tools), now, connector.id],
});
return { ok: true as const, tools };
} catch (error: unknown) {
const message = redactSecrets({
text: error instanceof Error ? error.message : String(error),
secrets: envs.filter((env) => env.secret),
}).slice(0, 4000);
await BunSQLite.sql({
sql: `UPDATE connectors SET status = 'error', last_error = ?, last_synced_at = ? WHERE id = ?`,
values: [message, now, connector.id],
});
return { ok: false as const, error: message };
}
}
@@ -20,10 +20,10 @@ import saveSkill from "../extensions/save-skill";
import grabKnowledgebasesOverview from "../knowledgebases/grab-knowledgebases-overview";
import recordKnowledgebaseDocument from "../knowledgebases/record-knowledgebase-document";
import saveKnowledgebase from "../knowledgebases/save-knowledgebase";
import extensionItemSchema from "./extension-item-schemas";
import extensionItemSchema from "@/src/utils/extension-item-schema";
import normalizeExtensionConfig from "@/src/utils/normalize-extension-config";
import grabExistingExtensionItems from "./grab-existing-extension-items";
import matchExtensionItem, { type ExistingExtensionItem } from "./match-extension-item";
import normalizeExtensionConfig from "./normalize-extension-config";
import uniqueCopyName from "./unique-copy-name";
type Params = {
@@ -7,11 +7,11 @@ import type {
ExtensionImportStatus,
} from "@/src/types";
import hasEnvTemplate from "@/src/utils/has-env-template";
import extensionItemSchema from "./extension-item-schemas";
import extensionItemSchema from "@/src/utils/extension-item-schema";
import normalizeExtensionConfig from "@/src/utils/normalize-extension-config";
import grabExistingExtensionItems from "./grab-existing-extension-items";
import matchExtensionItem, { type ExistingExtensionItem } from "./match-extension-item";
import missingEnvKeys from "./missing-env-keys";
import normalizeExtensionConfig from "./normalize-extension-config";
type Params = {
bundle: ExtensionBundle;
@@ -1,6 +1,8 @@
import BunSQLite from "@moduletrace/bun-sqlite";
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 grabExtensionsOverview from "./grab-extensions-overview";
type Params = {
@@ -31,9 +33,27 @@ export default async function grabBotExtensionsOverview({
BunSQLite.sql<{ kind: string }>({ sql: `SELECT kind FROM bots WHERE id = ?`, values: [bot_id] }),
]);
return grabExtensionsOverview({
can_manage: role == "super_admin" || (role == "admin" && bot.payload?.[0]?.kind != "coordinator"),
bot_id,
workspace_id,
});
const [overview, connector_count, connector_entries] = await Promise.all([
grabExtensionsOverview({
can_manage: role == "super_admin" || (role == "admin" && bot.payload?.[0]?.kind != "coordinator"),
bot_id,
workspace_id,
}),
countBotConnectors({ user_id, bot_id, workspace_id }),
grabBotConnectors({ 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.
*/
const connector_apps = connector_entries
.filter((entry) => entry.accounts.some((account) => account.status == "connected"))
.map((entry) => ({
id: Number(entry.connector.id),
name: entry.connector.name,
logo: entry.connector.logo,
}));
return { ...overview, connector_count, connector_apps };
}
@@ -4,6 +4,7 @@ import buildCustomTool from "@/src/harness/tools/custom/build-custom-tool";
import AppError from "@/src/utils/app-error";
import type { DraftCustomTool } from "@/src/schemas/extension-schema";
import type { CustomToolRecord } from "@/src/types";
import grabComputerEnvs from "../envs/grab-computer-envs";
import grabCustomTool from "./grab-custom-tool";
import grabRunEnvs from "./grab-run-envs";
@@ -49,7 +50,18 @@ export default async function testCustomTool({ custom_tool_id, draft, args, comp
(await BunSQLite.sql<{ id: number }>({ sql: `SELECT id FROM computers WHERE kind = 'main' ORDER BY id LIMIT 1` }))
.payload?.[0]?.id;
const harness_tool = buildCustomTool({ tool, envs: await grabRunEnvs(), computer_id: main, record: !draft });
const envs = await grabRunEnvs();
/**
* The same arguments a bot's run would fill: its computer's envs count
* too, by name, when the tool reads one as `{{env.KEY}}`.
*/
const arg_envs = [
...new Map(
[...(main ? await grabComputerEnvs({ computer_id: main }) : []), ...envs].map((env) => [env.key, env]),
).values(),
];
const harness_tool = buildCustomTool({ tool, envs, arg_envs, computer_id: main, record: !draft });
if (!harness_tool) throw new AppError(`There's no computer to run this script on.`);
@@ -56,6 +56,7 @@ export default async function grabHarnessModelEntries({
voices: model.voices,
input_modalities: model.input_modalities,
supported_parameters: model.supported_parameters,
context_length: model.context_length,
},
};
});
@@ -14,6 +14,13 @@ export type RunUsageLimits = {
steps: RunLimit | null;
run_tokens: RunLimit | null;
context_tokens: RunLimit | null;
/**
* How much of the working context the app's own prompt and tool
* definitions took before the conversation did, when the run recorded
* them: the usual answer to "why was there room for so little".
*/
system_tokens?: number;
tools_tokens?: number;
};
/**
@@ -137,6 +144,8 @@ const limitsOf = ({ calls }: { calls: RunUsageCall[] }): RunUsageLimits | null =
steps: kept(limits.steps),
run_tokens: kept(limits.run_tokens),
context_tokens: kept(limits.context_tokens),
...(typeof limits.system_tokens == "number" ? { system_tokens: limits.system_tokens } : {}),
...(typeof limits.tools_tokens == "number" ? { tools_tokens: limits.tools_tokens } : {}),
};
};
@@ -202,27 +202,3 @@ export function canSeePath({ resolved, path }: { resolved: ResolvedStorageSpec;
function joinPath({ relative, name }: { relative: string; name: string }) {
return relative ? `${relative}/${name}` : name;
}
/**
* The breadcrumb trail of a folder, from the volume's top: one crumb per
* segment, each with the address that opens it.
*/
export function storageBreadcrumbs({
spec,
path: relative,
}: {
spec: StorageSpec;
path?: string | null;
}) {
const segments = (relative || "").split("/").filter(Boolean);
const crumbs = [{ name: "", href: storageSpecHref({ spec }) }];
for (let i = 1; i <= segments.length; i++) {
crumbs.push({
name: segments[i - 1] || "",
href: storageSpecHref({ spec, path: segments.slice(0, i).join("/") }),
});
}
return crumbs;
}
+2 -1
View File
@@ -27,7 +27,8 @@ type Params = {
/**
* Turns speech into text with the transcription harness: its
* speech-to-text model gets the file at `/audio/transcriptions`.
* speech-to-text model gets the file, at `/audio/transcriptions` or, on
* Alibaba's hosts, at their native multimodal route.
*/
export default async function transcribeAudio({
audio,
@@ -0,0 +1,14 @@
import { expect, test } from "bun:test";
import connectorAccountGoneMessage from "./connector-account-gone";
test("names the account, the provider and where to reconnect", () => {
const message = connectorAccountGoneMessage({
connector_name: "Gmail",
label: "Benoti Sanchez Gmail",
provider_title: "Composio",
});
expect(message).toContain('The Gmail account "Benoti Sanchez Gmail"');
expect(message).toContain("no longer exists at Composio");
expect(message).toContain("Settings > Connectors");
});
@@ -0,0 +1,16 @@
type Params = {
connector_name: string;
label: string;
provider_title: string;
};
/**
* A row can outlive the account it names: a sign-in is deleted at the
* provider (a second one replaced it, a connection was cleared there) while
* the local row still says connected. Pinning that id would make the provider
* fall back to whatever account it does have, so the run would answer from a
* mailbox nobody chose. The tool refuses instead, naming the fix.
*/
export default function connectorAccountGoneMessage({ connector_name, label, provider_title }: Params) {
return `The ${connector_name} account "${label}" no longer exists at ${provider_title}, so this didn't run. Reconnect it in Settings > Connectors.`;
}
@@ -0,0 +1,177 @@
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";
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.
*/
account: ConnectorAccountRecord | null;
onMissingAccount?: () => Promise<string>;
/**
* The app's slug, or `<app slug>-<account slug>` once the user has more
* than one account for it: what the tools are named under.
*/
namespace: string;
/**
* 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.
*/
export default function connectorAccountTools({
connector,
provider,
user_id,
account,
onMissingAccount,
namespace,
names,
redact,
takeAction,
signal,
}: Params): ConnectorAccountTools {
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 });
if (names.has(name)) continue;
names.add(name);
tools.push({
name,
description: `${connector.name}${account ? ` (${account.label})` : ""}: ${tool.description || tool.name}`,
parameters: tool.input_schema,
deferred: true,
run: async ({ args, signal: runSignal }) => {
if (!account) {
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 {
tools,
close: async () => {
if (!connection) return;
await (await connection.catch(() => null))?.close().catch(() => {});
},
};
}
@@ -0,0 +1,43 @@
import AppError from "@/src/utils/app-error";
import { decrypt } from "@/src/utils/crypt";
import { ConnectorProviders } from "@/src/dict/connector-dict";
import type { ConnectorProvider } from "./connector-provider";
import composioConnectorProvider from "./providers/composio";
type Params = {
/**
* The `connector_connections` row the provider is built for: its id,
* provider, shown name and encrypted key. One provider can be connected
* several times (Composio Personal, Composio Work), each with its own
* key, so the connection, not the provider, decides which account's
* catalog and sign-ins are used.
*/
connection: {
provider: string;
name: string;
api_key: string;
};
};
/**
* The adapter for one connection, with its own key decrypted here and
* nowhere else. A missing key is a sentence a tool result or the settings
* page can show, never a silent no-op.
*/
export default async function connectorProviderFor({ connection }: Params): Promise<ConnectorProvider> {
const preset = ConnectorProviders.find((entry) => entry.value == connection.provider);
if (!preset) throw new AppError(`This install has no connector provider called "${connection.provider}".`);
const key = connection.api_key ? (await decrypt(connection.api_key)).trim() : "";
if (!key) {
throw new AppError(
`The ${preset.title} connection "${connection.name}" has no key yet, so its apps can't be used. A super admin can add one in Settings > Connectors.`,
);
}
if (preset.value == "composio") return composioConnectorProvider({ key, base_url: preset.base_url });
throw new AppError(`${preset.title} isn't available in this version.`);
}
@@ -0,0 +1,128 @@
/**
* What the app asks of a connector's provider. One provider is one file
* under `providers/` and one entry in `ConnectorProviders`.
*
* Everything here is per account: the endpoint a run's tools live at is
* bound to one of its user's connected accounts, which is why a user with
* two Gmail accounts gets two sets of tools.
*/
export type ConnectorApp = {
/**
* The provider's own app id, e.g. gmail.
*/
app: string;
name: string;
description: string;
/**
* The provider's logo URL for it, when it gives one.
*/
logo: string;
scopes: string[] | null;
};
export type ConnectorTool = {
/**
* The provider's own tool name, e.g. GMAIL_SEND_EMAIL.
*/
name: string;
description: string;
input_schema: Record<string, unknown>;
};
export type ProviderAccountStatus = "connected" | "pending" | "expired";
export type ProviderAccount = {
provider_account_id: string;
status: ProviderAccountStatus;
/**
* What the provider knows the account by, when it says: an address, a
* workspace name. Never a credential.
*/
label?: string;
};
export type ConnectorEndpoint = {
url: string;
headers: Record<string, string>;
session_id?: string;
/**
* Unix ms, when the provider says. Null means it didn't.
*/
expires_at?: number;
};
export type StartConnectParams = {
app: string;
user_id: number;
label: string;
auth_config_id?: string | null;
/**
* Where the provider sends the user back to once they finish. Left out
* when the install has no public address to send them to: the card and
* Settings > Connectors then find out by asking (`accounts`), which works
* either way.
*/
callback_url?: string;
};
export type StartedConnect = {
url: string;
/**
* The provider's id for the account it made, when it says up front. A
* request keeps it, so the account that appears is the one it meant.
*/
provider_account_id?: string;
/**
* The provider's sign-in setup the link belongs to (an auth config at
* Composio), so it can be kept and reused rather than made again.
*/
auth_config_id?: string;
/**
* Unix ms, when the provider says the link stops working.
*/
expires_at?: number;
};
export type ConnectorProvider = {
/** Apps this install may add, with what the provider says about each. */
listApps(): Promise<ConnectorApp[]>;
/** One app's tools as the provider lists them, for a bot to call. */
listTools({ app }: { app: string }): Promise<ConnectorTool[]>;
/**
* Where one account's tools live, for one user: an MCP endpoint and the
* headers it wants. Creates or reuses the provider's session.
*/
endpoint({
app,
user_id,
account,
tools,
}: {
app: string;
user_id: number;
account: string;
tools: string[];
}): Promise<ConnectorEndpoint>;
/** Start a sign-in. Returns the URL to send the user to. */
startConnect(params: StartConnectParams): Promise<StartedConnect>;
/** The user's accounts for the app, as the provider has them. */
accounts({ app, user_id }: { app: string; user_id: number }): Promise<ProviderAccount[]>;
/** Forget one account at the provider. Local rows are the caller's. */
revoke({ account }: { account: string }): Promise<void>;
/**
* Call one tool over the provider's REST API, with the account named in
* the call. The fallback for an endpoint that can't be pinned to one
* account; the model sees the same tool either way.
*/
execute({
tool,
args,
account,
user_id,
}: {
tool: string;
args: Record<string, unknown>;
account: string;
user_id: number;
}): Promise<unknown>;
};
@@ -0,0 +1,176 @@
import BunSQLite from "@moduletrace/bun-sqlite";
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 { decrypt, encrypt } from "@/src/utils/crypt";
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
import connectorAccountGoneMessage from "./connector-account-gone";
import type { ConnectorProvider } from "./connector-provider";
/**
* When each account was last checked against the provider, per process: the
* check is a listing of every account the user has, and a cached session is
* used many times a minute.
*/
const accountChecks = new Map<string, number>();
const AccountCheckEveryMs = 5 * 60 * 1000;
/**
* The endpoint one account's tools live at, cached in `connector_sessions`
* because asking the provider costs a call and the session expires.
*
* `rest` is the fallback for a provider whose session can't be pinned to
* one account: the same tools, executed through the provider's REST API
* with the account named in each call. It's remembered for
* `AppData.ConnectorRestRetryMs`, then the session is tried again.
*/
export type ConnectorEndpointResult =
| { kind: "mcp"; url: string; headers: Record<string, string> }
| { kind: "rest" };
type Params = {
connector: ConnectorRecord;
provider: ConnectorProvider;
user_id: number;
account: ConnectorAccountRecord;
};
/**
* A cached session's headers, or null when the stored copy can't be read.
* Null means the cache is unusable, never that the endpoint wants no
* headers: a session read as "no key" once reached the provider keyless and
* every tool came back with a 401, so a broken copy is rebuilt instead.
*/
async function readCachedHeaders({ headers }: { headers: string | null }): Promise<Record<string, string> | null> {
if (!headers) return null;
try {
const parsed = JSON.parse(await decrypt(headers));
return parsed && typeof parsed == "object" && !Array.isArray(parsed)
? (parsed as Record<string, string>)
: null;
} catch {
return null;
}
}
/**
* A row can name an account the provider no longer has (a second sign-in
* replaced it, a connection was cleared there). A session pinned to that id
* is not refused: the provider answers from whichever account it does have,
* so a bot read a mailbox the user never chose. The row is marked revoked
* (its card then offers Reconnect) and the call stops instead.
*
* The check lists every account the user has, so it is remembered per account
* for `AccountCheckEveryMs`: a cached session is checked too, at that pace
* rather than on every tool call.
*/
async function assertAccountStillThere({ connector, provider, user_id, account, now }: Params & { now: number }) {
const key = `${connector.id}:${account.provider_account_id}`;
if (now - (accountChecks.get(key) || 0) < AccountCheckEveryMs) return;
if (accountChecks.size > 1000) accountChecks.clear();
accountChecks.set(key, now);
let accounts: Awaited<ReturnType<ConnectorProvider["accounts"]>>;
try {
accounts = await provider.accounts({ app: connector.app, user_id });
} catch {
// The provider is the one to say why the session failed; a list that
// can't be read is not proof the account is gone.
return;
}
if (accounts.some((entry) => entry.provider_account_id == account.provider_account_id)) return;
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
values: [now, now, Number(account.id)],
});
const provider_title =
ConnectorProviders.find((entry) => entry.value == connector.provider)?.title || connector.provider;
throw new AppError(
connectorAccountGoneMessage({
connector_name: connector.name,
label: account.label,
provider_title,
}),
);
}
export default async function ensureConnectorEndpoint({
connector,
provider,
user_id,
account,
}: Params): Promise<ConnectorEndpointResult> {
const now = Date.now();
await assertAccountStillThere({ connector, provider, user_id, account, now });
const cached = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS>({
sql: `SELECT * FROM connector_sessions WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`,
values: [connector.id, user_id, account.provider_account_id],
})
).payload?.[0];
if (cached && Number(cached.expires_at ?? 0) > now) {
if (cached.session_id == "rest") return { kind: "rest" };
if (cached.mcp_url) {
const headers = await readCachedHeaders({
headers: cached.headers || null,
});
if (headers) {
return { kind: "mcp", url: cached.mcp_url, headers };
}
}
}
const tools = connector.tools
.map((tool) => tool.name)
.filter((name) => !connector.excluded_tools.includes(name));
let session_id: string | null = null;
let url = "";
let headers = "{}";
let expires_at = now + AppData.ConnectorSessionTtlMs;
try {
const endpoint = await provider.endpoint({
app: connector.app,
user_id,
account: account.provider_account_id,
tools,
});
session_id = endpoint.session_id || null;
url = endpoint.url;
headers = await encrypt(JSON.stringify(endpoint.headers || {}));
expires_at = endpoint.expires_at || expires_at;
} catch {
// 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_id = "rest";
expires_at = now + AppData.ConnectorRestRetryMs;
}
await BunSQLite.sql({
sql: `INSERT OR REPLACE INTO connector_sessions (connector_id, user_id, provider_account_id, session_id, mcp_url, headers, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
values: [connector.id, user_id, account.provider_account_id, session_id, url || null, headers, expires_at],
});
if (session_id == "rest" || !url) return { kind: "rest" };
return { kind: "mcp", url, headers: JSON.parse(await decrypt(headers)) };
}
@@ -0,0 +1,83 @@
import { describe, expect, test } from "bun:test";
import expandPreviewResult from "./expand-preview-result";
function previewText() {
return JSON.stringify({
data: {
results: [
{
response: {
data_preview: {
messages: [{ messageId: "a" }, { messageId: "b" }, "...8 more items"],
},
next_steps: "Write code to parse the saved response.",
},
},
],
},
});
}
const whole = { messages: [{ messageId: "a" }, { messageId: "b" }] };
describe("expandPreviewResult", () => {
test("asks the provider again and returns the whole result", async () => {
let calls = 0;
const text = await expandPreviewResult({
text: previewText(),
retry: async () => {
calls += 1;
return whole;
},
});
expect(calls).toBe(1);
expect(JSON.parse(text)).toEqual(whole);
});
test("keeps the preview's note when the retry fails", async () => {
const text = await expandPreviewResult({
text: previewText(),
retry: async () => {
throw new Error("401 API key is required");
},
});
expect(text).toContain("2 of 10 items are here");
});
test("keeps the preview's note when there is no retry to make", async () => {
const text = await expandPreviewResult({ text: previewText() });
expect(text).toContain("2 of 10 items are here");
});
test("rewrites a retry that came back cut as well", async () => {
const text = await expandPreviewResult({
text: previewText(),
retry: async () => ({ data_preview: { messages: [{ messageId: "a" }, "...9 more items"] } }),
});
expect(text).toContain("1 of 10 items are here");
expect(text).not.toContain("data_preview");
});
test("leaves a whole answer alone and asks nothing", async () => {
let calls = 0;
const text = JSON.stringify(whole);
const answer = await expandPreviewResult({
text,
retry: async () => {
calls += 1;
return whole;
},
});
expect(answer).toBe(text);
expect(calls).toBe(0);
});
});
@@ -0,0 +1,41 @@
import previewResult from "./preview-result";
type Params = {
text: string;
/**
* The same call over the provider's REST API, which answers with the whole
* result its MCP router cut. Left out when the text already came from
* REST, or when there is nothing left to ask.
*/
retry?: () => Promise<unknown>;
};
/**
* A provider's preview replaced by the whole result when the provider can
* still give it, and by an honest account of what is missing when it can't.
*
* A retry runs only for an answer that was cut, and costs one more action of
* the same tool, so most answers pay nothing.
*/
export default async function expandPreviewResult({ text, retry }: Params): Promise<string> {
const seen = previewResult({ text });
if (!seen.preview) return text;
if (retry) {
try {
const full = await retry();
if (full != null) {
const whole = typeof full == "string" ? full : JSON.stringify(full, null, 2);
const again = previewResult({ text: whole });
return again.preview ? again.text : whole;
}
} catch {
// Best effort: the preview's own note still says what is missing.
}
}
return seen.text;
}
@@ -0,0 +1,89 @@
import { describe, expect, test } from "bun:test";
import previewResult from "./preview-result";
function gmailMessage({ id }: { id: string }) {
return {
messageId: id,
threadId: id,
labelIds: ["CATEGORY_PROMOTIONS", "...1 more items"],
subject: `Subject ${id}`,
preview: { body: `Body ${id}` },
};
}
/**
* The answer Composio's MCP router gave a Gmail fetch of 10 messages: two of
* them, a marker for the other eight, and instructions to parse a file the
* app never receives.
*/
function gmailPreview() {
return {
successful: true,
data: {
results: [
{
response: {
successful: true,
data_preview: {
messages: [
gmailMessage({ id: "1a201de2616a75cd" }),
gmailMessage({ id: "1a201dc5ff69132f" }),
"...8 more items",
],
nextPageToken: "token",
resultSizeEstimate: 201,
},
tool_slug: "GMAIL_FETCH_EMAILS",
index: 0,
structure_info: {
data_structure: { properties: { messages: { type: "array", length: 10 } } },
},
next_steps: "Write code to parse the saved response and run the analysis.",
},
error: null,
log_id: "log-1",
},
],
},
};
}
describe("previewResult", () => {
test("says how much of a preview is missing and keeps the items", () => {
const result = previewResult({ text: JSON.stringify(gmailPreview()) });
expect(result.preview).toBe(true);
if (!result.preview) throw new Error("expected a preview");
expect(result.text).toContain("2 of 10 items are here");
expect(result.text).toContain("the other 8 were cut");
expect(result.text).toContain("1a201de2616a75cd");
expect(result.text).toContain("1a201dc5ff69132f");
expect(result.text).not.toContain("structure_info");
expect(result.text).not.toContain("next_steps");
expect(result.text).not.toContain("log_id");
expect(result.text).not.toContain("saved response");
});
test("leaves a whole result alone", () => {
const result = previewResult({
text: JSON.stringify({ messages: [{ messageId: "a" }, { messageId: "b" }] }),
});
expect(result).toEqual({ preview: false });
});
test("leaves a non-JSON answer alone", () => {
expect(previewResult({ text: "Gmail: two messages" })).toEqual({ preview: false });
});
test("says only part is here when the preview marks nothing as cut", () => {
const result = previewResult({ text: JSON.stringify({ data_preview: { messages: [] } }) });
if (!result.preview) throw new Error("expected a preview");
expect(result.text).toContain("only part of it is here");
expect(result.text).toContain("never an empty result");
});
});
+125
View File
@@ -0,0 +1,125 @@
/**
* Composio's hosted MCP router cuts a large tool result down to a preview:
* `data` becomes `data_preview`, holding a couple of the items, a
* "...N more items" marker and instructions to parse a "saved response"
* that a programmatic client never gets, plus `structure_info`, `next_steps`
* and a `log_id`. Read as the whole answer it looks like an empty inbox (a
* Gmail fetch of 10 messages came back as 2, and a bot reported that the
* account had only those two), so a run that got a preview is told what it
* actually holds instead (ComposioHQ/composio#5025).
*/
export type PreviewResult = { preview: false } | { preview: true; text: string };
const MoreItems = /^\.\.\.(\d+) more items$/;
type Elision = {
/** Items the provider kept. */
shown: number;
/** Items the provider cut. */
left_out: number;
};
/**
* The biggest cut in the tree: the array the provider truncated most (the
* messages of a fetch, not the few label ids elided on each one).
*/
function largestElision({ value }: { value: unknown }): Elision {
let largest: Elision = { shown: 0, left_out: 0 };
const visit = (node: unknown) => {
if (Array.isArray(node)) {
let shown = 0;
let left_out = 0;
for (const item of node) {
const match = typeof item == "string" ? MoreItems.exec(item) : null;
if (match) left_out += Number(match[1]);
else if (item != null) shown += 1;
}
if (left_out > largest.left_out) largest = { shown, left_out };
for (const item of node) visit(item);
return;
}
if (node && typeof node == "object") {
for (const item of Object.values(node as Record<string, unknown>)) visit(item);
}
};
visit(value);
return largest;
}
/**
* Every `data_preview` the tree carries. The preview itself is not walked:
* only the key names it as cut.
*/
function collectPreviews({ value }: { value: unknown }): unknown[] {
const previews: unknown[] = [];
const visit = (node: unknown) => {
if (Array.isArray(node)) {
for (const item of node) visit(item);
return;
}
if (!node || typeof node != "object") return;
for (const [key, item] of Object.entries(node as Record<string, unknown>)) {
if (key == "data_preview") previews.push(item);
else visit(item);
}
};
visit(value);
return previews;
}
function previewNote({ previews }: { previews: unknown[] }): string {
const { shown, left_out } = largestElision({ value: previews });
const count = left_out
? `${shown} of ${shown + left_out} items are here and the other ${left_out} were cut before they reached you`
: "only part of it is here";
return [
`The provider returned a preview, not the whole result: ${count}.`,
"This is a truncated sample, never the total and never an empty result: ask again for a smaller page (fewer results, no message payload, or ids only) to see the rest.",
].join(" ");
}
/**
* The text a run should see in place of the provider's answer: the preview
* rewritten to say how much of the result is missing, or `preview: false`
* when the answer is the whole one.
*
* `structure_info`, `next_steps` and `log_id` are dropped with the envelope:
* they describe the preview, and `next_steps` sends a run looking for a file
* the app never receives.
*/
export default function previewResult({ text }: { text: string }): PreviewResult {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return { preview: false };
}
const previews = collectPreviews({ value: parsed });
if (!previews.length) return { preview: false };
return {
preview: true,
text: [previewNote({ previews }), ...previews.map((preview) => JSON.stringify(preview, null, 2))].join("\n\n"),
};
}
@@ -0,0 +1,308 @@
import { describe, expect, test } from "bun:test";
import composioConnectorProvider from "./composio";
type Call = {
url: URL;
method: string;
body: any;
headers: Record<string, string>;
};
function stub({ answer }: { answer: (call: Call) => { status?: number; body: unknown } }) {
const calls: Call[] = [];
const fetchImpl = (async (input: any, init?: RequestInit) => {
const url = new URL(String(input));
const body = init?.body ? JSON.parse(String(init.body)) : null;
const call: Call = {
url,
method: init?.method || "GET",
body,
headers: (init?.headers || {}) as Record<string, string>,
};
calls.push(call);
const result = answer(call);
return new Response(JSON.stringify(result.body), {
status: result.status ?? 200,
headers: { "Content-Type": "application/json" },
});
}) as unknown as typeof fetch;
return { fetchImpl, calls };
}
describe("composioConnectorProvider", () => {
test("lists apps and pages until there is no cursor", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url }) =>
url.searchParams.get("cursor")
? { body: { items: [{ slug: "slack", name: "Slack", meta: { description: "Chat" } }] } }
: { body: { items: [{ slug: "gmail", name: "Gmail", meta: { scopes: ["mail"] } }], next_cursor: "n2" } },
});
const apps = await composioConnectorProvider({ key: "k", fetchImpl }).listApps();
expect(apps).toEqual([
{ app: "gmail", name: "Gmail", description: "", logo: "", scopes: ["mail"] },
{ app: "slack", name: "Slack", description: "Chat", logo: "", scopes: null },
]);
expect(calls[0]!.url.pathname).toBe("/api/v3.1/toolkits");
expect(calls[0]!.headers["x-api-key"]).toBe("k");
expect(calls[1]!.url.searchParams.get("cursor")).toBe("n2");
});
test("lists one app's tools", async () => {
const { fetchImpl, calls } = stub({
answer: () => ({
body: {
items: [
{
slug: "GMAIL_SEND_EMAIL",
description: "Send an email",
input_parameters: { type: "object", properties: {} },
},
],
},
}),
});
const tools = await composioConnectorProvider({ key: "k", fetchImpl }).listTools({ app: "gmail" });
expect(tools[0]!.name).toBe("GMAIL_SEND_EMAIL");
expect(calls[0]!.url.searchParams.get("toolkit_slug")).toBe("gmail");
});
test("asks for a session pinned to the account and the app's tools", async () => {
const { fetchImpl, calls } = stub({
answer: () => ({ body: { session_id: "s1", mcp: { url: "https://mcp/x", headers: { "x-a": "1" } } } }),
});
const endpoint = await composioConnectorProvider({ key: "k", fetchImpl }).endpoint({
app: "gmail",
user_id: 4,
account: "ca_1",
tools: ["GMAIL_SEND_EMAIL"],
});
expect(endpoint.url).toBe("https://mcp/x");
expect(endpoint.session_id).toBe("s1");
expect(endpoint.headers).toEqual({ "x-api-key": "k", "x-a": "1" });
expect(calls[0]!.url.pathname).toBe("/api/v3.1/tool_router/session");
expect(calls[0]!.body.user_id).toBe("cobble-user-4");
expect(calls[0]!.body.connected_accounts).toEqual({ gmail: ["ca_1"] });
expect(calls[0]!.body.tools).toEqual({ gmail: { enable: ["GMAIL_SEND_EMAIL"] } });
expect(calls[0]!.body.manage_connections).toEqual({ enable: false });
});
test("a session without an mcp endpoint is an error the run can read", async () => {
const { fetchImpl } = stub({ answer: () => ({ body: { session_id: "s1" } }) });
await expect(
composioConnectorProvider({ key: "k", fetchImpl }).endpoint({
app: "gmail",
user_id: 4,
account: "ca_1",
tools: [],
}),
).rejects.toThrow("no MCP endpoint");
});
test("a refused key names the setting to fix", async () => {
const { fetchImpl } = stub({
answer: () => ({ status: 401, body: { error: { message: "Invalid API key" } } }),
});
await expect(composioConnectorProvider({ key: "bad", fetchImpl }).listApps()).rejects.toThrow(
"Check this connection's key in Settings > Connectors.",
);
});
test("a consumer key says it is not a project key", async () => {
const { fetchImpl } = stub({
answer: () => ({ status: 401, body: { error: { message: "Invalid API key" } } }),
});
await expect(
composioConnectorProvider({ key: "ck_abcdefghijklmnopqrstu12", fetchImpl }).listApps(),
).rejects.toThrow("consumer key for connect.composio.dev/mcp");
});
test("starts a sign-in with the app's sign-in setup and keeps what the provider returns", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url, method }) => {
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/tool_router/session/trs_1/link")) {
return { status: 201, body: { redirect_url: "https://connect/x", connected_account_id: "ca_9", expires_at: "2027-01-01T00:00:00Z" } };
}
return method == "GET" ? { body: { items: [{ id: "ac_1", auth_scheme: "OAUTH2" }] } } : { body: {} };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
app: "gmail",
user_id: 4,
label: "Work",
});
expect(started.url).toBe("https://connect/x");
expect(started.auth_config_id).toBe("ac_1");
expect(started.provider_account_id).toBe("ca_9");
expect(started.expires_at).toBe(Date.parse("2027-01-01T00:00:00Z"));
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
expect(session.body.multi_account).toEqual({ enable: true, max_accounts_per_toolkit: 5 });
expect(session.body.auth_configs).toEqual({ gmail: "ac_1" });
const link = calls.find((call) => call.url.pathname.endsWith("/tool_router/session/trs_1/link"))!;
expect(link.body.toolkit).toBe("gmail");
expect(link.body.auth_config_id).toBe("ac_1");
expect(link.body.callback_url).toBeUndefined();
expect(calls.some((call) => call.url.pathname.endsWith("/connected_accounts/link"))).toBe(false);
});
test("makes a managed sign-in setup when the app has none", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url, method }) => {
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/link")) return { status: 201, body: { redirect_url: "https://connect/y" } };
if (!url.pathname.endsWith("/auth_configs")) return { body: {} };
return method == "POST" ? { status: 201, body: { auth_config: { id: "ac_new" } } } : { body: { items: [] } };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
app: "gmail",
user_id: 4,
label: "Work",
});
expect(started.auth_config_id).toBe("ac_new");
const made = calls.find((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")!;
expect(made.body.toolkit).toEqual({ slug: "gmail" });
expect(made.body.use_composio_managed_auth).toBe(true);
});
test("makes a custom sign-in setup for a toolkit Composio manages no credentials for", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url, method }) => {
if (url.pathname.endsWith("/toolkits/gitea")) {
return { body: { composio_managed_auth_schemes: [], auth_config_details: [{ mode: "API_KEY" }] } };
}
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/link")) {
return { status: 201, body: { redirect_url: "https://connect/gitea" } };
}
if (!url.pathname.endsWith("/auth_configs")) return { body: {} };
return method == "POST" ? { status: 201, body: { auth_config: { id: "ac_gitea" } } } : { body: { items: [] } };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
app: "gitea",
user_id: 4,
label: "Self-hosted",
});
expect(started.auth_config_id).toBe("ac_gitea");
const made = calls.find((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")!;
expect(made.body).toEqual({
toolkit: { slug: "gitea" },
auth_config: { type: "use_custom_auth", authScheme: "API_KEY" },
});
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
expect(session.body.auth_configs).toEqual({ gitea: "ac_gitea" });
});
test("reuses a sign-in setup the toolkit can use, whatever its scheme", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url }) => {
if (url.pathname.endsWith("/toolkits/gitea")) {
return { body: { composio_managed_auth_schemes: [], auth_config_details: [{ mode: "API_KEY" }] } };
}
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/link")) {
return { status: 201, body: { redirect_url: "https://connect/gitea" } };
}
return { body: { items: [{ id: "ac_dash", auth_scheme: "API_KEY" }] } };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
app: "gitea",
user_id: 4,
label: "Work",
});
expect(started.auth_config_id).toBe("ac_dash");
expect(calls.some((call) => call.url.pathname.endsWith("/auth_configs") && call.method == "POST")).toBe(false);
});
test("maps account statuses and keeps the provider's id", async () => {
const { fetchImpl, calls } = stub({
answer: () => ({
body: {
items: [
{ id: "ca_1", status: "ACTIVE", account_name: "work@x" },
{ id: "ca_2", status: "EXPIRED" },
],
},
}),
});
const accounts = await composioConnectorProvider({ key: "k", fetchImpl }).accounts({ app: "gmail", user_id: 4 });
expect(accounts).toEqual([
{ provider_account_id: "ca_1", status: "connected", label: "work@x" },
{ provider_account_id: "ca_2", status: "expired", label: undefined },
]);
expect(calls[0]!.url.searchParams.get("toolkit_slugs")).toBe("gmail");
expect(calls[0]!.url.searchParams.get("user_ids")).toBe("cobble-user-4");
expect(calls[0]!.url.searchParams.get("user_id")).toBeNull();
});
test("executes one tool with the account named in the call", async () => {
const { fetchImpl, calls } = stub({ answer: () => ({ body: { successful: true, data: { id: "m1" } } }) });
const result = await composioConnectorProvider({ key: "k", fetchImpl }).execute({
tool: "GMAIL_SEND_EMAIL",
args: { to: "a@b" },
account: "ca_1",
user_id: 4,
});
expect(result).toEqual({ id: "m1" });
expect(calls[0]!.url.pathname).toBe("/api/v3.1/tools/execute/GMAIL_SEND_EMAIL");
expect(calls[0]!.body.connected_account_id).toBe("ca_1");
expect(calls[0]!.body.arguments).toEqual({ to: "a@b" });
});
test("a failed execution says why", async () => {
const { fetchImpl } = stub({
answer: () => ({ body: { successful: false, error: "the account expired" } }),
});
await expect(
composioConnectorProvider({ key: "k", fetchImpl }).execute({
tool: "GMAIL_SEND_EMAIL",
args: {},
account: "ca_1",
user_id: 4,
}),
).rejects.toThrow("the account expired");
});
});
@@ -0,0 +1,381 @@
import AppError from "@/src/utils/app-error";
import type {
ConnectorApp,
ConnectorEndpoint,
ConnectorProvider,
ConnectorTool,
ProviderAccount,
ProviderAccountStatus,
StartConnectParams,
} from "../connector-provider";
type Params = {
/**
* The install's Composio key (Settings, under Environment).
*/
key: string;
/**
* Where its API answers. Tests point it at a stub.
*/
base_url?: string;
fetchImpl?: typeof fetch;
};
const DefaultBaseUrl = "https://backend.composio.dev/api/v3.1";
const PageLimit = 100;
/** Composio keeps one account per app unless a session allows more; 5 is its own ceiling in the docs. */
const MaxAccountsPerToolkit = 5;
const MaxPages = 20;
const Statuses: Record<string, ProviderAccountStatus> = {
ACTIVE: "connected",
INITIALIZING: "pending",
INITIATED: "pending",
EXPIRED: "expired",
INACTIVE: "expired",
FAILED: "expired",
};
/**
* Composio, the first connector provider: it holds the apps, the sign-ins
* and the accounts, and hands a run one MCP endpoint per account
* (`endpoint`). Its REST `tools/execute` is the fallback for an endpoint
* that can't be pinned to the account, and the model's tools are the same
* either way.
*/
export default function composioConnectorProvider({ key, base_url, fetchImpl }: Params): ConnectorProvider {
const base = (base_url || DefaultBaseUrl).replace(/\/$/, "");
const doFetch = fetchImpl || fetch;
/**
* One request, with its arguments in a query string where it takes
* them. A provider error becomes a sentence that names what was being
* done, since the model reads it.
*/
async function request<T>({
path,
method = "GET",
query,
body,
what,
}: {
path: string;
method?: "GET" | "POST" | "DELETE";
query?: Record<string, string | number | undefined>;
body?: unknown;
what: string;
}): Promise<T> {
const url = new URL(`${base}${path}`);
for (const [name, value] of Object.entries(query || {})) {
if (value !== undefined) url.searchParams.set(name, String(value));
}
const response = await doFetch(url, {
method,
headers: {
"x-api-key": key,
"Content-Type": "application/json",
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
let parsed: any = null;
try {
parsed = JSON.parse(text);
} catch {}
if (!response.ok) {
const reason =
parsed?.error?.message || parsed?.error?.suggested_fix || parsed?.message || text.slice(0, 300);
const key_note = key.startsWith("ck_")
? " That is a consumer key for connect.composio.dev/mcp: a connector needs a project API key (ak_...) from the project's Settings > API Keys."
: key.startsWith("uak_")
? " That is a user API key: a connector needs a project API key (ak_...) from the project's Settings > API Keys."
: "";
const hint =
response.status == 401 || response.status == 403
? ` Check this connection's key in Settings > Connectors.${key_note}`
: "";
throw new AppError(`Composio refused ${what} (HTTP ${response.status}): ${reason}.${hint}`);
}
return (parsed ?? ({} as T)) as T;
}
async function listAllPages<T>({ path, query, what }: { path: string; query?: Record<string, string>; what: string }) {
const items: T[] = [];
let cursor: string | undefined;
for (let page = 0; page < MaxPages; page++) {
const answer = await request<any>({
path,
query: { ...query, limit: PageLimit, cursor },
what,
});
items.push(...(answer.items || []));
cursor = answer.next_cursor || undefined;
if (!cursor) break;
}
return items;
}
/**
* How a toolkit can be signed in: the schemes Composio manages itself and
* every scheme it accepts. Empty when the toolkit can't be read, which
* leaves the managed OAuth setup that every OAuth app has.
*/
async function toolkitAuthMethods({ app }: { app: string }): Promise<{ managed: string[]; schemes: string[] }> {
try {
const toolkit = await request<any>({
path: `/toolkits/${encodeURIComponent(app)}`,
what: `the ${app} sign-in methods`,
});
return {
managed: (toolkit.composio_managed_auth_schemes || []).map((scheme: string) =>
String(scheme).toUpperCase(),
),
schemes: (toolkit.auth_config_details || [])
.map((detail: any) => String(detail.mode || "").toUpperCase())
.filter(Boolean),
};
} catch {
return { managed: [], schemes: [] };
}
}
/**
* The sign-in setup a link belongs to. Composio wants an auth config on
* every link, and makes a managed one for a toolkit that has none yet,
* so a fresh install can connect an app without visiting its dashboard.
* A toolkit Composio manages no credentials for (Gitea, whose key and
* instance URL are the user's own) gets a custom setup of its own scheme
* instead, which the hosted sign-in page fills in.
*/
async function authConfigFor({ app, auth_config_id }: { app: string; auth_config_id?: string | null }) {
if (auth_config_id) return auth_config_id;
const [existing, methods] = await Promise.all([
listAllPages<any>({
path: "/auth_configs",
query: { toolkit_slug: app },
what: `the ${app} sign-in setups`,
}),
toolkitAuthMethods({ app }),
]);
const usable = (item: any) =>
!methods.schemes.length || methods.schemes.includes(String(item.auth_scheme || "").toUpperCase());
const reusable =
existing.find((item) => usable(item) && String(item.auth_scheme).toUpperCase() == "OAUTH2") ||
existing.find(usable);
if (reusable?.id) return String(reusable.id);
// Nothing known about the toolkit means an OAuth app that Composio
// manages, as before.
const managed = !methods.schemes.length || methods.managed.length > 0;
try {
const created = await request<any>({
path: "/auth_configs",
method: "POST",
what: `a sign-in setup for ${app}`,
body: managed
? {
toolkit: { slug: app },
auth_scheme: methods.managed.includes("OAUTH2")
? "OAUTH2"
: methods.managed[0] || "OAUTH2",
use_composio_managed_auth: true,
}
: { toolkit: { slug: app }, auth_config: { type: "use_custom_auth", authScheme: methods.schemes[0] } },
});
const id = created.auth_config?.id || created.id;
if (!id) throw new AppError(`Composio didn't return a sign-in setup for ${app}.`);
return String(id);
} catch (error) {
throw new AppError(
`${app} has no sign-in setup at Composio yet, and one couldn't be made: ${(error as Error).message}`,
);
}
}
return {
async listApps() {
const items = await listAllPages<any>({ path: "/toolkits", what: "the app list" });
return items.map(
(item): ConnectorApp => ({
app: item.slug,
name: item.name || item.slug,
description: item.meta?.description || item.description || "",
logo: item.meta?.logo || item.logo || "",
scopes: Array.isArray(item.meta?.scopes) ? item.meta.scopes : null,
}),
);
},
async listTools({ app }) {
const items = await listAllPages<any>({
path: "/tools",
query: { toolkit_slug: app },
what: `the tool list for ${app}`,
});
return items.map(
(item): ConnectorTool => ({
name: item.slug || item.name,
description: item.description || item.slug || item.name,
input_schema: item.input_parameters || item.input_schema || { type: "object", properties: {} },
}),
);
},
async endpoint({ app, user_id, account, tools }) {
const answer = await request<any>({
path: "/tool_router/session",
method: "POST",
what: `a session for ${app}`,
body: {
user_id: `cobble-user-${user_id}`,
connected_accounts: { [app]: [account] },
toolkits: { enable: [app] },
tools: { [app]: { enable: tools } },
manage_connections: { enable: false },
search: { enable: false },
preload: { tools: "all" },
mcp: true,
},
});
const mcp = answer.mcp || answer.session?.mcp;
if (!mcp?.url) {
throw new AppError(
`Composio answered with a session but no MCP endpoint for ${app}, so its tools can't be reached.`,
);
}
return {
url: mcp.url,
// The tool router answers with a URL and no headers, and
// rejects a request without the project key ("API key is
// required"), so the key travels with every call. It only
// 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,
} satisfies ConnectorEndpoint;
},
async startConnect({ app, user_id, auth_config_id, callback_url }: StartConnectParams) {
const config = await authConfigFor({ app, auth_config_id });
// A plain connected-accounts link replaces the app's account for
// that user, so a second sign-in would take the first one away.
// A multi-account session keeps both, which is what a connection
// named "Work" beside one named "Personal" needs.
const session = await request<any>({
path: "/tool_router/session",
method: "POST",
what: `a sign-in session for ${app}`,
body: {
user_id: `cobble-user-${user_id}`,
toolkits: { enable: [app] },
// The link names no auth config, so the session is what
// pins the setup a toolkit with several of them uses.
auth_configs: { [app]: config },
multi_account: { enable: true, max_accounts_per_toolkit: MaxAccountsPerToolkit },
},
});
const session_id = session.session_id || session.id;
if (!session_id) throw new AppError(`Composio didn't open a sign-in session for ${app}.`);
const answer = await request<any>({
path: `/tool_router/session/${session_id}/link`,
method: "POST",
what: `a sign-in link for ${app}`,
body: {
toolkit: app,
auth_config_id: config,
...(callback_url ? { callback_url } : {}),
},
});
if (!answer.redirect_url) {
throw new AppError(`Composio didn't return a sign-in link for ${app}.`);
}
return {
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,
};
},
async accounts({ app, user_id }) {
const items = await listAllPages<any>({
path: "/connected_accounts",
// The listing filters on the plural names only: `toolkit_slug`
// and `user_id` are ignored and answer with the whole
// project's accounts, which is how one user's sync took over
// another's account.
query: { user_ids: `cobble-user-${user_id}`, toolkit_slugs: app },
what: `the ${app} accounts`,
});
return items
.filter((item) => !item.toolkit?.slug || item.toolkit.slug == app)
.map(
(item): ProviderAccount => ({
provider_account_id: item.id,
status: Statuses[item.status] || "expired",
label: item.account_name || item.meta?.account_name || undefined,
}),
);
},
async revoke({ account }) {
await request<any>({
path: `/connected_accounts/${account}`,
method: "DELETE",
what: "disconnecting an account",
});
},
async execute({ tool, args, account, user_id }) {
const answer = await request<any>({
path: `/tools/execute/${tool}`,
method: "POST",
what: `a call to ${tool}`,
body: {
user_id: `cobble-user-${user_id}`,
connected_account_id: account,
arguments: args,
},
});
if (answer.successful === false) {
throw new AppError(
`Composio failed ${tool}: ${answer.error || "it gave no reason"}`,
);
}
return answer.data ?? answer;
},
};
}
+13
View File
@@ -26,6 +26,12 @@ type Params = {
* instead of leaving the bot to guess one.
*/
model_name?: string;
/**
* No fallback and no retry can help: another model fails the same way
* (or the caller's own prompt is the problem), so the run stops with
* this message rather than spending the next candidate on it.
*/
fatal?: boolean;
};
/**
@@ -57,6 +63,11 @@ export default class HarnessError extends Error {
method?: string;
url?: string;
model_name?: string;
/**
* Nothing else can be tried: `withCandidates` rethrows it at once,
* without resting the candidate or falling back to another model.
*/
fatal: boolean;
constructor({
message,
@@ -70,6 +81,7 @@ export default class HarnessError extends Error {
method,
url,
model_name,
fatal = false,
}: Params) {
super(message);
this.name = "HarnessError";
@@ -83,5 +95,6 @@ export default class HarnessError extends Error {
this.method = method;
this.url = url;
this.model_name = model_name;
this.fatal = fatal;
}
}
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import isContextOverflowError from "./is-context-overflow-error";
describe("isContextOverflowError", () => {
test.each([
"This model's maximum context length is 131072 tokens",
"context_length_exceeded",
"The prompt is too long for this model",
"Please reduce the length of the messages",
"input length and max_tokens exceed the model's context",
"This request exceeds the maximum number of tokens",
"Your request is 200000 tokens which exceeds the maximum",
])("reads %p as a window the prompt went past", (detail) => {
expect(isContextOverflowError({ status: 400, detail })).toBe(true);
});
test("a plain 400 about something else is not a context overflow", () => {
expect(isContextOverflowError({ status: 400, detail: "Invalid `temperature`: must be between 0 and 2" })).toBe(
false,
);
});
test("a server error or a rate limit is never read as one, whatever it says", () => {
expect(isContextOverflowError({ status: 500, detail: "maximum context length" })).toBe(false);
expect(isContextOverflowError({ status: 429, detail: "context length exceeded" })).toBe(false);
});
test("an empty detail is not one", () => {
expect(isContextOverflowError({ status: 400 })).toBe(false);
expect(isContextOverflowError({ status: 400, detail: "" })).toBe(false);
});
});
@@ -0,0 +1,45 @@
/**
* The shapes providers use when the prompt was too long for the model it
* was sent to. Their message carries the real limit and what was sent
* ("prompt is too long: 1,038,402 tokens > 1,000,000 maximum"), which is
* the only place a model with no declared window states its window.
*/
const ContextOverflowPhrases = [
"maximum context length",
"context length exceeded",
"context_length_exceeded",
"prompt is too long",
"reduce the length of the messages",
"input length and max_tokens exceed",
"exceeds the maximum number of tokens",
"maximum number of input tokens",
];
/**
* "1,038,402 tokens > 1,000,000 maximum": a count compared against a
* limit, which no other kind of 400 phrases that way.
*/
const OverLimitTokens = /\b\d[\d,]{2,}\s*tokens?\b[^.]{0,30}\b(maximum|max|limit)\b/;
type Params = {
status: number;
/**
* The provider's own words, already read out of its error body.
*/
detail?: string;
};
/**
* Whether a provider refused a call because the prompt did not fit its
* model. A 400 usually means "only another model can help", but this one
* means the window this run was sized for is too big: no fallback model
* and no retry fixes it, and the message says what the real limit is
* (`isContextOverflowError` -> `toHarnessError`).
*/
export default function isContextOverflowError({ status, detail }: Params) {
if (status != 400 && status != 413 && status != 422) return false;
const text = (detail || "").toLowerCase();
return ContextOverflowPhrases.some((phrase) => text.includes(phrase)) || OverLimitTokens.test(text);
}
@@ -0,0 +1,59 @@
import HarnessError from "../../harness-error";
/**
* Alibaba's native routes (images, speech) live at the host root, beside
* `<base>/compatible-mode/v1`, never under it.
*/
export const NativeGenerationPath = "/api/v1/services/aigc/multimodal-generation/generation";
/**
* The host root: the native routes live beside `<base>/compatible-mode/v1`,
* never under it.
*/
export function dashScopeOrigin({ base_url }: { base_url: string }) {
try {
return new URL(base_url).origin;
} catch {
throw new HarnessError({
message: `The provider's base URL can't be read as an address: ${base_url}`,
retryable: false,
});
}
}
/**
* Alibaba's Token Plan host. Its models are served only by the native
* calls; the compatible routes 404, and trying one first benches the model
* before the request that works.
*/
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
return new URL(base_url).hostname.startsWith("token-plan.");
} catch {
return false;
}
}
/**
* A DashScope or Model Studio host, where the native calls take the
* provider's own extensions (`image` references, audio input). The shared
* `dashscope` hosts and the workspace `maas` hosts both count; a custom
* provider pointed elsewhere keeps the standard behaviour.
*/
export function isDashScopeHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
const host = new URL(base_url).hostname;
return (
host == "dashscope.aliyuncs.com" ||
host == "dashscope-intl.aliyuncs.com" ||
host.endsWith(".maas.aliyuncs.com")
);
} catch {
return false;
}
}
@@ -1,6 +1,7 @@
import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessCandidate, HarnessImageOutput } from "../../types";
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
import downloadProviderFile from "./download-provider-file";
import providerRequest from "./provider-request";
@@ -24,8 +25,6 @@ type Params = {
* how the native API takes image editing too. The answer carries image URLs,
* downloaded here under the same guards as every other provider URL.
*/
export const NativeImagePath = "/api/v1/services/aigc/multimodal-generation/generation";
export default async function generateImageNative({
candidate,
prompt,
@@ -40,8 +39,8 @@ export default async function generateImageNative({
const res = await providerRequest({
provider,
base_url: nativeOrigin({ base_url: provider.base_url }),
path: NativeImagePath,
base_url: dashScopeOrigin({ base_url: provider.base_url }),
path: NativeGenerationPath,
json: {
model: model.slug,
input: {
@@ -90,7 +89,7 @@ export default async function generateImageNative({
if (!urls.length) {
throw new HarnessError({
message: `${name}: no image came back from ${NativeImagePath}.`,
message: `${name}: no image came back from ${NativeGenerationPath}.`,
retryable: true,
candidate_key: candidate.key,
});
@@ -112,21 +111,6 @@ export default async function generateImageNative({
return { images };
}
/**
* The host root: the native routes live beside `<base>/compatible-mode/v1`,
* never under it.
*/
function nativeOrigin({ base_url }: { base_url: string }) {
try {
return new URL(base_url).origin;
} catch {
throw new HarnessError({
message: `The provider's base URL can't be read as an address: ${base_url}`,
retryable: false,
});
}
}
/**
* The tool's size is a plain `1024x1024`; the native API wants
* `1024*1024` and ignores anything that isn't a pair of pixels.
@@ -0,0 +1,109 @@
import HarnessError from "../../harness-error";
import type { HarnessCandidate } from "../../types";
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
import providerRequest from "./provider-request";
type Params = {
candidate: HarnessCandidate;
audio: { data: Uint8Array; format: string };
language?: string;
signal: AbortSignal;
};
/**
* What the audio formats the browser records are called as MIME types.
* DashScope takes a data URL, and Safari's `audio/mp4` recording arrives
* here as `m4a`, which no browser spells as a MIME type.
*/
const AudioMimeTypes: Record<string, string> = {
m4a: "audio/mp4",
mp4: "audio/mp4",
mp3: "audio/mpeg",
ogg: "audio/ogg",
opus: "audio/ogg",
};
/**
* Qwen-ASR on Alibaba's native multimodal route. The Token Plan host and the
* workspace Model Studio hosts have no `/audio/transcriptions` at all: the
* model is asked on the host root (beside `compatible-mode/v1`) with the
* audio inline as a data URL, and answers its transcript at `output.text`.
*
* The formats Alibaba documents are wav, mp3 and opus, but live calls take
* every format the recorders here produce (webm, m4a, ogg) when the label
* matches the bytes, so the browser's own recording is sent as it is rather
* than re-encoded first.
*/
export default async function transcribeNative({
candidate,
audio,
language,
signal,
}: Params): Promise<{ text: string }> {
const { provider, model } = candidate;
const name = provider.name || "Alibaba Cloud";
const format = audio.format.toLowerCase();
const mime_type = AudioMimeTypes[format] || `audio/${format}`;
const data_url = `data:${mime_type};base64,${Buffer.from(audio.data).toString("base64")}`;
const hint = languageHint({ language });
const res = await providerRequest({
provider,
base_url: dashScopeOrigin({ base_url: provider.base_url }),
path: NativeGenerationPath,
json: {
model: model.slug,
input: {
messages: [
{
role: "user",
content: [{ type: "input_audio", input_audio: { data: data_url } }],
},
],
},
parameters: {
format,
...(hint ? { language_hints: [hint] } : {}),
},
},
signal,
candidate_key: candidate.key,
});
const json = await res.json().catch(() => null);
/**
* A cut-off or malformed answer is a failed call, not silence: saying
* it failed lets the harness try the next model instead of handing the
* user an empty transcript.
*/
if (json === null) {
throw new HarnessError({
message: `${name} returned an unreadable transcript.`,
retryable: true,
candidate_key: candidate.key,
});
}
const text = String(json?.output?.text ?? json?.text ?? "").trim();
if (!text) {
throw new HarnessError({
message: `${name} returned an empty transcript.`,
retryable: true,
candidate_key: candidate.key,
});
}
return { text };
}
/**
* `language_hints` takes a language (`en`), not a locale (`en-US`), so the
* browser's BCP-47 tag is cut to its primary subtag.
*/
function languageHint({ language }: { language?: string }) {
const primary = language?.trim().split(/[-_]/)[0]?.toLowerCase() ?? "";
return /^[a-z]{2,3}$/.test(primary) ? primary : undefined;
}
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessAdapter, HarnessCandidate, HarnessImageOutput } from "../../types";
import grabProviderPreset from "../grab-provider-preset";
import { isDashScopeHost, isTokenPlanHost } from "./dashscope-hosts";
import downloadProviderFile from "./download-provider-file";
import generateImageNative from "./dashscope-native-image";
import imageRequestFields from "./image-request-fields";
@@ -217,37 +218,5 @@ async function editForm({ model, prompt, n, size, references, signal }: EditForm
* Alibaba's DashScope and Model Studio (`maas`) hosts serve the OpenAI
* images protocol with their own quirks: references go in the `image`
* extension field on `/images/generations` (no multipart `/images/edits`),
* and the response is always URLs. The shared `dashscope` hosts and the
* workspace `maas` hosts both count; a custom provider pointed elsewhere
* keeps the standard behaviour.
* and the response is always URLs.
*/
/**
* Alibaba's Token Plan host. Its image models are served only by the native
* call; the compatible `/images/generations` path 404s, and trying it first
* benches the model before the picture is made.
*/
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
return new URL(base_url).hostname.startsWith("token-plan.");
} catch {
return false;
}
}
function isDashScopeHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
const host = new URL(base_url).hostname;
return (
host == "dashscope.aliyuncs.com" ||
host == "dashscope-intl.aliyuncs.com" ||
host.endsWith(".maas.aliyuncs.com")
);
} catch {
return false;
}
}
@@ -3,9 +3,14 @@ import HarnessError from "../../harness-error";
import type { HarnessCandidate } from "../../types";
let payload: unknown = { text: "hello world" };
let request: any = null;
mock.module("./provider-request", () => ({
default: async () => ({ json: async () => payload }),
default: async (args: any) => {
request = args;
return { json: async () => payload };
},
}));
const { default: transcribe } = await import("./transcribe");
@@ -23,6 +28,7 @@ const signal = new AbortController().signal;
afterAll(() => mock.restore());
beforeEach(() => {
payload = { text: "hello world" };
request = null;
});
describe("transcribe", () => {
@@ -64,4 +70,82 @@ describe("transcribe", () => {
expect(result.usage).toEqual({ prompt_tokens: 10, completion_tokens: 2 });
});
});
test("Alibaba's hosts are asked on the native route, not /audio/transcriptions", async () => {
payload = { output: { text: " 你好 " } };
const result = await transcribe({
candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }),
audio,
signal,
});
expect(result.text).toBe("你好");
expect(request.path).toBe("/api/v1/services/aigc/multimodal-generation/generation");
expect(request.base_url).toBe("https://token-plan.ap-southeast-1.maas.aliyuncs.com");
expect(request.form).toBeUndefined();
expect(request.json.model).toBe("qwen-audio-3.0-asr-flash");
expect(request.json.input.messages[0].content[0]).toEqual({
type: "input_audio",
input_audio: { data: "data:audio/wav;base64,AQID" },
});
expect(request.json.parameters).toEqual({ format: "wav" });
});
test("the native call labels the recording's format and cuts the language to its primary subtag", async () => {
payload = { output: { text: "hello" } };
await transcribe({
candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }),
audio: { data: new Uint8Array([1, 2, 3]), format: "webm" },
language: "en-US",
signal,
});
expect(request.json.input.messages[0].content[0].input_audio.data).toStartWith(
"data:audio/webm;base64,",
);
expect(request.json.parameters).toEqual({ format: "webm", language_hints: ["en"] });
});
test("a model that only transcribes as a job is refused without a call", async () => {
const error = await transcribe({
candidate: tokenPlanCandidate({ slug: "qwen3-asr-flash-filetrans" }),
audio,
signal,
}).catch((thrown: unknown) => thrown);
expect(error).toBeInstanceOf(HarnessError);
expect(error).toMatchObject({ retryable: false });
expect(request).toBeNull();
});
test("an ASR model on another provider keeps the OpenAI-style upload", async () => {
payload = { text: "hello" };
await transcribe({
candidate: {
...candidate,
model: { slug: "qwen3-asr-flash" },
} as unknown as HarnessCandidate,
audio,
signal,
});
expect(request.path).toBe("/audio/transcriptions");
expect(request.form).toBeInstanceOf(FormData);
});
});
function tokenPlanCandidate({ slug }: { slug: string }) {
return {
key: `transcription:${slug}`,
provider: {
kind: "custom",
base_url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
name: "Alibaba Cloud Token Plan",
},
model: { slug },
source: "pinned",
} as unknown as HarnessCandidate;
}
@@ -1,10 +1,25 @@
import HarnessError from "../../harness-error";
import type { HarnessAdapter } from "../../types";
import { isDashScopeHost } from "./dashscope-hosts";
import transcribeNative from "./dashscope-native-transcribe";
import providerRequest from "./provider-request";
/**
* The native Qwen-ASR models: the only synchronous speech models Alibaba's
* DashScope/Model Studio hosts serve, at their own route rather than
* `/audio/transcriptions`.
*/
const NativeAsrModel = /asr|paraformer/i;
/**
* File transcription is a job at the provider (submit, then poll), which
* this adapter doesn't run: it would queue a task and wait for nothing.
*/
const AsyncOnlyAsrModel = /filetrans|paraformer/i;
/**
* `POST /audio/transcriptions` as an OpenAI-style file upload, which
* OpenRouter, OpenAI, Groq and local servers all take.
* OpenRouter, OpenAI, Groq and local servers all take. Alibaba's hosts have
* no such route, so their ASR models go to the native call instead.
*/
const transcribe: HarnessAdapter["transcribe"] = async ({
candidate,
@@ -12,6 +27,18 @@ const transcribe: HarnessAdapter["transcribe"] = async ({
language,
signal,
}) => {
if (isDashScopeHost({ base_url: candidate.provider.base_url }) && NativeAsrModel.test(candidate.model.slug)) {
if (AsyncOnlyAsrModel.test(candidate.model.slug)) {
throw new HarnessError({
message: `${candidate.provider.name || "Alibaba Cloud"}: ${candidate.model.slug} only transcribes as an asynchronous job, which this harness doesn't run. Pick a synchronous ASR model such as qwen-audio-3.0-asr-flash.`,
retryable: false,
candidate_key: candidate.key,
});
}
return await transcribeNative({ candidate, audio, language, signal });
}
const form = new FormData();
form.append("model", candidate.model.slug);
@@ -159,4 +159,32 @@ describe("toHarnessError", () => {
expect(error.message.match(/images\/generations/g)?.length).toBe(1);
});
test("a prompt past the model's window is fatal, keeps the provider's limit and says what to set", () => {
const error = toHarnessError({
status: 400,
body: JSON.stringify({
error: { message: "This model's maximum context length is 65536 tokens. However, your messages resulted in 99812 tokens." },
}),
provider_name: "Nvidia Cloud",
});
expect(error.fatal).toBe(true);
expect(error.retryable).toBe(false);
expect(error.provider_wide).toBe(false);
expect(error.message).toContain("maximum context length is 65536 tokens");
expect(error.message).toContain("Set this model's context window under Settings > Models");
expect(error.message).toContain("assumed to have 1,000,000");
});
test("any other 400 is only about the model, never fatal", () => {
const error = toHarnessError({
status: 400,
body: JSON.stringify({ error: { message: "temperature is not supported" } }),
provider_name: "Example",
});
expect(error.fatal).toBe(false);
expect(error.message).not.toContain("Settings > Models");
});
});
+18 -1
View File
@@ -1,4 +1,5 @@
import HarnessError from "../harness-error";
import isContextOverflowError from "./is-context-overflow-error";
import parseRetryAt from "./parse-retry-at";
import redactProviderError from "./redact-provider-error";
@@ -26,6 +27,8 @@ type Params = {
* the same way, so it is `provider_wide`
* - 408, 409, 425, 429, 5xx: `retryable`, with `retry_at` when the
* provider says
* - a 400 saying the prompt did not fit the model's window: `fatal`, and
* the run stops with the provider's own limit (`isContextOverflowError`)
* - anything else (400, 403, 404, 422): only another model can help. A
* 403 is about the model (OpenRouter refuses some free models to most
* apps), not the key
@@ -54,12 +57,26 @@ export default function toHarnessError({
address = addressText({ detail, method, url }),
hint = missing_endpoint ? " - no endpoint at that address; check the provider's base URL" : "";
/**
* A prompt that did not fit the model's window is the one 400 no
* fallback model or retry fixes: the run was sized for a window this
* model does not have, and the provider has just said what it is. The
* run stops with this message, so the user reads the real limit rather
* than a bot that trimmed every result and answered from nothing.
*/
const overflow = isContextOverflowError({ status, detail: provider_detail });
const advice = overflow
? "\nSet this model's context window under Settings > Models: a model with none declared is assumed to have 1,000,000."
: "";
const retryable = [408, 409, 425, 429].includes(status) || status >= 500;
return new HarnessError({
message: redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, 400),
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow ? 320 : 400)}${advice}`,
status,
retryable,
fatal: overflow,
retry_at: retryable && headers ? parseRetryAt({ headers }) : undefined,
provider_wide: status == 401 || status == 402,
candidate_key,
@@ -70,6 +70,36 @@ describe("withCandidates", () => {
expect(tried).toEqual(["b"]);
});
test("a fatal failure is thrown at once, with no fallback and nothing rested", async () => {
const cooldowns = createCooldowns();
const tried: string[] = [];
const a = candidate("a");
const b = candidate("b");
const fatal = new HarnessError({
message: "prompt is too long for this model",
status: 400,
fatal: true,
candidate_key: a.key,
});
const call = withCandidates({
harness: "text",
candidates: [a, b],
cooldowns,
run: async (c) => {
tried.push(c.model.slug);
throw fatal;
},
});
await expect(call).rejects.toBe(fatal);
// A smaller window is not a fault of the model: no other model can
// answer the same prompt, so none is tried and none is rested.
expect(tried).toEqual(["a"]);
expect(cooldowns.get({ key: a.key })).toBeUndefined();
});
test("tries the preferred model first", async () => {
const tried: string[] = [];
+23 -1
View File
@@ -69,7 +69,8 @@ type Params<T> = {
* install's model rest (`coolDown`) and is logged.
*
* Throws a `HarnessError`: `unavailable` when there is nothing to try,
* otherwise the last failure, `retryable` if any failure was.
* otherwise the last failure, `retryable` if any failure was. A `fatal`
* failure is rethrown at once: no cooldown, no next candidate.
*/
export default async function withCandidates<T>({
harness,
@@ -166,6 +167,27 @@ export default async function withCandidates<T>({
} catch (error: unknown) {
if (!(error instanceof HarnessError)) throw error;
if (error.code == "aborted") throw error;
/**
* A fatal failure is the run's own: another model fails the same
* way, and the message (the provider's own limit, or the app's
* arithmetic on a window) is what the user needs to read. It
* rests nothing and falls back to nothing. It is still written
* down as a failed call, so the notice the message carries can
* say which model refused it and why.
*/
if (error.fatal) {
error.model_name ||= candidate.model.slug;
if (log_failures) {
await recordHarnessFailure({
harness: harness_of?.get(candidate.key) || harness,
candidate,
error,
});
}
throw error;
}
/**
* The model's own name goes on the failure: a tool tells the bot
+21 -5
View File
@@ -3,14 +3,30 @@ import type { HarnessTool } from "../types";
import { LoadToolsToolName } from "../tools/load-tools-tool";
/**
* The system prompt's list of the tools a run may load (`load_tools`):
* each by name with the start of its description, so the model knows
* what is there without every definition riding along on each turn.
* The system prompt's list of the tools a run may load (`load_tools`): the
* bot's own tools by family, each with the names in it, and every extension
* tool by name with the start of its description, so the model knows what is
* there without every definition riding along on each turn.
*/
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
const lines = tools.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`);
const families = new Map<string, string[]>();
const loose: HarnessTool[] = [];
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with the names you need (one call can load several), then call them. Don't load what you won't use.\n${lines.join("\n")}`;
for (const tool of tools) {
if (!tool.group) {
loose.push(tool);
continue;
}
families.set(tool.group, [...(families.get(tool.group) ?? []), tool.name]);
}
const lines = [
...[...families].map(([group, names]) => `- ${group}: ${names.join(", ")} (load the family by its name)`),
...loose.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`),
];
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with what you need (one call can load several), then call them: exact names, a family's name for all of it, or "<prefix>*". Don't load what you won't use.\n${lines.join("\n")}`;
}
function shortDescription({ text }: { text: string }) {
@@ -23,7 +23,7 @@ function transcript(): HarnessMessage[] {
];
}
const params = { system: "s", context_length: 200, keep_last: 4 };
const params = { system: "s", working_tokens: 140, keep_last: 4 };
describe("fitTranscriptToContext keeps a head+tail trim across passes (M4)", () => {
test("a long result is cut to its start and end, not replaced whole", () => {
@@ -54,3 +54,89 @@ describe("fitTranscriptToContext keeps a head+tail trim across passes (M4)", ()
expect(messages[0]!.content as string).toContain("_END_MARKER");
});
});
describe("fitTranscriptToContext never leaves a run reading a note instead of an answer", () => {
test("a result short enough to keep whole is kept whole", () => {
const messages: HarnessMessage[] = [
{ role: "tool", tool_call_id: "c1", content: "/usr/bin/pdftoppm" },
];
// Far below the result, so every pass that could cut it runs.
const result = fitTranscriptToContext({ system: "s", transcript: messages, working_tokens: 10 });
expect(result.trimmed).toBe(0);
expect(messages[0]!.content).toBe("/usr/bin/pdftoppm");
});
test("the newest turn's results are cut last, only once the older ones are gone", () => {
const old = `OLD_START_${"x".repeat(30_000)}_OLD_END`;
const fresh = `FRESH_START_${"y".repeat(6000)}_FRESH_END`;
const messages: HarnessMessage[] = [
{ role: "tool", tool_call_id: "old", content: old },
{ role: "user", content: "u1" },
{
role: "assistant",
content: "a1",
tool_calls: [{ id: "new", name: "computer_bash", arguments: "{}" }],
},
{ role: "tool", tool_call_id: "new", content: fresh },
];
// Enough room once the older result is cut, so the newest one stays.
const result = fitTranscriptToContext({
system: "s",
transcript: messages,
working_tokens: 5_000,
keep_last: 0,
});
expect(result.trimmed).toBe(1);
expect(messages[0]!.content as string).toContain("OLD_START_");
expect(messages[3]!.content).toBe(fresh);
});
});
describe("fitTranscriptToContext names what is over the working context", () => {
test("its own instructions alone past the context is static", () => {
const result = fitTranscriptToContext({
system: "x".repeat(3_000),
transcript: [],
working_tokens: 500,
});
expect(result.over_budget).toBe("static");
expect(result.base).toBe(result.system_tokens);
});
test("tool definitions count toward the static part", () => {
const result = fitTranscriptToContext({
system: "s",
transcript: [],
working_tokens: 500,
tools_chars: 3_000,
});
expect(result.over_budget).toBe("static");
expect(result.tools_tokens).toBe(1_000);
});
test("a conversation the user made too long is the request", () => {
const result = fitTranscriptToContext({
system: "s",
transcript: [{ role: "user", content: "y".repeat(3_000) }],
working_tokens: 500,
keep_last: 0,
});
expect(result.over_budget).toBe("request");
// The user's own text is never cut.
expect(result.trimmed).toBe(0);
});
test("a prompt that fits says nothing is over", () => {
const result = fitTranscriptToContext({ system: "s", transcript: [], working_tokens: 500 });
expect(result.over_budget).toBe(false);
});
});
+78 -55
View File
@@ -8,30 +8,35 @@ type Params = {
*/
transcript: HarnessMessage[];
/**
* The model's context window, in tokens.
* The working context (`workingContextTokens`): the most a turn may
* send, the model's window less the room its answer needs, or the
* install's own tighter cap.
*/
context_length: number;
/**
* The working context (`grabContextBudgetTokens`): the most the prompt
* may be per turn, whatever the window. Left out, only the window
* limits it.
*/
budget_tokens?: number;
working_tokens: number;
/**
* Characters of the tool definitions sent with every turn: they count
* against the budget like the prompt.
*/
tools_chars?: number;
/**
* The newest messages, never trimmed: the model needs them to go on.
* The newest messages: the passes that cut everything else leave them
* alone, so the turn the run is working from keeps its answer. Only the
* last resort (still over budget with nothing older left to cut) cuts
* their tool results, and what the user wrote is never cut at all.
*/
keep_last?: number;
};
/**
* Share of the window the prompt may fill; the rest is for the answer.
* Why the prompt still doesn't fit:
* - `static`: the system prompt and tool definitions alone are past the
* working context, so no amount of trimming can help and the run must
* stop and say so
* - `request`: what is over is the conversation itself, most often what
* the user wrote, which is never cut
*/
const PromptShare = 0.7;
export type OverBudgetCause = "static" | "request";
/**
* Once over budget, trimming goes on down to this share of it. Cutting in
* one block, rather than one message each turn, keeps the start of the
@@ -54,6 +59,14 @@ const MediaTokens = 1500;
* and its totals, as `truncate` does) is usually all the run still needs.
*/
const TrimmedKeepChars = 500;
/**
* A result no longer than this is kept whole. Cutting it saved nothing
* worth a note, and a short result used to be replaced by the note alone:
* a 14-character answer from a shell reached the model as "Trimmed: 14
* characters", so the run was reading nothing at all and went on doing it
* for the rest of its steps.
*/
const ResultKeepWholeChars = TrimmedKeepChars * 4;
/**
* Tool call arguments longer than this (a file written whole) are cut on
* the second pass, after the tool results.
@@ -62,35 +75,51 @@ const ArgumentsKeepChars = 1500;
/**
* Keeps a long tool run inside its working context: once the estimated
* prompt (system, tool definitions, transcript) passes the budget (the
* working context, or 70% of the window when that is smaller), the
* oldest tool results, then long tool call arguments, then the oldest
* assistant texts are replaced with a note of what was cut, down to 60%
* of the budget. Returns how many messages were trimmed, and whether the
* prompt still doesn't fit (nothing trimmable was left: the conversation
* is the user's own text, which is never cut).
* prompt (system, tool definitions, transcript) passes it, the oldest tool
* results, then long tool call arguments, then the oldest assistant texts
* are replaced with a note of what was cut, down to 60% of it. The newest
* turn's results are cut last, and only once everything older is gone.
* Reports how many messages were trimmed, and, when the prompt still
* doesn't fit, whether the static part is the cause.
*/
export default function fitTranscriptToContext({
system,
transcript,
context_length,
budget_tokens,
working_tokens,
tools_chars = 0,
keep_last = 4,
}: Params) {
const window_budget = Math.floor(context_length * PromptShare);
const budget = budget_tokens && budget_tokens > 0 ? Math.min(window_budget, budget_tokens) : window_budget;
let total =
estimateTokens({ text: system }) +
Math.ceil(tools_chars / CharsPerToken) +
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
const budget = working_tokens;
const system_tokens = estimateTokens({ text: system });
const tools_tokens = Math.ceil(tools_chars / CharsPerToken);
const base = system_tokens + tools_tokens;
let total = base + transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
let trimmed = 0;
if (total <= budget) return { trimmed, estimated_tokens: total, budget, over_budget: false };
if (total <= budget) {
return {
trimmed,
estimated_tokens: total,
budget,
base,
system_tokens,
tools_tokens,
over_budget: false as false | OverBudgetCause,
};
}
const target = Math.floor(budget * TrimToShare);
const trimmable = transcript.length - keep_last;
const names = toolNames({ transcript });
/**
* Everything after the newest user turn is what the run is working
* from right now. Cutting it is the last resort, not the first: it is
* why a run over budget kept its command and lost its answer.
*/
const newest_turn = Math.max(
0,
Math.min(trimmable, transcript.reduce((last, message, index) => (message.role == "user" ? index : last), trimmable)),
);
const replace = ({ index, message }: { index: number; message: HarnessMessage }) => {
const before = messageTokens({ message: transcript[index]! });
@@ -104,24 +133,22 @@ export default function fitTranscriptToContext({
* A tool result cut down to its two ends and a note: the run works from
* what it kept, rather than paying for the call again.
*/
const trimResult = ({ index, content, name }: { index: number; content: string; name: string | undefined }) => {
const kept = content.length > TrimmedKeepChars * 4;
const head = kept ? content.slice(0, TrimmedKeepChars) : "";
const tail = kept ? content.slice(-TrimmedKeepChars) : "";
const trimResult = ({ content, name }: { content: string; name: string | undefined }) => {
const head = content.slice(0, TrimmedKeepChars);
const tail = content.slice(-TrimmedKeepChars);
const cut = content.length - head.length - tail.length;
const label = name ? `${name} output` : "tool output";
if (!kept) return `[Trimmed: ${cut} characters of this ${label} to fit the working context.]`;
const note = `[Trimmed: ${cut} characters of the middle of this ${label} to fit the working context. Its start and end are kept here: work from them, and narrow the call (a smaller range, a filter, one row) rather than repeating it.]`;
return `${head}\n\n${note}\n\n${tail}`;
};
for (let index = 0; index < trimmable && total > target; index++) {
const trimToolResult = ({ index }: { index: number }) => {
const message = transcript[index]!;
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
if (message.role != "tool" || isTrimmed({ text: message.content })) return;
if (message.content.length <= ResultKeepWholeChars) return;
const name = names.get(message.tool_call_id);
@@ -129,12 +156,14 @@ export default function fitTranscriptToContext({
index,
message: {
...message,
content: trimResult({ index, content: message.content, name }),
content: trimResult({ content: message.content, name }),
},
});
}
};
for (let index = 0; index < trimmable && total > target; index++) {
for (let index = 0; index < newest_turn && total > target; index++) trimToolResult({ index });
for (let index = 0; index < newest_turn && total > target; index++) {
const message = transcript[index]!;
if (message.role != "assistant" || !message.tool_calls?.some((call) => call.arguments.length > ArgumentsKeepChars)) {
@@ -159,7 +188,7 @@ export default function fitTranscriptToContext({
});
}
for (let index = 0; index < trimmable && total > target; index++) {
for (let index = 0; index < newest_turn && total > target; index++) {
const message = transcript[index]!;
if (message.role != "assistant" || typeof message.content != "string" || isTrimmed({ text: message.content })) {
@@ -183,23 +212,17 @@ export default function fitTranscriptToContext({
* they are cut last, and only once everything older is gone. A user's
* own text is never touched.
*/
for (let index = Math.max(trimmable, 0); index < transcript.length && total > target; index++) {
const message = transcript[index]!;
for (let index = newest_turn; index < transcript.length && total > target; index++) trimToolResult({ index });
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
const name = names.get(message.tool_call_id);
replace({
index,
message: {
...message,
content: trimResult({ index, content: message.content, name }),
},
});
}
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
return {
trimmed,
estimated_tokens: total,
budget,
base,
system_tokens,
tools_tokens,
over_budget: total > budget ? (base >= budget ? ("static" as const) : ("request" as const)) : (false as const),
};
}
/**
+107 -5
View File
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { HarnessTrace } from "../trace/types";
@@ -14,6 +14,7 @@ import runTextLoop, {
stepsLowWarningLeft,
wrapUpPrompt,
} from "./run-text-loop";
import { WorkingContextReserveMax } from "./working-context";
/**
* A reviewer that threw is logged (`logError`), and the log goes to the
@@ -280,7 +281,7 @@ describe("runTextLoop", () => {
});
});
test("a run with no step limit keeps going, and records that its limits were off", async () => {
test("a run with no step limit keeps going, and records the window it works to", async () => {
memory.length = 0;
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
@@ -304,7 +305,11 @@ describe("runTextLoop", () => {
expect(seen[0]!.limits).toEqual({
steps: UnlimitedLimit,
run_tokens: UnlimitedLimit,
context_tokens: UnlimitedLimit,
// The working context is a number even with no cap: the model's
// window less the room its answer needs.
context_tokens: AppData.HarnessUnknownContextWindow - WorkingContextReserveMax,
system_tokens: 1,
tools_tokens: expect.any(Number),
});
});
@@ -1039,6 +1044,99 @@ describe("runTextLoop", () => {
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "srv__small"]);
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
});
/**
* A model with a small window, which is where a bot's own tool
* definitions are a real share of the prompt (the default candidate
* declares none, so its working context is ~936,000 tokens).
*/
const narrow = async () => [{ ...candidate, model: { ...candidate.model, context_length: 20_000 } }];
const bulk = (name: string, group?: string): HarnessTool => ({
name,
description: "Works on the tracker. ".repeat(220),
parameters: { type: "object", properties: {} },
group,
deferred: true,
run: async () => "done",
});
const family = ["list_tasks", "create_task", "update_task", "delete_task", "defer_task"].map((name) =>
bulk(name, "tasks"),
);
test("defers a family of the bot's own tools once it is worth a load turn", async () => {
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, ...family],
generate,
resolveCandidates: narrow,
});
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "load_tools"]);
expect(String(seen[0]!.messages[0]!.content)).toContain("Tools you can load");
expect(String(seen[0]!.messages[0]!.content)).toContain(
"- tasks: list_tasks, create_task, update_task, delete_task, defer_task (load the family by its name)",
);
});
test("keeps the tools that end a run loaded, however big they are", async () => {
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, ...family, bulk("send_reply", "sessions"), bulk("write_file", "files")],
generate,
resolveCandidates: narrow,
});
const names = seen[0]!.tools!.map((tool) => tool.name);
expect(names).toContain("send_reply");
expect(names).toContain("write_file");
expect(names).toContain("load_tools");
expect(names).not.toContain("list_tasks");
});
test("defers its own tools only once together they take a share of the context", async () => {
// The same family on a model with room to spare: the turn a load
// costs is not worth saving 7,000 tokens out of 936,000.
const { generate, seen } = scripted([{ text: "Hi." }]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember, ...family],
generate,
resolveCandidates,
});
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", ...family.map((tool) => tool.name)]);
});
test("stops at once when its own instructions alone are past the working context", async () => {
const { generate, seen } = scripted([{ text: "never" }]);
const call = runTextLoop({
system: "x".repeat(3_000),
messages: [{ role: "user", content: "go" }],
tools: [remember],
generate,
resolveCandidates,
context_budget: 100,
});
await expect(call).rejects.toBeInstanceOf(HarnessError);
await expect(call).rejects.toThrow("stopped before its first answer");
// Nothing was sent, and no turn was spent trimming its way to an
// answer it could not write.
expect(seen).toHaveLength(0);
});
});
describe("runTextLoop repeated reads", () => {
@@ -2338,7 +2436,11 @@ describe("runTextLoop answer not sent", () => {
describe("runTextLoop over budget", () => {
test("tells a run whose own request is over the working context, once", async () => {
const brief = "x".repeat(30_000);
const note = oversizedRequestNote({ budget: 4_000 });
/**
* A phrase from `oversizedRequestNote`: the note's numbers are the
* loop's own arithmetic, so only its fixed words are matched here.
*/
const note = "larger than the working context this model may be sent";
const { generate, seen } = scripted([
{ text: "One piece.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
@@ -2364,7 +2466,7 @@ describe("runTextLoop over budget", () => {
});
test("says nothing when the transcript fits, or when trimming was enough", async () => {
const note = oversizedRequestNote({ budget: 20_000 });
const note = "larger than the working context this model may be sent";
const { generate, seen } = scripted([
{ text: "One.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },

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