Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c92d0b4be | ||
|
|
319eb74a23 | ||
|
|
c745f58991 | ||
|
|
b046e90958 | ||
|
|
4a02035f33 | ||
|
|
f8a7b0f2e7 | ||
|
|
fdaa5649ef | ||
|
|
94b999aef1 | ||
|
|
70fd37e707 | ||
|
|
1ae360cffd | ||
|
|
85af8ac4e9 | ||
|
|
9202e80331 | ||
|
|
b088050577 | ||
|
|
a2149e2397 | ||
|
|
71bb4d517f |
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 [];
|
||||
}
|
||||
}
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
+314
-1
@@ -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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.26.0",
|
||||
"version": "0.27.3",
|
||||
"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",
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
passedOnRequestNote,
|
||||
SecretsNote,
|
||||
SettingsNote,
|
||||
ConnectorsNote,
|
||||
GraphicsNote,
|
||||
botFilesNote,
|
||||
chatReplyNote,
|
||||
@@ -48,6 +49,9 @@ 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 +68,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 +249,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 +445,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 +489,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 +537,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 +591,7 @@ export default async function runBotReply({
|
||||
*/
|
||||
plan_mode,
|
||||
onAsk: ({ ref }) => proposals.push(ref),
|
||||
redact: redact_reply,
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
@@ -554,6 +599,7 @@ export default async function runBotReply({
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => shown.push(ref),
|
||||
redact: redact_reply,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
@@ -591,6 +637,7 @@ export default async function runBotReply({
|
||||
}),
|
||||
...extensions.tools,
|
||||
...browsers.tools,
|
||||
...connectors.tools,
|
||||
...skills.tools,
|
||||
...knowledge.tools,
|
||||
];
|
||||
@@ -660,6 +707,7 @@ export default async function runBotReply({
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
extensions.note,
|
||||
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "",
|
||||
knowledge_context,
|
||||
`Now: ${new Date().toUTCString()}.`,
|
||||
]
|
||||
@@ -709,7 +757,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 +819,7 @@ export default async function runBotReply({
|
||||
} finally {
|
||||
await extensions.close();
|
||||
await browsers.close();
|
||||
await connectors.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
SettingsNote,
|
||||
GraphicsNote,
|
||||
botFilesNote,
|
||||
ConnectorsNote,
|
||||
ComputerFilesNote,
|
||||
ScheduledRunNote,
|
||||
ScheduledPlanNote,
|
||||
@@ -40,9 +41,11 @@ 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";
|
||||
@@ -175,9 +178,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 +387,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 +395,7 @@ export default async function runBotTask({
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => suggestions.push(ref),
|
||||
redact: redact_text,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
@@ -488,15 +501,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 +661,7 @@ export default async function runBotTask({
|
||||
skills.note,
|
||||
knowledge.note,
|
||||
extensions.note,
|
||||
connectors.lines.length ? ConnectorsNote({ lines: connectors.lines }) : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
@@ -694,6 +724,7 @@ export default async function runBotTask({
|
||||
}),
|
||||
...extensions.tools,
|
||||
...browsers.tools,
|
||||
...connectors.tools,
|
||||
...skills.tools,
|
||||
...knowledge.tools,
|
||||
],
|
||||
@@ -704,7 +735,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 +787,7 @@ export default async function runBotTask({
|
||||
});
|
||||
|
||||
if (failure) {
|
||||
throw new ScheduledRunFailedError(computer ? computer.redact(failure) : failure);
|
||||
throw new ScheduledRunFailedError(redact_text(failure));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -805,7 +836,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 +852,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} />;
|
||||
}
|
||||
@@ -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,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],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
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 checks the accounts a sign-in left waiting.
|
||||
* 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 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'`,
|
||||
values: [Date.now()],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
for (const request of waiting) {
|
||||
await syncConnectorAccounts({
|
||||
user_id: request.user_id,
|
||||
connector_id: request.connector_id,
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
+39
-1
@@ -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
|
||||
@@ -844,6 +844,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"];
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,120 @@
|
||||
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 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), 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 [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 = ?)` : ""}
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY a.id ASC`,
|
||||
values: workspace_id
|
||||
? [...ids, Number(user_id), Number(bot_id), Number(workspace_id)]
|
||||
: [...ids, Number(user_id), Number(bot_id)],
|
||||
}),
|
||||
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,83 @@
|
||||
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 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, 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. 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 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 = ?)
|
||||
)
|
||||
ORDER BY a.id ASC`,
|
||||
values: [...ids, Number(user_id), Number(bot_id), Number(workspace_id || 0)],
|
||||
})
|
||||
).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,22 @@
|
||||
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 whether or not a request claims it", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false })).toBe(true);
|
||||
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true })).toBe(true);
|
||||
});
|
||||
|
||||
test("adopts a pending account a request here started", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(true);
|
||||
});
|
||||
|
||||
test("adopts a pending account that reconnects a row", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false })).toBe(true);
|
||||
});
|
||||
|
||||
test("skips a pending account nothing here started", () => {
|
||||
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false })).toBe(false);
|
||||
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
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 a provider account becomes a local row. A connected one always does.
|
||||
* A pending one does only when a request here started it or reconnects it: an
|
||||
* abandoned sign-in at the provider must not arrive as a second account, which
|
||||
* is how a reconnect once left a never connected duplicate beside the account
|
||||
* it replaced.
|
||||
*/
|
||||
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed }: Params) {
|
||||
return reconnect || status == "connected" || claimed;
|
||||
}
|
||||
@@ -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,304 @@
|
||||
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 an account is connected.
|
||||
*/
|
||||
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' AND provider_account_id != ''`,
|
||||
values: [connector.id, Number(user_id)],
|
||||
})
|
||||
).payload || [];
|
||||
const reconnect_for = new Map(
|
||||
requests.filter((row) => Number(row.account_id) != 0).map((row) => [String(row.provider_account_id), Number(row.account_id)]),
|
||||
);
|
||||
/**
|
||||
* 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)));
|
||||
|
||||
const seen = new Set(accounts.map((account) => account.provider_account_id));
|
||||
const now = Date.now();
|
||||
const hasConnected = local.some((row) => row.status == "connected");
|
||||
|
||||
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 = hasConnected ? null : 0;
|
||||
|
||||
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),
|
||||
claimed: claimed.has(provider_account_id),
|
||||
})
|
||||
)
|
||||
continue;
|
||||
|
||||
await upsertAccount({
|
||||
connector_id: connector.id,
|
||||
user_id: Number(user_id),
|
||||
account,
|
||||
fallback_label: label,
|
||||
reconnect_id,
|
||||
});
|
||||
|
||||
if (account.status != "connected") continue;
|
||||
|
||||
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) });
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id }: 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A reconnect the provider gave no id for still lands on the row it
|
||||
* replaces: one dead row with this account's name is that row, and a
|
||||
* second one with the same name would be the duplicate this prevents.
|
||||
*/
|
||||
const name = account.label || fallback_label || "";
|
||||
const dead = name
|
||||
? ((
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') AND lower(label) = lower(?) ORDER BY id ASC`,
|
||||
values: [connector_id, user_id, name],
|
||||
})
|
||||
).payload || [])
|
||||
: [];
|
||||
|
||||
if (dead.length == 1) {
|
||||
const row = dead[0]!;
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? WHERE id = ?`,
|
||||
values: [
|
||||
account.provider_account_id,
|
||||
account.status,
|
||||
account.status == "connected" ? now : null,
|
||||
now,
|
||||
now,
|
||||
Number(row.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 = name || "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
|
||||
))
|
||||
)`,
|
||||
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.`);
|
||||
|
||||
|
||||
@@ -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,113 @@
|
||||
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 { decrypt, encrypt } from "@/src/utils/crypt";
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import type { ConnectorProvider } from "./connector-provider";
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
export default async function ensureConnectorEndpoint({
|
||||
connector,
|
||||
provider,
|
||||
user_id,
|
||||
account,
|
||||
}: Params): Promise<ConnectorEndpointResult> {
|
||||
const now = Date.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");
|
||||
});
|
||||
});
|
||||
@@ -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,243 @@
|
||||
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 });
|
||||
|
||||
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("maps account statuses and keeps the provider's id", async () => {
|
||||
const { fetchImpl } = 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 },
|
||||
]);
|
||||
});
|
||||
|
||||
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,327 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
async function authConfigFor({ app, auth_config_id }: { app: string; auth_config_id?: string | null }) {
|
||||
if (auth_config_id) return auth_config_id;
|
||||
|
||||
const existing = await listAllPages<any>({
|
||||
path: "/auth_configs",
|
||||
query: { toolkit_slug: app },
|
||||
what: `the ${app} sign-in setups`,
|
||||
});
|
||||
const usable = existing.find((item) => item.auth_scheme == "OAUTH2") || existing[0];
|
||||
|
||||
if (usable?.id) return String(usable.id);
|
||||
|
||||
try {
|
||||
const created = await request<any>({
|
||||
path: "/auth_configs",
|
||||
method: "POST",
|
||||
what: `a sign-in setup for ${app}`,
|
||||
body: { toolkit: { slug: app }, auth_scheme: "OAUTH2", use_composio_managed_auth: true },
|
||||
});
|
||||
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] },
|
||||
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",
|
||||
query: { user_id: `cobble-user-${user_id}`, toolkit_slug: 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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -27,6 +27,12 @@ type Params = {
|
||||
* card.
|
||||
*/
|
||||
onAsk: (params: { ref: string }) => void;
|
||||
/**
|
||||
* Blank out what must not reach the user (a secret env's value, a
|
||||
* password a page showed). Blanked here, since this is where the words
|
||||
* leave the run: the card is stored and read like a message.
|
||||
*/
|
||||
redact?: (text: string) => string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -49,6 +55,7 @@ export default function askUserTool({
|
||||
plan_mode,
|
||||
in_task,
|
||||
onAsk,
|
||||
redact = (text) => text,
|
||||
}: Params): HarnessTool<Args> {
|
||||
let asked = false;
|
||||
|
||||
@@ -83,11 +90,11 @@ export default function askUserTool({
|
||||
session_id,
|
||||
workspace_id,
|
||||
plan_mode: Boolean(plan_mode),
|
||||
title: args.title?.trim() || "",
|
||||
title: args.title?.trim() ? redact(args.title.trim()) : "",
|
||||
questions: args.questions.map((item) => ({
|
||||
question: item.question,
|
||||
question: redact(item.question),
|
||||
kind: item.kind,
|
||||
options: item.options,
|
||||
options: item.options.map((option) => redact(option)),
|
||||
allow_other: Boolean(item.allow_other),
|
||||
})),
|
||||
});
|
||||
|
||||
@@ -19,6 +19,11 @@ type Params = {
|
||||
* Saves and pushes the message (`insertBotMessage`, `pushBotNotice`).
|
||||
*/
|
||||
post?: (params: { text: string }) => Promise<{ id?: number | "" }>;
|
||||
/**
|
||||
* Blank out what must not reach the user (a secret env's value, a
|
||||
* password a page showed).
|
||||
*/
|
||||
redact?: (text: string) => string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -37,6 +42,7 @@ export default function sendMessageTool({
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSend,
|
||||
redact = (text) => text,
|
||||
post = async ({ text }) => {
|
||||
const message = await insertBotMessage({ bot_id, session_id, workspace_id, text, interim: true });
|
||||
|
||||
@@ -60,7 +66,7 @@ export default function sendMessageTool({
|
||||
);
|
||||
}
|
||||
|
||||
const message = await post({ text: args.text });
|
||||
const message = await post({ text: redact(args.text) });
|
||||
|
||||
sent++;
|
||||
onSend?.({ message_id: Number(message.id) });
|
||||
|
||||
@@ -18,6 +18,12 @@ type Params = {
|
||||
* their buttons.
|
||||
*/
|
||||
onSuggest: (params: { ref: string }) => void;
|
||||
/**
|
||||
* Blank out what must not reach the user (a secret env's value, a
|
||||
* password a page showed). Blanked here, since this is where the words
|
||||
* leave the run.
|
||||
*/
|
||||
redact?: (text: string) => string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -32,7 +38,7 @@ type Args = {
|
||||
* the closing turn with `send_reply` (`ClosingToolNames`): the buttons
|
||||
* belong under that answer, and a later turn would replace it.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest, redact = (text) => text }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
@@ -57,8 +63,8 @@ export default function suggestNextStepsTool({ user_id, bot_id, session_id, work
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
title: args.title?.trim() || "",
|
||||
steps: args.steps,
|
||||
title: args.title?.trim() ? redact(args.title.trim()) : "",
|
||||
steps: args.steps.map((step) => redact(step)),
|
||||
});
|
||||
|
||||
suggested = true;
|
||||
|
||||
@@ -8,6 +8,7 @@ import grabRunEnvs from "@/src/functions/backend/db/extensions/grab-run-envs";
|
||||
import parseJsonColumn from "@/src/functions/backend/db/extensions/parse-json-column";
|
||||
import { decrypt } from "@/src/utils/crypt";
|
||||
import mcpToolName from "@/src/utils/mcp-tool-name";
|
||||
import maskPasswordFieldValues from "@/src/utils/mask-password-field-values";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import connectMcpServer from "../../mcp/connect-mcp-server";
|
||||
import mcpHarnessTool from "../../mcp/mcp-harness-tool";
|
||||
@@ -57,7 +58,11 @@ export default async function openBotBrowsers({
|
||||
|
||||
const envs = await grabRunEnvs({ bot_id, user_id, workspace_id });
|
||||
const secrets = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
/**
|
||||
* A page can hold a password the browser saved itself: a value this
|
||||
* install never knew, so blanking the envs can't catch it.
|
||||
*/
|
||||
const redact = (text: string) => redactSecrets({ text: maskPasswordFieldValues({ text }), secrets });
|
||||
const names = new Set(taken);
|
||||
const tools: HarnessTool[] = [];
|
||||
const connections: Promise<Client>[] = [];
|
||||
|
||||
@@ -11,6 +11,7 @@ import BotJobFatalError from "@/src/bots-queue/bot-job-fatal-error";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import maskPasswordFieldValues from "@/src/utils/mask-password-field-values";
|
||||
import connectMcpServer from "../../mcp/connect-mcp-server";
|
||||
import grabMcpTools from "../../mcp/grab-mcp-tools";
|
||||
import type { HarnessTool } from "../../types";
|
||||
@@ -150,6 +151,12 @@ export default async function openComputerTools({
|
||||
*/
|
||||
const secrets: { key: string; value: string }[] = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
/**
|
||||
* A browser reads a page, and a page can hold a password Chrome filled in
|
||||
* from its own vault: a value this install never knew, so blanking the
|
||||
* envs can't catch it.
|
||||
*/
|
||||
const redact_page = (text: string) => redact(maskPasswordFieldValues({ text }));
|
||||
|
||||
const client = browser
|
||||
? await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal })
|
||||
@@ -170,7 +177,7 @@ export default async function openComputerTools({
|
||||
? await grabMcpTools({
|
||||
client,
|
||||
exclude: ComputerMcpExcludedTools,
|
||||
redact,
|
||||
redact: redact_page,
|
||||
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
|
||||
})
|
||||
: [];
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
|
||||
import type { ConnectorProvider } from "@/src/harness/connectors/connector-provider";
|
||||
import grabConnectorActionsPerRun from "@/src/functions/backend/db/connectors/grab-connector-actions-per-run";
|
||||
import grabRunConnectors from "@/src/functions/backend/db/connectors/grab-run-connectors";
|
||||
import grabRunEnvs from "@/src/functions/backend/db/extensions/grab-run-envs";
|
||||
import { ConnectorAccountSeparator } from "@/src/dict/connector-dict";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import connectorAccountTools from "../../connectors/connector-account-tools";
|
||||
import grabConnectorProvider from "@/src/functions/backend/db/connectors/grab-connector-provider";
|
||||
import type { HarnessTool } from "../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Whether the user is waiting on this run's answer. Only then may a
|
||||
* connector the user has no account for offer its tools: calling one
|
||||
* asks them to connect, through the card under the reply. A task,
|
||||
* routine, hook call or crew request gets tools only for accounts that
|
||||
* already work.
|
||||
*/
|
||||
attended?: boolean;
|
||||
/**
|
||||
* Names the run's other tools already use: they win.
|
||||
*/
|
||||
taken?: string[];
|
||||
/**
|
||||
* Called when a tool of a connector without an account is used, in an
|
||||
* attended run. It makes the connect request and returns the ref the
|
||||
* message must carry, or whatever should be said instead.
|
||||
*/
|
||||
onMissingAccount?: (params: { connector: ConnectorRecord }) => Promise<string>;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type OpenBotConnectorSummary = {
|
||||
connector: ConnectorRecord;
|
||||
accounts: ConnectorAccountRecord[];
|
||||
};
|
||||
|
||||
export type OpenBotConnectors = {
|
||||
tools: HarnessTool[];
|
||||
/**
|
||||
* For the run's prompt (`ConnectorsNote`): which accounts it can use
|
||||
* and how to load them, one line each.
|
||||
*/
|
||||
lines: string[];
|
||||
connectors: OpenBotConnectorSummary[];
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The connectors one run reaches, each account's tools named under its own
|
||||
* namespace (`gmail__...` for a single account, `gmail-work__...` for one of
|
||||
* several), all deferred so a turn that doesn't use them doesn't carry
|
||||
* their definitions. The endpoint is connected on the first call and
|
||||
* closed with the run.
|
||||
*/
|
||||
export default async function openBotConnectors({
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
attended = false,
|
||||
taken = [],
|
||||
onMissingAccount,
|
||||
signal,
|
||||
}: Params): Promise<OpenBotConnectors> {
|
||||
const runConnectors = await grabRunConnectors({ user_id, bot_id, workspace_id });
|
||||
|
||||
if (!runConnectors.length) return { tools: [], lines: [], connectors: [], close: async () => {} };
|
||||
|
||||
const envs = await grabRunEnvs({ bot_id, user_id, workspace_id });
|
||||
const secrets = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
const names = new Set(taken);
|
||||
const tools: HarnessTool[] = [];
|
||||
const closers: (() => Promise<void>)[] = [];
|
||||
const lines: string[] = [];
|
||||
const cap = await grabConnectorActionsPerRun();
|
||||
const namespaces = new Set<string>();
|
||||
let actions = 0;
|
||||
|
||||
/**
|
||||
* A tool namespace no other account of this run already holds, so two
|
||||
* accounts with the same label stay apart.
|
||||
*/
|
||||
const freeNamespace = ({ base }: { base: string }) => {
|
||||
let candidate = base;
|
||||
let suffix = 2;
|
||||
|
||||
while (namespaces.has(candidate) || [...names].some((name) => name.startsWith(`${candidate}__`))) {
|
||||
candidate = `${base}-${suffix}`;
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
namespaces.add(candidate);
|
||||
return candidate;
|
||||
};
|
||||
|
||||
const takeAction = () => {
|
||||
if (actions >= cap) {
|
||||
throw new Error(
|
||||
`This run has already taken ${cap} connector actions, so it can't take another. A provider bills per action; a super admin can raise the limit in Settings > Connectors.`,
|
||||
);
|
||||
}
|
||||
|
||||
actions += 1;
|
||||
};
|
||||
|
||||
for (const { connector, accounts } of runConnectors) {
|
||||
const connected = accounts.filter((account) => account.status == "connected");
|
||||
|
||||
if (!connected.length) {
|
||||
if (attended && onMissingAccount) {
|
||||
let provider: ConnectorProvider;
|
||||
|
||||
try {
|
||||
provider = await grabConnectorProvider({ connector_id: connector.id });
|
||||
} catch (error: unknown) {
|
||||
lines.push(`${connector.name}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const built = connectorAccountTools({
|
||||
connector,
|
||||
provider,
|
||||
user_id: Number(user_id),
|
||||
account: null,
|
||||
onMissingAccount: () => onMissingAccount({ connector }),
|
||||
namespace: connector.slug,
|
||||
names,
|
||||
redact,
|
||||
takeAction,
|
||||
signal,
|
||||
});
|
||||
|
||||
tools.push(...built.tools);
|
||||
closers.push(built.close);
|
||||
lines.push(
|
||||
`${connector.name}: no account connected yet. Calling one of its tools (${connector.slug}__*) asks the user to connect one, through the card under your reply; don't tell them to connect it in a sentence alone.`,
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const status = accounts[0]?.status;
|
||||
const why =
|
||||
status == "pending"
|
||||
? "waiting for you to finish connecting"
|
||||
: status == "expired"
|
||||
? "needs reconnecting"
|
||||
: "no account connected";
|
||||
|
||||
lines.push(`${connector.name}: ${why}, so its tools aren't available in this run.`);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
let provider: ConnectorProvider;
|
||||
|
||||
try {
|
||||
provider = await grabConnectorProvider({ connector_id: connector.id });
|
||||
} catch (error: unknown) {
|
||||
lines.push(`${connector.name}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const account of connected) {
|
||||
const namespace = freeNamespace({
|
||||
base:
|
||||
connected.length > 1
|
||||
? `${connector.slug}${ConnectorAccountSeparator}${account.slug}`
|
||||
: connector.slug,
|
||||
});
|
||||
const shared = account.user_id != Number(user_id) && Boolean(account.owner_name);
|
||||
const built = connectorAccountTools({
|
||||
connector,
|
||||
provider,
|
||||
/**
|
||||
* The account's own owner: the provider session and the
|
||||
* sign-in belong to whoever connected it, even when another
|
||||
* person's run is using it.
|
||||
*/
|
||||
user_id: account.user_id,
|
||||
account,
|
||||
namespace,
|
||||
names,
|
||||
redact,
|
||||
takeAction,
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!built.tools.length) continue;
|
||||
|
||||
tools.push(...built.tools);
|
||||
closers.push(built.close);
|
||||
lines.push(
|
||||
`${connector.name} (${account.label}${shared ? `, ${account.owner_name}'s account` : ""}): call its tools as ${namespace}__*, listing ${built.tools.length} tool${built.tools.length == 1 ? "" : "s"} you load with load_tools first.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
tools,
|
||||
lines,
|
||||
connectors: runConnectors,
|
||||
close: async () => {
|
||||
await Promise.all(closers.map(async (close) => close().catch(() => {})));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import type { CustomToolPromptConfig, CustomToolRecord } from "@/src/types";
|
||||
import type { HarnessMessage } from "../../types";
|
||||
|
||||
let sent: HarnessMessage[] = [];
|
||||
|
||||
mock.module("../../text/generate-text", () => ({
|
||||
default: async ({ messages }: { messages: HarnessMessage[] }) => {
|
||||
sent = messages;
|
||||
return { text: "the answer" };
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: buildCustomTool } = await import("./build-custom-tool");
|
||||
|
||||
afterAll(() => mock.restore());
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
function promptTool(): CustomToolRecord {
|
||||
return {
|
||||
id: 1,
|
||||
name: "summarise",
|
||||
description: "Summarises something",
|
||||
kind: "prompt",
|
||||
config: { prompt: "Password: {{args.password}}" } as CustomToolPromptConfig,
|
||||
parameters: { type: "object", properties: { password: { type: "string" } } },
|
||||
all_bots: false,
|
||||
enabled: true,
|
||||
status: "untested",
|
||||
last_error: "",
|
||||
last_checked_at: null,
|
||||
updated_at: null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildCustomTool fills {{env.KEY}} in the arguments", () => {
|
||||
test("an argument template is filled before the tool runs", async () => {
|
||||
sent = [];
|
||||
|
||||
const tool = buildCustomTool({
|
||||
tool: promptTool(),
|
||||
envs: [],
|
||||
arg_envs: [{ key: "MAIL_PASSWORD", value: "hunter2secret", secret: true }],
|
||||
record: false,
|
||||
});
|
||||
|
||||
await tool!.run({ args: { password: "{{env.MAIL_PASSWORD}}" }, signal });
|
||||
|
||||
expect(String(sent[0]?.content)).toBe("Password: [MAIL_PASSWORD]");
|
||||
});
|
||||
|
||||
test("a prompt tool gets a secret's marker, never its value", async () => {
|
||||
sent = [];
|
||||
|
||||
const tool = buildCustomTool({
|
||||
tool: promptTool(),
|
||||
envs: [],
|
||||
arg_envs: [{ key: "MAIL_PASSWORD", value: "hunter2secret", secret: true }],
|
||||
record: false,
|
||||
});
|
||||
|
||||
const result = await tool!.run({ args: { password: "{{env.MAIL_PASSWORD}}" }, signal });
|
||||
|
||||
expect(result).not.toContain("hunter2secret");
|
||||
expect(String(sent[0]?.content)).not.toContain("hunter2secret");
|
||||
});
|
||||
|
||||
test("an argument with no template is passed as it was sent", async () => {
|
||||
sent = [];
|
||||
|
||||
const tool = buildCustomTool({ tool: promptTool(), envs: [], arg_envs: [], record: false });
|
||||
|
||||
await tool!.run({ args: { password: "typed by hand" }, signal });
|
||||
|
||||
expect(String(sent[0]?.content)).toBe("Password: typed by hand");
|
||||
});
|
||||
|
||||
test("a key that isn't set names Settings > Environment", async () => {
|
||||
const tool = buildCustomTool({ tool: promptTool(), envs: [], arg_envs: [], record: false });
|
||||
|
||||
await expect(tool!.run({ args: { password: "{{env.NOT_SET}}" }, signal })).rejects.toThrow(
|
||||
/NOT_SET isn't set. Add it in Settings, under Environment/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import type { CustomToolRecord } from "@/src/types";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import checkRequiredArgs from "./check-required-args";
|
||||
import fillEnvArgs from "./fill-env-args";
|
||||
import runHttpTool from "./run-http-tool";
|
||||
import runPromptTool from "./run-prompt-tool";
|
||||
import runScriptTool from "./run-script-tool";
|
||||
@@ -15,6 +16,12 @@ type Params = {
|
||||
* out of every result and error.
|
||||
*/
|
||||
envs: { key: string; value: string; secret: boolean }[];
|
||||
/**
|
||||
* What `{{env.KEY}}` reads when the model writes it in an argument:
|
||||
* every env the run can reach on this computer, not only the ones tools
|
||||
* fill in themselves. Defaults to `envs`.
|
||||
*/
|
||||
arg_envs?: { key: string; value: string; secret: boolean }[];
|
||||
/**
|
||||
* Where a script tool runs. Without one, a script tool isn't offered.
|
||||
*/
|
||||
@@ -47,6 +54,7 @@ type Params = {
|
||||
export default function buildCustomTool({
|
||||
tool,
|
||||
envs,
|
||||
arg_envs,
|
||||
computer_id,
|
||||
bot_id,
|
||||
user_id,
|
||||
@@ -56,9 +64,28 @@ export default function buildCustomTool({
|
||||
}: Params): HarnessTool<Record<string, unknown>> | null {
|
||||
if (tool.kind == "script" && !computer_id) return null;
|
||||
|
||||
const secrets = envs.filter((env) => env.secret);
|
||||
/**
|
||||
* A value filled into an argument can come back in the result (the
|
||||
* script echoes it, the server answers with it), so what fills the
|
||||
* arguments is redacted too.
|
||||
*/
|
||||
const secrets = [
|
||||
...new Map(
|
||||
[...envs, ...(arg_envs || [])].filter((env) => env.secret).map((env) => [env.key, env]),
|
||||
).values(),
|
||||
];
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
|
||||
/**
|
||||
* A prompt tool's filled text IS the model's input, so a secret fills in
|
||||
* there as its `[KEY]` marker, never its value (`runPromptTool` does the
|
||||
* same for the prompt itself). HTTP and script tools get the value: it
|
||||
* stays in the request or the script, where the model never sees it.
|
||||
*/
|
||||
const arg_values = (arg_envs || envs).map((env) =>
|
||||
tool.kind == "prompt" && env.secret ? { ...env, value: `[${env.key}]` } : env,
|
||||
);
|
||||
|
||||
const call = ({ args, signal }: { args: Record<string, unknown>; signal: AbortSignal }) => {
|
||||
switch (tool.kind) {
|
||||
case "http":
|
||||
@@ -79,6 +106,14 @@ export default function buildCustomTool({
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The arguments as the model sent them, with `{{env.KEY}}` filled in:
|
||||
* the run is told that is how a tool reads an env, so an argument that
|
||||
* holds one is a template, not a literal string.
|
||||
*/
|
||||
const filledArgs = ({ args }: { args: Record<string, unknown> }) =>
|
||||
fillEnvArgs({ value: args, envs: arg_values }) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
name: tool.name,
|
||||
description:
|
||||
@@ -90,7 +125,7 @@ export default function buildCustomTool({
|
||||
checkRequiredArgs({ parameters: tool.parameters, args });
|
||||
|
||||
try {
|
||||
const result = redact(await call({ args, signal }));
|
||||
const result = redact(await call({ args: filledArgs({ args }), signal }));
|
||||
if (record) await recordCustomToolRun({ custom_tool_id: tool.id });
|
||||
return result;
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import fillEnvArgs from "./fill-env-args";
|
||||
|
||||
const envs = [
|
||||
{ key: "MAIL_PASSWORD", value: "s3cret" },
|
||||
{ key: "MAIL_USER", value: "[email protected]" },
|
||||
];
|
||||
|
||||
describe("fillEnvArgs", () => {
|
||||
test("fills an env named in a string argument", () => {
|
||||
expect(fillEnvArgs({ value: "{{env.MAIL_PASSWORD}}", envs })).toBe("s3cret");
|
||||
});
|
||||
|
||||
test("fills one inside a longer string, and every occurrence", () => {
|
||||
expect(
|
||||
fillEnvArgs({
|
||||
value: "imap://{{env.MAIL_USER}}:{{ env.MAIL_PASSWORD }}@box/mail",
|
||||
envs,
|
||||
}),
|
||||
).toBe("imap://[email protected]:s3cret@box/mail");
|
||||
});
|
||||
|
||||
test("walks objects and arrays", () => {
|
||||
expect(
|
||||
fillEnvArgs({
|
||||
value: {
|
||||
password: "{{env.MAIL_PASSWORD}}",
|
||||
to: ["{{env.MAIL_USER}}", "[email protected]"],
|
||||
nested: { user: "{{env.MAIL_USER}}" },
|
||||
port: 993,
|
||||
},
|
||||
envs,
|
||||
}),
|
||||
).toEqual({
|
||||
password: "s3cret",
|
||||
to: ["[email protected]", "[email protected]"],
|
||||
nested: { user: "[email protected]" },
|
||||
port: 993,
|
||||
});
|
||||
});
|
||||
|
||||
test("leaves text without a template untouched", () => {
|
||||
expect(fillEnvArgs({ value: "list_folders", envs })).toBe("list_folders");
|
||||
expect(fillEnvArgs({ value: 25, envs })).toBe(25);
|
||||
expect(fillEnvArgs({ value: null, envs })).toBeNull();
|
||||
});
|
||||
|
||||
test("leaves a template it does not know as written", () => {
|
||||
expect(fillEnvArgs({ value: "{{args.anything}}", envs })).toBe("{{args.anything}}");
|
||||
expect(fillEnvArgs({ value: '{"a": "{{other}}"}', envs })).toBe('{"a": "{{other}}"}');
|
||||
});
|
||||
|
||||
test("a key that isn't set throws, naming it and where to add it", () => {
|
||||
expect(() => fillEnvArgs({ value: "{{env.NOPE}}", envs })).toThrow(
|
||||
"The env NOPE isn't set. Add it in Settings, under Environment.",
|
||||
);
|
||||
});
|
||||
|
||||
test("does not fill the same env twice from a previous call", () => {
|
||||
const args = { password: "{{env.MAIL_PASSWORD}}" };
|
||||
|
||||
expect(fillEnvArgs({ value: args, envs })).toEqual({ password: "s3cret" });
|
||||
expect(fillEnvArgs({ value: args, envs })).toEqual({ password: "s3cret" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { EnvPattern, envTemplateValue } from "@/src/utils/fill-template";
|
||||
|
||||
type Env = { key: string; value: string };
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The arguments the model sent the tool.
|
||||
*/
|
||||
value: unknown;
|
||||
/**
|
||||
* What `{{env.KEY}}` reads. A secret fills in as its `[KEY]` marker here
|
||||
* when the value would otherwise reach the model; the caller decides.
|
||||
*/
|
||||
envs: Env[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Fills `{{env.KEY}}` in the arguments a custom tool is called with
|
||||
* (strings, and strings inside objects and arrays), the same way its
|
||||
* template is filled. The run is told `{{env.KEY}}` is how a tool reads an
|
||||
* env, so an argument written that way is the documented way to pass a
|
||||
* secret, not a literal string; a tool that never filled it in sent
|
||||
* `{{env.KEY}}` to the server or the script and failed.
|
||||
*
|
||||
* A key that isn't set throws naming it: better a clear refusal than a
|
||||
* credential sent as that literal text.
|
||||
*/
|
||||
export default function fillEnvArgs({ value, envs }: Params): unknown {
|
||||
if (typeof value == "string") return fillString({ text: value, envs });
|
||||
|
||||
if (Array.isArray(value)) return value.map((item) => fillEnvArgs({ value: item, envs }));
|
||||
|
||||
if (value && typeof value == "object") return fillObject({ value: value as Record<string, unknown>, envs });
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function fillObject({ value, envs }: { value: Record<string, unknown>; envs: Env[] }) {
|
||||
const filled: Record<string, unknown> = {};
|
||||
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
filled[key] = fillEnvArgs({ value: item, envs });
|
||||
}
|
||||
|
||||
return filled;
|
||||
}
|
||||
|
||||
function fillString({ text, envs }: { text: string; envs: Env[] }) {
|
||||
/**
|
||||
* Most arguments hold no template at all, and the walk runs over every
|
||||
* one of them on every call.
|
||||
*/
|
||||
if (!text.includes("{{")) return text;
|
||||
|
||||
return text.replace(EnvPattern, (_match, key: string) => envTemplateValue({ key, envs }));
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import grabBotExtensions from "@/src/functions/backend/db/extensions/grab-bot-extensions";
|
||||
import grabComputerEnvs from "@/src/functions/backend/db/envs/grab-computer-envs";
|
||||
import grabRunEnvs from "@/src/functions/backend/db/extensions/grab-run-envs";
|
||||
import type { KnowledgebaseRecord, SkillRecord } from "@/src/types";
|
||||
import mcpToolName from "@/src/utils/mcp-tool-name";
|
||||
@@ -77,6 +78,24 @@ export default async function openBotExtensions({
|
||||
}
|
||||
|
||||
const envs = await grabRunEnvs({ bot_id, user_id, workspace_id });
|
||||
/**
|
||||
* A custom tool's arguments are filled the same way its template is
|
||||
* (`fillEnvArgs`), and a key the run only has on its computer is one the
|
||||
* model is told to use by name: an argument naming it must fill in, not
|
||||
* be sent as that template. The run's own envs win on a key they share.
|
||||
*/
|
||||
const arg_envs = tools.length
|
||||
? [
|
||||
...new Map(
|
||||
[
|
||||
...(computer_id
|
||||
? await grabComputerEnvs({ computer_id, bot_id, user_id, workspace_id })
|
||||
: []),
|
||||
...envs,
|
||||
].map((env) => [env.key, env]),
|
||||
).values(),
|
||||
]
|
||||
: [];
|
||||
const secrets = envs.filter((env) => env.secret);
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
const names = new Set(taken);
|
||||
@@ -91,7 +110,7 @@ export default async function openBotExtensions({
|
||||
};
|
||||
|
||||
for (const tool of tools) {
|
||||
add(buildCustomTool({ tool, envs, computer_id, bot_id, user_id, workspace_id, dirs }));
|
||||
add(buildCustomTool({ tool, envs, arg_envs, computer_id, bot_id, user_id, workspace_id, dirs }));
|
||||
}
|
||||
|
||||
for (const server of servers) {
|
||||
|
||||
@@ -12,7 +12,6 @@ import { AppContext } from "../pages/__root";
|
||||
import type { ImageInputToBase64FunctionReturn } from "@moduletrace/twui/utils/form/imageInputToBase64";
|
||||
import EJSON from "../utils/ejson";
|
||||
import twuiSlugify from "@moduletrace/twui/utils/slugify";
|
||||
import _ from "lodash";
|
||||
import type { AppContextObject } from "../types";
|
||||
|
||||
type Params<T extends {} = BUN_SQLITE_COBBLE_ALL_TYPEDEFS> = {
|
||||
@@ -96,7 +95,14 @@ export default function useFormInit<
|
||||
|
||||
if (local_storage_form_title) {
|
||||
try {
|
||||
let form_to_store = _.cloneDeep(form);
|
||||
/**
|
||||
* A shallow copy is all this needs: the keys being left out
|
||||
* are taken off the copy, never out of the form itself, and
|
||||
* EJSON serialises the rest deeply. Importing lodash for
|
||||
* cloneDeep put the whole library in every page that uses a
|
||||
* form, the conversation page included.
|
||||
*/
|
||||
const form_to_store: Partial<T> = { ...form };
|
||||
|
||||
if (params?.local_storage_exclude_keys) {
|
||||
params.local_storage_exclude_keys.forEach((k) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import SettingsStatus from "@/src/pages/admin/settings/(partials)/settings-status";
|
||||
|
||||
@@ -7,22 +8,47 @@ type Props = {
|
||||
submit_label: string;
|
||||
loading?: boolean;
|
||||
error?: string;
|
||||
/**
|
||||
* A line above the buttons that isn't an error or a save, e.g. what a
|
||||
* pasted export brought along.
|
||||
*/
|
||||
notice?: string;
|
||||
/**
|
||||
* Left out on a form embedded in a settings page: then there is
|
||||
* nothing to cancel into.
|
||||
*/
|
||||
onCancel?: () => void;
|
||||
/**
|
||||
* An extra button before Cancel, e.g. pasting JSON into an add form.
|
||||
*/
|
||||
action?: { label: string; onClick: () => void };
|
||||
};
|
||||
|
||||
/**
|
||||
* The foot of an add form: the error, if any, then Cancel and the submit
|
||||
* button.
|
||||
*/
|
||||
export default function AddFormActions({ submit_label, loading, error, onCancel }: Props) {
|
||||
export default function AddFormActions({ submit_label, loading, error, notice, onCancel, action }: Props) {
|
||||
return (
|
||||
<Stack className="gap-3! items-stretch">
|
||||
{notice ? (
|
||||
<Span className="text-[13px] leading-[18px] whitespace-pre-line text-ink-secondary">{notice}</Span>
|
||||
) : null}
|
||||
<SettingsStatus status={error ? { error: true, msg: error } : undefined} />
|
||||
<Row className="gap-2! flex-nowrap justify-end">
|
||||
{action ? (
|
||||
<Button
|
||||
title={action.label}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
disabled={loading}
|
||||
onClick={action.onClick}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
) : null}
|
||||
{onCancel ? (
|
||||
<Button
|
||||
title="Cancel"
|
||||
@@ -42,4 +68,4 @@ export default function AddFormActions({ submit_label, loading, error, onCancel
|
||||
</Row>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import TopModalEscape from "@/src/components/general/top-modal-escape";
|
||||
@@ -10,6 +11,10 @@ type Props = {
|
||||
setOpen: (open: boolean) => void;
|
||||
title: string;
|
||||
description?: string;
|
||||
/**
|
||||
* A picture beside the title, e.g. the app an account signs in to.
|
||||
*/
|
||||
icon?: ReactNode;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
@@ -17,7 +22,7 @@ type Props = {
|
||||
* The frame every Add modal shares: a title, one line on what it does, the
|
||||
* content.
|
||||
*/
|
||||
export default function AddModalShell({ open, setOpen, title, description, children }: Props) {
|
||||
export default function AddModalShell({ open, setOpen, title, description, icon, children }: Props) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
@@ -25,13 +30,16 @@ export default function AddModalShell({ open, setOpen, title, description, child
|
||||
className="max-w-lg bg-paper p-6"
|
||||
>
|
||||
{open ? <TopModalEscape onClose={() => setOpen(false)} /> : null}
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{title}</H2>
|
||||
{description ? (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{description}</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
<Row className="w-full items-center gap-3! flex-nowrap">
|
||||
{icon}
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{title}</H2>
|
||||
{description ? (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{description}</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
</Row>
|
||||
{children}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { ConnectorRequestPayload } from "@/src/types";
|
||||
import loadRefView from "../(utils)/ref-view-loader";
|
||||
|
||||
/**
|
||||
* One connect card's request: read once, then kept here, so the buttons in
|
||||
* the card can put what they just learned back into it.
|
||||
*/
|
||||
export default function useConnectRequest({ request_id }: { request_id: number }) {
|
||||
const [view, setView] = useState<ConnectorRequestPayload | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
loadRefView<ConnectorRequestPayload>({
|
||||
key: `connect:${request_id}`,
|
||||
url: `/api/admin/connectors/request?request_id=${request_id}`,
|
||||
}).then((read) => {
|
||||
if (!live) return;
|
||||
|
||||
setView(read);
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [request_id]);
|
||||
|
||||
return { view, setView, loading };
|
||||
}
|
||||
@@ -145,6 +145,7 @@ export default function BotQuestionField({
|
||||
onChange={(e) =>
|
||||
onChange({ ...draft, other: e.target.value })
|
||||
}
|
||||
autoFocus
|
||||
/>
|
||||
) : null}
|
||||
</Stack>
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Check } from "lucide-react";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import ConnectorLogo from "@/src/pages/admin/settings/connectors/(partials)/connector-logo";
|
||||
import { ConnectorAccountStatuses } from "@/src/dict/connector-dict";
|
||||
import type {
|
||||
AttachableConnector,
|
||||
ConnectorAccountRecord,
|
||||
ConnectorConnectionRecord,
|
||||
ConnectorConnectionsPayload,
|
||||
} from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
onAdded: (msg: string) => void;
|
||||
onCancel: () => void;
|
||||
onError: (msg: string) => void;
|
||||
};
|
||||
|
||||
type SetBotPayload = { connector_id: number; attached: boolean };
|
||||
|
||||
const accountNote = ({ account }: { account: ConnectorAccountRecord }) => {
|
||||
if (account.status == "connected") return account.label;
|
||||
|
||||
const status =
|
||||
ConnectorAccountStatuses.find(
|
||||
(option) => option.value == account.status,
|
||||
)?.title || account.status;
|
||||
|
||||
return `${account.label} · ${status}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a connector to this bot, from the connection at the top down to the
|
||||
* account: pick which provider account (for example Composio Work), then the
|
||||
* app inside it, then the account that should reach this bot. Only apps with
|
||||
* a connected account reaching here are listed: one with no sign-in has
|
||||
* nothing to give the bot. The account stays the user's own; giving it here
|
||||
* says its runs on this bot may use it.
|
||||
*/
|
||||
export default function ComposerConnectorPicker({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
onAdded,
|
||||
onCancel,
|
||||
onError,
|
||||
}: Props) {
|
||||
const [connections, setConnections] =
|
||||
useState<ConnectorConnectionRecord[]>();
|
||||
const [connection_id, setConnectionId] = useState(0);
|
||||
const [query, setQuery] = useState("");
|
||||
const [items, setItems] = useState<AttachableConnector[]>();
|
||||
const [chosen, setChosen] = useState<AttachableConnector>();
|
||||
const [accounts, setAccounts] = useState<ConnectorAccountRecord[]>();
|
||||
const [account_id, setAccountId] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<ConnectorConnectionsPayload>
|
||||
>("/api/admin/connectors/connections", { method: "GET" });
|
||||
|
||||
if (!live) return;
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't read the connections.");
|
||||
return;
|
||||
}
|
||||
|
||||
const all = res.singleRes?.connections || [];
|
||||
setConnections(all);
|
||||
setConnectionId(Number(all[0]?.id) || 0);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!connection_id) return;
|
||||
|
||||
let live = true;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
const params = new URLSearchParams({
|
||||
bot_id: String(bot_id),
|
||||
connection_id: String(connection_id),
|
||||
q: query,
|
||||
});
|
||||
|
||||
if (workspace_id) params.set("workspace_id", String(workspace_id));
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<AttachableConnector[]>
|
||||
>(`/api/admin/connectors/attachables?${params.toString()}`, {
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
if (!live) return;
|
||||
|
||||
if (!res.success) {
|
||||
setError(
|
||||
res.msg || "Couldn't read the apps of that connection.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setItems(res.singleRes || []);
|
||||
})();
|
||||
}, 300);
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [bot_id, workspace_id, connection_id, query]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chosen) return;
|
||||
|
||||
let live = true;
|
||||
setAccounts(undefined);
|
||||
setAccountId(0);
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<ConnectorAccountRecord[]>
|
||||
>(
|
||||
`/api/admin/connectors/accounts?connector_id=${chosen.id}&bot_id=${bot_id}${workspace_id ? `&workspace_id=${workspace_id}` : ""}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
|
||||
if (!live) return;
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't read that app's accounts.");
|
||||
return;
|
||||
}
|
||||
|
||||
setAccounts(res.singleRes || []);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [chosen, bot_id, workspace_id]);
|
||||
|
||||
const add = async () => {
|
||||
if (!chosen) return;
|
||||
|
||||
setError(undefined);
|
||||
setBusy(true);
|
||||
|
||||
const account = accounts?.find((option) => option.id == account_id);
|
||||
|
||||
if (!account) {
|
||||
const added = await postAdminApi<SetBotPayload>({
|
||||
path: "connectors/set-bot",
|
||||
body: { connector_id: chosen.id, attached: true, bot_id },
|
||||
});
|
||||
|
||||
setBusy(false);
|
||||
|
||||
if (!added.success) {
|
||||
setError(added.msg || `Couldn't add ${chosen.name}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
onAdded(`${chosen.name} is now on this bot, with every account you have in it.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const given = await postAdminApi({
|
||||
path: "connectors/set-account-access",
|
||||
body: {
|
||||
account_id: account.id,
|
||||
workspace_ids: account.workspace_ids,
|
||||
bot_ids: [...account.bot_ids.map(Number), bot_id],
|
||||
all_bots: account.all_bots,
|
||||
},
|
||||
});
|
||||
|
||||
setBusy(false);
|
||||
|
||||
if (!given.success) {
|
||||
setError(given.msg || `Couldn't give ${account.label} to this bot.`);
|
||||
return;
|
||||
}
|
||||
|
||||
onAdded(`${chosen.name} is now on this bot, with ${account.label}.`);
|
||||
};
|
||||
|
||||
const connection_options = (connections || []).map((connection) => ({
|
||||
title: connection.name,
|
||||
value: String(connection.id),
|
||||
}));
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => {
|
||||
if (!next) onCancel();
|
||||
}}
|
||||
title="Add a connector"
|
||||
description="Pick the connection, then the app inside it, then the account that should reach this bot."
|
||||
>
|
||||
<Form
|
||||
submitHandler={() => void add()}
|
||||
className="w-full flex-col gap-3! items-stretch"
|
||||
>
|
||||
<SearchSelect
|
||||
id="composer-connector-connection"
|
||||
title="Connection"
|
||||
options={connection_options}
|
||||
defaultValues={connection_id ? [String(connection_id)] : []}
|
||||
changeHandler={(value) => {
|
||||
const picked = Array.isArray(value) ? value[0] : value;
|
||||
setChosen(undefined);
|
||||
setConnectionId(Number(picked) || 0);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Input
|
||||
id="composer-connector-search"
|
||||
title="Apps"
|
||||
placeholder="Search apps by name"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
|
||||
{items === undefined ? (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Reading apps...
|
||||
</Span>
|
||||
) : items.length ? (
|
||||
<Stack className="w-full max-h-52 overflow-y-auto py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface">
|
||||
{items.map((connector) => (
|
||||
<Button
|
||||
key={connector.id}
|
||||
title={connector.name}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
onClick={() => {
|
||||
setChosen(connector);
|
||||
setAccountId(0);
|
||||
}}
|
||||
className={
|
||||
chosen?.id == connector.id
|
||||
? "w-full justify-start! rounded-none! px-3! py-1.5! bg-sunken!"
|
||||
: "w-full justify-start! rounded-none! px-3! py-1.5!"
|
||||
}
|
||||
>
|
||||
<Row className="w-full gap-2.5! flex-nowrap items-center">
|
||||
<ConnectorLogo
|
||||
logo={connector.logo}
|
||||
name={connector.name}
|
||||
/>
|
||||
<Stack className="grow min-w-0 items-start gap-0!">
|
||||
<Span className="text-sm leading-5 truncate text-ink">
|
||||
{connector.name}
|
||||
</Span>
|
||||
<Span className="text-xs leading-4 truncate text-ink-secondary">
|
||||
{connector.connection_name}
|
||||
</Span>
|
||||
</Stack>
|
||||
{chosen?.id == connector.id ? (
|
||||
<Check size={14} aria-hidden />
|
||||
) : null}
|
||||
</Row>
|
||||
</Button>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Nothing to add: no connected app matches that, or every
|
||||
one is already on this bot.
|
||||
</Span>
|
||||
)}
|
||||
|
||||
{chosen ? (
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Span className="text-xs leading-4 font-bold text-ink">
|
||||
Account
|
||||
</Span>
|
||||
{accounts === undefined ? (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Reading accounts...
|
||||
</Span>
|
||||
) : (
|
||||
<Stack className="w-full py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface">
|
||||
<Button
|
||||
title={`Give ${chosen.name} every account you have`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
onClick={() => setAccountId(0)}
|
||||
className={
|
||||
account_id == 0
|
||||
? "w-full justify-start! rounded-none! px-3! py-1.5! bg-sunken!"
|
||||
: "w-full justify-start! rounded-none! px-3! py-1.5!"
|
||||
}
|
||||
>
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
<Stack className="grow min-w-0 items-start gap-0!">
|
||||
<Span className="text-sm leading-5 truncate w-full text-left text-ink">
|
||||
All accounts
|
||||
</Span>
|
||||
<Span className="text-xs leading-4 truncate w-full text-left text-ink-secondary">
|
||||
Every account you have in{" "}
|
||||
{chosen.name}
|
||||
</Span>
|
||||
</Stack>
|
||||
{account_id == 0 ? (
|
||||
<Check size={14} aria-hidden />
|
||||
) : null}
|
||||
</Row>
|
||||
</Button>
|
||||
{(accounts || []).map((account) => (
|
||||
<Button
|
||||
key={account.id}
|
||||
title={accountNote({ account })}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
onClick={() => setAccountId(account.id)}
|
||||
className={
|
||||
account_id == account.id
|
||||
? "w-full justify-start! rounded-none! px-3! py-1.5! bg-sunken!"
|
||||
: "w-full justify-start! rounded-none! px-3! py-1.5!"
|
||||
}
|
||||
>
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
<Span className="grow text-sm leading-5 text-left text-ink">
|
||||
{accountNote({ account })}
|
||||
</Span>
|
||||
{account_id == account.id ? (
|
||||
<Check size={14} aria-hidden />
|
||||
) : null}
|
||||
</Row>
|
||||
</Button>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
{account_id == 0 && !(accounts || []).length ? (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Every account you have here already reaches this
|
||||
bot; All accounts keeps that true for ones you
|
||||
connect later. Another account can be connected
|
||||
in Settings > Connectors.
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
<AddFormActions
|
||||
submit_label="Add"
|
||||
loading={busy}
|
||||
error={error}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</Form>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import { X } from "lucide-react";
|
||||
import { ConnectorAccountStatuses } from "@/src/dict/connector-dict";
|
||||
import type { BotConnectorEntry, ConnectorAccountRecord } from "@/src/types";
|
||||
import ConnectorLogo from "@/src/pages/admin/settings/connectors/(partials)/connector-logo";
|
||||
|
||||
type Props = {
|
||||
entry: BotConnectorEntry;
|
||||
/**
|
||||
* Takes it off this bot: this user's own attachment, or their own account
|
||||
* given here. Not given for a workspace's or the install's.
|
||||
*/
|
||||
onRemove?: () => void;
|
||||
};
|
||||
|
||||
const viaNote = ({ entry }: { entry: BotConnectorEntry }) =>
|
||||
entry.via == "global"
|
||||
? "Every bot"
|
||||
: entry.via == "workspace"
|
||||
? "From this workspace"
|
||||
: entry.via == "account"
|
||||
? "From an account given here"
|
||||
: "Only you";
|
||||
|
||||
const accountNote = ({ account }: { account: ConnectorAccountRecord }) => {
|
||||
if (account.status == "connected") return account.label;
|
||||
|
||||
const status =
|
||||
ConnectorAccountStatuses.find(
|
||||
(option) => option.value == account.status,
|
||||
)?.title || account.status;
|
||||
|
||||
return `${account.label} · ${status}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* One connector app in the composer's tools modal: its logo, the connection it
|
||||
* came from, the account it reaches through (when one was given here rather
|
||||
* than the whole app), where it comes from, and a way to take it off the bot.
|
||||
* An app with no account says so rather than listing nothing.
|
||||
*/
|
||||
export default function ComposerConnectorRow({ entry, onRemove }: Props) {
|
||||
const connected = entry.accounts.filter(
|
||||
(account) => account.status == "connected",
|
||||
);
|
||||
const given =
|
||||
entry.via == "account"
|
||||
? connected.filter(
|
||||
(account) =>
|
||||
account.all_bots ||
|
||||
account.bot_ids.length ||
|
||||
account.workspace_ids.length,
|
||||
)
|
||||
: [];
|
||||
const pending = entry.accounts.filter(
|
||||
(account) => account.status != "connected",
|
||||
);
|
||||
const subtitle = connected.length
|
||||
? viaNote({ entry })
|
||||
: `${viaNote({ entry })} · ${
|
||||
pending.length
|
||||
? pending
|
||||
.map((account) => accountNote({ account }))
|
||||
.join(", ")
|
||||
: "no account connected yet"
|
||||
}`;
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-2.5! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<ConnectorLogo
|
||||
logo={entry.connector.logo}
|
||||
name={entry.connector.name}
|
||||
/>
|
||||
<Stack className="grow min-w-0 gap-0.5!">
|
||||
<Row className="w-full gap-1.5! flex-nowrap items-center min-w-0">
|
||||
<Span
|
||||
title={entry.connector.description}
|
||||
className="text-sm leading-5 truncate text-ink"
|
||||
>
|
||||
{entry.connector.name}
|
||||
</Span>
|
||||
{entry.connection_name ? (
|
||||
<Tag color="success" className="shrink-0">
|
||||
{entry.connection_name}
|
||||
</Tag>
|
||||
) : null}
|
||||
{given.map((account) => (
|
||||
<Tag
|
||||
key={account.id}
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
className="shrink-0"
|
||||
>
|
||||
{account.label}
|
||||
</Tag>
|
||||
))}
|
||||
</Row>
|
||||
<Span className="text-xs leading-4 truncate w-full text-ink-secondary">
|
||||
{subtitle}
|
||||
</Span>
|
||||
</Stack>
|
||||
{onRemove ? (
|
||||
<Button
|
||||
title={`Remove ${entry.connector.name}`}
|
||||
aria-label={`Remove ${entry.connector.name}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="shrink-0 p-1!"
|
||||
onClick={onRemove}
|
||||
>
|
||||
<X size={14} aria-hidden />
|
||||
</Button>
|
||||
) : null}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotConnectorEntry, ConnectorAppIcon } from "@/src/types";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import ComposerConnectorPicker from "./composer-connector-picker";
|
||||
import ComposerConnectorRow from "./composer-connector-row";
|
||||
|
||||
type Props = {
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
/**
|
||||
* Read only while the modal is open: a conversation shouldn't pay for a
|
||||
* list nobody is looking at.
|
||||
*/
|
||||
open: boolean;
|
||||
/**
|
||||
* How many apps reach the bot here, told to the composer so its tools
|
||||
* count follows an add or a remove without a reload.
|
||||
*/
|
||||
onCount?: (count: number) => void;
|
||||
/**
|
||||
* The apps a connected account reaches here, told to the composer for the
|
||||
* icons on its tools button.
|
||||
*/
|
||||
onApps?: (apps: ConnectorAppIcon[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The connectors this bot can use for the person chatting, shown under the
|
||||
* tools in the composer's modal. Apps given to the bot by the workspace or
|
||||
* the install, and the ones this user attached, with the accounts that
|
||||
* reach there. Sign-in itself lives in Settings > Connectors.
|
||||
*/
|
||||
export default function ComposerConnectorsSection({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
open,
|
||||
onCount,
|
||||
onApps,
|
||||
}: Props) {
|
||||
const [items, setItems] = useState<BotConnectorEntry[]>();
|
||||
const [error, setError] = useState<string>();
|
||||
const [notice, setNotice] = useState<string>();
|
||||
const [tick, setTick] = useState(0);
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
const reload = useCallback((msg?: string) => {
|
||||
if (msg) setNotice(msg);
|
||||
setTick((value) => value + 1);
|
||||
}, []);
|
||||
|
||||
const remove = async ({ entry }: { entry: BotConnectorEntry }) => {
|
||||
const res = await postAdminApi({
|
||||
path: "connectors/detach",
|
||||
body: { connector_id: entry.connector.id, bot_id },
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || `Couldn't remove ${entry.connector.name}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
reload(`${entry.connector.name} is no longer on this bot.`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
let live = true;
|
||||
const params = new URLSearchParams({ bot_id: String(bot_id) });
|
||||
|
||||
if (workspace_id) params.set("workspace_id", String(workspace_id));
|
||||
|
||||
setError(undefined);
|
||||
|
||||
void (async () => {
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<BotConnectorEntry[]>
|
||||
>(`/api/admin/connectors/bot?${params.toString()}`, {
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
if (!live) return;
|
||||
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't read this bot's connectors.");
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = res.singleRes || [];
|
||||
|
||||
setItems(entries);
|
||||
onCount?.(entries.length);
|
||||
onApps?.(
|
||||
entries
|
||||
.filter((entry) =>
|
||||
entry.accounts.some((account) => account.status == "connected"),
|
||||
)
|
||||
.map((entry) => ({
|
||||
id: Number(entry.connector.id),
|
||||
name: entry.connector.name,
|
||||
logo: entry.connector.logo,
|
||||
})),
|
||||
);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [open, bot_id, workspace_id, tick, onCount, onApps]);
|
||||
|
||||
return (
|
||||
<Stack className="w-full mt-4 pt-4 items-stretch border-0 border-t border-solid border-hairline">
|
||||
<Row className="w-full items-center gap-2!">
|
||||
<Span className="grow text-[13px] leading-[18px] font-bold text-ink">
|
||||
Connectors
|
||||
</Span>
|
||||
<Button
|
||||
title={
|
||||
adding
|
||||
? "Stop adding a connector"
|
||||
: "Add a connector to this bot"
|
||||
}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={<Plus size={12} aria-hidden />}
|
||||
className="shrink-0 gap-1! px-1.5! py-0.5! text-[12px] leading-4"
|
||||
onClick={() => setAdding((value) => !value)}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</Row>
|
||||
|
||||
{notice ? (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
{notice}
|
||||
</Span>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<Span
|
||||
role="alert"
|
||||
className="text-xs leading-4 text-ink-secondary"
|
||||
>
|
||||
{error}
|
||||
</Span>
|
||||
) : items === undefined ? (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
Reading connectors...
|
||||
</Span>
|
||||
) : items.length ? (
|
||||
<Stack className="w-full py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface">
|
||||
{items.map((entry) => (
|
||||
<ComposerConnectorRow
|
||||
key={entry.connector.id}
|
||||
entry={entry}
|
||||
onRemove={
|
||||
entry.removable
|
||||
? () => void remove({ entry })
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
No connector is given to this bot yet. Give one in{" "}
|
||||
<Link
|
||||
href="/admin/settings/connectors"
|
||||
target="_blank"
|
||||
className="underline"
|
||||
>
|
||||
Settings > Connectors
|
||||
</Link>
|
||||
</Span>
|
||||
)}
|
||||
|
||||
{adding ? (
|
||||
<ComposerConnectorPicker
|
||||
bot_id={bot_id}
|
||||
workspace_id={workspace_id}
|
||||
onAdded={(msg) => {
|
||||
setAdding(false);
|
||||
reload(msg);
|
||||
}}
|
||||
onCancel={() => setAdding(false)}
|
||||
onError={setError}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Span variant="faded" size="smaller">
|
||||
Manage connectors{" "}
|
||||
<Link
|
||||
href="/admin/settings/connectors"
|
||||
target="_blank"
|
||||
className="underline"
|
||||
>
|
||||
here
|
||||
</Link>
|
||||
</Span>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -2,12 +2,21 @@ import { useState } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { CircleAlert, type LucideIcon } from "lucide-react";
|
||||
import ExtensionAddSelect from "@/src/components/general/extension-add-select";
|
||||
import type { BotExtension, BotExtensionKind, BotExtensionsPayload } from "@/src/types";
|
||||
import type {
|
||||
BotExtension,
|
||||
BotExtensionKind,
|
||||
BotExtensionsPayload,
|
||||
ConnectorAppIcon,
|
||||
} from "@/src/types";
|
||||
import ComposerConnectorsSection from "./composer-connectors-section";
|
||||
import ComposerToolRow from "./composer-tool-row";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
/**
|
||||
* What one of the composer's buttons is about, in copy: its tools, or its
|
||||
@@ -49,7 +58,33 @@ type Props = {
|
||||
*/
|
||||
busy?: string;
|
||||
onAdd: (params: { kind: BotExtensionKind; id: number }) => Promise<boolean>;
|
||||
onRemove: (params: { kind: BotExtensionKind; id: number; name: string }) => Promise<boolean>;
|
||||
onRemove: (params: {
|
||||
kind: BotExtensionKind;
|
||||
id: number;
|
||||
name: string;
|
||||
}) => Promise<boolean>;
|
||||
/**
|
||||
* Where to read the bot's connectors from, for the tools modal only: the
|
||||
* apps it can use here as the person chatting.
|
||||
*/
|
||||
connectors?: { bot_id: number; workspace_id?: number | null };
|
||||
/**
|
||||
* How many apps connector accounts reach here, counted with the tools
|
||||
* (a connector is a tool too).
|
||||
*/
|
||||
connector_count?: number;
|
||||
/**
|
||||
* Told the live count once the connectors are read, so the button's
|
||||
* number follows an add or a remove without a reload.
|
||||
*/
|
||||
onConnectorCount?: (count: number) => void;
|
||||
/**
|
||||
* The apps a connector account reaches here, drawn as small circles
|
||||
* before the spanner (5 at most). Read with the count, so adding or
|
||||
* removing one shows without a reload.
|
||||
*/
|
||||
connector_apps?: ConnectorAppIcon[];
|
||||
onConnectorApps?: (apps: ConnectorAppIcon[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -67,14 +102,23 @@ export default function ComposerToolsModal({
|
||||
busy,
|
||||
onAdd,
|
||||
onRemove,
|
||||
connectors,
|
||||
connector_count = 0,
|
||||
onConnectorCount,
|
||||
connector_apps = [],
|
||||
onConnectorApps,
|
||||
}: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const count = attached.length;
|
||||
const total = count + (connectors ? Number(connector_count || 0) : 0);
|
||||
const has_problem = attached.some(
|
||||
(item) => !item.enabled || item.state == "error",
|
||||
);
|
||||
const TriggerIcon = has_problem ? CircleAlert : copy.Icon;
|
||||
const label = count ? `${count} ${count == 1 ? copy.one : copy.many}` : copy.empty_label;
|
||||
const app_icons = connector_apps.filter((app) => app.logo).slice(0, 5);
|
||||
const label = total
|
||||
? `${total} ${total == 1 ? copy.one : copy.many}`
|
||||
: copy.empty_label;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -85,7 +129,26 @@ export default function ComposerToolsModal({
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={<TriggerIcon size={12} aria-hidden />}
|
||||
beforeIcon={
|
||||
<Row className="items-center gap-1! flex-nowrap">
|
||||
{app_icons.map((app, index) => (
|
||||
<Img
|
||||
key={app.id}
|
||||
src={app.logo}
|
||||
alt={app.name}
|
||||
title={app.name}
|
||||
size={16}
|
||||
circle
|
||||
className={twMerge(
|
||||
"shrink-0 border border-hairline bg-white object-contain relative",
|
||||
index > 0 ? "-ml-1.5" : "",
|
||||
)}
|
||||
style={{ zIndex: index + 1 }}
|
||||
/>
|
||||
))}
|
||||
<TriggerIcon size={12} aria-hidden />
|
||||
</Row>
|
||||
}
|
||||
className="shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary"
|
||||
>
|
||||
{label}
|
||||
@@ -101,7 +164,7 @@ export default function ComposerToolsModal({
|
||||
{copy.title}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{count ? copy.some : copy.none}
|
||||
{total ? copy.some : copy.none}
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
@@ -144,6 +207,16 @@ export default function ComposerToolsModal({
|
||||
/>
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
{connectors ? (
|
||||
<ComposerConnectorsSection
|
||||
bot_id={connectors.bot_id}
|
||||
workspace_id={connectors.workspace_id}
|
||||
open={open}
|
||||
onCount={onConnectorCount}
|
||||
onApps={onConnectorApps}
|
||||
/>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { useContext } from "react";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useExtensions from "@/src/hooks/use-extensions";
|
||||
import type { BotExtensionsPayload, BotWithLastMessage } from "@/src/types";
|
||||
import type {
|
||||
BotExtensionsPayload,
|
||||
BotWithLastMessage,
|
||||
ConnectorAppIcon,
|
||||
} from "@/src/types";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
import { composerKnowledgebasesCopy, composerToolsCopy } from "../(data)/composer-extensions-copy";
|
||||
import ComposerBrowserButton from "./composer-browser-button";
|
||||
@@ -63,7 +67,24 @@ export default function ComposerTools({
|
||||
addable: extensions.addable.filter(is_knowledge),
|
||||
};
|
||||
|
||||
const has_tools = Boolean(tools.attached.length || (extensions.can_manage && tools.addable.length));
|
||||
const [connector_count, set_connector_count] = useState(
|
||||
Number(initial?.connector_count || 0),
|
||||
);
|
||||
const [connector_apps, set_connector_apps] = useState<ConnectorAppIcon[]>(
|
||||
initial?.connector_apps || [],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
set_connector_count(Number(initial?.connector_count || 0));
|
||||
}, [initial?.connector_count]);
|
||||
|
||||
useEffect(() => {
|
||||
set_connector_apps(initial?.connector_apps || []);
|
||||
}, [initial?.connector_apps]);
|
||||
|
||||
const has_tools = Boolean(
|
||||
tools.attached.length || connector_count || (extensions.can_manage && tools.addable.length),
|
||||
);
|
||||
const has_knowledge = Boolean(knowledge.attached.length || (extensions.can_manage && knowledge.addable.length));
|
||||
|
||||
return (
|
||||
@@ -82,6 +103,11 @@ export default function ComposerTools({
|
||||
busy={extensions.busy}
|
||||
onAdd={extensions.add}
|
||||
onRemove={extensions.remove}
|
||||
connectors={{ bot_id: bot.id || 0, workspace_id }}
|
||||
connector_count={connector_count}
|
||||
onConnectorCount={set_connector_count}
|
||||
connector_apps={connector_apps}
|
||||
onConnectorApps={set_connector_apps}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { Cable, CircleCheck, ExternalLink, RefreshCw } from "lucide-react";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ConnectorRequestPayload } from "@/src/types";
|
||||
import useConnectRequest from "../(hooks)/use-connect-request";
|
||||
import RefCardShell from "./ref-card-shell";
|
||||
|
||||
type Props = {
|
||||
request_id: number;
|
||||
};
|
||||
|
||||
const StatusLabels = {
|
||||
pending: "Waiting for you",
|
||||
connected: "Connected",
|
||||
expired: "Expired",
|
||||
cancelled: "Cancelled",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* A connector the bot needs an account for, as the card the user acts on:
|
||||
* the provider's own sign-in opened from here, then read again until it
|
||||
* says the account is in. What is connected is the viewer's alone.
|
||||
*/
|
||||
export default function ConnectRefCard({ request_id }: Props) {
|
||||
const { view, setView, loading } = useConnectRequest({ request_id });
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `connect ${request_id}` : `connect ${request_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
const pending = view.status == "pending";
|
||||
const connected = view.status == "connected";
|
||||
|
||||
const recheck = async () => {
|
||||
const res = await postAdminApi<ConnectorRequestPayload>({
|
||||
path: "connectors/connection-status",
|
||||
body: { request_id },
|
||||
});
|
||||
|
||||
if (res.singleRes) setView(res.singleRes);
|
||||
};
|
||||
|
||||
return (
|
||||
<RefCardShell
|
||||
icon={<Cable size={14} aria-hidden />}
|
||||
title={view.connector_name}
|
||||
status={StatusLabels[view.status]}
|
||||
tone={connected ? "success" : pending ? "warning" : "gray"}
|
||||
description={
|
||||
connected
|
||||
? `Your ${view.label || "account"} is connected. Its tools are ready for your next message.`
|
||||
: pending
|
||||
? "Its sign-in happens at the provider, which keeps the account. Nothing here sees it."
|
||||
: view.status == "expired"
|
||||
? "The link expired before the sign-in finished. Ask the bot to send a new one."
|
||||
: "This connect request was cancelled."
|
||||
}
|
||||
>
|
||||
{pending ? (
|
||||
<Row className="flex-wrap items-center gap-2!">
|
||||
<Button
|
||||
title={`Open the sign-in for ${view.connector_name}`}
|
||||
type="button"
|
||||
size="small"
|
||||
className="gap-1!"
|
||||
href={view.url}
|
||||
linkProps={{ target: "_blank", rel: "noopener noreferrer" }}
|
||||
>
|
||||
<ExternalLink size={14} aria-hidden />
|
||||
Open sign-in
|
||||
</Button>
|
||||
<Button
|
||||
title="Check whether the sign-in finished"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="gap-1!"
|
||||
onClick={recheck}
|
||||
>
|
||||
<RefreshCw size={14} aria-hidden />
|
||||
Check again
|
||||
</Button>
|
||||
</Row>
|
||||
) : connected ? (
|
||||
<Row className="items-center gap-1.5!">
|
||||
<CircleCheck size={14} aria-hidden />
|
||||
<Span className="text-[13px] leading-[18px] text-ink">Connected as {view.label}.</Span>
|
||||
</Row>
|
||||
) : null}
|
||||
</RefCardShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { isCardRefHref } from "./card-ref-href";
|
||||
|
||||
describe("isCardRefHref", () => {
|
||||
test("a connect ref is a card", () => {
|
||||
expect(isCardRefHref({ href: "#connect-4" })).toBe(true);
|
||||
});
|
||||
|
||||
test("a file ref stays on the line", () => {
|
||||
expect(isCardRefHref({ href: "#file-4" })).toBe(false);
|
||||
});
|
||||
|
||||
test("an empty href is no card", () => {
|
||||
expect(isCardRefHref({ href: undefined })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { HookProposalRefHrefPrefix, ProposalRefHrefPrefix, SecretRequestRefHrefPrefix } from "@/src/utils/link-computer-refs";
|
||||
import { ConnectRefHrefPrefix, HookProposalRefHrefPrefix, ProposalRefHrefPrefix, SecretRequestRefHrefPrefix } from "@/src/utils/link-computer-refs";
|
||||
import { botPlanRefId } from "@/src/utils/bot-plan-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
|
||||
@@ -17,6 +17,7 @@ export function isCardRefHref({ href }: { href?: string }): boolean {
|
||||
botQuestionRefId({ href }) ||
|
||||
href.startsWith(ProposalRefHrefPrefix) ||
|
||||
href.startsWith(HookProposalRefHrefPrefix) ||
|
||||
href.startsWith(SecretRequestRefHrefPrefix),
|
||||
href.startsWith(SecretRequestRefHrefPrefix) ||
|
||||
href.startsWith(ConnectRefHrefPrefix),
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
WorkspaceRefHrefPrefix,
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { parseFolderRefHref } from "@/src/utils/folder-ref";
|
||||
import { connectRequestIdFromHref } from "@/src/utils/connect-ref";
|
||||
import { botPlanRefId } from "@/src/utils/bot-plan-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
import { botSuggestionRefId } from "@/src/utils/bot-suggestion-ref";
|
||||
@@ -23,6 +24,7 @@ import BotPlanCard from "../(partials)/bot-plan-card";
|
||||
import BotQuestionRefCard from "../(partials)/bot-question-ref-card";
|
||||
import BotSuggestionsRef from "../(partials)/bot-suggestions-ref";
|
||||
import BotRefChip from "../(partials)/bot-ref-chip";
|
||||
import ConnectRefCard from "../(partials)/connect-ref-card";
|
||||
import ComputerRefChip from "../(partials)/computer-ref-chip";
|
||||
import FileRefChip from "../(partials)/file-ref-chip";
|
||||
import FolderRefChip from "../(partials)/folder-ref-chip";
|
||||
@@ -111,6 +113,9 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
if (request_id) return <SecretRequestRefCard request_id={request_id} />;
|
||||
}
|
||||
|
||||
const connect_id = connectRequestIdFromHref({ href });
|
||||
if (connect_id) return <ConnectRefCard request_id={connect_id} />;
|
||||
|
||||
const question_id = botQuestionRefId({ href });
|
||||
if (question_id) return <BotQuestionRefCard question_id={question_id} />;
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useState } from "react";
|
||||
import { Copy } from "lucide-react";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ExtensionBundle, ExtensionBundleKind } from "@/src/types";
|
||||
import copyPendingText from "@/src/utils/copy-pending-text";
|
||||
import SettingsRowMenuItem from "./settings-row-menu-item";
|
||||
|
||||
type Props = {
|
||||
kind: ExtensionBundleKind;
|
||||
id: number;
|
||||
/**
|
||||
* What the item is called, one of them, e.g. "MCP server".
|
||||
*/
|
||||
one: string;
|
||||
disabled?: boolean;
|
||||
onCopied: (msg: string) => void;
|
||||
onError: (msg: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copies one item's JSON, the same shape an export carries, so it can be
|
||||
* pasted into its Add form on another install.
|
||||
*/
|
||||
export default function CopyExtensionMenuItem({ kind, id, one, disabled, onCopied, onError }: Props) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const copy = async () => {
|
||||
if (busy) return;
|
||||
|
||||
setBusy(true);
|
||||
|
||||
const text = (async () => {
|
||||
const res = await postAdminApi<ExtensionBundle>({
|
||||
path: "extensions/export-bundle",
|
||||
body: { kind, ids: [id] },
|
||||
});
|
||||
const item = res.singleRes?.items?.[0];
|
||||
|
||||
if (!res.success || !item) throw new Error(res.msg || "That didn't work.");
|
||||
|
||||
return `${JSON.stringify(item, null, 2)}\n`;
|
||||
})();
|
||||
|
||||
const copied = await copyPendingText({ text }).catch((error: Error) => {
|
||||
onError(error.message || "Couldn't copy it.");
|
||||
return false;
|
||||
});
|
||||
|
||||
setBusy(false);
|
||||
|
||||
if (copied) onCopied(`${one} copied. Paste it into an Add form on another install.`);
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsRowMenuItem
|
||||
icon={Copy}
|
||||
title={`Copy ${one}`}
|
||||
description="Its JSON, to paste into an Add form on another install."
|
||||
disabled={disabled}
|
||||
loading={busy}
|
||||
onClick={copy}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import CodeEditor from "@/src/components/general/code-editor";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import type { ExtensionBundleKind } from "@/src/types";
|
||||
import readExtensionPaste, { ExtensionPasteLabels, type ExtensionPaste } from "@/src/utils/read-extension-paste";
|
||||
import SettingsStatus from "./settings-status";
|
||||
|
||||
type Props = {
|
||||
kind: ExtensionBundleKind;
|
||||
/**
|
||||
* The JSON read: the item, and what the form now holds that the user
|
||||
* has to know about.
|
||||
*/
|
||||
onFill: (result: { paste: ExtensionPaste; notice: string }) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The JSON one item is copied as, pasted into its Add form: one item, or
|
||||
* a whole export. Its button opens this; the form fills when it reads.
|
||||
*/
|
||||
export default function PasteExtensionModal({ kind, onFill, onCancel }: Props) {
|
||||
const [text, setText] = useState("");
|
||||
const [error, setError] = useState<string>();
|
||||
const labels = ExtensionPasteLabels[kind];
|
||||
|
||||
const fill = () => {
|
||||
const result = readExtensionPaste({ kind, text });
|
||||
|
||||
if (!result.ok) {
|
||||
setError(result.problem);
|
||||
return;
|
||||
}
|
||||
|
||||
const notice = [filled({ paste: result.paste }), pasteNotes({ paste: result.paste })]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
onFill({ paste: result.paste, notice });
|
||||
onCancel();
|
||||
};
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(next) => !next && onCancel()}
|
||||
title={`Paste ${labels.one} JSON`}
|
||||
description={`Copy one from another install's menu, or paste a whole export. It fills this form; nothing is saved until you add it.`}
|
||||
>
|
||||
<Stack className="w-full gap-3! items-stretch pt-4">
|
||||
<CodeEditor
|
||||
mode="json"
|
||||
className="h-64"
|
||||
title="JSON"
|
||||
placeholder={`{"kind": "${kind}", "key": "github", "config": { ... }}`}
|
||||
info="One item's JSON, or a whole export."
|
||||
onChange={(value) => setText(value)}
|
||||
/>
|
||||
<SettingsStatus status={error ? { error: true, msg: error } : undefined} />
|
||||
<Row className="gap-2! flex-nowrap justify-end">
|
||||
<Button
|
||||
title="Cancel"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button title="Fill the form" type="button" size="small" disabled={!text.trim()} onClick={fill}>
|
||||
Fill the form
|
||||
</Button>
|
||||
</Row>
|
||||
</Stack>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the paste read, in one line.
|
||||
*/
|
||||
function filled({ paste }: { paste: ExtensionPaste }) {
|
||||
const name = paste.config.name || paste.key;
|
||||
const labels = ExtensionPasteLabels[paste.kind];
|
||||
const others = paste.left
|
||||
? ` The JSON holds ${paste.left} more ${labels.many}, and this filled the first.`
|
||||
: "";
|
||||
|
||||
return `Filled the form from ${name}.${others}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the form now holds that the user has to know about: values the
|
||||
* export left out, env keys it uses, and documents that come with it.
|
||||
*/
|
||||
function pasteNotes({ paste }: { paste: ExtensionPaste }) {
|
||||
const documents = paste.item.documents.length;
|
||||
const lines = [
|
||||
paste.item.redacted.length ? `The export left out ${paste.item.redacted.join(", ")}. Fill it in here.` : "",
|
||||
paste.item.env_keys.length
|
||||
? `It uses the env keys ${paste.item.env_keys.join(", ")} (Settings > Environment).`
|
||||
: "",
|
||||
...paste.item.notes,
|
||||
documents
|
||||
? `${documents} ${documents == 1 ? "document comes" : "documents come"} with it, added when you save.`
|
||||
: "",
|
||||
].filter(Boolean);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { ConnectorConnectionsPayload } from "@/src/types";
|
||||
|
||||
/**
|
||||
* Reads the connectors page's connections again after one is added, synced
|
||||
* or deleted, without the apps themselves: those live on their own page.
|
||||
*/
|
||||
export default async function readConnectorConnections() {
|
||||
return await fetchApi<Record<string, unknown>, APIResponseObject<ConnectorConnectionsPayload>>(
|
||||
"/api/admin/connectors/connections",
|
||||
{ method: "GET" },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { PagePropsType } from "@/src/types";
|
||||
import type { BunextPageModuleMetaFn } from "@moduletrace/bunext/types";
|
||||
import { SiteData } from "@/src/data/site-data";
|
||||
|
||||
/**
|
||||
* One connection's apps page names the connection in the tab and the
|
||||
* description: the breadcrumb trail can only say "Connectors".
|
||||
*/
|
||||
export default function settingsConnectorPageMeta(): BunextPageModuleMetaFn {
|
||||
return async (params) => {
|
||||
const props = params.serverRes?.props as PagePropsType | undefined;
|
||||
const connection = props?.connector_apps_page?.connection;
|
||||
const name = connection?.name || "Connector";
|
||||
|
||||
return {
|
||||
title: `${name} apps | ${SiteData["SiteName"]}`,
|
||||
description: `The apps ${name} offers, one page at a time.`,
|
||||
};
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user