Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Remove the HighLevel integration (#4637)
Milind Soni164002b72b54
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.ymlindex e2fd8fbc25..940f5acfd4 100644--- a/.github/workflows/docker.yml+++ b/.github/workflows/docker.yml@@ -282,7 +282,7 @@ jobs:secret=$(rand43)host=home.own-server.invalidcontract=(-e OMB_CLOUD_ROLE=home -e OMB_CLOUD_MACHINE_ID=7d1e2f3a-4b5c-4d6e-8f70-8192a3b4c5d6 -e OMB_CLOUD_ADMIN_URL=https://cloud.example.test- -e "OMB_PUBLIC_URL=https://$host" -e "OMB_CLOUD_BOOTSTRAP_SECRET=$secret" -e OMB_COMPOSIO_BROKER_URL=http://127.0.0.1:9 -e OMB_HIGHLEVEL_RELAY_URL=off)+ -e "OMB_PUBLIC_URL=https://$host" -e "OMB_CLOUD_BOOTSTRAP_SECRET=$secret" -e OMB_COMPOSIO_BROKER_URL=http://127.0.0.1:9)run_home() { # name volume port [docker run options...]local name=$1 volume=$2 port=$3; shift 3docker run -d --name "$name" --init --stop-timeout 30 -p "127.0.0.1:$port:8080" -v "$volume:/data" "${contract[@]}" "$@" omb-cloud-home:ci >/dev/nulldiff --git a/cloudflare/composio-broker/src/index.test.ts b/cloudflare/composio-broker/src/index.test.tsindex 1ff27f59ff..59de57e0db 100644--- a/cloudflare/composio-broker/src/index.test.ts+++ b/cloudflare/composio-broker/src/index.test.ts@@ -707,7 +707,7 @@ describe("MCP relay Session reuse", () => {describe("project auth configs", () => {afterEach(() => vi.useRealTimers());- const highlevel = { id: "ac_new", status: "ENABLED", is_composio_managed: false, last_updated_at: "2026-10-01T00:00:00Z", toolkit: { slug: "HighLevel_Location" } };+ const zohoCrm = { id: "ac_new", status: "ENABLED", is_composio_managed: false, last_updated_at: "2026-10-01T00:00:00Z", toolkit: { slug: "Zoho_Crm" } };function projectHarness(authConfigs: () => Response | Promise<Response>) {const fetchCalls: Array<{ url: string; init?: RequestInit }> = [];@@ -752,8 +752,8 @@ describe("project auth configs", () => {? { items: [{ id: "ac_x", is_composio_managed: false, toolkit: { slug: "X" } }] }: {items: [- { id: "ac_old", is_composio_managed: false, last_updated_at: "2026-09-01T00:00:00Z", toolkit: { slug: "highlevel_location" } },- highlevel,+ { id: "ac_old", is_composio_managed: false, last_updated_at: "2026-09-01T00:00:00Z", toolkit: { slug: "zoho_crm" } },+ zohoCrm,{ id: "ac_gmail", is_composio_managed: true, toolkit: { slug: "gmail" } },{ id: "ac_hubspot", status: "DISABLED", is_composio_managed: false, toolkit: { slug: "hubspot" } },{ id: "ac_slack", is_composio_managed: false, is_enabled_for_tool_router: false, toolkit: { slug: "slack" } },@@ -765,27 +765,27 @@ describe("project auth configs", () => {await expect(ensureSession(harness.install(null), harness.env as never, harness.ctx as never)).resolves.toMatchObject({sessionId: "trs_new_1",- authConfigs: { highlevel_location: "ac_new", twitter: "ac_x" },+ authConfigs: { zoho_crm: "ac_new", twitter: "ac_x" },});expect(harness.authConfigReads().map((call) => new URL(call.url).searchParams.get("is_composio_managed"))).toEqual(["false", "false"]);expect(harness.creations()).toEqual([expect.objectContaining({user_id: "omb_stable",multi_account: multiAccount,- auth_configs: { highlevel_location: "ac_new", twitter: "ac_x" },+ auth_configs: { zoho_crm: "ac_new", twitter: "ac_x" },})]);expect(harness.dbRuns.some((run) => run.sql.includes("SET session_id") && run.values[0] === "trs_new_1")).toBe(true);- await expect(listCustomAuthConfigs(harness.env as never)).resolves.toEqual({ highlevel_location: "ac_new", twitter: "ac_x" });+ await expect(listCustomAuthConfigs(harness.env as never)).resolves.toEqual({ zoho_crm: "ac_new", twitter: "ac_x" });});it("recreates a Session that lacks the project's auth configs once, keeping the Composio user", async () => {const { ensureSession } = await freshBroker();- const harness = projectHarness(() => Response.json({ items: [highlevel] }));+ const harness = projectHarness(() => Response.json({ items: [zohoCrm] }));harness.sessions.set("trs_old", session("trs_old", "omb_stable"));harness.echoAuthConfigs = false;const upgraded = await ensureSession(harness.install("trs_old"), harness.env as never, harness.ctx as never);expect(upgraded.sessionId).toBe("trs_new_1");- expect(harness.creations()).toEqual([expect.objectContaining({ user_id: "omb_stable", auth_configs: { highlevel_location: "ac_new" } })]);+ expect(harness.creations()).toEqual([expect.objectContaining({ user_id: "omb_stable", auth_configs: { zoho_crm: "ac_new" } })]);expect(harness.dbRuns.filter((run) => run.sql.includes("SET session_id")).map((run) => [run.values[0], run.values[2]])).toEqual([["trs_new_1", "install-1"]]);// Composio left auth_configs out of the echo: the upgrade is not retried.@@ -793,7 +793,7 @@ describe("project auth configs", () => {expect(harness.creations()).toHaveLength(1);// A Session that echoes the config (in any slug case) is reused as is.- harness.sessions.set("trs_covered", { ...session("trs_covered", "omb_stable"), config: { user_id: "omb_stable", multi_account: multiAccount, auth_configs: { HighLevel_Location: "ac_new" } } });+ harness.sessions.set("trs_covered", { ...session("trs_covered", "omb_stable"), config: { user_id: "omb_stable", multi_account: multiAccount, auth_configs: { Zoho_Crm: "ac_new" } } });await expect(ensureSession(harness.install("trs_covered"), harness.env as never, harness.ctx as never)).resolves.toMatchObject({ sessionId: "trs_covered" });expect(harness.creations()).toHaveLength(1);expect(harness.authConfigReads()).toHaveLength(1);@@ -820,7 +820,7 @@ describe("project auth configs", () => {vi.setSystemTime(new Date("2026-10-15T12:00:00Z"));const { ensureSession } = await freshBroker();const errors = vi.spyOn(console, "error").mockImplementation(() => {});- let items: unknown[] | "fail" = [highlevel];+ let items: unknown[] | "fail" = [zohoCrm];const harness = projectHarness(() => items === "fail"? Response.json({ error: "down" }, { status: 503 }): Response.json({ items }));@@ -842,14 +842,14 @@ describe("project auth configs", () => {expect(errors).toHaveBeenCalledTimes(1);// The failed read is retried after a minute; a new auth config upgrades the Session once more.- items = [highlevel, { id: "ac_x", is_composio_managed: false, toolkit: { slug: "x" } }];+ items = [zohoCrm, { id: "ac_x", is_composio_managed: false, toolkit: { slug: "x" } }];vi.setSystemTime(new Date("2026-10-15T12:10:30Z"));await verify("trs_new_1");expect(harness.authConfigReads()).toHaveLength(2);vi.setSystemTime(new Date("2026-10-15T12:11:02Z"));- await expect(verify("trs_new_1")).resolves.toMatchObject({ sessionId: "trs_new_2", authConfigs: { highlevel_location: "ac_new", twitter: "ac_x" } });+ await expect(verify("trs_new_1")).resolves.toMatchObject({ sessionId: "trs_new_2", authConfigs: { zoho_crm: "ac_new", twitter: "ac_x" } });expect(harness.authConfigReads()).toHaveLength(3);- expect(harness.creations().at(-1)).toEqual(expect.objectContaining({ user_id: "omb_stable", auth_configs: { highlevel_location: "ac_new", twitter: "ac_x" } }));+ expect(harness.creations().at(-1)).toEqual(expect.objectContaining({ user_id: "omb_stable", auth_configs: { zoho_crm: "ac_new", twitter: "ac_x" } }));errors.mockRestore();});});diff --git a/cloudflare/composio-broker/src/index.ts b/cloudflare/composio-broker/src/index.tsindex 3da7da759f..db55e03eb6 100644--- a/cloudflare/composio-broker/src/index.ts+++ b/cloudflare/composio-broker/src/index.ts@@ -69,8 +69,8 @@ const sessionWireSchema = z.object({});type SessionWire = z.infer<typeof sessionWireSchema>;-// A Session reaches a toolkit Composio doesn't manage auth for (HighLevel, a-// BYO OAuth app) only if created with the project's auth config id under+// A Session reaches a toolkit Composio doesn't manage auth for (a BYO OAuth+// app) only if created with the project's auth config id under// `auth_configs`.const authConfigItemSchema = z.object({id: z.string().optional(),diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.mdindex 1e74eacf82..fc73514a65 100644--- a/cloudflare/control-plane/README.md+++ b/cloudflare/control-plane/README.md@@ -51,6 +51,10 @@ tunnel and DNS IDs would make operator cleanup impossible. `0011` drops1.7.1, and from 1.7.3 Better Auth never writes the column, so it would refuseany new account row. Apply `0011` before deploying a Worker on Better Auth1.7.7.+`0013` drops `highlevel_flows` and `highlevel_ip_rate_limits`, the HighLevel+OAuth relay's tables from `0009` and `0010`, with any sealed token payload still+in them. Apply it after deploying a Worker without that relay: an older Worker+still reads those tables.## API surface@@ -635,46 +639,6 @@ Setup, once:4. To rotate, give the relay both public keys, set `RELAY_TOKEN_KID` and the new secret, deploy, then drop the old keyfrom the relay after 12 hours.-### HighLevel OAuth relay--OpenMausBot's native HighLevel (GoHighLevel, and white-labels such as Growably)-integration signs a person in through a Marketplace app registered to us. The-app's client secret lives only in this Worker; the harness (desktop or a Cloud-home) never sees it. Routes, none of which need an installation credential: the-random `state` and the tokens themselves are the secrets, and each route is-rate-limited per caller address.--| Route | Does |-| --- | --- |-| `POST /v1/highlevel/start` | Mints a 32-byte `state`, stores only `HKDF(state, "lookup")`, returns the white-label authorization URL (`marketplace.leadconnectorhq.com/v2/oauth/chooselocation`) with our client id, redirect URL and scopes. |-| `GET /v1/highlevel/callback?code&state` | HighLevel sends the person's browser here. Exchanges the code (`POST services.leadconnectorhq.com/oauth/token`, `user_type=Location`), seals the token payload with AES-GCM under `HKDF(state, "wrap")`, shows a plain "Connected" page. Never echoes query parameters. |-| `POST /v1/highlevel/claim {state}` | The harness collects the payload once (404 before the callback, 410 after); the row is emptied. |-| `POST /v1/highlevel/refresh {refreshToken}` | Refreshes with the client secret; HighLevel's refusal is `401 highlevel_refresh_rejected`. |--Rows live at most ten minutes (`highlevel_flows`, swept by the cron). Without the-raw state a row opens nothing, and no plaintext token is ever written to D1.-Logs carry counts and error codes, never codes or tokens.--Setup, once:--1. Register the Marketplace app (private, sub-account, installable by agency and- sub-account). Redirect URL: `https://accounts.openmausbot.com/v1/highlevel/callback`.- Scopes: `contacts.readonly contacts.write opportunities.readonly opportunities.write conversations.readonly locations.readonly calendars.readonly users.readonly`.-2. Put the client id in `vars.HIGHLEVEL_CLIENT_ID` (it is public: it appears in the- authorization URL). Keep `HIGHLEVEL_REDIRECT_URL` and `HIGHLEVEL_SCOPES` in step- with the app.-3. `wrangler d1 migrations apply DB --config wrangler.jsonc` (0009 and 0010).- On a running Worker, apply 0010 before deploying a Worker built from this- code: its callback marks the flow in `callback_at`. An older Worker- ignores the column.-4. `wrangler secret put HIGHLEVEL_CLIENT_SECRET --config wrangler.jsonc`. It is- deliberately not in `secrets.required`: until it exists the routes answer- `503 highlevel_unavailable`.-5. `wrangler deploy --config wrangler.jsonc`.--A private app stops accepting installs past five external agencies; publish it-(HighLevel review) before that.-## Local checksInstall from the repository root, then run:diff --git a/cloudflare/control-plane/migrations/0013_drop_highlevel.sql b/cloudflare/control-plane/migrations/0013_drop_highlevel.sqlnew file mode 100644index 0000000000..478ab02604--- /dev/null+++ b/cloudflare/control-plane/migrations/0013_drop_highlevel.sql@@ -0,0 +1,8 @@+-- Drops the HighLevel OAuth relay's tables from 0009 and 0010, with any+-- sealed token payload still in them; nothing references them. IF EXISTS+-- keeps it safe where they were dropped by hand. Apply it after deploying a+-- Worker without the relay: an older Worker still reads and sweeps them.+DROP INDEX IF EXISTS highlevel_flows_created_idx;+DROP INDEX IF EXISTS highlevel_ip_rate_limits_updated_idx;+DROP TABLE IF EXISTS highlevel_flows;+DROP TABLE IF EXISTS highlevel_ip_rate_limits;diff --git a/cloudflare/control-plane/src/highlevel.ts b/cloudflare/control-plane/src/highlevel.tsdeleted file mode 100644index c76b57c1dd..0000000000--- a/cloudflare/control-plane/src/highlevel.ts+++ /dev/null@@ -1,434 +0,0 @@-// HighLevel OAuth relay: the app's client secret lives here only. A desktop or-// Cloud home starts a flow, the person signs in at HighLevel in a browser,-// HighLevel redirects to this Worker, and the harness collects the tokens once.-// D1 holds, per flow, a hash derived from the random state, the token payload-// encrypted under a second key derived from the same state, and timestamps:-// never the state, never a plaintext token.-import { z } from "zod";--import { errorResponse, HTTPError, json, readBoundedJSON } from "./http";--export const HIGHLEVEL_AUTHORIZE_URL = "https://marketplace.leadconnectorhq.com/v2/oauth/chooselocation";-export const HIGHLEVEL_TOKEN_URL = "https://services.leadconnectorhq.com/oauth/token";-export const HIGHLEVEL_CALLBACK_PATH = "/v1/highlevel/callback";--/** A flow that was started but never claimed is forgotten after this long. */-export const HIGHLEVEL_FLOW_TTL_MS = 10 * 60 * 1_000;-const HOUR_MS = 60 * 60 * 1_000;-const LIMIT_RETENTION_MS = 24 * HOUR_MS;-const HIGHLEVEL_TIMEOUT_MS = 10_000;-/** Per IP per hour. A harness polls `claim` every 2 s for up to 10 minutes- * (300 polls per flow); Cloud homes may share an egress address. */-export const HIGHLEVEL_START_LIMIT = 60;-export const HIGHLEVEL_CALLBACK_LIMIT = 60;-export const HIGHLEVEL_CLAIM_LIMIT = 3_000;-export const HIGHLEVEL_REFRESH_LIMIT = 600;--const STATE_BYTES = 32;-/** 32 random bytes, base64url without padding. */-const STATE = /^[A-Za-z0-9_-]{43}$/;-/** HighLevel's authorization codes are opaque; accept any single token of- * printable ASCII. The value is sent to HighLevel once and never kept. */-const CODE = /^[\x21-\x7e]{1,1024}$/;-const REFRESH_TOKEN = /^[\x21-\x7e]{1,8192}$/;-const CLIENT_ID = /^[\x21-\x7e]{1,256}$/;-const SCOPES = /^[A-Za-z0-9_./-]+(?: [A-Za-z0-9_./-]+)*$/;-const HKDF_SALT = "openmausbot-highlevel-relay-v1";-const encoder = new TextEncoder();--export interface HighLevelConfig {- clientId: string;- clientSecret: string;- redirectUrl: string;- scopes: string;-}--const startSchema = z.strictObject({ kind: z.literal("location") });-const claimSchema = z.strictObject({ state: z.string().regex(STATE) });-const refreshSchema = z.strictObject({ refreshToken: z.string().regex(REFRESH_TOKEN) });--const tokenResponseSchema = z.looseObject({- access_token: z.string().min(1),- refresh_token: z.string().min(1),- expires_in: z.number().finite().nonnegative(),- scope: z.string().optional(),- locationId: z.string().optional(),- companyId: z.string().optional(),- userId: z.string().optional(),-});--/** What the harness receives from `claim` and `refresh`, and what a flow row- * holds encrypted between the callback and the claim. */-const tokenPayloadSchema = z.strictObject({- accessToken: z.string().min(1),- refreshToken: z.string().min(1),- expiresIn: z.number(),- scope: z.string(),- locationId: z.string(),- companyId: z.string(),- userId: z.string(),-});-export type HighLevelTokenPayload = z.infer<typeof tokenPayloadSchema>;--export function readHighLevelConfig(env: Env): HighLevelConfig | null {- const vars = env as unknown as Partial<Record<string, unknown>>;- const clientId = vars.HIGHLEVEL_CLIENT_ID;- const clientSecret = vars.HIGHLEVEL_CLIENT_SECRET;- const redirectUrl = vars.HIGHLEVEL_REDIRECT_URL;- const scopes = vars.HIGHLEVEL_SCOPES;- if (typeof clientId !== "string" || !CLIENT_ID.test(clientId)) return null;- if (typeof clientSecret !== "string" || clientSecret.length < 8 || clientSecret.length > 1_024 || /\s/.test(clientSecret)) return null;- if (typeof redirectUrl !== "string") return null;- let redirect: URL;- try {- redirect = new URL(redirectUrl);- } catch {- return null;- }- if (redirect.protocol !== "https:" || redirect.username || redirect.password || redirect.search || redirect.hash) return null;- if (typeof scopes !== "string" || scopes.length > 2_048 || !SCOPES.test(scopes)) return null;- return { clientId, clientSecret, redirectUrl: redirect.href, scopes };-}--export function highLevelAuthorizationUrl(config: HighLevelConfig, state: string): string {- // Built by hand so the scope separator is `%20`, as in HighLevel's examples,- // not the `+` URLSearchParams would produce.- const query = [- ["response_type", "code"],- ["redirect_uri", config.redirectUrl],- ["client_id", config.clientId],- ["scope", config.scopes],- ["state", state],- ].map(([name, value]) => `${name}=${encodeURIComponent(value!)}`).join("&");- return `${HIGHLEVEL_AUTHORIZE_URL}?${query}`;-}--function base64url(bytes: ArrayBuffer | Uint8Array): string {- let binary = "";- for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");-}--function fromBase64url(value: string): Uint8Array<ArrayBuffer> {- const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));- const bytes = new Uint8Array(binary.length);- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);- return bytes;-}--/** The one spelling newState makes. The last character's two spare bits carry nothing, so "…A", "…B", "…C" and "…D"- * decode to the same bytes: only the canonical one may open a flow. */-function canonicalState(state: string): boolean {- return STATE.test(state) && base64url(fromBase64url(state)) === state;-}--function hex(bytes: ArrayBuffer): string {- return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");-}--function newState(): string {- const bytes = new Uint8Array(STATE_BYTES);- crypto.getRandomValues(bytes);- return base64url(bytes);-}--async function hkdfMaterial(state: string): Promise<CryptoKey> {- return crypto.subtle.importKey("raw", fromBase64url(state), "HKDF", false, ["deriveBits", "deriveKey"]);-}--function hkdfParams(info: string): HkdfParams {- return { name: "HKDF", hash: "SHA-256", salt: encoder.encode(HKDF_SALT), info: encoder.encode(info) };-}--/** The row key: a state is never stored, only this derivation of it. */-export async function flowLookup(state: string): Promise<string> {- return hex(await crypto.subtle.deriveBits(hkdfParams("lookup"), await hkdfMaterial(state), 256));-}--async function wrapKey(state: string): Promise<CryptoKey> {- return crypto.subtle.deriveKey(hkdfParams("wrap"), await hkdfMaterial(state), { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);-}--async function seal(state: string, payload: HighLevelTokenPayload): Promise<string> {- const iv = new Uint8Array(12);- crypto.getRandomValues(iv);- const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await wrapKey(state), encoder.encode(JSON.stringify(payload)));- const out = new Uint8Array(iv.byteLength + sealed.byteLength);- out.set(iv, 0);- out.set(new Uint8Array(sealed), iv.byteLength);- return base64url(out);-}--async function open(state: string, ciphertext: string): Promise<HighLevelTokenPayload | null> {- try {- const bytes = fromBase64url(ciphertext);- const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await wrapKey(state), bytes.slice(12));- const parsed = tokenPayloadSchema.safeParse(JSON.parse(new TextDecoder().decode(plain)));- return parsed.success ? parsed.data : null;- } catch {- return null;- }-}--function unavailable(): never {- throw new HTTPError(503, "highlevel_unavailable");-}--async function parse<T>(request: Request, schema: z.ZodType<T>): Promise<T> {- const parsed = schema.safeParse(await readBoundedJSON(request));- if (!parsed.success) throw new HTTPError(400, "invalid_request");- return parsed.data;-}--function rateLimited(retryAfterSeconds: number): Response {- const response = errorResponse(429, "rate_limited");- response.headers.set("retry-after", String(retryAfterSeconds));- return response;-}--async function clientKey(request: Request, env: Env): Promise<string> {- // Cloudflare sets cf-connecting-ip on every request that reaches a Worker.- const address = request.headers.get("cf-connecting-ip")?.trim() || "unknown";- const key = await crypto.subtle.importKey("raw", encoder.encode(env.BETTER_AUTH_SECRET), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);- return hex(await crypto.subtle.sign("HMAC", key, encoder.encode(address)));-}--/** The installation limiter's shape (`installation_action_rate_limits`), keyed- * by a keyed hash of the caller's address because these routes carry no- * credential. Resolves to a 429 when the hour's budget is spent. */-async function takeLimit(request: Request, env: Env, action: string, limit: number, now: number): Promise<Response | null> {- const key = await clientKey(request, env);- const cutoff = now - HOUR_MS;- const [taken] = await env.DB.batch([- env.DB.prepare(- `INSERT INTO highlevel_ip_rate_limits- (ip_key, action, window_started_at, attempts, updated_at)- VALUES (?, ?, ?, 1, ?)- ON CONFLICT(ip_key, action) DO UPDATE SET- window_started_at = CASE WHEN window_started_at <= ? THEN excluded.window_started_at ELSE window_started_at END,- attempts = CASE WHEN window_started_at <= ? THEN 1 ELSE attempts + 1 END,- updated_at = excluded.updated_at- WHERE window_started_at <= ? OR attempts < ?`,- ).bind(key, action, now, now, cutoff, cutoff, cutoff, limit),- env.DB.prepare("DELETE FROM highlevel_ip_rate_limits WHERE updated_at < ?").bind(now - LIMIT_RETENTION_MS),- ]);- return taken?.meta.changes === 0 ? rateLimited(60) : null;-}--export async function startHighLevelFlow(request: Request, env: Env): Promise<Response> {- const config = readHighLevelConfig(env) ?? unavailable();- await parse(request, startSchema);- const now = Date.now();- const limited = await takeLimit(request, env, "start", HIGHLEVEL_START_LIMIT, now);- if (limited) return limited;- const state = newState();- await env.DB.prepare("INSERT INTO highlevel_flows (lookup, ciphertext, created_at) VALUES (?, NULL, ?)")- .bind(await flowLookup(state), now)- .run();- return json({ state, authorizationUrl: highLevelAuthorizationUrl(config, state), expiresAt: now + HIGHLEVEL_FLOW_TTL_MS });-}--type Exchange =- | { kind: "ok"; payload: HighLevelTokenPayload }- | { kind: "rejected" | "failed"; status: number };--/** One `POST /oauth/token`. Only the status comes back from a failure. */-async function exchange(- config: HighLevelConfig,- grant: Record<string, string>,- highLevelFetch: typeof fetch,-): Promise<Exchange> {- const form = new URLSearchParams({- client_id: config.clientId,- client_secret: config.clientSecret,- user_type: "Location",- redirect_uri: config.redirectUrl,- ...grant,- });- let response: Response;- try {- response = await highLevelFetch(HIGHLEVEL_TOKEN_URL, {- method: "POST",- headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },- body: form.toString(),- redirect: "manual",- signal: AbortSignal.timeout(HIGHLEVEL_TIMEOUT_MS),- });- } catch {- return { kind: "failed", status: 0 };- }- if (response.status >= 400 && response.status < 500) return { kind: "rejected", status: response.status };- if (response.status !== 200) return { kind: "failed", status: response.status };- const answer = tokenResponseSchema.safeParse(await response.json().catch(() => null));- if (!answer.success) return { kind: "failed", status: 200 };- return {- kind: "ok",- payload: {- accessToken: answer.data.access_token,- refreshToken: answer.data.refresh_token,- expiresIn: answer.data.expires_in,- scope: answer.data.scope ?? "",- locationId: answer.data.locationId ?? "",- companyId: answer.data.companyId ?? "",- userId: answer.data.userId ?? "",- },- };-}--const PAGE_HEADERS = {- "content-type": "text/html; charset=utf-8",- "cache-control": "no-store",- "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'",-} as const;--/** Fixed copy only: nothing from the request reaches the page. */-function page(title: string, text: string, status = 200): Response {- const html = `<!doctype html>-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${title}</title>-<style>body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font:17px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1b1b1b;background:#f6f6f6}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.35rem;margin:0 0 .5rem}p{margin:0;color:#4a4a4a}</style></head>-<body><main><h1>${title}</h1><p>${text}</p></main></body></html>-`;- return new Response(html, { status, headers: PAGE_HEADERS });-}--const PAGES = {- connected: () => page("Connected", "Close this tab and go back to OpenMausBot."),- cancelled: () => page("Connection cancelled", "Go back to OpenMausBot and try again when you are ready."),- expired: () => page("Connection expired", "This link is no longer valid. Go back to OpenMausBot and try again.", 400),- failed: () => page("Connection failed", "Go back to OpenMausBot and try again.", 502),- unavailable: () => page("Connection failed", "Go back to OpenMausBot and try again.", 503),-};--interface FlowRow {- lookup: string;- ciphertext: string | null;- created_at: number;- claimed_at: number | null;-}--async function flowRow(env: Env, lookup: string): Promise<FlowRow | null> {- return env.DB.prepare("SELECT lookup, ciphertext, created_at, claimed_at FROM highlevel_flows WHERE lookup = ?")- .bind(lookup)- .first<FlowRow>();-}--function expired(row: FlowRow, now: number): boolean {- return row.created_at + HIGHLEVEL_FLOW_TTL_MS <= now;-}--/** Marks the flow as taken by this callback at `now`, or false when another callback, a claim or the TTL got there first. */-async function takeForCallback(env: Env, lookup: string, now: number): Promise<boolean> {- const taken = await env.DB.prepare(- `UPDATE highlevel_flows SET callback_at = ?1- WHERE lookup = ?2 AND callback_at IS NULL AND ciphertext IS NULL AND claimed_at IS NULL AND created_at > ?3`,- ).bind(now, lookup, now - HIGHLEVEL_FLOW_TTL_MS).run();- return taken.meta.changes === 1;-}--function endTakenFlow(env: Env, lookup: string, now: number) {- return env.DB.prepare("DELETE FROM highlevel_flows WHERE lookup = ? AND callback_at = ?").bind(lookup, now).run();-}--/** HighLevel sends the person's browser here: a top-level GET with no Origin- * header and no credential. Every answer is a fixed page; query values are- * never echoed or logged. */-export async function highLevelCallback(- request: Request,- env: Env,- highLevelFetch: typeof fetch,- requestId: string,-): Promise<Response> {- const config = readHighLevelConfig(env);- if (!config) return PAGES.unavailable();- const now = Date.now();- const limited = await takeLimit(request, env, "callback", HIGHLEVEL_CALLBACK_LIMIT, now);- if (limited) return limited;- const url = new URL(request.url);- const state = url.searchParams.get("state") ?? "";- if (!canonicalState(state)) return PAGES.expired();- const lookup = await flowLookup(state);- const row = await flowRow(env, lookup);- if (!row || row.claimed_at !== null || row.ciphertext !== null || expired(row, now)) return PAGES.expired();-- if (url.searchParams.has("error")) {- // The person declined, or HighLevel refused before issuing a code. The- // flow ends here: a claim finds nothing and the harness times out cleanly.- if (!(await takeForCallback(env, lookup, now))) return PAGES.expired();- await endTakenFlow(env, lookup, now);- console.log(JSON.stringify({ message: "highlevel flow cancelled", requestId }));- return PAGES.cancelled();- }- const code = url.searchParams.get("code") ?? "";- if (!CODE.test(code)) return PAGES.failed();-- if (!(await takeForCallback(env, lookup, now))) return PAGES.expired();- const outcome = await exchange(config, { grant_type: "authorization_code", code }, highLevelFetch);- if (outcome.kind !== "ok") {- // The code is single-use: nothing to retry with, so the flow ends.- await endTakenFlow(env, lookup, now);- console.error(JSON.stringify({ message: "highlevel exchange failed", requestId, status: outcome.status, errorCode: "highlevel_exchange_failed" }));- return PAGES.failed();- }- const stored = await env.DB.prepare(- `UPDATE highlevel_flows SET ciphertext = ?- WHERE lookup = ? AND callback_at = ? AND ciphertext IS NULL AND claimed_at IS NULL AND created_at > ?`,- ).bind(await seal(state, outcome.payload), lookup, now, now - HIGHLEVEL_FLOW_TTL_MS).run();- if (stored.meta.changes === 0) return PAGES.expired();- console.log(JSON.stringify({ message: "highlevel flow connected", requestId }));- return PAGES.connected();-}--export async function claimHighLevelFlow(request: Request, env: Env): Promise<Response> {- if (!readHighLevelConfig(env)) unavailable();- const body = await parse(request, claimSchema);- const now = Date.now();- const limited = await takeLimit(request, env, "claim", HIGHLEVEL_CLAIM_LIMIT, now);- if (limited) return limited;- if (!canonicalState(body.state)) return errorResponse(404, "highlevel_unknown_state");- const lookup = await flowLookup(body.state);- const row = await flowRow(env, lookup);- if (!row || expired(row, now)) return errorResponse(404, "highlevel_unknown_state");- if (row.claimed_at !== null) return errorResponse(410, "highlevel_claimed");- if (row.ciphertext === null) return errorResponse(404, "highlevel_unknown_state");- // The payload leaves D1 the moment it is handed out; the row keeps only the- // claimed mark until the sweep, so a second claim is told 410, not 404.- const taken = await env.DB.prepare(- "UPDATE highlevel_flows SET ciphertext = NULL, claimed_at = ? WHERE lookup = ? AND claimed_at IS NULL AND ciphertext IS NOT NULL",- ).bind(now, lookup).run();- if (taken.meta.changes === 0) return errorResponse(410, "highlevel_claimed");- const payload = await open(body.state, row.ciphertext);- if (!payload) throw new HTTPError(500, "internal_error");- return json(payload);-}--export async function refreshHighLevelToken(- request: Request,- env: Env,- highLevelFetch: typeof fetch,- requestId: string,-): Promise<Response> {- const config = readHighLevelConfig(env) ?? unavailable();- const body = await parse(request, refreshSchema);- const now = Date.now();- const limited = await takeLimit(request, env, "refresh", HIGHLEVEL_REFRESH_LIMIT, now);- if (limited) return limited;- const outcome = await exchange(config, { grant_type: "refresh_token", refresh_token: body.refreshToken }, highLevelFetch);- if (outcome.kind === "ok") return json(outcome.payload);- if (outcome.kind === "rejected") {- console.log(JSON.stringify({ message: "highlevel refresh rejected", requestId, status: outcome.status }));- return errorResponse(401, "highlevel_refresh_rejected");- }- console.error(JSON.stringify({ message: "highlevel refresh failed", requestId, status: outcome.status, errorCode: "highlevel_refresh_failed" }));- return errorResponse(502, "highlevel_refresh_failed");-}--/** Cron: forget flows older than the TTL, claimed or not, and stale limiter rows. */-export async function sweepHighLevelFlows(env: Env, requestId: string, now = Date.now()): Promise<number> {- const [flows] = await env.DB.batch([- env.DB.prepare("DELETE FROM highlevel_flows WHERE created_at <= ?").bind(now - HIGHLEVEL_FLOW_TTL_MS),- env.DB.prepare("DELETE FROM highlevel_ip_rate_limits WHERE updated_at < ?").bind(now - LIMIT_RETENTION_MS),- ]);- const deleted = flows?.meta.changes ?? 0;- if (deleted > 0) console.log(JSON.stringify({ message: "highlevel flow sweep", requestId, deleted }));- return deleted;-}diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.tsindex 45d84ed2d9..f4fb4ec4f9 100644--- a/cloudflare/control-plane/src/index.ts+++ b/cloudflare/control-plane/src/index.ts@@ -12,14 +12,6 @@ import {provisionManagedEndpoint,sweepManagedEndpointCleanup,} from "./endpoints";-import {- claimHighLevelFlow,- HIGHLEVEL_CALLBACK_PATH,- highLevelCallback,- refreshHighLevelToken,- startHighLevelFlow,- sweepHighLevelFlows,-} from "./highlevel";import { registerPushDevice, sendPush, unregisterPushDevice } from "./push";import { issueRelayToken, relayAdoption } from "./relay";import { capacityHealth, reportEndpointAccountProblems, scanTunnelCapacity } from "./tunnel-capacity";@@ -80,7 +72,6 @@ async function route(requestId: string,cloudflareFetch: CloudflareFetch,apnsFetch: typeof fetch,- highLevelFetch: typeof fetch,) {const url = new URL(request.url);if (request.method === "OPTIONS") return preflight(request, config);@@ -156,21 +147,6 @@ async function route(return sendPush(request, env, apnsFetch, requestId);}- // The HighLevel relay carries no credential: the random state and the- // tokens themselves are the secrets, and every route is limited per address.- if (request.method === "POST" && url.pathname === "/v1/highlevel/start") {- return startHighLevelFlow(request, env);- }- if (request.method === "GET" && url.pathname === HIGHLEVEL_CALLBACK_PATH) {- return highLevelCallback(request, env, highLevelFetch, requestId);- }- if (request.method === "POST" && url.pathname === "/v1/highlevel/claim") {- return claimHighLevelFlow(request, env);- }- if (request.method === "POST" && url.pathname === "/v1/highlevel/refresh") {- return refreshHighLevelToken(request, env, highLevelFetch, requestId);- }-const rotate = url.pathname.match(ROTATE_ROUTE);if (request.method === "POST" && rotate) {return rotateInstallationCredential(request, rotate[1], env, auth);@@ -199,7 +175,6 @@ async function route(export function createWorker(cloudflareFetch: CloudflareFetch = fetch,apnsFetch: typeof fetch = fetch,- highLevelFetch: typeof fetch = fetch,) {return {async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {@@ -229,16 +204,12 @@ export function createWorker(try {config = readConfig(env);const origin = request.headers.get("origin");- // HighLevel sends the person's browser to the callback: a top-level- // navigation that may carry any Origin (or `null` after a cross-site- // redirect) and never one of ours. It is a public GET like /healthz.- const publicNavigation = request.method === "GET" && url.pathname === HIGHLEVEL_CALLBACK_PATH;- if (origin && !publicNavigation && !config.allowedOrigins.has(origin)) {+ if (origin && !config.allowedOrigins.has(origin)) {return secureResponse(errorResponse(403, "origin_not_allowed"), request, config, requestId);}const boundedRequest = await withBoundedRequestBody(request);return secureResponse(- await route(boundedRequest, env, ctx, config, requestId, cloudflareFetch, apnsFetch, highLevelFetch),+ await route(boundedRequest, env, ctx, config, requestId, cloudflareFetch, apnsFetch),request,config,requestId,@@ -296,15 +267,6 @@ export function createWorker(errorCode: "endpoint_internal",}));}- try {- await sweepHighLevelFlows(env, requestId);- } catch {- console.error(JSON.stringify({- message: "highlevel flow sweep failed",- requestId,- errorCode: "highlevel_internal",- }));- }})());},} satisfies ExportedHandler<Env>;diff --git a/cloudflare/control-plane/test/control-plane.test.ts b/cloudflare/control-plane/test/control-plane.test.tsindex 34a5482414..07606bcc5b 100644--- a/cloudflare/control-plane/test/control-plane.test.ts+++ b/cloudflare/control-plane/test/control-plane.test.ts@@ -389,9 +389,6 @@ describe("control-plane migrations and health", () => {CLOUDFLARE_API_TOKEN: env.CLOUDFLARE_API_TOKEN,CLOUDFLARE_ENDPOINT_ACCOUNTS: env.CLOUDFLARE_ENDPOINT_ACCOUNTS,CLOUDFLARE_API_TOKEN_MAUSBOT_SI: env.CLOUDFLARE_API_TOKEN_MAUSBOT_SI,- HIGHLEVEL_CLIENT_ID: env.HIGHLEVEL_CLIENT_ID,- HIGHLEVEL_REDIRECT_URL: env.HIGHLEVEL_REDIRECT_URL,- HIGHLEVEL_SCOPES: env.HIGHLEVEL_SCOPES,OMB_TUNNEL_LIMIT: env.OMB_TUNNEL_LIMIT,OMB_DNS_RECORD_LIMIT: env.OMB_DNS_RECORD_LIMIT,OMB_TUNNEL_RECLAIM: env.OMB_TUNNEL_RECLAIM,diff --git a/cloudflare/control-plane/test/highlevel.test.ts b/cloudflare/control-plane/test/highlevel.test.tsdeleted file mode 100644index 044655b2f8..0000000000--- a/cloudflare/control-plane/test/highlevel.test.ts+++ /dev/null@@ -1,527 +0,0 @@-import { env } from "cloudflare:workers";-import { createExecutionContext, createScheduledController, waitOnExecutionContext } from "cloudflare:test";-import { afterEach, describe, expect, it, vi } from "vitest";--import {- HIGHLEVEL_CLAIM_LIMIT,- HIGHLEVEL_FLOW_TTL_MS,- HIGHLEVEL_START_LIMIT,- HIGHLEVEL_TOKEN_URL,- flowLookup,- readHighLevelConfig,-} from "../src/highlevel";-import { createWorker } from "../src/index";--const BASE_URL = "https://auth.openmausbot.test";-const CLIENT_ID = "68e9f2a1b3c4d5e6f7a8b9c0-mf1x2y3z";-const CLIENT_SECRET = "test-only-highlevel-client-secret-0123456789";-const REDIRECT_URL = "https://auth.openmausbot.test/v1/highlevel/callback";-const SCOPES = "contacts.readonly contacts.write locations.readonly";-const CODE = "7676cjcbdc6t76cdcbkjcd09821jknnkj";-const ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiJ9.access-token-for-location.sig";-const REFRESH_TOKEN = "eyJhbGciOiJIUzI1NiJ9.refresh-token-for-location.sig";-const ACCESS_TOKEN_2 = "eyJhbGciOiJIUzI1NiJ9.access-token-after-refresh.sig";-const REFRESH_TOKEN_2 = "eyJhbGciOiJIUzI1NiJ9.refresh-token-after-refresh.sig";-const SECRETS = [CLIENT_SECRET, CODE, ACCESS_TOKEN, REFRESH_TOKEN, ACCESS_TOKEN_2, REFRESH_TOKEN_2];--type TestWorker = ReturnType<typeof createWorker>;--interface HighLevelCall {- url: string;- contentType: string;- form: Record<string, string>;-}--type Answer = { status: number; body?: unknown } | { throws: true };--function tokenAnswer(overrides: Record<string, unknown> = {}) {- return {- status: 200,- body: {- access_token: ACCESS_TOKEN,- token_type: "Bearer",- expires_in: 86399,- refresh_token: REFRESH_TOKEN,- scope: SCOPES,- userType: "Location",- locationId: "l1C08ntBrFjLS0elLIYU",- companyId: "c0mp4nyIdXXXXXXXXXXX",- userId: "u5erIdXXXXXXXXXXXXXX",- planId: "plan",- ...overrides,- },- };-}--function fakeHighLevel(answers: Answer[] = []) {- const calls: HighLevelCall[] = [];- const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => {- const request = new Request(input, init);- const text = await request.text();- calls.push({- url: request.url,- contentType: request.headers.get("content-type") ?? "",- form: Object.fromEntries(new URLSearchParams(text)),- });- const answer = answers.shift() ?? tokenAnswer();- if ("throws" in answer) throw new TypeError("fetch failed");- return new Response(answer.body === undefined ? null : JSON.stringify(answer.body), {- status: answer.status,- headers: { "content-type": "application/json" },- });- }) as typeof fetch;- return { calls, fetch: fetchImpl };-}--function highLevelEnv(extra: Record<string, string | undefined> = {}): Env {- return {- ...env,- HIGHLEVEL_CLIENT_ID: CLIENT_ID,- HIGHLEVEL_CLIENT_SECRET: CLIENT_SECRET,- HIGHLEVEL_REDIRECT_URL: REDIRECT_URL,- HIGHLEVEL_SCOPES: SCOPES,- ...extra,- } as unknown as Env;-}--interface CallOptions {- body?: unknown;- method?: string;- ip?: string;- origin?: string;-}--/** Every response body goes through here so the leak check sees all of them. */-const bodies: string[] = [];-const logs: string[] = [];--async function call(worker: TestWorker, testEnv: Env, path: string, options: CallOptions = {}) {- const headers = new Headers();- if (options.body !== undefined) headers.set("content-type", "application/json");- headers.set("cf-connecting-ip", options.ip ?? "203.0.113.7");- if (options.origin !== undefined) headers.set("origin", options.origin);- const request = new Request(`${BASE_URL}${path}`, {- method: options.method ?? (options.body === undefined ? "GET" : "POST"),- headers,- body: options.body === undefined ? undefined : JSON.stringify(options.body),- });- const ctx = createExecutionContext();- const response = await worker.fetch(request, testEnv, ctx);- await waitOnExecutionContext(ctx);- bodies.push(await response.clone().text());- return response;-}--const start = (worker: TestWorker, testEnv: Env, options: CallOptions = {}) =>- call(worker, testEnv, "/v1/highlevel/start", { body: { kind: "location" }, ...options });-const claim = (worker: TestWorker, testEnv: Env, state: string, options: CallOptions = {}) =>- call(worker, testEnv, "/v1/highlevel/claim", { body: { state }, ...options });-const refresh = (worker: TestWorker, testEnv: Env, refreshToken: string, options: CallOptions = {}) =>- call(worker, testEnv, "/v1/highlevel/refresh", { body: { refreshToken }, ...options });-const callback = (worker: TestWorker, testEnv: Env, query: Record<string, string>, options: CallOptions = {}) =>- call(worker, testEnv, `/v1/highlevel/callback?${new URLSearchParams(query)}`, options);--async function started(worker: TestWorker, testEnv: Env) {- const response = await start(worker, testEnv);- expect(response.status).toBe(200);- const body = await response.json<{ state: string; authorizationUrl: string; expiresAt: number }>();- return body;-}--async function runScheduled(worker: TestWorker, testEnv: Env) {- const controller = createScheduledController({ cron: "*/5 * * * *", scheduledTime: Date.now() });- const ctx = createExecutionContext();- await worker.scheduled(controller, testEnv, ctx);- await waitOnExecutionContext(ctx);-}--async function age(state: string, byMs: number) {- const aged = await env.DB.prepare("UPDATE highlevel_flows SET created_at = created_at - ? WHERE lookup = ?")- .bind(byMs, await flowLookup(state))- .run();- expect(aged.meta.changes).toBe(1);-}--async function rows() {- return (await env.DB.prepare("SELECT lookup, ciphertext, created_at, claimed_at FROM highlevel_flows").all<{- lookup: string;- ciphertext: string | null;- created_at: number;- claimed_at: number | null;- }>()).results;-}--const expectedPayload = {- accessToken: ACCESS_TOKEN,- refreshToken: REFRESH_TOKEN,- expiresIn: 86399,- scope: SCOPES,- locationId: "l1C08ntBrFjLS0elLIYU",- companyId: "c0mp4nyIdXXXXXXXXXXX",- userId: "u5erIdXXXXXXXXXXXXXX",-};--describe("HighLevel OAuth relay", () => {- const capture = (...args: unknown[]) => {- logs.push(args.map((value) => (typeof value === "string" ? value : JSON.stringify(value))).join(" "));- };- vi.spyOn(console, "log").mockImplementation(capture);- vi.spyOn(console, "error").mockImplementation(capture);-- afterEach(async () => {- // The only places a secret may ever appear are the claim and refresh- // JSON answers, which the tests below assert on directly. Every other- // body, every page, and every log line must be free of the client secret,- // the authorization code and the tokens.- const allowed = new Set<string>();- for (const body of bodies) {- if (body.startsWith('{"accessToken":')) allowed.add(body);- }- for (const body of bodies) {- if (allowed.has(body)) continue;- for (const secret of SECRETS) expect(body).not.toContain(secret);- }- for (const line of logs) {- for (const secret of SECRETS) expect(line).not.toContain(secret);- expect(line).not.toMatch(/"(?:state|code|token|access_token|refresh_token)"/);- }- const stored = await rows();- for (const row of stored) {- for (const secret of SECRETS) expect(row.ciphertext ?? "").not.toContain(secret);- }- bodies.length = 0;- logs.length = 0;- });-- it("is unavailable, and says so, until the client secret is set", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const unset = highLevelEnv({ HIGHLEVEL_CLIENT_SECRET: undefined });- expect(readHighLevelConfig(unset)).toBeNull();- expect(readHighLevelConfig(env)).toBeNull();- const response = await start(worker, unset);- expect(response.status).toBe(503);- expect(await response.json()).toEqual({ error: "highlevel_unavailable" });- expect((await claim(worker, unset, "a".repeat(43))).status).toBe(503);- expect((await refresh(worker, unset, REFRESH_TOKEN)).status).toBe(503);- const page = await callback(worker, unset, { code: CODE, state: "a".repeat(43) });- expect(page.status).toBe(503);- expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");- expect(highLevel.calls).toEqual([]);- expect(await rows()).toEqual([]);- });-- it("start, callback, claim once, then 410", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();- const before = Date.now();- const flow = await started(worker, testEnv);-- expect(flow.state).toMatch(/^[A-Za-z0-9_-]{43}$/);- expect(flow.expiresAt).toBeGreaterThanOrEqual(before + HIGHLEVEL_FLOW_TTL_MS);- const authorize = new URL(flow.authorizationUrl);- expect(authorize.origin + authorize.pathname).toBe("https://marketplace.leadconnectorhq.com/v2/oauth/chooselocation");- expect(Object.fromEntries(authorize.searchParams)).toEqual({- response_type: "code",- redirect_uri: REDIRECT_URL,- client_id: CLIENT_ID,- scope: SCOPES,- state: flow.state,- });- expect(flow.authorizationUrl).toContain("scope=contacts.readonly%20contacts.write");-- // The row holds a derivation of the state, not the state, and no payload yet.- const [row] = await rows();- expect(row).toMatchObject({ ciphertext: null, claimed_at: null });- expect(row!.lookup).toBe(await flowLookup(flow.state));- expect(row!.lookup).not.toContain(flow.state);-- // The person's browser arrives from HighLevel: no Origin, no credential.- const page = await callback(worker, testEnv, { code: CODE, state: flow.state });- expect(page.status).toBe(200);- expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");- expect(page.headers.get("cache-control")).toBe("no-store");- const html = await page.text();- expect(html).toContain("Connected");- expect(html).toContain("Close this tab and go back to OpenMausBot.");- expect(html).not.toContain(flow.state);-- expect(highLevel.calls).toHaveLength(1);- expect(highLevel.calls[0]!.url).toBe(HIGHLEVEL_TOKEN_URL);- expect(highLevel.calls[0]!.contentType).toBe("application/x-www-form-urlencoded");- expect(highLevel.calls[0]!.form).toEqual({- client_id: CLIENT_ID,- client_secret: CLIENT_SECRET,- grant_type: "authorization_code",- code: CODE,- user_type: "Location",- redirect_uri: REDIRECT_URL,- });-- // Sealed, not stored in clear.- const [filled] = await rows();- expect(filled!.ciphertext).toBeTruthy();- for (const secret of [ACCESS_TOKEN, REFRESH_TOKEN, "l1C08ntBrFjLS0elLIYU"]) {- expect(filled!.ciphertext).not.toContain(secret);- }-- const first = await claim(worker, testEnv, flow.state);- expect(first.status).toBe(200);- expect(await first.json()).toEqual(expectedPayload);- const [claimed] = await rows();- expect(claimed).toMatchObject({ ciphertext: null });- expect(claimed!.claimed_at).toEqual(expect.any(Number));-- const second = await claim(worker, testEnv, flow.state);- expect(second.status).toBe(410);- expect(await second.json()).toEqual({ error: "highlevel_claimed" });- // A late or replayed callback cannot refill a claimed flow.- const replay = await callback(worker, testEnv, { code: CODE, state: flow.state });- expect(replay.status).toBe(400);- expect(highLevel.calls).toHaveLength(1);- });-- it("claim before the callback is 404 so the harness keeps polling; a wrong state is 404 too", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);-- const early = await claim(worker, testEnv, flow.state);- expect(early.status).toBe(404);- expect(await early.json()).toEqual({ error: "highlevel_unknown_state" });- // The other spellings of the very same 32 bytes (the last character's two spare bits) open nothing.- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";- const aliases = [1, 2, 3].map((spare) => `${flow.state.slice(0, -1)}${alphabet[alphabet.indexOf(flow.state.at(-1)!) | spare]}`);- for (const alias of aliases) expect((await callback(worker, testEnv, { code: CODE, state: alias })).status, alias).not.toBe(200);-- expect((await callback(worker, testEnv, { code: CODE, state: flow.state })).status).toBe(200);- for (const alias of aliases) expect((await claim(worker, testEnv, alias)).status, alias).toBe(404);- // A state that differs in one character opens nothing, before or after.- const wrong = `${flow.state.slice(0, -1)}${flow.state.endsWith("A") ? "B" : "A"}`;- const other = await claim(worker, testEnv, wrong);- expect(other.status).toBe(404);- expect(await other.json()).toEqual({ error: "highlevel_unknown_state" });- expect((await claim(worker, testEnv, "not a state")).status).toBe(400);- expect((await claim(worker, testEnv, flow.state)).status).toBe(200);- });-- it("an expired state fails the callback and the claim, and the cron sweeps it", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);- await age(flow.state, HIGHLEVEL_FLOW_TTL_MS + 1_000);-- const page = await callback(worker, testEnv, { code: CODE, state: flow.state });- expect(page.status).toBe(400);- expect(await page.text()).toContain("Connection expired");- expect(highLevel.calls).toEqual([]);- expect((await claim(worker, testEnv, flow.state)).status).toBe(404);-- expect(await rows()).toHaveLength(1);- await runScheduled(worker, testEnv);- expect(await rows()).toEqual([]);- expect(logs.some((line) => line.includes('"message":"highlevel flow sweep"') && line.includes('"deleted":1'))).toBe(true);- expect((await claim(worker, testEnv, flow.state)).status).toBe(404);-- // A live flow survives the sweep.- const live = await started(worker, testEnv);- await runScheduled(worker, testEnv);- expect(await rows()).toHaveLength(1);- expect((await callback(worker, testEnv, { code: CODE, state: live.state })).status).toBe(200);- });-- it("a denied consent shows a cancelled page and the claim stays 404", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);-- const page = await callback(worker, testEnv, { error: "access_denied", error_description: "<script>alert(1)</script>", state: flow.state });- expect(page.status).toBe(200);- const html = await page.text();- expect(html).toContain("Connection cancelled");- expect(html).not.toContain("script");- expect(html).not.toContain("access_denied");- expect(highLevel.calls).toEqual([]);- expect(await rows()).toEqual([]);- const response = await claim(worker, testEnv, flow.state);- expect(response.status).toBe(404);- expect(await response.json()).toEqual({ error: "highlevel_unknown_state" });- // The state cannot be reused with a code afterwards.- expect((await callback(worker, testEnv, { code: CODE, state: flow.state })).status).toBe(400);- });-- it("of two callbacks with the same code, only one exchanges it, and the other cannot wipe the saved tokens", async () => {- let finish!: () => void;- const firstDone = new Promise<void>((resolve) => { finish = resolve; });- let secondArrived!: () => void;- const second = new Promise<void>((resolve) => { secondArrived = resolve; });- const calls: number[] = [];- // HighLevel redeems the code once: the first exchange waits until the- // second callback has either reached HighLevel too or answered, and the- // second is refused only after the first has finished.- const highLevelFetch = (async () => {- calls.push(calls.length);- if (calls.length === 1) {- await Promise.race([second, firstDone]);- return new Response(JSON.stringify(tokenAnswer().body), { status: 200, headers: { "content-type": "application/json" } });- }- secondArrived();- await firstDone;- return new Response(JSON.stringify({ error: "invalid_grant" }), { status: 400, headers: { "content-type": "application/json" } });- }) as typeof fetch;- const worker = createWorker(fetch, fetch, highLevelFetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);-- const pages = [callback(worker, testEnv, { code: CODE, state: flow.state }), callback(worker, testEnv, { code: CODE, state: flow.state })];- await Promise.race(pages);- finish();- const statuses = (await Promise.all(pages)).map((page) => page.status).sort();- expect(statuses).toEqual([200, 400]);- expect(calls).toHaveLength(1);- const claimed = await claim(worker, testEnv, flow.state);- expect(claimed.status).toBe(200);- expect(await claimed.json()).toEqual(expectedPayload);- });-- it("a denied consent that arrives during the exchange does not end the flow", async () => {- let release!: () => void;- const released = new Promise<void>((resolve) => { release = resolve; });- let exchanging!: () => void;- const inExchange = new Promise<void>((resolve) => { exchanging = resolve; });- const highLevelFetch = (async () => {- exchanging();- await released;- return new Response(JSON.stringify(tokenAnswer().body), { status: 200, headers: { "content-type": "application/json" } });- }) as typeof fetch;- const worker = createWorker(fetch, fetch, highLevelFetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);-- const connected = callback(worker, testEnv, { code: CODE, state: flow.state });- await inExchange;- const denied = await callback(worker, testEnv, { error: "access_denied", state: flow.state });- expect(denied.status).toBe(400);- release();- expect((await connected).status).toBe(200);- const claimed = await claim(worker, testEnv, flow.state);- expect(claimed.status).toBe(200);- expect(await claimed.json()).toEqual(expectedPayload);- });-- it("a failed exchange shows the failed page, logs only a status, and the claim stays 404", async () => {- const highLevel = fakeHighLevel([{ status: 400, body: { message: `invalid code ${CODE}`, statusCode: 400 } }]);- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);-- const page = await callback(worker, testEnv, { code: CODE, state: flow.state });- expect(page.status).toBe(502);- const html = await page.text();- expect(html).toContain("Connection failed");- expect(html).toContain("Go back to OpenMausBot and try again.");- expect(highLevel.calls).toHaveLength(1);- expect(logs.some((line) => line.includes('"errorCode":"highlevel_exchange_failed"') && line.includes('"status":400'))).toBe(true);- expect((await claim(worker, testEnv, flow.state)).status).toBe(404);- expect(await rows()).toEqual([]);-- // An unreachable HighLevel, or a malformed answer, fails the same way.- for (const answer of [{ throws: true } as const, { status: 200, body: { token_type: "Bearer" } }]) {- const again = await started(worker, testEnv);- highLevel.calls.length = 0;- const broken = fakeHighLevel([answer]);- const brokenWorker = createWorker(fetch, fetch, broken.fetch);- expect((await callback(brokenWorker, testEnv, { code: CODE, state: again.state })).status).toBe(502);- expect((await claim(brokenWorker, testEnv, again.state)).status).toBe(404);- }- });-- it("the callback is not blocked by the origin allow-list, unlike the JSON routes", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();- const flow = await started(worker, testEnv);-- // A JSON route from a foreign origin is refused as everywhere else.- const foreign = await claim(worker, testEnv, flow.state, { origin: "https://evil.example" });- expect(foreign.status).toBe(403);- expect(await foreign.json()).toEqual({ error: "origin_not_allowed" });-- // Browsers may attach `Origin: null` to a cross-site redirect; the page must still render.- const page = await callback(worker, testEnv, { code: CODE, state: flow.state }, { origin: "null" });- expect(page.status).toBe(200);- expect(page.headers.get("access-control-allow-origin")).toBeNull();- expect(page.headers.get("x-content-type-options")).toBe("nosniff");- expect(page.headers.get("referrer-policy")).toBe("no-referrer");- expect((await claim(worker, testEnv, flow.state)).status).toBe(200);-- // Only GET renders the callback; nothing else is served on that path.- expect((await call(worker, testEnv, "/v1/highlevel/callback", { method: "POST", body: {} })).status).toBe(404);- });-- it("refresh returns the rotated pair, and a HighLevel 4xx is 401 highlevel_refresh_rejected", async () => {- const highLevel = fakeHighLevel([- tokenAnswer({ access_token: ACCESS_TOKEN_2, refresh_token: REFRESH_TOKEN_2 }),- { status: 401, body: { message: "Invalid refresh token", statusCode: 401 } },- { status: 503, body: null },- { throws: true },- ]);- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();-- const rotated = await refresh(worker, testEnv, REFRESH_TOKEN);- expect(rotated.status).toBe(200);- expect(await rotated.json()).toEqual({ ...expectedPayload, accessToken: ACCESS_TOKEN_2, refreshToken: REFRESH_TOKEN_2 });- expect(highLevel.calls[0]!.form).toEqual({- client_id: CLIENT_ID,- client_secret: CLIENT_SECRET,- grant_type: "refresh_token",- refresh_token: REFRESH_TOKEN,- user_type: "Location",- redirect_uri: REDIRECT_URL,- });-- const rejected = await refresh(worker, testEnv, REFRESH_TOKEN);- expect(rejected.status).toBe(401);- expect(await rejected.json()).toEqual({ error: "highlevel_refresh_rejected" });-- for (let attempt = 0; attempt < 2; attempt += 1) {- const failed = await refresh(worker, testEnv, REFRESH_TOKEN);- expect(failed.status).toBe(502);- expect(await failed.json()).toEqual({ error: "highlevel_refresh_failed" });- }- expect((await refresh(worker, testEnv, "")).status).toBe(400);- expect((await call(worker, testEnv, "/v1/highlevel/refresh", { body: { refreshToken: REFRESH_TOKEN, extra: 1 } })).status).toBe(400);- expect(highLevel.calls).toHaveLength(4);- expect(await rows()).toEqual([]);- });-- it("limits each route per caller address", async () => {- const highLevel = fakeHighLevel();- const worker = createWorker(fetch, fetch, highLevel.fetch);- const testEnv = highLevelEnv();-- for (let attempt = 0; attempt < HIGHLEVEL_START_LIMIT; attempt += 1) {- expect((await start(worker, testEnv, { ip: "198.51.100.1" })).status).toBe(200);- }- const limited = await start(worker, testEnv, { ip: "198.51.100.1" });- expect(limited.status).toBe(429);- expect(limited.headers.get("retry-after")).toBe("60");- expect(await limited.json()).toEqual({ error: "rate_limited" });- // Another address, and the other routes from the same address, still work.- expect((await start(worker, testEnv, { ip: "198.51.100.2" })).status).toBe(200);- expect((await claim(worker, testEnv, "a".repeat(43), { ip: "198.51.100.1" })).status).toBe(404);- expect(HIGHLEVEL_CLAIM_LIMIT).toBeGreaterThan(HIGHLEVEL_START_LIMIT);-- const keys = await env.DB.prepare("SELECT ip_key FROM highlevel_ip_rate_limits").all<{ ip_key: string }>();- expect(keys.results.length).toBeGreaterThan(0);- for (const { ip_key } of keys.results) {- expect(ip_key).toMatch(/^[0-9a-f]{64}$/);- expect(ip_key).not.toContain("198.51.100");- }- });-});diff --git a/cloudflare/control-plane/test/migrations.test.ts b/cloudflare/control-plane/test/migrations.test.tsnew file mode 100644index 0000000000..7e90cdf81e--- /dev/null+++ b/cloudflare/control-plane/test/migrations.test.ts@@ -0,0 +1,47 @@+import { env } from "cloudflare:workers";+import { applyD1Migrations } from "cloudflare:test";+import { describe, expect, it } from "vitest";++const migrationIndex = (prefix: string) => env.TEST_MIGRATIONS.findIndex((migration) => migration.name.startsWith(prefix));++async function schemaNames(db: D1Database, pattern: string) {+ const rows = await db.prepare(+ "SELECT type, name FROM sqlite_master WHERE name LIKE ? ORDER BY type, name",+ ).bind(pattern).all<{ type: string; name: string }>();+ return rows.results;+}++describe("migration 0013", () => {+ it("drops the retired OAuth relay's tables, rows and indexes included, after 0010", async () => {+ const db = env.MIGRATION_DB;+ const drop = migrationIndex("0013_");+ expect(drop).toBeGreaterThan(migrationIndex("0010_"));+ expect(migrationIndex("0010_")).toBeGreaterThan(migrationIndex("0009_"));+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(0, drop));+ // What the relay left behind on a database that had 0009 and 0010.+ await db.batch([+ db.prepare(+ "INSERT INTO highlevel_flows (lookup, ciphertext, created_at, callback_at) VALUES (?, 'sealed', 1, 2)",+ ).bind("a".repeat(64)),+ db.prepare(+ `INSERT INTO highlevel_ip_rate_limits (ip_key, action, window_started_at, attempts, updated_at)+ VALUES (?, 'start', 1, 1, 1)`,+ ).bind("b".repeat(64)),+ ]);+ expect(await schemaNames(db, "highlevel%")).not.toEqual([]);++ await applyD1Migrations(db, env.TEST_MIGRATIONS);++ expect(await schemaNames(db, "highlevel%")).toEqual([]);+ // The rest of the schema is untouched.+ expect(await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'installations'").first())+ .toEqual({ name: "installations" });+ // Running it again, on a database where the tables are already gone, is harmless.+ for (const query of env.TEST_MIGRATIONS[drop]!.queries) await db.prepare(query).run();+ expect(await schemaNames(db, "highlevel%")).toEqual([]);+ });++ it("leaves no relay table in the fully migrated database", async () => {+ expect(await schemaNames(env.DB, "highlevel%")).toEqual([]);+ });+});diff --git a/cloudflare/control-plane/test/setup.ts b/cloudflare/control-plane/test/setup.tsindex 50d1a7f92d..5a3e39ae6b 100644--- a/cloudflare/control-plane/test/setup.ts+++ b/cloudflare/control-plane/test/setup.ts@@ -28,8 +28,6 @@ afterEach(async () => {env.DB.prepare("DELETE FROM installation_action_rate_limits"),env.DB.prepare("DELETE FROM installation_endpoints"),env.DB.prepare("DELETE FROM installation_push_devices"),- env.DB.prepare("DELETE FROM highlevel_flows"),- env.DB.prepare("DELETE FROM highlevel_ip_rate_limits"),// A missing row reads as an empty snapshot (never scanned, never refused).env.DB.prepare("DELETE FROM managed_endpoint_account_capacity"),env.DB.prepare("DELETE FROM installation_credentials"),diff --git a/cloudflare/control-plane/wrangler.jsonc b/cloudflare/control-plane/wrangler.jsoncindex a597a56eae..567cb28fa4 100644--- a/cloudflare/control-plane/wrangler.jsonc+++ b/cloudflare/control-plane/wrangler.jsonc@@ -63,15 +63,6 @@// Cleanup rows per five-minute cron run. 20 needs Workers Paid; use 4 on// Workers Free (50 subrequests per invocation)."OMB_CLEANUP_SWEEP_LIMIT": "20",- // HighLevel OAuth relay (README "HighLevel OAuth relay"). The client id- // is public (it is in the authorization URL); the secret is- // HIGHLEVEL_CLIENT_SECRET, set with `wrangler secret put` and deliberately- // not in secrets.required: the relay answers 503 highlevel_unavailable- // until it exists. The redirect URL must match the one registered in the- // HighLevel Marketplace app exactly.- "HIGHLEVEL_CLIENT_ID": "6ad0c3b87999ff4de949c785-mv9n5v73",- "HIGHLEVEL_REDIRECT_URL": "https://accounts.openmausbot.com/v1/highlevel/callback",- "HIGHLEVEL_SCOPES": "contacts.readonly contacts.write opportunities.readonly opportunities.write conversations.readonly locations.readonly calendars.readonly calendars/events.readonly users.readonly",// MausBot Relay (README "MausBot Relay"). Host tokens are signed with RELAY_TOKEN_SIGNING_KEY (b64u of a 32-byte// Ed25519 seed, `wrangler secret put`). It is in secrets.required so a deploy can't drop it: set it before the// first deploy that lists it. The relay holds only the matching public key. RELAY_NODES lists only nodes thatdiff --git a/connector/e2e/run.sh b/connector/e2e/run.shindex 07aca30041..0545e7ec54 100644--- a/connector/e2e/run.sh+++ b/connector/e2e/run.sh@@ -4,8 +4,8 @@# starts the connector and enrols; then start (the box passes every check), update to another digest, an unclean kill# started again, an update forced to fail rolled back (image and data), a job from root on the server, the audit log of# all of it, and uninstall keeping the data and the log.-# Nothing reaches a production service: the home's connected-apps broker points at a closed loopback port and its-# HighLevel relay is off; the Admin is the fake one on loopback.+# Nothing reaches a production service: the home's connected-apps broker points at a closed loopback port; the Admin is+# the fake one on loopback.# OUT=<evidence folder> bash connector/e2e/run.shset -euo pipefailROOT=$(cd "$(dirname "$0")/../.." && pwd)@@ -95,7 +95,7 @@ expect '.heartbeats >= 1 and .lastHeartbeat.host.arch == "x86_64" and ([.lastHeaENV_JSON=$(jq -cn --arg secret "$SECRET" '{OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "e2e-connector-home", OMB_CLOUD_ADMIN_URL: "https://admin.e2e.invalid",OMB_PUBLIC_URL: "https://home.e2e.invalid", OMB_CLOUD_BOOTSTRAP_SECRET: $secret,- OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9", OMB_HIGHLEVEL_RELAY_URL: "off"+ OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9"}')step "the team's Owner accepts the server; until then it takes no job that changes anything"@@ -120,7 +120,6 @@ expect '.host | .Init and .ShmSize == 536870912 and (.MaskedPaths // [] | lengthexpect '.host | (.CapDrop | map(sub("^CAP_"; ""))) == ["ALL"] and (.CapAdd | map(sub("^CAP_"; "")) | sort) == ["CHOWN", "KILL", "SETGID", "SETUID"]' "$settings" "the home's capabilities"expect '.host | .PortBindings["8080/tcp"] == [{"HostIp": "127.0.0.1", "HostPort": "8080"}] and (.SecurityOpt | any(startswith("seccomp="))) and (.SecurityOpt | any(. == "no-new-privileges=true" or . == "no-new-privileges"))' "$settings" "the home's port and seccomp"docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' mausbot-home | grep -qx "OMB_COMPOSIO_BROKER_URL=http://127.0.0.1:9" || fail "the home could reach the production connected-apps broker"-docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' mausbot-home | grep -qx "OMB_HIGHLEVEL_RELAY_URL=off" || fail "the home could reach the production HighLevel relay"docker exec -u maus mausbot-home sh -c 'echo kept > /data/e2e-marker'step "update to another digest: a safety copy, a swap, and the new image's health"diff --git a/connector/test/protocol.test.ts b/connector/test/protocol.test.tsindex c680d1adb5..c3054b70cf 100644--- a/connector/test/protocol.test.ts+++ b/connector/test/protocol.test.ts@@ -49,7 +49,7 @@ describe("the connector protocol", () => {it("starts a home only with its contract, OMB_ settings the image does not own, and one-line values, and never echoes a value", () => {expect(checkHomeEnv(env)).toEqual({ ok: true, value: env });- expect(checkHomeEnv({ ...env, OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9", OMB_HIGHLEVEL_RELAY_URL: "off", OMB_CLOUD_TEAM_ID: "t1" }).ok).toBe(true);+ expect(checkHomeEnv({ ...env, OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9", OMB_CLOUD_TEAM_ID: "t1" }).ok).toBe(true);for (const name of REQUIRED_HOME_ENV) {const { [name]: _dropped, ...rest } = env;expect(checkHomeEnv(rest), name).toMatchObject({ ok: false, message: `env must set ${name}` });diff --git a/docs/bot-box.md b/docs/bot-box.mdindex 3d500c574b..f2b15f7b01 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -93,8 +93,8 @@ Cloudflare Worker answers with 404), anything below it below that address, withupstream's own. MCP Settings → **Test** reaches a URL server the same way where turns are boxed(`server/bot-box/broker-probe.ts`): a grant made like a turn's, through the broker's socket, revoked when the testends. A server that answers directly but not through the broker fails the test with "Your bots can't reach this-server", never "Connected", and says the fault is ours. Connected apps (Composio,-HighLevel) were already behind the harness (`/api/internal/connectors/*` with a per-turn bearer) and stay there.+server", never "Connected", and says the fault is ours. Connected apps (Composio) were already behind the harness+(`/api/internal/connectors/*` with a per-turn bearer) and stay there.A key whose CLI takes no base URL from the environment (xAI, Mistral, Groq, Greenference, Cerebras, MiniMax, Kimi, Cursor, Factory,Cline, OpenCode, OpenRouter's own variable) stays raw in that box, and the report names it under `broker.unbrokered`,diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 39e9e722d0..b8cbb46387 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1208,7 +1208,7 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):the root supervisor that restarts them is -1000, never picked. When memoryruns out the kernel takes a bot's process, never the workspace.- **OpenCode reaches OpenMausBot's own tools over HTTP.** The agents,- browser, computer, Data and HighLevel servers are endpoints of this server+ browser, computer, Data, Email and phone servers are endpoints of this server(`/api/internal/mcp-http/<name>`, `server/routes/own-mcp-http.ts`) with theturn's capability in the Authorization header, instead of a Node proxyprocess each (about 20–30 MB PSS apiece) in every OpenCode session. A server@@ -1708,9 +1708,8 @@ kinds, random ids, connector slugs, booleans and machine numbers. Connectedapps are looked up in the background at most every 30 minutes, so a slowprovider never holds the answer. `connectors.items` lists only apps theperson set up: connected now, or connected once and since expired or failed.-An app never connected, HighLevel without a saved connection included, is not-listed. Cloud computers are not listed: through the-Admin's Boat relay that would count as using an included service and hold back+An app never connected is not listed. Cloud computers are not listed: through+the Admin's Boat relay that would count as using an included service and hold backupdates; a cloud computer that fails a turn arrives as its place's code(`cc-unavailable`, `cc-no-start`, `cc-provider`, …).diff --git a/docs/highlevel.md b/docs/highlevel.mddeleted file mode 100644index 9668666a91..0000000000--- a/docs/highlevel.md+++ /dev/null@@ -1,197 +0,0 @@-# HighLevel CRM (native integration)--One card, **HighLevel**, in Connected apps, on desktop and on a Cloud home alike. It also covers Growably and every-other HighLevel-based white-label CRM: the sign-in uses HighLevel's white-label page, so those users never see the-HighLevel brand. Composio is not involved; the server (`server/highlevel/*`) talks to-`https://services.leadconnectorhq.com` itself.--## How it works--```-OMB server (desktop or Cloud home) accounts.openmausbot.com (relay) HighLevel- POST /api/highlevel/sign-in ───────────▶ POST /v1/highlevel/start → state + auth URL- app opens the auth URL in the browser ─────────────────────────────────────────────▶ sign in, pick a location- ◀── GET /v1/highlevel/callback?code&state ── redirect- exchanges the code (client secret lives there only)- polls POST /v1/highlevel/claim every 2 s ◀── tokens, once (404 before, 410 after)- stores the tokens, encrypted, in DATA_DIR- calls services.leadconnectorhq.com with the access token (Version: 2021-07-28; conversations 2021-04-15)- on 401 or near expiry: POST /v1/highlevel/refresh {refreshToken} → new pair, stored (the refresh token rotates)-```--- **Connect** starts a flow and returns `{flowId, authorizationUrl, expiresAt}`; the app opens the link and polls the- flow. The server polls the relay for up to 10 minutes; the flow lives in memory only.-- **Private Integration token** (for agencies that hide the Marketplace): `POST /api/highlevel/token {token, locationId}`.- The token is created inside the sub-account (Settings → Private Integrations) with the permissions under- [Permissions](#permissions-scopes), and checked with `GET /locations/{locationId}` before it is saved, so it needs- **View Locations**. A refused check says which case it is (`tokenCheckError` in `server/highlevel/client.ts`), adds- HighLevel's own reason (secrets redacted, at most 160 characters) and never repeats the token:- - 401 "not authorized for this scope": the token is missing View Locations; turn it on (the token stays the same).- - any other 401: the token was not accepted (mistyped, rotated or deleted), or lacks View Locations.- - 403: the token belongs to another sub-account, or is an agency-level token.- - 404: no location with that ID.-- The token never refreshes. A 401 that rejects the token itself signs it out; a 401 for a missing scope does not (see- [Permissions](#permissions-scopes)).-- **Storage:** `DATA_DIR/highlevel.json.enc`, AES-256-GCM under `DATA_DIR/highlevel-key` (0600), the same scheme as- saved logins. No keychain in the path, so a Cloud home works the same way. Stored: kind (`oauth` | `token`), access- token, refresh token, expiry, locationId, companyId, userId, location name, scopes, state (`signed-in` |- `needs-sign-in`) and the plain-sentence problem when a new sign-in is needed. No route ever returns a token.-- **Reconnect:** when the relay rejects a refresh (`401 highlevel_refresh_rejected`: revoked, app uninstalled) the- store is marked `needs-sign-in`, the card shows "Signed out. Reconnect to keep using it.", and every tool call- answers the plain signed-out note until the person reconnects.-- **Disconnect** (`DELETE /api/highlevel`) removes the tokens. HighLevel's own uninstall is a link in the UI.--### "Please reach out to the agency admin for assistance with installation"--HighLevel's Marketplace install page shows this when the agency that owns the sub-account (often a white-label agency,-e.g. Growably) does not let sub-account users install apps. It comes from HighLevel, not OpenMausBot, and Connect-cannot get past it. Either ask the agency admin to install the app for that sub-account (or to allow sub-account-installs), or use **Use a Private Integration token instead** on the card: a sub-account admin can create one under Settings →-Private Integrations when the agency allows it.--## Owner routes (`server/routes/highlevel.ts`, admin or owner session only)--| Route | Answer |-|---|---|-| `GET /api/highlevel` | `{ state: unavailable \| signed-out \| connecting \| connected \| needs-sign-in, kind?, location?: {id, name}, connectedAt?, flow?: {flowId, authorizationUrl, expiresAt}, problem? }` |-| `POST /api/highlevel/sign-in` | `{ flowId, authorizationUrl, expiresAt }` |-| `GET /api/highlevel/sign-in/:flowId` | `{ phase: waiting \| connected \| failed \| expired, message? }`; 404 `{error}` for an unknown flow |-| `DELETE /api/highlevel/sign-in/:flowId` | cancels |-| `POST /api/highlevel/token` | body `{ token, locationId }` → the status; errors are `{ error: "<plain sentences>" }` with HighLevel's status (401, 403, 404) or 400 |-| `DELETE /api/highlevel` | disconnects → the status |--`GET /api/connectors/tools` also carries a `highlevel` entry with the twenty tool names. Bot settings do not use it for-HighLevel (see [Per-bot scope](#per-bot-scope)). Cloud health merges `{ highlevel: { connected } }` into its connectors-report while a HighLevel connection is saved (signed in, or needing sign-in again); a HighLevel never connected is not-listed.--## Environment--| Variable | Meaning |-|---|---|-| `OMB_HIGHLEVEL_RELAY_URL` | The relay. Default `https://accounts.openmausbot.com`. `off` disables the integration (`state: "unavailable"`); a Private Integration token still works. Loopback `http://` is accepted for tests. |-| `OMB_HIGHLEVEL_API_URL` | Tests only: a fake HighLevel in place of `https://services.leadconnectorhq.com`. |--## Tools (bots)--Mounted as the MCP server `highlevel` through the harness proxy (`/api/internal/highlevel/mcp`, token env-`OMB_MCP_TOKEN_HIGHLEVEL`), so drivers see `mcp__highlevel__HIGHLEVEL_GET_CONTACT` and the like. Every call carries the-turn's capability; the server re-reads the live bot on every call for the verdict.--| Tool | Does | Read/write |-|---|---|---|-| `HIGHLEVEL_SEARCH_CONTACTS` | free text + exact tag/email/phone filters, page | read |-| `HIGHLEVEL_GET_CONTACT` | one contact, custom fields by name | read |-| `HIGHLEVEL_CREATE_CONTACT` / `HIGHLEVEL_UPDATE_CONTACT` | name, email, phone, company, tags, source, address, custom fields by name | write |-| `HIGHLEVEL_ADD_TAGS` / `HIGHLEVEL_REMOVE_TAGS` | tags on a contact | write |-| `HIGHLEVEL_LIST_NOTES` / `HIGHLEVEL_ADD_NOTE` | notes on a contact | read / write |-| `HIGHLEVEL_LIST_TASKS` / `HIGHLEVEL_ADD_TASK` | tasks on a contact (title, due date, description, assignee) | read / write |-| `HIGHLEVEL_LIST_PIPELINES` | pipelines with stages | read |-| `HIGHLEVEL_SEARCH_OPPORTUNITIES` / `HIGHLEVEL_GET_OPPORTUNITY` | by pipeline, stage, contact, status, text; one by id | read |-| `HIGHLEVEL_CREATE_OPPORTUNITY` / `HIGHLEVEL_UPDATE_OPPORTUNITY` | pipeline, stage, contact, name, value, status (open/won/lost/abandoned) | write |-| `HIGHLEVEL_SEARCH_CONVERSATIONS` / `HIGHLEVEL_READ_CONVERSATION` | conversation summaries; the messages of one | read |-| `HIGHLEVEL_LIST_CALENDARS` / `HIGHLEVEL_LIST_EVENTS` | calendars; events in a date range | read |-| `HIGHLEVEL_GET_LOCATION` | name, timezone, contact details, custom field definitions | read |--Outputs are trimmed objects (ids, names, email, phone, tags, dates, custom fields by name), never raw API dumps.-Errors are one plain sentence: "HighLevel refused this (403): the connection lacks the contacts.write permission.",-"HighLevel refused this (401): the connection lacks the View Custom Fields permission (locations/customFields.readonly).",-"HighLevel has no contact with that id (404).", "HighLevel is rate-limiting; try again in a few seconds."--**Never:** no tool sends SMS, email or WhatsApp, starts a campaign or workflow, books or changes appointments, deletes a-record (except removing tags) or touches payments. The guard is in the client (`assertAllowedPath` and-`FORBIDDEN_PATHS` in `server/highlevel/client.ts`), so no later tool can grow a path to those endpoints; a test asserts-the client has no such method. The system prompt tells the bot the same.--## Per-bot scope--The same rules as other connected apps, with slug `highlevel`:--- `bot.composio === false` → no HighLevel tools.-- `connectorScopes.apps.highlevel`: `read` allows SEARCH/GET/LIST/READ only; `write` allows everything; a scopes record- without `highlevel` mounts nothing.-- In the app: **Bot settings → Access → Connected apps**, with "Limit this bot to specific apps" on, gives HighLevel- **Off**, **Read** or **Read & write** per bot (`connectorScopes.apps.highlevel`). There is no per-tool picker for- HighLevel: the tool-grants picker lists Composio apps only (`AccessSection.tsx` filters `highlevel` out).-- `connectorTools.highlevel.tools`: `"*"` or a list of tool names, still honoured on every call when a bot record carries- one. `shared/highlevel.ts` `HIGHLEVEL_TOOL_GROUPS` defines four groups (*Contacts and notes*, *Pipelines and deals*,- *Conversations (read)*, *Calendars (read)*; `HIGHLEVEL_GET_LOCATION` is in every group) for such grants; no screen- shows them yet.-- Whatever the level, sending messages, campaigns, workflows and payments stay blocked for every bot- (`FORBIDDEN_PATHS`; see **Never** above).-- `tools/list` shows only what the bot may run; a refused call answers the connector scope text ("HighLevel is- read-only for <bot>, and Add note would write to it…") and writes a decision row (`source: connector-scope`).-- CRM record changes are not messages: no outbound card; the write scope is the control.--## Permissions (scopes)--Each call needs one HighLevel scope. A Private Integration is given them by name on HighLevel's Private Integrations-page; the Marketplace app asks for `HIGHLEVEL_SCOPES` (`cloudflare/control-plane/wrangler.jsonc`), which must match the-scopes approved for the app in HighLevel's developer dashboard. That list does not include-`locations/customFields.readonly` or `conversations/message.readonly` yet, so a Marketplace connection reads custom-fields keyed by id and, per HighLevel's API reference, cannot read a conversation's messages until both are added in-both places.--| Permission (Private Integrations page) | Scope | Used by |-|---|---|---|-| View Locations | `locations.readonly` | the token check, `HIGHLEVEL_GET_LOCATION` |-| View Contacts | `contacts.readonly` | contact search and reads, notes and tasks lists |-| Edit Contacts | `contacts.write` | contact create and update, tags, add note, add task |-| View Opportunities | `opportunities.readonly` | pipelines, opportunity search and reads |-| Edit Opportunities | `opportunities.write` | opportunity create and update |-| View Custom Fields | `locations/customFields.readonly` | naming custom fields in contact reads and `HIGHLEVEL_GET_LOCATION`; writing custom fields by name |-| View Conversations | `conversations.readonly` | `HIGHLEVEL_SEARCH_CONVERSATIONS` |-| View Conversation Messages | `conversations/message.readonly` | `HIGHLEVEL_READ_CONVERSATION` |-| View Calendars | `calendars.readonly` | `HIGHLEVEL_LIST_CALENDARS` |-| View Calendar Events | `calendars/events.readonly` | `HIGHLEVEL_LIST_EVENTS` |--The first six cover contacts, notes, tags, tasks and deals; add the last four for conversations and calendars.--HighLevel answers **401** both for a dead token (`Invalid JWT`) and for a live token missing a scope (`The token is not-authorized for this scope.`). Only the first signs the connection out (and, for OAuth, is refreshed first). A missing-scope answers the bot "HighLevel refused this (401): the connection lacks the Edit Contacts permission-(contacts.write)." and the connection stays signed in. The custom-field lookup inside contact reads is optional: without-View Custom Fields, contacts still read (their custom fields keyed by id), the refusal is cached for 10 minutes, and only-a write that names a custom field fails, naming the missing permission.--## Writes in the activity--Every successful write appends an activity row to the thread: `tool.name` `mcp__highlevel__HIGHLEVEL_<ACTION>`, and-`tool.summary` with the record id and the field names changed (`contact abc123: email, tags`), never the values.--## Limits--- HighLevel: 100 requests / 10 s and 200,000 / day per app per location. The client keeps under **90 / 10 s** per- location, waits per `Retry-After` / `X-RateLimit-Interval-Milliseconds` (at most 10 s) and retries once on 429,- retries once on 5xx, refreshes once on a dead-token 401 (and ahead of expiry) and retries the call; a missing-scope- 401 is answered at once.-- A call that creates a contact, note, task or opportunity is never sent twice. HighLevel takes no idempotency key and- may have saved the record before a 5xx or a lost answer. The bot gets an error that says so and checks first.-- Each tool call checks its turn after retry or budget waits and before each HighLevel API request.- Stop prevents later requests. A request already sent can still complete.-- Access tokens last a day; refresh tokens a year and rotate on every use. The rotated pair is stored before the retry.- A refresh or a sign-out lands only on the token pair it started from. A call whose tokens were replaced meanwhile- retries with the newer tokens of the same location, or stops when another location was connected.-- Results: at most 50 per page, pages 1 to 1,000; text fields are cut at 4,000 characters; responses over 4 MB are refused.-- Custom field definitions are cached for 10 minutes per location.--## Not in v1--Sending messages (SMS, email, WhatsApp), campaigns, workflows, payments, booking or changing appointments, deleting-records, webhooks from HighLevel (contact changed → bot), agency-level (Company) tokens, bulk installs, several-locations at once (one connection per installation).--## Tests--- `server/highlevel/client.test.ts`: request shapes, trimming, Version header, refresh-once with rotation persisted,- refreshes and late 401s that race a reconnect or another refresh,- 429 backoff, 5xx retry without replaying a create, the budget, plain errors, the store's encryption and the no-messaging guard; a missing scope- is not a sign-out (token and OAuth) while a dead token still is; the token check's 401/403/404 sentences and redaction.-- `server/highlevel/rpc.test.ts`: per-bot scoping (read-only refusal text, grants, tools/list filtering), the write- record and the host's activity row.-- `server/highlevel/cancellation.test.ts`: Stop during 429, 5xx and budget waits, before dispatch, and concurrent call isolation.-- `server/highlevel/sign-in.test.ts`: the relay contract, the sign-in flow, a replaced flow's late claim, the token path- and the owner routes.-- `server/highlevel.e2e.test.ts`: a real server, fake relay and fake HighLevel, Connect → tools → refresh →- revocation → Disconnect → Private Integration token, and Stop during a 429 wait without a later write.diff --git a/docs/localization-pt-br.md b/docs/localization-pt-br.mdindex 361bf0f8fa..aa37fc9456 100644--- a/docs/localization-pt-br.md+++ b/docs/localization-pt-br.md@@ -189,7 +189,7 @@ These stay unchanged in every pt-BR string.| Boat | Name of a third-party provider. Write it only where the English says Boat; the test fails otherwise. || Jev, Maus, Grok Bot | Names of product features or characters. || Claude, Claude Code, ChatGPT, Codex, Grok, Gemini, Cursor, OpenCode, Antigravity, OpenAI, Anthropic, xAI, OpenRouter, Ollama, Groq, Cerebras | Third-party product and company names. |-| Slack, Discord, Telegram, WhatsApp, Gmail, Notion, GitHub, Chrome, Tailscale, Cloudflare Tunnel, Docker, Podman, HighLevel, Whop, Product Hunt | Third-party product names. |+| Slack, Discord, Telegram, WhatsApp, Gmail, Notion, GitHub, Chrome, Tailscale, Cloudflare Tunnel, Docker, Podman, Whop, Product Hunt | Third-party product names. || Admin, and labels inside the Admin console | The Admin console is not localized, so pointers keep its English labels. || `SKILL.md`, `MEMORY.md`, `config.toml`, `.ombbackup`, commands, paths, URLs, environment variables, keyboard keys | Code and file names. || MCP, API, CLI, URL, HTTPS, DNS, SSH, USB, ID, CSV, PNG, JPEG | Standard abbreviations. Use `IA` for AI, never `AI`. |diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 261bef88b5..5d57f09c88 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -65,10 +65,10 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t(below), never off the team.- **Rules.** A team's Owner and Admins choose the AI engines and computers its bots may use, whether bots may add MCP serversof their own, and whether it opens on a phone or with a link (below, "Rules"). What they restrict shows as *Managed by Acme*.-- **Connected apps.** The team's connections (Composio, HighLevel, MCP sign-ins, an AI key an Admin saved) belong to the+- **Connected apps.** The team's connections (Composio, MCP sign-ins, an AI key an Admin saved) belong to theTeam Cloud and serve every member's turn through the broker. An Admin can instead make an app or an MCP server *eachperson's own* (below): then every member connects their own, and only their own chats use it. A person's- connections from elsewhere have no way in: a share code, a moved MCP sign-in or a HighLevel connection is refused with+ connections from elsewhere have no way in: a share code, a moved MCP sign-in or a mailbox is refused with*"Personal connections never enter Acme. Ask an admin to connect it for Acme."* A login from a sign-in card is saved byan Admin only, for the whole team.- **Browsers.** Each private chat with a bot drives that person's own browser of the bot, each group chat the group@@ -108,7 +108,7 @@ The team's rules live on the Admin (openmaus-cloud `docs/team-cloud.md` "Rules")only restricts. `server/cloud-team-policy.ts` fetches it at boot, every 5 minutes and when the Admin's signed `POST/api/cloud/team/policy-changed` nudges it, signed with the bootstrap secret (`POST /api/cloud/machines/team-policy`), and eachrequest reports the fingerprint in force here. A change applies without a restart. A turn already running keeps its engine-process and the servers it mounted when it began, HighLevel included, and finishes with them. What it reaches for through this+process and the servers it mounted when it began, and finishes with them. What it reaches for through thismachine is refused from that moment, mid-turn too: a connected-apps tool (the turn carries on without it) and the first claim ona computer (the turn stops there, in the rule's words; a computer it already holds stays with it until it ends). Every turn thatstarts after the change, a hand-off's included, gets the new rules, even in a chat whose engine process is still warm: that@@ -122,7 +122,7 @@ process restarts without what is now blocked.all come through `mcpServersHost.mounted`, which drops what isn't allowed, whoever connected it; adding or signing in to one isrefused. `allowedMcpServers: "team"` is the plain form: admins add servers as ever, a bot can't add one, a bot's own doesn'tstart and an engine's own user settings aren't read. Every connected-apps tool crosses `POST /api/internal/connectors/mcp`, which refuses a tool of an app that isn't- allowed, and code that could reach any app; connecting one is refused, and HighLevel isn't mounted.+ allowed, and code that could reach any app; connecting one is refused.- **Remote access** on a Team Cloud is what a member's own code opens: "Open on your phone" is refused, codes already made stopworking and phones already open sign out. The Admin-signed pairing stays: it is how every member's app and the Admin reachthis machine, so a rule never locks the team out.diff --git a/docs/verification/cloud-send.md b/docs/verification/cloud-send.mdindex 8471724a02..2c3620d1b7 100644--- a/docs/verification/cloud-send.md+++ b/docs/verification/cloud-send.md@@ -38,7 +38,7 @@ everything did, so a test can start from what such a send left on My Cloud.context summaries, a 610-message room and a conversation both sides added topass the path check; MCP servers with their keys and header tokens, an MCPsign-in of its own (left here by the first pass, carried by the final one and-let go of here), an AI key, HighLevel by its token and the connected-apps+let go of here), an AI key and the connected-appsaccount (a fake broker) arrive, with equal credential fingerprints; the move'ssession counts as someone using My Cloud; a moved conversation may use a lentMac and feeds its bot's memory on My Cloud; and a move run again changesdiff --git a/electron/cloud-connections.d.mts b/electron/cloud-connections.d.mtsindex 05784eeae4..9a2bfd6123 100644--- a/electron/cloud-connections.d.mts+++ b/electron/cloud-connections.d.mts@@ -1,7 +1,7 @@-export type ConnectionKind = "mcp" | "key" | "composio" | "highlevel" | "email";+export type ConnectionKind = "mcp" | "key" | "composio" | "email";export interface Connection {- /** "mcp:<name>", "key:<provider>", "composio", "highlevel" or "email". */+ /** "mcp:<name>", "key:<provider>", "composio" or "email". */id: string;kind: ConnectionKind;label: string;diff --git a/electron/cloud-connections.mjs b/electron/cloud-connections.mjsindex 1d309f9555..5d95422f40 100644--- a/electron/cloud-connections.mjs+++ b/electron/cloud-connections.mjs@@ -1,5 +1,5 @@// This computer's connections, moved once with the rest of the person's things to their own Cloud: MCP servers with-// their secrets and sign-ins, the AI keys bots run on, connected apps, HighLevel and mailboxes. Secrets reach main only over the+// their secrets and sign-ins, the AI keys bots run on, connected apps and mailboxes. Secrets reach main only over the// server's private port (cloud-logins.mjs) and go only to the move's owner session on My Cloud. A sign-in that// refreshes itself moves: once My Cloud has it, this computer forgets its own copy, so only My Cloud uses it.//@@ -14,16 +14,16 @@ import nativeText from "./native-text.cjs";const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);const sentence = (value) => (typeof value === "string" && value.trim() ? value.trim().slice(0, 300) : null);const pick = (source, names) => Object.fromEntries(names.filter((name) => source[name] !== undefined && source[name] !== null).map((name) => [name, source[name]]));-const ID = /^(?:mcp:[a-z][a-z0-9_-]{0,31}|key:\w{1,40}|composio|highlevel|email)$/u;+const ID = /^(?:mcp:[a-z][a-z0-9_-]{0,31}|key:\w{1,40}|composio|email)$/u;const INSTALLATION = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;const ENVIRONMENT = /^[\w-]{1,128}$/u;const SLUG = /^[a-z0-9_][a-z0-9_-]{0,80}$/u;const ENGINE = /^[\w.:-]{1,128}$/u;const LAUNCHER = /^[a-z0-9._+-]{1,40}$/u;const DIGEST = /^[0-9a-f]{64}$/u;-const KINDS = new Set(["mcp", "key", "composio", "highlevel", "email"]);+const KINDS = new Set(["mcp", "key", "composio", "email"]);/** Keys first, so the engines they run are ready before anything that follows them; connected apps last. */-const ORDER = { key: 0, mcp: 1, highlevel: 2, email: 2, composio: 3 };+const ORDER = { key: 0, mcp: 1, email: 2, composio: 3 };const MCP_FIELDS = ["command", "args", "env", "type", "url", "headers", "oauth", "resultBudget", "enabled", "runsOn"];/** How long a move waits for My Cloud to run the engines whose keys just went. */const ENGINE_WAIT_MS = 10_000;@@ -90,12 +90,12 @@ async function runningEngines(target, engines, waitMs, cloud) {}}-const signInRoute = (item) => (item.kind === "mcp" ? `/api/cloud-connections/mcp/${item.id.slice("mcp:".length)}/sign-in` : "/api/cloud-connections/highlevel");+const signInRoute = (item) => `/api/cloud-connections/mcp/${item.id.slice("mcp:".length)}/sign-in`;/** This computer's newer copy of a sign-in, in place of the one My Cloud took from it (`onCloud`); its digest, or null. */async function sendAgain(local, target, item, onCloud) {const fresh = await secrets(local, item).catch(() => null);- const signIn = item.kind === "mcp" ? fresh?.connection.mcp?.signIn : fresh?.connection.highlevel;+ const signIn = fresh?.connection.mcp?.signIn;if (!record(signIn) || !fresh.digest) return null;const answer = await target.call("PUT", `${signInRoute(item)}?replaces=${onCloud}`, signIn).catch(() => null);return answer?.ok && answer.body?.adopted === true ? fresh.digest : null;@@ -212,15 +212,6 @@ export async function sendConnections(collected, target, { local, release = trueawait moveSignIn(item, signIn, digest);}},- async highlevel(item) {- if (item.signIn && !signIns) return void result.later.push({ id: item.id, label: item.label });- const { connection, digest } = await secrets(local, item);- const highlevel = connection.highlevel;- if (!record(highlevel) || (highlevel.kind === "oauth" && !digest)) throw new ConnectionMoveError("local", "HighLevel could not be read on this computer.");- const kept = result.kept.length;- await moveSignIn(item, highlevel, highlevel.kind === "oauth" ? digest : undefined);- if (result.kept.length === kept) done(item);- },async email(item) {const accounts = (await secrets(local, item)).connection.email;if (!Array.isArray(accounts)) throw new ConnectionMoveError("local", t("native.cloud.mailRead"));diff --git a/electron/cloud-connections.node-test.mjs b/electron/cloud-connections.node-test.mjsindex e4ba51088f..3d8ef34aac 100644--- a/electron/cloud-connections.node-test.mjs+++ b/electron/cloud-connections.node-test.mjs@@ -5,7 +5,7 @@ import { adoptComposioId, collectConnections, ConnectionMoveError, parseConnecticonst COMPUTER = { environmentId: "env-desktop-1", label: "Milind's MacBook" };const INSTALLATION = "0f1e2d3c-4b5a-4968-8778-695a4b3c2d1e";-const D1 = "1".repeat(64), D2 = "2".repeat(64), D3 = "3".repeat(64);+const D1 = "1".repeat(64), D2 = "2".repeat(64);const linearSignIn = (refresh) => ({ url: "https://mcp.linear.app/sse", state: "signed-in", tokens: { access: `a-${refresh}`, refresh } });/** This computer's server: its list, and the private port's answers, each ask recorded. */@@ -45,17 +45,17 @@ function cloud({ connections = [], engines = [], commands = ["npx", "node"], repconst writes = (target) => target.calls.filter(([method]) => method !== "GET").map(([method, route]) => `${method} ${route}`);-test("moves keys first, then MCP servers with their secrets, HighLevel and connected apps, each over My Cloud's own routes", async () => {+test("moves keys first, then MCP servers with their secrets, mailboxes and connected apps, each over My Cloud's own routes", async () => {const local = computer({connections: [{ id: "mcp:dodo", kind: "mcp", label: "dodo", launcher: "npx" },{ id: "composio", kind: "composio", label: "Connected apps", mode: "managed", account: "managed:aaa" },- { id: "highlevel", kind: "highlevel", label: "HighLevel" },+ { id: "email", kind: "email", label: "Email" },{ id: "key:openrouter", kind: "key", label: "OpenRouter", for: ["openrouter"] },],answers: {"mcp:dodo": { connection: { mcp: { name: "dodo", server: { command: "npx", args: ["-y", "dodo"], env: { KEY: "k" }, enabled: true } } } },- highlevel: { connection: { highlevel: { kind: "token", accessToken: "pit-1", locationId: "loc" } } },+ email: { connection: { email: [{ address: "[email protected]" }] } },"key:openrouter": { connection: { config: { openrouter: { key: "sk-or" } } } },},connected: { gmail: { connected: true }, slack: { connected: false } },@@ -65,13 +65,14 @@ test("moves keys first, then MCP servers with their secrets, HighLevel and conneconst progress = [];const result = await sendConnections(await collectConnections(local), target, { local, onProgress: (step) => progress.push(step) });assert.deepEqual(result.failed, []);- assert.deepEqual(writes(target), ["PUT /api/cloud-connections/held-keys", "PATCH /api/config", "POST /api/mcp/servers", "PATCH /api/mcp/servers/dodo", "PUT /api/cloud-connections/highlevel", "POST /api/cloud-connections/connected-apps"]);+ assert.deepEqual(writes(target), ["PUT /api/cloud-connections/held-keys", "PATCH /api/config", "POST /api/mcp/servers", "PATCH /api/mcp/servers/dodo", "PUT /api/cloud-connections/email", "POST /api/cloud-connections/connected-apps"]);assert.deepEqual(result.held, [], "a Cloud with no trial credit to keep runs the key at once");assert.deepEqual(target.calls.find(([, route]) => route === "/api/mcp/servers")[2], { name: "dodo", command: "npx", args: ["-y", "dodo"], env: { KEY: "k" } });assert.deepEqual(target.calls.find(([, route]) => route === "/api/cloud-connections/connected-apps")[2], { share: "c".repeat(64), apps: ["gmail"] });assert.deepEqual(local.asked.find((what) => what.kind === "composio-share"), { kind: "composio-share", for: INSTALLATION });- assert.deepEqual(result.moved.map((item) => item.id), ["key:openrouter", "mcp:dodo", "highlevel", "composio"]);- assert.deepEqual(progress.map((step) => `${step.done}/${step.total} ${step.label}`), ["1/4 OpenRouter", "2/4 dodo", "3/4 HighLevel", "4/4 Connected apps"]);+ assert.deepEqual(target.calls.find(([, route]) => route === "/api/cloud-connections/email")[2], { accounts: [{ address: "[email protected]" }] });+ assert.deepEqual(result.moved.map((item) => item.id), ["key:openrouter", "mcp:dodo", "email", "composio"]);+ assert.deepEqual(progress.map((step) => `${step.done}/${step.total} ${step.label}`), ["1/4 OpenRouter", "2/4 dodo", "3/4 Email", "4/4 Connected apps"]);});test("a trial's Cloud keeps a moved key saved but unused while its Claude credit lasts, asked before the key is saved, and the move goes on without waiting for it", async () => {@@ -142,25 +143,25 @@ test("a sign-in moves and this computer lets go of it; one that refreshed meanwh});test("My Cloud keeps a sign-in of its own; with release off the result lists what this computer still holds, for later", async () => {- const connections = [{ id: "mcp:linear", kind: "mcp", label: "linear", signIn: true }, { id: "highlevel", kind: "highlevel", label: "HighLevel", signIn: true }];+ const connections = [{ id: "mcp:linear", kind: "mcp", label: "linear", signIn: true }];const answers = {"mcp:linear": { connection: { mcp: { name: "linear", server: { type: "http", url: "https://mcp.linear.app/sse", headers: {}, enabled: true }, signIn: linearSignIn("r1") } }, digest: D1 },- highlevel: { connection: { highlevel: { kind: "oauth", accessToken: "a", refreshToken: "r", locationId: "loc" } }, digest: D3 },};const keeps = computer({ connections, answers });- const own = cloud({ connections: [{ id: "mcp:linear", kind: "mcp", label: "linear" }], reply: (method, route) => (route.includes("sign-in") || route.endsWith("/highlevel") ? { status: 200, body: { kept: true } } : undefined) });+ const own = cloud({ connections: [{ id: "mcp:linear", kind: "mcp", label: "linear" }], reply: (method, route) => (route.includes("sign-in") ? { status: 200, body: { kept: true } } : undefined) });const kept = await sendConnections(await collectConnections(keeps), own, { local: keeps });- assert.deepEqual(kept.kept.map((item) => item.id), ["mcp:linear", "highlevel"]);+ assert.deepEqual(kept.kept.map((item) => item.id), ["mcp:linear"]);assert.deepEqual(kept.moved.map((item) => item.id), ["mcp:linear"], "its definition went; its sign-in there is its own");assert.equal(keeps.asked.some((what) => what.kind === "connection-release"), false);const holds = computer({ connections, answers });- const takes = cloud({ reply: (method, route) => (route.includes("sign-in") || route.endsWith("/highlevel") ? { status: 200, body: { adopted: true } } : undefined) });+ const takes = cloud({ reply: (method, route) => (route.includes("sign-in") ? { status: 200, body: { adopted: true } } : undefined) });const held = await sendConnections(await collectConnections(holds), takes, { local: holds, release: false });- assert.deepEqual(held.release, [{ id: "mcp:linear", label: "linear", digest: D1 }, { id: "highlevel", label: "HighLevel", digest: D3 }]);+ assert.deepEqual(held.release, [{ id: "mcp:linear", label: "linear", digest: D1 }]);assert.equal(holds.asked.some((what) => what.kind === "connection-release"), false);- assert.deepEqual(await releaseConnections(held.release, { local: holds, target: takes }), []);- assert.deepEqual(holds.asked.filter((what) => what.kind === "connection-release").map((what) => what.id), ["mcp:linear", "highlevel"]);+ // A held entry of a connection kind this app does not know is dropped, never asked about.+ assert.deepEqual(await releaseConnections([...held.release, { id: "highlevel", label: "HighLevel", digest: D2 }], { local: holds, target: takes }), []);+ assert.deepEqual(holds.asked.filter((what) => what.kind === "connection-release").map((what) => what.id), ["mcp:linear"]);});test("one connection failing never stops the others; a refusal trying again can't fix is final", async () => {diff --git a/electron/cloud-send.d.mts b/electron/cloud-send.d.mtsindex 299ff76c74..e69fc07541 100644--- a/electron/cloud-send.d.mts+++ b/electron/cloud-send.d.mts@@ -12,7 +12,7 @@ export interface CloudSendResult {onePassword: boolean;/** "profile" and/or "language". */settings: string[];- /** Apps and keys a move carried (MCP servers, AI keys, HighLevel, connected apps); 0 or absent for any other send. */+ /** Apps and keys a move carried (MCP servers, AI keys, mailboxes, connected apps); 0 or absent for any other send. */connections?: number;/** The chats My Cloud lacked, added by row or by Bring newer chats; null when this send did not bring chats. `left`:* conversations that did not all go this time (a bot answering in one, or My Cloud not taking a page yet). */diff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjsindex ece3d88659..5453c8c853 100644--- a/electron/cloud-send.mjs+++ b/electron/cloud-send.mjs@@ -458,7 +458,7 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>return [...ctx.cloudBots].filter((id) => bots.has(id) && ctx.localItems.has(itemKey.bot(id))).map((id) => ({ id, name: bots.get(id).name }));}- /** This computer's apps and keys, MCP servers, HighLevel and connected apps, over the move's session. A sign-in that+ /** This computer's apps and keys, MCP servers, mailboxes and connected apps, over the move's session. A sign-in that* refreshes itself goes only in the final pass; this computer then lets go of its copy once My Cloud has it, and one it* could not let go of yet is kept and let go of on the next final pass. */async function moveConnections(origin, session, result, final) {diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex 1501a2cbb5..371fc463b0 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -160,8 +160,8 @@ exports.createClient = async ({ auth }) => {* refuse this computer's token on My Cloud. `toolCalls`: each turn on this computer makes that many tool calls first, so a* few turns make a conversation of several pages. `broker`: the connected-apps service both servers use, this computer* with an installation of its own as the desktop app registers one, My Cloud registering itself as a Cloud home does.- * `env`: more of both servers' environment (a fake HighLevel and its relay). `cloudEngine`: lines run at the start of My- * Cloud's synthetic Claude CLI, to script its turns (fake-claude-cli.ts). */+ * `env`: more of both servers' environment. `cloudEngine`: lines run at the start of My Cloud's synthetic Claude CLI, to+ * script its turns (fake-claude-cli.ts). */export async function launchCloudSendFixture({ onePasswordToken, cloudOnePasswordToken = onePasswordToken, toolCalls = 0, broker, env = {}, cloudEnv = {}, cloudEngine = "", desktopEngine = "", space, cloudSignedIn = true, team }: {onePasswordToken: string; cloudOnePasswordToken?: string; toolCalls?: number;/** A Team Cloud too (OMB_CLOUD_ROLE=team), with its own environment and synthetic Claude CLI lines. */diff --git a/scripts/testing/vitest-shard-weights.json b/scripts/testing/vitest-shard-weights.jsonindex 48221204c2..788c438828 100644--- a/scripts/testing/vitest-shard-weights.json+++ b/scripts/testing/vitest-shard-weights.json@@ -163,7 +163,6 @@"server/headless-cli.e2e.test.ts": 16,"server/headless/run.test.ts": 5,"server/helper-model.e2e.test.ts": 12,- "server/highlevel.e2e.test.ts": 6,"server/hooks.e2e.test.ts": 11,"server/host-lazy-claim.e2e.test.ts": 28,"server/host/room-sessions.test.ts": 14,@@ -503,7 +502,6 @@"server/headless-cli.e2e.test.ts": 18,"server/headless/run.test.ts": 5,"server/helper-model.e2e.test.ts": 13,- "server/highlevel.e2e.test.ts": 9,"server/hooks.e2e.test.ts": 15,"server/host-lazy-claim.e2e.test.ts": 1,"server/host/room-sessions.test.ts": 9,@@ -835,7 +833,6 @@"server/headless-cli.e2e.test.ts": 27,"server/headless/run.test.ts": 5,"server/helper-model.e2e.test.ts": 1,- "server/highlevel.e2e.test.ts": 8,"server/hooks.e2e.test.ts": 1,"server/host-lazy-claim.e2e.test.ts": 34,"server/host/room-sessions.test.ts": 14,diff --git a/server/activity.test.ts b/server/activity.test.tsindex f5219ee131..6caa70b591 100644--- a/server/activity.test.ts+++ b/server/activity.test.ts@@ -27,8 +27,6 @@ describe("describeTool", () => {expect(describeTool("GMAIL_SEND_EMAIL")).toEqual({ app: "Gmail", label: "Send email" });expect(describeTool("mcp__composio__GITHUB_CREATE_AN_ISSUE")).toEqual({ app: "GitHub", label: "Create an issue" });expect(describeTool("GOOGLESHEETS_BATCH_UPDATE")).toEqual({ app: "Google Sheets", label: "Batch update" });- expect(describeTool("mcp__highlevel__HIGHLEVEL_ADD_NOTE")).toEqual({ app: "HighLevel", label: "Add note" });- expect(describeTool("HIGHLEVEL_UPDATE_CONTACT")).toEqual({ app: "HighLevel", label: "Update contact" });expect(describeTool("mcp__device__PHONE_CREATE_EVENT")).toEqual({ app: "Phone", label: "Create event" });});@@ -98,7 +96,7 @@ describe("describeTool", () => {});it("keeps an unknown or third-party tool in its own words, with no key", () => {- for (const name of ["GMAIL_SEND_EMAIL", "mcp__composio__GITHUB_CREATE_AN_ISSUE", "mcp__claude_ai_Gmail__search_threads", "mcp__highlevel__HIGHLEVEL_ADD_NOTE",+ for (const name of ["GMAIL_SEND_EMAIL", "mcp__composio__GITHUB_CREATE_AN_ISSUE", "mcp__claude_ai_Gmail__search_threads","mcp__agents__brand_new_tool", "mcp__computer__teleport", "mcp__some_server__do_thing", "TaskUpdate", "constructor"]) {expect(describedTool(name).labelKey, name).toBeUndefined();}diff --git a/server/activity.ts b/server/activity.tsindex 3b5b6959e6..720de80730 100644--- a/server/activity.ts+++ b/server/activity.ts@@ -18,7 +18,6 @@ const TOOLKIT_NAMES: Record<string, string> = {GOOGLEDRIVE: "Google Drive",GOOGLEDOCS: "Google Docs",HUBSPOT: "HubSpot",- HIGHLEVEL: "HighLevel",LINKEDIN: "LinkedIn",YOUTUBE: "YouTube",TWITTER: "X",@@ -217,7 +216,6 @@ export function describedTool(name: string, input?: unknown): Described {const member = (AGENTS_ACTION_TOOLS[action]?.members.length ?? 0) > 1 ? agentsCallMember(action, callArguments(input)) : action;return Object.hasOwn(RESEARCH_TOOL_LABELS, member) ? RESEARCH_TOOL_LABELS[member]! : ownAction("Team", member, TEAM_ACTION_KEYS);}- if (server === "highlevel") return { app: "HighLevel", label: humanize(action.replace(/^HIGHLEVEL_/, "")) };if (server === "email") return { app: "Email", appKey: "activity.app.email", label: humanize(action.replace(/^EMAIL_/, "")) };if (server === "device") return { app: "Phone", label: humanize(action.replace(/^PHONE_/, "")) };if (server.startsWith("claude_ai_")) {diff --git a/server/automatic-recovery.test.ts b/server/automatic-recovery.test.tsindex d202304c34..3dfd8dc609 100644--- a/server/automatic-recovery.test.ts+++ b/server/automatic-recovery.test.ts@@ -4,17 +4,17 @@ import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.tsdescribe("automatic recovery capabilities", () => {const engine = { driverKind: "qwenAgent", capabilities: {sessionModelSwitch: "unsupported" as const, agentsMcp: true, browserMcp: true,- customMcp: true, dataMcp: true, highlevelMcp: true, images: true,+ customMcp: true, dataMcp: true, emailMcp: true, images: true,} };it("keeps a compatible local workspace and rejects losing a tool or attachment", () => {expect(recoveryCapabilityError(engine, { ...engine, driverKind: "claudeAgent" })).toBeUndefined();- for (const key of ["agentsMcp", "browserMcp", "customMcp", "dataMcp", "highlevelMcp", "images"] as const) {+ for (const key of ["agentsMcp", "browserMcp", "customMcp", "dataMcp", "emailMcp", "images"] as const) {expect(recoveryCapabilityError(engine, { ...engine, capabilities: { ...engine.capabilities, [key]: false } })).toMatch(/tools and attachments/);}});it("lets a limited Claude bot carry on with an engine that has every tool but a USB phone", () => {const claude = { driverKind: "claudeAgent", capabilities: { sessionModelSwitch: "in-session" as const, agentsMcp: true, customMcp: true,- computerMcp: true, composioMcp: true, phoneMcp: true, browserMcp: true, dataMcp: true, highlevelMcp: true, deviceMcp: true, images: true } };+ computerMcp: true, composioMcp: true, phoneMcp: true, browserMcp: true, dataMcp: true, emailMcp: true, deviceMcp: true, images: true } };const { phoneMcp: _phone, ...rest } = claude.capabilities;const opencode = { driverKind: "opencodeAgent", capabilities: { ...rest, sessionModelSwitch: "unsupported" as const, localComputerMcp: true } };expect(recoveryCapabilityError(claude, opencode)).toBeUndefined();diff --git a/server/automatic-recovery.ts b/server/automatic-recovery.tsindex ff26a5ac30..3c857e8d38 100644--- a/server/automatic-recovery.ts+++ b/server/automatic-recovery.ts@@ -19,7 +19,7 @@ export function recoveryCapabilityError(from: Engine, to: Engine): string | undeif (supportsWorkspaceFiles(from.driverKind) !== supportsWorkspaceFiles(to.driverKind)) {return "The backup cannot use the same workspace.";}- const tools = ["agentsMcp", "computerMcp", "composioMcp", "dataMcp", "highlevelMcp", "deviceMcp",+ const tools = ["agentsMcp", "computerMcp", "composioMcp", "dataMcp", "emailMcp", "deviceMcp","browserMcp", "localComputerMcp", "customMcp", "images"] as const;if (tools.some(key => from.capabilities[key] === true && to.capabilities[key] !== true)) {return "The backup does not support all of this AI's tools and attachments.";diff --git a/server/bot-box/box-check.ts b/server/bot-box/box-check.tsindex 698e3ccf6e..4546b0aea5 100644--- a/server/bot-box/box-check.ts+++ b/server/bot-box/box-check.ts@@ -11,7 +11,7 @@ import { detectBox } from "./detect.ts";import { BOX_MUTATIONS, type BoxMutation } from "./plan.ts";import { runBoxSelfCheck } from "./self-check.ts";-export const CHECK_DENY_ENV: ReadonlySet<string> = new Set(["COMPOSIO_API_KEY", "OMB_COMPOSIO_BROKER_TOKEN", "OMB_HIGHLEVEL_TOKEN"]);+export const CHECK_DENY_ENV: ReadonlySet<string> = new Set(["COMPOSIO_API_KEY", "OMB_COMPOSIO_BROKER_TOKEN"]);export async function boxCheckMain(argv: readonly string[], env: Record<string, string | undefined> = process.env): Promise<number> {const mutate = new Set<BoxMutation>();diff --git a/server/cloud-connections-host.test.ts b/server/cloud-connections-host.test.tsindex 59e04d7a48..325a8d7097 100644--- a/server/cloud-connections-host.test.ts+++ b/server/cloud-connections-host.test.ts@@ -6,8 +6,6 @@ import { afterEach, describe, expect, it } from "vitest";import { createCloudConnectionsHost } from "./cloud-connections-host.ts";import { signInDigest } from "./cloud-connections.ts";import type { AppConfig } from "./config.ts";-import { createHighLevelService } from "./highlevel/service.ts";-import type { HighLevelConnection } from "./highlevel/store.ts";import { McpOAuthManager } from "./mcp-oauth.ts";import type { McpOAuthRecord } from "./mcp-oauth-store.ts";import { PASS } from "./routes/table.ts";@@ -19,15 +17,13 @@ const temp = () => { const dir = mkdtempSync(join(tmpdir(), "omb-connections-hosconst LINEAR = "https://mcp.linear.app/sse";const signIn = (access: string, refresh: string): McpOAuthRecord => ({ url: LINEAR, state: "signed-in", clientId: "client", tokenEndpoint: "https://linear.app/token", tokens: { access, refresh, expiresAt: 10 } });-const HIGHLEVEL: HighLevelConnection = { kind: "oauth", accessToken: "hl-access", refreshToken: "hl-refresh", expiresAt: 5, locationId: "loc_1", scopes: "", connectedAt: 1, state: "signed-in" };function host(cloudHome: boolean) {const dir = temp();const config = { mcpServers: { linear: { type: "http", url: LINEAR, headers: {}, enabled: true }, dodo: { command: "npx", args: ["dodo"], env: {}, enabled: true } } } as unknown as AppConfig;const mcpOAuth = new McpOAuthManager({ file: join(dir, "mcp-oauth.json") });- const highlevel = createHighLevelService({ dataDir: dir, env: {} });const connections = createCloudConnectionsHost({ cloudHome: cloudHome ? { publicOrigin: "https://omb-u-1.fly.dev" } : null, config: () => config,- environmentId: "env-desktop-1", mcpOAuth, highlevel, engines: async () => ["claude", "openrouter"] });+ environmentId: "env-desktop-1", mcpOAuth, engines: async () => ["claude", "openrouter"] });async function call(method: string, path: string, body?: unknown, type = "application/json") {let status = 0, answered: unknown = null;const url = new URL(`https://cloud.test${path}`);@@ -38,7 +34,7 @@ function host(cloudHome: boolean) {});return { out, status, body: answered as Record<string, any> };}- return { connections, mcpOAuth, highlevel, call };+ return { connections, mcpOAuth, call };}describe("a move's routes and private port", () => {@@ -74,15 +70,6 @@ describe("a move's routes and private port", () => {expect(mcpOAuth.signInRecord("linear", LINEAR)?.tokens?.refresh).toBe("r2");});- it("takes a moved HighLevel connection, keeping one signed in here", async () => {- const { call, highlevel } = host(true);- expect((await call("PUT", "/api/cloud-connections/highlevel", { kind: "oauth" })).status).toBe(400);- expect(await call("PUT", "/api/cloud-connections/highlevel", HIGHLEVEL)).toMatchObject({ status: 200, body: { adopted: true } });- expect(highlevel.status()).toMatchObject({ state: "connected", kind: "oauth", location: { id: "loc_1" } });- expect(await call("PUT", "/api/cloud-connections/highlevel", { ...HIGHLEVEL, accessToken: "other", locationId: "loc_2" })).toMatchObject({ status: 200, body: { kept: true } });- expect(highlevel.store.get()?.locationId).toBe("loc_1");- });-it("hands over a sign-in over the private port, then forgets it here without signing it out", async () => {const { connections, mcpOAuth } = host(false);mcpOAuth.adopt("linear", LINEAR, signIn("a1", "r1"));diff --git a/server/cloud-connections-host.ts b/server/cloud-connections-host.tsindex 560935709b..2684f154e0 100644--- a/server/cloud-connections-host.ts+++ b/server/cloud-connections-host.ts@@ -4,7 +4,7 @@import { hostname } from "node:os";import { join } from "node:path";-import { answerConnection, connectionFingerprints, highlevelDigest, launchersOnPath, listConnections, releaseConnection, signInDigest } from "./cloud-connections.ts";+import { answerConnection, connectionFingerprints, launchersOnPath, listConnections, releaseConnection, signInDigest } from "./cloud-connections.ts";import { createConnectionPrompt, type ConnectionPromptBot } from "./cloud-connections-prompt.ts";import { createStayedNotices, type StayedNoticesDeps } from "./cloud-connections-stayed.ts";import { movedFrom } from "./cloud-send-arrived.ts";@@ -12,7 +12,6 @@ import * as composio from "./composio.ts";import { brokerAccess } from "./composio-broker-access.ts";import { adoptComposioShare, adoptOwnComposio, composioIdentity, composioShareCode } from "./composio-share.ts";import type { AppConfig } from "./config.ts";-import type { HighLevelService } from "./highlevel/service.ts";import type { EmailAccount } from "./email/store.ts";import type { ConnectionHandoffAnswer, ConnectionHandoffWhat } from "./login-handoff.ts";import type { McpOAuthManager } from "./mcp-oauth.ts";@@ -30,7 +29,6 @@ export interface CloudConnectionsHostDeps {/** This server's own environment id: the computer a server that needs it is marked as running on. */environmentId: string;mcpOAuth: Pick<McpOAuthManager, "authState" | "signInRecord" | "adopt" | "forget">;- highlevel: Pick<HighLevelService, "store" | "connected" | "adopt" | "disconnect">;/** The engines (instance ids) ready to run here now. */engines(): Promise<string[]>;/** A trial's moved keys, unused while its Claude credit lasts. */@@ -50,16 +48,16 @@ export function createCloudConnectionsHost(deps: CloudConnectionsHostDeps) {const computer: McpRunsOn = { environmentId: deps.environmentId, label };let commands: string[] | null = null;const mcpAuth = (name: string, url: string) => deps.mcpOAuth.authState(name, url);- const sources = () => ({ config: deps.config(), mcpSignIn: (name: string, url: string) => deps.mcpOAuth.signInRecord(name, url), highlevel: () => deps.highlevel.store.get(), email: () => deps.email?.accounts() ?? [] });+ const sources = () => ({ config: deps.config(), mcpSignIn: (name: string, url: string) => deps.mcpOAuth.signInRecord(name, url), email: () => deps.email?.accounts() ?? [] });const composioConnected = async (slugs: string[]) =>Object.fromEntries(Object.entries(await composio.connectionStatus(deps.config(), slugs)).map(([slug, state]) => [slug, state.connected]));const programs = () => (commands ??= launchersOnPath());const prompt = deps.cloudHome ? createConnectionPrompt({ mcpServers: () => deps.config().mcpServers, mcpAuth, programs,- highlevelConnected: () => deps.highlevel.connected(), composioConnected, movedFrom: () => (deps.dataDir ? movedFrom(deps.dataDir)?.computer ?? null : null) }, deps.cloudHome.publicOrigin) : null;+ composioConnected, movedFrom: () => (deps.dataDir ? movedFrom(deps.dataDir)?.computer ?? null : null) }, deps.cloudHome.publicOrigin) : null;const stayed = deps.cloudHome && deps.dataDir && deps.stayedNotices ? createStayedNotices({ ...deps.stayedNotices, origin: deps.cloudHome.publicOrigin, file: join(deps.dataDir, "connectors-stayed-told.json"), servers: () => deps.config().mcpServers, programs, mailConnected: () => (deps.email?.accounts().length ?? 0) > 0 }) : null;const connections = async () => {const cfg = deps.config();- return listConnections({ config: cfg, mcpAuth, composio: await composioIdentity(cfg).catch(() => null), highlevel: () => deps.highlevel.store.get(), email: () => deps.email?.accounts() ?? [] });+ return listConnections({ config: cfg, mcpAuth, composio: await composioIdentity(cfg).catch(() => null), email: () => deps.email?.accounts() ?? [] });};return {@@ -83,7 +81,6 @@ export function createCloudConnectionsHost(deps: CloudConnectionsHostDeps) {if (parsed.server.url !== record.url) return { ok: false, status: 409, error: "This MCP server has another address here." };return { ok: true, outcome: deps.mcpOAuth.adopt(name, parsed.server.url, record, replaces ? (current) => signInDigest(current.tokens) === replaces : undefined) };},- adoptHighLevel: (connection, replaces) => ({ ok: true, outcome: deps.highlevel.adopt(connection, replaces ? (current) => highlevelDigest(current) === replaces : undefined) }),...(deps.email ? { adoptEmail: deps.email.adopt } : {}),holdKeys: (engines) => deps.heldKeys?.hold(engines) ?? false,}),@@ -97,7 +94,7 @@ export function createCloudConnectionsHost(deps: CloudConnectionsHostDeps) {}if (what.kind === "connection-fingerprints") return { ok: true, secrets: connectionFingerprints(what.nonce, sources()) };if (what.kind === "connection-release") {- return releaseConnection(what.id, what.digest, { ...sources(), forgetSignIn: (name) => deps.mcpOAuth.forget(name), forgetHighLevel: () => { deps.highlevel.disconnect(); } });+ return releaseConnection(what.id, what.digest, { ...sources(), forgetSignIn: (name) => deps.mcpOAuth.forget(name) });}return answerConnection(what.id, sources());},diff --git a/server/cloud-connections-prompt.test.ts b/server/cloud-connections-prompt.test.tsindex 272a5276d8..cd5b2fb7ab 100644--- a/server/cloud-connections-prompt.test.ts+++ b/server/cloud-connections-prompt.test.ts@@ -12,13 +12,12 @@ const SERVERS = {off: { type: "http", url: "https://mcp.off.example/mcp", headers: {}, enabled: false },};-function sources(auth: Record<string, McpAuthState> = {}, connected: Record<string, boolean> = {}, highlevel = false): ConnectionPromptSources & { reads: string[][] } {+function sources(auth: Record<string, McpAuthState> = {}, connected: Record<string, boolean> = {}): ConnectionPromptSources & { reads: string[][] } {const reads: string[][] = [];return {reads,mcpServers: () => SERVERS,mcpAuth: (name) => auth[name] ?? "none",- highlevelConnected: () => highlevel,composioConnected: async (slugs) => { reads.push(slugs); return Object.fromEntries(slugs.map((slug) => [slug, connected[slug] === true])); },};}@@ -47,12 +46,11 @@ describe("what a bot on My Cloud is told about connections that need the person"expect(prompt({ mcpServers: ["dodo", "linear", "jira"] })).toBe("");});- it("HighLevel and connected apps assigned to the bot but not connected here, read in the background for the next turn", async () => {+ it("connected apps assigned to the bot but not connected here, read in the background for the next turn", async () => {const source = sources({}, { gmail: false, slack: true });const prompt = createConnectionPrompt(source, ORIGIN);- const bot = { mcpServers: [], connectorTools: { gmail: { tools: "*" as const }, slack: { tools: "*" as const }, highlevel: { tools: "*" as const } } };- expect(prompt(bot)).toBe(" Not connected on My Cloud yet: HighLevel (connect it here: https://omb-u-1.fly.dev/?connect=highlevel)."- + " When a task needs one, say in plain words that it needs the person once on My Cloud and give its link; do not try another way.");+ const bot = { mcpServers: [], connectorTools: { gmail: { tools: "*" as const }, slack: { tools: "*" as const } } };+ expect(prompt(bot)).toBe("");await vi.waitFor(() => expect(source.reads).toEqual([["gmail", "slack"]]));await new Promise((resolve) => setTimeout(resolve, 0));expect(prompt(bot)).toContain(" Assigned to this bot but not connected on My Cloud yet: Gmail. When a task needs one, call COMPOSIO_MANAGE_CONNECTIONS for it,"@@ -74,7 +72,7 @@ describe("what a bot on My Cloud is told about connections that need the person"});it("once its bots moved here, each bot knows what stayed on the computer they came from, and nobody is told before", () => {- const quiet = { mcpServers: () => ({}), mcpAuth: () => "none" as const, highlevelConnected: () => false, composioConnected: async () => ({}) };+ const quiet = { mcpServers: () => ({}), mcpAuth: () => "none" as const, composioConnected: async () => ({}) };expect(createConnectionPrompt({ ...quiet, movedFrom: () => null }, ORIGIN)({})).toBe("");const line = createConnectionPrompt({ ...quiet, movedFrom: () => "MacBook Air" }, ORIGIN)({});expect(line).toContain("You moved to My Cloud from the person's computer MacBook Air");diff --git a/server/cloud-connections-prompt.ts b/server/cloud-connections-prompt.tsindex 202ce5c942..f873beb79e 100644--- a/server/cloud-connections-prompt.ts+++ b/server/cloud-connections-prompt.ts@@ -1,8 +1,7 @@// What a bot on My Cloud is told about the connections it reaches for that need the person, or another computer, read-// from this Cloud's own state on each turn: an MCP server that needs a sign-in here, HighLevel or connected apps-// assigned to the bot but not connected here, an MCP server that runs on the person's computer, and what stayed on the+// from this Cloud's own state on each turn: an MCP server that needs a sign-in here, connected apps assigned to the+// bot but not connected here, an MCP server that runs on the person's computer, and what stayed on the// computer the bots moved here from. So the bot says so in plain words, with the link that connects it.-import { HIGHLEVEL_SLUG } from "../shared/highlevel.ts";import type { ConnectorToolGrant } from "../shared/wire.ts";import { toolkitName } from "./activity.ts";import type { McpAuthState } from "./mcp-oauth.ts";@@ -15,7 +14,6 @@ const SLUG = /^[a-z0-9_][a-z0-9_-]{0,80}$/u;export interface ConnectionPromptSources {mcpServers(): Record<string, unknown> | undefined;mcpAuth(name: string, url: string): McpAuthState;- highlevelConnected(): boolean;/** Which of these connected apps are connected here now. */composioConnected(slugs: string[]): Promise<Record<string, boolean>>;/** The computer the bots moved here from, once a move is done. */@@ -67,8 +65,7 @@ export function createConnectionPrompt(sources: ConnectionPromptSources, origin:}}const granted = bot.composio === false ? [] : Object.keys(bot.connectorTools ?? {});- if (granted.includes(HIGHLEVEL_SLUG) && !sources.highlevelConnected()) toConnect.push(`HighLevel (connect it here: ${link(HIGHLEVEL_SLUG)})`);- const apps = connected(granted.filter((slug) => slug !== HIGHLEVEL_SLUG && SLUG.test(slug))).filter(([, on]) => !on).map(([slug]) => toolkitName(slug.toUpperCase()));+ const apps = connected(granted.filter((slug) => SLUG.test(slug))).filter(([, on]) => !on).map(([slug]) => toolkitName(slug.toUpperCase()));const from = sources.movedFrom?.() ?? null;return [from ? ` You moved to My Cloud from the person's computer ${from}, with everything in OpenMausBot. What lives outside OpenMausBot stayed on ${from}: its other folders and files, passkeys, the person's own browser sessions and apps, Local VM disks and model servers on its home network. When a task needs one, use ${from} if it is lent to My Cloud and online; otherwise say in plain words that it stayed there.` : "",diff --git a/server/cloud-connections.e2e.test.ts b/server/cloud-connections.e2e.test.tsindex bf4605fcda..2a25cc56a1 100644--- a/server/cloud-connections.e2e.test.ts+++ b/server/cloud-connections.e2e.test.ts@@ -1,7 +1,7 @@// A move to the person's own Cloud carries this computer's connections, end to end: this computer's server and a Cloud// home (scripts/testing/cloud-send-fixture.ts), main's own functions between them (electron/cloud-connections.mjs) over// the private port and the owner session, OpenMausBot's connected-apps service with a fake Composio behind it, a fake-// sign-in server for an MCP server's own account, and a fake HighLevel with its relay. Disposable homes; no network.+// sign-in server for an MCP server's own account. Disposable homes; no network.import { createHash, randomBytes } from "node:crypto";import { readFileSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";@@ -10,7 +10,6 @@ import { afterAll, beforeAll, expect, it } from "vitest";import { collectConnections, sendConnections, type ConnectionsLocal, type ConnectionsTarget } from "../electron/cloud-connections.mjs";import { launchCloudSendFixture, type CloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";import { startBrokerFake, type BrokerFake } from "./testing/broker-fake.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, startFakeRelay, type FakeHighLevel, type FakeRelay } from "./testing/fake-highlevel.ts";import { hostTimeout } from "./testing/host-timeout.ts";// Obvious fakes only.@@ -44,8 +43,6 @@ process.stdin.on("data", (chunk) => {});`;let broker: BrokerFake;-let hl: FakeHighLevel;-let relay: FakeRelay;let fx: CloudSendFixture;let signIns: Server;let tokenEndpoint = "";@@ -54,9 +51,7 @@ const refreshes: Array<{ refresh: string; client: string; secret: string }> = []beforeAll(async () => {broker = await startBrokerFake();- hl = await startFakeHighLevel();- relay = await startFakeRelay({ onAccessToken: (token) => hl.tokens.add(token) });- fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, broker, env: { OMB_HIGHLEVEL_RELAY_URL: relay.url, OMB_HIGHLEVEL_API_URL: hl.url } });+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, broker });signIns = createServer((req, res) => {let body = "";req.on("data", (chunk) => { body += chunk; });@@ -74,8 +69,6 @@ beforeAll(async () => {afterAll(async () => {await fx?.close();await broker?.close();- await relay?.close();- await hl?.close();await new Promise((resolve) => signIns?.close(resolve));});@@ -110,15 +103,9 @@ it("moves the MCP servers with their secrets and sign-ins, the keys and the connwriteFileSync(desktopSignIns, JSON.stringify({ servers: { linear: { url: LINEAR_URL, state: "signed-in", clientId: "omb-fixture-client", tokenAuth: "client_secret_post",tokenEndpoint, tokens: { access: ACCESS, refresh: REFRESH, expiresAt: Date.now() - 60_000 } } } }));expect((await local("PATCH", "/api/config", { openrouter: { key: OPENROUTER_KEY } })).status).toBe(200);- // HighLevel, signed in here through its relay: its refresh token rotates, so only one side may ever spend it.- const started = await local("POST", "/api/highlevel/sign-in");- relay.complete([...relay.states.keys()].at(-1)!);- await expect.poll(async () => (await local("GET", `/api/highlevel/sign-in/${started.body.flowId}`)).body.phase, { timeout: 8_000, interval: 200 }).toBe("connected");- const refreshToken = [...relay.refreshTokens][0]!;const collected = await collectConnections(asLocal(fx));- expect(collected.connections.map((item) => item.id)).toEqual(["mcp:dodo", "mcp:docs", "mcp:linear", "mcp:notes", "mcp:easy", "key:openrouter", "composio", "highlevel"]);- expect(collected.connections.find((item) => item.id === "highlevel")).toMatchObject({ signIn: true });+ expect(collected.connections.map((item) => item.id)).toEqual(["mcp:dodo", "mcp:docs", "mcp:linear", "mcp:notes", "mcp:easy", "key:openrouter", "composio"]);expect(collected.connections.find((item) => item.id === "mcp:linear")).toMatchObject({ signIn: true });expect(collected.connections.find((item) => item.id === "mcp:notes")).toMatchObject({ runsHere: true });expect(collected.computer.label).toBeTruthy();@@ -126,11 +113,11 @@ it("moves the MCP servers with their secrets and sign-ins, the keys and the connconst progress: string[] = [];const result = await sendConnections(collected, asTarget(fx), { local: asLocal(fx), onProgress: ({ label }) => progress.push(label) });expect(result.failed).toEqual([]);- expect(result.moved.map((item) => item.id)).toEqual(["key:openrouter", "mcp:dodo", "mcp:docs", "mcp:linear", "highlevel", "composio"]);+ expect(result.moved.map((item) => item.id)).toEqual(["key:openrouter", "mcp:dodo", "mcp:docs", "mcp:linear", "composio"]);expect(result.runsHere).toEqual([{ id: "mcp:notes", label: "notes" }, { id: "mcp:easy", label: "easy" }]);expect(result.kept).toEqual([]);expect(result.release).toEqual([]);- expect(progress).toEqual(["OpenRouter", "dodo", "docs", "linear", "notes", "easy", "HighLevel", "Connected apps"]);+ expect(progress).toEqual(["OpenRouter", "dodo", "docs", "linear", "notes", "easy", "Connected apps"]);// The MCP servers arrived with their secrets, on, and the command-line one works there with its key.const servers = (await onCloud("GET", "/api/mcp/servers")).body.servers as Array<Record<string, unknown>>;@@ -154,13 +141,6 @@ it("moves the MCP servers with their secrets and sign-ins, the keys and the connexpect(JSON.parse(readFileSync(desktopSignIns, "utf8")).servers.linear).toBeUndefined();expect((await local("GET", "/api/mcp/servers")).body.servers.find((server: { name: string }) => server.name === "linear").auth).toBeUndefined();- // HighLevel moved with its sign-in, which only My Cloud holds now; nothing spent its refresh token on the way.- expect((await onCloud("GET", "/api/highlevel")).body).toMatchObject({ state: "connected", kind: "oauth", location: { id: FAKE_LOCATION_ID } });- expect((await local("GET", "/api/highlevel")).body).toEqual({ state: "signed-out" });- expect(relay.refreshes).toBe(0);- expect(relay.refreshTokens.has(refreshToken)).toBe(true);- SECRETS.push(refreshToken, ...relay.issued);-// The key arrived, and so did its engine, before anything that follows it.expect((await onCloud("GET", "/api/config")).body.openrouter).toMatchObject({ configured: true });expect((await onCloud("GET", "/api/cloud-connections")).body.engines).toContain("openrouter");diff --git a/server/cloud-connections.test.ts b/server/cloud-connections.test.tsindex 28e235b2d6..cae0ce049c 100644--- a/server/cloud-connections.test.ts+++ b/server/cloud-connections.test.ts@@ -5,7 +5,6 @@ import { afterEach, describe, expect, it } from "vitest";import { addressHere, answerConnection, KEY_PROVIDERS, launcherOf, listConnections, releaseConnection, runsHere, signInDigest } from "./cloud-connections.ts";import type { AppConfig } from "./config.ts";-import type { HighLevelConnection } from "./highlevel/store.ts";import type { McpOAuthRecord } from "./mcp-oauth-store.ts";import type { StoredMcpServer } from "./mcp-registry.ts";import { removeTempDir } from "./testing/cleanup.ts";@@ -18,7 +17,6 @@ const stdio = (command: string, args: string[] = [], env: Record<string, string>const remote = (url: string, extra: Partial<StoredMcpServer> = {}): StoredMcpServer => ({ type: "http", url, headers: {}, enabled: true, ...extra } as StoredMcpServer);const record = (tokens: McpOAuthRecord["tokens"], state: McpOAuthRecord["state"] = "signed-in"): McpOAuthRecord =>({ url: "https://mcp.linear.app/sse", state, clientId: "client", tokenEndpoint: "https://linear.app/token", ...(tokens ? { tokens } : {}) });-const HIGHLEVEL: HighLevelConnection = { kind: "oauth", accessToken: "hl-access", refreshToken: "hl-refresh", expiresAt: 5, locationId: "loc_1", scopes: "", connectedAt: 1, state: "signed-in" };describe("which MCP servers need this computer", () => {it("a program by path, a file or folder of this computer, or an address only it reaches", () => {@@ -47,7 +45,7 @@ describe("which MCP servers need this computer", () => {describe("what GET /api/cloud-connections names", () => {const sources = (config: AppConfig, extra: Partial<Parameters<typeof listConnections>[0]> = {}) => ({- config, mcpAuth: () => "none" as const, composio: null, highlevel: () => null, ...extra,+ config, mcpAuth: () => "none" as const, composio: null, ...extra,});it("each connection by name, with what moves it, and never a secret", () => {@@ -62,7 +60,7 @@ describe("what GET /api/cloud-connections names", () => {} as unknown as AppConfig;const listed = listConnections(sources(config, { mcpAuth: (name) => (name === "linear" ? "signed-in" : "none"),composio: { mode: "managed", account: "managed:abc", installationId: "11111111-2222-4333-8444-555555555555", shared: false },- highlevel: () => HIGHLEVEL }));+ email: () => [{ address: "[email protected]" }] }));expect(listed).toEqual([{ id: "mcp:dodo", kind: "mcp", label: "dodo", detail: "npx dodopayments-mcp", launcher: "npx" },{ id: "mcp:linear", kind: "mcp", label: "linear", detail: "mcp.linear.app", signIn: true },@@ -70,11 +68,10 @@ describe("what GET /api/cloud-connections names", () => {{ id: "key:openrouter", kind: "key", label: "OpenRouter", for: ["openrouter"] },{ id: "key:anthropic", kind: "key", label: "Anthropic", for: ["claudeApi"] },{ id: "composio", kind: "composio", label: "Connected apps", mode: "managed", account: "managed:abc", installationId: "11111111-2222-4333-8444-555555555555" },- { id: "highlevel", kind: "highlevel", label: "HighLevel", signIn: true },+ { id: "email", kind: "email", label: "Email" },]);const text = JSON.stringify(listed);- for (const secret of ["dodo_live_fake", "sk-or-fake", "sk-ant-fake", "sk_live_fake", "linear_fake", "voice-fake", "hl-access", "hl-refresh"]) expect(text).not.toContain(secret);- expect(listConnections(sources({} as AppConfig, { highlevel: () => ({ ...HIGHLEVEL, kind: "token", refreshToken: undefined }) }))).toEqual([{ id: "highlevel", kind: "highlevel", label: "HighLevel" }]);+ for (const secret of ["dodo_live_fake", "sk-or-fake", "sk-ant-fake", "sk_live_fake", "linear_fake", "voice-fake"]) expect(text).not.toContain(secret);});it("an Anthropic key serves Claude (API key) alone there, never Claude bots that sign in with an account", () => {@@ -91,33 +88,29 @@ describe("what the private port hands over, and lets go of", () => {const tokens = { access: "access-1", refresh: "refresh-1", expiresAt: 10 };it("a server with its secrets and its sign-in, and the digest of that sign-in", () => {- const answer = answerConnection("mcp:linear", { config, mcpSignIn: () => record(tokens), highlevel: () => null });+ const answer = answerConnection("mcp:linear", { config, mcpSignIn: () => record(tokens) });expect(answer).toEqual({ ok: true, digest: signInDigest(tokens), connection: { mcp: { name: "linear", signIn: record(tokens),server: { type: "http", url: "https://mcp.linear.app/sse", headers: { Authorization: "Bearer h" }, oauth: { clientId: "client", clientSecret: "app-secret" }, enabled: true } } } });// A sign-in that needs signing in again, or a server that runs here, hands over no sign-in.- expect(answerConnection("mcp:linear", { config, mcpSignIn: () => record(undefined, "needs-sign-in"), highlevel: () => null })).not.toHaveProperty("digest");- const here = answerConnection("mcp:notes", { config, mcpSignIn: () => ({ ...record(tokens), url: "http://localhost:9/mcp" }), highlevel: () => null });+ expect(answerConnection("mcp:linear", { config, mcpSignIn: () => record(undefined, "needs-sign-in") })).not.toHaveProperty("digest");+ const here = answerConnection("mcp:notes", { config, mcpSignIn: () => ({ ...record(tokens), url: "http://localhost:9/mcp" }) });expect(here).toMatchObject({ ok: true, connection: { mcp: { name: "notes" } } });expect(here).not.toHaveProperty("digest");expect(JSON.stringify(here)).not.toContain("refresh-1");});- it("a key, the person's own Composio project and HighLevel, each as My Cloud's routes take them", () => {- const sources = { config, mcpSignIn: () => undefined, highlevel: () => HIGHLEVEL };+ it("a key and the person's own Composio project, each as My Cloud's routes take them", () => {+ const sources = { config, mcpSignIn: () => undefined };expect(answerConnection("key:openrouter", sources)).toEqual({ ok: true, connection: { config: { openrouter: { key: "sk-or-fake" } } } });expect(answerConnection("key:openai", sources)).toEqual({ ok: false, error: "This key is no longer saved on this computer." });expect(answerConnection("composio", sources)).toEqual({ ok: true, connection: { composio: { apiKey: "ck_fake", userId: "u_1" } } });- expect(answerConnection("highlevel", sources)).toMatchObject({ ok: true, connection: { highlevel: HIGHLEVEL }, digest: expect.stringMatching(/^[0-9a-f]{64}$/u) });- expect(answerConnection("highlevel", { ...sources, highlevel: () => ({ ...HIGHLEVEL, kind: "token" }) })).not.toHaveProperty("digest");expect(answerConnection("mcp:gone", sources)).toEqual({ ok: false, error: "This MCP server is no longer on this computer." });});it("lets go of a sign-in only while it is the one My Cloud took: one that refreshed since is said to have changed", () => {const forgot: string[] = [];let current = record(tokens);- let highlevel: HighLevelConnection | null = HIGHLEVEL;- const sources = { config, mcpSignIn: () => current, highlevel: () => highlevel,- forgetSignIn: (name: string) => { forgot.push(name); }, forgetHighLevel: () => { forgot.push("highlevel"); highlevel = null; } };+ const sources = { config, mcpSignIn: () => current, forgetSignIn: (name: string) => { forgot.push(name); } };const moved = signInDigest(tokens);current = record({ ...tokens, access: "access-2", refresh: "refresh-2" });expect(releaseConnection("mcp:linear", moved, sources)).toEqual({ ok: true, release: { changed: true } });@@ -125,10 +118,6 @@ describe("what the private port hands over, and lets go of", () => {current = record(tokens);expect(releaseConnection("mcp:linear", moved, sources)).toEqual({ ok: true, release: { released: true } });expect(forgot).toEqual(["linear"]);- const highlevelDigest = (answerConnection("highlevel", sources) as { digest: string }).digest;- expect(releaseConnection("highlevel", "0".repeat(64), sources)).toEqual({ ok: true, release: { changed: true } });- expect(releaseConnection("highlevel", highlevelDigest, sources)).toEqual({ ok: true, release: { released: true } });- expect(forgot).toEqual(["linear", "highlevel"]);expect(releaseConnection("key:openrouter", moved, sources)).toEqual({ ok: false, error: "Only a sign-in that moved is let go of." });});});diff --git a/server/cloud-connections.ts b/server/cloud-connections.tsindex ff982d91da..e72eb82755 100644--- a/server/cloud-connections.ts+++ b/server/cloud-connections.ts@@ -1,8 +1,8 @@// This computer's connections, as they move once to the person's own Cloud: MCP servers with their secrets and-// sign-ins, the AI keys bots run on, the connected-apps account and HighLevel. GET /api/cloud-connections names each,+// sign-ins, the AI keys bots run on, the connected-apps account and mailboxes. GET /api/cloud-connections names each,// never a secret; the secrets reach the desktop's main process only over its private port (login-handoff.ts), which-// sends them only to the person's own Cloud. A sign-in that refreshes itself (an MCP server's own account, HighLevel's)-// moves: once My Cloud has it, this computer forgets its copy, so the two never spend one refresh token.+// sends them only to the person's own Cloud. A sign-in that refreshes itself (an MCP server's own account) moves: once+// My Cloud has it, this computer forgets its copy, so the two never spend one refresh token.import { createHash } from "node:crypto";import { existsSync } from "node:fs";import { basename, isAbsolute, join } from "node:path";@@ -12,16 +12,15 @@ import { fingerprint } from "./cloud-send-verify.ts";import type { ComposioIdentity } from "./composio-share.ts";import type { AppConfig } from "./config.ts";import type { EmailAccount } from "./email/store.ts";-import type { HighLevelConnection } from "./highlevel/store.ts";import type { McpOAuthRecord } from "./mcp-oauth-store.ts";import type { McpAuthState } from "./mcp-oauth.ts";import { isRemoteMcpServer, parseStoredMcpServer, type StoredMcpServer } from "./mcp-registry.ts";-export type ConnectionKind = "mcp" | "key" | "composio" | "highlevel" | "email";+export type ConnectionKind = "mcp" | "key" | "composio" | "email";/** One connection, by name only. */export interface ConnectionListing {- /** "mcp:<name>", "key:<provider>", "composio", "highlevel" or "email". */+ /** "mcp:<name>", "key:<provider>", "composio" or "email". */id: string;kind: ConnectionKind;label: string;@@ -33,8 +32,7 @@ export interface ConnectionListing {launcher?: string;/** A key: the engines (instance ids) it runs. */for?: string[];- /** A sign-in that refreshes itself (an MCP server's own account, HighLevel's): it moves, and this computer then- * forgets it. */+ /** A sign-in that refreshes itself (an MCP server's own account): it moves, and this computer then forgets it. */signIn?: true;/** Connected apps: OpenMausBot's service or the person's own Composio project, the account in a digest equal on two* servers exactly when they reach the same apps, and the service's installation a code is minted for. */@@ -142,7 +140,6 @@ export interface ConnectionSources {config: AppConfig;mcpAuth(name: string, url: string): McpAuthState;composio: ComposioIdentity | null;- highlevel(): HighLevelConnection | null;/** The person's mailboxes, by address only here. */email?(): ReadonlyArray<{ address: string }>;}@@ -168,8 +165,6 @@ export function listConnections(sources: ConnectionSources): ConnectionListing[]items.push({ id: "composio", kind: "composio", label: "Connected apps", mode: account.mode, account: account.account,...(account.installationId ? { installationId: account.installationId } : {}) });}- const highlevel = sources.highlevel();- if (highlevel) items.push({ id: "highlevel", kind: "highlevel", label: "HighLevel", ...(highlevel.kind === "oauth" ? { signIn: true as const } : {}) });if (sources.email?.().length) items.push({ id: "email", kind: "email", label: "Email" });return items;}@@ -179,14 +174,12 @@ export type ConnectionHandoff =| { mcp: { name: string; server: StoredMcpServer; signIn?: McpOAuthRecord } }| { config: Partial<AppConfig> }| { composio: { apiKey: string; userId: string } }- | { highlevel: HighLevelConnection }| { email: readonly EmailAccount[] };export interface HandoffSources {config: AppConfig;/** The sign-in kept for a server reached by URL, with its tokens. */mcpSignIn(name: string, url: string): McpOAuthRecord | undefined;- highlevel(): HighLevelConnection | null;/** The person's mailboxes with their passwords, which go only to the owner's session on their own Cloud. */email?(): readonly EmailAccount[];}@@ -229,11 +222,6 @@ export function answerConnection(id: string, sources: HandoffSources):const apiKey = cfg.composio?.apiKey?.trim(), userId = cfg.composio?.userId;return apiKey && userId ? { ok: true, connection: { composio: { apiKey, userId } } } : { ok: false, error: "Connected apps here use OpenMausBot's service." };}- if (id === "highlevel") {- const connection = sources.highlevel();- if (!connection) return { ok: false, error: "HighLevel is not connected on this computer." };- return { ok: true, connection: { highlevel: connection }, ...(connection.kind === "oauth" ? { digest: highlevelDigest(connection) } : {}) };- }if (id === "email") {const accounts = sources.email?.() ?? [];return accounts.length ? { ok: true, connection: { email: accounts } } : { ok: false, error: "No mailbox is connected on this computer." };@@ -241,13 +229,9 @@ export function answerConnection(id: string, sources: HandoffSources):return { ok: false, error: "This connection is not on this computer." };}-export const highlevelDigest = (connection: HighLevelConnection) =>- signInDigest({ accessToken: connection.accessToken, refreshToken: connection.refreshToken ?? null, expiresAt: connection.expiresAt ?? null });-export interface ReleaseSources extends HandoffSources {/** Forgets a server's sign-in here, without signing it out: My Cloud uses it now. */forgetSignIn(name: string): void;- forgetHighLevel(): void;}/** This computer lets go of a sign-in that moved to My Cloud, unless it refreshed since it was read (`changed`): then@@ -263,20 +247,13 @@ export function releaseConnection(id: string, digest: string, sources: ReleaseSosources.forgetSignIn(mcp[1]!);return { ok: true, release: { released: true } };}- if (id === "highlevel") {- const connection = sources.highlevel();- if (connection?.kind !== "oauth") return { ok: true, release: { released: true } };- if (highlevelDigest(connection) !== digest) return { ok: true, release: { changed: true } };- sources.forgetHighLevel();- return { ok: true, release: { released: true } };- }return { ok: false, error: "Only a sign-in that moved is let go of." };}/** Each connection's own secrets in a fingerprint under `nonce` (cloud-send-verify.ts), by the id it moves under. A* sign-in that refreshes itself is left out: it moves once and this computer lets go of it, so the two sides never* hold it at once. */-export function connectionFingerprints(nonce: string, sources: Pick<HandoffSources, "config" | "highlevel">): Record<string, string> {+export function connectionFingerprints(nonce: string, sources: Pick<HandoffSources, "config">): Record<string, string> {const cfg = sources.config;const out: Record<string, string> = {};for (const [name, raw] of Object.entries(cfg.mcpServers ?? {})) {@@ -288,8 +265,6 @@ export function connectionFingerprints(nonce: string, sources: Pick<HandoffSourcfor (const { provider, fragment } of movingKeys(cfg)) out[`key:${provider.id}`] = fingerprint(nonce, fragment);const apiKey = cfg.composio?.apiKey?.trim(), userId = cfg.composio?.userId;if (apiKey && userId) out.composio = fingerprint(nonce, { apiKey, userId });- const highlevel = sources.highlevel();- if (highlevel?.kind === "token") out.highlevel = fingerprint(nonce, { token: highlevel.accessToken, locationId: highlevel.locationId });return out;}diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex 3387c080e2..1331bc5285 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -37,7 +37,7 @@ const SERVER_ENV_NAMES = new Set(["AGENT_BROWSER_EXECUTABLE_PATH", "OMB_STATIC_DIR", "OMB_DATA_DIR", "OMB_DUCKDB_DIR","OMB_CLOUD_ROLE", "OMB_CLOUD_MACHINE_ID", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_IMAGE", "OMB_PUBLIC_URL", "OMB_WEBHOOK_PUBLIC_URL","OMB_CLOUD_TEAM_ID", "OMB_CLOUD_TEAM_NAME", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_VOICE_URL", "OMB_CLOUD_DECIDER_URL", "OMB_CLOUD_AI_URL", "OMB_CLOUD_X_URL", "OMB_TTS_DEFAULT_VOICE",- "OMB_HIGHLEVEL_RELAY_URL", "OMB_COMPOSIO_BROKER_URL",+ "OMB_COMPOSIO_BROKER_URL",// The bot box switch (server/bot-box/detect.ts): the Admin may turn a home's box off for support."OMB_BOT_BOX",// An ended Cloud started only for its owner's export: the server runs frozen (server/move-freeze.ts).diff --git a/server/cloud-send-manifest.ts b/server/cloud-send-manifest.tsindex 916cf29623..643999afc0 100644--- a/server/cloud-send-manifest.ts+++ b/server/cloud-send-manifest.ts@@ -29,7 +29,7 @@ export interface CloudSendManifest {forgotten: string[];teams: Array<{ section: string; context: string[] | null; memory: string[] }>;rooms: Array<{ id: string; name: string; members: string[]; threads: string[] }>;- /** "mcp:<name>", "key:<provider>", "composio", "highlevel" or "email". */+ /** "mcp:<name>", "key:<provider>", "composio" or "email". */connections: string[];conversations: ManifestConversation[];/** The stored attachments the conversations' rows name. */diff --git a/server/cloud-send-move.e2e.test.ts b/server/cloud-send-move.e2e.test.tsindex 1660f11c35..ed9117d94b 100644--- a/server/cloud-send-move.e2e.test.ts+++ b/server/cloud-send-move.e2e.test.ts@@ -1,7 +1,7 @@// The one-time move to the person's own Cloud, end to end: this computer's server and a Cloud home// (scripts/testing/cloud-send-fixture.ts) with main's own wiring between them, the move run and checked as main runs and-// checks it, the connected-apps service with a fake Composio behind it, a fake sign-in server for an MCP server's own-// account and a fake HighLevel. Disposable homes; no network.+// checks it, the connected-apps service with a fake Composio behind it and a fake sign-in server for an MCP server's+// own account. Disposable homes; no network.import { randomBytes, randomUUID } from "node:crypto";import { spawn, type ChildProcess } from "node:child_process";import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";@@ -14,7 +14,6 @@ import { createComputerSharing } from "../electron/computer-sharing.mjs";import { itemKey } from "../electron/cloud-send-parts.mjs";import { launchCloudSendFixture, type CloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";import { startBrokerFake, type BrokerFake } from "./testing/broker-fake.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, startFakeRelay, type FakeHighLevel, type FakeRelay } from "./testing/fake-highlevel.ts";import { hostTimeout } from "./testing/host-timeout.ts";// Obvious fakes only.@@ -25,14 +24,11 @@ const DODO_KEY = `dodo_test_fake_${hex(12)}`;const DOCS_TOKEN = `fake-docs-token-${hex(8)}`;const CLIENT_SECRET = `fake-client-secret-${hex(8)}`;const OPENROUTER_KEY = `sk-or-v1-fake${hex(16)}`;-const PIT = `pit-fake-move-${hex(8)}`;const ACCESS = `fake-access-${hex(8)}`, REFRESH = `fake-refresh-${hex(8)}`;-const SECRETS = [TOKEN, PASSWORD, DODO_KEY, DOCS_TOKEN, CLIENT_SECRET, OPENROUTER_KEY, PIT, ACCESS, REFRESH];+const SECRETS = [TOKEN, PASSWORD, DODO_KEY, DOCS_TOKEN, CLIENT_SECRET, OPENROUTER_KEY, ACCESS, REFRESH];const LINEAR_URL = "https://mcp.linear.example.test/mcp";let broker: BrokerFake;-let hl: FakeHighLevel;-let relay: FakeRelay;let fx: CloudSendFixture;let signIns: Server;let tokenEndpoint = "";@@ -47,9 +43,7 @@ beforeAll(async () => {mkdirSync(join(scratch, "turns"));writeFileSync(release, "");broker = await startBrokerFake();- hl = await startFakeHighLevel();- relay = await startFakeRelay({ onAccessToken: (token) => hl.tokens.add(token) });- fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, broker, toolCalls: 36, env: { OMB_HIGHLEVEL_RELAY_URL: relay.url, OMB_HIGHLEVEL_API_URL: hl.url },+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, broker, toolCalls: 36,cloudEngine: `process.env.FAKE_CLAUDE_MODE = "hang"; process.env.FAKE_CLAUDE_RELEASE = ${JSON.stringify(release)};if (process.argv[2] !== "--version") { process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(join(scratch, "turns"))} + "/" + process.pid + ".json"; process.env.FAKE_CLAUDE_TEXT_DUMP = ${JSON.stringify(join(scratch, "one-shot.json"))}; }` });signIns = createServer((req, res) => {@@ -69,8 +63,6 @@ afterAll(async () => {for (const proxy of proxies) proxy.kill();await fx?.close();await broker?.close();- await relay?.close();- await hl?.close();await new Promise((resolve) => signIns?.close(resolve));if (scratch) rmSync(scratch, { recursive: true, force: true });});@@ -202,8 +194,8 @@ it("a move carries everything, apps and keys first, and its check finds every roexpect((await local("POST", "/api/logins", { site: "accounts.example.test", username: "alice", password: PASSWORD, totp: "JBSWY3DPEHPK3PXP", bots: [ember.id] })).status).toBe(201);expect((await local("POST", "/api/logins/1password", { token: TOKEN })).status).toBe(200);- // Apps and keys: an MCP server's key and another's header token, a sign-in of its own, an AI key, HighLevel by its token,- // and the connected-apps account.+ // Apps and keys: an MCP server's key and another's header token, a sign-in of its own, an AI key and the connected-apps+ // account.for (const server of [{ name: "dodo", command: "node", args: ["-e", "process.stdin.resume()"], env: { DODO_PAYMENTS_API_KEY: DODO_KEY } },{ name: "docs", type: "http", url: "https://mcp.docs.example.test/mcp", headers: { Authorization: `Bearer ${DOCS_TOKEN}` } },@@ -216,8 +208,6 @@ it("a move carries everything, apps and keys first, and its check finds every rowriteFileSync(desktopSignIns, JSON.stringify({ servers: { linear: { url: LINEAR_URL, state: "signed-in", clientId: "omb-fixture-client", tokenAuth: "client_secret_post",tokenEndpoint, tokens: { access: ACCESS, refresh: REFRESH, expiresAt: Date.now() + 3_600_000 } } } }));expect((await local("PATCH", "/api/config", { openrouter: { key: OPENROUTER_KEY } })).status).toBe(200);- hl.tokens.add(PIT);- expect((await local("POST", "/api/highlevel/token", { token: PIT, locationId: FAKE_LOCATION_ID })).status).toBe(200);const gmail = broker.account(fx.desktopInstallation!.userId, "gmail");// The first pass: everything but the sign-in that refreshes itself, which stays here while this computer is home.@@ -251,7 +241,7 @@ it("a move carries everything, apps and keys first, and its check finds every roexpect(report.attachments).toEqual([]);expect(report.secrets.differs).toEqual([]);expect(report.secrets.missing).toEqual([]);- expect(report.secrets.equal).toEqual(expect.arrayContaining([itemKey.login("example.test", "alice"), "1password", "key:openrouter", "mcp:dodo", "mcp:docs", "mcp:linear", "highlevel"]));+ expect(report.secrets.equal).toEqual(expect.arrayContaining([itemKey.login("example.test", "alice"), "1password", "key:openrouter", "mcp:dodo", "mcp:docs", "mcp:linear"]));// Read back the way each side's chat view and bot read it.const [here, there] = [await history(local, archie.threadId), await history(onCloud, archie.threadId)];diff --git a/server/cloud-send-settings.test.ts b/server/cloud-send-settings.test.tsindex 3e68c499cc..bbe4147e1c 100644--- a/server/cloud-send-settings.test.ts+++ b/server/cloud-send-settings.test.ts@@ -55,9 +55,9 @@ describe("a model on this computer's own network", () => {it("stays here: its key is neither listed for a move, handed over, nor fingerprinted", () => {const config = { openaiCompat: { key: "sk-home", url: "http://192.168.1.20:11434/v1" }, openrouter: { key: "sk-or" }, groq: { key: "gk", url: "http://localhost:9000" },xai: { key: "xk", url: "https://api.x.ai/v1" } } as unknown as AppConfig;- const listed = listConnections({ config, mcpAuth: () => "signed-out" as never, composio: null, highlevel: () => null }).map((item) => item.id);+ const listed = listConnections({ config, mcpAuth: () => "signed-out" as never, composio: null }).map((item) => item.id);expect(listed).toEqual(["key:openrouter", "key:xai"]);- expect(Object.keys(connectionFingerprints("n".repeat(43), { config, highlevel: () => null }))).toEqual(["key:openrouter", "key:xai"]);- expect(answerConnection("key:openaiCompat", { config, mcpSignIn: () => undefined, highlevel: () => null })).toEqual({ ok: false, error: "This key's model is on this computer's own network, so it stays here." });+ expect(Object.keys(connectionFingerprints("n".repeat(43), { config }))).toEqual(["key:openrouter", "key:xai"]);+ expect(answerConnection("key:openaiCompat", { config, mcpSignIn: () => undefined })).toEqual({ ok: false, error: "This key's model is on this computer's own network, so it stays here." });});});diff --git a/server/cloud-send-verify.test.ts b/server/cloud-send-verify.test.tsindex cd5b2a50f5..04f8bf3555 100644--- a/server/cloud-send-verify.test.ts+++ b/server/cloud-send-verify.test.ts@@ -36,16 +36,14 @@ describe("credential fingerprints a move checks by", () => {expect(JSON.stringify(loginFingerprints(NONCE, here))).not.toContain(PASSWORD);});- it("cover keys, MCP servers' own secrets, the person's own connected-apps project and a HighLevel token, never a sign-in that moves once", () => {+ it("cover keys, MCP servers' own secrets and the person's own connected-apps project, never a sign-in that moves once", () => {const config = { openrouter: { key: KEY }, composio: { apiKey: "fake-composio-key", userId: "u1" },mcpServers: { docs: { type: "http", url: "https://mcp.docs.example.test/mcp", headers: { Authorization: "Bearer fake-docs" }, enabled: true },dodo: { command: "node", args: ["server.js"], env: { DODO_KEY: "fake-dodo" }, enabled: true } } } as unknown as AppConfig;- const token = { kind: "token", accessToken: "fake-pit", locationId: "loc1", scopes: "", connectedAt: 1, state: "signed-in" } as const;- const seen = connectionFingerprints(NONCE, { config, highlevel: () => token });- expect(Object.keys(seen).sort()).toEqual(["composio", "highlevel", "key:openrouter", "mcp:docs", "mcp:dodo"]);+ const seen = connectionFingerprints(NONCE, { config });+ expect(Object.keys(seen).sort()).toEqual(["composio", "key:openrouter", "mcp:docs", "mcp:dodo"]);expect(seen["key:openrouter"]).toBe(fingerprint(NONCE, { openrouter: { key: KEY } }));- expect(connectionFingerprints(NONCE, { config, highlevel: () => ({ ...token, kind: "oauth" as const, refreshToken: "fake-refresh" }) })).not.toHaveProperty("highlevel");- const changed = connectionFingerprints(NONCE, { config: { ...config, mcpServers: { ...config.mcpServers, docs: { ...(config.mcpServers!.docs as object), headers: { Authorization: "Bearer other" } } } } as AppConfig, highlevel: () => token });+ const changed = connectionFingerprints(NONCE, { config: { ...config, mcpServers: { ...config.mcpServers, docs: { ...(config.mcpServers!.docs as object), headers: { Authorization: "Bearer other" } } } } as AppConfig });expect(changed["mcp:docs"]).not.toBe(seen["mcp:docs"]);expect(JSON.stringify(seen)).not.toMatch(/fake-|sk-or/u);});diff --git a/server/cloud-team-policy.test.ts b/server/cloud-team-policy.test.tsindex b0e6d377a6..dbf0fe3e38 100644--- a/server/cloud-team-policy.test.ts+++ b/server/cloud-team-policy.test.ts@@ -243,7 +243,7 @@ describe("the managed policy with a team's rules", () => {expect(managed.appsCallRefusal([{ slug: "BLAND_AI_CALL" }], ["bland_ai"])).toMatch(/Bland Ai/);expect(managed.appsCallRefusal([{ slug: "BLAND_CALL" }], ["bland_ai"])).toBeUndefined();expect(managed.appsConnectRefusal(["gmail", "notion"])).toMatch(/Notion/);- expect(managed.appAllowed("highlevel")).toBe(false);+ expect(managed.appAllowed("email")).toBe(false);managed.close();const open = managedWith({ allowedEngines: ["codex"] });expect(open.appsCallRefusal([{ slug: "SLACK_POST" }, { slug: "COMPOSIO_PROXY_EXECUTE" }])).toBeUndefined();diff --git a/server/cloud-team.e2e.test.ts b/server/cloud-team.e2e.test.tsindex 3124cebe62..2fd7fb8f3d 100644--- a/server/cloud-team.e2e.test.ts+++ b/server/cloud-team.e2e.test.ts@@ -280,7 +280,7 @@ it("a person's own connected apps cannot be brought into the team, and the team'const refused = await team.as(owner, "POST", "/api/cloud-connections/connected-apps", { share: "share-code-from-a-laptop", apps: ["gmail"] });expect(refused.status).toBe(403);expect(refused.body.error).toBe("Personal connections never enter Acme. Ask an admin to connect these apps for Acme.");- expect((await team.as(owner, "PUT", "/api/cloud-connections/highlevel", { locationId: "loc", accessToken: "a", refreshToken: "r", expiresAt: 1 })).body.error).toContain("Personal connections never enter Acme");+ expect((await team.as(owner, "PUT", "/api/cloud-connections/email", { accounts: [{ address: "[email protected]" }] })).body.error).toContain("Personal connections never enter Acme");// Nor anything of a computer's one-time move: every send and move route answers the same plain line.for (const [method, route] of [["GET", "/api/cloud-send/manifest"], ["POST", "/api/cloud-send/chats"], ["GET", "/api/cloud-send?move=1"]] as const) {const moved = await team.as(owner, method, route, method === "POST" ? { conversations: [] } : undefined);diff --git a/server/cloud-team.ts b/server/cloud-team.tsindex 7dcf25a8a4..0b1f7411c5 100644--- a/server/cloud-team.ts+++ b/server/cloud-team.ts@@ -61,7 +61,7 @@ export function parseMemberClaim(body: Record<string, unknown>, team: CloudTeam)return { ok: true, member: { email: email.trim().toLowerCase(), role } };}-/** A member's own connection (a Composio share, an MCP sign-in, HighLevel) has no path into a team. */+/** A member's own connection (a Composio share, an MCP sign-in, a mailbox) has no path into a team. */export function personalConnectionRefusal(team: Pick<CloudTeam, "name">, what = "it"): string {return `Personal connections never enter ${team.name}. Ask an admin to connect ${what} for ${team.name}.`;}diff --git a/server/contracts.ts b/server/contracts.tsindex 9af44a8160..82756bd679 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -191,8 +191,6 @@ export interface SendTurnInput {browser?: { command: string; args: string[]; env: Record<string, string> };/** The Data tools' MCP proxy: DuckDB on this bot's own database. */data?: { command: string; args: string[]; env: Record<string, string> };- /** The HighLevel CRM tools' MCP proxy: the harness holds the tokens and the per-bot verdict. */- highlevel?: { command: string; args: string[]; env: Record<string, string> };/** The Email tools' MCP proxy: the harness holds the passwords and the per-bot verdict. */email?: { command: string; args: string[]; env: Record<string, string> };/** The paired phone's app tools' MCP proxy: the harness holds the jobs and the per-bot verdict. */@@ -262,8 +260,8 @@ export interface ProviderAdapter {browserMcp?: boolean;/** The driver can mount the Data tools MCP. */dataMcp?: boolean;- /** The driver can mount the HighLevel CRM tools MCP, and the Email tools the same way. */- highlevelMcp?: boolean;+ /** The driver can mount the Email tools MCP. */+ emailMcp?: boolean;/** The driver can mount the phone apps MCP. */deviceMcp?: boolean;/** The engine accepts images in the prompt (gates composer paste). */diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 9f4b8b6801..8d8a209ec5 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -1687,7 +1687,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>computerMcp: true,composioMcp: true,browserMcp: true,- dataMcp: true, highlevelMcp: true, deviceMcp: true,+ dataMcp: true, emailMcp: true, deviceMcp: true,images: support.images !== false,nativeImageInput: support.images === true,effortLevels: support.effortLevels,diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.tsindex 631aa23f4d..a1f41d2460 100644--- a/server/drivers/acp/grok.ts+++ b/server/drivers/acp/grok.ts@@ -428,7 +428,7 @@ const support: AcpSupport = {const available = new Set([...(turn.integrations?.agents ? ["agents"] : []), ...(turn.integrations?.composio ? ["composio"] : []), ...(turn.integrations?.composioOwn ? [OWN_APPS_SERVER] : []),...(turn.integrations?.browser ? ["browser"] : []), ...(turn.integrations?.localComputer ? ["computer"] : []),- ...(turn.integrations?.data ? ["data"] : []), ...(turn.integrations?.highlevel ? ["highlevel"] : []), ...(turn.integrations?.email ? ["email"] : []), ...(turn.integrations?.device ? ["device"] : []),+ ...(turn.integrations?.data ? ["data"] : []), ...(turn.integrations?.email ? ["email"] : []), ...(turn.integrations?.device ? ["device"] : []),...Object.keys(turn.integrations?.custom ?? {}),].filter((name) => canUseMcpServer(turn.toolScope, name)));const deadline = Date.now() + 10_000;diff --git a/server/drivers/capability-fields.test.ts b/server/drivers/capability-fields.test.tsindex 0554ebc855..948de30dfe 100644--- a/server/drivers/capability-fields.test.ts+++ b/server/drivers/capability-fields.test.ts@@ -36,7 +36,7 @@ describe("typed capability fields for the cloud computer", () => {}));expect(mounted.adapter.capabilities.computerMcp).toBe(true);expect(mounted.adapter.capabilities.dataMcp).toBe(true);- expect(mounted.adapter.capabilities.highlevelMcp).toBe(true);+ expect(mounted.adapter.capabilities.emailMcp).toBe(true);expect(mounted.adapter.capabilities.deviceMcp).toBe(true);expect(onBoat(mounted)).toBe(true);const bare = await keep(OpenAICompatDriver.create({@@ -45,7 +45,7 @@ describe("typed capability fields for the cloud computer", () => {}));expect(bare.adapter.capabilities.computerMcp).toBe(false);expect(bare.adapter.capabilities.dataMcp).toBe(false);- expect(bare.adapter.capabilities.highlevelMcp).toBe(false);+ expect(bare.adapter.capabilities.emailMcp).toBe(false);expect(bare.adapter.capabilities.deviceMcp).toBe(false);expect(onBoat(bare)).toBe(false);expect(cloudPlaceRefusal({ computerMcp: bare.adapter.capabilities.computerMcp, name: "Caps Compat Bare" }, "works-on", "Scout")?.message)diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 5f401e49f9..b97dee5b5b 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -776,7 +776,7 @@ describe("Chat MCP tool limit", () => {try {const { session, names } = await mount(windowsTurn(51, {composio: catalog(syntheticToolNames("router", 14)),- highlevel: catalog(syntheticToolNames("crm", 20)),+ email: catalog(syntheticToolNames("mail", 20)),device: catalog(syntheticToolNames("phone", 23)),}));expect(names).toHaveLength(127);@@ -784,8 +784,8 @@ describe("Chat MCP tool limit", () => {expect(names).toEqual(expect.arrayContaining(CORE_COMPUTER.map((tool) => `computer_${tool}`)));expect(names.filter((name) => name.startsWith("data_"))).toEqual(["data_table_1", "data_table_2"]);expect(session.skipped).toEqual([]);- expect(session.trimmed).toEqual([{ server: "data", listed: 2, of: 5 }, { server: "highlevel", listed: 0, of: 20 }, { server: "device", listed: 0, of: 23 }]);- expect(trimmedToolsNotice(session.trimmed)).toBe(`"data" listed 2 of 5 tools, "highlevel" listed 0 of 20 tools, "device" listed 0 of 23 tools to fit the model's 128-tool limit; the rest are left out of this turn.`);+ expect(session.trimmed).toEqual([{ server: "data", listed: 2, of: 5 }, { server: "email", listed: 0, of: 20 }, { server: "device", listed: 0, of: 23 }]);+ expect(trimmedToolsNotice(session.trimmed)).toBe(`"data" listed 2 of 5 tools, "email" listed 0 of 20 tools, "device" listed 0 of 23 tools to fit the model's 128-tool limit; the rest are left out of this turn.`);expect(trimmedToolsNotice([])).toBeUndefined();} finally { warn.mockRestore(); }});diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 6110ee7139..f928c1ce94 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -432,7 +432,6 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (integrations?.composio && eligible("composio")) servers.push(["composio", integrations.composio]);if (integrations?.composioOwn && eligible(OWN_APPS_SERVER)) servers.push([OWN_APPS_SERVER, integrations.composioOwn]);if (integrations?.data && eligible("data")) servers.push(["data", integrations.data]);- if (integrations?.highlevel && eligible("highlevel")) servers.push(["highlevel", integrations.highlevel]);if (integrations?.email && eligible("email")) servers.push(["email", integrations.email]);if (integrations?.device && eligible("device")) servers.push(["device", integrations.device]);const builtIns = servers.length;diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex fd5d0e51bc..5ad142ec01 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -1851,7 +1851,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {const stdio = (name: string) => ({ command: process.execPath, args: [`/fake/${name}.js`], env: {} });const integrations = {agents: stdio("agents"), browser: stdio("browser"), composio: stdio("composio"), composioOwn: stdio("own-apps"),- localComputer: stdio("computer"), phone: stdio("phone"), data: stdio("data"), highlevel: stdio("highlevel"), email: stdio("email"),+ localComputer: stdio("computer"), phone: stdio("phone"), data: stdio("data"), email: stdio("email"),device: stdio("device"), dweb: { url: "http://127.0.0.1:1" },custom: {shop: { command: "npx", args: ["shop"], env: {} }, docs: { type: "http" as const, url: "https://docs.example.test/mcp", headers: {} },@@ -1878,7 +1878,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {const browsing = await mounted("t-tool-search", true);expect(browsing.toolSearch).toBe("true");expect(browsing.alwaysLoaded).toEqual(["agents", "browser", "ogb"]);- expect(browsing.onDemand).toEqual(["composio", "computer", "data", "device", "docs", "dweb", "email", "highlevel", "own_apps", "phone", "postiz", "shop"]);+ expect(browsing.onDemand).toEqual(["composio", "computer", "data", "device", "docs", "dweb", "email", "own_apps", "phone", "postiz", "shop"]);const other = await mounted("t-tool-search-no-browse", false);expect(other.alwaysLoaded).toEqual(["agents", "ogb"]);expect(other.onDemand).toContain("browser");diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex bcad5fe0f8..cd6e014fb6 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -1083,7 +1083,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {: { ...turn.integrations.browser };allowed.push("mcp__browser");}- for (const name of ["data", "highlevel", "device"] as const) {+ for (const name of ["data", "device"] as const) {if (turn.integrations?.[name]) { mcpServers[name] = { ...turn.integrations[name] }; allowed.push(`mcp__${name}`); }}if (turn.integrations?.email) { mcpServers.email = { ...turn.integrations.email }; allowed.push(...EMAIL_READ_TOOL_NAMES.map((tool) => `mcp__email__${tool}`)); } // Only its reads: a send asks as any tool of a person's own server does.@@ -2040,7 +2040,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {composioMcp: true, mcpToolsFoundByName: true,phoneMcp: true,browserMcp: true,- dataMcp: true, highlevelMcp: true, deviceMcp: true,+ dataMcp: true, emailMcp: true, deviceMcp: true,images: true,nativeImageInput: true,effortLevels: ["low", "medium", "high", "xhigh", "max"],diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 584c2fbd9f..dd2ef41497 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -633,7 +633,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {if (turn.integrations?.browser) {mountSelected("browser", "browser", turn.integrations.browser);}- for (const name of ["data", "highlevel", "email", "device"] as const) if (turn.integrations?.[name]) mountSelected(name, name, turn.integrations[name]);+ for (const name of ["data", "email", "device"] as const) if (turn.integrations?.[name]) mountSelected(name, name, turn.integrations[name]);// A `-c` override merges with a same-named server in config.toml, and stdio over url is// "invalid configuration" that kills the turn, so such a server mounts under its own name.const codexConfig = codexConfigMcp(env), declaredInCodexConfig = codexConfig.names;@@ -1686,7 +1686,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {customMcp: true,phoneMcp: true,browserMcp: true,- dataMcp: true, highlevelMcp: true, deviceMcp: true,+ dataMcp: true, emailMcp: true, deviceMcp: true,images: true,nativeImageInput: true,effortLevels: ["low", "medium", "high", "xhigh", "max"],diff --git a/server/drivers/muse-code.ts b/server/drivers/muse-code.tsindex 7a0cb6e88d..f0c1527c1b 100644--- a/server/drivers/muse-code.ts+++ b/server/drivers/muse-code.ts@@ -650,7 +650,7 @@ export const MuseCodeDriver: ProviderDriver<MuseConfig> = {composioMcp: true,browserMcp: true,dataMcp: true,- highlevelMcp: true, deviceMcp: true,+ emailMcp: true, deviceMcp: true,images: true,nativeImageInput: true,effortLevels: EFFORT_LEVELS,diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex a083fe21e5..a49b304143 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -953,7 +953,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)browserMcp: options.tools !== false, nativeImageInput: true, images: true } : {}),sessionModelSwitch: "in-session", customMcp: options.tools !== false, agentsMcp: options.tools !== false, composioMcp: options.tools !== false,dataMcp: options.tools !== false,- highlevelMcp: options.tools !== false,+ emailMcp: options.tools !== false,deviceMcp: options.tools !== false,queueing: true,...(options.tools !== false ? { askTool: { kind: "native" as const, name: ASK_USER_TOOL } } : {}),diff --git a/server/drivers/pi-mcp-servers.ts b/server/drivers/pi-mcp-servers.tsindex 902e43e2b4..a7eaba4ccf 100644--- a/server/drivers/pi-mcp-servers.ts+++ b/server/drivers/pi-mcp-servers.ts@@ -33,7 +33,7 @@ export function buildMcpServers(turn: SendTurnInput): Record<string, unknown> |};}if (turn.integrations?.browser) servers.browser = { ...turn.integrations.browser };- for (const name of ["data", "highlevel", "email", "device"] as const) if (turn.integrations?.[name]) servers[name] = { ...turn.integrations[name] };+ for (const name of ["data", "email", "device"] as const) if (turn.integrations?.[name]) servers[name] = { ...turn.integrations[name] };for (const [name, server] of Object.entries(turn.integrations?.custom ?? {})) servers[name] = { ...server, scope: "custom" };for (const [name, server] of Object.entries(servers)) {if (parsed.scope !== undefined && !canUseMcpServer(parsed.scope, name)) { delete servers[name]; continue; }diff --git a/server/drivers/pi.ts b/server/drivers/pi.tsindex bbf90e051e..94417bfda9 100644--- a/server/drivers/pi.ts+++ b/server/drivers/pi.ts@@ -985,7 +985,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {phoneMcp: true,customMcp: true,browserMcp: true,- dataMcp: true, highlevelMcp: true, deviceMcp: true,+ dataMcp: true, emailMcp: true, deviceMcp: true,localComputerMcp: true,images: true,nativeImageInput: true,diff --git a/server/drivers/turn-mcp.ts b/server/drivers/turn-mcp.tsindex 09e9943059..333c3fdb15 100644--- a/server/drivers/turn-mcp.ts+++ b/server/drivers/turn-mcp.ts@@ -33,7 +33,6 @@ export function turnStdioMcpServers(turn: SendTurnInput, options: { schemaProfiladd(OWN_APPS_SERVER, turn.integrations?.composioOwn);add("browser", turn.integrations?.browser);add("data", turn.integrations?.data);- add("highlevel", turn.integrations?.highlevel);add("email", turn.integrations?.email);add("device", turn.integrations?.device);// Cua connections expose Cua Driver's own MCP server; a cloud turn runs on its boat, so none is mounted.@@ -85,7 +84,7 @@ type NameValue = Array<{ name: string; value: string }>;export type AcpMcpServer = { name: string; command: string; args: string[]; env: NameValue }| { type: "http"; name: string; url: string; headers: NameValue };-const HARNESS_KINDS = ["browser", "computer", "data", "highlevel", "email", "device"] as const;+const HARNESS_KINDS = ["browser", "computer", "data", "email", "device"] as const;/** OpenMausBot's own server behind a stdio proxy, as its HTTP endpoint on this server; null for any other server (the* person's, or one wrapped in a tool-selection gate). */diff --git a/server/email/store.ts b/server/email/store.tsindex a1de8bb422..23cb97fc62 100644--- a/server/email/store.ts+++ b/server/email/store.ts@@ -1,6 +1,6 @@-// The person's mailboxes with their passwords, sealed under a key of their own (a 0600 file beside the store), as-// highlevel/store.ts keeps its tokens, so they rest encrypted on a desktop and on a Cloud home alike. No route, card,-// bot or log ever gets a password back; the box hides the data folder, so no bot's shell can open these files.+// The person's mailboxes with their passwords, sealed under a key of their own (a 0600 file beside the store), so they+// rest encrypted on a desktop and on a Cloud home alike. No route, card, bot or log ever gets a password back; the box+// hides the data folder, so no bot's shell can open these files.import { randomBytes } from "node:crypto";import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";import { join } from "node:path";diff --git a/server/harness-budget.ts b/server/harness-budget.tsindex 8225fc2451..9078752bf9 100644--- a/server/harness-budget.ts+++ b/server/harness-budget.ts@@ -13,6 +13,6 @@ export const DEVICE_PROXY_TIMEOUT_MS = 9 * 60_000 + 120_000 + 15_000 + 30_000;export const COMPUTER_COPY_BUDGET_MS = 9 * 60_000;/** Outwaits the longest cloud computer call; Codex, which ends a tool call itself, waits a little longer still. */export const COMPUTER_PROXY_TIMEOUT_MS = COMPUTER_COPY_BUDGET_MS + 10_000;-export const HARNESS_PROXY_TIMEOUTS_MS: Partial<Record<"browser" | "computer" | "data" | "highlevel" | "email" | "device", number>> = {+export const HARNESS_PROXY_TIMEOUTS_MS: Partial<Record<"browser" | "computer" | "data" | "email" | "device", number>> = {device: DEVICE_PROXY_TIMEOUT_MS, computer: COMPUTER_PROXY_TIMEOUT_MS,};diff --git a/server/harness-mcp-proxy.test.ts b/server/harness-mcp-proxy.test.tsindex 5e67935184..d4dda53d46 100644--- a/server/harness-mcp-proxy.test.ts+++ b/server/harness-mcp-proxy.test.ts@@ -27,7 +27,7 @@ beforeAll(async () => {url = `http://127.0.0.1:${(server.address() as { port: number }).port}`;});afterAll(async () => { server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve())); });-const connection = (kind: "browser" | "computer" | "data" | "highlevel" | "email" | "device" = "browser") => ({ url, token: "scoped-capability", kind });+const connection = (kind: "browser" | "computer" | "data" | "email" | "device" = "browser") => ({ url, token: "scoped-capability", kind });const frame = (method: string, params: unknown = {}) => ({ jsonrpc: "2.0", id: 1, method, params });describe("harness MCP capability proxy", () => {@@ -48,17 +48,17 @@ describe("harness MCP capability proxy", () => {await expect(harnessMcpRequest(frame("tools/call", { name: "agent_browser_snapshot" }), connection())).resolves.toMatchObject({ result: { content: [{ type: "image", data: "jpeg" }] } });});- it("sends HighLevel calls to their own harness route with the CRM instructions", async () => {+ it("sends Email calls to their own harness route with the Email instructions", async () => {status = 200;- payload = { result: { tools: [{ name: "HIGHLEVEL_GET_CONTACT" }], instructions: "crm" } };- await expect(harnessMcpRequest(frame("initialize"), connection("highlevel"))).resolves.toMatchObject({ result: { serverInfo: { name: "openmausbot-highlevel" }, instructions: expect.stringContaining("never send SMS") } });- await expect(harnessMcpRequest(frame("tools/list"), connection("highlevel"))).resolves.toEqual({ jsonrpc: "2.0", id: 1, result: { tools: [{ name: "HIGHLEVEL_GET_CONTACT" }], instructions: "crm" } });- expect(requests.at(-1)).toEqual({ path: "/api/internal/highlevel/mcp", auth: "Bearer scoped-capability", body: { method: "tools/list", params: {} } });+ payload = { result: { tools: [{ name: "EMAIL_READ_MESSAGE" }], instructions: "mail" } };+ await expect(harnessMcpRequest(frame("initialize"), connection("email"))).resolves.toMatchObject({ result: { serverInfo: { name: "openmausbot-email" }, instructions: expect.stringContaining("OpenMausBot holds the password") } });+ await expect(harnessMcpRequest(frame("tools/list"), connection("email"))).resolves.toEqual({ jsonrpc: "2.0", id: 1, result: { tools: [{ name: "EMAIL_READ_MESSAGE" }], instructions: "mail" } });+ expect(requests.at(-1)).toEqual({ path: "/api/internal/email/mcp", auth: "Bearer scoped-capability", body: { method: "tools/list", params: {} } });status = 401;payload = { error: "the internal turn capability has expired" };- const refused = await harnessMcpRequest(frame("tools/call", { name: "HIGHLEVEL_ADD_NOTE", arguments: {} }), connection("highlevel")) as any;+ const refused = await harnessMcpRequest(frame("tools/call", { name: "EMAIL_SEND_MESSAGE", arguments: {} }), connection("email")) as any;expect(refused.result.isError).toBe(true);- expect(refused.result.content[0].text).toContain("never message anyone through the CRM");+ expect(refused.result.content[0].text).toContain("look in the Sent folder");});it("forwards device calls to /api/internal/device/mcp with the phone recovery text", async () => {diff --git a/server/harness-mcp-proxy.ts b/server/harness-mcp-proxy.tsindex e3594ce13e..31b34a6bb9 100644--- a/server/harness-mcp-proxy.ts+++ b/server/harness-mcp-proxy.ts@@ -50,7 +50,7 @@ function run(kind: HarnessMcpKind): void {if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {const kind = parseHarnessMcpKind(process.argv[2]);if (!kind) {- process.stderr.write("usage: harness-mcp-proxy browser|computer|data|highlevel|email|device\n");+ process.stderr.write("usage: harness-mcp-proxy browser|computer|data|email|device\n");process.exitCode = 2;} else run(kind);}diff --git a/server/harness-mcp-request.ts b/server/harness-mcp-request.tsindex 0ebfd6c9ad..3de4e89fd4 100644--- a/server/harness-mcp-request.ts+++ b/server/harness-mcp-request.ts@@ -1,8 +1,7 @@-// One MCP request to OpenMausBot's own browser, computer, data, HighLevel or Email tools, made with a turn's capability: the+// One MCP request to OpenMausBot's own browser, computer, data, Email or phone tools, made with a turn's capability: the// stdio proxy an engine starts and the HTTP endpoint an engine reaches both answer through it.import { DATA_INSTRUCTIONS } from "./data/instructions.ts";import { EMAIL_INSTRUCTIONS } from "./email/instructions.ts";-import { HIGHLEVEL_INSTRUCTIONS } from "./highlevel/instructions.ts";import { PHONE_INSTRUCTIONS, PHONE_RECOVERY } from "./phones/instructions.ts";import { HARNESS_PROXY_TIMEOUT_MS, HARNESS_PROXY_TIMEOUTS_MS } from "./harness-budget.ts";import { capToolListResult } from "./tool-count-limit.ts";@@ -10,21 +9,20 @@ import { capToolListResult } from "./tool-count-limit.ts";export const MAX_INPUT_BYTES = 1_048_576;export const MAX_OUTPUT_BYTES = 16_777_216;export type RpcId = string | number | null;-export type HarnessMcpKind = "browser" | "computer" | "data" | "highlevel" | "email" | "device";+export type HarnessMcpKind = "browser" | "computer" | "data" | "email" | "device";-const NAMES: Record<HarnessMcpKind, string> = { browser: "Browser", computer: "Cloud computer", data: "Data", highlevel: "HighLevel", email: "Email", device: "Phone" };-const INSTRUCTIONS: Partial<Record<HarnessMcpKind, string>> = { data: DATA_INSTRUCTIONS, highlevel: HIGHLEVEL_INSTRUCTIONS, email: EMAIL_INSTRUCTIONS, device: PHONE_INSTRUCTIONS };+const NAMES: Record<HarnessMcpKind, string> = { browser: "Browser", computer: "Cloud computer", data: "Data", email: "Email", device: "Phone" };+const INSTRUCTIONS: Partial<Record<HarnessMcpKind, string>> = { data: DATA_INSTRUCTIONS, email: EMAIL_INSTRUCTIONS, device: PHONE_INSTRUCTIONS };const RECOVERY: Record<HarnessMcpKind, string> = {browser: " This failure does not establish that all browsers are unavailable. Inspect available connections with select_computer if that tool is present. Keep the requested computer and account; do not bypass a permission refusal or human takeover, and do not repeat an uncertain action without checking its result.",computer: " Keep working on the assigned cloud computer only; do not bypass a person's control of it, and take a fresh screenshot before repeating an action whose result is uncertain.",data: " The tables already loaded are unchanged; check with data_describe or SHOW TABLES before repeating a load, and do not repeat a statement whose result is uncertain.",- highlevel: " The CRM may or may not have taken the change; read the record back (HIGHLEVEL_GET_CONTACT, HIGHLEVEL_GET_OPPORTUNITY) before repeating a write, and never message anyone through the CRM.",email: " A send may or may not have gone; look in the Sent folder (EMAIL_SEARCH_MESSAGES) before repeating one.",device: PHONE_RECOVERY,};export function parseHarnessMcpKind(value: unknown): HarnessMcpKind | null {- return value === "browser" || value === "computer" || value === "data" || value === "highlevel" || value === "email" || value === "device" ? value : null;+ return value === "browser" || value === "computer" || value === "data" || value === "email" || value === "device" ? value : null;}/** Node's fetch (undici) rejects with the socket error as its `cause`: refused before anything was sent, reset or closed after. */diff --git a/server/harness-mcp-token.ts b/server/harness-mcp-token.tsindex c335b9d486..6e4cf1318e 100644--- a/server/harness-mcp-token.ts+++ b/server/harness-mcp-token.ts@@ -1,4 +1,4 @@/** Codex starts every MCP server from one shared environment, so each harness family needs its own token variable. */-export function harnessMcpTokenEnv(kind: "browser" | "computer" | "data" | "highlevel" | "email" | "device"): string {+export function harnessMcpTokenEnv(kind: "browser" | "computer" | "data" | "email" | "device"): string {return `OMB_MCP_TOKEN_${kind.toUpperCase()}`;}diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex 36cc2eee6d..eb7df83a77 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -526,7 +526,7 @@ export class ProviderRegistry {phoneMcp: inst.adapter.capabilities.phoneMcp === true,deviceMcp: inst.adapter.capabilities.deviceMcp === true,dataMcp: inst.adapter.capabilities.dataMcp === true,- highlevelMcp: inst.adapter.capabilities.highlevelMcp === true,+ emailMcp: inst.adapter.capabilities.emailMcp === true,browserMcp: inst.adapter.capabilities.browserMcp === true,images: inst.adapter.capabilities.images === true,effortLevels: inst.adapter.capabilities.effortLevels,diff --git a/server/highlevel.e2e.test.ts b/server/highlevel.e2e.test.tsdeleted file mode 100644index abce04e292..0000000000--- a/server/highlevel.e2e.test.ts+++ /dev/null@@ -1,185 +0,0 @@-// A real server with a fake relay and a fake HighLevel: the owner connects from the card, a bot gets exactly the tools-// its scope allows, a write lands in the activity, an expired token refreshes through the relay, a revoked one signs-// out with the plain note, and Disconnect removes the tokens.-import { spawn, type ChildProcess } from "node:child_process";-import { closeSync, openSync, readFileSync, writeFileSync } from "node:fs";-import { join } from "node:path";-import { fileURLToPath } from "node:url";-import { afterAll, beforeAll, expect, it } from "vitest";--import { launchVerificationServer, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";-import { HIGHLEVEL_TOOL_NAMES } from "../shared/highlevel.ts";-import { HIGHLEVEL_NOT_CONNECTED_TEXT, HIGHLEVEL_SIGNED_OUT_TEXT } from "./highlevel/instructions.ts";-import { isHighLevelWrite } from "./highlevel/tools.ts";-import { SessionRegistry } from "./sessions.ts";-import { waitForExit } from "./testing/cleanup.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, startFakeRelay, type FakeHighLevel, type FakeRelay } from "./testing/fake-highlevel.ts";--const key = "isolated-highlevel-capability";-let fixture: VerificationServer;-let child: ChildProcess;-let hl: FakeHighLevel;-let relay: FakeRelay;-let admin: string;-let member: string;--const api = async (method: string, path: string, body?: unknown, token = admin) => {- const response = await fetch(fixture.info.url + path, {- method, headers: { "content-type": "application/json", authorization: `Bearer ${token}` },- ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(20_000),- });- return { status: response.status, body: await response.json() as any };-};-const mint = async (botId: string, threadId: string, kind = "highlevel") => {- const response = await fetch(fixture.info.url + "/api/testing/internal-capability", {- method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": key },- body: JSON.stringify({ botId, threadId, kind }),- });- expect(response.status).toBe(201);- return (await response.json() as any).token as string;-};-const rpc = (token: string, method: string, params: unknown = {}) => api("POST", "/api/internal/highlevel/mcp", { method, params }, token);-const call = (token: string, name: string, args: unknown = {}) => rpc(token, "tools/call", { name, arguments: args });--beforeAll(async () => {- hl = await startFakeHighLevel();- relay = await startFakeRelay({ onAccessToken: (token) => hl.tokens.add(token) });- fixture = await launchVerificationServer();- await waitForExit(fixture.child, { signal: "SIGTERM" });- const configFile = join(fixture.info.dataDir, "config.json");- const config = JSON.parse(readFileSync(configFile, "utf8"));- config.signIn = { admins: ["[email protected]"], members: ["[email protected]"] };- writeFileSync(configFile, JSON.stringify(config));- const sessions = new SessionRegistry({ file: join(fixture.info.dataDir, "sessions.json"),- emailScopes: email => email === "[email protected]" ? ["admin", "client"] : ["client"] });- admin = sessions.issue({ label: "isolated admin", email: "[email protected]", scopes: ["admin", "client"] }).token;- member = sessions.issue({ label: "isolated member", email: "[email protected]", scopes: ["client"] }).token;- sessions.close();- const log = openSync(fixture.info.logPath, "a", 0o600);- child = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {- cwd: fileURLToPath(new URL("..", import.meta.url)),- env: { ...verificationServerEnvironment({}, fixture.info.dataDir, Number(new URL(fixture.info.url).port)),- OMB_TEST_INTERNAL_CAPABILITY_KEY: key, OMB_HIGHLEVEL_RELAY_URL: relay.url, OMB_HIGHLEVEL_API_URL: hl.url },- stdio: ["ignore", log, log],- });- closeSync(log);- const deadline = Date.now() + 20_000;- while (Date.now() < deadline) {- try { if ((await fetch(fixture.info.url + "/api/health")).ok) return; } catch {}- await new Promise(resolve => setTimeout(resolve, 20));- }- throw new Error("isolated HighLevel server did not start");-}, 40_000);--afterAll(async () => {- await waitForExit(child, { signal: "SIGTERM" });- await fixture.close();- await hl.close();- await relay.close();-});--it("connects from the card through the relay, keeps the tokens out of every answer, and lists the tools for grants", async () => {- expect(await api("GET", "/api/highlevel")).toEqual({ status: 200, body: { state: "signed-out" } });- expect((await api("GET", "/api/highlevel", undefined, member)).status).toBe(403);- expect((await api("POST", "/api/highlevel/sign-in", undefined, member)).status).toBe(403);- const started = await api("POST", "/api/highlevel/sign-in");- expect(started.status).toBe(200);- expect(started.body).toEqual({ flowId: expect.stringMatching(/^[0-9a-f-]{36}$/u), authorizationUrl: expect.stringMatching(/^https:\/\/marketplace\.leadconnectorhq\.com\//u), expiresAt: expect.any(Number) });- expect(await api("GET", "/api/highlevel")).toMatchObject({ status: 200, body: { state: "connecting", flow: started.body } });- expect(await api("GET", `/api/highlevel/sign-in/${started.body.flowId}`)).toEqual({ status: 200, body: { phase: "waiting" } });- relay.complete([...relay.states.keys()].at(-1)!);- await expect.poll(async () => (await api("GET", `/api/highlevel/sign-in/${started.body.flowId}`)).body.phase, { timeout: 8_000, interval: 200 }).toBe("connected");- const status = await api("GET", "/api/highlevel");- expect(status.body).toMatchObject({ state: "connected", kind: "oauth", location: { id: FAKE_LOCATION_ID, name: "Example Profiles" }, connectedAt: expect.any(Number) });- expect(JSON.stringify(status.body)).not.toMatch(/hl_access|hl_refresh/u);- const tools = await api("GET", "/api/connectors/tools");- expect(tools.status).toBe(200);- expect(tools.body.services.highlevel.map((tool: { name: string }) => tool.name)).toEqual([...HIGHLEVEL_TOOL_NAMES]);-}, 30_000);--it("gives a bot its scoped tools, records writes without contact data, refreshes once, signs out on revocation and disconnects", async () => {- const created = await api("POST", "/api/bots", { name: "CRM scout" });- expect(created.status).toBe(201);- const bot = created.body.bot;- expect((await api("PATCH", `/api/bots/${bot.id}`, { connectorScopes: { apps: { highlevel: "read" } } })).status).toBe(200);- // Another kind's capability never reaches the CRM route. (A later mint on the same thread replaces this turn.)- expect((await rpc(await mint(bot.id, bot.threadId, "connectors"), "tools/list")).status).toBe(403);- const token = await mint(bot.id, bot.threadId);-- const listed = await rpc(token, "tools/list");- expect(listed.status).toBe(200);- expect(listed.body.result.tools.map((tool: { name: string }) => tool.name)).toEqual(HIGHLEVEL_TOOL_NAMES.filter((name) => !isHighLevelWrite(name)));- expect(listed.body.result.instructions).toContain("never send SMS");-- hl.calls.length = 0;- const read = await call(token, "HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" });- expect(read.body.result.isError).toBeUndefined();- expect(read.body.result.structuredContent).toMatchObject({ id: "contact_1", email: "[email protected]", customFields: { "Lead Source": "Referral" } });- const contactCall = hl.calls.find((row) => row.path === "/contacts/contact_1")!;- expect(contactCall.headers.version).toBe("2021-07-28");- expect(contactCall.headers.authorization).toBe(`Bearer ${relay.issued[0]}`);-- const refused = await call(token, "HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Called back" });- expect(refused.body.result.isError).toBe(true);- expect(refused.body.result.content[0].text).toBe("OpenMausBot did not run this: HighLevel is read-only for CRM scout, and Add note would write to it. Ask the user before trying again.");- expect(hl.calls.some((row) => row.path.endsWith("/notes"))).toBe(false);-- expect((await api("PATCH", `/api/bots/${bot.id}`, { connectorScopes: { apps: { highlevel: "write" } } })).status).toBe(200);- const written = await call(token, "HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Called back, wants the quote by Friday" });- expect(written.body.result.isError).toBeUndefined();- expect(written.body.result.structuredContent).toMatchObject({ contactId: "contact_1", note: { id: "note_new" } });- const messages = (await api("GET", `/api/threads/${bot.threadId}/messages?limit=100`)).body.messages as any[];- const row = messages.find((message) => message.kind === "activity" && message.tool?.name === "mcp__highlevel__HIGHLEVEL_ADD_NOTE");- expect(row).toMatchObject({ role: "bot", tool: { name: "mcp__highlevel__HIGHLEVEL_ADD_NOTE", ok: true, summary: "note note_new: body" } });- expect(JSON.stringify(row)).not.toContain("wants the quote");-- // The access token expires: one refresh through the relay, the call retried with the new token, the pair rotated.- hl.tokens.delete(relay.issued[0]!);- expect(relay.refreshes).toBe(0);- const afterExpiry = await call(token, "HIGHLEVEL_LIST_PIPELINES");- expect(afterExpiry.body.result.isError).toBeUndefined();- expect(relay.refreshes).toBe(1);- expect(hl.calls.filter((row) => row.path === "/opportunities/pipelines").map((row) => row.headers.authorization)).toEqual([`Bearer ${relay.issued[0]}`, `Bearer ${relay.issued[1]}`]);- expect(await api("GET", "/api/highlevel")).toMatchObject({ body: { state: "connected" } });-- // Revoked: the relay rejects the refresh, the bot gets the plain note, the card says reconnect.- hl.tokens.clear();- relay.refreshTokens.clear();- const revoked = await call(token, "HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" });- expect(revoked.body.result.isError).toBe(true);- expect(revoked.body.result.content[0].text).toBe(HIGHLEVEL_SIGNED_OUT_TEXT);- expect(relay.refreshes).toBe(2);- expect(await api("GET", "/api/highlevel")).toMatchObject({ body: { state: "needs-sign-in", kind: "oauth", location: { name: "Example Profiles" }, problem: expect.stringMatching(/rejected the saved sign-in/u) } });- const again = await call(token, "HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" });- expect(again.body.result.content[0].text).toBe(HIGHLEVEL_SIGNED_OUT_TEXT);- expect(relay.refreshes).toBe(2);-- // Disconnect removes the tokens; a Private Integration token connects without the relay.- expect(await api("DELETE", "/api/highlevel")).toEqual({ status: 200, body: { state: "signed-out" } });- expect((await call(token, "HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" })).body.result.content[0].text).toBe(HIGHLEVEL_NOT_CONNECTED_TEXT);- expect(await api("POST", "/api/highlevel/token", { token: "pit-e2e-rejected-1", locationId: FAKE_LOCATION_ID })).toMatchObject({ status: 401, body: { error: expect.stringMatching(/did not accept this token/u) } });- hl.tokens.add("pit-e2e-token-12345");- expect(await api("POST", "/api/highlevel/token", { token: "pit-e2e-token-12345", locationId: FAKE_LOCATION_ID })).toMatchObject({ status: 200, body: { state: "connected", kind: "token", location: { id: FAKE_LOCATION_ID, name: "Example Profiles" } } });- const viaToken = await call(token, "HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" });- expect(viaToken.body.result.isError).toBeUndefined();- expect(hl.calls.at(-1)?.headers.authorization).toBe("Bearer pit-e2e-token-12345");- expect(relay.refreshes).toBe(2);-}, 40_000);--it("does not create a note after Stop during a rate-limit wait, and allows the next turn", async () => {- const bot = (await api("POST", "/api/bots", { name: "Stopped CRM writer" })).body.bot;- hl.tokens.add("pit-stop-fixture-12345");- expect((await api("POST", "/api/highlevel/token", { token: "pit-stop-fixture-12345", locationId: FAKE_LOCATION_ID })).status).toBe(200);- const token = await mint(bot.id, bot.threadId);- hl.calls.length = 0;- hl.overrides.push({ status: 429, headers: { "retry-after": "3" } });- const pending = call(token, "HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Stopped fixture note" });- await expect.poll(() => hl.calls.length, { timeout: 2_000, interval: 10 }).toBe(1);- expect((await api("POST", `/api/bots/${bot.id}/interrupt`, { threadId: bot.threadId })).status).toBe(200);- expect((await pending).status).toBe(401);- expect(hl.calls.filter((row) => row.method === "POST" && row.path.endsWith("/notes"))).toHaveLength(1);- const messages = (await api("GET", `/api/threads/${bot.threadId}/messages?limit=100`)).body.messages as any[];- expect(messages.filter((row) => row.tool?.name === "mcp__highlevel__HIGHLEVEL_ADD_NOTE")).toEqual([]);- const next = await call(await mint(bot.id, bot.threadId), "HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Next fixture note" });- expect(next.body.result.structuredContent).toMatchObject({ note: { id: "note_new" } });-}, 20_000);diff --git a/server/highlevel/access.ts b/server/highlevel/access.tsdeleted file mode 100644index 2dae78662b..0000000000--- a/server/highlevel/access.ts+++ /dev/null@@ -1,76 +0,0 @@-// Per-bot checks for HighLevel calls, the same rules Composio calls get: connectorTools grants decide which tools,-// connectorScopes.apps.highlevel decides read or write. A refusal names the bot and the app, never the other grants.-import { HIGHLEVEL_SLUG } from "../../shared/highlevel.ts";-import { connectorAccessDecision, describeConnectorScopes, type ConnectorScopes } from "../../shared/connector-scopes.ts";-import type { ConnectorToolGrant } from "../../shared/wire.ts";-import { connectorRefusalText, connectorScopeRefusalText, evaluateConnectorTools } from "../connector-verdict.ts";-import { HIGHLEVEL_PROMPT } from "./instructions.ts";--export interface HighLevelBot {- id: string;- name: string;- composio?: boolean;- connectorTools?: Record<string, ConnectorToolGrant>;- connectorScopes?: ConnectorScopes;-}--export interface HighLevelDecisionRow {- tool: string;- summary?: string;- decision: "auto-approved" | "auto-denied";- rule: string;-}--export type HighLevelAccess =- | { ok: true; rows: HighLevelDecisionRow[] }- | { ok: false; text: string; rows: HighLevelDecisionRow[] };--/** Does this bot get the HighLevel tools at all? Off with connected apps off, or with a scope or grant record that leaves HighLevel out. */-export function highlevelAllowedFor(bot: HighLevelBot): boolean {- if (bot.composio === false) return false;- if (bot.connectorScopes && !Object.hasOwn(bot.connectorScopes.apps, HIGHLEVEL_SLUG)) return false;- if (bot.connectorTools !== undefined && !Object.hasOwn(bot.connectorTools, HIGHLEVEL_SLUG)) return false;- return true;-}--/** tools/list shows only what a call would be allowed to run. */-export function highlevelToolVisible(bot: HighLevelBot, name: string): boolean {- return highlevelAccess(bot, name).ok;-}--/** The verdict for one call, with the decision rows the handler writes. */-export function highlevelAccess(bot: HighLevelBot, name: string): HighLevelAccess {- const rows: HighLevelDecisionRow[] = [];- if (!highlevelAllowedFor(bot)) {- rows.push({ tool: name, summary: "HighLevel is not enabled for this bot", decision: "auto-denied", rule: `scope:${HIGHLEVEL_SLUG}:app` });- return { ok: false, text: connectorScopeRefusalText({ kind: "tools", invoked: name, names: [name] }, "app", bot.name, "HighLevel", describeAction(name)), rows };- }- const verdict = evaluateConnectorTools([name], bot.connectorTools, [HIGHLEVEL_SLUG]);- if (!verdict.allowed) {- for (const denial of verdict.denials) {- rows.push({ tool: denial.tool, summary: denial.onGrantedService ? "tool is not in this service's grant" : "service is not granted", decision: "auto-denied", rule: `connectorTools.${HIGHLEVEL_SLUG}` });- }- return { ok: false, text: connectorRefusalText(verdict.denials), rows };- }- const access = connectorAccessDecision(bot.connectorScopes, [{ slug: name }], [HIGHLEVEL_SLUG]);- if (!access.ok) {- rows.push({ tool: name, decision: "auto-denied", rule: `scope:${HIGHLEVEL_SLUG}:${access.reason}` });- return { ok: false, text: connectorScopeRefusalText({ kind: "tools", invoked: name, names: [name] }, access.reason, bot.name, "HighLevel", describeAction(name)), rows };- }- rows.push({ tool: name, summary: `allowed ${name}`, decision: "auto-approved", rule: verdict.legacy ? `scope:${HIGHLEVEL_SLUG}` : verdict.rule });- return { ok: true, rows };-}--/** HIGHLEVEL_ADD_NOTE → "Add note". */-export function describeAction(name: string): string {- const action = name.replace(/^HIGHLEVEL_/u, "").replace(/_+/gu, " ").toLowerCase();- return action ? action[0]!.toUpperCase() + action.slice(1) : name;-}--/** The system prompt part: what the bot can do, that it never messages anyone, and its HighLevel scope. */-export function highlevelSystemPrompt(bot: Pick<HighLevelBot, "connectorScopes" | "connectorTools">): string {- const scopes = bot.connectorScopes ? { apps: { [HIGHLEVEL_SLUG]: bot.connectorScopes.apps[HIGHLEVEL_SLUG]! } } : undefined;- const grant = bot.connectorTools?.[HIGHLEVEL_SLUG];- const granted = grant && grant.tools !== "*" ? ` Of the highlevel tools, this bot was granted only: ${grant.tools.join(", ")}.` : "";- return HIGHLEVEL_PROMPT + granted + describeConnectorScopes(scopes);-}diff --git a/server/highlevel/cancellation.test.ts b/server/highlevel/cancellation.test.tsdeleted file mode 100644index 253f58b62d..0000000000--- a/server/highlevel/cancellation.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import { mkdtempSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, afterEach, beforeAll, beforeEach, expect, it } from "vitest";--import { removeTempDir } from "../testing/cleanup.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, type FakeHighLevel } from "../testing/fake-highlevel.ts";-import { BUDGET_CALLS, HighLevelClient } from "./client.ts";-import { highlevelRpc, type HighLevelRpcDeps } from "./rpc.ts";-import { HighLevelStore } from "./store.ts";-import type { HighLevelWriteRecord } from "./tools.ts";--let hl: FakeHighLevel;-const dirs: string[] = [];-beforeAll(async () => { hl = await startFakeHighLevel(); hl.tokens.add("hl_access_seed"); });-beforeEach(() => { hl.calls.length = 0; hl.overrides.length = 0; });-afterEach(async () => { for (const dir of dirs.splice(0)) await removeTempDir(dir); });-afterAll(async () => { await hl.close(); });--const call = (name: string, args: unknown) => ({ method: "tools/call", params: { name, arguments: args } });-const note = call("HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Fixture note" });--function deferred<T>() {- let resolve!: (value: T) => void;- const promise = new Promise<T>((yes) => { resolve = yes; });- return { promise, resolve };-}--function harness() {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-cancel-"));- dirs.push(dir);- const store = new HighLevelStore({ dataDir: dir });- store.put({ kind: "token", accessToken: "hl_access_seed", locationId: FAKE_LOCATION_ID, scopes: "" });- const waiting = deferred<number>();- const resume = deferred<void>();- let now = Date.now();- const client = new HighLevelClient({ store, refresh: null, apiUrl: hl.url, now: () => now, sleep: async (ms) => {- waiting.resolve(ms);- await resume.promise;- now += ms;- } });- const stopped = Object.assign(new Error("turn ended"), { status: 409 });- let active = true;- const writes: HighLevelWriteRecord[] = [];- const deps: HighLevelRpcDeps = {- client, assertActive: () => { if (!active) throw stopped; }, authorize: () => ({ ok: true }),- onWrite: (record) => { writes.push(record); },- };- return { client, deps, writes, waiting: waiting.promise, resume: resume.resolve, stop: () => { active = false; }, stopped };-}--it.each(["429", "5xx", "budget"])("sends no request after Stop during a %s wait", async (wait) => {- const h = harness();- const request = wait === "5xx" ? call("HIGHLEVEL_ADD_TAGS", { contactId: "contact_1", tags: ["fixture"] }) : note;- if (wait === "budget") {- for (let i = 0; i < BUDGET_CALLS; i++) await h.client.listPipelines();- hl.calls.length = 0;- } else {- hl.overrides.push({ status: wait === "429" ? 429 : 503, headers: { "retry-after": "3" } });- }- const pending = highlevelRpc(request, h.deps).catch((error: unknown) => error);- await expect(h.waiting).resolves.toBe(wait === "429" ? 3_000 : wait === "5xx" ? 1_000 : 10_000);- expect(hl.calls).toHaveLength(wait === "budget" ? 0 : 1);- h.stop();- h.resume();- expect(await pending).toBe(h.stopped);- expect(hl.calls).toHaveLength(wait === "budget" ? 0 : 1);- expect(h.writes).toEqual([]);-});--it("checks Stop before the first request after asynchronous call setup", async () => {- const h = harness();- h.deps.authorize = () => { queueMicrotask(h.stop); return { ok: true }; };- await expect(highlevelRpc(note, h.deps)).rejects.toBe(h.stopped);- expect(hl.calls).toEqual([]);- expect(h.writes).toEqual([]);-});--it("keeps concurrent calls on the shared client scoped to their own turn", async () => {- const h = harness();- hl.overrides.push({ status: 429, headers: { "retry-after": "3" } });- const pending = highlevelRpc(note, h.deps).catch((error: unknown) => error);- await h.waiting;- h.stop();- const otherWrites: HighLevelWriteRecord[] = [];- const live = { ...h.deps, assertActive: () => {}, onWrite: (record: HighLevelWriteRecord) => { otherWrites.push(record); } };- expect(await highlevelRpc(note, live)).not.toHaveProperty("isError", true);- h.resume();- expect(await pending).toBe(h.stopped);- expect(hl.calls.filter((row) => row.method === "POST")).toHaveLength(2);- expect(h.writes).toEqual([]);- expect(otherWrites).toEqual([{ tool: "HIGHLEVEL_ADD_NOTE", kind: "note", recordId: "note_new", fields: ["body"] }]);- expect(await highlevelRpc(note, live)).not.toHaveProperty("isError", true);- expect(otherWrites).toHaveLength(2);-});diff --git a/server/highlevel/client.test.ts b/server/highlevel/client.test.tsdeleted file mode 100644index cb963f83cb..0000000000--- a/server/highlevel/client.test.ts+++ /dev/null@@ -1,755 +0,0 @@-// The API client against a fake HighLevel: request shapes, trimmed outputs, the Version header, refresh-once-and-retry-// with the rotated pair persisted, 429 backoff, 5xx retry, plain error sentences, and the no-messaging guard.-import { mkdtempSync, readFileSync, statSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";--import { HIGHLEVEL_TOOL_NAMES } from "../../shared/highlevel.ts";-import { removeTempDir } from "../testing/cleanup.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, startFakeRelay, type FakeHighLevel, type FakeRelay } from "../testing/fake-highlevel.ts";-import { BUDGET_CALLS, FORBIDDEN_PATHS, HIGHLEVEL_CONVERSATIONS_VERSION, HIGHLEVEL_VERSION, HighLevelClient, HighLevelError, assertAllowedPath, type HighLevelClientOptions, isScopeRefusal, lookupLocation, plainError, redactSecrets } from "./client.ts";-import { HIGHLEVEL_NOT_CONNECTED_TEXT, HIGHLEVEL_SIGNED_OUT_TEXT } from "./instructions.ts";-import { HighLevelRelayError, createHighLevelRelay, type RelayTokens } from "./relay.ts";-import { HIGHLEVEL_FILE, HIGHLEVEL_KEY_FILE, HighLevelStore } from "./store.ts";-import { HIGHLEVEL_TOOLS, runHighLevelTool } from "./tools.ts";--let hl: FakeHighLevel;-let relay: FakeRelay;-const dirs: string[] = [];-let clock = 1_800_000_000_000;-const slept: number[] = [];--beforeAll(async () => {- hl = await startFakeHighLevel();- relay = await startFakeRelay({ onAccessToken: (token) => hl.tokens.add(token) });-});-afterAll(async () => { await hl.close(); await relay.close(); });-beforeEach(() => { hl.calls.length = 0; hl.overrides.length = 0; hl.pathOverrides.clear(); slept.length = 0; hl.tokens.clear(); relay.refreshes = 0; });-afterEach(async () => { for (const dir of dirs.splice(0)) await removeTempDir(dir); });--function harness(connection: Partial<Parameters<HighLevelStore["put"]>[0]> & { kind?: "oauth" | "token" } = {}, options: Partial<HighLevelClientOptions> = {}) {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-client-"));- dirs.push(dir);- const store = new HighLevelStore({ dataDir: dir, now: () => clock });- const accessToken = connection.accessToken ?? "hl_access_seed";- hl.tokens.add(accessToken);- relay.refreshTokens.add("hl_refresh_seed");- store.put({ kind: "oauth", accessToken, refreshToken: "hl_refresh_seed", expiresAt: clock + 3_600_000, locationId: FAKE_LOCATION_ID, locationName: "Example Profiles", scopes: "contacts.write", ...connection });- const upstream = createHighLevelRelay(relay.url);- const client = new HighLevelClient({ store, refresh: (token) => upstream.refresh(token), apiUrl: hl.url, now: () => clock, sleep: async (ms) => { slept.push(ms); clock += ms; }, ...options });- return { dir, store, client };-}--const last = () => hl.calls.at(-1)!;--function deferred<T = void>() {- let resolve!: (value: T) => void;- let reject!: (error: unknown) => void;- const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });- return { promise, resolve, reject };-}--const settle = () => new Promise((resolve) => setImmediate(resolve));--describe("HighLevelStore", () => {- it("rests encrypted under its own 0600 key file and reads back the same connection", () => {- const { dir } = harness();- const bytes = readFileSync(join(dir, HIGHLEVEL_FILE));- expect(bytes.toString("latin1")).not.toContain("hl_access_seed");- expect(bytes.toString("latin1")).not.toContain("hl_refresh_seed");- if (process.platform !== "win32") {- expect(statSync(join(dir, HIGHLEVEL_FILE)).mode & 0o777).toBe(0o600);- expect(statSync(join(dir, HIGHLEVEL_KEY_FILE)).mode & 0o777).toBe(0o600);- }- const again = new HighLevelStore({ dataDir: dir });- expect(again.get()).toMatchObject({ kind: "oauth", accessToken: "hl_access_seed", refreshToken: "hl_refresh_seed", locationId: FAKE_LOCATION_ID, locationName: "Example Profiles", state: "signed-in" });- expect(again.secretValues()).toEqual(["hl_access_seed", "hl_refresh_seed"]);- expect(again.rotate({ accessToken: "hl_access_x", refreshToken: "hl_refresh_x" }, { ...again.get()!, accessToken: "hl_access_spent" })).toBeNull();- again.rotate({ accessToken: "hl_access_2", refreshToken: "hl_refresh_2", expiresAt: 5 }, again.get()!);- expect(new HighLevelStore({ dataDir: dir }).get()).toMatchObject({ accessToken: "hl_access_2", refreshToken: "hl_refresh_2", expiresAt: 5, state: "signed-in" });- again.markNeedsSignIn("stale", { ...again.get()!, accessToken: "hl_access_seed" });- expect(new HighLevelStore({ dataDir: dir }).get()).toMatchObject({ state: "signed-in" });- again.markNeedsSignIn("revoked", again.get()!);- expect(new HighLevelStore({ dataDir: dir }).get()).toMatchObject({ state: "needs-sign-in", problem: "revoked" });- again.clear();- expect(new HighLevelStore({ dataDir: dir }).get()).toBeNull();- });-});--describe("HighLevelClient requests", () => {- it("sends the bearer and the Version header on every call, and the conversations version on conversations", async () => {- const { client } = harness();- await client.getContact("contact_1");- expect(last().headers.authorization).toBe("Bearer hl_access_seed");- expect(last().headers.version).toBe(HIGHLEVEL_VERSION);- await client.searchConversations({ contactId: "contact_1" });- expect(last().headers.version).toBe(HIGHLEVEL_CONVERSATIONS_VERSION);- expect(last().query).toEqual({ locationId: FAKE_LOCATION_ID, contactId: "contact_1", limit: "20" });- await client.readConversation("conv_1", { limit: 5 });- expect(last().headers.version).toBe(HIGHLEVEL_CONVERSATIONS_VERSION);- expect(last().path).toBe("/conversations/conv_1/messages");- });-- it("trims a contact to what a person cares about and names its custom fields", async () => {- const { client } = harness();- const contact = await client.getContact("contact_1");- expect(contact).toEqual({- id: "contact_1", name: "Ada Lovelace", firstName: "Ada", lastName: "Lovelace", email: "[email protected]", phone: "+15550001234",- companyName: "Analytical Engines", tags: ["vip", "newsletter"], source: "web form", assignedTo: "user_1",- dateAdded: "2026-01-02T03:04:05.000Z", dateUpdated: "2026-02-03T04:05:06.000Z", dnd: false,- address: { address1: "1 Engine Row", city: "London", country: "GB" }, customFields: { "Lead Source": "Referral", Budget: 1200 },- });- expect(JSON.stringify(contact)).not.toMatch(/attributionSource|emailLowerCase|visitorId|dndSettings|10\.0\.0\.1/u);- // The custom field definitions are fetched once and cached.- await client.getContact("contact_1");- expect(hl.calls.filter((call) => call.path.endsWith("/customFields"))).toHaveLength(1);- });-- it("searches with the location, page and exact filters", async () => {- const { client } = harness();- const out = await client.searchContacts({ query: "ada", tag: "vip", email: "[email protected]", limit: 10, page: 2 });- const search = hl.calls.find((call) => call.path === "/contacts/search")!;- expect(search.method).toBe("POST");- expect(search.body).toEqual({ locationId: FAKE_LOCATION_ID, page: 2, pageLimit: 10, query: "ada", filters: [- { field: "email", operator: "eq", value: "[email protected]" }, { field: "tags", operator: "eq", value: "vip" },- ] });- expect(out).toMatchObject({ total: 1, page: 2 });- expect(out.contacts[0]).toMatchObject({ id: "contact_1", email: "[email protected]" });- });-- it("passes page numbers past the page-size limit through unchanged", async () => {- const { client } = harness();- expect(await client.searchContacts({ query: "ada", page: 51, limit: 50 })).toMatchObject({ page: 51 });- expect(hl.calls.find((call) => call.path === "/contacts/search")!.body).toMatchObject({ page: 51, pageLimit: 50 });- expect(await client.searchOpportunities({ page: 1000, limit: 80 })).toMatchObject({ page: 1000 });- expect(last().query).toMatchObject({ page: "1000", limit: "50" });- const page = HIGHLEVEL_TOOLS.find((tool) => tool.name === "HIGHLEVEL_SEARCH_CONTACTS")!.inputSchema.properties.page;- expect(page).toMatchObject({ minimum: 1, maximum: 1000 });- });-- it("creates and updates contacts with the location id and custom fields mapped from names to ids", async () => {- const { client } = harness();- await client.createContact({ firstName: "Grace", email: "[email protected]", tags: ["new"], customFields: { "lead source": "Event", "contact.budget": 900 } });- const create = hl.calls.find((call) => call.path === "/contacts/" && call.method === "POST")!;- expect(create.body).toEqual({ firstName: "Grace", email: "[email protected]", tags: ["new"], locationId: FAKE_LOCATION_ID,- customFields: [{ id: "cf_lead", field_value: "Event" }, { id: "cf_budget", field_value: 900 }] });- await client.updateContact("contact_1", { phone: "+15550002222" });- expect(last()).toMatchObject({ method: "PUT", path: "/contacts/contact_1", body: { phone: "+15550002222" } });- await expect(client.updateContact("contact_1", { customFields: { Nope: 1 } })).rejects.toThrow(/no custom field named "Nope"/u);- });-- it("shapes every other endpoint the tools use", async () => {- const { client } = harness();- expect(await client.addTags("contact_1", ["a", "b"])).toEqual({ contactId: "contact_1", tags: ["a", "b"] });- expect(last()).toMatchObject({ method: "POST", path: "/contacts/contact_1/tags", body: { tags: ["a", "b"] } });- await client.removeTags("contact_1", ["a"]);- expect(last()).toMatchObject({ method: "DELETE", path: "/contacts/contact_1/tags", body: { tags: ["a"] } });- expect((await client.listNotes("contact_1")).notes).toEqual([{ id: "note_1", body: "Called back", dateAdded: "2026-03-03T00:00:00.000Z", userId: "user_1" }]);- expect((await client.addNote("contact_1", "Left voicemail")).note).toMatchObject({ id: "note_new", body: "Left voicemail" });- expect(last().body).toEqual({ body: "Left voicemail" });- expect((await client.listTasks("contact_1")).tasks[0]).toEqual({ id: "task_1", title: "Send quote", dueDate: "2026-03-10T09:00:00.000Z", completed: false, assignedTo: "user_1" });- await client.addTask("contact_1", { title: "Follow up", dueDate: "2026-03-12T09:00:00.000Z", body: "re: quote" });- expect(last().body).toEqual({ title: "Follow up", dueDate: "2026-03-12T09:00:00.000Z", body: "re: quote", completed: false });- expect(await client.listPipelines()).toEqual({ pipelines: [{ id: "pipe_1", name: "Sales", stages: [{ id: "stage_new", name: "New", position: 0 }, { id: "stage_won", name: "Won", position: 1 }] }] });- expect(last().query).toEqual({ locationId: FAKE_LOCATION_ID });- const opps = await client.searchOpportunities({ pipelineId: "pipe_1", status: "open", query: "web" });- expect(last().query).toEqual({ location_id: FAKE_LOCATION_ID, q: "web", pipeline_id: "pipe_1", status: "open", page: "1", limit: "20" });- expect(opps.opportunities[0]).toEqual({- id: "opp_1", name: "Website redesign", status: "open", monetaryValue: 4500, pipelineId: "pipe_1", pipelineStageId: "stage_new", contactId: "contact_1",- contact: { id: "contact_1", name: "Ada Lovelace", email: "[email protected]", phone: "+15550001234", companyName: "Analytical Engines" },- assignedTo: "user_1", source: "referral", createdAt: "2026-02-28T00:00:00.000Z", updatedAt: "2026-03-02T00:00:00.000Z",- lastStageChangeAt: "2026-03-02T00:00:00.000Z", lastStatusChangeAt: "2026-03-01T00:00:00.000Z",- });- expect(JSON.stringify(opps)).not.toContain("indexVersion");- await client.getOpportunity("opp_1");- expect(last()).toMatchObject({ method: "GET", path: "/opportunities/opp_1" });- await client.createOpportunity({ pipelineId: "pipe_1", contactId: "contact_1", name: "Deal", value: 10, stageId: "stage_new" });- expect(last().body).toEqual({ pipelineId: "pipe_1", locationId: FAKE_LOCATION_ID, name: "Deal", pipelineStageId: "stage_new", status: "open", contactId: "contact_1", monetaryValue: 10 });- await client.updateOpportunity("opp_1", { stageId: "stage_won", status: "won" });- expect(last()).toMatchObject({ method: "PUT", path: "/opportunities/opp_1", body: { pipelineStageId: "stage_won", status: "won" } });- const conversations = await client.searchConversations({ query: "tuesday" });- expect(conversations.conversations[0]).toEqual({ id: "conv_1", contactId: "contact_1", contactName: "Ada Lovelace", email: "[email protected]", phone: "+15550001234",- type: "TYPE_PHONE", lastMessageBody: "See you Tuesday", lastMessageType: "TYPE_SMS", lastMessageDate: new Date(1772000000000).toISOString(), unreadCount: 2 });- const thread = await client.readConversation("conv_1");- expect(thread.messages).toEqual([- { id: "msg_2", type: "TYPE_SMS", direction: "inbound", status: "delivered", dateAdded: "2026-03-05T10:00:00.000Z", body: "See you Tuesday", contentType: "text/plain", attachments: 0 },- { id: "msg_1", type: "TYPE_SMS", direction: "outbound", status: "delivered", dateAdded: "2026-03-05T09:00:00.000Z", body: "Can we meet?", contentType: "text/plain", attachments: 1 },- ]);- expect(thread).toMatchObject({ nextPage: false, lastMessageId: "msg_2" });- expect((await client.listCalendars()).calendars).toEqual([{ id: "cal_1", name: "Consultations", description: "30 min", isActive: true, calendarType: "round_robin", slotDuration: 30, slotDurationUnit: "mins", teamMembers: 1 }]);- const events = await client.listEvents({ startTime: "2026-03-10T00:00:00Z", endTime: "2026-03-11T00:00:00Z", calendarId: "cal_1" });- expect(last().query).toEqual({ locationId: FAKE_LOCATION_ID, calendarId: "cal_1", startTime: String(Date.parse("2026-03-10T00:00:00Z")), endTime: String(Date.parse("2026-03-11T00:00:00Z")) });- expect(events.events[0]).toEqual({ id: "evt_1", title: "Intro call", calendarId: "cal_1", contactId: "contact_1", appointmentStatus: "confirmed", startTime: "2026-03-10T15:00:00.000Z", endTime: "2026-03-10T15:30:00.000Z", assignedUserId: "user_1", address: "Zoom", notes: "bring deck" });- await expect(client.listEvents({ startTime: "yesterday", endTime: "2026-03-11T00:00:00Z" })).rejects.toThrow(/startTime must be an ISO 8601/u);- const location = await client.getLocation();- expect(location).toMatchObject({ id: FAKE_LOCATION_ID, name: "Example Profiles", timezone: "America/Chicago", city: "Austin" });- expect(location.customFields).toEqual([- { id: "cf_lead", name: "Lead Source", key: "contact.lead_source", dataType: "TEXT", model: "contact" },- { id: "cf_budget", name: "Budget", key: "contact.budget", dataType: "NUMERICAL", model: "contact" },- ]);- });-});--describe("HighLevelClient resilience", () => {- it("starts no OAuth refresh when the first 401 arrives after Stop", async () => {- const received = deferred();- const respond = deferred();- const { client, store, dir } = harness({}, { fetch: async (...args) => {- const response = await fetch(...args);- received.resolve();- await respond.promise;- return response;- } });- hl.tokens.delete("hl_access_seed");- const saved = store.get();- const relayCalls = relay.calls.length;- const stopped = Object.assign(new Error("turn ended"), { status: 409 });- let active = true;- const pending = client.withActiveCall(() => { if (!active) throw stopped; },- () => client.request("GET", "/contacts/contact_1")).catch((error: unknown) => error);- await received.promise;- active = false;- respond.resolve();- expect(await pending).toBe(stopped);- expect(hl.calls).toHaveLength(1);- expect(relay.refreshes).toBe(0);- expect(relay.calls).toHaveLength(relayCalls);- expect(new HighLevelStore({ dataDir: dir }).get()).toEqual(saved);- });-- it("keeps and stores a shared refresh started by another call after Stop", async () => {- const refreshed = deferred();- const resume = deferred();- const upstream = createHighLevelRelay(relay.url);- const { client, dir } = harness({ expiresAt: clock + 30_000 }, { refresh: async (token) => {- const tokens = await upstream.refresh(token);- refreshed.resolve();- await resume.promise;- return tokens;- } });- const live = client.request("GET", "/contacts/contact_1");- await refreshed.promise;- const stopped = Object.assign(new Error("turn ended"), { status: 409 });- const pending = client.withActiveCall(() => {- expect(new HighLevelStore({ dataDir: dir }).get()?.accessToken).toBe(relay.issued.at(-1));- throw stopped;- }, () => client.request("GET", "/contacts/contact_2")).catch((error: unknown) => error);- resume.resolve();- await expect(live).resolves.toMatchObject({ contact: { id: "contact_1" } });- expect(await pending).toBe(stopped);- expect(relay.refreshes).toBe(1);- expect(hl.calls).toHaveLength(1);- expect(new HighLevelStore({ dataDir: dir }).get()).toMatchObject({- accessToken: relay.issued.at(-1), state: "signed-in",- });- });-- it("refreshes once through the relay on a 401, retries with the new token and keeps the rotated pair", async () => {- const { client, store, dir } = harness();- hl.tokens.delete("hl_access_seed");- const contact = await client.getContact("contact_1");- expect(contact.id).toBe("contact_1");- expect(relay.refreshes).toBe(1);- expect(relay.calls.at(-1)).toEqual({ path: "/v1/highlevel/refresh", body: { refreshToken: "hl_refresh_seed" } });- const bearers = hl.calls.filter((call) => call.path === "/contacts/contact_1").map((call) => call.headers.authorization);- expect(bearers).toEqual(["Bearer hl_access_seed", `Bearer ${relay.issued.at(-1)}`]);- const saved = new HighLevelStore({ dataDir: dir }).get()!;- expect(saved.accessToken).toBe(relay.issued.at(-1));- expect(saved.refreshToken).toMatch(/^hl_refresh_\d+$/u);- expect(saved.refreshToken).not.toBe("hl_refresh_seed");- expect(saved.expiresAt).toBe(clock + 86_400_000);- expect(store.get()?.state).toBe("signed-in");- // Mutation check: a client that forgot to persist the rotation would still hold the spent refresh token.- hl.tokens.delete(saved.accessToken);- await client.getContact("contact_1");- expect(relay.refreshes).toBe(2);- expect(relay.calls.at(-1)).toEqual({ path: "/v1/highlevel/refresh", body: { refreshToken: saved.refreshToken } });- });-- it("drops a refresh that finishes after another account was connected, keeping that account's credentials", async () => {- const pending = deferred<RelayTokens>();- let asked = 0;- const { client, store } = harness({ expiresAt: clock + 30_000 }, { refresh: () => { asked++; return pending.promise; } });- const call = client.listPipelines();- await settle();- expect(asked).toBe(1);- hl.tokens.add("pit-account-b-token");- store.put({ kind: "token", accessToken: "pit-account-b-token", locationId: "loc_account_b", locationName: "Account B", scopes: "" });- pending.resolve({ accessToken: "hl_access_late", refreshToken: "hl_refresh_late", expiresIn: 86_400, scope: "", locationId: FAKE_LOCATION_ID });- await expect(call).rejects.toMatchObject({ signedOut: false, message: expect.stringMatching(/connection changed/u) });- expect(store.get()).toMatchObject({ kind: "token", accessToken: "pit-account-b-token", locationId: "loc_account_b", state: "signed-in" });- expect(store.get()?.refreshToken).toBeUndefined();- expect(hl.calls.filter((call) => call.path === "/opportunities/pipelines")).toHaveLength(0);- });-- it("does not sign out an account connected while the previous account's refresh was being rejected", async () => {- const pending = deferred<RelayTokens>();- const { client, store } = harness({ expiresAt: clock + 30_000 }, { refresh: () => pending.promise });- const call = client.listPipelines();- await settle();- hl.tokens.add("pit-account-b-token");- store.put({ kind: "token", accessToken: "pit-account-b-token", locationId: "loc_account_b", scopes: "" });- pending.reject(new HighLevelRelayError(401, "highlevel_refresh_rejected", "rejected"));- await expect(call).rejects.toMatchObject({ signedOut: false, message: expect.stringMatching(/connection changed/u) });- expect(store.get()).toMatchObject({ accessToken: "pit-account-b-token", state: "signed-in" });- expect(store.get()?.problem).toBeUndefined();- });-- it("retries a call for the same location with the new sign-in when it changed during the refresh", async () => {- const pending = deferred<RelayTokens>();- const { client, store } = harness({ expiresAt: clock + 30_000 }, { refresh: () => pending.promise });- const call = client.listPipelines();- await settle();- hl.tokens.add("hl_access_reconnected");- store.put({ kind: "oauth", accessToken: "hl_access_reconnected", refreshToken: "hl_refresh_reconnected", expiresAt: clock + 3_600_000, locationId: FAKE_LOCATION_ID, scopes: "" });- pending.resolve({ accessToken: "hl_access_late", refreshToken: "hl_refresh_late", expiresIn: 86_400, scope: "", locationId: FAKE_LOCATION_ID });- expect((await call).pipelines).toHaveLength(1);- expect(last().headers.authorization).toBe("Bearer hl_access_reconnected");- expect(store.get()).toMatchObject({ accessToken: "hl_access_reconnected", refreshToken: "hl_refresh_reconnected", state: "signed-in" });- });-- it("reuses the tokens another call already refreshed when a stale 401 arrives late", async () => {- const gate = deferred();- const { client, store } = harness({}, {- fetch: async (url, init) => {- const bearer = new Headers(init?.headers).get("authorization");- if (String(url).includes("/contacts/contact_slow") && bearer === "Bearer hl_access_seed") await gate.promise;- return fetch(url, init);- },- });- hl.tokens.delete("hl_access_seed");- const slow = client.getContact("contact_slow");- await settle();- expect((await client.getContact("contact_fast")).id).toBe("contact_fast");- expect(relay.refreshes).toBe(1);- const refreshed = store.get()!;- gate.resolve();- expect((await slow).id).toBe("contact_slow");- expect(relay.refreshes).toBe(1);- expect(store.get()).toMatchObject({ accessToken: refreshed.accessToken, refreshToken: refreshed.refreshToken, state: "signed-in" });- const bearers = hl.calls.filter((call) => call.path === "/contacts/contact_slow").map((call) => call.headers.authorization);- expect(bearers).toEqual(["Bearer hl_access_seed", `Bearer ${refreshed.accessToken}`]);- });-- it("does not sign out a refreshed connection when a stale 401 for the old token arrives after the retry", async () => {- const { client, store } = harness({ kind: "token", accessToken: "pit-old-token-123", refreshToken: undefined, expiresAt: undefined }, {- fetch: async (url, init) => {- if (String(url).includes("/contacts/contact_slow")) {- hl.tokens.add("pit-new-token-456");- store.put({ kind: "token", accessToken: "pit-new-token-456", locationId: FAKE_LOCATION_ID, scopes: "" });- }- return fetch(url, init);- },- });- hl.tokens.delete("pit-old-token-123");- expect((await client.getContact("contact_slow")).id).toBe("contact_slow");- expect(store.get()).toMatchObject({ accessToken: "pit-new-token-456", state: "signed-in" });- });-- it("still refreshes a same-location connection adopted while a call waited, when its token is dead too", async () => {- let adopted = false;- const { client, store } = harness({}, {- fetch: async (url, init) => {- if (!adopted) {- adopted = true;- hl.tokens.delete("hl_access_seed");- relay.refreshTokens.add("hl_refresh_adopted");- store.put({ kind: "oauth", accessToken: "hl_access_adopted", refreshToken: "hl_refresh_adopted", expiresAt: clock + 3_600_000, locationId: FAKE_LOCATION_ID, scopes: "" });- }- return fetch(url, init);- },- });- expect((await client.listPipelines()).pipelines).toHaveLength(1);- expect(relay.refreshes).toBe(1);- expect(relay.calls.at(-1)).toEqual({ path: "/v1/highlevel/refresh", body: { refreshToken: "hl_refresh_adopted" } });- expect(store.get()).toMatchObject({ accessToken: relay.issued.at(-1), state: "signed-in" });- });-- it("stops with the changed-connection error when another location is connected after the refresh", async () => {- const { client, store } = harness({}, {- fetch: async (url, init) => {- const bearer = new Headers(init?.headers).get("authorization");- if (bearer === `Bearer ${relay.issued.at(-1)}` && store.get()?.kind === "oauth") {- hl.tokens.delete(relay.issued.at(-1)!);- hl.tokens.add("pit-account-b-token");- store.put({ kind: "token", accessToken: "pit-account-b-token", locationId: "loc_account_b", scopes: "" });- }- return fetch(url, init);- },- });- hl.tokens.delete("hl_access_seed");- await expect(client.listPipelines()).rejects.toMatchObject({ status: 409, signedOut: false, message: expect.stringMatching(/connection changed/u) });- expect(relay.refreshes).toBe(1);- expect(store.get()).toMatchObject({ accessToken: "pit-account-b-token", state: "signed-in" });- });-- it("gives up when the sign-in keeps changing under a call, without signing the newest one out", async () => {- let dispatched = 0;- const { client, store } = harness({}, {- fetch: async (url, init) => {- if (++dispatched > 20) throw new Error("fixture cutoff");- hl.tokens.clear();- store.put({ kind: "oauth", accessToken: `hl_access_churn_${dispatched}`, refreshToken: `hl_refresh_churn_${dispatched}`, expiresAt: clock + 3_600_000, locationId: FAKE_LOCATION_ID, scopes: "" });- return fetch(url, init);- },- });- await expect(client.listPipelines()).rejects.toMatchObject({ status: 503, signedOut: false, message: expect.stringMatching(/kept changing/u) });- expect(dispatched).toBeLessThanOrEqual(4);- expect(relay.refreshes).toBe(0);- expect(store.get()?.state).toBe("signed-in");- });-- it("reports the changed location even after the call followed the sign-in as often as it may", async () => {- let dispatched = 0;- const { client, store } = harness({}, {- fetch: async (url, init) => {- dispatched++;- hl.tokens.clear();- const elsewhere = dispatched === 4;- store.put({ kind: "oauth", accessToken: `hl_access_churn_${dispatched}`, refreshToken: `hl_refresh_churn_${dispatched}`, expiresAt: clock + 3_600_000, locationId: elsewhere ? "loc_account_b" : FAKE_LOCATION_ID, scopes: "" });- return fetch(url, init);- },- });- await expect(client.listPipelines()).rejects.toMatchObject({ status: 409, message: expect.stringMatching(/connection changed/u) });- expect(dispatched).toBe(4);- });-- it("refreshes ahead of expiry without waiting for a 401", async () => {- const { client } = harness({ expiresAt: clock + 30_000 });- await client.listPipelines();- expect(relay.refreshes).toBe(1);- expect(hl.calls.filter((call) => call.path === "/opportunities/pipelines")).toHaveLength(1);- expect(last().headers.authorization).toBe(`Bearer ${relay.issued.at(-1)}`);- });-- it("marks the store needs-sign-in and answers the signed-out note when the relay rejects the refresh", async () => {- const { client, store } = harness({ refreshToken: "hl_refresh_revoked" });- hl.tokens.delete("hl_access_seed");- await expect(client.getContact("contact_1")).rejects.toMatchObject({ message: HIGHLEVEL_SIGNED_OUT_TEXT, signedOut: true });- expect(store.get()).toMatchObject({ state: "needs-sign-in", problem: expect.stringMatching(/rejected the saved sign-in/u) });- // Signed out: no further API or relay calls until a person reconnects.- const calls = hl.calls.length;- await expect(client.getContact("contact_1")).rejects.toMatchObject({ signedOut: true });- expect(hl.calls.length).toBe(calls);- expect(relay.refreshes).toBe(1);- });-- it("never refreshes a Private Integration token: a 401 signs it out", async () => {- const { client, store } = harness({ kind: "token", accessToken: "pit-fixture-token-123", refreshToken: undefined, expiresAt: undefined });- hl.tokens.delete("pit-fixture-token-123");- await expect(client.getContact("contact_1")).rejects.toMatchObject({ signedOut: true });- expect(relay.refreshes).toBe(0);- expect(store.get()?.state).toBe("needs-sign-in");- });-- it("waits per the rate-limit headers (capped at 10 s) and retries once on 429", async () => {- const { client } = harness();- hl.overrides.push({ status: 429, headers: { "retry-after": "3" }, body: { message: "Too many requests" } });- await client.getContact("contact_1");- expect(slept).toEqual([3_000]);- hl.overrides.push({ status: 429, headers: { "x-ratelimit-interval-milliseconds": "60000" } }, { status: 429 });- await expect(client.getContact("contact_1")).rejects.toThrow("HighLevel is rate-limiting; try again in a few seconds.");- expect(slept).toEqual([3_000, 10_000]);- });-- it("retries a 5xx once and then gives one plain sentence", async () => {- const { client } = harness();- hl.overrides.push({ status: 503 });- expect((await client.getContact("contact_1")).id).toBe("contact_1");- hl.overrides.push({ status: 502 }, { status: 502 });- await expect(client.getContact("contact_1")).rejects.toThrow("HighLevel is having trouble (502); try again in a minute.");- });-- it("never replays a create after a 5xx: HighLevel may have saved it", async () => {- const { client } = harness();- const posts = (path: string) => hl.calls.filter((call) => call.method === "POST" && call.path === path).length;- hl.overrides.push({ status: 502 });- await expect(client.addNote("contact_1", "Left voicemail")).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/may have been saved anyway/u) });- expect(posts("/contacts/contact_1/notes")).toBe(1);- hl.overrides.push({ status: 500 });- await expect(client.addTask("contact_1", { title: "Follow up", dueDate: "2026-03-12T09:00:00.000Z" })).rejects.toThrow(/task.+may have been saved anyway/u);- expect(posts("/contacts/contact_1/tasks")).toBe(1);- hl.overrides.push({ status: 503 });- await expect(client.createOpportunity({ pipelineId: "pipe_1", contactId: "contact_1", name: "Deal" })).rejects.toThrow(/opportunity.+may have been saved anyway/u);- expect(posts("/opportunities/")).toBe(1);- // A search and adding tags are safe to send twice, so they still retry.- hl.overrides.push({ status: 503 });- expect((await client.searchContacts({ query: "ada" })).contacts).toHaveLength(1);- expect(posts("/contacts/search")).toBe(2);- hl.overrides.push({ status: 503 });- expect((await client.addTags("contact_1", ["a"])).tags).toEqual(["a"]);- expect(posts("/contacts/contact_1/tags")).toBe(2);- });-- it("says a create may have been saved when HighLevel's answer is lost", async () => {- const { client } = harness({}, { fetch: async () => { throw new TypeError("socket hang up"); } });- await expect(client.addNote("contact_1", "x")).rejects.toMatchObject({ status: 503, message: expect.stringMatching(/may have been saved anyway/u) });- await expect(client.getContact("contact_1")).rejects.toThrow("HighLevel did not answer (the request timed out or the network failed); try again in a minute.");- });-- it("refuses an answer over 4 MB counted in bytes, and stops reading it there", async () => {- const wide = harness({}, { fetch: async () => new Response(JSON.stringify({ contact: { id: "contact_1", name: "é".repeat(2_500_000) } }), { status: 200 }) });- await expect(wide.client.getContact("contact_1")).rejects.toThrow("HighLevel's answer was too large to read; narrow the request.");- let pulled = 0;- let cancelled = false;- const endless = harness({}, { fetch: async () => new Response(new ReadableStream<Uint8Array>({- pull(controller) { if (++pulled > 20) controller.close(); else controller.enqueue(new Uint8Array(1_000_000)); },- cancel() { cancelled = true; },- }), { status: 200 }) });- await expect(endless.client.getContact("contact_1")).rejects.toThrow(/too large to read/u);- expect(cancelled).toBe(true);- expect(pulled).toBeLessThan(10);- });-- it("says a create may have been saved when HighLevel fails with an answer over 4 MB, without reading it", async () => {- let pulled = 0;- let cancelled = false;- const { client } = harness({}, { fetch: async () => new Response(new ReadableStream<Uint8Array>({- pull(controller) { if (++pulled > 20) controller.close(); else controller.enqueue(new Uint8Array(1_000_000)); },- cancel() { cancelled = true; },- }), { status: 502 }) });- await expect(client.addNote("contact_1", "x")).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/may have been saved anyway/u) });- expect(cancelled).toBe(true);- expect(pulled).toBeLessThan(2);- });-- it("retries a read once when HighLevel fails with an answer over 4 MB, without reading it", async () => {- let pulled = 0;- let cancelled = false;- let calls = 0;- const { client } = harness({}, { fetch: async (input, init) => ++calls > 1 ? fetch(input, init) : new Response(new ReadableStream<Uint8Array>({- pull(controller) { if (++pulled > 20) controller.close(); else controller.enqueue(new Uint8Array(1_000_000)); },- cancel() { cancelled = true; },- }), { status: 502 }) });- expect((await client.getContact("contact_1")).id).toBe("contact_1");- expect(hl.calls.filter((call) => call.path === "/contacts/contact_1")).toHaveLength(1);- expect(slept).toEqual([1_000]);- expect(cancelled).toBe(true);- expect(pulled).toBeLessThan(2);- });-- it("says a create may have been saved when HighLevel's answer breaks off after the headers", async () => {- let status = 201;- const broken = () => new Response(new ReadableStream<Uint8Array>({ pull(controller) { controller.error(new TypeError("terminated")); } }), { status });- const { client } = harness({}, { fetch: async () => broken() });- await expect(client.addNote("contact_1", "x")).rejects.toMatchObject({ status: 503, message: expect.stringMatching(/may have been saved anyway/u) });- status = 502;- await expect(client.addNote("contact_1", "x")).rejects.toMatchObject({ status: 502, message: expect.stringMatching(/may have been saved anyway/u) });- status = 200;- await expect(client.listPipelines()).rejects.toMatchObject({ status: 503, message: "HighLevel did not answer (the request timed out or the network failed); try again in a minute." });- });-- it("keeps under 90 calls per 10 s per location", async () => {- const { client } = harness();- for (let i = 0; i < BUDGET_CALLS; i++) await client.listPipelines();- expect(slept).toEqual([]);- await client.listPipelines();- expect(slept).toEqual([10_000]);- });-- it("turns refusals into plain sentences that name the missing permission or the record", async () => {- const { client } = harness();- hl.overrides.push({ status: 403, body: { message: "The token does not have access to this resource." } });- await expect(client.addNote("contact_1", "x")).rejects.toThrow("HighLevel refused this (403): the connection lacks the contacts.write permission. HighLevel said: The token does not have access to this resource.");- await expect(client.getContact("missing")).rejects.toThrow("HighLevel has no contact with that id (404).");- hl.overrides.push({ status: 422, body: { message: ["email must be an email", "phone is invalid"] } });- await expect(client.createContact({ email: "nope" })).rejects.toThrow("HighLevel rejected this (422): email must be an email; phone is invalid");- expect(plainError(403, "GET", "/opportunities/search", {}).message).toBe("HighLevel refused this (403): the connection lacks the opportunities.readonly permission.");- expect(plainError(404, "GET", "/opportunities/x", {}).message).toBe("HighLevel has no opportunity with that id (404).");- });-- it("answers the not-connected note when nothing is stored", async () => {- const { client, store } = harness();- store.clear();- await expect(client.getContact("contact_1")).rejects.toMatchObject({ message: HIGHLEVEL_NOT_CONNECTED_TEXT, signedOut: true });- });-});--describe("no messaging through the CRM", () => {- it("has no method that sends, campaigns, automates or charges, and refuses those paths at the request layer", () => {- const methods = Object.getOwnPropertyNames(HighLevelClient.prototype).filter((name) => name !== "constructor");- expect(methods.filter((name) => /send|message|campaign|workflow|payment|invoice|email|sms|whatsapp|delete|remove(?!Tags)/iu.test(name))).toEqual([]);- for (const [method, path] of [- ["POST", "/conversations/messages"], ["POST", "/conversations/messages/inbound"], ["PUT", "/conversations/conv_1"], ["DELETE", "/conversations/conv_1"],- ["POST", "/campaigns/x/contacts"], ["POST", "/contacts/c/campaigns/x"], ["POST", "/contacts/c/workflow/w"], ["POST", "/payments/orders"],- ["POST", "/calendars/events/appointments"], ["DELETE", "/contacts/c"], ["DELETE", "/opportunities/o"], ["PUT", "/locations/l"], ["POST", "/emails/builder"],- ] as const) {- expect(() => assertAllowedPath(method, path), `${method} ${path}`).toThrow(HighLevelError);- }- expect(FORBIDDEN_PATHS.some((pattern) => pattern.test("/conversations/messages"))).toBe(true);- for (const [method, path] of [["GET", "/contacts/c"], ["POST", "/contacts/"], ["DELETE", "/contacts/c/tags"], ["GET", "/conversations/c/messages"], ["GET", "/calendars/events"]] as const) {- expect(() => assertAllowedPath(method, path)).not.toThrow();- }- });-- it("lists exactly the twenty tools and none of them reaches a send endpoint", async () => {- expect(HIGHLEVEL_TOOLS.map((tool) => tool.name)).toEqual([...HIGHLEVEL_TOOL_NAMES]);- expect(HIGHLEVEL_TOOLS.map((tool) => tool.name).filter((name) => /SEND|MESSAGE|CAMPAIGN|WORKFLOW|PAY|DELETE/u.test(name))).toEqual([]);- const { client } = harness();- const sample: Record<string, Record<string, unknown>> = {- HIGHLEVEL_SEARCH_CONTACTS: { query: "ada" }, HIGHLEVEL_GET_CONTACT: { contactId: "contact_1" }, HIGHLEVEL_CREATE_CONTACT: { email: "[email protected]" },- HIGHLEVEL_UPDATE_CONTACT: { contactId: "contact_1", city: "Austin" }, HIGHLEVEL_ADD_TAGS: { contactId: "contact_1", tags: ["a"] }, HIGHLEVEL_REMOVE_TAGS: { contactId: "contact_1", tags: ["a"] },- HIGHLEVEL_LIST_NOTES: { contactId: "contact_1" }, HIGHLEVEL_ADD_NOTE: { contactId: "contact_1", body: "n" }, HIGHLEVEL_LIST_TASKS: { contactId: "contact_1" },- HIGHLEVEL_ADD_TASK: { contactId: "contact_1", title: "t", dueDate: "2026-03-12T09:00:00Z" }, HIGHLEVEL_LIST_PIPELINES: {}, HIGHLEVEL_SEARCH_OPPORTUNITIES: {},- HIGHLEVEL_GET_OPPORTUNITY: { opportunityId: "opp_1" }, HIGHLEVEL_CREATE_OPPORTUNITY: { pipelineId: "pipe_1", contactId: "contact_1", name: "d" },- HIGHLEVEL_UPDATE_OPPORTUNITY: { opportunityId: "opp_1", status: "won" }, HIGHLEVEL_SEARCH_CONVERSATIONS: {}, HIGHLEVEL_READ_CONVERSATION: { conversationId: "conv_1" },- HIGHLEVEL_LIST_CALENDARS: {}, HIGHLEVEL_LIST_EVENTS: { startTime: "2026-03-10T00:00:00Z", endTime: "2026-03-11T00:00:00Z" }, HIGHLEVEL_GET_LOCATION: {},- };- for (const name of HIGHLEVEL_TOOL_NAMES) {- const { result } = await runHighLevelTool(client, name, sample[name]!);- expect(result.isError, name).toBeUndefined();- }- for (const call of hl.calls) {- expect(call.path, `${call.method} ${call.path}`).not.toMatch(/campaigns|workflow|payments/u);- if (call.path.includes("messages")) expect(call.method, call.path).toBe("GET");- if (call.path.startsWith("/conversations")) expect(call.method).toBe("GET");- }- expect(hl.calls.some((call) => call.method === "POST" && call.path.startsWith("/conversations"))).toBe(false);- });-});--// HighLevel's real answers: a dead token, a live token missing a scope, a token from another location.-const INVALID_TOKEN = { statusCode: 401, message: "Invalid JWT" };-const MISSING_SCOPE = { statusCode: 401, message: "The token is not authorized for this scope.", error: "Unauthorized" };-const OTHER_LOCATION = { statusCode: 403, message: "The token does not have access to this location." };-const CUSTOM_FIELDS = `GET /locations/${FAKE_LOCATION_ID}/customFields`;--describe("a missing permission is not a sign-out", () => {- it("tells a scope refusal from a dead token by HighLevel's own words", () => {- expect(isScopeRefusal(MISSING_SCOPE)).toBe(true);- expect(isScopeRefusal({ message: "insufficient_scope" })).toBe(true);- expect(isScopeRefusal(INVALID_TOKEN)).toBe(false);- expect(isScopeRefusal({ statusCode: 401, message: "Invalid token: access token is invalid", error: "Unauthorized" })).toBe(false);- expect(isScopeRefusal({})).toBe(false);- expect(plainError(401, "GET", `/locations/${FAKE_LOCATION_ID}/customFields`, MISSING_SCOPE)).toMatchObject({- message: "HighLevel refused this (401): the connection lacks the View Custom Fields permission (locations/customFields.readonly). HighLevel said: The token is not authorized for this scope.",- signedOut: false, status: 401,- });- expect(plainError(401, "GET", "/contacts/c", INVALID_TOKEN)).toMatchObject({ message: HIGHLEVEL_SIGNED_OUT_TEXT, signedOut: true });- });-- it("keeps a token connection signed in when only the custom-fields lookup inside a contact read is refused", async () => {- const { client, store } = harness({ kind: "token", accessToken: "pit-fixture-token-123", refreshToken: undefined, expiresAt: undefined });- hl.pathOverrides.set(CUSTOM_FIELDS, { status: 401, body: MISSING_SCOPE });- const contact = await client.getContact("contact_1");- expect(contact).toMatchObject({ id: "contact_1", email: "[email protected]", customFields: { cf_lead: "Referral", cf_budget: 1200 } });- expect(store.get()).toMatchObject({ state: "signed-in" });- expect(store.get()?.problem).toBeUndefined();- // The refusal is remembered for the cache's lifetime: later reads do not ask again.- await client.getContact("contact_1");- expect((await client.searchContacts({ query: "ada" })).contacts[0]).toMatchObject({ id: "contact_1" });- expect(hl.calls.filter((call) => call.path.endsWith("/customFields"))).toHaveLength(1);- expect((await client.getLocation()).customFields).toEqual([]);- // A write that names a custom field says which permission is missing, not that the field does not exist.- await expect(client.updateContact("contact_1", { customFields: { "Lead Source": "Event" } })).rejects.toMatchObject({- message: expect.stringMatching(/^HighLevel refused this \(401\): the connection lacks the View Custom Fields permission/u), signedOut: false,- });- expect(store.get()?.state).toBe("signed-in");- // Through the tool layer: the bot gets a plain error, not the signed-out note.- const { result } = await runHighLevelTool(client, "HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" });- expect(result.isError).toBeUndefined();- });-- it("keeps an OAuth connection signed in on a scope refusal, without spending a refresh", async () => {- const { client, store } = harness();- hl.pathOverrides.set(CUSTOM_FIELDS, { status: 401, body: MISSING_SCOPE });- expect((await client.getContact("contact_1")).id).toBe("contact_1");- expect(relay.refreshes).toBe(0);- expect(store.get()?.state).toBe("signed-in");- });-- it("answers a scope refusal on the call itself with the missing permission, still signed in", async () => {- const { client, store } = harness({ kind: "token", accessToken: "pit-fixture-token-123", refreshToken: undefined, expiresAt: undefined });- hl.pathOverrides.set("POST /contacts/contact_1/notes", { status: 401, body: MISSING_SCOPE });- const { result } = await runHighLevelTool(client, "HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "x" });- expect(result).toMatchObject({ isError: true, structuredContent: {- error: "HighLevel refused this (401): the connection lacks the Edit Contacts permission (contacts.write). HighLevel said: The token is not authorized for this scope.",- status: 401,- } });- expect(result.structuredContent?.signedOut).toBeUndefined();- expect(store.get()?.state).toBe("signed-in");- });-- it("still signs a token out when HighLevel rejects the token itself, on the main call or the custom-fields lookup", async () => {- const dead = harness({ kind: "token", accessToken: "pit-fixture-dead-123", refreshToken: undefined, expiresAt: undefined });- hl.tokens.delete("pit-fixture-dead-123");- await expect(dead.client.getContact("contact_1")).rejects.toMatchObject({ message: HIGHLEVEL_SIGNED_OUT_TEXT, signedOut: true });- expect(dead.store.get()).toMatchObject({ state: "needs-sign-in", problem: "HighLevel rejected the Private Integration token." });-- // Revoked between the two calls: the optional lookup's 401 is not a scope refusal, so it signs out.- const revoked = harness({ kind: "token", accessToken: "pit-fixture-revoked-1", refreshToken: undefined, expiresAt: undefined });- hl.pathOverrides.set(CUSTOM_FIELDS, { status: 401, body: INVALID_TOKEN });- await revoked.client.getContact("contact_1");- expect(revoked.store.get()?.state).toBe("needs-sign-in");- await expect(revoked.client.getContact("contact_1")).rejects.toMatchObject({ signedOut: true });- });-- it("still refreshes an OAuth token on a dead-token 401", async () => {- const { client, store } = harness();- hl.overrides.push({ status: 401, body: INVALID_TOKEN });- expect((await client.getContact("contact_1")).id).toBe("contact_1");- expect(relay.refreshes).toBe(1);- expect(store.get()?.state).toBe("signed-in");- });-});--describe("lookupLocation", () => {- it("validates a Private Integration token against its location and returns the name", async () => {- hl.tokens.add("pit-valid-token-123");- expect(await lookupLocation({ token: "pit-valid-token-123", locationId: FAKE_LOCATION_ID, apiUrl: hl.url })).toEqual({ id: FAKE_LOCATION_ID, name: "Example Profiles", companyId: "company_1", timezone: "America/Chicago" });- expect(last().headers.version).toBe(HIGHLEVEL_VERSION);- await expect(lookupLocation({ token: "pit-valid-token-123", locationId: "other_location", apiUrl: hl.url })).rejects.toMatchObject({ status: 403, message: expect.stringMatching(/^This token does not belong to that location \(403\)/u) });- await expect(lookupLocation({ token: "pit-bad", locationId: FAKE_LOCATION_ID, apiUrl: hl.url })).rejects.toMatchObject({ status: 401, message: expect.stringMatching(/^HighLevel did not accept this token \(401\)/u) });- hl.pathOverrides.set(`GET /locations/${FAKE_LOCATION_ID}`, { status: 401, body: MISSING_SCOPE });- await expect(lookupLocation({ token: "pit-valid-token-123", locationId: FAKE_LOCATION_ID, apiUrl: hl.url })).rejects.toMatchObject({ status: 401, message: expect.stringMatching(/^This token is missing the View Locations permission/u) });- });-- const TOKEN = "pit-0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0";- const answering = (status: number, body?: unknown): typeof fetch => async () => new Response(body === undefined ? "" : JSON.stringify(body), { status, headers: { "content-type": "application/json" } });- const check = async (status: number, body?: unknown) => {- const error = await lookupLocation({ token: TOKEN, locationId: FAKE_LOCATION_ID, apiUrl: "https://hl.fixture.test", fetch: answering(status, body) }).then(() => null, (cause: unknown) => cause);- expect(error).toBeInstanceOf(HighLevelError);- expect((error as HighLevelError).signedOut).toBe(false);- expect((error as HighLevelError).message).not.toContain(TOKEN);- return error as HighLevelError;- };-- it("says which case a refusal is, in plain words, with HighLevel's own reason when it gave one", async () => {- expect(await check(401, MISSING_SCOPE)).toMatchObject({ status: 401, message:- "This token is missing the View Locations permission (401), which OpenMausBot needs to check it. In HighLevel, open Settings → Private Integrations, " +- "edit this integration, turn on View Locations and save, then connect again: the token stays the same. HighLevel said: The token is not authorized for this scope." });- expect(await check(401, INVALID_TOKEN)).toMatchObject({ status: 401, message:- "HighLevel did not accept this token (401). Check that it was copied whole and has not been rotated or deleted, " +- "and that its Private Integration has the View Locations permission. HighLevel said: Invalid JWT" });- expect((await check(401)).message).toBe(- "HighLevel did not accept this token (401). Check that it was copied whole and has not been rotated or deleted, " +- "and that its Private Integration has the View Locations permission.");- expect(await check(403, OTHER_LOCATION)).toMatchObject({ status: 403, message:- "This token does not belong to that location (403): it was created in another sub-account or at the agency level. " +- "Create the Private Integration inside the sub-account whose location ID you entered. HighLevel said: The token does not have access to this location." });- expect((await check(403, {})).message).toBe(- "This token does not belong to that location (403): it was created in another sub-account or at the agency level. " +- "Create the Private Integration inside the sub-account whose location ID you entered.");- expect(await check(404, { statusCode: 404, message: "Location not found" })).toMatchObject({ status: 404, message:- "HighLevel has no location with that ID (404). Copy the location ID from Settings → Business Profile in the sub-account where you created the token." });- expect((await check(422, { statusCode: 422, message: ["locationId must be a string"] })).message).toBe("HighLevel rejected this (422): locationId must be a string");- });-- it("never repeats the token, or anything shaped like one, and keeps HighLevel's reason to one short line", async () => {- const echoed = await check(401, { message: `Invalid JWT ${TOKEN} (Bearer ${TOKEN}); also pit-abcdefgh1234 and eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0.c2ln` });- expect(echoed.message).toMatch(/HighLevel said: Invalid JWT \[redacted\] \(Bearer \[redacted\]\); also \[redacted\] and \[redacted\]$/u);- expect(echoed.message).not.toMatch(/pit-|eyJ|0f1e2d3c/u);- const long = await check(403, { message: `line one\nline\ttwo ${"x".repeat(400)}` });- const said = long.message.split("HighLevel said: ")[1]!;- expect(said.startsWith("line one line two x")).toBe(true);- expect(said).toHaveLength(160);- expect(said.endsWith("…")).toBe(true);- // The exact secret goes even when it has no token shape (an OAuth access token need not look like one).- expect(redactSecrets("token opaque-secret-42 was refused", ["opaque-secret-42"])).toBe("token [redacted] was refused");- expect(redactSecrets("Bearer token is missing")).toBe("Bearer token is missing");- // A token split across the cut is redacted before cutting, so no fragment survives.- const cut = await check(401, { message: `${"y".repeat(150)} ${TOKEN}` });- expect(cut.message).not.toMatch(/pit-|0f1e/u);- });-});diff --git a/server/highlevel/client.ts b/server/highlevel/client.tsdeleted file mode 100644index 4251da279c..0000000000--- a/server/highlevel/client.ts+++ /dev/null@@ -1,774 +0,0 @@-// One function per HighLevel endpoint a bot may reach, with inputs typed and outputs trimmed to what a person cares-// about. The client itself cannot address a message, campaign, workflow or payment endpoint: that guard is here, not-// in the tool list, so no later tool can grow a path to them.-import { AsyncLocalStorage } from "node:async_hooks";-import { HIGHLEVEL_NOT_CONNECTED_TEXT, HIGHLEVEL_SIGNED_OUT_TEXT } from "./instructions.ts";-import { HighLevelRelayError, type RelayTokens } from "./relay.ts";-import { sameTokens, type HighLevelConnection, type HighLevelStore } from "./store.ts";--export const HIGHLEVEL_API_URL = "https://services.leadconnectorhq.com";-export const HIGHLEVEL_API_ENV = "OMB_HIGHLEVEL_API_URL";-export const HIGHLEVEL_VERSION = "2021-07-28";-export const HIGHLEVEL_CONVERSATIONS_VERSION = "2021-04-15";--/** Client-side budget under HighLevel's 100 requests / 10 s per location. */-export const BUDGET_CALLS = 90;-export const BUDGET_WINDOW_MS = 10_000;-const BACKOFF_MAX_MS = 10_000;-const REFRESH_MARGIN_MS = 60_000;-const MAX_SUCCESSORS = 3;-const REQUEST_TIMEOUT_MS = 30_000;-const MAX_RESPONSE_BYTES = 4_000_000;-const CUSTOM_FIELDS_TTL_MS = 10 * 60_000;-const TEXT_MAX = 4_000;-export const PAGE_MAX = 50;-export const PAGE_NUMBER_MAX = 1_000;--/** Paths this client refuses outright, whatever tool asks: nothing here sends, campaigns, automates or charges. */-export const FORBIDDEN_PATHS = [- /\/conversations\/messages/u,- /\/conversations\/[^/]+\/messages\/[^/]+/u,- /\/campaigns/u,- /\/workflows?\//u,- /\/workflows?$/u,- /\/payments/u,- /\/emails/u,- /\/sms/u,- /\/whatsapp/u,- /\/invoices/u,- /\/funnels/u,- /\/forms/u,- /\/surveys/u,- /\/social-media-posting/u,- /\/marketplace/u,-] as const;--export class HighLevelError extends Error {- readonly status: number | undefined;- /** The connection needs a new sign-in: the tool answer tells the bot to ask the person and end the turn. */- readonly signedOut: boolean;- constructor(message: string, options: { status?: number; signedOut?: boolean } = {}) {- super(message);- this.name = "HighLevelError";- this.status = options.status;- this.signedOut = options.signedOut === true;- }-}--export interface HighLevelClientOptions {- store: HighLevelStore;- /** Refresh through the relay; null when no relay is configured (a Private Integration token never refreshes). */- refresh: ((refreshToken: string) => Promise<RelayTokens>) | null;- apiUrl?: string;- fetch?: typeof fetch;- now?: () => number;- sleep?: (ms: number) => Promise<void>;-}--type Query = Record<string, string | number | undefined>;-type Json = Record<string, unknown>;-interface RequestOptions {- query?: Query; body?: unknown; version?: string;- /** A POST HighLevel may receive twice with the same result (a search, adding tags). HighLevel takes no idempotency key. */- repeatable?: boolean;-}--const repeatable = (method: string, options: RequestOptions): boolean => method !== "POST" || options.repeatable === true;--function unknownOutcome(path: string, cause: string, status: number): HighLevelError {- return new HighLevelError(`${cause}, and the ${thing(path)} may have been saved anyway. Check before trying again, so it is not added twice.`, { status });-}--const isRecord = (value: unknown): value is Json => Boolean(value) && typeof value === "object" && !Array.isArray(value);-const str = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value.slice(0, TEXT_MAX) : undefined);-const num = (value: unknown): number | undefined => (typeof value === "number" && Number.isFinite(value) ? value : undefined);-const bool = (value: unknown): boolean | undefined => (typeof value === "boolean" ? value : undefined);-const list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isRecord) : []);-const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === "string").slice(0, 200) : []);-/** Drops undefined fields so trimmed objects stay small. */-const compact = <T extends object>(record: T): T => Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;-const pageSize = (value: number | undefined) => Math.min(PAGE_MAX, Math.max(1, Math.floor(value ?? 20)));-const pageNumber = (value: number | undefined) => Math.min(PAGE_NUMBER_MAX, Math.max(1, Math.floor(value ?? 1)));--export interface CustomFieldDefinition { id: string; name: string; key?: string; dataType?: string; model?: string; options?: string[] }--export interface ContactFields {- firstName?: string; lastName?: string; name?: string; email?: string; phone?: string; companyName?: string;- tags?: string[]; source?: string; address1?: string; city?: string; state?: string; postalCode?: string; country?: string;- website?: string; timezone?: string; assignedTo?: string; dateOfBirth?: string;- /** By custom field name or key; the client maps names to ids. */- customFields?: Record<string, unknown>;-}--export interface TrimmedContact {- id: string; name?: string; firstName?: string; lastName?: string; email?: string; phone?: string; companyName?: string;- tags: string[]; source?: string; assignedTo?: string; dateAdded?: string; dateUpdated?: string; website?: string; timezone?: string;- dnd?: boolean; address?: { address1?: string; city?: string; state?: string; postalCode?: string; country?: string };- customFields?: Record<string, unknown>;-}--function scopeFor(path: string, method: string): string {- const read = method === "GET";- if (path.startsWith("/contacts")) return read ? "contacts.readonly" : "contacts.write";- if (path.startsWith("/opportunities")) return read ? "opportunities.readonly" : "opportunities.write";- if (/^\/conversations\/[^/]+\/messages/u.test(path)) return "conversations/message.readonly";- if (path.startsWith("/conversations")) return "conversations.readonly";- if (path.startsWith("/calendars/events")) return "calendars/events.readonly";- if (path.startsWith("/calendars")) return "calendars.readonly";- if (/^\/locations\/[^/]+\/customFields/u.test(path)) return "locations/customFields.readonly";- if (path.startsWith("/locations")) return "locations.readonly";- return "the required";-}--/** What HighLevel's Private Integrations page calls each scope, so a person can find the box to tick. */-const PERMISSION_NAMES: Record<string, string> = {- "contacts.readonly": "View Contacts", "contacts.write": "Edit Contacts",- "opportunities.readonly": "View Opportunities", "opportunities.write": "Edit Opportunities",- "conversations.readonly": "View Conversations", "conversations/message.readonly": "View Conversation Messages", "calendars.readonly": "View Calendars", "calendars/events.readonly": "View Calendar Events",- "locations.readonly": "View Locations", "locations/customFields.readonly": "View Custom Fields",-};--function thing(path: string): string {- if (/^\/contacts\/[^/]+\/notes/u.test(path)) return "note";- if (/^\/contacts\/[^/]+\/tasks/u.test(path)) return "task";- if (path.startsWith("/contacts")) return "contact";- if (path.startsWith("/opportunities/pipelines")) return "pipeline";- if (path.startsWith("/opportunities")) return "opportunity";- if (path.startsWith("/conversations")) return "conversation";- if (path.startsWith("/calendars")) return "calendar";- if (path.startsWith("/locations")) return "location";- return "record";-}--/** HighLevel's error bodies carry `message` as a string or a list of validation strings. */-function rawApiMessage(body: unknown): string | undefined {- if (!isRecord(body)) return undefined;- const message = body.message ?? body.error;- if (typeof message === "string") return message || undefined;- if (Array.isArray(message)) return message.filter((item) => typeof item === "string").join("; ") || undefined;- return undefined;-}--const SECRET_SHAPES = [/\bBearer\s+[\w.~+/=-]{8,}/giu, /\bpit-[\w-]{4,}/gu, /\beyJ[\w-]{6,}(?:\.[\w-]*)*/gu] as const;--/** Removes the given secrets and anything shaped like a token (Bearer values, pit- tokens, JWTs). */-export function redactSecrets(text: string, secrets: readonly string[] = []): string {- let out = text;- for (const secret of secrets) if (secret.length >= 8) out = out.split(secret).join("[redacted]");- for (const shape of SECRET_SHAPES) out = out.replace(shape, "[redacted]");- return out;-}--/** HighLevel's own explanation, safe to show a person or a bot: secrets redacted, one line, cut short. */-export function apiMessage(body: unknown, options: { secrets?: readonly string[]; max?: number } = {}): string | undefined {- const raw = rawApiMessage(body);- if (!raw) return undefined;- const max = options.max ?? 300;- const text = redactSecrets(raw, options.secrets).replace(/[\p{Cc}\s]+/gu, " ").trim();- if (!text) return undefined;- return text.length > max ? `${text.slice(0, max - 1)}…` : text;-}--/** HighLevel answers 401 both for a dead token ("Invalid JWT") and for a live one that lacks a scope- * ("The token is not authorized for this scope."). Only the second says "scope"; it is a missing permission, not a sign-out. */-const SCOPE_REFUSAL = /not authori[sz]ed for (?:this|the) scope|insufficient[_ ]scope/iu;--export function isScopeRefusal(body: unknown): boolean {- const raw = rawApiMessage(body);- return raw !== undefined && SCOPE_REFUSAL.test(raw);-}--export function plainError(status: number, method: string, path: string, body: unknown): HighLevelError {- const detail = apiMessage(body);- if (status === 401 && isScopeRefusal(body)) {- const scope = scopeFor(path, method);- const name = PERMISSION_NAMES[scope];- const permission = name ? `${name} permission (${scope})` : `${scope} permission`;- return new HighLevelError(`HighLevel refused this (401): the connection lacks the ${permission}.${detail ? ` HighLevel said: ${detail}` : ""}`, { status });- }- if (status === 401) return new HighLevelError(HIGHLEVEL_SIGNED_OUT_TEXT, { status, signedOut: true });- if (status === 403) return new HighLevelError(`HighLevel refused this (403): the connection lacks the ${scopeFor(path, method)} permission.${detail ? ` HighLevel said: ${detail}` : ""}`, { status });- if (status === 404) return new HighLevelError(`HighLevel has no ${thing(path)} with that id (404).`, { status });- if (status === 429) return new HighLevelError("HighLevel is rate-limiting; try again in a few seconds.", { status });- if (status >= 500) return new HighLevelError(`HighLevel is having trouble (${status}); try again in a minute.`, { status });- return new HighLevelError(`HighLevel rejected this (${status})${detail ? `: ${detail}` : "."}`, { status });-}--function waitFromHeaders(headers: Headers, now: number): number {- const retryAfter = headers.get("retry-after");- if (retryAfter) {- const seconds = Number(retryAfter);- if (Number.isFinite(seconds) && seconds >= 0) return Math.min(BACKOFF_MAX_MS, seconds * 1000);- const at = Date.parse(retryAfter);- if (Number.isFinite(at)) return Math.min(BACKOFF_MAX_MS, Math.max(0, at - now));- }- const interval = Number(headers.get("x-ratelimit-interval-milliseconds"));- if (Number.isFinite(interval) && interval > 0) return Math.min(BACKOFF_MAX_MS, interval);- return 2_000;-}--/** The body as UTF-8 text, or null once it passes `max` bytes; reading stops there. */-async function textUpTo(response: Response, max: number): Promise<string | null> {- if (!response.body) return "";- const reader = response.body.getReader();- const chunks: Uint8Array[] = [];- let size = 0;- for (;;) {- const { done, value } = await reader.read();- if (done) return new TextDecoder().decode(Buffer.concat(chunks));- size += value.byteLength;- if (size > max) {- await reader.cancel().catch(() => {});- return null;- }- chunks.push(value);- }-}--export function assertAllowedPath(method: string, path: string): void {- if (!path.startsWith("/") || path.includes("..") || path.includes("?") || path.includes("#")) throw new HighLevelError("HighLevel request path is not valid.");- if (FORBIDDEN_PATHS.some((pattern) => pattern.test(path))) throw new HighLevelError("OpenMausBot never sends messages, runs campaigns or workflows, or moves money through HighLevel.");- if (path.startsWith("/conversations") && method !== "GET") throw new HighLevelError("OpenMausBot reads conversations only; it never writes to them.");- if (path.startsWith("/calendars") && method !== "GET") throw new HighLevelError("OpenMausBot reads calendars only; it never books or changes events.");- if (path.startsWith("/locations") && method !== "GET") throw new HighLevelError("OpenMausBot never changes the location's settings.");- if (method === "DELETE" && !/^\/contacts\/[^/]+\/tags$/u.test(path)) throw new HighLevelError("OpenMausBot never deletes HighLevel records.");-}--export class HighLevelClient {- private readonly store: HighLevelStore;- private readonly refreshViaRelay: HighLevelClientOptions["refresh"];- private readonly apiUrl: string;- private readonly fetch: typeof fetch;- private readonly now: () => number;- private readonly sleep: (ms: number) => Promise<void>;- private readonly activeCall = new AsyncLocalStorage<() => void>();- private readonly budget = new Map<string, number[]>();- private refreshing: { from: HighLevelConnection; promise: Promise<HighLevelConnection | null> } | null = null;- /** `refused` holds a missing-permission answer so contact reads do not re-ask HighLevel on every call. */- private customFieldCache: { locationId: string; at: number; fields: CustomFieldDefinition[]; refused?: HighLevelError } | null = null;-- constructor(options: HighLevelClientOptions) {- this.store = options.store;- this.refreshViaRelay = options.refresh;- this.apiUrl = (options.apiUrl ?? process.env[HIGHLEVEL_API_ENV] ?? HIGHLEVEL_API_URL).replace(/\/+$/u, "");- this.fetch = options.fetch ?? fetch;- this.now = options.now ?? Date.now;- this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));- }-- withActiveCall<T>(assertActive: () => void, run: () => Promise<T>): Promise<T> {- return this.activeCall.run(assertActive, run);- }-- private async wait(ms: number): Promise<void> {- await this.sleep(ms);- this.activeCall.getStore()?.();- }-- /** The connection, refreshed ahead of expiry; throws the signed-out error when a person must reconnect. */- private async connection(): Promise<HighLevelConnection> {- const current = this.store.get();- if (!current) throw new HighLevelError(HIGHLEVEL_NOT_CONNECTED_TEXT, { signedOut: true });- if (current.state === "needs-sign-in") throw new HighLevelError(HIGHLEVEL_SIGNED_OUT_TEXT, { signedOut: true });- if (current.kind === "oauth" && current.expiresAt !== undefined && current.expiresAt - this.now() < REFRESH_MARGIN_MS) return (await this.refresh(current)) ?? this.successor(current);- return current;- }-- /** A connection the call can no longer use as it holds it: disconnected, signed out, reconnected or rotated since. */- private replaced(connection: HighLevelConnection): boolean {- const current = this.store.get();- return !current || current.state !== "signed-in" || !sameTokens(current, connection);- }-- /** What replaced `from` while a call used it: newer tokens for the same location carry the call on; another location ends it. */- private successor(from: HighLevelConnection): HighLevelConnection {- const current = this.store.get();- if (!current) throw new HighLevelError(HIGHLEVEL_NOT_CONNECTED_TEXT, { signedOut: true });- if (current.state === "needs-sign-in") throw new HighLevelError(HIGHLEVEL_SIGNED_OUT_TEXT, { signedOut: true });- if (current.locationId !== from.locationId) throw new HighLevelError("The HighLevel connection changed to another location while this call ran; run it again.", { status: 409 });- return current;- }-- /** One refresh per token version: a burst of calls that all see an expired token shares the rotation. Null when the- * connection was replaced meanwhile, so nothing was refreshed. */- private refresh(current: HighLevelConnection): Promise<HighLevelConnection | null> {- if (this.refreshing && sameTokens(this.refreshing.from, current)) return this.refreshing.promise;- this.activeCall.getStore()?.();- const promise = (async () => {- if (current.kind !== "oauth" || !current.refreshToken) {- this.store.markNeedsSignIn("The saved token was rejected by HighLevel.", current);- throw new HighLevelError(HIGHLEVEL_SIGNED_OUT_TEXT, { status: 401, signedOut: true });- }- if (!this.refreshViaRelay) throw new HighLevelError("HighLevel's sign-in has expired and no OpenMausBot relay is configured to refresh it; ask the person to reconnect.", { signedOut: true });- let tokens: RelayTokens;- try {- tokens = await this.refreshViaRelay(current.refreshToken);- } catch (error) {- if (this.replaced(current)) return null;- if (error instanceof HighLevelRelayError && error.status === 401) {- this.store.markNeedsSignIn("HighLevel rejected the saved sign-in (it was revoked or the app was uninstalled).", current);- throw new HighLevelError(HIGHLEVEL_SIGNED_OUT_TEXT, { status: 401, signedOut: true });- }- throw new HighLevelError("HighLevel's sign-in could not be refreshed right now (the OpenMausBot relay did not answer); try again in a minute.", { status: 503 });- }- return this.store.rotate({- accessToken: tokens.accessToken, refreshToken: tokens.refreshToken,- expiresAt: this.now() + tokens.expiresIn * 1000, scopes: tokens.scope,- }, current);- })().finally(() => { if (this.refreshing?.promise === promise) this.refreshing = null; });- this.refreshing = { from: current, promise };- return promise;- }-- private async spend(locationId: string): Promise<void> {- const window = this.budget.get(locationId) ?? [];- const now = this.now();- const recent = window.filter((at) => now - at < BUDGET_WINDOW_MS);- if (recent.length >= BUDGET_CALLS) {- await this.wait(Math.max(1, recent[0]! + BUDGET_WINDOW_MS - now));- return this.spend(locationId);- }- recent.push(now);- this.budget.set(locationId, recent);- }-- private async dispatch(connection: HighLevelConnection, method: string, path: string, options: RequestOptions): Promise<Response> {- const url = new URL(`${this.apiUrl}${path}`);- for (const [key, value] of Object.entries(options.query ?? {})) if (value !== undefined && value !== "") url.searchParams.set(key, String(value));- await this.spend(connection.locationId);- this.activeCall.getStore()?.();- try {- return await this.fetch(url, {- method, redirect: "error",- headers: {- authorization: `Bearer ${connection.accessToken}`,- version: options.version ?? HIGHLEVEL_VERSION,- accept: "application/json",- ...(options.body === undefined ? {} : { "content-type": "application/json" }),- },- ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),- });- } catch {- throw this.noAnswer(method, path, options);- }- }-- private noAnswer(method: string, path: string, options: RequestOptions): HighLevelError {- if (!repeatable(method, options)) return unknownOutcome(path, "HighLevel did not answer (the request timed out or the network failed)", 503);- return new HighLevelError("HighLevel did not answer (the request timed out or the network failed); try again in a minute.", { status: 503 });- }-- private async body(response: Response, method: string, path: string, options: RequestOptions): Promise<unknown> {- let text: string | null;- try {- text = await textUpTo(response, MAX_RESPONSE_BYTES);- } catch {- throw this.noAnswer(method, path, options);- }- if (text === null) throw new HighLevelError("HighLevel's answer was too large to read; narrow the request.", { status: response.status });- try {- return text ? JSON.parse(text) : {};- } catch {- return {};- }- }-- /** A create is never replayed after a 5xx: HighLevel may have saved it before failing. */- async request(method: "GET" | "POST" | "PUT" | "DELETE", path: string, options: RequestOptions = {}): Promise<unknown> {- assertAllowedPath(method, path);- let connection = await this.connection();- let refreshed = false;- let waited = false;- let retried5xx = false;- let successors = 0;- const successor = (from: HighLevelConnection) => {- const next = this.successor(from);- if (++successors > MAX_SUCCESSORS) throw new HighLevelError("HighLevel's sign-in kept changing while this call ran; try again in a minute.", { status: 503 });- return next;- };- for (;;) {- const response = await this.dispatch(connection, method, path, options);- if (response.ok) return this.body(response, method, path, options);- if (response.status >= 500 && !repeatable(method, options)) {- await response.body?.cancel().catch(() => {});- throw unknownOutcome(path, `HighLevel had trouble (${response.status})`, response.status);- }- if (response.status >= 500 && !retried5xx) {- await response.body?.cancel().catch(() => {});- retried5xx = true;- await this.wait(1_000);- continue;- }- const body = await this.body(response, method, path, options);- // A live token that lacks one scope: name the permission; refreshing would not add it and the token still works.- if (response.status === 401 && isScopeRefusal(body)) throw plainError(response.status, method, path, body);- if (response.status === 401 && this.replaced(connection)) {- connection = successor(connection);- continue;- }- if (response.status === 401 && !refreshed) {- if (connection.kind === "token") {- this.store.markNeedsSignIn("HighLevel rejected the Private Integration token.", connection);- throw new HighLevelError(HIGHLEVEL_SIGNED_OUT_TEXT, { status: 401, signedOut: true });- }- const rotated = await this.refresh(connection);- refreshed = rotated !== null;- connection = rotated ?? successor(connection);- continue;- }- if (response.status === 429 && !waited) {- waited = true;- await this.wait(waitFromHeaders(response.headers, this.now()));- continue;- }- if (response.status === 401) {- this.store.markNeedsSignIn("HighLevel rejected the refreshed sign-in.", connection);- }- throw plainError(response.status, method, path, body);- }- }-- private async locationId(): Promise<string> {- return (await this.connection()).locationId;- }-- // ---- custom fields -------------------------------------------------------------------------------------------------- async customFieldDefinitions(): Promise<CustomFieldDefinition[]> {- const locationId = await this.locationId();- const cached = this.customFieldCache;- if (cached && cached.locationId === locationId && this.now() - cached.at < CUSTOM_FIELDS_TTL_MS) {- if (cached.refused) throw cached.refused;- return cached.fields;- }- let raw: unknown;- try {- raw = await this.request("GET", `/locations/${encodeURIComponent(locationId)}/customFields`);- } catch (error) {- // Optional for reads (fields then show by id): a token without View Custom Fields keeps working and stays signed in.- if (error instanceof HighLevelError && !error.signedOut && (error.status === 401 || error.status === 403)) {- this.customFieldCache = { locationId, at: this.now(), fields: [], refused: error };- }- throw error;- }- const fields = list(isRecord(raw) ? raw.customFields : []).flatMap((field) => {- const id = str(field.id);- const name = str(field.name);- if (!id || !name) return [];- const options = strings(field.picklistOptions);- return [compact<CustomFieldDefinition>({ id, name, key: str(field.fieldKey), dataType: str(field.dataType), model: str(field.model), ...(options.length ? { options } : {}) })];- });- this.customFieldCache = { locationId, at: this.now(), fields };- return fields;- }-- private async customFieldsByName(values: Record<string, unknown> | undefined): Promise<Array<{ id: string; field_value: unknown }> | undefined> {- if (!values || Object.keys(values).length === 0) return undefined;- const definitions = await this.customFieldDefinitions();- const out: Array<{ id: string; field_value: unknown }> = [];- for (const [name, value] of Object.entries(values)) {- const wanted = name.trim().toLowerCase();- const match = definitions.find((field) => field.id === name || field.name.toLowerCase() === wanted || field.key?.toLowerCase() === wanted || field.key?.toLowerCase() === `contact.${wanted}`);- if (!match) throw new HighLevelError(`HighLevel has no custom field named "${name.slice(0, 80)}". HIGHLEVEL_GET_LOCATION lists the custom fields.`, { status: 400 });- out.push({ id: match.id, field_value: value });- }- return out;- }-- private namedCustomFields(raw: unknown, definitions: CustomFieldDefinition[]): Record<string, unknown> | undefined {- const entries = list(raw).flatMap((field) => {- const id = str(field.id);- if (!id) return [];- const value = field.value ?? field.fieldValue ?? field.field_value;- if (value === undefined || value === null || value === "") return [];- const definition = definitions.find((candidate) => candidate.id === id);- return [[definition?.name ?? id, typeof value === "string" ? value.slice(0, TEXT_MAX) : value] as const];- });- return entries.length ? Object.fromEntries(entries) : undefined;- }-- // ---- contacts --------------------------------------------------------------------------------------------------------- private trimContact(raw: Json, definitions: CustomFieldDefinition[]): TrimmedContact {- const address = compact({ address1: str(raw.address1), city: str(raw.city), state: str(raw.state), postalCode: str(raw.postalCode), country: str(raw.country) });- return compact<TrimmedContact>({- id: String(raw.id ?? ""), name: str(raw.name) ?? str(raw.contactName), firstName: str(raw.firstName), lastName: str(raw.lastName),- email: str(raw.email), phone: str(raw.phone), companyName: str(raw.companyName), tags: strings(raw.tags), source: str(raw.source),- assignedTo: str(raw.assignedTo), dateAdded: str(raw.dateAdded), dateUpdated: str(raw.dateUpdated), website: str(raw.website),- timezone: str(raw.timezone), dnd: bool(raw.dnd), ...(Object.keys(address).length ? { address } : {}),- customFields: this.namedCustomFields(raw.customFields, definitions),- });- }-- private async contactBody(fields: ContactFields): Promise<Json> {- const { customFields, ...plain } = fields;- const mapped = await this.customFieldsByName(customFields);- return compact({ ...plain, ...(mapped ? { customFields: mapped } : {}) });- }-- async searchContacts(input: { query?: string; tag?: string; email?: string; phone?: string; page?: number; limit?: number }): Promise<{ contacts: TrimmedContact[]; total?: number; page: number }> {- const locationId = await this.locationId();- const filters: Json[] = [];- if (input.email) filters.push({ field: "email", operator: "eq", value: input.email });- if (input.phone) filters.push({ field: "phone", operator: "eq", value: input.phone });- if (input.tag) filters.push({ field: "tags", operator: "eq", value: input.tag });- const current = pageNumber(input.page);- const raw = await this.request("POST", "/contacts/search", { repeatable: true, body: compact({- locationId, page: current, pageLimit: pageSize(input.limit), query: input.query?.trim() || undefined, ...(filters.length ? { filters } : {}),- }) });- const definitions = await this.customFieldDefinitions().catch(() => []);- const record = isRecord(raw) ? raw : {};- return compact({ contacts: list(record.contacts).map((contact) => this.trimContact(contact, definitions)), total: num(record.total) ?? num(record.count), page: current });- }-- async getContact(contactId: string): Promise<TrimmedContact> {- const raw = await this.request("GET", `/contacts/${encodeURIComponent(contactId)}`);- const contact = isRecord(raw) && isRecord(raw.contact) ? raw.contact : {};- return this.trimContact(contact, await this.customFieldDefinitions().catch(() => []));- }-- async createContact(fields: ContactFields): Promise<TrimmedContact> {- const locationId = await this.locationId();- const raw = await this.request("POST", "/contacts/", { body: { ...(await this.contactBody(fields)), locationId } });- const contact = isRecord(raw) && isRecord(raw.contact) ? raw.contact : {};- return this.trimContact(contact, await this.customFieldDefinitions().catch(() => []));- }-- async updateContact(contactId: string, fields: ContactFields): Promise<TrimmedContact> {- const raw = await this.request("PUT", `/contacts/${encodeURIComponent(contactId)}`, { body: await this.contactBody(fields) });- const contact = isRecord(raw) && isRecord(raw.contact) ? raw.contact : { id: contactId };- return this.trimContact(contact, await this.customFieldDefinitions().catch(() => []));- }-- async addTags(contactId: string, tags: string[]): Promise<{ contactId: string; tags: string[] }> {- const raw = await this.request("POST", `/contacts/${encodeURIComponent(contactId)}/tags`, { repeatable: true, body: { tags } });- return { contactId, tags: strings(isRecord(raw) ? raw.tags : []) };- }-- async removeTags(contactId: string, tags: string[]): Promise<{ contactId: string; tags: string[] }> {- const raw = await this.request("DELETE", `/contacts/${encodeURIComponent(contactId)}/tags`, { body: { tags } });- return { contactId, tags: strings(isRecord(raw) ? raw.tags : []) };- }-- private trimNote(raw: Json) {- return compact({ id: String(raw.id ?? ""), body: str(raw.body), title: str(raw.title), dateAdded: str(raw.dateAdded), userId: str(raw.userId), pinned: bool(raw.pinned) });- }-- async listNotes(contactId: string) {- const raw = await this.request("GET", `/contacts/${encodeURIComponent(contactId)}/notes`);- return { contactId, notes: list(isRecord(raw) ? raw.notes : []).map((note) => this.trimNote(note)) };- }-- async addNote(contactId: string, body: string) {- const raw = await this.request("POST", `/contacts/${encodeURIComponent(contactId)}/notes`, { body: { body } });- return { contactId, note: this.trimNote(isRecord(raw) && isRecord(raw.note) ? raw.note : {}) };- }-- private trimTask(raw: Json) {- return compact({ id: String(raw.id ?? ""), title: str(raw.title), body: str(raw.body), dueDate: str(raw.dueDate), completed: bool(raw.completed), assignedTo: str(raw.assignedTo) });- }-- async listTasks(contactId: string) {- const raw = await this.request("GET", `/contacts/${encodeURIComponent(contactId)}/tasks`);- return { contactId, tasks: list(isRecord(raw) ? raw.tasks : []).map((task) => this.trimTask(task)) };- }-- async addTask(contactId: string, input: { title: string; dueDate: string; body?: string; assignedTo?: string }) {- const raw = await this.request("POST", `/contacts/${encodeURIComponent(contactId)}/tasks`, {- body: compact({ title: input.title, dueDate: input.dueDate, body: input.body, assignedTo: input.assignedTo, completed: false }),- });- return { contactId, task: this.trimTask(isRecord(raw) && isRecord(raw.task) ? raw.task : {}) };- }-- // ---- pipelines and opportunities --------------------------------------------------------------------------------------- async listPipelines() {- const locationId = await this.locationId();- const raw = await this.request("GET", "/opportunities/pipelines", { query: { locationId } });- return {- pipelines: list(isRecord(raw) ? raw.pipelines : []).map((pipeline) => compact({- id: String(pipeline.id ?? ""), name: str(pipeline.name),- stages: list(pipeline.stages).map((stage) => compact({ id: String(stage.id ?? ""), name: str(stage.name), position: num(stage.position) })),- })),- };- }-- private trimOpportunity(raw: Json) {- const contact = isRecord(raw.contact) ? raw.contact : null;- return compact({- id: String(raw.id ?? ""), name: str(raw.name), status: str(raw.status), monetaryValue: num(raw.monetaryValue),- pipelineId: str(raw.pipelineId), pipelineStageId: str(raw.pipelineStageId), contactId: str(raw.contactId),- contact: contact ? compact({ id: str(contact.id), name: str(contact.name), email: str(contact.email), phone: str(contact.phone), companyName: str(contact.companyName) }) : undefined,- assignedTo: str(raw.assignedTo), source: str(raw.source), createdAt: str(raw.createdAt), updatedAt: str(raw.updatedAt),- lastStageChangeAt: str(raw.lastStageChangeAt), lastStatusChangeAt: str(raw.lastStatusChangeAt),- });- }-- async searchOpportunities(input: { query?: string; pipelineId?: string; stageId?: string; contactId?: string; status?: string; page?: number; limit?: number }) {- const locationId = await this.locationId();- const current = pageNumber(input.page);- const raw = await this.request("GET", "/opportunities/search", { query: {- location_id: locationId, q: input.query?.trim() || undefined, pipeline_id: input.pipelineId, pipeline_stage_id: input.stageId,- contact_id: input.contactId, status: input.status, page: current, limit: pageSize(input.limit),- } });- const record = isRecord(raw) ? raw : {};- const meta = isRecord(record.meta) ? record.meta : {};- return compact({ opportunities: list(record.opportunities).map((item) => this.trimOpportunity(item)), total: num(meta.total) ?? num(record.total), page: current });- }-- async getOpportunity(id: string) {- const raw = await this.request("GET", `/opportunities/${encodeURIComponent(id)}`);- return this.trimOpportunity(isRecord(raw) && isRecord(raw.opportunity) ? raw.opportunity : {});- }-- async createOpportunity(input: { pipelineId: string; stageId?: string; contactId: string; name: string; value?: number; status?: string }) {- const locationId = await this.locationId();- const raw = await this.request("POST", "/opportunities/", { body: compact({- pipelineId: input.pipelineId, locationId, name: input.name, pipelineStageId: input.stageId, status: input.status ?? "open",- contactId: input.contactId, monetaryValue: input.value,- }) });- return this.trimOpportunity(isRecord(raw) && isRecord(raw.opportunity) ? raw.opportunity : {});- }-- async updateOpportunity(id: string, input: { stageId?: string; status?: string; value?: number; name?: string; pipelineId?: string }) {- const raw = await this.request("PUT", `/opportunities/${encodeURIComponent(id)}`, { body: compact({- pipelineStageId: input.stageId, status: input.status, monetaryValue: input.value, name: input.name, pipelineId: input.pipelineId,- }) });- return this.trimOpportunity(isRecord(raw) && isRecord(raw.opportunity) ? raw.opportunity : { id });- }-- // ---- conversations (read only) ------------------------------------------------------------------------------------------- async searchConversations(input: { contactId?: string; query?: string; limit?: number }) {- const locationId = await this.locationId();- const raw = await this.request("GET", "/conversations/search", {- version: HIGHLEVEL_CONVERSATIONS_VERSION,- query: { locationId, contactId: input.contactId, query: input.query?.trim() || undefined, limit: pageSize(input.limit) },- });- const record = isRecord(raw) ? raw : {};- return compact({- conversations: list(record.conversations).map((item) => compact({- id: String(item.id ?? ""), contactId: str(item.contactId), contactName: str(item.fullName) ?? str(item.contactName), email: str(item.email), phone: str(item.phone),- type: str(item.type), lastMessageBody: str(item.lastMessageBody), lastMessageType: str(item.lastMessageType),- lastMessageDate: str(item.lastMessageDate) ?? (num(item.lastMessageDate) !== undefined ? new Date(item.lastMessageDate as number).toISOString() : undefined),- unreadCount: num(item.unreadCount), assignedTo: str(item.assignedTo),- })),- total: num(record.total),- });- }-- async readConversation(conversationId: string, input: { limit?: number; lastMessageId?: string } = {}) {- const raw = await this.request("GET", `/conversations/${encodeURIComponent(conversationId)}/messages`, {- version: HIGHLEVEL_CONVERSATIONS_VERSION, query: { limit: pageSize(input.limit), lastMessageId: input.lastMessageId },- });- // Documented as { lastMessageId, nextPage, messages }; served as { messages: { lastMessageId, nextPage, messages } }.- const record = isRecord(raw) ? raw : {};- const pageRecord = isRecord(record.messages) ? record.messages : record;- return compact({- conversationId,- messages: list(pageRecord.messages).map((message) => compact({- id: String(message.id ?? ""), type: str(message.messageType) ?? (num(message.type) !== undefined ? String(message.type) : undefined),- direction: str(message.direction), status: str(message.status), dateAdded: str(message.dateAdded), body: str(message.body),- contentType: str(message.contentType), attachments: Array.isArray(message.attachments) ? message.attachments.length : undefined,- })),- nextPage: bool(pageRecord.nextPage), lastMessageId: str(pageRecord.lastMessageId),- });- }-- // ---- calendars (read only) ------------------------------------------------------------------------------------------------ async listCalendars() {- const locationId = await this.locationId();- const raw = await this.request("GET", "/calendars/", { query: { locationId } });- return {- calendars: list(isRecord(raw) ? raw.calendars : []).map((calendar) => compact({- id: String(calendar.id ?? ""), name: str(calendar.name), description: str(calendar.description), isActive: bool(calendar.isActive),- calendarType: str(calendar.calendarType), slotDuration: num(calendar.slotDuration), slotDurationUnit: str(calendar.slotDurationUnit),- teamMembers: Array.isArray(calendar.teamMembers) ? calendar.teamMembers.length : undefined,- })),- };- }-- async listEvents(input: { startTime: string; endTime: string; calendarId?: string; userId?: string }) {- const locationId = await this.locationId();- const ms = (value: string, name: string) => {- const parsed = /^\d{10,}$/u.test(value.trim()) ? Number(value.trim()) : Date.parse(value);- if (!Number.isFinite(parsed)) throw new HighLevelError(`${name} must be an ISO 8601 date-time.`, { status: 400 });- return parsed;- };- const raw = await this.request("GET", "/calendars/events", { query: {- locationId, calendarId: input.calendarId, userId: input.userId, startTime: ms(input.startTime, "startTime"), endTime: ms(input.endTime, "endTime"),- } });- return {- events: list(isRecord(raw) ? raw.events : []).map((event) => compact({- id: String(event.id ?? ""), title: str(event.title), calendarId: str(event.calendarId), contactId: str(event.contactId),- appointmentStatus: str(event.appointmentStatus), startTime: str(event.startTime), endTime: str(event.endTime),- assignedUserId: str(event.assignedUserId), address: str(event.address), notes: str(event.notes),- })),- };- }-- // ---- location ---------------------------------------------------------------------------------------------------------------- async getLocation() {- const locationId = await this.locationId();- const raw = await this.request("GET", `/locations/${encodeURIComponent(locationId)}`);- const location = isRecord(raw) && isRecord(raw.location) ? raw.location : {};- const customFields = await this.customFieldDefinitions().catch(() => []);- return compact({- id: str(location.id) ?? locationId, name: str(location.name), timezone: str(location.timezone), email: str(location.email), phone: str(location.phone),- website: str(location.website), address: str(location.address), city: str(location.city), state: str(location.state), country: str(location.country),- postalCode: str(location.postalCode), customFields,- });- }-}--/** Why the token check failed, in words a person can act on. HighLevel's own short reason is kept; the token never is. */-export function tokenCheckError(status: number, body: unknown, token: string, path: string): HighLevelError {- const detail = apiMessage(body, { secrets: [token], max: 160 });- const said = detail ? ` HighLevel said: ${detail}` : "";- if (status === 401 && isScopeRefusal(body)) {- return new HighLevelError(- "This token is missing the View Locations permission (401), which OpenMausBot needs to check it. In HighLevel, open Settings → Private Integrations, " +- `edit this integration, turn on View Locations and save, then connect again: the token stays the same.${said}`, { status });- }- if (status === 401) {- return new HighLevelError(- "HighLevel did not accept this token (401). Check that it was copied whole and has not been rotated or deleted, " +- `and that its Private Integration has the View Locations permission.${said}`, { status });- }- if (status === 403) {- return new HighLevelError(- "This token does not belong to that location (403): it was created in another sub-account or at the agency level. " +- `Create the Private Integration inside the sub-account whose location ID you entered.${said}`, { status });- }- if (status === 404) {- return new HighLevelError("HighLevel has no location with that ID (404). Copy the location ID from Settings → Business Profile in the sub-account where you created the token.", { status });- }- return plainError(status, "GET", path, detail ? { message: detail } : {});-}--/** A Private Integration token is checked against the location it was issued for before it is saved. */-export async function lookupLocation(- input: { token: string; locationId: string; apiUrl?: string; fetch?: typeof fetch },-): Promise<{ id: string; name: string; companyId?: string; timezone?: string }> {- const apiUrl = (input.apiUrl ?? process.env[HIGHLEVEL_API_ENV] ?? HIGHLEVEL_API_URL).replace(/\/+$/u, "");- const path = `/locations/${encodeURIComponent(input.locationId)}`;- assertAllowedPath("GET", path);- let response: Response;- try {- response = await (input.fetch ?? fetch)(`${apiUrl}${path}`, {- method: "GET", redirect: "error", headers: { authorization: `Bearer ${input.token}`, version: HIGHLEVEL_VERSION, accept: "application/json" },- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),- });- } catch {- throw new HighLevelError("HighLevel did not answer; check the connection and try again.", { status: 503 });- }- const text = await response.text();- let body: unknown = {};- try { body = text ? JSON.parse(text) : {}; } catch {}- if (!response.ok) throw tokenCheckError(response.status, body, input.token, path);- const location = isRecord(body) && isRecord(body.location) ? body.location : {};- return compact({ id: str(location.id) ?? input.locationId, name: str(location.name) ?? input.locationId, companyId: str(location.companyId), timezone: str(location.timezone) });-}diff --git a/server/highlevel/host.ts b/server/highlevel/host.tsdeleted file mode 100644index aad6251a79..0000000000--- a/server/highlevel/host.ts+++ /dev/null@@ -1,86 +0,0 @@-// What server/index.ts needs from the HighLevel integration, in one object so the host file gains only a few lines:-// the per-turn mount, the prompt part, the internal MCP handler (per-bot verdict, decision rows, write activity) and-// the Cloud health merge.-import { HIGHLEVEL_MCP_SERVER } from "../../shared/highlevel.ts";-import { appendDecision } from "../decision-log.ts";-import { harnessMcpTokenEnv } from "../harness-mcp-token.ts";-import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "../proxy-paths.ts";-import { highlevelAccess, highlevelAllowedFor, highlevelSystemPrompt, type HighLevelBot } from "./access.ts";-import { highlevelRpc, type HighLevelToolsList } from "./rpc.ts";-import type { HighLevelService } from "./service.ts";-import { HIGHLEVEL_TOOLS, type HighLevelToolResult, type HighLevelWriteRecord } from "./tools.ts";--export interface HighLevelHostDeps {- service: HighLevelService;- dataDir: string;- bot(id: string): (HighLevelBot & { color?: string }) | undefined | null;- /** True when the thread is a room, so the activity row names its author. */- inRoom(threadId: string): boolean;- appendMessage(threadId: string, message: Record<string, unknown>): void;-}--export interface HighLevelHost {- /** Connected, and this bot allowed to use it. */- mounts(bot: HighLevelBot): boolean;- integration(bot: HighLevelBot, mint: () => string, harnessUrl: string): { command: string; args: string[]; env: Record<string, string> } | null;- prompt(bot: HighLevelBot): string;- handle(body: unknown, capability: { botId: string; threadId: string }, assertActive: () => void): Promise<HighLevelToolsList | HighLevelToolResult>;- /** The HIGHLEVEL_* names for the per-bot tool grants picker (/api/connectors/tools); null when the integration is unavailable. */- toolListing(): { highlevel: Array<{ name: string; description: string }> } | null;- /** Merges {highlevel:{connected}} into the Cloud health connectors report, only while a HighLevel connection is saved- * (signed in, or needing sign-in again): a HighLevel never set up is not listed. */- health(base: Promise<Record<string, { connected: boolean; pending?: boolean }>> | null): Promise<Record<string, { connected: boolean; pending?: boolean }>> | null;-}--/** "contact abc: email, tags": the record and the field names, never the values. */-export function writeSummary(record: HighLevelWriteRecord): string {- return `${record.kind} ${record.recordId}: ${record.fields.join(", ")}`.slice(0, 240);-}--export function createHighLevelHost(deps: HighLevelHostDeps): HighLevelHost {- const { service } = deps;- const mounts = (bot: HighLevelBot) => service.connected() && highlevelAllowedFor(bot);- return {- mounts,- integration(bot, mint, harnessUrl) {- if (!mounts(bot)) return null;- const token = mint();- return {- command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, HIGHLEVEL_MCP_SERVER],- env: { ...AGENTS_NODE_FLAG, [harnessMcpTokenEnv("highlevel")]: token, OMB_HARNESS_URL: harnessUrl },- };- },- prompt: (bot) => highlevelSystemPrompt(bot),- toolListing: () => (service.status().state === "unavailable" ? null : { highlevel: HIGHLEVEL_TOOLS.map(({ name, description }) => ({ name, description })) }),- async handle(body, capability, assertActive) {- return highlevelRpc(body as { method?: unknown; params?: unknown }, {- client: service.client,- assertActive,- // Re-read the live bot on every call, so a permission change wins over a request authenticated under the old one.- authorize: (name) => {- const bot = deps.bot(capability.botId);- if (!bot) return { ok: false, text: "This bot no longer exists." };- const verdict = highlevelAccess(bot, name);- for (const row of verdict.rows) {- appendDecision(deps.dataDir, { threadId: capability.threadId, botId: bot.id, botName: bot.name, tool: row.tool, decision: row.decision, source: "connector-scope", rule: row.rule, ...(row.summary ? { summary: row.summary } : {}) });- }- return verdict.ok ? { ok: true } : { ok: false, text: verdict.text };- },- onWrite: (record) => {- const bot = deps.bot(capability.botId);- deps.appendMessage(capability.threadId, {- role: "bot", kind: "activity",- tool: { name: `mcp__${HIGHLEVEL_MCP_SERVER}__${record.tool}`, ok: true, summary: writeSummary(record) },- ...(bot && deps.inRoom(capability.threadId) ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {}),- });- },- });- },- health(base) {- const connection = service.store.get();- if (!connection) return base;- const highlevel = { connected: connection.state === "signed-in" };- return (base ?? Promise.resolve({})).then((connectors) => ({ ...connectors, highlevel }), () => ({ highlevel }));- },- };-}diff --git a/server/highlevel/instructions.ts b/server/highlevel/instructions.tsdeleted file mode 100644index 04158ff990..0000000000--- a/server/highlevel/instructions.ts+++ /dev/null@@ -1,33 +0,0 @@-// No imports: harness-mcp-proxy bundles this file into the agent process.--/** tools/list instructions for the HighLevel MCP server. */-export const HIGHLEVEL_INSTRUCTIONS =- "The HighLevel tools read and update the connected HighLevel (or Growably, or another HighLevel-based) CRM location: contacts, tags, notes, tasks, " +- "pipelines and opportunities, conversations (read only), calendars and events (read only), and the location's custom fields. " +- "Call HIGHLEVEL_GET_LOCATION once to learn the location's name, timezone and custom field names before writing custom fields. " +- "Find a contact with HIGHLEVEL_SEARCH_CONTACTS before creating one; pass ids from results, never guessed ones. " +- "Dates are ISO 8601 strings. Results are trimmed to the fields a person would care about, never raw API dumps. " +- "These tools never send SMS, email, WhatsApp or any other message, and never start campaigns or workflows: do not try to message anyone through the CRM, " +- "and do not work around it with other tools. Every write is recorded in the bot's activity with the record id and the fields changed. " +- "When a tool answers that HighLevel is signed out, ask the person to reconnect it under Connected apps and end the turn.";--/** The system prompt part for a bot whose turn mounts the HighLevel tools. */-export const HIGHLEVEL_PROMPT =- " The user's HighLevel CRM (also Growably and other HighLevel-based CRMs) is reachable through the highlevel tools (HIGHLEVEL_SEARCH_CONTACTS, HIGHLEVEL_GET_CONTACT, " +- "HIGHLEVEL_CREATE_CONTACT, HIGHLEVEL_UPDATE_CONTACT, HIGHLEVEL_ADD_TAGS, HIGHLEVEL_REMOVE_TAGS, HIGHLEVEL_LIST_NOTES, HIGHLEVEL_ADD_NOTE, HIGHLEVEL_LIST_TASKS, HIGHLEVEL_ADD_TASK, " +- "HIGHLEVEL_LIST_PIPELINES, HIGHLEVEL_SEARCH_OPPORTUNITIES, HIGHLEVEL_GET_OPPORTUNITY, HIGHLEVEL_CREATE_OPPORTUNITY, HIGHLEVEL_UPDATE_OPPORTUNITY, " +- "HIGHLEVEL_SEARCH_CONVERSATIONS, HIGHLEVEL_READ_CONVERSATION, HIGHLEVEL_LIST_CALENDARS, HIGHLEVEL_LIST_EVENTS, HIGHLEVEL_GET_LOCATION). " +- "Use them for contacts, tags, notes, tasks, pipelines and deals, reading conversations, and reading calendars; only the tools this bot was granted will run. " +- "You can never message anyone through the CRM (no SMS, email, WhatsApp, campaigns or workflows); if the user asks for that, say it is not available and offer to prepare the text instead. " +- "Every change you make in the CRM is recorded in your activity with the record id and the fields changed. " +- "If a HighLevel tool says it is signed out, ask the user to reconnect HighLevel under Connected apps and end the turn.";--/** The failed-call text when the connection is signed out: the bot asks the person to reconnect and ends the turn. */-export const HIGHLEVEL_SIGNED_OUT_TEXT =- "OpenMausBot note: HighLevel is signed out (its sign-in expired or was revoked), so this call did not run. " +- "Ask the person to reconnect HighLevel under Connected apps in OpenMausBot, then end this turn. Do not retry this call before they reconnect.";--/** The failed-call text when no connection exists at all. */-export const HIGHLEVEL_NOT_CONNECTED_TEXT =- "OpenMausBot note: HighLevel is not connected, so this call did not run. " +- "Ask the person to connect HighLevel under Connected apps in OpenMausBot, then end this turn.";diff --git a/server/highlevel/relay.ts b/server/highlevel/relay.tsdeleted file mode 100644index 496a74cc68..0000000000--- a/server/highlevel/relay.ts+++ /dev/null@@ -1,119 +0,0 @@-// The OpenMausBot relay (accounts.openmausbot.com) holds HighLevel's client secret; this server only ever sees-// tokens. Contract: spec §9 (start → authorizationUrl, claim once → tokens, refresh → new pair).-import { z } from "zod";--export const HIGHLEVEL_RELAY_URL_DEFAULT = "https://accounts.openmausbot.com";-export const HIGHLEVEL_RELAY_ENV = "OMB_HIGHLEVEL_RELAY_URL";-const RELAY_TIMEOUT_MS = 20_000;-const MAX_RELAY_BYTES = 64_000;--/** The relay URL, or null when the integration is switched off (`OMB_HIGHLEVEL_RELAY_URL=off`) or misconfigured. */-export function highlevelRelayUrl(env: NodeJS.ProcessEnv = process.env): string | null {- const raw = env[HIGHLEVEL_RELAY_ENV]?.trim();- if (raw === undefined || raw === "") return HIGHLEVEL_RELAY_URL_DEFAULT;- if (/^(off|none|0|false)$/iu.test(raw)) return null;- try {- const url = new URL(raw);- if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) return null;- return url.origin + url.pathname.replace(/\/+$/u, "");- } catch {- return null;- }-}--const tokensSchema = z.object({- accessToken: z.string().min(1),- refreshToken: z.string().min(1),- expiresIn: z.number().positive(),- scope: z.string().default(""),- locationId: z.string().min(1),- companyId: z.string().optional(),- userId: z.string().optional(),-});--const startSchema = z.object({- state: z.string().min(1),- authorizationUrl: z.string().url(),- expiresAt: z.union([z.number(), z.string()]),-});--export type RelayTokens = z.infer<typeof tokensSchema>;-export type RelayStart = { state: string; authorizationUrl: string; expiresAt: number };--export class HighLevelRelayError extends Error {- readonly status: number;- readonly code: string;- constructor(status: number, code: string, message: string) {- super(message);- this.name = "HighLevelRelayError";- this.status = status;- this.code = code;- }-}--export interface HighLevelRelay {- start(): Promise<RelayStart>;- /** "pending" before HighLevel has called back; "claimed" once the payload was collected (410). */- claim(state: string): Promise<RelayTokens | "pending" | "claimed">;- refresh(refreshToken: string): Promise<RelayTokens>;-}--async function boundedJson(response: Response): Promise<unknown> {- const text = await response.text();- if (text.length > MAX_RELAY_BYTES) throw new HighLevelRelayError(502, "relay_oversized", "The OpenMausBot relay sent an oversized answer.");- try {- return text ? JSON.parse(text) : {};- } catch {- return {};- }-}--export function createHighLevelRelay(relayUrl: string, fetchImpl: typeof fetch = fetch): HighLevelRelay {- const post = async (path: string, body: unknown): Promise<{ status: number; body: unknown }> => {- let response: Response;- try {- response = await fetchImpl(`${relayUrl}${path}`, {- method: "POST", redirect: "error",- headers: { "content-type": "application/json", accept: "application/json" },- body: JSON.stringify(body), signal: AbortSignal.timeout(RELAY_TIMEOUT_MS),- });- } catch {- throw new HighLevelRelayError(503, "relay_unreachable", "The OpenMausBot relay did not answer; check the connection and try again in a minute.");- }- return { status: response.status, body: await boundedJson(response) };- };- const code = (body: unknown) => (body && typeof body === "object" && typeof (body as { error?: unknown }).error === "string" ? (body as { error: string }).error : "relay_error");- const expectTokens = (body: unknown, where: string): RelayTokens => {- const parsed = tokensSchema.safeParse(body);- if (!parsed.success) throw new HighLevelRelayError(502, "relay_bad_tokens", `The OpenMausBot relay answered ${where} without a usable token set.`);- return parsed.data;- };- return {- async start() {- const { status, body } = await post("/v1/highlevel/start", { kind: "location" });- if (status === 503) throw new HighLevelRelayError(503, code(body), "HighLevel sign-in is not available on the OpenMausBot relay right now.");- if (status !== 200) throw new HighLevelRelayError(status, code(body), `The OpenMausBot relay refused to start a HighLevel sign-in (${status}).`);- const parsed = startSchema.safeParse(body);- if (!parsed.success) throw new HighLevelRelayError(502, "relay_bad_start", "The OpenMausBot relay answered without a sign-in link.");- const expiresAt = typeof parsed.data.expiresAt === "number" ? parsed.data.expiresAt : Date.parse(parsed.data.expiresAt);- const url = new URL(parsed.data.authorizationUrl);- if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost"].includes(url.hostname))) {- throw new HighLevelRelayError(502, "relay_bad_start", "The OpenMausBot relay answered with a sign-in link that is not https.");- }- return { state: parsed.data.state, authorizationUrl: parsed.data.authorizationUrl, expiresAt: Number.isFinite(expiresAt) ? expiresAt : Date.now() + 600_000 };- },- async claim(state) {- const { status, body } = await post("/v1/highlevel/claim", { state });- if (status === 404) return "pending";- if (status === 410) return "claimed";- if (status !== 200) throw new HighLevelRelayError(status, code(body), `The OpenMausBot relay could not finish the HighLevel sign-in (${status}).`);- return expectTokens(body, "the sign-in");- },- async refresh(refreshToken) {- const { status, body } = await post("/v1/highlevel/refresh", { refreshToken });- if (status === 401) throw new HighLevelRelayError(401, code(body), "HighLevel rejected the saved sign-in; connect it again.");- if (status !== 200) throw new HighLevelRelayError(status, code(body), `The OpenMausBot relay could not refresh the HighLevel sign-in (${status}).`);- return expectTokens(body, "the refresh");- },- };-}diff --git a/server/highlevel/rpc.test.ts b/server/highlevel/rpc.test.tsdeleted file mode 100644index f56cc3df35..0000000000--- a/server/highlevel/rpc.test.ts+++ /dev/null@@ -1,239 +0,0 @@-// Per-bot scoping and the JSON-RPC entry: tools/list shows what the bot may run, a write by a read-only bot is-// refused with the connector scope text, grants narrow the list, and a successful write is recorded.-import { mkdtempSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";--import { HIGHLEVEL_TOOL_GROUPS, HIGHLEVEL_TOOL_NAMES, highlevelGroupsForTools, highlevelToolsForGroups } from "../../shared/highlevel.ts";-import { connectorScopeRefusalText } from "../connector-verdict.ts";-import { removeTempDir } from "../testing/cleanup.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, type FakeHighLevel } from "../testing/fake-highlevel.ts";-import { describeTool } from "../activity.ts";-import { highlevelAccess, highlevelAllowedFor, highlevelSystemPrompt, type HighLevelBot } from "./access.ts";-import { HighLevelClient } from "./client.ts";-import { HIGHLEVEL_INSTRUCTIONS, HIGHLEVEL_PROMPT, HIGHLEVEL_SIGNED_OUT_TEXT } from "./instructions.ts";-import { createHighLevelHost, writeSummary } from "./host.ts";-import { HIGHLEVEL_INTERNAL_MCP_PATH, highlevelRpc, type HighLevelRpcDeps } from "./rpc.ts";-import { HighLevelStore } from "./store.ts";-import { isHighLevelWrite, type HighLevelWriteRecord } from "./tools.ts";-import { createHighLevelService } from "./service.ts";--let hl: FakeHighLevel;-const dirs: string[] = [];-beforeAll(async () => { hl = await startFakeHighLevel(); hl.tokens.add("hl_access_seed"); });-afterAll(async () => { await hl.close(); });-beforeEach(() => { hl.calls.length = 0; });-afterEach(async () => { for (const dir of dirs.splice(0)) await removeTempDir(dir); });--const call = (name: string, args: unknown = {}) => ({ method: "tools/call", params: { name, arguments: args } });-const READ = HIGHLEVEL_TOOL_NAMES.filter((name) => !isHighLevelWrite(name));-const WRITE = HIGHLEVEL_TOOL_NAMES.filter((name) => isHighLevelWrite(name));--function harness(bot: HighLevelBot, options: { connected?: boolean } = {}) {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-rpc-"));- dirs.push(dir);- const store = new HighLevelStore({ dataDir: dir });- if (options.connected !== false) store.put({ kind: "oauth", accessToken: "hl_access_seed", refreshToken: "r", expiresAt: Date.now() + 3_600_000, locationId: FAKE_LOCATION_ID, scopes: "" });- const client = new HighLevelClient({ store, refresh: null, apiUrl: hl.url });- const writes: HighLevelWriteRecord[] = [];- let checks = 0;- const deps: HighLevelRpcDeps = {- client, assertActive: () => { checks++; },- authorize: (name) => { const verdict = highlevelAccess(bot, name); return verdict.ok ? { ok: true } : { ok: false, text: verdict.text }; },- onWrite: (record) => { writes.push(record); },- };- return { deps, writes, checks: () => checks, store, dir };-}--const legacy: HighLevelBot = { id: "b1", name: "Scout" };-const readOnly: HighLevelBot = { id: "b2", name: "Reader", connectorScopes: { apps: { highlevel: "read", gmail: "write" } } };-const contactsOnly: HighLevelBot = { id: "b3", name: "Sales", connectorTools: { highlevel: { tools: highlevelToolsForGroups(["contacts"]) } }, connectorScopes: { apps: { highlevel: "write" } } };--describe("read and write split", () => {- it("decides by the verb: SEARCH/GET/LIST/READ read, the rest write", () => {- expect(READ).toEqual(["HIGHLEVEL_SEARCH_CONTACTS", "HIGHLEVEL_GET_CONTACT", "HIGHLEVEL_LIST_NOTES", "HIGHLEVEL_LIST_TASKS", "HIGHLEVEL_LIST_PIPELINES",- "HIGHLEVEL_SEARCH_OPPORTUNITIES", "HIGHLEVEL_GET_OPPORTUNITY", "HIGHLEVEL_SEARCH_CONVERSATIONS", "HIGHLEVEL_READ_CONVERSATION", "HIGHLEVEL_LIST_CALENDARS",- "HIGHLEVEL_LIST_EVENTS", "HIGHLEVEL_GET_LOCATION"]);- expect(WRITE).toEqual(["HIGHLEVEL_CREATE_CONTACT", "HIGHLEVEL_UPDATE_CONTACT", "HIGHLEVEL_ADD_TAGS", "HIGHLEVEL_REMOVE_TAGS", "HIGHLEVEL_ADD_NOTE", "HIGHLEVEL_ADD_TASK",- "HIGHLEVEL_CREATE_OPPORTUNITY", "HIGHLEVEL_UPDATE_OPPORTUNITY"]);- });-- it("maps the settings groups to tool grants and back", () => {- expect(highlevelToolsForGroups(["contacts", "calendars"])).toContain("HIGHLEVEL_LIST_EVENTS");- expect(highlevelToolsForGroups(["calendars"])).toEqual(["HIGHLEVEL_LIST_CALENDARS", "HIGHLEVEL_LIST_EVENTS", "HIGHLEVEL_GET_LOCATION"]);- expect(highlevelGroupsForTools("*")).toEqual(["contacts", "pipelines", "conversations", "calendars"]);- expect(highlevelGroupsForTools(HIGHLEVEL_TOOL_GROUPS.contacts.tools)).toEqual(["contacts"]);- expect(new Set(Object.values(HIGHLEVEL_TOOL_GROUPS).flatMap((group) => group.tools))).toEqual(new Set(HIGHLEVEL_TOOL_NAMES));- });-});--describe("per-bot access", () => {- it("mounts for a legacy bot, not for one with connected apps off or a scope or grant record without highlevel", () => {- expect(highlevelAllowedFor(legacy)).toBe(true);- expect(highlevelAllowedFor(readOnly)).toBe(true);- expect(highlevelAllowedFor(contactsOnly)).toBe(true);- expect(highlevelAllowedFor({ ...legacy, composio: false })).toBe(false);- expect(highlevelAllowedFor({ ...legacy, connectorScopes: { apps: { gmail: "write" } } })).toBe(false);- expect(highlevelAllowedFor({ ...legacy, connectorTools: { gmail: { tools: "*" } } })).toBe(false);- expect(highlevelAllowedFor({ ...legacy, connectorTools: {} })).toBe(false);- });-- it("refuses a write for a read-only bot with the connector scope text and a decision row", () => {- const verdict = highlevelAccess(readOnly, "HIGHLEVEL_ADD_NOTE");- expect(verdict.ok).toBe(false);- if (verdict.ok) throw new Error("unreachable");- expect(verdict.text).toBe(connectorScopeRefusalText({ kind: "tools", invoked: "HIGHLEVEL_ADD_NOTE", names: ["HIGHLEVEL_ADD_NOTE"] }, "write", "Reader", "HighLevel", "Add note"));- expect(verdict.text).toBe("OpenMausBot did not run this: HighLevel is read-only for Reader, and Add note would write to it. Ask the user before trying again.");- expect(verdict.rows).toEqual([{ tool: "HIGHLEVEL_ADD_NOTE", decision: "auto-denied", rule: "scope:highlevel:write" }]);- expect(highlevelAccess(readOnly, "HIGHLEVEL_GET_CONTACT")).toMatchObject({ ok: true, rows: [{ decision: "auto-approved", rule: "scope:highlevel" }] });- });-- it("refuses a tool outside the bot's grant without naming the others", () => {- const verdict = highlevelAccess(contactsOnly, "HIGHLEVEL_LIST_PIPELINES");- expect(verdict.ok).toBe(false);- if (verdict.ok) throw new Error("unreachable");- expect(verdict.text).toBe('"HIGHLEVEL_LIST_PIPELINES" is not granted to this bot. This call was not performed. Ask the person to grant it in OpenMausBot if they want it run.');- expect(verdict.text).not.toContain("HIGHLEVEL_GET_CONTACT");- expect(verdict.rows[0]).toMatchObject({ decision: "auto-denied", rule: "connectorTools.highlevel", summary: "tool is not in this service's grant" });- expect(highlevelAccess(contactsOnly, "HIGHLEVEL_ADD_NOTE")).toMatchObject({ ok: true, rows: [{ rule: "connectorTools.highlevel" }] });- const off = highlevelAccess({ ...legacy, composio: false }, "HIGHLEVEL_GET_CONTACT");- expect(off.ok).toBe(false);- if (!off.ok) expect(off.text).toContain("Scout has not been given access to HighLevel");- });-- it("writes the prompt part with the scope and the granted tools", () => {- expect(highlevelSystemPrompt(legacy)).toBe(HIGHLEVEL_PROMPT);- expect(highlevelSystemPrompt(readOnly)).toBe(HIGHLEVEL_PROMPT + " This bot may use only these connected apps: highlevel (read only). Do not try others, and do not write to a read-only one.");- expect(highlevelSystemPrompt(contactsOnly)).toContain("granted only: HIGHLEVEL_SEARCH_CONTACTS, HIGHLEVEL_GET_CONTACT");- expect(highlevelSystemPrompt(contactsOnly)).not.toContain("HIGHLEVEL_LIST_PIPELINES.");- expect(HIGHLEVEL_PROMPT).toMatch(/never message anyone through the CRM/u);- expect(HIGHLEVEL_PROMPT).toMatch(/recorded in your activity/u);- for (const name of HIGHLEVEL_TOOL_NAMES) expect(HIGHLEVEL_PROMPT).toContain(name);- });-- it("labels the activity rows HighLevel", () => {- expect(describeTool("mcp__highlevel__HIGHLEVEL_ADD_NOTE")).toEqual({ app: "HighLevel", label: "Add note" });- expect(describeTool("HIGHLEVEL_UPDATE_CONTACT")).toEqual({ app: "HighLevel", label: "Update contact" });- expect(writeSummary({ tool: "HIGHLEVEL_UPDATE_CONTACT", kind: "contact", recordId: "contact_1", fields: ["email", "tags"] })).toBe("contact contact_1: email, tags");- });-});--describe("highlevelRpc", () => {- it("lists only the tools the bot may run, with the instructions, and touches no API", async () => {- const all = await highlevelRpc({ method: "tools/list" }, harness(legacy).deps) as { tools: Array<{ name: string; inputSchema: { additionalProperties: boolean } }>; instructions: string };- expect(all.tools.map((tool) => tool.name)).toEqual([...HIGHLEVEL_TOOL_NAMES]);- expect(all.tools.every((tool) => tool.inputSchema.additionalProperties === false)).toBe(true);- expect(all.instructions).toBe(HIGHLEVEL_INSTRUCTIONS);- const reads = await highlevelRpc({ method: "tools/list" }, harness(readOnly).deps) as { tools: Array<{ name: string }> };- expect(reads.tools.map((tool) => tool.name)).toEqual(READ);- const contacts = await highlevelRpc({ method: "tools/list" }, harness(contactsOnly).deps) as { tools: Array<{ name: string }> };- expect(contacts.tools.map((tool) => tool.name)).toEqual(HIGHLEVEL_TOOL_GROUPS.contacts.tools);- expect(hl.calls).toEqual([]);- expect(HIGHLEVEL_INTERNAL_MCP_PATH).toBe("/api/internal/highlevel/mcp");- });-- it("validates arguments before the capability check or any request", async () => {- const { deps, checks } = harness(legacy);- const bad = await highlevelRpc(call("HIGHLEVEL_GET_CONTACT", { contactId: 5 }), deps) as { isError?: boolean; content: Array<{ text: string }> };- expect(bad.isError).toBe(true);- expect(bad.content[0].text).toMatch(/do not match the advertised input schema/u);- const unknown = await highlevelRpc(call("HIGHLEVEL_SEND_SMS", {}), deps) as { isError?: boolean; content: Array<{ text: string }> };- expect(unknown.isError).toBe(true);- expect(unknown.content[0].text).toMatch(/Unknown HighLevel tool/u);- const extra = await highlevelRpc(call("HIGHLEVEL_LIST_PIPELINES", { locationId: "x" }), deps) as { isError?: boolean };- expect(extra.isError).toBe(true);- expect(checks()).toBe(0);- expect(hl.calls).toEqual([]);- await expect(highlevelRpc({ method: "resources/list" }, deps)).rejects.toMatchObject({ status: 400 });- });-- it("runs an allowed call with the capability checked before and after, and records a write", async () => {- const { deps, writes, checks } = harness(legacy);- const read = await highlevelRpc(call("HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" }), deps) as { isError?: boolean; structuredContent: Record<string, unknown> };- expect(read.isError).toBeUndefined();- expect(read.structuredContent).toMatchObject({ id: "contact_1", email: "[email protected]" });- expect(checks()).toBeGreaterThanOrEqual(2);- expect(writes).toEqual([]);- const write = await highlevelRpc(call("HIGHLEVEL_UPDATE_CONTACT", { contactId: "contact_1", email: "[email protected]", tags: ["a"] }), deps) as { isError?: boolean };- expect(write.isError).toBeUndefined();- expect(writes).toEqual([{ tool: "HIGHLEVEL_UPDATE_CONTACT", kind: "contact", recordId: "contact_1", fields: ["email", "tags"] }]);- expect(JSON.stringify(writes)).not.toContain("[email protected]");- await highlevelRpc(call("HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Private note text" }), deps);- expect(writes.at(-1)).toEqual({ tool: "HIGHLEVEL_ADD_NOTE", kind: "note", recordId: "note_new", fields: ["body"] });- expect(JSON.stringify(writes)).not.toContain("Private note");- await highlevelRpc(call("HIGHLEVEL_CREATE_OPPORTUNITY", { pipelineId: "pipe_1", contactId: "contact_1", name: "Deal", value: 9 }), deps);- expect(writes.at(-1)).toEqual({ tool: "HIGHLEVEL_CREATE_OPPORTUNITY", kind: "opportunity", recordId: "opp_new", fields: ["contactId", "name", "pipelineId", "value"] });- });-- it("refuses a read-only bot's write before any request and records nothing", async () => {- const { deps, writes } = harness(readOnly);- const refused = await highlevelRpc(call("HIGHLEVEL_ADD_TAGS", { contactId: "contact_1", tags: ["vip"] }), deps) as { isError?: boolean; content: Array<{ text: string }> };- expect(refused.isError).toBe(true);- expect(refused.content[0].text).toBe("OpenMausBot did not run this: HighLevel is read-only for Reader, and Add tags would write to it. Ask the user before trying again.");- expect(hl.calls).toEqual([]);- expect(writes).toEqual([]);- const allowed = await highlevelRpc(call("HIGHLEVEL_LIST_NOTES", { contactId: "contact_1" }), deps) as { isError?: boolean };- expect(allowed.isError).toBeUndefined();- expect(hl.calls).toHaveLength(1);- });-- it("does not record a write that failed", async () => {- const { deps, writes } = harness(legacy);- hl.overrides.push({ status: 403, body: { message: "no" } }, { status: 403, body: { message: "no" } });- const failed = await highlevelRpc(call("HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "x" }), deps) as { isError?: boolean; content: Array<{ text: string }> };- expect(failed.isError).toBe(true);- expect(failed.content[0].text).toMatch(/^HighLevel refused this \(403\): the connection lacks the contacts\.write permission\./u);- expect(writes).toEqual([]);- hl.overrides.length = 0;- });-- it("answers the signed-out note so the bot asks the person to reconnect", async () => {- const { deps, store } = harness(legacy);- store.markNeedsSignIn("revoked", store.get()!);- const out = await highlevelRpc(call("HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" }), deps) as { isError?: boolean; content: Array<{ text: string }>; structuredContent: Record<string, unknown> };- expect(out.isError).toBe(true);- expect(out.content[0].text).toBe(HIGHLEVEL_SIGNED_OUT_TEXT);- expect(out.structuredContent.signedOut).toBe(true);- expect(hl.calls).toEqual([]);- });-});--describe("host", () => {- it("mounts only with a connection and an allowed bot, records writes as activity rows, and lists itself in health only while a connection is saved", async () => {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-host-"));- dirs.push(dir);- const service = createHighLevelService({ dataDir: dir, env: { OMB_HIGHLEVEL_RELAY_URL: "http://127.0.0.1:9", OMB_HIGHLEVEL_API_URL: hl.url } });- const bots = new Map<string, HighLevelBot & { color?: string }>([["b1", { ...legacy, color: "#abc" }], ["b4", { id: "b4", name: "Off", composio: false }]]);- const rows: Array<{ threadId: string; message: Record<string, unknown> }> = [];- const host = createHighLevelHost({ service, dataDir: dir, bot: (id) => bots.get(id), inRoom: (threadId) => threadId.startsWith("room"), appendMessage: (threadId, message) => { rows.push({ threadId, message }); } });- expect(host.mounts(legacy)).toBe(false);- expect(host.integration(legacy, () => "tok", "http://127.0.0.1:1")).toBeNull();- expect(await host.health(null)).toBeNull();- expect(await host.health(Promise.resolve({ gmail: { connected: false } }))).toEqual({ gmail: { connected: false } });- expect(host.toolListing()?.highlevel.map((tool) => tool.name)).toEqual([...HIGHLEVEL_TOOL_NAMES]);- service.store.put({ kind: "oauth", accessToken: "hl_access_seed", refreshToken: "r", expiresAt: Date.now() + 3_600_000, locationId: FAKE_LOCATION_ID, scopes: "" });- expect(host.mounts(legacy)).toBe(true);- expect(host.mounts({ id: "b4", name: "Off", composio: false })).toBe(false);- const mounted = host.integration(legacy, () => "turn-token", "http://127.0.0.1:1")!;- expect(mounted.args.at(-1)).toBe("highlevel");- expect(mounted.env).toMatchObject({ OMB_MCP_TOKEN_HIGHLEVEL: "turn-token", OMB_HARNESS_URL: "http://127.0.0.1:1" });- expect(await host.health(null)).toEqual({ highlevel: { connected: true } });- expect(await host.health(Promise.resolve({ gmail: { connected: true } }))).toEqual({ gmail: { connected: true }, highlevel: { connected: true } });- const result = await host.handle(call("HIGHLEVEL_ADD_NOTE", { contactId: "contact_1", body: "Secret body" }), { botId: "b1", threadId: "room-1" }, () => {}) as { isError?: boolean };- expect(result.isError).toBeUndefined();- expect(rows).toEqual([{ threadId: "room-1", message: { role: "bot", kind: "activity", tool: { name: "mcp__highlevel__HIGHLEVEL_ADD_NOTE", ok: true, summary: "note note_new: body" }, from: { botId: "b1", name: "Scout", color: "#abc" } } }]);- expect(JSON.stringify(rows)).not.toContain("Secret body");- const off = await host.handle(call("HIGHLEVEL_GET_CONTACT", { contactId: "contact_1" }), { botId: "b4", threadId: "t" }, () => {}) as { isError?: boolean; content: Array<{ text: string }> };- expect(off.isError).toBe(true);- expect(off.content[0].text).toContain("Off has not been given access to HighLevel");- const listed = await host.handle({ method: "tools/list" }, { botId: "b4", threadId: "t" }, () => {}) as { tools: unknown[] };- expect(listed.tools).toEqual([]);- service.store.markNeedsSignIn("revoked", service.store.get()!);- expect(await host.health(Promise.resolve({ gmail: { connected: true } }))).toEqual({ gmail: { connected: true }, highlevel: { connected: false } });- service.disconnect();- expect(await host.health(Promise.resolve({ gmail: { connected: true } }))).toEqual({ gmail: { connected: true } });- expect(await host.health(null)).toBeNull();- service.close();- });-});diff --git a/server/highlevel/rpc.ts b/server/highlevel/rpc.tsdeleted file mode 100644index 51b3805293..0000000000--- a/server/highlevel/rpc.ts+++ /dev/null@@ -1,41 +0,0 @@-// The JSON-RPC entry the harness proxy reaches: tools/list (filtered to what this bot may run) and tools/call-// (validate → per-bot verdict → run). The turn's capability must still be live before and after the call.-import { HIGHLEVEL_INSTRUCTIONS } from "./instructions.ts";-import type { HighLevelClient } from "./client.ts";-import { HIGHLEVEL_TOOLS, highlevelErrorResult, highlevelToolCallProblem, isHighLevelToolName, runHighLevelTool, type HighLevelTool, type HighLevelToolResult, type HighLevelWriteRecord } from "./tools.ts";--export const HIGHLEVEL_INTERNAL_MCP_PATH = "/api/internal/highlevel/mcp";--export interface HighLevelRpcDeps {- client: HighLevelClient;- assertActive(): void;- /** The per-bot verdict for one tool name; a refusal's text is returned to the bot as a failed call. */- authorize(name: string): { ok: true } | { ok: false; text: string };- /** A successful write: the handler records it in the bot's activity. */- onWrite?(record: HighLevelWriteRecord): void;-}--export type HighLevelToolsList = { tools: HighLevelTool[]; instructions: string };--export async function highlevelRpc(- request: { method?: unknown; params?: unknown } | null | undefined,- deps: HighLevelRpcDeps,-): Promise<HighLevelToolsList | HighLevelToolResult> {- if (request?.method === "tools/list") {- deps.assertActive();- return { tools: HIGHLEVEL_TOOLS.filter((tool) => deps.authorize(tool.name).ok), instructions: HIGHLEVEL_INSTRUCTIONS };- }- if (request?.method !== "tools/call") throw Object.assign(new Error("unsupported highlevel method"), { status: 400 });- const params = (request.params && typeof request.params === "object" ? request.params : {}) as { name?: unknown; arguments?: unknown };- const args = params.arguments ?? {};- const problem = highlevelToolCallProblem(params.name, args);- if (problem || !isHighLevelToolName(params.name)) return highlevelErrorResult(problem ?? "Unknown HighLevel tool.", { code: "invalid_input" });- const name = params.name;- deps.assertActive();- const verdict = deps.authorize(name);- if (!verdict.ok) return highlevelErrorResult(verdict.text, { code: "refused" });- const { result, write } = await deps.client.withActiveCall(deps.assertActive, () => runHighLevelTool(deps.client, name, args as Record<string, unknown>));- deps.assertActive();- if (write && !result.isError) deps.onWrite?.(write);- return result;-}diff --git a/server/highlevel/service.ts b/server/highlevel/service.tsdeleted file mode 100644index 1ac15cd6c6..0000000000--- a/server/highlevel/service.ts+++ /dev/null@@ -1,104 +0,0 @@-// The HighLevel connection as one object: its store, API client, sign-in flow and the status the app shows.-// Desktop and Cloud home build the same service; only DATA_DIR and the relay URL differ.-import type { HighLevelStatus } from "../../shared/highlevel.ts";-import { HIGHLEVEL_API_ENV, HighLevelClient, HighLevelError, lookupLocation } from "./client.ts";-import { createHighLevelRelay, highlevelRelayUrl, type HighLevelRelay } from "./relay.ts";-import { HighLevelSignIn } from "./sign-in.ts";-import { HighLevelStore, type HighLevelConnection } from "./store.ts";--export interface HighLevelServiceOptions {- dataDir: string;- env?: NodeJS.ProcessEnv;- fetch?: typeof fetch;- now?: () => number;- pollMs?: number;- /** Status changes the app may want to push (connected, signed out). */- onChange?(): void;-}--export interface HighLevelService {- readonly store: HighLevelStore;- readonly client: HighLevelClient;- readonly relayUrl: string | null;- connected(): boolean;- status(): HighLevelStatus;- startSignIn(): Promise<{ flowId: string; authorizationUrl: string; expiresAt: number }>;- signInStatus(flowId: string): ReturnType<HighLevelSignIn["status"]>;- cancelSignIn(flowId: string): boolean;- connectWithToken(token: string, locationId: string): Promise<HighLevelStatus>;- disconnect(): HighLevelStatus;- /** A connection moved here from the person's own computer; one already signed in here is kept, unless `replaces` says- * it is the one that computer moved here before. */- adopt(connection: HighLevelConnection, replaces?: (current: HighLevelConnection) => boolean): "adopted" | "kept";- close(): void;-}--const PIT = /^pit-[A-Za-z0-9_-]{8,}$/u;-const LOCATION_ID = /^[A-Za-z0-9_-]{4,64}$/u;--export function createHighLevelService(options: HighLevelServiceOptions): HighLevelService {- const env = options.env ?? process.env;- const fetchImpl = options.fetch ?? fetch;- const now = options.now ?? Date.now;- const relayUrl = highlevelRelayUrl(env);- const relay: HighLevelRelay | null = relayUrl ? createHighLevelRelay(relayUrl, fetchImpl) : null;- // The API base is fixed; the env override exists for tests against a fake HighLevel.- const apiUrl = env[HIGHLEVEL_API_ENV];- const store = new HighLevelStore({ dataDir: options.dataDir, now });- const client = new HighLevelClient({ store, refresh: relay ? (token) => relay.refresh(token) : null, apiUrl, fetch: fetchImpl, now });- const lookupName = async (accessToken: string, locationId: string) => (await lookupLocation({ token: accessToken, locationId, apiUrl, fetch: fetchImpl })).name;- const signIn = relay ? new HighLevelSignIn({ relay, store, lookupLocationName: lookupName, now, pollMs: options.pollMs, onChange: options.onChange }) : null;-- const status = (): HighLevelStatus => {- const connection = store.get();- const flow = signIn?.active();- if (flow) return { state: "connecting", flow: { flowId: flow.flowId, authorizationUrl: flow.authorizationUrl, expiresAt: flow.expiresAt } };- if (connection) {- return {- state: connection.state === "signed-in" ? "connected" : "needs-sign-in",- kind: connection.kind,- location: { id: connection.locationId, name: connection.locationName ?? connection.locationId },- connectedAt: connection.connectedAt,- ...(connection.problem ? { problem: connection.problem } : {}),- };- }- return { state: relayUrl ? "signed-out" : "unavailable" };- };-- return {- store, client, relayUrl,- connected: () => store.get()?.state === "signed-in",- status,- async startSignIn() {- if (!signIn) throw new HighLevelError("HighLevel sign-in is not available: no OpenMausBot relay is configured. Use a Private Integration token instead.", { status: 503 });- return signIn.start();- },- signInStatus: (flowId) => signIn?.status(flowId) ?? null,- cancelSignIn: (flowId) => signIn?.cancel(flowId) ?? false,- async connectWithToken(token, locationId) {- const trimmed = token.trim();- if (!PIT.test(trimmed)) throw new HighLevelError("Paste a Private Integration token. It starts with pit-.", { status: 400 });- if (!LOCATION_ID.test(locationId.trim())) throw new HighLevelError("Enter the location id (Settings → Business Profile in HighLevel).", { status: 400 });- const location = await lookupLocation({ token: trimmed, locationId: locationId.trim(), apiUrl, fetch: fetchImpl });- if (signIn) for (const flow of [signIn.active()]) if (flow) signIn.cancel(flow.flowId);- store.put({ kind: "token", accessToken: trimmed, locationId: location.id, ...(location.companyId ? { companyId: location.companyId } : {}), locationName: location.name, scopes: "" });- options.onChange?.();- return status();- },- disconnect() {- if (signIn) for (const flow of [signIn.active()]) if (flow) signIn.cancel(flow.flowId);- store.clear();- options.onChange?.();- return status();- },- adopt(connection, replaces) {- const current = store.get();- if (current?.state === "signed-in" && !replaces?.(current)) return "kept";- if (signIn) for (const flow of [signIn.active()]) if (flow) signIn.cancel(flow.flowId);- store.put(connection);- options.onChange?.();- return "adopted";- },- close: () => signIn?.close(),- };-}diff --git a/server/highlevel/sign-in.test.ts b/server/highlevel/sign-in.test.tsdeleted file mode 100644index 73066120cc..0000000000--- a/server/highlevel/sign-in.test.ts+++ /dev/null@@ -1,257 +0,0 @@-// The sign-in flow and the service's status against the fake relay: start → waiting → claim → connected, the once-only-// claim, expiry, cancellation, the Private Integration token path, disconnect, and the owner routes over all of it.-import { mkdtempSync } from "node:fs";-import type { IncomingMessage, ServerResponse } from "node:http";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";--import { json, readBody } from "../harness/http.ts";-import type { RequestAuth } from "../request-auth.ts";-import { createHighLevelRoutes } from "../routes/highlevel.ts";-import { PASS } from "../routes/table.ts";-import { removeTempDir } from "../testing/cleanup.ts";-import { FAKE_LOCATION_ID, startFakeHighLevel, startFakeRelay, type FakeHighLevel, type FakeRelay } from "../testing/fake-highlevel.ts";-import { HIGHLEVEL_RELAY_URL_DEFAULT, HighLevelRelayError, createHighLevelRelay, highlevelRelayUrl, type HighLevelRelay, type RelayTokens } from "./relay.ts";-import { HighLevelSignIn } from "./sign-in.ts";-import { HighLevelStore } from "./store.ts";-import { createHighLevelService, type HighLevelService } from "./service.ts";--let hl: FakeHighLevel;-let relay: FakeRelay;-const dirs: string[] = [];-const services: HighLevelService[] = [];--beforeAll(async () => {- hl = await startFakeHighLevel();- relay = await startFakeRelay({ onAccessToken: (token) => hl.tokens.add(token) });-});-afterAll(async () => { await hl.close(); await relay.close(); });-afterEach(async () => {- hl.pathOverrides.clear();- for (const service of services.splice(0)) service.close();- for (const dir of dirs.splice(0)) await removeTempDir(dir);-});--function service(env: Record<string, string> = {}) {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-signin-"));- dirs.push(dir);- const created = createHighLevelService({ dataDir: dir, env: { OMB_HIGHLEVEL_RELAY_URL: relay.url, OMB_HIGHLEVEL_API_URL: hl.url, ...env }, pollMs: 20 });- services.push(created);- return created;-}--const until = async <T>(read: () => T, want: (value: T) => boolean, ms = 3_000): Promise<T> => {- const deadline = Date.now() + ms;- for (;;) {- const value = read();- if (want(value)) return value;- if (Date.now() > deadline) throw new Error(`timed out waiting; last ${JSON.stringify(value)}`);- await new Promise((resolve) => setTimeout(resolve, 10));- }-};--describe("relay URL", () => {- it("defaults to accounts.openmausbot.com, accepts https or loopback http, and reads off as unavailable", () => {- expect(highlevelRelayUrl({})).toBe(HIGHLEVEL_RELAY_URL_DEFAULT);- expect(highlevelRelayUrl({ OMB_HIGHLEVEL_RELAY_URL: "" })).toBe(HIGHLEVEL_RELAY_URL_DEFAULT);- expect(highlevelRelayUrl({ OMB_HIGHLEVEL_RELAY_URL: "https://relay.example.test/" })).toBe("https://relay.example.test");- expect(highlevelRelayUrl({ OMB_HIGHLEVEL_RELAY_URL: "http://127.0.0.1:4321" })).toBe("http://127.0.0.1:4321");- expect(highlevelRelayUrl({ OMB_HIGHLEVEL_RELAY_URL: "http://relay.example.test" })).toBeNull();- expect(highlevelRelayUrl({ OMB_HIGHLEVEL_RELAY_URL: "off" })).toBeNull();- expect(highlevelRelayUrl({ OMB_HIGHLEVEL_RELAY_URL: "not a url" })).toBeNull();- });-- it("speaks the control plane's contract: 404 pending, 200 once, 410 after, 401 on a rejected refresh, 503 unavailable", async () => {- const upstream = createHighLevelRelay(relay.url);- const started = await upstream.start();- expect(started.authorizationUrl).toMatch(/^https:\/\/marketplace\.leadconnectorhq\.com\/v2\/oauth\/chooselocation\?/u);- expect(relay.calls.at(-1)).toEqual({ path: "/v1/highlevel/start", body: { kind: "location" } });- expect(await upstream.claim(started.state)).toBe("pending");- relay.complete(started.state);- const tokens = await upstream.claim(started.state);- expect(tokens).toMatchObject({ accessToken: expect.stringMatching(/^hl_access_/u), refreshToken: expect.stringMatching(/^hl_refresh_/u), expiresIn: 86_400, locationId: FAKE_LOCATION_ID });- expect(await upstream.claim(started.state)).toBe("claimed");- if (typeof tokens === "string") throw new Error("unreachable");- const rotated = await upstream.refresh(tokens.refreshToken);- expect(rotated.refreshToken).not.toBe(tokens.refreshToken);- await expect(upstream.refresh(tokens.refreshToken)).rejects.toMatchObject({ status: 401, code: "highlevel_refresh_rejected" });- relay.unavailable = true;- await expect(upstream.start()).rejects.toMatchObject({ status: 503, code: "highlevel_unavailable", message: "HighLevel sign-in is not available on the OpenMausBot relay right now." });- relay.unavailable = false;- });-});--describe("sign-in flow", () => {- it("connects once the person finishes in the browser and stores the location's name", async () => {- const svc = service();- expect(svc.status()).toEqual({ state: "signed-out" });- const started = await svc.startSignIn();- expect(started.authorizationUrl).toMatch(/^https:\/\//u);- expect(svc.status()).toEqual({ state: "connecting", flow: { flowId: started.flowId, authorizationUrl: started.authorizationUrl, expiresAt: started.expiresAt } });- expect(svc.signInStatus(started.flowId)).toEqual({ phase: "waiting" });- expect(svc.signInStatus("00000000-0000-0000-0000-000000000000")).toBeNull();- await new Promise((resolve) => setTimeout(resolve, 60));- expect(svc.signInStatus(started.flowId)).toEqual({ phase: "waiting" });- expect(relay.calls.filter((call) => call.path === "/v1/highlevel/claim").length).toBeGreaterThan(0);- const state = [...relay.states.keys()].at(-1)!;- relay.complete(state);- await until(() => svc.signInStatus(started.flowId), (status) => status?.phase === "connected");- expect(svc.status()).toMatchObject({ state: "connected", kind: "oauth", location: { id: FAKE_LOCATION_ID, name: "Example Profiles" } });- expect(svc.status().connectedAt).toEqual(expect.any(Number));- expect(svc.connected()).toBe(true);- expect(svc.store.get()).toMatchObject({ kind: "oauth", locationName: "Example Profiles", companyId: "company_1", userId: "user_1", scopes: expect.stringContaining("contacts.write") });- // The flow's answer stays readable, and the tokens are nowhere in the status.- expect(JSON.stringify(svc.status())).not.toMatch(/hl_access|hl_refresh/u);- expect(svc.signInStatus(started.flowId)).toEqual({ phase: "connected" });- expect(svc.disconnect()).toEqual({ state: "signed-out" });- expect(svc.store.get()).toBeNull();- });-- it("replaces a waiting flow, cancels on request, and reports a used state as failed", async () => {- const svc = service();- const first = await svc.startSignIn();- const second = await svc.startSignIn();- expect(svc.signInStatus(first.flowId)).toEqual({ phase: "failed", message: "A newer sign-in replaced this one." });- expect(svc.status().flow?.flowId).toBe(second.flowId);- expect(svc.cancelSignIn(second.flowId)).toBe(true);- expect(svc.signInStatus(second.flowId)).toEqual({ phase: "failed", message: "Cancelled." });- expect(svc.status()).toEqual({ state: "signed-out" });- const third = await svc.startSignIn();- const state = [...relay.states.keys()].at(-1)!;- relay.complete(state);- relay.states.get(state)!.claimed = true;- await until(() => svc.signInStatus(third.flowId), (status) => status?.phase === "failed");- expect(svc.signInStatus(third.flowId)).toEqual({ phase: "failed", message: "This sign-in was already used. Start again." });- });-- it("expires after the cap and keeps polling through relay hiccups", async () => {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-signin-"));- dirs.push(dir);- let now = Date.now();- const svc = createHighLevelService({ dataDir: dir, env: { OMB_HIGHLEVEL_RELAY_URL: relay.url, OMB_HIGHLEVEL_API_URL: hl.url }, pollMs: 10, now: () => now });- services.push(svc);- const started = await svc.startSignIn();- relay.unavailable = true;- await new Promise((resolve) => setTimeout(resolve, 50));- expect(svc.signInStatus(started.flowId)).toEqual({ phase: "waiting" });- relay.unavailable = false;- now += 11 * 60_000;- await until(() => svc.signInStatus(started.flowId), (status) => status?.phase === "expired");- expect(svc.signInStatus(started.flowId)).toEqual({ phase: "expired", message: "The sign-in took longer than 10 minutes. Start again." });- });-- it("is unavailable without a relay, and a Private Integration token still works", async () => {- const svc = service({ OMB_HIGHLEVEL_RELAY_URL: "off" });- expect(svc.status()).toEqual({ state: "unavailable" });- await expect(svc.startSignIn()).rejects.toThrow(/no OpenMausBot relay is configured/u);- await expect(svc.connectWithToken("nope", FAKE_LOCATION_ID)).rejects.toThrow("Paste a Private Integration token. It starts with pit-.");- await expect(svc.connectWithToken("pit-abcdefgh12345678", "x")).rejects.toThrow(/Enter the location id/u);- await expect(svc.connectWithToken("pit-abcdefgh12345678", FAKE_LOCATION_ID)).rejects.toThrow(/^HighLevel did not accept this token \(401\)\./u);- expect(svc.store.get()).toBeNull();- hl.tokens.add("pit-abcdefgh12345678");- expect(await svc.connectWithToken(" pit-abcdefgh12345678 ", ` ${FAKE_LOCATION_ID} `)).toMatchObject({ state: "connected", kind: "token", location: { id: FAKE_LOCATION_ID, name: "Example Profiles" } });- expect(svc.store.get()).toMatchObject({ kind: "token", accessToken: "pit-abcdefgh12345678", companyId: "company_1" });- expect(svc.store.get()?.refreshToken).toBeUndefined();- svc.store.markNeedsSignIn("HighLevel rejected the Private Integration token.", svc.store.get()!);- expect(svc.status()).toMatchObject({ state: "needs-sign-in", kind: "token", problem: "HighLevel rejected the Private Integration token." });- });-});--describe("a replaced flow's late claim", () => {- function staged() {- const dir = mkdtempSync(join(tmpdir(), "omb-highlevel-signin-"));- dirs.push(dir);- const claims: Array<{ state: string; reject(error: unknown): void }> = [];- let starts = 0;- const stub: HighLevelRelay = {- start: async () => ({ state: `state_${++starts}`, authorizationUrl: "https://marketplace.leadconnectorhq.com/v2/oauth/chooselocation", expiresAt: Date.now() + 600_000 }),- claim: (state) => new Promise<RelayTokens | "pending" | "claimed">((_resolve, reject) => { claims.push({ state, reject }); }),- refresh: () => Promise.reject(new Error("unused")),- };- const signIn = new HighLevelSignIn({ relay: stub, store: new HighLevelStore({ dataDir: dir }), lookupLocationName: async () => undefined, pollMs: 1 });- const claimsFor = (state: string) => claims.filter((claim) => claim.state === state);- return { signIn, claims, claimsFor };- }-- it.each([- ["refused", new HighLevelRelayError(400, "highlevel_bad_state", "The relay refused this sign-in.")],- ["unavailable", new HighLevelRelayError(503, "highlevel_unavailable", "The relay is down.")],- ])("leaves the newer flow alone when the replaced flow's claim fails late (%s)", async (_name, failure) => {- const { signIn, claimsFor } = staged();- try {- const first = await signIn.start();- await until(() => claimsFor("state_1").length, (count) => count === 1);- const second = await signIn.start();- await until(() => claimsFor("state_2").length, (count) => count === 1);- claimsFor("state_1")[0]!.reject(failure);- await new Promise((resolve) => setTimeout(resolve, 30));- expect(signIn.active()?.flowId).toBe(second.flowId);- expect(signIn.status(second.flowId)).toEqual({ phase: "waiting" });- expect(signIn.status(first.flowId)).toEqual({ phase: "failed", message: "A newer sign-in replaced this one." });- expect(claimsFor("state_1")).toHaveLength(1);- expect(claimsFor("state_2")).toHaveLength(1);- } finally {- signIn.close();- }- });-});--describe("owner routes", () => {- const admin: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };- const member: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };- async function request(handler: ReturnType<typeof createHighLevelRoutes>, method: string, path: string, auth: RequestAuth, body?: unknown) {- const { createServer } = await import("node:http");- const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {- const url = new URL(req.url ?? "/", "http://fixture");- const out = await handler({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });- if (out === PASS && !res.writableEnded) { res.writeHead(599); res.end("pass"); }- });- await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));- try {- const port = (server.address() as { port: number }).port;- const response = await fetch(`http://127.0.0.1:${port}${path}`, { method, headers: body === undefined ? {} : { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });- const text = await response.text();- return { status: response.status, body: text === "pass" ? "pass" : JSON.parse(text) };- } finally {- server.closeAllConnections();- await new Promise<void>((resolve) => server.close(() => resolve()));- }- }-- it("answers the contract for the owner and refuses everyone else", async () => {- const svc = service();- const routes = createHighLevelRoutes({ service: svc });- expect(await request(routes, "GET", "/api/bots", admin)).toMatchObject({ status: 599, body: "pass" });- expect(await request(routes, "GET", "/api/highlevel", member)).toMatchObject({ status: 403, body: { error: expect.stringMatching(/owner or an admin/u) } });- expect(await request(routes, "GET", "/api/highlevel", admin)).toEqual({ status: 200, body: { state: "signed-out" } });- const started = await request(routes, "POST", "/api/highlevel/sign-in", admin);- expect(started.status).toBe(200);- expect(started.body).toEqual({ flowId: expect.stringMatching(/^[0-9a-f-]{36}$/u), authorizationUrl: expect.stringMatching(/^https:\/\//u), expiresAt: expect.any(Number) });- expect(await request(routes, "GET", "/api/highlevel", admin)).toMatchObject({ status: 200, body: { state: "connecting", flow: { flowId: started.body.flowId } } });- expect(await request(routes, "GET", `/api/highlevel/sign-in/${started.body.flowId}`, admin)).toEqual({ status: 200, body: { phase: "waiting" } });- expect(await request(routes, "GET", "/api/highlevel/sign-in/00000000-0000-0000-0000-000000000000", admin)).toEqual({ status: 404, body: { error: "This sign-in is no longer available. Start again." } });- expect(await request(routes, "DELETE", `/api/highlevel/sign-in/${started.body.flowId}`, admin)).toEqual({ status: 200, body: { ok: true } });- expect(await request(routes, "GET", `/api/highlevel/sign-in/${started.body.flowId}`, admin)).toEqual({ status: 200, body: { phase: "failed", message: "Cancelled." } });- expect(await request(routes, "POST", "/api/highlevel/token", admin, { token: "", locationId: FAKE_LOCATION_ID })).toEqual({ status: 400, body: { error: "Paste a Private Integration token. It starts with pit-." } });- expect(await request(routes, "POST", "/api/highlevel/token", admin, { token: "pit-abcdefgh12345678" })).toEqual({ status: 400, body: { error: "Enter the location id (Settings → Business Profile in HighLevel)." } });- // Each refusal reaches the card as its own sentence, with HighLevel's reason and never the token.- expect(await request(routes, "POST", "/api/highlevel/token", admin, { token: "pit-not-accepted-1", locationId: FAKE_LOCATION_ID })).toEqual({ status: 401, body: { error: "HighLevel did not accept this token (401). Check that it was copied whole and has not been rotated or deleted, and that its Private Integration has the View Locations permission. HighLevel said: Invalid JWT" } });- hl.tokens.add("pit-route-token-123");- expect(await request(routes, "POST", "/api/highlevel/token", admin, { token: "pit-route-token-123", locationId: "loc_other_9" })).toEqual({ status: 403, body: {- error: "This token does not belong to that location (403): it was created in another sub-account or at the agency level. Create the Private Integration inside the sub-account whose location ID you entered. HighLevel said: The token does not have access to this location.",- } });- hl.pathOverrides.set(`GET /locations/${FAKE_LOCATION_ID}`, { status: 401, body: { statusCode: 401, message: "The token is not authorized for this scope.", error: "Unauthorized" } });- const missing = await request(routes, "POST", "/api/highlevel/token", admin, { token: "pit-route-token-123", locationId: FAKE_LOCATION_ID });- expect(missing).toMatchObject({ status: 401, body: { error: expect.stringMatching(/^This token is missing the View Locations permission \(401\).+HighLevel said: The token is not authorized for this scope\.$/u) } });- expect(JSON.stringify(missing.body)).not.toContain("pit-route");- hl.pathOverrides.clear();- const connected = await request(routes, "POST", "/api/highlevel/token", admin, { token: " pit-route-token-123 ", locationId: FAKE_LOCATION_ID });- expect(connected).toMatchObject({ status: 200, body: { state: "connected", kind: "token", location: { id: FAKE_LOCATION_ID, name: "Example Profiles" } } });- expect(JSON.stringify(connected.body)).not.toContain("pit-route");- expect(await request(routes, "DELETE", "/api/highlevel", admin)).toEqual({ status: 200, body: { state: "signed-out" } });- relay.unavailable = true;- expect(await request(routes, "POST", "/api/highlevel/sign-in", admin)).toEqual({ status: 502, body: { error: "HighLevel sign-in is not available on the OpenMausBot relay right now.", code: "highlevel_unavailable" } });- relay.unavailable = false;- });-});diff --git a/server/highlevel/sign-in.ts b/server/highlevel/sign-in.tsdeleted file mode 100644index dbb286a190..0000000000--- a/server/highlevel/sign-in.ts+++ /dev/null@@ -1,133 +0,0 @@-// A sign-in: the relay mints a state and a HighLevel link; the person's browser does the rest; this server polls the-// relay's claim every 2 s for up to 10 minutes and stores the tokens once. One live flow at a time, in memory only.-import { randomUUID } from "node:crypto";--import type { HighLevelSignInPhase } from "../../shared/highlevel.ts";-import { HighLevelRelayError, type HighLevelRelay, type RelayTokens } from "./relay.ts";-import type { HighLevelStore } from "./store.ts";--export const SIGN_IN_POLL_MS = 2_000;-export const SIGN_IN_MAX_MS = 10 * 60_000;--export interface HighLevelSignInFlow {- flowId: string;- authorizationUrl: string;- expiresAt: number;- phase: HighLevelSignInPhase;- message?: string;-}--export interface HighLevelSignInOptions {- relay: HighLevelRelay;- store: HighLevelStore;- /** The location's name for the card; a failure here never fails the connection. */- lookupLocationName(accessToken: string, locationId: string): Promise<string | undefined>;- pollMs?: number;- maxMs?: number;- now?: () => number;- onChange?(): void;-}--export class HighLevelSignIn {- private readonly options: HighLevelSignInOptions;- private readonly now: () => number;- private flow: (HighLevelSignInFlow & { state: string; timer?: NodeJS.Timeout; cancelled?: boolean }) | null = null;- /** Finished flows stay readable for a while so the app's last poll gets its answer. */- private readonly finished = new Map<string, HighLevelSignInFlow>();-- constructor(options: HighLevelSignInOptions) {- this.options = options;- this.now = options.now ?? Date.now;- }-- /** Starts a new flow; a flow already waiting is cancelled first. */- async start(): Promise<{ flowId: string; authorizationUrl: string; expiresAt: number }> {- this.cancelActive("A newer sign-in replaced this one.");- const started = await this.options.relay.start();- const expiresAt = Math.min(started.expiresAt, this.now() + (this.options.maxMs ?? SIGN_IN_MAX_MS));- const flow = { flowId: randomUUID(), state: started.state, authorizationUrl: started.authorizationUrl, expiresAt, phase: "waiting" as const };- this.flow = flow;- this.schedule(this.options.pollMs ?? SIGN_IN_POLL_MS);- this.options.onChange?.();- return { flowId: flow.flowId, authorizationUrl: flow.authorizationUrl, expiresAt: flow.expiresAt };- }-- /** The live flow, for GET /api/highlevel. */- active(): HighLevelSignInFlow | null {- return this.flow ? { flowId: this.flow.flowId, authorizationUrl: this.flow.authorizationUrl, expiresAt: this.flow.expiresAt, phase: this.flow.phase } : null;- }-- status(flowId: string): { phase: HighLevelSignInPhase; message?: string } | null {- if (this.flow?.flowId === flowId) return { phase: this.flow.phase };- const done = this.finished.get(flowId);- return done ? { phase: done.phase, ...(done.message ? { message: done.message } : {}) } : null;- }-- cancel(flowId: string): boolean {- if (this.flow?.flowId !== flowId) return this.finished.delete(flowId);- this.cancelActive("Cancelled.");- return true;- }-- close(): void {- this.cancelActive("OpenMausBot stopped.");- }-- private cancelActive(message: string): void {- const flow = this.flow;- if (!flow) return;- flow.cancelled = true;- if (flow.timer) clearTimeout(flow.timer);- this.flow = null;- this.remember({ ...flow, phase: "failed", message });- this.options.onChange?.();- }-- private remember(flow: HighLevelSignInFlow): void {- this.finished.set(flow.flowId, { flowId: flow.flowId, authorizationUrl: flow.authorizationUrl, expiresAt: flow.expiresAt, phase: flow.phase, ...(flow.message ? { message: flow.message } : {}) });- while (this.finished.size > 8) this.finished.delete(this.finished.keys().next().value!);- }-- private finish(phase: HighLevelSignInPhase, message?: string): void {- const flow = this.flow;- if (!flow) return;- if (flow.timer) clearTimeout(flow.timer);- this.flow = null;- this.remember({ ...flow, phase, message });- this.options.onChange?.();- }-- private schedule(ms: number): void {- const flow = this.flow;- if (!flow) return;- flow.timer = setTimeout(() => { void this.poll(); }, ms);- flow.timer.unref?.();- }-- private async poll(): Promise<void> {- const flow = this.flow;- if (!flow || flow.cancelled) return;- const live = () => this.flow === flow && !flow.cancelled;- if (this.now() >= flow.expiresAt) return this.finish("expired", "The sign-in took longer than 10 minutes. Start again.");- let claimed: RelayTokens | "pending" | "claimed";- try {- claimed = await this.options.relay.claim(flow.state);- } catch (error) {- if (!live()) return;- // A relay hiccup is not a failed sign-in; keep polling until the flow expires.- if (error instanceof HighLevelRelayError && error.status < 500 && error.status !== 503) return this.finish("failed", error.message);- return this.schedule(this.options.pollMs ?? SIGN_IN_POLL_MS);- }- if (!live()) return;- if (claimed === "pending") return this.schedule(this.options.pollMs ?? SIGN_IN_POLL_MS);- if (claimed === "claimed") return this.finish("failed", "This sign-in was already used. Start again.");- const locationName = await this.options.lookupLocationName(claimed.accessToken, claimed.locationId).catch(() => undefined);- if (!live()) return;- this.options.store.put({- kind: "oauth", accessToken: claimed.accessToken, refreshToken: claimed.refreshToken, expiresAt: this.now() + claimed.expiresIn * 1000,- locationId: claimed.locationId, ...(claimed.companyId ? { companyId: claimed.companyId } : {}), ...(claimed.userId ? { userId: claimed.userId } : {}),- ...(locationName ? { locationName } : {}), scopes: claimed.scope,- });- this.finish("connected");- }-}diff --git a/server/highlevel/store.ts b/server/highlevel/store.tsdeleted file mode 100644index f5574a177b..0000000000--- a/server/highlevel/store.ts+++ /dev/null@@ -1,153 +0,0 @@-// The HighLevel connection's tokens, sealed under a key of their own (a 0600 file beside the store) so they rest-// encrypted on desktop and on a Cloud home alike, with no keychain in the path. No route ever returns a token.-import { randomBytes } from "node:crypto";-import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";-import { join } from "node:path";-import { z } from "zod";--import { writeFileAtomic } from "../atomic.ts";-import { decryptBrowserState, encryptBrowserState } from "../browser-sites.ts";--export const HIGHLEVEL_FILE = "highlevel.json.enc";-export const HIGHLEVEL_KEY_FILE = "highlevel-key";--const connectionSchema = z.object({- kind: z.enum(["oauth", "token"]),- accessToken: z.string().min(1),- refreshToken: z.string().min(1).optional(),- /** Epoch ms; absent for a Private Integration token, which never expires on its own. */- expiresAt: z.number().optional(),- locationId: z.string().min(1),- companyId: z.string().optional(),- userId: z.string().optional(),- locationName: z.string().optional(),- scopes: z.string().default(""),- connectedAt: z.number(),- state: z.enum(["signed-in", "needs-sign-in"]),- /** Why the connection needs a new sign-in, in one plain sentence. */- problem: z.string().optional(),-});--const fileSchema = z.object({ version: z.literal(1), connection: connectionSchema.optional() });--/** The stored connection with its secrets. Server-only. */-export type HighLevelConnection = z.infer<typeof connectionSchema>;-type StoreFile = z.infer<typeof fileSchema>;--/** A connection as this store keeps it, from anywhere else (one moved from the person's own computer); null if not. */-export function parseHighLevelConnection(value: unknown): HighLevelConnection | null {- const parsed = connectionSchema.safeParse(value);- return parsed.success ? parsed.data : null;-}--export interface HighLevelTokenRotation {- accessToken: string;- refreshToken?: string;- expiresAt?: number;- scopes?: string;-}--const EMPTY: StoreFile = { version: 1 };--export const sameTokens = (a: HighLevelConnection, b: HighLevelConnection): boolean =>- a.accessToken === b.accessToken && a.refreshToken === b.refreshToken;--export class HighLevelStore {- private readonly file: string;- private readonly keyFile: string;- private readonly now: () => number;- private cache: StoreFile | null = null;- private unreadableWarned = false;-- constructor(options: { dataDir: string; now?: () => number }) {- this.file = join(options.dataDir, HIGHLEVEL_FILE);- this.keyFile = join(options.dataDir, HIGHLEVEL_KEY_FILE);- this.now = options.now ?? Date.now;- }-- private key(create: boolean): string | null {- try {- const existing = readFileSync(this.keyFile, "utf8").trim();- if (/^[0-9a-f]{64}$/u.test(existing)) return existing;- } catch {- }- if (!create) return null;- const key = randomBytes(32).toString("hex");- mkdirSync(join(this.keyFile, ".."), { recursive: true });- writeFileAtomic(this.keyFile, `${key}\n`, { mode: 0o600 });- return key;- }-- private read(): StoreFile {- if (this.cache) return this.cache;- let data: StoreFile = EMPTY;- if (existsSync(this.file)) {- const key = this.key(false);- try {- if (!key) throw new Error("missing key");- data = fileSchema.parse(JSON.parse(decryptBrowserState(readFileSync(this.file), key)));- } catch {- // Never log an unreadable file's contents.- if (!this.unreadableWarned) console.warn("HighLevel: the saved connection could not be opened; connect again");- this.unreadableWarned = true;- data = EMPTY;- }- }- this.cache = data;- return data;- }-- private write(data: StoreFile): void {- const parsed = fileSchema.parse(data);- const key = this.key(true)!;- mkdirSync(join(this.file, ".."), { recursive: true });- writeFileAtomic(this.file, encryptBrowserState(JSON.stringify(parsed), key), { mode: 0o600 });- this.cache = parsed;- }-- get(): HighLevelConnection | null {- return this.read().connection ?? null;- }-- put(connection: Omit<HighLevelConnection, "connectedAt" | "state"> & { connectedAt?: number; state?: HighLevelConnection["state"] }): HighLevelConnection {- const stored: HighLevelConnection = connectionSchema.parse({ connectedAt: this.now(), state: "signed-in", ...connection });- this.write({ version: 1, connection: stored });- return stored;- }-- /** A refresh rotates both tokens: the new pair replaces the old one at once, so a retry never reuses a spent refresh token.- * It lands only on the token version it was started from; null when a newer sign-in, rotation or disconnect came first. */- rotate(tokens: HighLevelTokenRotation, from: HighLevelConnection): HighLevelConnection | null {- const current = this.get();- if (!current || !sameTokens(current, from)) return null;- const { problem: _problem, ...rest } = current;- const next: HighLevelConnection = {- ...rest,- accessToken: tokens.accessToken,- ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),- ...(tokens.expiresAt === undefined ? {} : { expiresAt: tokens.expiresAt }),- ...(tokens.scopes === undefined ? {} : { scopes: tokens.scopes }),- state: "signed-in",- };- this.write({ version: 1, connection: next });- return next;- }-- /** Only for the token version HighLevel rejected: a newer sign-in or rotation stays signed in. */- markNeedsSignIn(problem: string, rejected: HighLevelConnection): void {- const current = this.get();- if (!current || !sameTokens(current, rejected)) return;- this.write({ version: 1, connection: { ...current, state: "needs-sign-in", problem } });- }-- clear(): void {- this.cache = EMPTY;- rmSync(this.file, { force: true });- }-- /** The tokens, for secret redaction. */- secretValues(): string[] {- const current = this.get();- return current ? [current.accessToken, ...(current.refreshToken ? [current.refreshToken] : [])] : [];- }-}diff --git a/server/highlevel/tools.ts b/server/highlevel/tools.tsdeleted file mode 100644index 8560df3d64..0000000000--- a/server/highlevel/tools.ts+++ /dev/null@@ -1,180 +0,0 @@-// The twenty HighLevel tools: small flat inputs validated against their advertised schema, outputs trimmed by the-// client. A write returns, beside the result, the record id and the field names it changed for the activity log.-import type { ValidateFunction } from "ajv";--import { HIGHLEVEL_TOOL_NAMES, type HighLevelToolName } from "../../shared/highlevel.ts";-import { isReadOnlyAction } from "../../shared/connector-scopes.ts";-import { compileToolSchema, schemaProblems } from "../mcp-schema-validator.ts";-import { HighLevelError, PAGE_MAX, PAGE_NUMBER_MAX, type ContactFields, type HighLevelClient } from "./client.ts";--const ID = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z0-9_.-]+$" };-const TEXT = (maxLength: number, description?: string) => ({ type: "string", maxLength, ...(description ? { description } : {}) });-const TAGS = { type: "array", minItems: 1, maxItems: 50, items: { type: "string", minLength: 1, maxLength: 100 } };-const PAGE = { type: "integer", minimum: 1, maximum: PAGE_NUMBER_MAX, description: "Page number, from 1." };-const LIMIT = { type: "integer", minimum: 1, maximum: PAGE_MAX, description: `Results per page, at most ${PAGE_MAX}. Default 20.` };-const DATE = TEXT(64, "ISO 8601 date-time, e.g. 2026-10-20T15:00:00Z.");--const CONTACT_FIELDS = {- firstName: TEXT(200), lastName: TEXT(200), name: TEXT(400, "Full name; use firstName and lastName when you have them."),- email: TEXT(320), phone: TEXT(50, "With country code, e.g. +15551234567."), companyName: TEXT(200),- tags: { type: "array", maxItems: 50, items: { type: "string", minLength: 1, maxLength: 100 } },- source: TEXT(200, "Where the contact came from."), address1: TEXT(400), city: TEXT(200), state: TEXT(200), postalCode: TEXT(40), country: TEXT(8, "Two-letter country code."),- website: TEXT(400), timezone: TEXT(100), assignedTo: TEXT(128, "User id of the owner."), dateOfBirth: TEXT(32, "YYYY-MM-DD."),- customFields: { type: "object", maxProperties: 50, description: "Custom field values by field name (HIGHLEVEL_GET_LOCATION lists them).", additionalProperties: { type: ["string", "number", "boolean", "array"], items: { type: "string", maxLength: 1000 }, maxLength: 4000 } },-};--const tool = (name: HighLevelToolName, description: string, properties: Record<string, unknown>, required: string[] = []) =>- ({ name, description, inputSchema: { type: "object", properties, required, additionalProperties: false } });--export const HIGHLEVEL_TOOLS = [- tool("HIGHLEVEL_SEARCH_CONTACTS", "Search the CRM's contacts by free text (name, email, phone, company) with optional exact tag, email or phone filters. Returns trimmed contacts with ids.",- { query: TEXT(500, "Free text to match."), tag: TEXT(100, "Only contacts with this tag."), email: TEXT(320, "Exact email."), phone: TEXT(50, "Exact phone with country code."), page: PAGE, limit: LIMIT }),- tool("HIGHLEVEL_GET_CONTACT", "Read one contact by id, with its tags and custom fields by name.", { contactId: ID }, ["contactId"]),- tool("HIGHLEVEL_CREATE_CONTACT", "Create a contact. Search first so you do not create a duplicate. Give at least an email, a phone or a name.", CONTACT_FIELDS),- tool("HIGHLEVEL_UPDATE_CONTACT", "Change fields of an existing contact; only the fields given change. Tags given here replace the contact's tags: use HIGHLEVEL_ADD_TAGS to add.",- { contactId: ID, ...CONTACT_FIELDS }, ["contactId"]),- tool("HIGHLEVEL_ADD_TAGS", "Add tags to a contact.", { contactId: ID, tags: TAGS }, ["contactId", "tags"]),- tool("HIGHLEVEL_REMOVE_TAGS", "Remove tags from a contact.", { contactId: ID, tags: TAGS }, ["contactId", "tags"]),- tool("HIGHLEVEL_LIST_NOTES", "List the notes on a contact.", { contactId: ID }, ["contactId"]),- tool("HIGHLEVEL_ADD_NOTE", "Add a note to a contact.", { contactId: ID, body: { type: "string", minLength: 1, maxLength: 10_000 } }, ["contactId", "body"]),- tool("HIGHLEVEL_LIST_TASKS", "List the tasks on a contact.", { contactId: ID }, ["contactId"]),- tool("HIGHLEVEL_ADD_TASK", "Add a task to a contact with a title and due date; optionally a description and an assignee (user id).",- { contactId: ID, title: { type: "string", minLength: 1, maxLength: 500 }, dueDate: DATE, body: TEXT(5000, "Description."), assignedTo: TEXT(128, "User id.") }, ["contactId", "title", "dueDate"]),- tool("HIGHLEVEL_LIST_PIPELINES", "List the location's pipelines with their stages (ids and names).", {}),- tool("HIGHLEVEL_SEARCH_OPPORTUNITIES", "Search opportunities (deals) by pipeline, stage, contact, status or free text.",- { query: TEXT(500), pipelineId: ID, stageId: ID, contactId: ID, status: { type: "string", enum: ["open", "won", "lost", "abandoned", "all"] }, page: PAGE, limit: LIMIT }),- tool("HIGHLEVEL_GET_OPPORTUNITY", "Read one opportunity by id.", { opportunityId: ID }, ["opportunityId"]),- tool("HIGHLEVEL_CREATE_OPPORTUNITY", "Create an opportunity for a contact in a pipeline (HIGHLEVEL_LIST_PIPELINES gives pipeline and stage ids).",- { pipelineId: ID, stageId: ID, contactId: ID, name: { type: "string", minLength: 1, maxLength: 500 }, value: { type: "number", minimum: 0, description: "Monetary value." }, status: { type: "string", enum: ["open", "won", "lost", "abandoned"] } },- ["pipelineId", "contactId", "name"]),- tool("HIGHLEVEL_UPDATE_OPPORTUNITY", "Move an opportunity to a stage, change its status, value or name. Only the fields given change.",- { opportunityId: ID, stageId: ID, status: { type: "string", enum: ["open", "won", "lost", "abandoned"] }, value: { type: "number", minimum: 0 }, name: TEXT(500) }, ["opportunityId"]),- tool("HIGHLEVEL_SEARCH_CONVERSATIONS", "Find conversations by contact or free text; returns summaries with the last message. Read only.",- { contactId: ID, query: TEXT(500), limit: LIMIT }),- tool("HIGHLEVEL_READ_CONVERSATION", "Read the messages of one conversation, newest first. Read only: nothing can be sent.",- { conversationId: ID, limit: LIMIT, lastMessageId: { ...ID, description: "Page on from this message id." } }, ["conversationId"]),- tool("HIGHLEVEL_LIST_CALENDARS", "List the location's calendars. Read only.", {}),- tool("HIGHLEVEL_LIST_EVENTS", "List calendar events (appointments) in a date range, optionally for one calendar or one user. Read only.",- { startTime: DATE, endTime: DATE, calendarId: ID, userId: ID }, ["startTime", "endTime"]),- tool("HIGHLEVEL_GET_LOCATION", "The connected location: name, timezone, contact details and its custom field definitions.", {}),-] as const;--export type HighLevelTool = (typeof HIGHLEVEL_TOOLS)[number];--export function isHighLevelToolName(name: unknown): name is HighLevelToolName {- return typeof name === "string" && (HIGHLEVEL_TOOL_NAMES as readonly string[]).includes(name);-}--/** SEARCH/GET/LIST/READ read; everything else writes. */-export function isHighLevelWrite(name: string): boolean {- return !isReadOnlyAction(name, "highlevel");-}--let validators: Map<string, ValidateFunction> | undefined;--export function highlevelToolCallProblem(name: unknown, args: unknown): string | null {- validators ??= new Map(HIGHLEVEL_TOOLS.map((entry) => [entry.name, compileToolSchema(entry.inputSchema as Record<string, unknown>, { allErrors: true })]));- const validate = typeof name === "string" ? validators.get(name) : undefined;- if (!validate) return `Unknown HighLevel tool. Use one of ${HIGHLEVEL_TOOL_NAMES.join(", ")}.`;- if (!args || typeof args !== "object" || Array.isArray(args) || !validate(args)) {- return `Tool arguments do not match the advertised input schema: ${schemaProblems(validate.errors).join("; ") || "use its required fields and types"}.`;- }- return null;-}--export interface HighLevelToolResult {- content: Array<{ type: "text"; text: string }>;- structuredContent?: Record<string, unknown>;- isError?: boolean;-}--/** What the activity row records for a write: the record's id and the fields changed, never the values. */-export interface HighLevelWriteRecord {- tool: HighLevelToolName;- kind: "contact" | "note" | "task" | "opportunity" | "tags";- recordId: string;- fields: string[];-}--export function highlevelErrorResult(message: string, extra: Record<string, unknown> = {}): HighLevelToolResult {- return { content: [{ type: "text", text: message }], structuredContent: { error: message, ...extra }, isError: true };-}--const ok = (value: unknown): HighLevelToolResult => {- const structured = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : { value };- return { content: [{ type: "text", text: JSON.stringify(structured) }], structuredContent: structured };-};--const changed = (fields: object, skip: string[] = []) =>- Object.entries(fields).filter(([key, value]) => value !== undefined && !skip.includes(key)).map(([key]) => key).sort();--/** Runs one validated call; the write record is set only when a write succeeded. */-export async function runHighLevelTool(- client: HighLevelClient,- name: HighLevelToolName,- args: Record<string, unknown>,-): Promise<{ result: HighLevelToolResult; write?: HighLevelWriteRecord }> {- const a = args as Record<string, any>;- try {- switch (name) {- case "HIGHLEVEL_SEARCH_CONTACTS": return { result: ok(await client.searchContacts(a)) };- case "HIGHLEVEL_GET_CONTACT": return { result: ok(await client.getContact(a.contactId)) };- case "HIGHLEVEL_CREATE_CONTACT": {- const fields = a as ContactFields;- if (!fields.email && !fields.phone && !fields.name && !fields.firstName && !fields.lastName) {- return { result: highlevelErrorResult("Give at least an email, a phone or a name to create a contact.") };- }- const contact = await client.createContact(fields);- return { result: ok(contact), write: { tool: name, kind: "contact", recordId: contact.id, fields: changed(fields) } };- }- case "HIGHLEVEL_UPDATE_CONTACT": {- const { contactId, ...fields } = a as ContactFields & { contactId: string };- const names = changed(fields);- if (names.length === 0) return { result: highlevelErrorResult("Give at least one field to change.") };- const contact = await client.updateContact(contactId, fields);- return { result: ok(contact), write: { tool: name, kind: "contact", recordId: contactId, fields: names } };- }- case "HIGHLEVEL_ADD_TAGS": {- const out = await client.addTags(a.contactId, a.tags);- return { result: ok(out), write: { tool: name, kind: "tags", recordId: a.contactId, fields: ["tags"] } };- }- case "HIGHLEVEL_REMOVE_TAGS": {- const out = await client.removeTags(a.contactId, a.tags);- return { result: ok(out), write: { tool: name, kind: "tags", recordId: a.contactId, fields: ["tags"] } };- }- case "HIGHLEVEL_LIST_NOTES": return { result: ok(await client.listNotes(a.contactId)) };- case "HIGHLEVEL_ADD_NOTE": {- const out = await client.addNote(a.contactId, a.body);- return { result: ok(out), write: { tool: name, kind: "note", recordId: out.note.id || a.contactId, fields: ["body"] } };- }- case "HIGHLEVEL_LIST_TASKS": return { result: ok(await client.listTasks(a.contactId)) };- case "HIGHLEVEL_ADD_TASK": {- const { contactId, ...task } = a;- const out = await client.addTask(contactId, task as { title: string; dueDate: string; body?: string; assignedTo?: string });- return { result: ok(out), write: { tool: name, kind: "task", recordId: out.task.id || contactId, fields: changed(task) } };- }- case "HIGHLEVEL_LIST_PIPELINES": return { result: ok(await client.listPipelines()) };- case "HIGHLEVEL_SEARCH_OPPORTUNITIES": return { result: ok(await client.searchOpportunities({ ...a, status: a.status === "all" ? undefined : a.status })) };- case "HIGHLEVEL_GET_OPPORTUNITY": return { result: ok(await client.getOpportunity(a.opportunityId)) };- case "HIGHLEVEL_CREATE_OPPORTUNITY": {- const out = await client.createOpportunity(a as { pipelineId: string; stageId?: string; contactId: string; name: string; value?: number; status?: string });- return { result: ok(out), write: { tool: name, kind: "opportunity", recordId: out.id, fields: changed(a) } };- }- case "HIGHLEVEL_UPDATE_OPPORTUNITY": {- const { opportunityId, ...fields } = a;- const names = changed(fields);- if (names.length === 0) return { result: highlevelErrorResult("Give at least one field to change.") };- const out = await client.updateOpportunity(opportunityId, fields);- return { result: ok(out), write: { tool: name, kind: "opportunity", recordId: opportunityId, fields: names } };- }- case "HIGHLEVEL_SEARCH_CONVERSATIONS": return { result: ok(await client.searchConversations(a)) };- case "HIGHLEVEL_READ_CONVERSATION": return { result: ok(await client.readConversation(a.conversationId, a)) };- case "HIGHLEVEL_LIST_CALENDARS": return { result: ok(await client.listCalendars()) };- case "HIGHLEVEL_LIST_EVENTS": return { result: ok(await client.listEvents(a as { startTime: string; endTime: string; calendarId?: string; userId?: string })) };- case "HIGHLEVEL_GET_LOCATION": return { result: ok(await client.getLocation()) };- }- } catch (error) {- if (error instanceof HighLevelError) return { result: highlevelErrorResult(error.message, { ...(error.status ? { status: error.status } : {}), ...(error.signedOut ? { signedOut: true } : {}) }) };- throw error;- }-}diff --git a/server/host/outside-fence.ts b/server/host/outside-fence.tsindex 735c8a9dec..35e8d48677 100644--- a/server/host/outside-fence.ts+++ b/server/host/outside-fence.ts@@ -62,7 +62,6 @@ const EXACT: ReadonlySet<string> = new Set(["POST /api/internal/connectors/mcp","POST /api/internal/connectors/request","POST /api/internal/data/mcp",- "POST /api/internal/highlevel/mcp","POST /api/internal/email/mcp",]);const ASKED_MCP_PREFIX = "/api/internal/mcp-http/";diff --git a/server/index.test.ts b/server/index.test.tsindex 945d7129ca..21b8f1bb1d 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -1,5 +1,4 @@// The config pins one deliberately unknown driver, so the suite is deterministic with or without agent CLIs installed.-import { HIGHLEVEL_TOOLS } from "./highlevel/tools.js";import { EMAIL_TOOLS } from "./email/tools.ts";import { spawn, type ChildProcess } from "node:child_process";import { createHash, randomUUID } from "node:crypto";@@ -12643,9 +12642,7 @@ describe("harness HTTP API", () => {{ name: "GMAIL_SEND_EMAIL", description: "Send an email" },],slack: [{ name: "SLACK_POST_MESSAGE", description: "a".repeat(240) }],- // HighLevel's tools are listed whenever its relay is configured, so grants can be set before connecting.- highlevel: HIGHLEVEL_TOOLS.map(({ name, description }) => ({ name, description })),- // So are email's, wherever a mailbox can be connected here.+ // Email's tools are listed wherever a mailbox can be connected here, so grants can be set before connecting.email: EMAIL_TOOLS.map(({ name, description }) => ({ name, description })),},});diff --git a/server/index.ts b/server/index.tsindex 09a3e117b8..d750b2fd8f 100644--- a/server/index.ts+++ b/server/index.ts@@ -98,10 +98,7 @@ import { cloudComputerRpc } from "./cloud-computer-tools.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";import { DATA_INTERNAL_MCP_PATH, dataRpc } from "./data/rpc.ts";-import { createHighLevelHost } from "./highlevel/host.ts";-import { HIGHLEVEL_INTERNAL_MCP_PATH } from "./highlevel/rpc.ts";-import { createHighLevelService } from "./highlevel/service.ts";-import { createHighLevelRoutes } from "./routes/highlevel.ts"; import { createEmailRoutes } from "./routes/email.ts"; import { createEmailHost, EMAIL_INTERNAL_MCP_PATH } from "./email/host.ts"; import { createEmailService } from "./email/service.ts"; import { createPostizRoutes } from "./routes/postiz.ts"; import { createPostiz } from "./postiz/service.ts";+import { removeRetiredAppFiles } from "./retired-apps.ts"; import { createEmailRoutes } from "./routes/email.ts"; import { createEmailHost, EMAIL_INTERNAL_MCP_PATH } from "./email/host.ts"; import { createEmailService } from "./email/service.ts"; import { createPostizRoutes } from "./routes/postiz.ts"; import { createPostiz } from "./postiz/service.ts";import { createPhones } from "./host/phones.ts";import { NOT_THE_OWNER } from "./phones/owner.ts";import { PHONE_INTERNAL_MCP_PATH } from "./phones/rpc.ts";@@ -737,7 +734,7 @@ const threadStarters = new ThreadStarters(join(DATA_DIR, "thread-starters.json")const commandAllowlist = new CommandAllowlistStore(join(DATA_DIR, "command-allowlist.json"));// Every saved login value is scrubbed from whatever a bot or a transcript can read.const logins = new LoginStore({ dataDir: DATA_DIR });-const highlevel = createHighLevelService({ dataDir: DATA_DIR }); const emailService = createEmailService({ dataDir: DATA_DIR, publicOnly: Boolean(CLOUD_HOME), refusal: CLOUD_TEAM ? "Email isn't on a Team Cloud yet: every bot there would read the same mailbox." : null }); addHeldSecretScrubber((text) => emailService.scrub(text));+removeRetiredAppFiles(DATA_DIR); const emailService = createEmailService({ dataDir: DATA_DIR, publicOnly: Boolean(CLOUD_HOME), refusal: CLOUD_TEAM ? "Email isn't on a Team Cloud yet: every bot there would read the same mailbox." : null }); addHeldSecretScrubber((text) => emailService.scrub(text));const heldSecrets = new HeldSecrets(logins);addHeldSecretScrubber((text) => heldSecrets.scrub(text));const onePassword = new OnePasswordLogins({@@ -1605,7 +1602,7 @@ type InternalCapability = {threadId: string;generation: string;depth: number;- kind: "agents" | "connectors" | "computer" | "browser" | "hooks" | "phone" | "data" | "highlevel" | "email" | "device" | "lent";+ kind: "agents" | "connectors" | "computer" | "browser" | "hooks" | "phone" | "data" | "email" | "device" | "lent";skillAuthoring: boolean;createdBots: number;createdRooms?: number;@@ -2426,10 +2423,7 @@ function dataIntegration(botId: string, turn: { threadId: string; generation: st},};}-/** Only with a connection and for a bot allowed to use it (connected apps on; scopes and grants name highlevel). */-function highlevelIntegration(bot: BotRecord, turn: { threadId: string; generation: string }) {- return !managedPolicy.appAllowed("highlevel") ? null : highlevelHost.integration(bot, () => mintInternalCapability({ botId: bot.id, ...turn, kind: "highlevel", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), `http://127.0.0.1:${PORT}`);-} const emailIntegration = (bot: BotRecord, turn: { threadId: string; generation: string }) => emailHost.integration(bot, () => mintInternalCapability({ botId: bot.id, ...turn, kind: "email", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), `http://127.0.0.1:${PORT}`);+const emailIntegration = (bot: BotRecord, turn: { threadId: string; generation: string }) => emailHost.integration(bot, () => mintInternalCapability({ botId: bot.id, ...turn, kind: "email", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), `http://127.0.0.1:${PORT}`);let browserEngineInstall: Promise<void> | null = null;let browserEngineInstallError: string | null = null;@@ -2845,9 +2839,8 @@ const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, storconst routineHolds = CLOUD_HOME ? createRoutineHoldsHost({ dataDir: DATA_DIR, store, mcpServers: () => Object.keys(cfg.mcpServers ?? {}).length, log: (line) => console.warn(line),appsConnected: async () => composio.configured(cfg) ? Object.values(await composio.connectedServices(cfg)).some((service) => service.connected) : false }) : null;const skillsHost = createSkillsLibraryHost({ store, cfg, appendSkillRequestCard, engineConfig: (instanceId) => providerConfigs()[instanceId], instanceOf: (instanceId) => { const instance = registry.get(instanceId); return instance ? { instanceId, driverKind: instance.driverKind } : undefined; } });-const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, highlevel, heldKeys, dataDir: DATA_DIR, email: { accounts: () => emailService.store.list(), adopt: (accounts) => emailService.adopt(accounts) }, stayedNotices: { bots: () => store.bots, language: (threadId) => threadLanguage(threadId), say: (threadId, text, kind) => { store.appendMessage(threadId, kind === "line" ? { role: "bot", kind: "text", text } : { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok: true } }); }, notify: (text, bot, threadId) => notify(buildNoticeNotification(bot, threadId, text)), lent: (runsOn) => { const at = sharedComputers.runsOn(CLOUD_HOME_LENDER, runsOn); return Boolean(at.online ?? at.known?.lent); } }, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) }); const lentMcp = createLentMcp({ cfg: () => cfg, computers: sharedComputers, policy: (servers) => managedPolicy.filterMcp(servers), bot: (id) => store.bot(id), principal: (turn) => (CLOUD_TEAM || !lendingEnabled() ? null : sharedComputerPrincipal(turn)), notice: (turn) => (CLOUD_HOME ? cloudLendingRefusalNotice(turn) : null), refusal: (turn) => (CLOUD_HOME ? cloudLendingRefusalForBot(turn) : null), mint: (turn) => mintInternalCapability({ ...turn, kind: "lent", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), active: (turn) => activeInternalGenerationByThread.get(turn.threadId) === turn.generation, origin: `http://127.0.0.1:${PORT}`, personal: CLOUD_PERSONAL, place: CLOUD_HOME ? "My Cloud" : "this server" }); // Security: a team Cloud lends nothing, so nobody's own computer serves its bots.-const highlevelHost = createHighLevelHost({ service: highlevel, dataDir: DATA_DIR, bot: (id) => store.bot(id),- inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); } }); const emailHost = createEmailHost({ service: emailService, dataDir: DATA_DIR, bot: (id) => store.bot(id), inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); }, appAllowed: () => managedPolicy.appAllowed("email"), onChange: (listener) => store.onChange(listener as never), markOutside: (threadId) => outsideLineage.mark(threadId) });+const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, heldKeys, dataDir: DATA_DIR, email: { accounts: () => emailService.store.list(), adopt: (accounts) => emailService.adopt(accounts) }, stayedNotices: { bots: () => store.bots, language: (threadId) => threadLanguage(threadId), say: (threadId, text, kind) => { store.appendMessage(threadId, kind === "line" ? { role: "bot", kind: "text", text } : { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok: true } }); }, notify: (text, bot, threadId) => notify(buildNoticeNotification(bot, threadId, text)), lent: (runsOn) => { const at = sharedComputers.runsOn(CLOUD_HOME_LENDER, runsOn); return Boolean(at.online ?? at.known?.lent); } }, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) }); const lentMcp = createLentMcp({ cfg: () => cfg, computers: sharedComputers, policy: (servers) => managedPolicy.filterMcp(servers), bot: (id) => store.bot(id), principal: (turn) => (CLOUD_TEAM || !lendingEnabled() ? null : sharedComputerPrincipal(turn)), notice: (turn) => (CLOUD_HOME ? cloudLendingRefusalNotice(turn) : null), refusal: (turn) => (CLOUD_HOME ? cloudLendingRefusalForBot(turn) : null), mint: (turn) => mintInternalCapability({ ...turn, kind: "lent", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), active: (turn) => activeInternalGenerationByThread.get(turn.threadId) === turn.generation, origin: `http://127.0.0.1:${PORT}`, personal: CLOUD_PERSONAL, place: CLOUD_HOME ? "My Cloud" : "this server" }); // Security: a team Cloud lends nothing, so nobody's own computer serves its bots.+const emailHost = createEmailHost({ service: emailService, dataDir: DATA_DIR, bot: (id) => store.bot(id), inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); }, appAllowed: () => managedPolicy.appAllowed("email"), onChange: (listener) => store.onChange(listener as never), markOutside: (threadId) => outsideLineage.mark(threadId) });const phones = createPhones({dataDir: DATA_DIR, shared: Boolean(HOSTED_WORKSPACE || CLOUD_TEAM), cloudHome: Boolean(CLOUD_HOME), cloudOwnerKey: CLOUD_OWNER_KEY,loopbackTrust: LOOPBACK.trust, sharedMembership, store, sessions, routines: () => routines, ownerOrAdmin, cloudOwnerSession,@@ -2859,7 +2852,7 @@ const phones = createPhones({const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const botLimit = createBotLimit({ starter: () => cloudPlanTier.starter(), bots: () => store.bots }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),- connectors: () => emailHost.health(highlevelHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null)),+ connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });const teamComputers = new TeamComputers(join(DATA_DIR, "team-computers.json"), ENVIRONMENT_ID);let followupsReady = false;@@ -3000,7 +2993,7 @@ function previewSystemPrompt(bot: BotRecord) {}, { note: previewPlan.note, cloudHome: Boolean(CLOUD_HOME), ownComputer: CLOUD_HOME && agentsMounted && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER) : undefined }) },{ id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(agentsMounted && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, bot.threadId) : "" },{ id: "composio", label: "Connected apps", text: caps?.composioMcp && bot.composio !== false && composio.configured(cfg) ? composioSystemPrompt(bot.connectorTools) + describeConnectorScopes(bot.connectorScopes) : "" },- { id: "highlevel", label: "HighLevel", text: caps?.highlevelMcp === true && highlevelHost.mounts(bot) ? highlevelHost.prompt(bot) : "" }, { id: "email", label: "Email", text: caps?.highlevelMcp === true ? emailHost.prompt(bot) : "" },+ { id: "email", label: "Email", text: caps?.emailMcp === true ? emailHost.prompt(bot) : "" },...phones.previewParts(bot, caps?.deviceMcp === true),{ id: "mcp", label: "MCP servers", text: caps?.customMcp ? customMcpPrompt(Object.keys(engineMcpServers(bot)), mcpServersHost.off(bot)) : "" }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(bot) },{ id: "browser", label: "Browser", text: previewPlan.browser ? browserPromptFor(bot, agentsMounted) : "" },@@ -8333,7 +8326,7 @@ async function beginTurn(const data = dataIntegration(bot.id, { threadId, generation: dispatchClaimId });if (data) integrations.data = data;}- if (liveBot && instance.adapter.capabilities.highlevelMcp === true) { const crm = highlevelIntegration(liveBot, { threadId, generation: dispatchClaimId }); if (crm) integrations.highlevel = crm; const mail = emailIntegration(liveBot, { threadId, generation: dispatchClaimId }); if (mail) integrations.email = mail; }+ if (liveBot && instance.adapter.capabilities.emailMcp === true) { const mail = emailIntegration(liveBot, { threadId, generation: dispatchClaimId }); if (mail) integrations.email = mail; }const phone = liveBot && instance.adapter.capabilities.deviceMcp === true ? phones.integration(liveBot, { threadId, generation: dispatchClaimId }) : null;if (phone) integrations.device = phone;const mountedComputer = surfaceOfComputerKind(computerKind);@@ -8402,7 +8395,7 @@ async function beginTurn({ id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot, lentMcp.lines(liveBot ?? bot, { botId: bot.id, threadId, generation: dispatchClaimId })) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },{ id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },- { id: "highlevel", label: "HighLevel", text: integrations.highlevel ? highlevelHost.prompt(liveBot ?? bot) : "" }, { id: "email", label: "Email", text: instance.adapter.capabilities.highlevelMcp === true ? emailHost.prompt(liveBot ?? bot) : "" },+ { id: "email", label: "Email", text: instance.adapter.capabilities.emailMcp === true ? emailHost.prompt(liveBot ?? bot) : "" },...phones.promptParts(liveBot ?? bot, {mounted: Boolean(integrations.device), offered: instance.adapter.capabilities.deviceMcp === true, turn: { botId: bot.id, threadId, generation: dispatchClaimId },place: phones.place(threadId, !(commsDepth > 0 || opts?.automationSource !== undefined || opts?.unattended || opts?.peerAsk || opts?.coordination)),@@ -10009,7 +10002,7 @@ async function runClaimedGroupMemberTurn(const data = dataIntegration(readyBot.id, { threadId, generation: internalGeneration });if (data) integrations.data = data;}- if (instance.adapter.capabilities.highlevelMcp === true) { const crm = highlevelIntegration(readyBot, { threadId, generation: internalGeneration }); if (crm) integrations.highlevel = crm; const mail = emailIntegration(readyBot, { threadId, generation: internalGeneration }); if (mail) integrations.email = mail; }+ if (instance.adapter.capabilities.emailMcp === true) { const mail = emailIntegration(readyBot, { threadId, generation: internalGeneration }); if (mail) integrations.email = mail; }const phone = instance.adapter.capabilities.deviceMcp === true ? phones.integration(readyBot, { threadId, generation: internalGeneration }) : null;if (phone) integrations.device = phone;if (roomPlan.browser && !(roomPlan.computer === undefined && roomTeamComputer)) {@@ -10218,7 +10211,7 @@ async function runClaimedGroupMemberTurn({ id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) : "" },{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },{ id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },- { id: "highlevel", label: "HighLevel", text: integrations.highlevel ? highlevelHost.prompt(readyBot) : "" }, { id: "email", label: "Email", text: instance.adapter.capabilities.highlevelMcp === true ? emailHost.prompt(readyBot) : "" },+ { id: "email", label: "Email", text: instance.adapter.capabilities.emailMcp === true ? emailHost.prompt(readyBot) : "" },...phones.promptParts(readyBot, {mounted: Boolean(integrations.device), offered: instance.adapter.capabilities.deviceMcp === true,turn: { botId: readyBot.id, threadId, generation: internalGeneration }, place: "computer",@@ -12198,7 +12191,7 @@ ROUTES.push(createBotLifecycleRoutes({activeGroupTurnForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle,}));ROUTES.push(createBotSkillsRoutes({ store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing }));-ROUTES.push(createHighLevelRoutes({ service: highlevel })); ROUTES.push(createEmailRoutes({ service: emailService }));+ROUTES.push(createEmailRoutes({ service: emailService }));ROUTES.push(phones.routes);ROUTES.push(createSkillShareRoutes({ enabled: () => skillsHost.mode() !== "off", botExists: (id) => Boolean(store.bot(id)),cardRefusal: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow"), shareFromReceipt: skillsHost.shareFromReceipt, shareFromBot: skillsHost.shareFromBot }));@@ -12912,7 +12905,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const parsed = z.object({botId: z.string().regex(/^[\w-]{1,128}$/),threadId: z.string().regex(/^[\w-]{1,128}$/),- kind: z.enum(["agents", "connectors", "computer", "data", "highlevel", "email", "device"]).default("agents"),+ kind: z.enum(["agents", "connectors", "computer", "data", "email", "device"]).default("agents"),depth: z.number().int().min(0).max(MAX_COMMS_DEPTH).default(0),skillAuthoring: z.boolean().default(false),deliversSavedFiles: z.boolean().default(false),@@ -12966,8 +12959,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {? "browser": path === DATA_INTERNAL_MCP_PATH? "data"- : path === HIGHLEVEL_INTERNAL_MCP_PATH- ? "highlevel" : path === EMAIL_INTERNAL_MCP_PATH ? "email"+ : path === EMAIL_INTERNAL_MCP_PATH ? "email": path === PHONE_INTERNAL_MCP_PATH? "device" : isLentMcpPath(path) ? "lent": path === "/api/internal/phone/claim"@@ -13210,10 +13202,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {},}) });}- // The CRM tokens stay here; the agent process holds only the turn's capability, and every call gets the live bot's verdict.- if (method === "POST" && path === HIGHLEVEL_INTERNAL_MCP_PATH) {- return json(res, 200, { result: await highlevelHost.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability) });- } if (method === "POST" && path === EMAIL_INTERNAL_MCP_PATH) { return json(res, 200, { result: await emailHost.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability) }); }+ // The mail passwords stay here; the agent process holds only the turn's capability, and every call gets the live bot's verdict.+ if (method === "POST" && path === EMAIL_INTERNAL_MCP_PATH) { return json(res, 200, { result: await emailHost.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability) }); }if (method === "POST" && path === PHONE_INTERNAL_MCP_PATH) {return json(res, 200, { result: await phones.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability) });}@@ -15135,12 +15125,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (method === "GET" && path === "/api/connectors/tools") {const availability = composio.connectorAvailability(cfg);- const highlevelTools = { ...highlevelHost.toolListing(), ...emailHost.toolListing(), ...phones.toolListing() };+ const nativeTools = { ...emailHost.toolListing(), ...phones.toolListing() };if (availability !== "configured") {- return json(res, 200, { configured: Object.keys(highlevelTools).length > 0, services: highlevelTools });+ return json(res, 200, { configured: Object.keys(nativeTools).length > 0, services: nativeTools });}try {- return json(res, 200, { configured: true, services: { ...await composio.listConnectorTools(cfg), ...highlevelTools } });+ return json(res, 200, { configured: true, services: { ...await composio.listConnectorTools(cfg), ...nativeTools } });} catch (e) {return json(res, 502, { configured: true, services: {}, error: e instanceof Error ? e.message : String(e) });}diff --git a/server/login-handoff.ts b/server/login-handoff.tsindex c731db8767..fa50d93a02 100644--- a/server/login-handoff.ts+++ b/server/login-handoff.ts@@ -45,7 +45,7 @@ export type LoginHandoffResult = { type: typeof LOGIN_HANDOFF_RESULT; requestId:const REQUEST_ID = /^[\w-]{8,64}$/u;const LOGIN_ID = /^[\w-]{1,128}$/u;-const CONNECTION_ID = /^(?:mcp:[a-z][a-z0-9_-]{0,31}|key:\w{1,40}|composio|highlevel|email)$/u;+const CONNECTION_ID = /^(?:mcp:[a-z][a-z0-9_-]{0,31}|key:\w{1,40}|composio|email)$/u;const INSTALLATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;const DIGEST = /^[0-9a-f]{64}$/u;diff --git a/server/own-home.e2e.test.ts b/server/own-home.e2e.test.tsindex 52f2e7978c..691f2e53c6 100644--- a/server/own-home.e2e.test.ts+++ b/server/own-home.e2e.test.ts@@ -54,7 +54,7 @@ it("only a server that is the person's alone says it is theirs, takes a move andexpect(fx.main.chosen()).toBeNull();expect((await family.as("POST", "/api/cloud-send/memory", { v: 1, about: "", teams: [] })).status).toBe(403);expect((await family.as("POST", "/api/cloud-send/arrived", { v: 1, computer: "Work laptop", webhooks: [] })).status).toBe(404);- expect((await family.as("PUT", "/api/cloud-connections/highlevel", {})).status).toBe(404);+ expect((await family.as("PUT", "/api/cloud-connections/email", { accounts: [] })).status).toBe(404);// Garage server takes them from this sign-in: a body it can't read is answered as such, never refused.expect((await garage.as("POST", "/api/cloud-send/arrived", { v: 1 })).status).toBe(400);}, hostTimeout(60_000));diff --git a/server/retired-apps.test.ts b/server/retired-apps.test.tsnew file mode 100644index 0000000000..fe9055729f--- /dev/null+++ b/server/retired-apps.test.ts@@ -0,0 +1,33 @@+import { existsSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { dropRetiredApps, removeRetiredAppFiles } from "./retired-apps.ts";+import { removeTempDir } from "./testing/cleanup.ts";++const dirs: string[] = [];+afterEach(async () => { for (const dir of dirs.splice(0)) await removeTempDir(dir); });++describe("retired connected apps", () => {+ it("leave a bot's scopes and grants, which keep every other app as it was", () => {+ const bot = { connectorTools: { gmail: { tools: ["GMAIL_FETCH_EMAILS"] }, highlevel: { tools: "*" as const } }, connectorScopes: { apps: { gmail: "read" as const, highlevel: "write" as const } } };+ expect(dropRetiredApps(bot)).toBe(true);+ expect(bot).toEqual({ connectorTools: { gmail: { tools: ["GMAIL_FETCH_EMAILS"] } }, connectorScopes: { apps: { gmail: "read" } } });+ expect(dropRetiredApps(bot), "nothing left to drop").toBe(false);+ const unscoped = {};+ expect(dropRetiredApps(unscoped)).toBe(false);+ expect(unscoped).toEqual({});+ });++ it("leave the data folder with their sealed tokens and key, and nothing else", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-retired-apps-")); dirs.push(dir);+ const retired = ["highlevel.json.enc", "highlevel-key", "highlevel.json.enc.4242.05a7b3e0-1234-4abc-8def-0123456789ab.tmp"];+ const kept = ["logins.json.enc", "logins-key", "highlevel.md"];+ for (const name of [...retired, ...kept]) writeFileSync(join(dir, name), "x");+ expect(removeRetiredAppFiles(dir).sort()).toEqual([...retired].sort());+ for (const name of retired) expect(existsSync(join(dir, name)), name).toBe(false);+ for (const name of kept) expect(existsSync(join(dir, name)), name).toBe(true);+ expect(removeRetiredAppFiles(join(dir, "missing"))).toEqual([]);+ });+});diff --git a/server/retired-apps.ts b/server/retired-apps.tsnew file mode 100644index 0000000000..ccaafa8856--- /dev/null+++ b/server/retired-apps.ts@@ -0,0 +1,35 @@+// Retired connected apps. A bot saved by an older version may name one in connectorScopes.apps or connectorTools, where+// it would read as a Composio app the bot is limited to or must be told to connect, and the data folder may hold its+// sealed tokens: both go when the server starts.+import { readdirSync, rmSync } from "node:fs";+import { join } from "node:path";++import type { ConnectorScopes } from "../shared/connector-scopes.ts";+import type { ConnectorToolGrant } from "../shared/wire.ts";++const RETIRED_APPS: readonly string[] = ["highlevel"];+/** A retired app's saved connection, the key that sealed it, and their half-written copies. */+const RETIRED_FILES = /^(?:highlevel\.json\.enc|highlevel-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/u;++const without = <T>(record: Record<string, T>, slugs: readonly string[]): Record<string, T> =>+ Object.fromEntries(Object.entries(record).filter(([slug]) => !slugs.includes(slug)));++/** Drops the retired apps from a bot's scopes and tool grants; true when the bot changed. A bot limited to them alone+ * stays limited, to no app, as before. */+export function dropRetiredApps(bot: { connectorScopes?: ConnectorScopes; connectorTools?: Record<string, ConnectorToolGrant> }): boolean {+ const scoped = bot.connectorScopes?.apps ? RETIRED_APPS.filter((slug) => Object.hasOwn(bot.connectorScopes!.apps, slug)) : [];+ const granted = bot.connectorTools && typeof bot.connectorTools === "object" ? RETIRED_APPS.filter((slug) => Object.hasOwn(bot.connectorTools!, slug)) : [];+ if (scoped.length) bot.connectorScopes = { ...bot.connectorScopes!, apps: without(bot.connectorScopes!.apps, scoped) };+ if (granted.length) bot.connectorTools = without(bot.connectorTools!, granted);+ return scoped.length > 0 || granted.length > 0;+}++/** Removes the retired apps' saved connections from the data folder; the names it removed. */+export function removeRetiredAppFiles(dataDir: string): string[] {+ let names: string[];+ try { names = readdirSync(dataDir); } catch { return []; }+ return names.filter((name) => {+ if (!RETIRED_FILES.test(name)) return false;+ try { rmSync(join(dataDir, name), { force: true }); return true; } catch { return false; }+ });+}diff --git a/server/routes/cloud-connections.ts b/server/routes/cloud-connections.tsindex 24dc89b8e8..28fce5f230 100644--- a/server/routes/cloud-connections.ts+++ b/server/routes/cloud-connections.ts@@ -2,7 +2,7 @@// side, names this server's connections (never a secret) with the engines it runs and the programs it has. On a Cloud// home: POST /api/cloud-connections/connected-apps makes this Cloud act as the computer's connected-apps account (a// one-time code from OpenMausBot's service, or the person's own Composio project); PUT-// /api/cloud-connections/mcp/<name>/sign-in and PUT /api/cloud-connections/highlevel take a sign-in that moved; PUT+// /api/cloud-connections/mcp/<name>/sign-in takes a sign-in that moved; PUT// /api/cloud-connections/held-keys keeps a trial's moved keys unused while its Claude credit lasts; PUT// /api/cloud-connections/email takes the person's mailboxes. Admin scope// (request-auth's default): only the owner's app reaches them.@@ -10,7 +10,6 @@ import { z } from "zod";import type { ConnectionListing } from "../cloud-connections.ts";import type { ShareOutcome } from "../composio-share.ts";-import { parseHighLevelConnection, type HighLevelConnection } from "../highlevel/store.ts";import { parseMcpOAuthRecord, type McpOAuthRecord } from "../mcp-oauth-store.ts";import type { McpRunsOn } from "../mcp-registry.ts";import type { RequestAuth } from "../request-auth.ts";@@ -42,7 +41,7 @@ export interface CloudConnectionRouteDeps {/** Only a Cloud home takes connections, and a server of one person's own from that person's session (`ownHome`). */cloudHome: boolean;ownHome?(auth: RequestAuth): boolean;- /** A Team Cloud: a person's own connections (a share, a sign-in, HighLevel) are refused with one plain line. */+ /** A Team Cloud: a person's own connections (a share, a sign-in, a mailbox) are refused with one plain line. */personalRefusal?: (what: string) => string | null;list(): Promise<ConnectionsAnswer>;adoptShare(code: string): Promise<ShareOutcome>;@@ -51,7 +50,6 @@ export interface CloudConnectionRouteDeps {composioConnected(slugs: string[]): Promise<Record<string, boolean>>;/** `replaces`: the digest of the sign-in this computer moved here before, which a newer one may replace. */adoptSignIn(name: string, record: McpOAuthRecord, replaces: string | null): Adopted;- adoptHighLevel(connection: HighLevelConnection, replaces: string | null): Adopted;/** The person's mailboxes with their passwords; one already here at that address stays. */adoptEmail?(accounts: unknown[]): { adopted: number; kept: number };/** Keeps the keys of these engines unused while a trial's Claude credit lasts; false when they run now. */@@ -74,10 +72,10 @@ export function createCloudConnectionRoutes(deps: CloudConnectionRouteDeps): Roureturn json(res, 200, { held: deps.holdKeys?.(asked.data.for) ?? false });}const signIn = SIGN_IN.exec(path);- if (path !== "/api/cloud-connections/connected-apps" && path !== "/api/cloud-connections/highlevel" && path !== "/api/cloud-connections/email" && !signIn) return json(res, 404, { error: "not found" });+ if (path !== "/api/cloud-connections/connected-apps" && path !== "/api/cloud-connections/email" && !signIn) return json(res, 404, { error: "not found" });if (method !== (path === "/api/cloud-connections/connected-apps" ? "POST" : "PUT")) return json(res, 405, { error: "method not allowed" });if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return json(res, 415, { error: "content-type must be application/json" });- const refused = deps.personalRefusal?.(signIn ? signIn[1]! : path === "/api/cloud-connections/highlevel" ? "HighLevel" : path === "/api/cloud-connections/email" ? "Email" : "these apps");+ const refused = deps.personalRefusal?.(signIn ? signIn[1]! : path === "/api/cloud-connections/email" ? "Email" : "these apps");if (refused) { req.resume(); return json(res, 403, { error: refused }); }const body = await readBody(req, 64 * 1024);const replaces = url.searchParams.get("replaces");@@ -94,12 +92,6 @@ export function createCloudConnectionRoutes(deps: CloudConnectionRouteDeps): Rouif (!Array.isArray(accounts) || !deps.adoptEmail) return json(res, 400, { error: "send { accounts } as this computer keeps them" });return json(res, 200, deps.adoptEmail(accounts));}- if (path === "/api/cloud-connections/highlevel") {- const connection = parseHighLevelConnection(body);- if (!connection) return json(res, 400, { error: "send the HighLevel connection as this computer keeps it" });- const adopted = deps.adoptHighLevel(connection, replaces);- return adopted.ok ? json(res, 200, { [adopted.outcome]: true }) : json(res, adopted.status, { error: adopted.error });- }const parsed = connectSchema.safeParse(body);if (!parsed.success) return json(res, 400, { error: "send {share, apps} or {apiKey, userId, apps}" });diff --git a/server/routes/highlevel.ts b/server/routes/highlevel.tsdeleted file mode 100644index 4acbc8e111..0000000000--- a/server/routes/highlevel.ts+++ /dev/null@@ -1,59 +0,0 @@-// Owner/admin routes for the HighLevel connection. A client session never reaches these: request-auth denies any-// route not on its allow-list. No answer ever carries a token.-import { HighLevelError } from "../highlevel/client.ts";-import { HighLevelRelayError } from "../highlevel/relay.ts";-import type { HighLevelService } from "../highlevel/service.ts";-import { PASS, type RouteHandler } from "./table.ts";--export interface HighLevelRouteDeps {- service: HighLevelService;-}--const FLOW = /^\/api\/highlevel\/sign-in\/([0-9a-f-]{36})$/u;--export function createHighLevelRoutes(deps: HighLevelRouteDeps): RouteHandler {- const { service } = deps;- return async ({ req, res, path, method, auth, json, readBody }) => {- if (path !== "/api/highlevel" && !path.startsWith("/api/highlevel/")) return PASS;- if (!auth.scopes.includes("admin")) return json(res, 403, { error: "Only the owner or an admin can manage the HighLevel connection." });- res.setHeader("Cache-Control", "no-store");- try {- if (path === "/api/highlevel") {- if (method === "GET") return json(res, 200, service.status());- if (method === "DELETE") return json(res, 200, service.disconnect());- return json(res, 405, { error: "method not allowed" });- }- if (path === "/api/highlevel/sign-in") {- if (method !== "POST") return json(res, 405, { error: "method not allowed" });- return json(res, 200, await service.startSignIn());- }- const flow = FLOW.exec(path);- if (flow) {- const flowId = flow[1]!;- if (method === "GET") {- const status = service.signInStatus(flowId);- return status ? json(res, 200, status) : json(res, 404, { error: "This sign-in is no longer available. Start again." });- }- if (method === "DELETE") return json(res, 200, { ok: service.cancelSignIn(flowId) });- return json(res, 405, { error: "method not allowed" });- }- if (path === "/api/highlevel/token") {- if (method !== "POST") return json(res, 405, { error: "method not allowed" });- if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {- return json(res, 415, { error: "content-type must be application/json" });- }- const body = await readBody(req, 20_480);- const token = typeof body?.token === "string" ? body.token.trim() : "";- const locationId = typeof body?.locationId === "string" ? body.locationId.trim() : "";- if (!token) return json(res, 400, { error: "Paste a Private Integration token. It starts with pit-." });- if (!locationId) return json(res, 400, { error: "Enter the location id (Settings → Business Profile in HighLevel)." });- return json(res, 200, await service.connectWithToken(token, locationId));- }- return json(res, 404, { error: "not found" });- } catch (error) {- if (error instanceof HighLevelError) return json(res, error.status && error.status >= 400 && error.status < 600 ? error.status : 400, { error: error.message });- if (error instanceof HighLevelRelayError) return json(res, error.status >= 500 ? 502 : error.status, { error: error.message, code: error.code });- throw error;- }- };-}diff --git a/server/routes/own-mcp-http.ts b/server/routes/own-mcp-http.tsindex 771d7652b5..3ba29c5822 100644--- a/server/routes/own-mcp-http.ts+++ b/server/routes/own-mcp-http.ts@@ -1,4 +1,4 @@-// OpenMausBot's own MCP servers (agents, browser, computer, data, HighLevel) over MCP's Streamable HTTP transport, JSON+// OpenMausBot's own MCP servers (agents, browser, computer, data, Email, phone) over MCP's Streamable HTTP transport, JSON// responses only, for engines that reach MCP servers by URL: one endpoint in this process instead of a stdio proxy// process per server in every session. The turn's capability rides the Authorization header, and the endpoints behind// these answers check it, as they check the stdio proxies'.diff --git a/server/store.test.ts b/server/store.test.tsindex bb65e31262..1a351a3d6f 100644--- a/server/store.test.ts+++ b/server/store.test.ts@@ -58,6 +58,26 @@ describe("Store", () => {expect(loaded.bot(bot.id)?.connectorTools, "a list already chosen for an app stays").toEqual({ gmail: { tools: ["GMAIL_FETCH_EMAILS"] }, github: { tools: "*" } });});+ it("loads a bot saved with the retired HighLevel app, dropping it from its scopes and tool grants", () => {+ const store = new Store(selection);+ const crm = store.createBot({ name: "CRM helper" });+ const only = store.createBot({ name: "Limited bot" });+ const file = join(DATA_DIR, "bots.json");+ const rows = JSON.parse(readFileSync(file, "utf8")) as BotRecord[];+ Object.assign(rows.find((row) => row.id === crm.id)!, { composio: true,+ connectorTools: { gmail: { tools: "*" }, highlevel: { tools: ["HIGHLEVEL_GET_CONTACT"] } }, connectorScopes: { apps: { gmail: "read", highlevel: "write" } } });+ Object.assign(rows.find((row) => row.id === only.id)!, { composio: true, connectorTools: { highlevel: { tools: "*" } }, connectorScopes: { apps: { highlevel: "read" } } });+ writeFileSync(file, JSON.stringify(rows));++ const loaded = new Store(selection);+ expect(loaded.bot(crm.id)).toMatchObject({ name: "CRM helper", connectorTools: { gmail: { tools: "*" } }, connectorScopes: { apps: { gmail: "read" } } });+ expect(loaded.bot(crm.id)?.connectorTools).not.toHaveProperty("highlevel");+ expect(loaded.bot(only.id), "limited to HighLevel alone, it stays limited, to no app").toMatchObject({ name: "Limited bot", connectorTools: {}, connectorScopes: { apps: {} } });+ const saved = readFileSync(file, "utf8");+ expect(saved, "saved").not.toContain("highlevel");+ expect(JSON.parse(saved).map((row: BotRecord) => row.id)).toEqual(expect.arrayContaining([crm.id, only.id]));+ });+it.each([undefined, { allow: ["native:read"] }, { deny: ["native:bash"] }])("does not activate a wider tool selection when saving %j fails", (toolScope) => {const store = new Store(selection);const bot = store.createBot();diff --git a/server/store.ts b/server/store.tsindex 2721deaf12..9bb7e4d11f 100644--- a/server/store.ts+++ b/server/store.ts@@ -3,7 +3,7 @@ import { join } from "node:path"; import { isDeepStrictEqual } from "node:util";import { OwnedFile, writeFileAtomic } from "./atomic.ts"; import { saveSoon } from "./save-batch.ts"; import { discardNativeLog } from "./drivers/native.ts";import { commitRegistryChange, keptRevocation, saveRegistryFor, touchesPermissions } from "./registry-save.ts";-import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts";+import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts"; import { dropRetiredApps } from "./retired-apps.ts";import { reorderStable } from "../shared/bot-order.ts"; import { trimOutboundPolicy } from "../shared/outbound.ts";import { botOwner, chiefConflict, chiefScope, ownerEmail } from "../shared/bot-owner.ts";import { ensureSections, readSections, changeEmptySection } from "./section-context.ts";@@ -336,7 +336,7 @@ export class Store {for (const b of this.bots) {if (b.busy || (b.activity !== undefined && b.activity !== "idle")) botsMigrated = true;b.busy = false;- b.activity = "idle"; if (grantScopedApps(b)) botsMigrated = true; if (trimOutboundPolicy(b)) botsMigrated = true;+ b.activity = "idle"; if (dropRetiredApps(b)) botsMigrated = true; if (grantScopedApps(b)) botsMigrated = true; if (trimOutboundPolicy(b)) botsMigrated = true;if (typeof b.soul !== "string") {b.soul = "";botsMigrated = true;diff --git a/server/testing/fake-highlevel.ts b/server/testing/fake-highlevel.tsdeleted file mode 100644index fcb70e56de..0000000000--- a/server/testing/fake-highlevel.ts+++ /dev/null@@ -1,203 +0,0 @@-// A loopback stand-in for services.leadconnectorhq.com: canned records with the noise fields the real API adds,-// bearer checks against a set of live access tokens, and one-shot response overrides for 401/429/5xx paths.-import { createServer, type Server } from "node:http";--export interface FakeHighLevelCall {- method: string;- path: string;- query: Record<string, string>;- headers: Record<string, string>;- body: unknown;-}--export interface FakeHighLevelOverride { status: number; headers?: Record<string, string>; body?: unknown }--export interface FakeHighLevel {- url: string;- locationId: string;- calls: FakeHighLevelCall[];- /** Access tokens the API accepts. */- tokens: Set<string>;- /** Shifted one per request before any routing. */- overrides: FakeHighLevelOverride[];- /** Standing answers for "METHOD /path", given only to an accepted token: a missing scope, not a dead token. */- pathOverrides: Map<string, FakeHighLevelOverride>;- close(): Promise<void>;-}--export const FAKE_LOCATION_ID = "loc_fixture_01";--const RAW_CONTACT = (id: string, extra: Record<string, unknown> = {}) => ({- id, locationId: FAKE_LOCATION_ID, firstName: "Ada", lastName: "Lovelace", name: "Ada Lovelace", email: "[email protected]",- emailLowerCase: "[email protected]", firstNameLowerCase: "ada", lastNameLowerCase: "lovelace", fullNameLowerCase: "ada lovelace",- phone: "+15550001234", companyName: "Analytical Engines", tags: ["vip", "newsletter"], source: "web form", assignedTo: "user_1",- dateAdded: "2026-01-02T03:04:05.000Z", dateUpdated: "2026-02-03T04:05:06.000Z", address1: "1 Engine Row", city: "London", country: "GB",- dnd: false, dndSettings: { Email: { status: "inactive" } }, type: "lead", attributionSource: { url: "https://x.test", ip: "10.0.0.1", userAgent: "ua" },- lastAttributionSource: {}, visitorId: "v1", customFields: [{ id: "cf_lead", value: "Referral" }, { id: "cf_budget", value: 1200 }],- ...extra,-});--const RAW_OPPORTUNITY = (id: string, extra: Record<string, unknown> = {}) => ({- id, name: "Website redesign", monetaryValue: 4500, pipelineId: "pipe_1", pipelineStageId: "stage_new", assignedTo: "user_1", status: "open",- source: "referral", lastStatusChangeAt: "2026-03-01T00:00:00.000Z", lastStageChangeAt: "2026-03-02T00:00:00.000Z", indexVersion: 3,- createdAt: "2026-02-28T00:00:00.000Z", updatedAt: "2026-03-02T00:00:00.000Z", contactId: "contact_1", locationId: FAKE_LOCATION_ID,- contact: { id: "contact_1", name: "Ada Lovelace", companyName: "Analytical Engines", email: "[email protected]", phone: "+15550001234", tags: ["vip"] },- notes: [], tasks: [], calendarEvents: [], customFields: [], followers: [],- ...extra,-});--export async function startFakeHighLevel(options: { locationId?: string } = {}): Promise<FakeHighLevel> {- const locationId = options.locationId ?? FAKE_LOCATION_ID;- const calls: FakeHighLevelCall[] = [];- const tokens = new Set<string>();- const overrides: FakeHighLevelOverride[] = [];- const pathOverrides = new Map<string, FakeHighLevelOverride>();- const server: Server = createServer(async (req, res) => {- let raw = "";- for await (const chunk of req) raw += chunk;- const url = new URL(req.url ?? "/", "http://fixture");- const headers: Record<string, string> = {};- for (const [key, value] of Object.entries(req.headers)) if (typeof value === "string") headers[key] = value;- let body: unknown = null;- try { body = raw ? JSON.parse(raw) : null; } catch { body = raw; }- const call: FakeHighLevelCall = { method: req.method ?? "GET", path: url.pathname, query: Object.fromEntries(url.searchParams), headers, body };- calls.push(call);- const answer = (status: number, payload: unknown, extra: Record<string, string> = {}) => {- res.writeHead(status, { "content-type": "application/json", "x-ratelimit-remaining": "97", "x-ratelimit-daily-remaining": "199000", ...extra });- res.end(JSON.stringify(payload));- };- const override = overrides.shift();- if (override) return answer(override.status, override.body ?? { message: `fixture ${override.status}` }, override.headers);- const bearer = /^Bearer (.+)$/u.exec(headers.authorization ?? "")?.[1];- if (!bearer || !tokens.has(bearer)) return answer(401, { statusCode: 401, message: "Invalid JWT" });- if (headers.version !== "2021-07-28" && headers.version !== "2021-04-15") return answer(400, { message: "Version header is missing" });- const standing = pathOverrides.get(`${call.method} ${url.pathname}`);- if (standing) return answer(standing.status, standing.body ?? { message: `fixture ${standing.status}` }, standing.headers);- const { method } = call;- const path = url.pathname;- let m: RegExpExecArray | null;- if (method === "POST" && path === "/contacts/search") return answer(200, { contacts: [RAW_CONTACT("contact_1")], total: 1 });- if (method === "POST" && path === "/contacts/") return answer(201, { contact: RAW_CONTACT("contact_new", { ...(body as Record<string, unknown>), id: "contact_new" }) });- if ((m = /^\/contacts\/([^/]+)\/tags$/u.exec(path)) && (method === "POST" || method === "DELETE")) return answer(200, { tags: (body as { tags: string[] }).tags });- if ((m = /^\/contacts\/([^/]+)\/notes$/u.exec(path)) && method === "GET") return answer(200, { notes: [{ id: "note_1", body: "Called back", userId: "user_1", dateAdded: "2026-03-03T00:00:00.000Z", contactId: m[1] }] });- if ((m = /^\/contacts\/([^/]+)\/notes$/u.exec(path)) && method === "POST") return answer(201, { note: { id: "note_new", body: (body as { body: string }).body, userId: "user_1", dateAdded: "2026-03-04T00:00:00.000Z", contactId: m[1] } });- if ((m = /^\/contacts\/([^/]+)\/tasks$/u.exec(path)) && method === "GET") return answer(200, { tasks: [{ id: "task_1", title: "Send quote", body: "", dueDate: "2026-03-10T09:00:00.000Z", completed: false, assignedTo: "user_1", contactId: m[1] }] });- if ((m = /^\/contacts\/([^/]+)\/tasks$/u.exec(path)) && method === "POST") return answer(201, { task: { id: "task_new", ...(body as Record<string, unknown>), contactId: m[1] } });- if ((m = /^\/contacts\/([^/]+)$/u.exec(path)) && method === "GET") {- if (m[1] === "missing") return answer(404, { statusCode: 404, message: "Contact not found" });- return answer(200, { contact: RAW_CONTACT(m[1]!) });- }- if ((m = /^\/contacts\/([^/]+)$/u.exec(path)) && method === "PUT") return answer(200, { succeded: true, contact: RAW_CONTACT(m[1]!, body as Record<string, unknown>) });- if (method === "GET" && path === "/opportunities/pipelines") return answer(200, { pipelines: [{ id: "pipe_1", name: "Sales", showInFunnel: true, locationId, stages: [{ id: "stage_new", name: "New", position: 0 }, { id: "stage_won", name: "Won", position: 1 }] }] });- if (method === "GET" && path === "/opportunities/search") return answer(200, { opportunities: [RAW_OPPORTUNITY("opp_1")], meta: { total: 1, currentPage: 1 }, aggregations: {} });- if (method === "POST" && path === "/opportunities/") return answer(201, { opportunity: RAW_OPPORTUNITY("opp_new", body as Record<string, unknown>) });- if ((m = /^\/opportunities\/([^/]+)$/u.exec(path)) && method === "GET") return answer(200, { opportunity: RAW_OPPORTUNITY(m[1]!) });- if ((m = /^\/opportunities\/([^/]+)$/u.exec(path)) && method === "PUT") return answer(200, { opportunity: RAW_OPPORTUNITY(m[1]!, body as Record<string, unknown>) });- if (method === "GET" && path === "/conversations/search") {- return answer(200, { conversations: [{ id: "conv_1", contactId: "contact_1", locationId, lastMessageBody: "See you Tuesday", lastMessageType: "TYPE_SMS", lastMessageDate: 1772000000000, type: "TYPE_PHONE", unreadCount: 2, fullName: "Ada Lovelace", contactName: "Ada Lovelace", email: "[email protected]", phone: "+15550001234" }], total: 1 });- }- if ((m = /^\/conversations\/([^/]+)\/messages$/u.exec(path)) && method === "GET") {- return answer(200, { messages: { lastMessageId: "msg_2", nextPage: false, messages: [- { id: "msg_2", type: 1, messageType: "TYPE_SMS", direction: "inbound", status: "delivered", dateAdded: "2026-03-05T10:00:00.000Z", body: "See you Tuesday", contentType: "text/plain", attachments: [], conversationId: m[1], locationId, contactId: "contact_1", conversationProviderId: "prov" },- { id: "msg_1", type: 1, messageType: "TYPE_SMS", direction: "outbound", status: "delivered", dateAdded: "2026-03-05T09:00:00.000Z", body: "Can we meet?", contentType: "text/plain", attachments: [{ url: "x" }], conversationId: m[1], locationId, contactId: "contact_1" },- ] } });- }- if (method === "POST" && path.startsWith("/conversations/messages")) return answer(500, { message: "FIXTURE: a message send reached the fake; the client guard failed" });- if (method === "GET" && path === "/calendars/") return answer(200, { calendars: [{ id: "cal_1", name: "Consultations", description: "30 min", isActive: true, calendarType: "round_robin", slotDuration: 30, slotDurationUnit: "mins", teamMembers: [{ userId: "user_1" }], locationId, openHours: [] }] });- if (method === "GET" && path === "/calendars/events") return answer(200, { events: [{ id: "evt_1", title: "Intro call", calendarId: "cal_1", locationId, contactId: "contact_1", appointmentStatus: "confirmed", startTime: "2026-03-10T15:00:00.000Z", endTime: "2026-03-10T15:30:00.000Z", assignedUserId: "user_1", address: "Zoom", notes: "bring deck", users: ["user_1"], dateAdded: "2026-03-01T00:00:00.000Z" }] });- if ((m = /^\/locations\/([^/]+)\/customFields$/u.exec(path)) && method === "GET") {- return answer(200, { customFields: [- { id: "cf_lead", name: "Lead Source", fieldKey: "contact.lead_source", dataType: "TEXT", position: 0, locationId, model: "contact" },- { id: "cf_budget", name: "Budget", fieldKey: "contact.budget", dataType: "NUMERICAL", position: 1, locationId, model: "contact" },- ] });- }- if ((m = /^\/locations\/([^/]+)$/u.exec(path)) && method === "GET") {- if (m[1] !== locationId) return answer(403, { statusCode: 403, message: "The token does not have access to this location." });- return answer(200, { location: { id: locationId, companyId: "company_1", name: "Example Profiles", timezone: "America/Chicago", email: "[email protected]", phone: "+15550009999", website: "https://fixture.test", address: "2 Main St", city: "Austin", state: "TX", country: "US", postalCode: "78701", settings: {}, social: {}, business: {} } });- }- return answer(404, { statusCode: 404, message: `fixture has no route for ${method} ${path}` });- });- await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));- const address = server.address();- if (!address || typeof address === "string") throw new Error("fake HighLevel did not bind");- return {- url: `http://127.0.0.1:${address.port}`, locationId, calls, tokens, overrides, pathOverrides,- close: () => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()); }),- };-}--export interface FakeRelay {- url: string;- calls: Array<{ path: string; body: unknown }>;- refreshes: number;- /** What `start` has handed out, with whether the person finished and whether the payload was collected. */- states: Map<string, { completed: boolean; claimed: boolean }>;- /** The refresh tokens the relay (HighLevel) still honours. */- refreshTokens: Set<string>;- /** Every access token the relay has issued, in order. */- issued: string[];- unavailable: boolean;- /** Simulates HighLevel's callback for a state: the next claim gets tokens. */- complete(state: string): void;- close(): Promise<void>;-}--/** The control plane's HighLevel routes, per spec §9: start → claim once (404 before the callback, 410 after) → refresh. */-export async function startFakeRelay(options: { onAccessToken?(token: string): void; locationId?: string; expiresIn?: number } = {}): Promise<FakeRelay> {- const states = new Map<string, { completed: boolean; claimed: boolean }>();- const refreshTokens = new Set<string>();- const issued: string[] = [];- const calls: Array<{ path: string; body: unknown }> = [];- let counter = 0;- const relay: FakeRelay = {- url: "", calls, refreshes: 0, states, refreshTokens, issued, unavailable: false,- complete(state) { const row = states.get(state); if (row) row.completed = true; },- close: async () => {},- };- const tokenSet = () => {- counter++;- const accessToken = `hl_access_${counter}`;- const refreshToken = `hl_refresh_${counter}`;- refreshTokens.add(refreshToken);- issued.push(accessToken);- options.onAccessToken?.(accessToken);- return { accessToken, refreshToken, expiresIn: options.expiresIn ?? 86_400, scope: "contacts.readonly contacts.write opportunities.readonly", locationId: options.locationId ?? FAKE_LOCATION_ID, companyId: "company_1", userId: "user_1" };- };- const server = createServer(async (req, res) => {- let raw = "";- for await (const chunk of req) raw += chunk;- let body: unknown = {};- try { body = raw ? JSON.parse(raw) : {}; } catch {}- const path = new URL(req.url ?? "/", "http://fixture").pathname;- calls.push({ path, body });- const answer = (status: number, payload: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(payload)); };- if (relay.unavailable) return answer(503, { error: "highlevel_unavailable" });- if (req.method !== "POST") return answer(405, { error: "method_not_allowed" });- if (path === "/v1/highlevel/start") {- const state = `state_${++counter}_${Math.random().toString(36).slice(2, 10)}`;- states.set(state, { completed: false, claimed: false });- return answer(200, { state, authorizationUrl: `https://marketplace.leadconnectorhq.com/v2/oauth/chooselocation?response_type=code&client_id=fixture&state=${state}`, expiresAt: new Date(Date.now() + 600_000).toISOString() });- }- if (path === "/v1/highlevel/claim") {- const row = states.get(String((body as { state?: unknown }).state ?? ""));- if (!row || !row.completed) return answer(404, { error: "highlevel_unknown_state" });- if (row.claimed) return answer(410, { error: "highlevel_claimed" });- row.claimed = true;- return answer(200, tokenSet());- }- if (path === "/v1/highlevel/refresh") {- relay.refreshes++;- const token = String((body as { refreshToken?: unknown }).refreshToken ?? "");- if (!refreshTokens.has(token)) return answer(401, { error: "highlevel_refresh_rejected" });- refreshTokens.delete(token);- return answer(200, tokenSet());- }- return answer(404, { error: "not_found" });- });- await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));- const address = server.address();- if (!address || typeof address === "string") throw new Error("fake relay did not bind");- relay.url = `http://127.0.0.1:${address.port}`;- relay.close = () => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()); });- return relay;-}diff --git a/server/tool-schema-profile.test.ts b/server/tool-schema-profile.test.tsindex 9716adce75..3e569a52ab 100644--- a/server/tool-schema-profile.test.ts+++ b/server/tool-schema-profile.test.ts@@ -5,7 +5,6 @@ import { CLOUD_COMPUTER_TOOLS } from "./cloud-computer-tools.ts";import { DATA_TOOLS } from "./data/tools.ts";import bridgedAgents from "./drivers/agents-catalog-goldens/bridged.tools-list.json" with { type: "json" };import fullAgents from "./drivers/agents-catalog-goldens/full.tools-list.json" with { type: "json" };-import { HIGHLEVEL_TOOLS } from "./highlevel/tools.ts";import { createPageSchema, wideSchema } from "./testing/oversized-tool-schema.ts";import { fitToolSchema, schemaBytes, toolSchemaProfile, toolSchemaProfileFor, type ToolSchemaProfile } from "./tool-schema-profile.ts";@@ -166,7 +165,7 @@ describe("which turns carry a schema profile", () => {describe("OpenMausBot's own tools", () => {const catalogs: Array<[string, ReadonlyArray<{ name: string; inputSchema: unknown }>]> = [["agents (full)", fullAgents.tools], ["agents (bridged)", bridgedAgents.tools], ["browser", BROWSER_TOOLS],- ["data", DATA_TOOLS], ["highlevel", HIGHLEVEL_TOOLS], ["cloud computer", CLOUD_COMPUTER_TOOLS],+ ["data", DATA_TOOLS], ["cloud computer", CLOUD_COMPUTER_TOOLS],];it.each(catalogs)("fit every profile as written: %s", (_name, tools) => {diff --git a/server/workspace-backup-policy.test.ts b/server/workspace-backup-policy.test.tsindex 9084550522..b93b32e261 100644--- a/server/workspace-backup-policy.test.ts+++ b/server/workspace-backup-policy.test.ts@@ -61,13 +61,6 @@ describe("workspace backup data boundary", () => {for (const path of ["logins.json", "logins.md", "workspaces/bot/logins.json.enc", "attachments/logins-key"]) expect(excludedWorkspaceAuthPath(path)).toBe(false);});- it("never exports or restores the HighLevel connection or its key", () => {- for (const path of ["highlevel.json.enc", "highlevel-key", "highlevel.json.enc.4242.05a7b3e0-1234-4abc-8def-0123456789ab.tmp", "highlevel-key.12.05a7b3e0-1234.tmp"]) {- expect(excludedWorkspaceAuthPath(path)).toBe(true);- }- for (const path of ["highlevel.md", "workspaces/bot/highlevel.json.enc", "attachments/highlevel-key"]) expect(excludedWorkspaceAuthPath(path)).toBe(false);- });-it("never exports or restores a Cloud home's connected-apps installation", () => {for (const path of ["connected-apps-installation.json", "connected-apps-installation.json.4242.05a7b3e0-1234-4abc-8def-0123456789ab.tmp"]) {expect(excludedWorkspaceAuthPath(path)).toBe(true);diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.tsindex f76ed6b510..84aeda5570 100644--- a/server/workspace-backup-policy.ts+++ b/server/workspace-backup-policy.ts@@ -40,8 +40,6 @@ export function excludedWorkspaceAuthPath(path: string): boolean {if (/^mcp-oauth\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;// Saved website logins and their key never leave the computer they were saved on, nor does the key sealing webhook secrets.if (/^(?:logins\.json\.enc|logins-key|webhook-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;- // The HighLevel connection and its key stay with the installation that connected: its refresh token rotates, so a copy signs one side out.- if (/^(?:highlevel\.json\.enc|highlevel-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;// A Cloud home's connected-apps installation: its connected accounts belong to it, so a copy would share them.if (/^connected-apps-installation\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;// A Team Cloud's kept rules: a restored Cloud asks the Admin for the ones in force now.diff --git a/server/workspace-backup.test.ts b/server/workspace-backup.test.tsindex c7645d31d6..53d3356748 100644--- a/server/workspace-backup.test.ts+++ b/server/workspace-backup.test.ts@@ -370,7 +370,7 @@ describe("encrypted full workspace backups", () => {"vm-home/.browser-profiles/chrome/Cookies", "vm-homes/abc/.browser-profiles/chromium/Cookies","tmp/omb-mcp-123/mcp.json", ".tmp/secret","logins.json.enc", "logins-key", "logins.json.enc.123.05a7b3e0-1234.tmp",- "highlevel.json.enc", "highlevel-key", "connected-apps-installation.json", "webhook-key",+ "connected-apps-installation.json", "webhook-key",];for (const root of [source, target]) {for (const path of authPaths) {diff --git a/shared/highlevel.ts b/shared/highlevel.tsdeleted file mode 100644index 902952dd55..0000000000--- a/shared/highlevel.ts+++ /dev/null@@ -1,94 +0,0 @@-// The HighLevel CRM connector's fixed names, shared by the server (tools, per-bot checks) and the app (bot settings).-// Tool names are upper-snake with the HIGHLEVEL_ prefix so the connector grant and scope rules apply unchanged.--/** The connector slug in a bot's connectorScopes.apps and connectorTools. */-export const HIGHLEVEL_SLUG = "highlevel";--/** The MCP server name bots see (tools arrive as mcp__highlevel__HIGHLEVEL_<ACTION>). */-export const HIGHLEVEL_MCP_SERVER = "highlevel";--export const HIGHLEVEL_TOOL_NAMES = [- "HIGHLEVEL_SEARCH_CONTACTS",- "HIGHLEVEL_GET_CONTACT",- "HIGHLEVEL_CREATE_CONTACT",- "HIGHLEVEL_UPDATE_CONTACT",- "HIGHLEVEL_ADD_TAGS",- "HIGHLEVEL_REMOVE_TAGS",- "HIGHLEVEL_LIST_NOTES",- "HIGHLEVEL_ADD_NOTE",- "HIGHLEVEL_LIST_TASKS",- "HIGHLEVEL_ADD_TASK",- "HIGHLEVEL_LIST_PIPELINES",- "HIGHLEVEL_SEARCH_OPPORTUNITIES",- "HIGHLEVEL_GET_OPPORTUNITY",- "HIGHLEVEL_CREATE_OPPORTUNITY",- "HIGHLEVEL_UPDATE_OPPORTUNITY",- "HIGHLEVEL_SEARCH_CONVERSATIONS",- "HIGHLEVEL_READ_CONVERSATION",- "HIGHLEVEL_LIST_CALENDARS",- "HIGHLEVEL_LIST_EVENTS",- "HIGHLEVEL_GET_LOCATION",-] as const;--export type HighLevelToolName = (typeof HIGHLEVEL_TOOL_NAMES)[number];--export type HighLevelToolGroup = "contacts" | "pipelines" | "conversations" | "calendars";--/** The per-bot groups shown in bot settings; a group is a connectorTools grant naming exactly these tools.- * HIGHLEVEL_GET_LOCATION belongs to every group: it only describes the connected location. */-export const HIGHLEVEL_TOOL_GROUPS: Record<HighLevelToolGroup, { label: string; tools: readonly HighLevelToolName[] }> = {- contacts: {- label: "Contacts and notes",- tools: [- "HIGHLEVEL_SEARCH_CONTACTS", "HIGHLEVEL_GET_CONTACT", "HIGHLEVEL_CREATE_CONTACT", "HIGHLEVEL_UPDATE_CONTACT",- "HIGHLEVEL_ADD_TAGS", "HIGHLEVEL_REMOVE_TAGS", "HIGHLEVEL_LIST_NOTES", "HIGHLEVEL_ADD_NOTE",- "HIGHLEVEL_LIST_TASKS", "HIGHLEVEL_ADD_TASK", "HIGHLEVEL_GET_LOCATION",- ],- },- pipelines: {- label: "Pipelines and deals",- tools: [- "HIGHLEVEL_LIST_PIPELINES", "HIGHLEVEL_SEARCH_OPPORTUNITIES", "HIGHLEVEL_GET_OPPORTUNITY",- "HIGHLEVEL_CREATE_OPPORTUNITY", "HIGHLEVEL_UPDATE_OPPORTUNITY", "HIGHLEVEL_GET_LOCATION",- ],- },- conversations: {- label: "Conversations (read)",- tools: ["HIGHLEVEL_SEARCH_CONVERSATIONS", "HIGHLEVEL_READ_CONVERSATION", "HIGHLEVEL_GET_LOCATION"],- },- calendars: {- label: "Calendars (read)",- tools: ["HIGHLEVEL_LIST_CALENDARS", "HIGHLEVEL_LIST_EVENTS", "HIGHLEVEL_GET_LOCATION"],- },-};--/** The default grant for a new bot: contacts and notes. */-export const HIGHLEVEL_DEFAULT_GROUPS: readonly HighLevelToolGroup[] = ["contacts"];--export function highlevelToolsForGroups(groups: readonly HighLevelToolGroup[]): HighLevelToolName[] {- const names = new Set<HighLevelToolName>();- for (const group of groups) for (const tool of HIGHLEVEL_TOOL_GROUPS[group].tools) names.add(tool);- return HIGHLEVEL_TOOL_NAMES.filter((name) => names.has(name));-}--/** The groups a grant list covers completely. */-export function highlevelGroupsForTools(tools: "*" | readonly string[]): HighLevelToolGroup[] {- const all = Object.keys(HIGHLEVEL_TOOL_GROUPS) as HighLevelToolGroup[];- if (tools === "*") return all;- const granted = new Set(tools);- return all.filter((group) => HIGHLEVEL_TOOL_GROUPS[group].tools.every((tool) => granted.has(tool)));-}--export type HighLevelConnectionState = "unavailable" | "signed-out" | "connecting" | "connected" | "needs-sign-in";--/** GET /api/highlevel. */-export interface HighLevelStatus {- state: HighLevelConnectionState;- kind?: "oauth" | "token";- location?: { id: string; name: string };- connectedAt?: number;- flow?: { flowId: string; authorizationUrl: string; expiresAt: number };- problem?: string;-}--export type HighLevelSignInPhase = "waiting" | "connected" | "failed" | "expired";diff --git a/shared/today-outcomes.test.ts b/shared/today-outcomes.test.tsindex 60fd2470cf..b33d936c7b 100644--- a/shared/today-outcomes.test.ts+++ b/shared/today-outcomes.test.ts@@ -42,7 +42,6 @@ const CASES: ReadonlyArray<[string, OutcomeCategory | null]> = [["PIPEDRIVE_ADD_A_PERSON", "lead"],["APOLLO_PEOPLE_SEARCH", "lead"],["HUNTER_EMAIL_FINDER", "lead"],- ["mcp__highlevel__HIGHLEVEL_CREATE_CONTACT", "lead"],["HUBSPOT_LIST_CONTACTS", null],["STRIPE_CREATE_REFUND", "other"],["GOOGLECALENDAR_CREATE_EVENT", "other"],diff --git a/shared/today-outcomes.ts b/shared/today-outcomes.tsindex 3a49596d3d..5fc4376fee 100644--- a/shared/today-outcomes.ts+++ b/shared/today-outcomes.ts@@ -29,7 +29,7 @@ export function minutesSaved(counts: OutcomeCounts): number {const EMAIL_APPS = new Set(["GMAIL", "OUTLOOK", "ZOHOMAIL", "AGENTMAIL", "SENDGRID", "RESEND", "POSTMARK", "MAILGUN", "FASTMAIL", "YAHOOMAIL"]);/** CRMs: creating, updating, searching or enriching a person, company or deal is a lead or record. */-const CRM_APPS = new Set(["HUBSPOT", "SALESFORCE", "PIPEDRIVE", "ZOHO", "ATTIO", "CLOSE", "COPPER", "FRESHSALES", "HIGHLEVEL", "AFFINITY", "FOLK", "KEAP", "ACTIVECAMPAIGN"]);+const CRM_APPS = new Set(["HUBSPOT", "SALESFORCE", "PIPEDRIVE", "ZOHO", "ATTIO", "CLOSE", "COPPER", "FRESHSALES", "AFFINITY", "FOLK", "KEAP", "ACTIVECAMPAIGN"]);/** Prospecting and enrichment services: every call looks people or companies up. */const PROSPECTING_APPS = new Set(["APOLLO", "HUNTER", "CLEARBIT", "LUSHA", "SNOV", "PEOPLEDATALABS", "ROCKETREACH", "PROSPEO", "DROPCONTACT"]);const DOC_APPS = new Set([@@ -68,7 +68,7 @@ export function appTool(name: string): AppTool | null {if (name.startsWith("mcp__")) {const [, server = "", ...rest] = name.split("__");const action = rest.join("__");- if (isConnectedAppsServer(server) || server === "highlevel") return appTool(action);+ if (isConnectedAppsServer(server)) return appTool(action);if (OWN_SERVERS.has(server) || !action) return null;const app = words(server.replace(/^claude_ai_/, "")).join("");const tokens = words(action);diff --git a/src/components/HighLevelCard.test.ts b/src/components/HighLevelCard.test.tsdeleted file mode 100644index cf02741cbf..0000000000--- a/src/components/HighLevelCard.test.ts+++ /dev/null@@ -1,275 +0,0 @@-// @vitest-environment happy-dom-import { act, createElement } from "react";-import { createRoot, type Root } from "react-dom/client";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { setLocale } from "@/lib/i18n";-import type { HighLevelStatus } from "@/lib/highlevel-sign-in";--const fixture = vi.hoisted(() => {- (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;- return { api: vi.fn() };-});-vi.mock("@/state/store", () => ({ api: fixture.api }));--import { HighLevelCard } from "./HighLevelCard";-import { forgetHighLevelStatus, preloadHighLevelStatus } from "@/lib/highlevel-status";--const flow = { flowId: "flow-1", authorizationUrl: "https://marketplace.leadconnectorhq.com/v2/oauth/chooselocation?state=abc", expiresAt: "2026-10-15T12:10:00Z" };-const connectedStatus: HighLevelStatus = { state: "connected", kind: "oauth", location: { id: "loc_1", name: "Example Profiles" } };--interface Server {- status: HighLevelStatus;- polls: Array<{ phase: string; message?: string }>;- calls: Array<[string, string, unknown]>;-}-let server: Server;-let host: HTMLDivElement;-let root: Root;-let openExternal: ReturnType<typeof vi.fn<(url: string) => Promise<boolean>>>;-let onConnection: ReturnType<typeof vi.fn<(connected: boolean | null) => void>>;--const settle = () => act(async () => { for (let turn = 0; turn < 6; turn += 1) await Promise.resolve(); });-const card = () => host.querySelector<HTMLElement>('[data-app-tile="highlevel"]');-const buttons = () => [...host.querySelectorAll("button")];-const button = (label: string) => buttons().find((element) => element.textContent?.trim() === label || element.getAttribute("aria-label") === label);-const text = () => card()?.textContent ?? "";--function serve() {- fixture.api.mockImplementation(async (path: string, init?: RequestInit) => {- const method = init?.method ?? "GET";- const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;- server.calls.push([method, path, body]);- if (path === "/api/highlevel" && method === "GET") return server.status;- if (path === "/api/highlevel" && method === "DELETE") { server.status = { state: "signed-out" }; return { ok: true }; }- if (path === "/api/highlevel/sign-in" && method === "POST") { server.status = { state: "connecting", flow }; return flow; }- if (path === `/api/highlevel/sign-in/${flow.flowId}` && method === "GET") {- const next = server.polls.shift() ?? { phase: "waiting" };- if (next.phase === "connected") server.status = connectedStatus;- return next;- }- if (path === `/api/highlevel/sign-in/${flow.flowId}` && method === "DELETE") { server.status = { state: "signed-out" }; return { ok: true }; }- if (path === "/api/highlevel/token" && method === "POST") { server.status = { ...connectedStatus, kind: "token" }; return { ok: true }; }- throw new Error(`unexpected ${method} ${path}`);- });-}--async function mount(status: HighLevelStatus) {- server = { status, polls: [], calls: [] };- serve();- host = document.createElement("div");- document.body.append(host);- root = createRoot(host);- await act(async () => root.render(createElement(HighLevelCard, { onConnection })));- await settle();-}--const poll = async () => {- await act(async () => { await vi.advanceTimersByTimeAsync(1_500); });- await settle();-};--beforeEach(() => {- vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });- setLocale("en");- forgetHighLevelStatus();- fixture.api.mockReset();- openExternal = vi.fn<(url: string) => Promise<boolean>>(async () => true);- onConnection = vi.fn<(connected: boolean | null) => void>();- window.confirm = vi.fn(() => true);- (window as unknown as { ogb: unknown }).ogb = { openExternal };-});-afterEach(async () => {- await act(async () => root.unmount());- host.remove();- vi.useRealTimers();-});--describe("HighLevel card states", () => {- it("offers Connect with the CRM subtitle when signed out, and no token field until asked", async () => {- await mount({ state: "signed-out" });- expect(card()?.dataset.highlevelState).toBe("signed-out");- expect(text()).toContain("HighLevel");- expect(text()).toContain("Also Growably and other HighLevel-based CRMs.");- expect(button("Connect HighLevel")).toBeTruthy();- expect(button("Use a Private Integration token instead")).toBeTruthy();- expect(host.querySelector("input")).toBeNull();- expect(text()).not.toMatch(/OAuth/);- expect(onConnection).toHaveBeenLastCalledWith(false);- });-- it("shows the location's name once connected, with a menu instead of a Connect button", async () => {- await mount(connectedStatus);- expect(text()).toContain("Connected · Example Profiles");- expect(button("Connect HighLevel")).toBeUndefined();- expect(button("HighLevel options")).toBeTruthy();- expect(host.querySelector('[aria-label="Connected"]')).toBeTruthy();- expect(onConnection).toHaveBeenLastCalledWith(true);- });-- it("says it is signed out and offers Reconnect when the server lost the connection", async () => {- await mount({ state: "needs-sign-in", location: { id: "loc_1", name: "Example Profiles" } });- expect(text()).toContain("Signed out. Reconnect to keep using it.");- expect(button("Reconnect HighLevel")?.textContent).toBe("Reconnect");- expect(button("HighLevel options")).toBeTruthy();- expect(onConnection).toHaveBeenLastCalledWith(false);- });-- it("follows a sign-in the server already has, with Cancel and the finish-in-browser line", async () => {- await mount({ state: "connecting", flow });- expect(text()).toContain("Finish signing in to HighLevel in your browser.");- expect(button("Cancel")).toBeTruthy();- expect(openExternal).not.toHaveBeenCalled();- server.polls.push({ phase: "connected" });- await poll();- expect(text()).toContain("Connected · Example Profiles");- });-- it("draws nothing when the server has no relay", async () => {- await mount({ state: "unavailable" });- expect(card()).toBeNull();- expect(onConnection).toHaveBeenLastCalledWith(false);- });-});--describe("Connecting HighLevel", () => {- it("starts the flow, opens HighLevel's page, polls, and lands on connected", async () => {- await mount({ state: "signed-out" });- await act(async () => button("Connect HighLevel")!.click());- await settle();- expect(server.calls).toContainEqual(["POST", "/api/highlevel/sign-in", undefined]);- expect(openExternal).toHaveBeenCalledWith(flow.authorizationUrl);- expect(text()).toContain("Finish signing in to HighLevel in your browser.");- expect(button("Cancel")).toBeTruthy();- expect(server.calls.filter(([method, path]) => method === "GET" && path === `/api/highlevel/sign-in/${flow.flowId}`)).toHaveLength(0);-- await poll();- expect(server.calls.filter(([method, path]) => method === "GET" && path === `/api/highlevel/sign-in/${flow.flowId}`)).toHaveLength(1);- expect(text()).toContain("Finish signing in to HighLevel in your browser.");-- server.polls.push({ phase: "connected" });- await poll();- expect(text()).toContain("Connected · Example Profiles");- expect(button("Cancel")).toBeUndefined();- expect(host.querySelector('[role="alert"]')).toBeNull();- expect(onConnection).toHaveBeenLastCalledWith(true);- expect(await preloadHighLevelStatus()).toEqual(connectedStatus);- });-- it("cancels on the server and returns to Connect when the person cancels", async () => {- await mount({ state: "signed-out" });- await act(async () => button("Connect HighLevel")!.click());- await settle();- await act(async () => button("Cancel")!.click());- await settle();- expect(server.calls).toContainEqual(["DELETE", `/api/highlevel/sign-in/${flow.flowId}`, undefined]);- expect(button("Connect HighLevel")).toBeTruthy();- expect(host.querySelector('[role="alert"]')).toBeNull();- await poll();- expect(server.calls.filter(([method, path]) => method === "GET" && path === `/api/highlevel/sign-in/${flow.flowId}`)).toHaveLength(0);- });-- it("shows the server's reason in one line when the sign-in fails", async () => {- await mount({ state: "signed-out" });- await act(async () => button("Connect HighLevel")!.click());- await settle();- server.polls.push({ phase: "failed", message: "HighLevel refused the sign-in." });- server.status = { state: "signed-out" };- await poll();- expect([...host.querySelectorAll('[role="alert"]')].map((element) => element.textContent)).toEqual(["HighLevel refused the sign-in."]);- expect(button("Connect HighLevel")).toBeTruthy();- });-- it("reconnects through the same flow from the signed-out state", async () => {- await mount({ state: "needs-sign-in", location: { id: "loc_1", name: "Example Profiles" } });- await act(async () => button("Reconnect HighLevel")!.click());- await settle();- expect(server.calls).toContainEqual(["POST", "/api/highlevel/sign-in", undefined]);- expect(openExternal).toHaveBeenCalledWith(flow.authorizationUrl);- server.polls.push({ phase: "connected" });- await poll();- expect(text()).toContain("Connected · Example Profiles");- });-});--describe("Private Integration token", () => {- it("reveals the two fields with one line of help and posts token and location", async () => {- await mount({ state: "signed-out" });- await act(async () => button("Use a Private Integration token instead")!.click());- await settle();- const tokenField = host.querySelector<HTMLInputElement>('input[aria-label="Private Integration token"]')!;- const locationField = host.querySelector<HTMLInputElement>('input[aria-label="Location ID"]')!;- expect(tokenField.type).toBe("password");- expect(text()).toContain("go to Settings → Private Integrations");- // The one permission the token check itself needs, and the one contact reads use to name custom fields.- expect(text()).toMatch(/permissions: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities and View Custom Fields/u);-- await act(async () => host.querySelector<HTMLButtonElement>('form[data-highlevel-token-form] button[type="submit"]')!.click());- await settle();- expect(host.querySelector('[role="alert"]')?.textContent).toBe("Paste the token and the location ID.");- expect(server.calls.some(([, path]) => path === "/api/highlevel/token")).toBe(false);-- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;- await act(async () => {- nativeInputValueSetter.call(tokenField, " pit-abc ");- tokenField.dispatchEvent(new Event("input", { bubbles: true }));- nativeInputValueSetter.call(locationField, "loc_1");- locationField.dispatchEvent(new Event("input", { bubbles: true }));- });- await act(async () => host.querySelector<HTMLButtonElement>('form[data-highlevel-token-form] button[type="submit"]')!.click());- await settle();- expect(server.calls).toContainEqual(["POST", "/api/highlevel/token", { token: "pit-abc", locationId: "loc_1" }]);- expect(text()).toContain("Connected · Example Profiles");- expect(host.querySelector("input")).toBeNull();- });-- it("keeps the token out of the card and shows the server's refusal", async () => {- await mount({ state: "signed-out" });- await act(async () => button("Use a Private Integration token instead")!.click());- await settle();- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;- const [tokenField, locationField] = [...host.querySelectorAll("input")];- await act(async () => {- setter.call(tokenField, "pit-secret");- tokenField!.dispatchEvent(new Event("input", { bubbles: true }));- setter.call(locationField, "loc_x");- locationField!.dispatchEvent(new Event("input", { bubbles: true }));- });- const refusal = "This token does not belong to that location (403): it was created in another sub-account or at the agency level. Create the Private Integration inside the sub-account whose location ID you entered.";- fixture.api.mockImplementationOnce(async () => { throw new Error(refusal); });- await act(async () => host.querySelector<HTMLButtonElement>('form[data-highlevel-token-form] button[type="submit"]')!.click());- await settle();- expect(host.querySelector('[role="alert"]')?.textContent).toBe(refusal);- // The field keeps what was typed so it can be corrected, masked; nothing else in the card repeats it.- expect(tokenField!.type).toBe("password");- expect(text()).not.toContain("pit-secret");- expect(button("Connect HighLevel")).toBeTruthy();- });-});--describe("Disconnecting HighLevel", () => {- it("asks first, then removes the connection and returns to Connect", async () => {- await mount(connectedStatus);- await act(async () => button("HighLevel options")!.click());- await settle();- const item = document.querySelector<HTMLButtonElement>('[role="menuitem"][data-menu-key="disconnect"]')!;- expect(item.textContent).toContain("Disconnect");- await act(async () => item.click());- await settle();- expect(window.confirm).toHaveBeenCalledWith(expect.stringContaining("Disconnect HighLevel?"));- expect(server.calls).toContainEqual(["DELETE", "/api/highlevel", undefined]);- expect(button("Connect HighLevel")).toBeTruthy();- expect(onConnection).toHaveBeenLastCalledWith(false);- });-- it("does nothing when the person declines", async () => {- await mount(connectedStatus);- vi.mocked(window.confirm).mockReturnValueOnce(false);- await act(async () => button("HighLevel options")!.click());- await settle();- await act(async () => document.querySelector<HTMLButtonElement>('[role="menuitem"][data-menu-key="disconnect"]')!.click());- await settle();- expect(server.calls.some(([method, path]) => method === "DELETE" && path === "/api/highlevel")).toBe(false);- expect(text()).toContain("Connected · Example Profiles");- });-});diff --git a/src/components/HighLevelCard.tsx b/src/components/HighLevelCard.tsxdeleted file mode 100644index 90917d7079..0000000000--- a/src/components/HighLevelCard.tsx+++ /dev/null@@ -1,309 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";-import { Check, Loader2, MoreHorizontal } from "lucide-react";--import { api } from "@/state/store";-import { t } from "@/lib/i18n";-import { reserveConnectionPage } from "@/lib/connector-oauth";-import { openExternalLink } from "@/lib/app-links";-import {- HIGHLEVEL_API,- cancelHighLevelSignIn,- isHighLevelStatus,- runHighLevelSignIn,- watchHighLevelSignIn,- type HighLevelFlow,- type HighLevelSignInResult,- type HighLevelStatus,-} from "@/lib/highlevel-sign-in";-import { forgetHighLevelStatus, rememberHighLevelStatus } from "@/lib/highlevel-status";-import { SidebarPopoverMenu } from "./SidebarPopoverMenu";--const pill = "inline-flex h-7 min-w-[64px] shrink-0 items-center justify-center gap-2 rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink transition-colors hover:bg-raised-hover disabled:opacity-40";-const field = "h-8 w-full min-w-0 rounded-lg bg-inset px-2.5 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none focus:ring-1 focus:ring-accent/50";--export function HighLevelIcon() {- return (- <svg viewBox="0 0 40 40" className="size-10 shrink-0 rounded-[10px]" aria-hidden="true">- <rect width="40" height="40" rx="10" fill="#1b5e9b" />- <path d="M11 11h4.5v7h9v-7H29v18h-4.5v-7h-9v7H11z" fill="#fff" />- </svg>- );-}--/** The native HighLevel card in Connected apps: one connection per installation, set up by signing in. */-export function HighLevelCard({ refreshKey = 0, onConnection }: {- refreshKey?: number;- /** true once connected, false otherwise, null until the server has answered */- onConnection?: (connected: boolean | null) => void;-}) {- const [status, setStatus] = useState<HighLevelStatus | null>(null);- const [loadFailed, setLoadFailed] = useState(false);- const [busy, setBusy] = useState<"connect" | "token" | "disconnect" | null>(null);- const [flow, setFlow] = useState<HighLevelFlow | null>(null);- const [error, setError] = useState<string | null>(null);- const [tokenMode, setTokenMode] = useState(false);- const [token, setToken] = useState("");- const [locationId, setLocationId] = useState("");- const mounted = useRef(true);- const watching = useRef<AbortController | null>(null);-- const load = useCallback(async (): Promise<HighLevelStatus | null> => {- try {- const response = await api(HIGHLEVEL_API);- if (!mounted.current) return null;- if (!isHighLevelStatus(response)) throw new Error(t("highlevel.failed"));- rememberHighLevelStatus(response);- setStatus(response);- setLoadFailed(false);- return response;- } catch {- if (mounted.current) setLoadFailed(true);- return null;- }- }, []);-- const finish = useCallback(async (result: HighLevelSignInResult) => {- if (!mounted.current) return;- if (result.phase === "failed") setError(result.message || t("highlevel.failed"));- else if (result.phase === "expired") setError(t("highlevel.expired"));- await load();- }, [load]);-- /** Follows a flow the server already has (after a reload, or started elsewhere) without opening anything. */- const follow = useCallback((current: HighLevelFlow) => {- if (watching.current) return;- const controller = new AbortController();- watching.current = controller;- setFlow(current);- void watchHighLevelSignIn(current, { api, open: openExternalLink, signal: controller.signal })- .then(finish)- .finally(() => {- if (watching.current === controller) watching.current = null;- if (mounted.current) setFlow(null);- });- }, [finish]);-- useEffect(() => {- mounted.current = true;- void load().then((loaded) => {- if (loaded?.state === "connecting" && loaded.flow && mounted.current) follow(loaded.flow);- });- return () => {- mounted.current = false;- watching.current?.abort();- watching.current = null;- };- }, [load, follow, refreshKey]);-- useEffect(() => {- onConnection?.(status ? status.state === "connected" : null);- }, [status, onConnection]);-- const connect = async () => {- if (busy || watching.current) return;- // Reserve the tab during the click, before the request consumes the browser's user activation.- const launch = reserveConnectionPage();- const controller = new AbortController();- watching.current = controller;- setBusy("connect");- setError(null);- try {- const result = await runHighLevelSignIn({- api,- signal: controller.signal,- onStarted: (started) => {- if (!mounted.current) return;- setFlow(started);- setBusy(null);- },- open: async (url) => {- const opened = await launch.open(url);- launch.cancel();- if (!opened && mounted.current && !controller.signal.aborted) setError(t("connectors.popupBlockedContinue"));- return opened;- },- });- await finish(result);- } catch (cause) {- if (mounted.current) setError(cause instanceof Error ? cause.message : String(cause));- } finally {- launch.cancel();- if (watching.current === controller) watching.current = null;- if (mounted.current) {- setFlow(null);- setBusy(null);- }- }- };-- const cancel = () => {- const controller = watching.current;- if (controller) {- controller.abort();- return;- }- // A flow the server reported but nobody here is following (its watcher ended): tell the server directly.- if (flow) void cancelHighLevelSignIn(flow.flowId, api).then(() => load());- };-- const connectWithToken = async () => {- if (busy) return;- const trimmedToken = token.trim();- const trimmedLocation = locationId.trim();- if (!trimmedToken || !trimmedLocation) {- setError(t("highlevel.tokenIncomplete"));- return;- }- setBusy("token");- setError(null);- try {- await api(`${HIGHLEVEL_API}/token`, { method: "POST", body: JSON.stringify({ token: trimmedToken, locationId: trimmedLocation }) });- if (!mounted.current) return;- setToken("");- setLocationId("");- setTokenMode(false);- await load();- } catch (cause) {- if (mounted.current) setError(cause instanceof Error ? cause.message : String(cause));- } finally {- if (mounted.current) setBusy(null);- }- };-- const disconnect = async () => {- if (busy) return;- if (!window.confirm(t("highlevel.disconnectConfirm"))) return;- setBusy("disconnect");- setError(null);- try {- await api(HIGHLEVEL_API, { method: "DELETE" });- forgetHighLevelStatus();- await load();- } catch (cause) {- if (mounted.current) setError(cause instanceof Error ? cause.message : String(cause));- } finally {- if (mounted.current) setBusy(null);- }- };-- if (status?.state === "unavailable") return null;-- const state = status?.state ?? null;- const connecting = flow !== null || busy === "connect" || state === "connecting";- const connected = state === "connected";- const needsSignIn = state === "needs-sign-in";- const description = connected && status?.location?.name- ? t("highlevel.connectedTo", { name: status.location.name })- : connected- ? t("apps.connected")- : needsSignIn- ? t("connectors.signedOut")- : t("highlevel.description");- const menu = (connected || needsSignIn) && (- <SidebarPopoverMenu- placement="below"- ariaLabel={t("highlevel.menu")}- triggerClassName="shrink-0"- items={[{ key: "disconnect", label: t("connectors.disconnect"), disabled: busy !== null, onSelect: () => void disconnect() }]}- renderTrigger={() => (- <span className="inline-flex size-7 items-center justify-center rounded-full bg-control/80 text-ink hover:bg-raised-hover">- {busy === "disconnect" ? <Loader2 size={14} className="animate-spin" /> : <MoreHorizontal size={15} aria-hidden="true" />}- </span>- )}- />- );-- return (- <div data-app-tile="highlevel" data-highlevel-state={state ?? "loading"} className="flex min-w-0 flex-col rounded-xl px-2 py-2 transition-colors hover:bg-raised/40">- <div className="flex items-center gap-3">- <HighLevelIcon />- <div className="min-w-0 flex-1">- <div className="flex min-w-0 items-center gap-1.5">- <span className="truncate text-[14px] font-semibold leading-5 text-ink">{t("highlevel.title")}</span>- {connected && <Check size={13} strokeWidth={2.5} className="shrink-0 text-success" aria-label={t("apps.connected")} />}- </div>- <p className="truncate text-[13px] leading-[18px] text-ink-secondary" title={description}>{description}</p>- </div>- {connecting ? (- <button type="button" onClick={cancel} className={pill}>{t("mcp.auth.cancel")}</button>- ) : status === null ? (- loadFailed- ? <button type="button" onClick={() => void load()} className={pill}>{t("connectors.action.retry")}</button>- : <button type="button" disabled className={pill} aria-label={t("common.checking")}><Loader2 size={14} className="animate-spin" /></button>- ) : connected ? (- menu- ) : (- <div className="flex shrink-0 items-center gap-1.5">- <button- type="button"- aria-label={t(needsSignIn ? "highlevel.reconnect" : "highlevel.connect")}- disabled={busy !== null}- onClick={() => void connect()}- className={pill}- >- {t(needsSignIn ? "connectors.action.reconnect" : "connectors.action.connect")}- </button>- {menu}- </div>- )}- </div>- <div className="ps-[52px]">- {connecting && (- <p role="status" className="mt-1.5 flex items-center gap-2 text-[12px] text-ink-secondary">- <Loader2 size={12} className="shrink-0 animate-spin" aria-hidden="true" />- <span>{t("highlevel.finishInBrowser")}</span>- {flow && (- <button type="button" onClick={() => void openExternalLink(flow.authorizationUrl).catch(() => setError(t("mcp.auth.openFailed")))} className="text-accent-text underline underline-offset-2">- {t("mcp.auth.openAgain")}- </button>- )}- </p>- )}- {error && <p role="alert" className="mt-1.5 text-[12px] text-danger">{error}</p>}- {!connecting && status !== null && !connected && !needsSignIn && (- tokenMode ? (- <form- data-highlevel-token-form- className="mt-2 flex flex-col gap-2"- onSubmit={(event) => { event.preventDefault(); void connectWithToken(); }}- >- <input- type="password"- autoComplete="off"- spellCheck={false}- aria-label={t("highlevel.tokenField")}- placeholder={t("highlevel.tokenField")}- value={token}- onChange={(event) => setToken(event.target.value)}- className={field}- />- <input- type="text"- autoComplete="off"- spellCheck={false}- aria-label={t("highlevel.locationField")}- placeholder={t("highlevel.locationField")}- value={locationId}- onChange={(event) => setLocationId(event.target.value)}- className={field}- />- <p className="text-[12px] leading-relaxed text-ink-secondary">{t("highlevel.tokenHelp")}</p>- <div className="flex items-center gap-2">- <button type="submit" disabled={busy !== null} className={pill}>- {busy === "token" ? <Loader2 size={14} className="animate-spin" /> : t("connectors.action.connect")}- </button>- <button type="button" onClick={() => { setTokenMode(false); setError(null); }} className="text-[12px] text-ink-secondary underline underline-offset-2 hover:text-ink">- {t("highlevel.useSignIn")}- </button>- </div>- </form>- ) : (- <button type="button" onClick={() => { setTokenMode(true); setError(null); }} className="mt-1.5 inline-block text-[12px] text-accent-text underline underline-offset-2">- {t("highlevel.useToken")}- </button>- )- )}- </div>- </div>- );-}diff --git a/src/components/PluginsPanel.member.test.ts b/src/components/PluginsPanel.member.test.tsindex e3591ce568..0e3ad3ff51 100644--- a/src/components/PluginsPanel.member.test.ts+++ b/src/components/PluginsPanel.member.test.ts@@ -9,7 +9,6 @@ vi.mock("@/state/store", () => ({useStore: () => ({ state: { pluginsSurface: "apps", bots: [], instances: [] }, dispatch: vi.fn() }),}));vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));-vi.mock("./HighLevelCard", () => ({ HighLevelCard: () => null }));vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));const { PluginsPanel } = await import("./PluginsPanel");diff --git a/src/components/PluginsPanel.navigation.test.ts b/src/components/PluginsPanel.navigation.test.tsindex 575731afa5..c3566b34e4 100644--- a/src/components/PluginsPanel.navigation.test.ts+++ b/src/components/PluginsPanel.navigation.test.ts@@ -50,10 +50,6 @@ vi.mock("./McpServersPanel", async () => {});vi.mock("@/lib/analytics", () => ({ track: fixture.track }));vi.mock("./Avatar", () => ({ BotAvatar: ({ bot }: { bot: Bot }) => createElement("span", { "data-avatar": bot.id }) }));-// The native HighLevel card has its own DOM suite; here it is a marker so tile counts stay the catalog's.-vi.mock("./HighLevelCard", () => ({- HighLevelCard: () => createElement("div", { "data-highlevel-card": true }, "Connect HighLevel"),-}));vi.mock("./XCard", () => ({X_CARD_SEARCH: "x twitter treg tweets posts",XCard: () => createElement("div", { "data-x-card": true }, "X (Twitter)"),@@ -73,11 +69,10 @@ const CARDS = 0;const CONFIGURED = 3;const STATUS = 6;const PHASE = 13;-const HIGHLEVEL_CONNECTED = 21;-const X_CONNECTED = 22;+const X_CONNECTED = 21;const CATEGORY = 20;-const POSTIZ_CONNECTED = 23;-const EMAIL_CONNECTED = 24;+const POSTIZ_CONNECTED = 22;+const EMAIL_CONNECTED = 23;const MODE = 4;const SEARCH = 15;const HOSTED_CONNECTED = 18;@@ -177,28 +172,6 @@ describe("Apps pop-up", () => {const html = render().html;expect(html).toContain(`Connected: ${new Intl.ListFormat("en", { style: "long", type: "conjunction" }).format(HOSTED_MCP_APPS.map((app) => app.label))}.`);});- it("shows the native HighLevel card in the grid and counts it once connected", () => {- const { html, nodes: tree } = render();- const grid = tree.find((node) => node.props["data-apps-grid"] !== undefined)!;- expect(nodes(grid).some((node) => node.props.onConnection !== undefined && node.props.refreshKey !== undefined)).toBe(true);- expect(html).toContain("Connect HighLevel");- expect(html).toContain("1 connected");- fixture.overrides.set(HIGHLEVEL_CONNECTED, true);- expect(render().html).toContain("2 connected");- });- it("hides HighLevel from the Connected tab until it is connected, and from a search that does not name it", () => {- fixture.overrides.set(16, "connected");- fixture.overrides.set(HIGHLEVEL_CONNECTED, false);- const wrapper = (tree: Node[]) => tree.find((node) => node.props["data-native-card"] === "highlevel")!;- expect(wrapper(render().nodes).props.className).toBe("hidden");- fixture.overrides.set(HIGHLEVEL_CONNECTED, true);- expect(wrapper(render().nodes).props.className).toBe("contents");- fixture.overrides.set(16, "marketplace");- fixture.overrides.set(15, "growably");- expect(wrapper(render().nodes).props.className).toBe("contents");- fixture.overrides.set(15, "zendesk");- expect(wrapper(render().nodes).props.className).toBe("hidden");- });it("shows the Postiz card in the grid and under Social, with a Social pill, and counts it once connected", () => {const wrapper = (tree: Node[]) => tree.find((node) => node.props["data-native-card"] === "postiz")!;const { html, nodes: tree } = render();diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsxindex 5583c750c4..1bc570486c 100644--- a/src/components/PluginsPanel.tsx+++ b/src/components/PluginsPanel.tsx@@ -30,7 +30,6 @@ import { SidebarPopoverMenu } from "./SidebarPopoverMenu";import { appCategoryLabel, CATEGORY_SECTION_SIZE, catalogSections, connectorDescription, inCategory, rankCategories } from "@/lib/app-catalog";import { McpServersPanel } from "./McpServersPanel";import { HOSTED_MCP_APPS, type HostedApp, type HostedConnections } from "@/lib/hosted-mcp-apps";-import { HighLevelCard } from "./HighLevelCard";import { EmailCard } from "./EmailCard";import { PostizCard } from "./PostizCard";import { POSTIZ_CATALOG_CARD, POSTIZ_SEARCH } from "@/lib/postiz";@@ -154,7 +153,6 @@ export function PluginsPanel() {const [cardsRefresh, setCardsRefresh] = useState(0);const [category, setCategory] = useState<string | null>(null);// Appended after the older state so tests that seed state by call order keep their indices.- const [highLevelConnected, setHighLevelConnected] = useState<boolean | null>(null);const [xConnected, setXConnected] = useState<boolean | null>(null);const [postizConnected, setPostizConnected] = useState<boolean | null>(null);const [emailConnected, setEmailConnected] = useState<boolean | null>(null);@@ -404,8 +402,6 @@ export function PluginsPanel() {const isConnected = (slug: string) => Boolean(status[slug]?.connected || status[slug]?.accounts?.length);const filter: AppsFilter = surface === "mcp" ? "mcp" : tab === "connected" ? "connected" : "all";const shownHosted = new Set(HOSTED_MCP_APPS.filter((app) => hostedShown(app, search, filter, hostedConnected)).map((app) => app.id));- const highLevelMatches = !search || `highlevel high level growably crm ${t("highlevel.description")}`.toLowerCase().includes(search.toLowerCase().trim());- const showHighLevel = highLevelMatches && (filter === "all" || (filter === "connected" && highLevelConnected !== false));const showEmail = (!search || `email mail imap smtp mailbox ${t("email.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (filter === "all" || (filter === "connected" && emailConnected !== false));const showX = (!search || `${X_CARD_SEARCH} ${t("apps.x.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (filter === "all" || (filter === "connected" && xConnected !== false));const showPostiz = (!search || `${POSTIZ_SEARCH} ${t("postiz.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (filter === "all" || (filter === "connected" && postizConnected !== false));@@ -414,7 +410,7 @@ export function PluginsPanel() {.sort((a, b) => Number(isConnected(b.card.slug)) - Number(isConnected(a.card.slug)) || a.index - b.index).map(({ card }) => card);const connectedHosted = HOSTED_MCP_APPS.filter((app) => hostedConnected?.[app.id]);- const connectedCount = Object.values(status).filter(hasActiveConnection).length + connectedHosted.length + Number(highLevelConnected === true) + Number(emailConnected === true) + Number(xConnected === true) + Number(postizConnected === true);+ const connectedCount = Object.values(status).filter(hasActiveConnection).length + connectedHosted.length + Number(emailConnected === true) + Number(xConnected === true) + Number(postizConnected === true);const connectedEmptyCopy = connectedInventoryCopy(inventoryPhase);const close = () => dispatch({ type: "togglePlugins", open: false });const setupNotice = connectorSetupNotice({ configured, stale, setup, remoteClient });@@ -436,7 +432,7 @@ export function PluginsPanel() {const categoryInMore = category !== null && moreCategories.includes(category);const inCategoryView = filter === "all" && category !== null;const postizHere = showPostiz && (!inCategoryView || inCategory(POSTIZ_CATALOG_CARD, category));- const nativeCardsShown = (!inCategoryView && (shownHosted.size > 0 || showHighLevel || showEmail || showX)) || postizHere;+ const nativeCardsShown = (!inCategoryView && (shownHosted.size > 0 || showEmail || showX)) || postizHere;const categoryCards = inCategoryView ? visible.filter((card) => inCategory(card, category)) : visible;const sectioned = filter === "all" && !search && category === null;const sections = sectioned ? catalogSections(visible, isConnected, ranked.inline) : [];@@ -733,9 +729,6 @@ export function PluginsPanel() {<McpServersPanel hostedCards={{ shown: (id) => !inCategoryView && shownHosted.has(id), onConnections: setHostedConnected }} refreshKey={cardsRefresh} /><div data-native-card="x" className={showX && !inCategoryView ? "contents" : "hidden"}><XCard refreshKey={cardsRefresh} onConnection={setXConnected} /></div><div data-native-card="email" className={showEmail && !inCategoryView ? "contents" : "hidden"}><EmailCard refreshKey={cardsRefresh} onConnection={setEmailConnected} /></div>- <div data-native-card="highlevel" className={showHighLevel && !inCategoryView ? "contents" : "hidden"}>- <HighLevelCard refreshKey={cardsRefresh} onConnection={setHighLevelConnected} />- </div><div data-native-card="postiz" className={postizHere ? "contents" : "hidden"}><PostizCard refreshKey={cardsRefresh} onConnection={setPostizConnected} /></div>{allShown.map((card) => renderTile(card))}</AppsSection>diff --git a/src/components/bot-settings/AccessSection.test.ts b/src/components/bot-settings/AccessSection.test.tsindex 6c591ad8f2..b31bf47730 100644--- a/src/components/bot-settings/AccessSection.test.ts+++ b/src/components/bot-settings/AccessSection.test.ts@@ -16,7 +16,7 @@ vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({ state: { ...original.initialState, config: fixture.config ?? original.initialState.config }, dispatch: fixture.dispatch }) };});-// The connected-apps list (Composio accounts plus the native HighLevel connection) is seeded per test.+// The connected-apps list (Composio accounts plus the native Email connection) is seeded per test.vi.mock("./useBotApps", async (importOriginal) => ({...await importOriginal<typeof import("./useBotApps")>(),useBotApps: () => fixture.apps,@@ -334,21 +334,12 @@ describe("AccessSection Record browser steps", () => {describe("AccessSection per-app scopes", () => {const app = (slug: string, label: string) => ({ slug, label, blurb: "", card: { logo: null, domain: null, label }, scope: "write" as const });- it("lists HighLevel by name next to the Composio apps once the server reports it connected", () => {- fixture.apps = { phase: "ready", connectedSlugs: ["gmail", "highlevel"], apps: [app("gmail", "Gmail"), app("highlevel", "HighLevel")] };+ it("lists Email by name next to the Composio apps once the server reports a mailbox connected", () => {+ fixture.apps = { phase: "ready", connectedSlugs: ["email", "gmail"], apps: [app("email", "Email"), app("gmail", "Gmail")] };const html = render(makeBot({ connectorScopes: { apps: { gmail: "write" } } }));- expect(html).toContain('aria-label="highlevel access"');- expect(html).toMatch(/<span class="min-w-0 text-\[13px\] text-ink">HighLevel</);+ expect(html).toContain('aria-label="email access"');+ expect(html).toMatch(/<span class="min-w-0 text-\[13px\] text-ink">Email</);expect(html).not.toContain("not connected");- // Tool-by-tool grants are Composio's list; HighLevel is scoped by read/write only.- expect([...html.matchAll(/truncate font-mono text-\[13px\] text-ink">([^<]*)</g)].map((match) => match[1])).toEqual(["gmail"]);- });-- it("leaves HighLevel out while it is not connected", () => {- fixture.apps = { phase: "ready", connectedSlugs: ["gmail"], apps: [app("gmail", "Gmail")] };- const html = render(makeBot({ connectorScopes: { apps: { gmail: "write" } } }));- expect(html).not.toContain("HighLevel");- expect(html).not.toContain("highlevel");});it("shows no scope rows until the account list is known", () => {diff --git a/src/components/bot-settings/AccessSection.tsx b/src/components/bot-settings/AccessSection.tsxindex b5af1b1ace..8de9adee86 100644--- a/src/components/bot-settings/AccessSection.tsx+++ b/src/components/bot-settings/AccessSection.tsx@@ -21,7 +21,6 @@ import { BotApiCard } from "./BotApiCard";import { ToolBudgetLine } from "./ToolBudgetLine";import { useCloudPlan } from "../ProIntroduction";import { xResearchAction } from "@/lib/cloud-plan";-import { HIGHLEVEL_SLUG } from "@/lib/highlevel-sign-in";import { useBotApps } from "./useBotApps";import {classifyConnectorTool,@@ -663,7 +662,7 @@ export function AccessSection({const worksOn = placeViewFor(placeFacts({bot, place: bot.computer ?? "auto", seat: placeSeat, config: state.config, instances: state.instances,}));- // The same list the Vault tab shows: Composio's connected accounts plus the native HighLevel connection.+ // The same list the Vault tab shows: Composio's connected accounts plus the native Email connection.const apps = useBotApps(bot);const inventoryReady = apps.phase === "ready";const connectedSlugs = apps.connectedSlugs;@@ -732,8 +731,7 @@ export function AccessSection({{connectedAppsEnabled && inventoryReady && (<>{!draft && <ConnectorScopesControl connectedSlugs={connectedSlugs} labels={appLabels} scopes={bot.connectorScopes} onChange={(connectorScopes) => patch({ connectorScopes })} />}- {/* Tool-level grants list Composio's tools; HighLevel's tools are scoped by read/write above. */}- <ConnectorToolsGrants bot={bot} patch={patch} slugs={connectedSlugs.filter((slug) => slug !== HIGHLEVEL_SLUG)} />+ <ConnectorToolsGrants bot={bot} patch={patch} slugs={connectedSlugs} /></>)}{connectedAppsEnabled && connectedAppsConfigured && (diff --git a/src/components/bot-settings/useBotApps.test.ts b/src/components/bot-settings/useBotApps.test.tsindex ba966365e6..025b498367 100644--- a/src/components/bot-settings/useBotApps.test.ts+++ b/src/components/bot-settings/useBotApps.test.ts@@ -1,5 +1,6 @@import { afterAll, describe, expect, it, vi } from "vitest";+import type { EmailStatus } from "../../../shared/email";import type { ToolkitCard } from "../PluginsPanel";// PluginsPanel reads `window` when it loads; the src suite runs without one.@@ -10,8 +11,8 @@ vi.hoisted(() => {afterAll(() => vi.unstubAllGlobals());const { botAppsFrom } = await import("./useBotApps");-const highlevel = (state: "connected" | "signed-out" | "needs-sign-in" | "connecting" | "unavailable") =>- ({ state, ...(state === "connected" ? { kind: "oauth" as const, location: { id: "loc_1", name: "Example Profiles" } } : {}) });+const email = (state: "connected" | "signed-out" | "unavailable") =>+ ({ state, accounts: state === "connected" ? [{ address: "[email protected]" }] : [] }) as unknown as EmailStatus;const card = (slug: string, label: string): ToolkitCard => ({ slug, label, blurb: `${label} things`, logo: `https://logo.test/${slug}.png`, domain: `${slug}.com` });const cards = new Map([card("gmail", "Gmail"), card("slack", "Slack")].map((entry) => [entry.slug, entry]));@@ -53,27 +54,25 @@ describe("the connected apps as one bot sees them", () => {expect(off.map((app) => app.scope)).toEqual([null, null]);});- it("lists HighLevel, by name and in order, only while the server reports it connected", () => {- const connected = botAppsFrom({}, inventory({ slack: true, gmail: true }), cards, highlevel("connected"));- expect(connected.connectedSlugs).toEqual(["gmail", "highlevel", "slack"]);- const app = connected.apps.find((entry) => entry.slug === "highlevel")!;- expect(app).toMatchObject({ label: "HighLevel", blurb: "Also Growably and other HighLevel-based CRMs.", scope: "write", card: { logo: null, domain: "gohighlevel.com", label: "HighLevel" } });- for (const state of ["signed-out", "needs-sign-in", "connecting", "unavailable"] as const) {- expect(botAppsFrom({}, inventory({ gmail: true }), cards, highlevel(state)).connectedSlugs, state).toEqual(["gmail"]);+ it("lists Email, by name and in order, only while the server reports a mailbox connected", () => {+ const connected = botAppsFrom({}, inventory({ slack: true, gmail: true }), cards, email("connected"));+ expect(connected.connectedSlugs).toEqual(["email", "gmail", "slack"]);+ const app = connected.apps.find((entry) => entry.slug === "email")!;+ expect(app).toMatchObject({ label: "Email", blurb: "Read and send mail on any mail host, with your address and password.", scope: "write", card: { logo: null, domain: null, label: "Email" } });+ for (const state of ["signed-out", "unavailable"] as const) {+ expect(botAppsFrom({}, inventory({ gmail: true }), cards, email(state)).connectedSlugs, state).toEqual(["gmail"]);}expect(botAppsFrom({}, inventory({ gmail: true }), cards, null).connectedSlugs).toEqual(["gmail"]);- expect(botAppsFrom({}, inventory({}), cards, highlevel("connected")).apps.map((entry) => entry.slug)).toEqual(["highlevel"]);});- it("reads HighLevel's switch from connectorScopes.apps.highlevel like any other app", () => {+ it("reads Email's switch from connectorScopes.apps.email like any other app", () => {const connected = inventory({ gmail: true });- expect(botAppsFrom({ connectorScopes: { apps: { highlevel: "read" } } }, connected, cards, highlevel("connected")).apps.map((app) => [app.slug, app.scope]))- .toEqual([["gmail", null], ["highlevel", "read"]]);- expect(botAppsFrom({ connectorScopes: { apps: { gmail: "write" } } }, connected, cards, highlevel("connected")).apps.map((app) => app.scope)).toEqual(["write", null]);- expect(botAppsFrom({ composio: false }, connected, cards, highlevel("connected")).apps.map((app) => app.scope)).toEqual([null, null]);+ expect(botAppsFrom({ connectorScopes: { apps: { email: "read" } } }, connected, cards, email("connected")).apps.map((app) => [app.slug, app.scope]))+ .toEqual([["email", "read"], ["gmail", null]]);+ expect(botAppsFrom({ composio: false }, connected, cards, email("connected")).apps.map((app) => app.scope)).toEqual([null, null]);});- it("still says it does not know when the account store is unreadable, even with HighLevel connected", () => {- expect(botAppsFrom({}, inventory({}, false), cards, highlevel("connected"))).toEqual({ phase: "unknown", apps: [], connectedSlugs: [] });+ it("still says it does not know when the account store is unreadable, even with a mailbox connected", () => {+ expect(botAppsFrom({}, inventory({}, false), cards, email("connected"))).toEqual({ phase: "unknown", apps: [], connectedSlugs: [] });});});diff --git a/src/components/bot-settings/useBotApps.ts b/src/components/bot-settings/useBotApps.tsindex d915f04981..d7a5d0ec74 100644--- a/src/components/bot-settings/useBotApps.ts+++ b/src/components/bot-settings/useBotApps.ts@@ -1,8 +1,6 @@import { useEffect, useState } from "react";import { botAppScope } from "@/lib/bot-app-access";-import { HIGHLEVEL_SLUG, type HighLevelStatus } from "@/lib/highlevel-sign-in";-import { highLevelConnected, preloadHighLevelStatus } from "@/lib/highlevel-status";import { t } from "@/lib/i18n";import { api, type Bot } from "@/state/store";import type { ConnectorScope } from "../../../shared/connector-scopes";@@ -39,12 +37,7 @@ function slugLabel(slug: string): string {return slug.charAt(0).toUpperCase() + slug.slice(1).replace(/[_-]+/g, " ");}-/** HighLevel is connected natively, not through the Composio inventory, so it brings its own card. */-export function highLevelAppCard(): Pick<ToolkitCard, "logo" | "domain" | "label"> & { blurb: string } {- return { logo: null, domain: "gohighlevel.com", label: t("highlevel.title"), blurb: t("highlevel.description") };-}--/** Email is connected natively too. */+/** Email is connected natively, not through the Composio inventory, so it brings its own card. */export function emailAppCard(): Pick<ToolkitCard, "logo" | "domain" | "label"> & { blurb: string } {return { logo: null, domain: null, label: t("email.title"), blurb: t("email.description") };}@@ -53,7 +46,6 @@ export function botAppsFrom(bot: Pick<Bot, "composio" | "connectorScopes" | "connectorTools">,inventory: ConnectorInventory | null,cards: ReadonlyMap<string, ToolkitCard>,- highlevel: HighLevelStatus | null = null,email: EmailStatus | null = null,): BotApps {if (!inventory) return { phase: "loading", apps: [], connectedSlugs: [] };@@ -61,14 +53,9 @@ export function botAppsFrom(const connectedSlugs = Object.entries(inventory.services).filter(([, status]) => status.connected).map(([slug]) => slug);- if (highLevelConnected(highlevel) && !connectedSlugs.includes(HIGHLEVEL_SLUG)) connectedSlugs.push(HIGHLEVEL_SLUG);if (email?.state === "connected" && !connectedSlugs.includes(EMAIL_SLUG)) connectedSlugs.push(EMAIL_SLUG);connectedSlugs.sort((a, b) => a.localeCompare(b));const apps = connectedSlugs.map((slug) => {- if (slug === HIGHLEVEL_SLUG && highLevelConnected(highlevel)) {- const { blurb, ...card } = highLevelAppCard();- return { slug, label: card.label, blurb, card, scope: botAppScope(bot, slug) };- }if (slug === EMAIL_SLUG && email?.state === "connected") {const { blurb, ...card } = emailAppCard();return { slug, label: card.label, blurb, card, scope: botAppScope(bot, slug) };@@ -89,7 +76,6 @@ export function botAppsFrom(export function useBotApps(bot: Bot): BotApps {const [inventory, setInventory] = useState<ConnectorInventory | null>(null);const [cards, setCards] = useState<ReadonlyMap<string, ToolkitCard>>(() => new Map());- const [highlevel, setHighlevel] = useState<HighLevelStatus | null>(null);const [email, setEmail] = useState<EmailStatus | null>(null);useEffect(() => {@@ -100,14 +86,11 @@ export function useBotApps(bot: Bot): BotApps {void loadAppCards().then((result) => {if (!cancelled) setCards(result);});- void preloadHighLevelStatus().then((result) => {- if (!cancelled) setHighlevel(result);- });void api("/api/email").then((result: EmailStatus) => { if (!cancelled) setEmail(result); }).catch(() => {});return () => {cancelled = true;};}, []);- return botAppsFrom(bot, inventory, cards, highlevel, email);+ return botAppsFrom(bot, inventory, cards, email);}diff --git a/src/components/bot-settings/useBotSettingsDerived.test.ts b/src/components/bot-settings/useBotSettingsDerived.test.tsindex cefe9f2842..4e19e7085a 100644--- a/src/components/bot-settings/useBotSettingsDerived.test.ts+++ b/src/components/bot-settings/useBotSettingsDerived.test.ts@@ -3,12 +3,10 @@ import { renderToStaticMarkup } from "react-dom/server";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Bot, InstanceInfo } from "@/state/store";-import type { HighLevelStatus } from "@/lib/highlevel-sign-in";const fixture = vi.hoisted(() => ({instances: [] as unknown[],config: null as unknown,- highlevel: null as HighLevelStatus | null,}));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();@@ -18,10 +16,6 @@ vi.mock("@/state/store", async (importOriginal) => {};});vi.mock("../DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({ capabilities: { host: { packaged: false } } }) }));-vi.mock("@/lib/highlevel-status", async (importOriginal) => ({- ...await importOriginal<typeof import("@/lib/highlevel-status")>(),- useHighLevelStatus: () => fixture.highlevel,-}));const { useBotSettingsDerived } = await import("./useBotSettingsDerived");@@ -35,14 +29,14 @@ function derive() {return derived;}-beforeEach(() => { vi.stubGlobal("window", {}); fixture.instances = []; fixture.config = null; fixture.highlevel = null; });+beforeEach(() => { vi.stubGlobal("window", {}); fixture.instances = []; fixture.config = null; });afterEach(() => vi.unstubAllGlobals());describe("connected apps in bot settings", () => {- it("lets the engine use connected apps through either Composio's MCP or the native HighLevel one", () => {+ it("lets the engine use connected apps through either Composio's MCP or the native Email one", () => {fixture.instances = engine({ composioMcp: true });expect(derive().canUseConnectedApps).toBe(true);- fixture.instances = engine({ highlevelMcp: true });+ fixture.instances = engine({ emailMcp: true });expect(derive().canUseConnectedApps).toBe(true);fixture.instances = engine({ dataMcp: true });expect(derive().canUseConnectedApps).toBe(false);@@ -50,11 +44,7 @@ describe("connected apps in bot settings", () => {expect(derive().canUseConnectedApps).toBe(false);});- it("counts a connected HighLevel as configured connected apps even without the Composio service", () => {- expect(derive().connectedAppsConfigured).toBe(false);- fixture.highlevel = { state: "connected", location: { id: "loc_1", name: "Example Profiles" } };- expect(derive().connectedAppsConfigured).toBe(true);- fixture.highlevel = { state: "needs-sign-in" };+ it("counts connected apps as configured once the Composio service is", () => {expect(derive().connectedAppsConfigured).toBe(false);fixture.config = { composio: { configured: true } };expect(derive().connectedAppsConfigured).toBe(true);diff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex 85874316b9..2a5f7bd50e 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -4,7 +4,6 @@ import { stateForBot } from "@/lib/mascot";import { useStore, type Bot } from "@/state/store";import { approvalModeFor } from "../../../shared/approval-mode";import { connectorGrantsState, type ConnectorGrantsState } from "@/lib/connector-grants";-import { highLevelConnected, useHighLevelStatus } from "@/lib/highlevel-status";export type BotPatch = Partial<Pick<@@ -65,11 +64,9 @@ export function useBotSettingsDerived(bot: Bot) {const approvalMode = approvalModeFor(bot);const trustedModesAvailable = Boolean(window.ogb?.approvals && capabilities.host.packaged);const canCoordinate = engine?.capabilities?.agentsMcp === true;- // Connected apps reach a bot through Composio's MCP or the native HighLevel one; either lets the switch work.- const canUseConnectedApps = engine?.capabilities?.composioMcp === true || engine?.capabilities?.highlevelMcp === true;- // A native HighLevel connection counts as a connected app even where the Composio service is not set up (a Cloud home).- const highlevel = useHighLevelStatus();- const connectedAppsConfigured = state.config?.composio?.configured === true || highLevelConnected(highlevel);+ // Connected apps reach a bot through Composio's MCP or the native Email one; either lets the switch work.+ const canUseConnectedApps = engine?.capabilities?.composioMcp === true || engine?.capabilities?.emailMcp === true;+ const connectedAppsConfigured = state.config?.composio?.configured === true;const connectedAppsEnabled = bot.composio !== false;const connectorGrantState: ConnectorGrantsState = connectorGrantsState(bot);const canUseBrowser = engine?.capabilities?.browserMcp === true;diff --git a/src/lib/connect-link.test.ts b/src/lib/connect-link.test.tsindex 5f70812440..e76d5030f0 100644--- a/src/lib/connect-link.test.ts+++ b/src/lib/connect-link.test.ts@@ -4,7 +4,7 @@ import { takeConnectRequest } from "./connect-link";it("a bot's connect link opens the page that connects it and leaves the address clean", () => {expect(takeConnectRequest("https://omb-u-1.fly.dev/?connect=mcp%3Alinear&x=1#top")).toEqual({ rest: "/?x=1#top", surface: "mcp" });- expect(takeConnectRequest("https://omb-u-1.fly.dev/?connect=highlevel")).toEqual({ rest: "/", surface: "apps" });+ expect(takeConnectRequest("https://omb-u-1.fly.dev/?connect=gmail")).toEqual({ rest: "/", surface: "apps" });expect(takeConnectRequest("https://omb-u-1.fly.dev/?connect=javascript:alert(1)")).toEqual({ rest: "/", surface: "apps" });expect(takeConnectRequest("https://omb-u-1.fly.dev/?x=1")).toBeNull();});diff --git a/src/lib/connect-link.ts b/src/lib/connect-link.tsindex 7fe11103d4..224efe1b0d 100644--- a/src/lib/connect-link.ts+++ b/src/lib/connect-link.ts@@ -1,5 +1,5 @@/** A bot on My Cloud links to `/?connect=<id>` for a connection that needs the person there: an MCP server's sign-in- * opens the MCP servers, where its Sign in is; HighLevel opens the apps. The Admin's Team admin pages link a team's+ * opens the MCP servers, where its Sign in is; any other id opens the apps. The Admin's Team admin pages link a team's* admins to `/?connect=mcp`, `keys` (the keys in Settings) or `ai` (the engines in Settings). It only opens the page; it* never signs in by itself. Null for any other address. */export function takeConnectRequest(href: string): ({ rest: string } & ({ surface: "mcp" | "apps" } | { section: "connections" | "engines" })) | null {diff --git a/src/lib/highlevel-sign-in.test.ts b/src/lib/highlevel-sign-in.test.tsdeleted file mode 100644index ed0ce5241b..0000000000--- a/src/lib/highlevel-sign-in.test.ts+++ /dev/null@@ -1,104 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { isHighLevelStatus, runHighLevelSignIn, watchHighLevelSignIn } from "./highlevel-sign-in";--const flow = { flowId: "flow-1", authorizationUrl: "https://marketplace.leadconnectorhq.com/v2/oauth/chooselocation?state=abc", expiresAt: "2026-10-15T12:10:00Z" };--/** A fake server: POST starts the flow, each GET answers the next queued status, DELETE cancels. */-function stubApi(statuses: unknown[], started: unknown = flow) {- const calls: Array<[string, string, string | undefined]> = [];- const api = vi.fn(async (path: string, init?: { method?: string; body?: string }) => {- const method = init?.method ?? "GET";- calls.push([method, path, init?.body]);- if (method === "POST") return started;- if (method === "DELETE") return { ok: true };- const next = statuses.shift();- if (next instanceof Error) throw next;- return next;- });- return { api, calls };-}-const noSleep = async () => {};--describe("runHighLevelSignIn", () => {- it("starts the flow, opens HighLevel's page once, polls until connected", async () => {- const { api, calls } = stubApi([{ phase: "waiting" }, { phase: "waiting" }, { phase: "connected" }]);- const open = vi.fn(async () => true);- const onStarted = vi.fn();- const result = await runHighLevelSignIn({ api, open, sleep: noSleep, onStarted });- expect(result).toEqual({ phase: "connected" });- expect(onStarted).toHaveBeenCalledWith(flow);- expect(open).toHaveBeenCalledTimes(1);- expect(open).toHaveBeenCalledWith(flow.authorizationUrl);- expect(calls).toEqual([- ["POST", "/api/highlevel/sign-in", undefined],- ["GET", "/api/highlevel/sign-in/flow-1", undefined],- ["GET", "/api/highlevel/sign-in/flow-1", undefined],- ["GET", "/api/highlevel/sign-in/flow-1", undefined],- ]);- });-- it("passes the server's failure message through and treats expiry as its own phase", async () => {- const failed = stubApi([{ phase: "failed", message: "HighLevel refused the sign-in." }]);- expect(await runHighLevelSignIn({ api: failed.api, open: async () => true, sleep: noSleep })).toEqual({ phase: "failed", message: "HighLevel refused the sign-in." });- const expired = stubApi([{ phase: "expired" }]);- expect(await runHighLevelSignIn({ api: expired.api, open: async () => true, sleep: noSleep })).toEqual({ phase: "expired" });- });-- it("refuses a sign-in page that is not https and cancels the flow without opening it", async () => {- const { api, calls } = stubApi([], { ...flow, authorizationUrl: "http://evil.example/login" });- const open = vi.fn(async () => true);- const result = await runHighLevelSignIn({ api, open, sleep: noSleep });- expect(result.phase).toBe("failed");- expect(open).not.toHaveBeenCalled();- expect(calls).toContainEqual(["DELETE", "/api/highlevel/sign-in/flow-1", undefined]);- });-- it("cancels on the server when the person cancels, and stops polling", async () => {- const { api, calls } = stubApi([{ phase: "waiting" }, { phase: "waiting" }, { phase: "waiting" }]);- const controller = new AbortController();- let polls = 0;- const sleep = async () => { if (++polls === 2) controller.abort(); };- const result = await runHighLevelSignIn({ api, open: async () => true, sleep, signal: controller.signal });- expect(result).toEqual({ phase: "cancelled" });- expect(calls.filter(([method]) => method === "DELETE")).toEqual([["DELETE", "/api/highlevel/sign-in/flow-1", undefined]]);- expect(calls.filter(([method]) => method === "GET")).toHaveLength(1);- });-- it("does not wait for a slow page opener before honouring a cancel", async () => {- const { api, calls } = stubApi([]);- const controller = new AbortController();- const open = vi.fn(() => new Promise<boolean>(() => {}));- const pending = runHighLevelSignIn({ api, open, sleep: noSleep, signal: controller.signal });- await Promise.resolve();- await Promise.resolve();- controller.abort();- expect(await pending).toEqual({ phase: "cancelled" });- expect(calls.map(([method]) => method)).toEqual(["POST", "DELETE"]);- });-- it("reports a failed poll as a failure with the reason, not as success", async () => {- const { api } = stubApi([{ phase: "waiting" }, new Error("502 Bad Gateway")]);- const result = await runHighLevelSignIn({ api, open: async () => true, sleep: noSleep });- expect(result).toEqual({ phase: "failed", message: "502 Bad Gateway" });- });-});--describe("watchHighLevelSignIn", () => {- it("follows a flow the server already has without opening the page again", async () => {- const { api, calls } = stubApi([{ phase: "connected" }]);- const open = vi.fn(async () => true);- expect(await watchHighLevelSignIn(flow, { api, open, sleep: noSleep })).toEqual({ phase: "connected" });- expect(open).not.toHaveBeenCalled();- expect(calls).toEqual([["GET", "/api/highlevel/sign-in/flow-1", undefined]]);- });-});--describe("isHighLevelStatus", () => {- it("accepts the five states and nothing else", () => {- for (const state of ["unavailable", "signed-out", "connecting", "connected", "needs-sign-in"]) expect(isHighLevelStatus({ state })).toBe(true);- expect(isHighLevelStatus({ state: "ready" })).toBe(false);- expect(isHighLevelStatus(null)).toBe(false);- expect(isHighLevelStatus("connected")).toBe(false);- });-});diff --git a/src/lib/highlevel-sign-in.ts b/src/lib/highlevel-sign-in.tsdeleted file mode 100644index 893ab90344..0000000000--- a/src/lib/highlevel-sign-in.ts+++ /dev/null@@ -1,124 +0,0 @@-import { mcpSignInLink } from "./mcp-sign-in";--/** GET /api/highlevel: one HighLevel connection per installation (desktop and Cloud home alike). */-export type HighLevelState = "unavailable" | "signed-out" | "connecting" | "connected" | "needs-sign-in";--export interface HighLevelFlow {- flowId: string;- authorizationUrl: string;- expiresAt?: string;-}--export interface HighLevelStatus {- state: HighLevelState;- kind?: "oauth" | "token";- location?: { id: string; name: string };- connectedAt?: string;- flow?: HighLevelFlow;- problem?: string;-}--export type HighLevelSignInPhase = "waiting" | "connected" | "failed" | "expired" | "cancelled";--export interface HighLevelSignInResult {- phase: HighLevelSignInPhase;- message?: string;-}--export const HIGHLEVEL_API = "/api/highlevel";-export const HIGHLEVEL_SLUG = "highlevel";-const POLL_MS = 1_500;--interface Deps {- api: (path: string, init?: { method?: string; body?: string }) => Promise<any>;- /** Opens the sign-in page; a false result means the person has to open it by hand. */- open: (url: string) => Promise<boolean | void>;- sleep?: (ms: number) => Promise<void>;- signal?: AbortSignal;- onStarted?: (flow: HighLevelFlow) => void;-}--const CANCELLED: HighLevelSignInResult = { phase: "cancelled" };--export function isHighLevelStatus(value: unknown): value is HighLevelStatus {- if (!value || typeof value !== "object") return false;- const state = (value as { state?: unknown }).state;- return state === "unavailable" || state === "signed-out" || state === "connecting" || state === "connected" || state === "needs-sign-in";-}--function flowOf(value: unknown): HighLevelFlow | null {- if (!value || typeof value !== "object") return null;- const { flowId, authorizationUrl, expiresAt } = value as Record<string, unknown>;- if (typeof flowId !== "string" || !flowId) return null;- const link = mcpSignInLink(typeof authorizationUrl === "string" ? authorizationUrl : null);- if (!link) return null;- return { flowId, authorizationUrl: link, ...(typeof expiresAt === "string" ? { expiresAt } : {}) };-}--function resultOf(value: unknown): HighLevelSignInResult {- const phase = (value as { phase?: unknown } | null)?.phase;- const message = (value as { message?: unknown } | null)?.message;- const known = phase === "waiting" || phase === "connected" || phase === "failed" || phase === "expired";- return { phase: known ? phase : "failed", ...(typeof message === "string" && message ? { message } : {}) };-}--/** Starts a sign-in, opens HighLevel's page and waits for the server to report the outcome. */-export async function runHighLevelSignIn(deps: Deps): Promise<HighLevelSignInResult> {- const started = await deps.api(`${HIGHLEVEL_API}/sign-in`, { method: "POST" });- const flow = flowOf(started);- if (!flow) {- const flowId = (started as { flowId?: unknown } | null)?.flowId;- if (typeof flowId === "string" && flowId) await cancelHighLevelSignIn(flowId, deps.api);- return { phase: "failed" };- }- if (deps.signal?.aborted) {- await cancelHighLevelSignIn(flow.flowId, deps.api);- return CANCELLED;- }- deps.onStarted?.(flow);- return watchHighLevelSignIn(flow, deps, true);-}--export function cancelHighLevelSignIn(flowId: string, api: Deps["api"]): Promise<void> {- return api(`${HIGHLEVEL_API}/sign-in/${encodeURIComponent(flowId)}`, { method: "DELETE" }).then(() => undefined, () => undefined);-}--/** Follows a flow the server already has (opening its page first when asked) until it ends or the person cancels. */-export async function watchHighLevelSignIn(flow: HighLevelFlow, deps: Deps, openPage = false): Promise<HighLevelSignInResult> {- const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));- const { signal } = deps;- let onAbort: (() => void) | undefined;- const aborted = new Promise<HighLevelSignInResult>((resolve) => {- onAbort = () => resolve(CANCELLED);- if (signal?.aborted) onAbort();- else signal?.addEventListener("abort", onAbort, { once: true });- });- const cancelled = async () => {- await cancelHighLevelSignIn(flow.flowId, deps.api);- return CANCELLED;- };- try {- if (signal?.aborted) return await cancelled();- if (openPage) {- // Cancellation must not wait for the page or the status request to settle.- await Promise.race([Promise.resolve().then(() => deps.open(flow.authorizationUrl)).catch(() => undefined), aborted]);- if (signal?.aborted) return await cancelled();- }- for (;;) {- await Promise.race([sleep(POLL_MS), aborted]);- if (signal?.aborted) return await cancelled();- let status: HighLevelSignInResult;- try {- const response = await Promise.race([deps.api(`${HIGHLEVEL_API}/sign-in/${encodeURIComponent(flow.flowId)}`), aborted]);- if (signal?.aborted) return await cancelled();- status = resultOf(response);- } catch (error) {- if (signal?.aborted) return await cancelled();- return { phase: "failed", message: error instanceof Error ? error.message : String(error) };- }- if (status.phase !== "waiting") return status;- }- } finally {- if (onAbort) signal?.removeEventListener("abort", onAbort);- }-}diff --git a/src/lib/highlevel-status.ts b/src/lib/highlevel-status.tsdeleted file mode 100644index 1fbf5b53d2..0000000000--- a/src/lib/highlevel-status.ts+++ /dev/null@@ -1,53 +0,0 @@-import { useEffect, useState } from "react";--import { api } from "@/state/store";-import { HIGHLEVEL_API, isHighLevelStatus, type HighLevelStatus } from "./highlevel-sign-in";--// Bot settings read the same answer the Connected apps card last saw, so the-// per-bot app list does not re-ask the server on every open.-let cached: HighLevelStatus | null = null;-let cachedAt = 0;-let request: Promise<HighLevelStatus | null> | null = null;-const CACHE_MS = 30_000;--/** The HighLevel connection as the server reports it; null when it could not be asked. */-export function preloadHighLevelStatus(force = false): Promise<HighLevelStatus | null> {- if (!force && cached !== null && Date.now() - cachedAt < CACHE_MS) return Promise.resolve(cached);- if (request) return request;- request = api(HIGHLEVEL_API)- .then((response) => (isHighLevelStatus(response) ? rememberHighLevelStatus(response) : null))- .catch(() => null)- .finally(() => {- request = null;- });- return request;-}--export function rememberHighLevelStatus(status: HighLevelStatus): HighLevelStatus {- cached = status;- cachedAt = Date.now();- return status;-}--export function forgetHighLevelStatus(): void {- cached = null;- cachedAt = 0;-}--export function highLevelConnected(status: HighLevelStatus | null | undefined): boolean {- return status?.state === "connected";-}--export function useHighLevelStatus(): HighLevelStatus | null {- const [status, setStatus] = useState<HighLevelStatus | null>(cached);- useEffect(() => {- let cancelled = false;- void preloadHighLevelStatus().then((result) => {- if (!cancelled) setStatus(result);- });- return () => {- cancelled = true;- };- }, []);- return status;-}diff --git a/src/locales/de.json b/src/locales/de.jsonindex c06bf1f589..51b96a8967 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3,7 +3,6 @@"voice.gemini.model": "Gemini-Sprachmodell","keys.label.geminiTts": "Gemini-Sprach-API-Schlüssel","keys.purpose.geminiTts": "Gemini-Stimmen für gesprochene Antworten, Sprachnachrichten und Anrufe",- "highlevel.unavailable": "Hier nicht verfügbar.","postiz.description": "Social-Media-Beiträge mit Postiz entwerfen, planen und veröffentlichen.","postiz.connect": "Postiz verbinden","postiz.reconnect": "Postiz erneut verbinden",diff --git a/src/locales/en.json b/src/locales/en.jsonindex b80ab193ee..db55996d39 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -70,23 +70,6 @@"email.needsGoogle": "Gmail needs an app password here (with 2-step verification on), or sign in with Google.","email.needsMicrosoft": "Outlook doesn't take a mail password here: sign in with Microsoft.","email.needsAppPassword": "{provider} needs an app password here, not your normal password.",- "highlevel.title": "HighLevel",- "highlevel.description": "Also Growably and other HighLevel-based CRMs.",- "highlevel.connect": "Connect HighLevel",- "highlevel.reconnect": "Reconnect HighLevel",- "highlevel.connectedTo": "Connected · {name}",- "highlevel.finishInBrowser": "Finish signing in to HighLevel in your browser.",- "highlevel.menu": "HighLevel options",- "highlevel.disconnectConfirm": "Disconnect HighLevel? Bots lose access to its contacts, deals and conversations until you connect again.",- "highlevel.useToken": "Use a Private Integration token instead",- "highlevel.useSignIn": "Sign in instead",- "highlevel.tokenHelp": "In HighLevel or your CRM, open the sub-account you want to connect, go to Settings → Private Integrations and create one with these permissions: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities and View Custom Fields (for the conversation and calendar tools, also View Conversations, View Conversation Messages, View Calendars and View Calendar Events). Paste the token here with that sub-account's location ID (Settings → Business Profile).",- "highlevel.tokenField": "Private Integration token",- "highlevel.locationField": "Location ID",- "highlevel.tokenIncomplete": "Paste the token and the location ID.",- "highlevel.failed": "HighLevel could not be connected. Try again.",- "highlevel.expired": "The sign-in took too long. Try again.",- "highlevel.unavailable": "Not available here.","postiz.description": "Draft, schedule and publish social posts with Postiz.","postiz.connect": "Connect Postiz","postiz.reconnect": "Reconnect Postiz",@@ -1597,7 +1580,7 @@"cloudWelcome.files.foldersDesktop": "Bots on {name} can read folders you share from your computer, even when it's off. Share them from the desktop app, under Files.","cloudWelcome.files.foldersLent": "Bots on {name} use the files on this computer by themselves while it's awake and {app} is open. There's nothing to set up.","cloudWelcome.files.apps": "Connect apps",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel and more. Connections are per Cloud, so connect them here.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion and more. Connections are per Cloud, so connect them here.","cloudWelcome.files.appsAction": "Connect apps","cloudWelcome.files.finish": "Finish","cloudWelcome.done.title": "{name} is ready",diff --git a/src/locales/es.json b/src/locales/es.jsonindex abd01bd188..b3895cf7a3 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -14,23 +14,6 @@"hostedMcp.setupFailed": "No se pudo añadir {service}. Actualiza e inténtalo de nuevo.","hostedMcp.testFailed": "Sesión iniciada, pero no se pudieron cargar las herramientas de {service}: {reason} Vuelve a conectar para reintentarlo.","hostedMcp.loadingTools": "Sesión iniciada. Cargando las herramientas de {service}…",- "highlevel.title": "HighLevel",- "highlevel.description": "También Growably y otros CRM basados en HighLevel.",- "highlevel.connect": "Conectar HighLevel",- "highlevel.reconnect": "Volver a conectar HighLevel",- "highlevel.connectedTo": "Conectado · {name}",- "highlevel.finishInBrowser": "Termina de iniciar sesión en HighLevel en tu navegador.",- "highlevel.menu": "Opciones de HighLevel",- "highlevel.disconnectConfirm": "¿Desconectar HighLevel? Los bots pierden el acceso a sus contactos, oportunidades y conversaciones hasta que vuelvas a conectarlo.",- "highlevel.useToken": "Usar un token de Private Integration en su lugar",- "highlevel.useSignIn": "Iniciar sesión en su lugar",- "highlevel.tokenHelp": "En HighLevel o en tu CRM, abre la subcuenta que quieres conectar, ve a Settings → Private Integrations y crea una con estos permisos: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities y View Custom Fields (para las herramientas de conversaciones y calendario, también View Conversations, View Conversation Messages, View Calendars y View Calendar Events). Pega aquí el token junto con el ID de ubicación de esa subcuenta (Settings → Business Profile).",- "highlevel.tokenField": "Token de Private Integration",- "highlevel.locationField": "ID de ubicación",- "highlevel.tokenIncomplete": "Pega el token y el ID de ubicación.",- "highlevel.failed": "No se pudo conectar HighLevel. Inténtalo de nuevo.",- "highlevel.expired": "El inicio de sesión tardó demasiado. Inténtalo de nuevo.",- "highlevel.unavailable": "No disponible aquí.","postiz.description": "Redacta, programa y publica posts en redes sociales con Postiz.","postiz.connect": "Conectar Postiz","postiz.reconnect": "Volver a conectar Postiz",@@ -1194,7 +1177,7 @@"cloudWelcome.files.foldersDesktop": "Los bots de {name} pueden leer las carpetas que compartas desde tu equipo, incluso cuando está apagado. Compártelas desde la app de escritorio, en «Archivos».","cloudWelcome.files.foldersLent": "Los bots de {name} usan los archivos de este equipo por su cuenta mientras esté despierto y {app} esté abierto. No hay nada que configurar.","cloudWelcome.files.apps": "Conectar apps",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel y más. Las conexiones son por Cloud, así que conéctalas aquí.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion y más. Las conexiones son por Cloud, así que conéctalas aquí.","cloudWelcome.files.appsAction": "Conectar apps","cloudWelcome.files.finish": "Terminar","cloudWelcome.done.title": "{name} está lista",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 5282c36ab3..0d4e76bd03 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3,7 +3,6 @@"voice.gemini.model": "Modèle de synthèse vocale Gemini","keys.label.geminiTts": "Clé API de synthèse vocale Gemini","keys.purpose.geminiTts": "Voix Gemini pour les réponses vocales, les notes vocales et les appels",- "highlevel.unavailable": "Non disponible ici.","postiz.description": "Rédigez, planifiez et publiez vos posts sur les réseaux sociaux avec Postiz.","postiz.connect": "Connecter Postiz","postiz.reconnect": "Reconnecter Postiz",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex fd3c5241c2..bbb6d66d79 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3,7 +3,6 @@"voice.gemini.model": "Gemini वाक् मॉडल","keys.label.geminiTts": "Gemini वाक् API कुंजी","keys.purpose.geminiTts": "बोलकर दिए गए जवाबों, वॉइस नोट और कॉल के लिए Gemini की आवाज़ें",- "highlevel.unavailable": "यहाँ उपलब्ध नहीं।","postiz.description": "Postiz से सोशल मीडिया पोस्ट का ड्राफ़्ट बनाएँ, शेड्यूल करें और प्रकाशित करें।","postiz.connect": "Postiz कनेक्ट करें","postiz.reconnect": "Postiz फिर से कनेक्ट करें",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 5a7f2b327a..c8d5538350 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -14,22 +14,6 @@"hostedMcp.setupFailed": "Non è stato possibile aggiungere {service}. Aggiorna e riprova.","hostedMcp.testFailed": "Accesso fatto, ma gli strumenti di {service} non si sono caricati: {reason} Collegati di nuovo per riprovare.","hostedMcp.loadingTools": "Accesso fatto. Caricamento degli strumenti di {service}…",- "highlevel.description": "Anche Growably e gli altri CRM basati su HighLevel.",- "highlevel.connect": "Collega HighLevel",- "highlevel.reconnect": "Ricollega HighLevel",- "highlevel.connectedTo": "Collegato · {name}",- "highlevel.finishInBrowser": "Completa l’accesso a HighLevel nel browser.",- "highlevel.menu": "Opzioni di HighLevel",- "highlevel.disconnectConfirm": "Scolleghi HighLevel? I bot perdono contatti, trattative e conversazioni finché non lo ricolleghi.",- "highlevel.useToken": "Usa invece un token Private Integration",- "highlevel.useSignIn": "Accedi invece",- "highlevel.tokenHelp": "In HighLevel o nel tuo CRM, apri il sotto-account da collegare, vai in Settings → Private Integrations e creane uno con questi permessi: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities e View Custom Fields (per gli strumenti di conversazione e calendario, anche View Conversations, View Conversation Messages, View Calendars e View Calendar Events). Incolla qui il token con l’ID posizione di quel sotto-account (Settings → Business Profile).",- "highlevel.tokenField": "Token Private Integration",- "highlevel.locationField": "ID posizione",- "highlevel.tokenIncomplete": "Incolla il token e l’ID posizione.",- "highlevel.failed": "HighLevel non si è collegato. Riprova.",- "highlevel.expired": "L’accesso ha impiegato troppo tempo. Riprova.",- "highlevel.unavailable": "Non disponibile qui.","postiz.description": "Scrivi, pianifica e pubblica post sui social con Postiz.","postiz.connect": "Collega Postiz","postiz.reconnect": "Ricollega Postiz",@@ -1306,7 +1290,7 @@"cloudWelcome.files.foldersDesktop": "I bot su {name} possono leggere le cartelle che condividi dal tuo computer, anche quando è spento. Condividile dall'app desktop, sotto File.","cloudWelcome.files.foldersLent": "I bot su {name} usano da soli i file di questo computer mentre è acceso e {app} è aperto. Non c’è niente da configurare.","cloudWelcome.files.apps": "Collega le app",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel e altre. Le connessioni sono distinte per ogni Cloud, quindi collegale qui.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion e altre. Le connessioni sono distinte per ogni Cloud, quindi collegale qui.","cloudWelcome.files.appsAction": "Collega le app","cloudWelcome.files.finish": "Concludi","cloudWelcome.done.title": "{name} è pronto",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 51177fff7f..b9aee7724b 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -37,23 +37,6 @@"hostedMcp.testFailed": "サインインしましたが、{service} のツールを読み込めませんでした:{reason} もう一度接続してお試しください。","hostedMcp.loadingTools": "サインインしました。{service} のツールを読み込んでいます…","agentcard.notice": "Agentcard アカウントでサインインします。API キーは不要です。カードの保管と購入の承認は Agentcard が行い、OpenMausBot はカードの情報を保存しません。Agentcard を使えるボットは、購入やカード情報の表示を含むすべてのツールを呼び出せます。どのボットに使わせるかは「ボットへのアクセス」で選んでください。",- "highlevel.title": "HighLevel",- "highlevel.description": "Growablyなど、HighLevelベースのCRMにも対応しています。",- "highlevel.connect": "HighLevelを接続",- "highlevel.reconnect": "HighLevelを再接続",- "highlevel.connectedTo": "接続済み · {name}",- "highlevel.finishInBrowser": "ブラウザーで HighLevel へのサインインを完了してください。",- "highlevel.menu": "HighLevelのオプション",- "highlevel.disconnectConfirm": "HighLevelの接続を解除しますか? 再接続するまで、ボットはコンタクト、商談、会話にアクセスできなくなります。",- "highlevel.useToken": "代わりにプライベート連携トークンを使用",- "highlevel.useSignIn": "代わりにサインインする",- "highlevel.tokenHelp": "HighLevelまたはお使いのCRMで、接続したいサブアカウントを開き、「設定 → プライベート連携」で次の権限を持つ連携を作成してください:View Locations、View Contacts、Edit Contacts、View Opportunities、Edit Opportunities、View Custom Fields(会話ツールとカレンダーツールを使う場合は、View Conversations、View Conversation Messages、View Calendars、View Calendar Eventsも必要です)。作成したトークンを、そのサブアカウントのロケーションID(「設定 → ビジネスプロフィール」)とあわせてここに貼り付けてください。",- "highlevel.tokenField": "プライベート連携トークン",- "highlevel.locationField": "ロケーションID",- "highlevel.tokenIncomplete": "トークンとロケーションIDを貼り付けてください。",- "highlevel.failed": "HighLevelを接続できませんでした。もう一度お試しください。",- "highlevel.expired": "サインインに時間がかかりすぎました。もう一度お試しください。",- "highlevel.unavailable": "ここでは利用できません。","postiz.description": "Postizでソーシャルメディアの投稿を下書き、予約、公開します。","postiz.connect": "Postizを接続","postiz.reconnect": "Postizを再接続",@@ -1470,7 +1453,7 @@"cloudWelcome.files.foldersDesktop": "{name} 上のボットは、お使いのコンピューターから共有したフォルダーを、電源が切れていても読み取れます。フォルダーは、デスクトップアプリの「ファイル」から共有してください。","cloudWelcome.files.foldersLent": "このコンピューターがスリープしておらず {app} が開いている間、{name} のボットはこのコンピューターのファイルを自動で使います。設定は不要です。","cloudWelcome.files.apps": "アプリを接続",- "cloudWelcome.files.appsHint": "Gmail、Slack、HighLevelなど。接続はCloudごとに管理されるため、ここで接続してください。",+ "cloudWelcome.files.appsHint": "Gmail、Slack、Notionなど。接続はCloudごとに管理されるため、ここで接続してください。","cloudWelcome.files.appsAction": "アプリを接続","cloudWelcome.files.finish": "完了","cloudWelcome.done.title": "{name}の準備ができました",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 41307ad4d8..44dd11d3c5 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -35,23 +35,6 @@"hostedMcp.setupFailed": "{service}을 추가하지 못했어요. 새로고침한 뒤 다시 시도하세요.","hostedMcp.testFailed": "로그인은 됐지만 {service} 도구를 불러오지 못했어요: {reason} 다시 연결해 재시도하세요.","hostedMcp.loadingTools": "로그인했어요. {service} 도구를 불러오는 중…",- "highlevel.title": "HighLevel",- "highlevel.description": "Growably 등 HighLevel 기반 CRM도 지원해요.",- "highlevel.connect": "HighLevel 연결",- "highlevel.reconnect": "HighLevel 다시 연결",- "highlevel.connectedTo": "연결됨 · {name}",- "highlevel.finishInBrowser": "브라우저에서 HighLevel 로그인을 마치세요.",- "highlevel.menu": "HighLevel 옵션",- "highlevel.disconnectConfirm": "HighLevel 연결을 해제할까요? 다시 연결할 때까지 봇이 연락처, 거래, 대화에 접근할 수 없어요.",- "highlevel.useToken": "대신 Private Integration 토큰 사용",- "highlevel.useSignIn": "대신 로그인",- "highlevel.tokenHelp": "HighLevel 또는 사용 중인 CRM에서 연결할 하위 계정을 열고 Settings → Private Integrations로 이동해 다음 권한으로 하나 만드세요: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities, View Custom Fields(대화와 캘린더 도구를 쓰려면 View Conversations, View Conversation Messages, View Calendars, View Calendar Events도 필요해요). 만든 토큰과 해당 하위 계정의 위치 ID(Settings → Business Profile)를 여기에 붙여 넣으세요.",- "highlevel.tokenField": "Private Integration 토큰",- "highlevel.locationField": "위치 ID",- "highlevel.tokenIncomplete": "토큰과 위치 ID를 붙여 넣으세요.",- "highlevel.failed": "HighLevel을 연결하지 못했어요. 다시 시도하세요.",- "highlevel.expired": "로그인 시간이 너무 오래 걸렸어요. 다시 시도하세요.",- "highlevel.unavailable": "여기서는 사용할 수 없어요.","postiz.description": "Postiz로 소셜 게시물을 작성하고 예약하고 발행해요.","postiz.connect": "Postiz 연결","postiz.reconnect": "Postiz 다시 연결",@@ -1391,7 +1374,7 @@"cloudWelcome.files.foldersDesktop": "{name}의 봇은 컴퓨터가 꺼져 있어도 내가 공유한 폴더를 읽을 수 있어요. 데스크톱 앱의 파일에서 공유하세요.","cloudWelcome.files.foldersLent": "{name}의 봇은 이 컴퓨터가 깨어 있고 {app}이 열려 있는 동안 이 컴퓨터의 파일을 알아서 써요. 따로 설정할 것은 없어요.","cloudWelcome.files.apps": "앱 연결",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel 등. 연결은 클라우드마다 따로이니 여기서 연결하세요.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion 등. 연결은 클라우드마다 따로이니 여기서 연결하세요.","cloudWelcome.files.appsAction": "앱 연결","cloudWelcome.files.finish": "마치기","cloudWelcome.done.title": "{name} 준비 완료",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 0bf1e13cfd..2391fb4c67 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -14,23 +14,6 @@"hostedMcp.setupFailed": "Nie udało się dodać {service}. Odśwież i spróbuj ponownie.","hostedMcp.testFailed": "Zalogowano, ale nie udało się wczytać narzędzi {service}: {reason} Połącz ponownie, aby spróbować jeszcze raz.","hostedMcp.loadingTools": "Zalogowano. Wczytywanie narzędzi {service}…",- "highlevel.title": "HighLevel",- "highlevel.description": "Także Growably i inne CRM-y oparte na HighLevel.",- "highlevel.connect": "Połącz HighLevel",- "highlevel.reconnect": "Połącz ponownie z HighLevel",- "highlevel.connectedTo": "Połączono · {name}",- "highlevel.finishInBrowser": "Dokończ logowanie do HighLevel w przeglądarce.",- "highlevel.menu": "Opcje HighLevel",- "highlevel.disconnectConfirm": "Rozłączyć HighLevel? Boty utracą dostęp do jego kontaktów, transakcji i rozmów, dopóki nie połączysz go ponownie.",- "highlevel.useToken": "Użyj zamiast tego tokena integracji prywatnej",- "highlevel.useSignIn": "Zaloguj się zamiast tego",- "highlevel.tokenHelp": "W HighLevel lub swoim CRM otwórz podkonto, które chcesz połączyć, przejdź do Ustawienia → Integracje prywatne i utwórz integrację z tymi uprawnieniami: wyświetlanie lokalizacji, wyświetlanie kontaktów, edytowanie kontaktów, wyświetlanie szans sprzedaży, edytowanie szans sprzedaży i wyświetlanie pól niestandardowych (dla narzędzi rozmów i kalendarza także wyświetlanie rozmów, wyświetlanie wiadomości rozmów, wyświetlanie kalendarzy i wyświetlanie wydarzeń kalendarza). Wklej token tutaj wraz z identyfikatorem lokalizacji tego podkonta (Ustawienia → Profil firmy).",- "highlevel.tokenField": "Token integracji prywatnej",- "highlevel.locationField": "Identyfikator lokalizacji",- "highlevel.tokenIncomplete": "Wklej token i identyfikator lokalizacji.",- "highlevel.failed": "Nie udało się połączyć z HighLevel. Spróbuj ponownie.",- "highlevel.expired": "Logowanie trwało zbyt długo. Spróbuj ponownie.",- "highlevel.unavailable": "Niedostępne w tym miejscu.","postiz.description": "Twórz szkice, planuj i publikuj posty w mediach społecznościowych z Postiz.","postiz.connect": "Połącz Postiz","postiz.reconnect": "Połącz Postiz ponownie",@@ -1327,7 +1310,7 @@"cloudWelcome.files.foldersDesktop": "Boty w {name} mogą czytać foldery udostępniane z twojego komputera, nawet gdy jest wyłączony. Udostępnij je w aplikacji na komputer, w sekcji Pliki.","cloudWelcome.files.foldersLent": "Boty w {name} same korzystają z plików na tym komputerze, gdy jest włączony, a {app} otwarty. Nie trzeba niczego ustawiać.","cloudWelcome.files.apps": "Połącz aplikacje",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel i inne. Połączenia są przypisane do Chmury, więc połącz je tutaj.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion i inne. Połączenia są przypisane do Chmury, więc połącz je tutaj.","cloudWelcome.files.appsAction": "Połącz aplikacje","cloudWelcome.files.finish": "Zakończ","cloudWelcome.done.title": "{name} jest gotowe",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 26d21b0f06..bb0759b790 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -53,23 +53,6 @@"email.needsGoogle": "O Gmail precisa aqui de uma senha de app (com a verificação em duas etapas ativada), ou entre com o Google.","email.needsMicrosoft": "O Outlook não aceita aqui uma senha de e-mail: entre com a Microsoft.","email.needsAppPassword": "{provider} precisa aqui de uma senha de app, não da sua senha normal.",- "highlevel.title": "HighLevel",- "highlevel.description": "Também para o Growably e outros CRMs baseados no HighLevel.",- "highlevel.connect": "Conectar o HighLevel",- "highlevel.reconnect": "Reconectar o HighLevel",- "highlevel.connectedTo": "Conectado · {name}",- "highlevel.finishInBrowser": "Termine de entrar no HighLevel no seu navegador.",- "highlevel.menu": "Opções do HighLevel",- "highlevel.disconnectConfirm": "Desconectar o HighLevel? Os bots perdem o acesso aos contatos, negócios e conversas dele até você conectar novamente.",- "highlevel.useToken": "Usar um token de integração privado.",- "highlevel.useSignIn": "Fazer login",- "highlevel.tokenHelp": "No HighLevel ou no seu CRM, abra a subconta que você quer conectar, vá em Settings → Private Integrations e crie uma com estas permissões: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities e View Custom Fields (para as ferramentas de conversas e de calendário, também View Conversations, View Conversation Messages, View Calendars e View Calendar Events). Cole o token aqui com o ID do local (Location ID) dessa subconta (Settings → Business Profile).",- "highlevel.tokenField": "Token de Integração Privado",- "highlevel.locationField": "ID do local",- "highlevel.tokenIncomplete": "Cole o token e o ID do local.",- "highlevel.failed": "Não foi possível conectar o HighLevel. Tente novamente.",- "highlevel.expired": "O login demorou demais. Tente novamente.",- "highlevel.unavailable": "Indisponível aqui.","postiz.description": "Crie rascunhos, agende e publique posts nas redes sociais com o Postiz.","postiz.connect": "Conectar o Postiz","postiz.reconnect": "Reconectar o Postiz",@@ -1474,7 +1457,7 @@"cloudWelcome.files.foldersDesktop": "Os bots de {name} podem ler as pastas que você compartilhar do seu computador, mesmo quando ele estiver desligado. Compartilhe-as pelo app para computador, em “Arquivos”.","cloudWelcome.files.foldersLent": "Os bots de {name} usam automaticamente os arquivos deste computador enquanto ele estiver ativo e o app {app} estiver aberto. Não é preciso configurar nada.","cloudWelcome.files.apps": "Conectar apps",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel e mais. Cada Cloud tem suas próprias conexões, então conecte os apps aqui.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion e mais. Cada Cloud tem suas próprias conexões, então conecte os apps aqui.","cloudWelcome.files.appsAction": "Conectar apps","cloudWelcome.files.finish": "Concluir","cloudWelcome.done.title": "Tudo pronto em {name}",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 6b7e9ed93a..003de3616e 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -14,23 +14,6 @@"hostedMcp.setupFailed": "Не удалось добавить {service}. Обновите и попробуйте снова.","hostedMcp.testFailed": "Выполнен вход, но не удалось загрузить инструменты {service}: {reason} Подключитесь ещё раз, чтобы повторить попытку.","hostedMcp.loadingTools": "Выполнен вход. Загружаем инструменты {service}…",- "highlevel.title": "HighLevel",- "highlevel.description": "Также Growably и другие CRM на базе HighLevel.",- "highlevel.connect": "Подключить HighLevel",- "highlevel.reconnect": "Переподключить HighLevel",- "highlevel.connectedTo": "Подключено · {name}",- "highlevel.finishInBrowser": "Завершите вход в HighLevel в браузере.",- "highlevel.menu": "Параметры HighLevel",- "highlevel.disconnectConfirm": "Отключить HighLevel? Боты потеряют доступ к его контактам, сделкам и перепискам, пока вы не подключите его снова.",- "highlevel.useToken": "Использовать вместо этого токен Private Integration",- "highlevel.useSignIn": "Войти вместо этого",- "highlevel.tokenHelp": "В HighLevel или вашей CRM откройте субаккаунт, который нужно подключить, перейдите в Settings → Private Integrations и создайте интеграцию со следующими разрешениями: View Locations, View Contacts, Edit Contacts, View Opportunities, Edit Opportunities и View Custom Fields (для инструментов переписки и календаря также View Conversations, View Conversation Messages, View Calendars и View Calendar Events). Вставьте токен сюда вместе с Location ID этого субаккаунта (Settings → Business Profile).",- "highlevel.tokenField": "Токен Private Integration",- "highlevel.locationField": "Location ID",- "highlevel.tokenIncomplete": "Вставьте токен и Location ID.",- "highlevel.failed": "Не удалось подключить HighLevel. Попробуйте ещё раз.",- "highlevel.expired": "Вход занял слишком много времени. Попробуйте ещё раз.",- "highlevel.unavailable": "Здесь недоступно.","postiz.description": "Готовьте черновики, планируйте и публикуйте посты в соцсетях через Postiz.","postiz.connect": "Подключить Postiz","postiz.reconnect": "Переподключить Postiz",@@ -1333,7 +1316,7 @@"cloudWelcome.files.foldersDesktop": "Боты на {name} могут читать папки, доступ к которым вы открываете со своего компьютера, даже когда он выключен. Откройте к ним доступ в настольном приложении в разделе «Файлы».","cloudWelcome.files.foldersLent": "Боты в {name} сами пользуются файлами на этом компьютере, пока он не спит и {app} открыт. Ничего настраивать не нужно.","cloudWelcome.files.apps": "Подключить приложения",- "cloudWelcome.files.appsHint": "Gmail, Slack, HighLevel и другие. У каждого Cloud свои подключения, поэтому подключите их здесь.",+ "cloudWelcome.files.appsHint": "Gmail, Slack, Notion и другие. У каждого Cloud свои подключения, поэтому подключите их здесь.","cloudWelcome.files.appsAction": "Подключить приложения","cloudWelcome.files.finish": "Готово","cloudWelcome.done.title": "{name} готов",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 0be259a902..7a0e3e2d62 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -2,7 +2,6 @@"version": 1,"locales": {"de": {- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b","pro.seePlans": "30d9abfd7c7af513814bdfadcafe7ec4a90bc6bcee519086dc513f63f2cd7384","pro.reauthShort": "089c74d900d6e3d84b0d4981fb4eb0b4038d9a243ca8209862f7500766382473",@@ -3256,23 +3255,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -4024,7 +4006,7 @@"cloudWelcome.files.folders": "034d3b7cc8664b89643c8ac9b4c6b9950066e7f0d2cf47188783d1be7b41e328","cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -9154,7 +9136,6 @@"serverError.mailbox.outgoingFields": "77e3adfe271dc92e84f0b3b5b9d1c95512737f8609fd0b6197694ff71d444ca3"},"fr": {- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b","pro.seePlans": "30d9abfd7c7af513814bdfadcafe7ec4a90bc6bcee519086dc513f63f2cd7384","pro.reauthShort": "089c74d900d6e3d84b0d4981fb4eb0b4038d9a243ca8209862f7500766382473",@@ -12263,7 +12244,6 @@"serverError.mailbox.outgoingFields": "77e3adfe271dc92e84f0b3b5b9d1c95512737f8609fd0b6197694ff71d444ca3"},"hi": {- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b","pro.seePlans": "30d9abfd7c7af513814bdfadcafe7ec4a90bc6bcee519086dc513f63f2cd7384","pro.reauthShort": "089c74d900d6e3d84b0d4981fb4eb0b4038d9a243ca8209862f7500766382473",@@ -15235,23 +15215,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -16134,7 +16097,7 @@"cloudWelcome.files.folders": "034d3b7cc8664b89643c8ac9b4c6b9950066e7f0d2cf47188783d1be7b41e328","cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -22847,23 +22810,6 @@"email.connectedNoSending": "f5f012343ca3ea47006484c7155b42d3c01e6e31d7715e7be0ece00a9236faa9","email.addAnother": "e82c15f298f1fdd00afc9688ef6af584bff227a700a998fcfa860235ed0140bc","email.disconnect": "7bb7c343179f929195e46d35aa042ce4a1d50361bde1b685c5a8078c95d3115d",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","postiz.description": "688bc4128e2c899b128639b0439edfdf858a3cbb5eb94f7a0dd243b9a97baa17","postiz.connect": "91a5544ce7deb2aced1218ad8daaa1b572454943dccd3ef354aeefff69135d29","postiz.reconnect": "7df8908ab53d5adda91226b2e9bd9c991d4abfcd792c3201cd33021cd2c5b224",@@ -24240,7 +24186,7 @@"cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.foldersLent": "ade9225598e7eeb81bf77d1d62bb1460173eb509523f6fb9fd5c3e82efafdcc9","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -32470,7 +32416,6 @@"serverError.mailbox.outgoingFields": "77e3adfe271dc92e84f0b3b5b9d1c95512737f8609fd0b6197694ff71d444ca3"},"zh": {- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b","pro.seePlans": "30d9abfd7c7af513814bdfadcafe7ec4a90bc6bcee519086dc513f63f2cd7384","pro.reauthShort": "089c74d900d6e3d84b0d4981fb4eb0b4038d9a243ca8209862f7500766382473",@@ -35983,22 +35928,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -36617,7 +36546,7 @@"cloudWelcome.files.folders": "034d3b7cc8664b89643c8ac9b4c6b9950066e7f0d2cf47188783d1be7b41e328","cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -39956,7 +39885,6 @@"hostedMcp.botSettings": "a70b6aa99fd4be1504fc68df31ef433aa5e44a24379b9643e0e8d1b8cb3ffe19","hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -44730,7 +44658,6 @@"serverError.mailbox.outgoingFields": "77e3adfe271dc92e84f0b3b5b9d1c95512737f8609fd0b6197694ff71d444ca3"},"uk": {- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b","pro.seePlans": "30d9abfd7c7af513814bdfadcafe7ec4a90bc6bcee519086dc513f63f2cd7384","pro.reauthShort": "089c74d900d6e3d84b0d4981fb4eb0b4038d9a243ca8209862f7500766382473",@@ -48143,7 +48070,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -53535,7 +53461,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -58927,23 +58852,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -59819,7 +59727,7 @@"cloudWelcome.files.folders": "034d3b7cc8664b89643c8ac9b4c6b9950066e7f0d2cf47188783d1be7b41e328","cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -65598,23 +65506,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -66497,7 +66388,7 @@"cloudWelcome.files.folders": "034d3b7cc8664b89643c8ac9b4c6b9950066e7f0d2cf47188783d1be7b41e328","cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -72331,22 +72222,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","table.title": "16d1c9050a0b32e83764a81d801a880773abedfd7f8b0b08a1cd87ca0e404f12","table.search": "ae031c7268677cb7ecba0b8e17233ed705f2ba16d654c5ed61f7dc722ef77bd4","table.wrap": "766da8f11fafe1ecd77a324ddfbc1c25e8743240f272170dc0760ad108154e18",@@ -73203,7 +73078,7 @@"cloudWelcome.files.folders": "034d3b7cc8664b89643c8ac9b4c6b9950066e7f0d2cf47188783d1be7b41e328","cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",@@ -78883,23 +78758,6 @@"hostedMcp.setupFailed": "b4ef46d1fa1f788380010693a9df980916c45563eb6fa162e9f38a0bf2cda13b","hostedMcp.testFailed": "48cf00db2f575d9eaf8fce51a25b2a654c283e4daa078d3e85b3211e7ab4ecf0","hostedMcp.loadingTools": "a0fc717ac4c8c8caa59532400c2a487edb94ad9709eed8aa7f5edcf2e6ee9015",- "highlevel.title": "abfc6272b5ad06927cfe2eebc1717892428919e15ed940abb0a5e14b2ac4189f",- "highlevel.description": "e35a43c1cd65e769d7df9e9c17ad70acae2a653f9013570679ddbc30e54c1407",- "highlevel.connect": "1121d30e31fcfe4dc9448c6c77062db8295fdc85b994035e54b829cafd0d0c9c",- "highlevel.reconnect": "50adabb9188c94e5255a8f9d19da3de46f91dde419edb25147242c83e5e1f7ce",- "highlevel.connectedTo": "2b31ef06f3e61ae71040a06e0d27f8cb8b8318be399161a04bf2593d93c772b2",- "highlevel.finishInBrowser": "59427b69c67c53672c4a8f93bdbfcfd96b09c15b596997b141bd53b9d70aff73",- "highlevel.menu": "fe25699a2993f9a91359b22b516bf3ecd8865e748fbd5c23872d3fbb9311e9bf",- "highlevel.disconnectConfirm": "214c77fac386c1b90bd853bfff1b163bc9e27290c7070ed7f94f53583d2459e9",- "highlevel.useToken": "141f9e69bc79aa40f98f50cee70274d493b8cd5c01a9cbd2e00a170b7bb8dd63",- "highlevel.useSignIn": "65da838eacef849560b5321ae6a3d8bc5c1300379839b45553c33c34e52064ca",- "highlevel.tokenHelp": "a877204bb55c138d5c46b404ede2c0fd5a20a574de39ee33d8ddb067c5892987",- "highlevel.tokenField": "aa402e31ef59baf5dc6e6189f3c5569a05a2095b55200bfdebac2b0481aa8432",- "highlevel.locationField": "47689c2a178f5377cd9f562d8ef45611dd4c9f68db9b15636b4dae8ede3a4ba1",- "highlevel.tokenIncomplete": "bf62738f8c076e6f6022abc685a40f1111e5af4292df09b0cfb368c3f20e96df",- "highlevel.failed": "18091cc144221726c2cc07c2d6f91a0389bc0ec8ec3a9d837dccbab6fe70f4ce",- "highlevel.expired": "f2c7a992fabee431c093f2ee5fa888b552b5208d39580688f35f284681639d82",- "highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533","postiz.description": "688bc4128e2c899b128639b0439edfdf858a3cbb5eb94f7a0dd243b9a97baa17","postiz.connect": "91a5544ce7deb2aced1218ad8daaa1b572454943dccd3ef354aeefff69135d29","postiz.reconnect": "7df8908ab53d5adda91226b2e9bd9c991d4abfcd792c3201cd33021cd2c5b224",@@ -79969,7 +79827,7 @@"cloudWelcome.files.foldersDesktop": "9babcc03dad8748ca6e4ee5d8b96b0ce2330a6ab0110f99400956495f1b35c11","cloudWelcome.files.foldersLent": "ade9225598e7eeb81bf77d1d62bb1460173eb509523f6fb9fd5c3e82efafdcc9","cloudWelcome.files.apps": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b",- "cloudWelcome.files.appsHint": "c6b26309c33afe58dbff6904e1bae6ead1ac04dfc4eaa3759ca0ad1c22613705",+ "cloudWelcome.files.appsHint": "dcad1dd908a1ca87176908eadd01b7d3e07c14f3924148843d123076caccca19","cloudWelcome.files.appsAction": "02903f49f6f5124626cab7d5ed840cb122e9c507739c9b72e279a10846ddec1b","cloudWelcome.files.finish": "a6c7a84baa6750fce33f7512acd6793e53def1d228b5f2efb8074b42648424fc","cloudWelcome.done.title": "d52d436227c61e9da1158718cc94eceb1215f6b1fde4093900f45785261e5633",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex ca5b1df5c0..63ec8ad98d 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -14,7 +14,6 @@"hostedMcp.setupFailed": "{service} eklenemedi. Sayfayı yenileyip tekrar deneyin.","hostedMcp.testFailed": "Giriş yapıldı, ancak {service} araçları yüklenemedi: {reason} Yeniden denemek için lütfen tekrar bağlanın.","hostedMcp.loadingTools": "Giriş yapıldı. {service} araçları yükleniyor…",- "highlevel.unavailable": "Burada kullanılamıyor.","postiz.description": "Postiz ile sosyal medya gönderilerini taslak olarak hazırlayın, zamanlayın ve yayınlayın.","postiz.connect": "Postiz’i bağla","postiz.reconnect": "Postiz’i yeniden bağla",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 2e5f6da244..246ec740f0 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -3,7 +3,6 @@"voice.gemini.model": "Модель синтезу мовлення Gemini","keys.label.geminiTts": "API-ключ синтезу мовлення Gemini","keys.purpose.geminiTts": "Голоси Gemini для озвучення відповідей, голосових нотаток і дзвінків",- "highlevel.unavailable": "Тут недоступно.","postiz.description": "Створюйте чернетки, плануйте й публікуйте дописи в соцмережах через Postiz.","postiz.connect": "Підключити Postiz","postiz.reconnect": "Перепідключити Postiz",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex ee22f1bdfe..f650c945e7 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -14,7 +14,6 @@"hostedMcp.setupFailed": "Không thể thêm {service}. Hãy làm mới và thử lại.","hostedMcp.testFailed": "Đã đăng nhập, nhưng không thể tải các công cụ của {service}: {reason} Vui lòng kết nối lại để thử lại.","hostedMcp.loadingTools": "Đã đăng nhập. Đang tải công cụ của {service}…",- "highlevel.unavailable": "Không khả dụng ở đây.","postiz.description": "Soạn nháp, lên lịch và đăng bài mạng xã hội bằng Postiz.","postiz.connect": "Kết nối Postiz","postiz.reconnect": "Kết nối lại Postiz",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex ceb4832654..57c8c5d521 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -13,7 +13,6 @@"hostedMcp.botSettings": "管理 {name} 的存取權","hostedMcp.setupFailed": "無法新增 {service}。請重新整理後再試一次。","hostedMcp.testFailed": "已登入,但無法載入 {service} 的工具:{reason} 請重新連線以重試。",- "highlevel.unavailable": "這裡無法使用。","postiz.description": "用 Postiz 撰寫草稿、排程並發布社群貼文。","postiz.connect": "連結 Postiz","postiz.reconnect": "重新連結 Postiz",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 0590af504d..98f86db954 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -35,23 +35,6 @@"hostedMcp.setupFailed": "无法添加 {service}。请刷新后重试。","hostedMcp.testFailed": "已登录,但无法加载 {service} 的工具:{reason} 请重新连接后再试。","hostedMcp.loadingTools": "已登录。正在加载 {service} 的工具…",- "highlevel.title": "HighLevel",- "highlevel.description": "也支持 Growably 等其他基于 HighLevel 的 CRM。",- "highlevel.connect": "连接 HighLevel",- "highlevel.reconnect": "重新连接 HighLevel",- "highlevel.connectedTo": "已连接 · {name}",- "highlevel.finishInBrowser": "请在浏览器中完成 HighLevel 登录。",- "highlevel.menu": "HighLevel 选项",- "highlevel.disconnectConfirm": "要断开 HighLevel 连接吗?断开后,机器人将无法访问它的联系人、商机和对话,直到你重新连接。",- "highlevel.useToken": "改用 Private Integration 令牌",- "highlevel.useSignIn": "改用登录",- "highlevel.tokenHelp": "在 HighLevel 或你的 CRM 中打开要连接的子账户,进入「设置 → Private Integrations」,新建一个集成并授予这些权限:View Locations、View Contacts、Edit Contacts、View Opportunities、Edit Opportunities、View Custom Fields(如需对话和日历工具,还需 View Conversations、View Conversation Messages、View Calendars、View Calendar Events)。把令牌粘贴到这里,并填入该子账户的 Location ID(设置 → Business Profile)。",- "highlevel.tokenField": "Private Integration 令牌",- "highlevel.locationField": "Location ID",- "highlevel.tokenIncomplete": "请粘贴令牌和 Location ID。",- "highlevel.failed": "无法连接 HighLevel。请重试。",- "highlevel.expired": "登录超时。请重试。",- "highlevel.unavailable": "这里不可用。","postiz.description": "用 Postiz 撰写草稿、排期并发布社交媒体帖子。","postiz.connect": "连接 Postiz","postiz.reconnect": "重新连接 Postiz",@@ -1505,7 +1488,7 @@"cloudWelcome.files.foldersDesktop": "{name} 上的机器人可以读取你从电脑共享的文件夹,即使电脑已关机。请在桌面应用「文件」中共享它们。","cloudWelcome.files.foldersLent": "只要这台电脑处于唤醒状态且 {app} 已打开,{name} 上的机器人就会自动使用这台电脑上的文件,无需任何设置。","cloudWelcome.files.apps": "连接应用",- "cloudWelcome.files.appsHint": "Gmail、Slack、HighLevel 等。连接是按 Cloud 分别保存的,所以请在这里连接。",+ "cloudWelcome.files.appsHint": "Gmail、Slack、Notion 等。连接是按 Cloud 分别保存的,所以请在这里连接。","cloudWelcome.files.appsAction": "连接应用","cloudWelcome.files.finish": "完成","cloudWelcome.done.title": "{name} 已就绪",diff --git a/src/state/store.tsx b/src/state/store.tsxindex f99734d4b8..8d2e287cfc 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -488,8 +488,8 @@ export interface InstanceInfo extends InstanceEndpointInfo {computerMcp?: boolean;agentsMcp?: boolean;composioMcp?: boolean;- /** the engine can mount the native HighLevel tools (a connected app without Composio), the paired phone's app tools and the Data tools */- highlevelMcp?: boolean; deviceMcp?: boolean; dataMcp?: boolean;+ /** the engine can mount the native Email tools (a connected app without Composio), the paired phone's app tools and the Data tools */+ emailMcp?: boolean; deviceMcp?: boolean; dataMcp?: boolean;browserMcp?: boolean;images?: boolean;effortLevels?: readonly EffortLevel[];