Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(highlevel): stop waiting calls before sending another request

Sebastian Bb075d6be489b
diff --git a/docs/highlevel.md b/docs/highlevel.md
index 808e05cb4a..372b4d8f90 100644
--- a/docs/highlevel.md
+++ b/docs/highlevel.md
@@ -168,6 +168,8 @@ Every successful write appends an activity row to the thread: `tool.name` `mcp__
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.
@@ -188,7 +190,8 @@ locations at once (one connection per installation).
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.
+ revocation → Disconnect → Private Integration token, and Stop during a 429 wait without a later write.
diff --git a/server/highlevel.e2e.test.ts b/server/highlevel.e2e.test.ts
index f7647250ac..abce04e292 100644
--- a/server/highlevel.e2e.test.ts
+++ b/server/highlevel.e2e.test.ts
@@ -165,3 +165,21 @@ it("gives a bot its scoped tools, records writes without contact data, refreshes
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/cancellation.test.ts b/server/highlevel/cancellation.test.ts
new file mode 100644
index 0000000000..253f58b62d
--- /dev/null
+++ b/server/highlevel/cancellation.test.ts
@@ -0,0 +1,95 @@
+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.ts b/server/highlevel/client.ts
index e2f3c00797..30cde07d07 100644
--- a/server/highlevel/client.ts
+++ b/server/highlevel/client.ts
@@ -1,6 +1,7 @@
// 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";
@@ -240,6 +241,7 @@ export class HighLevelClient {
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. */
@@ -254,6 +256,15 @@ export class HighLevelClient {
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();
@@ -313,7 +324,7 @@ export class HighLevelClient {
const now = this.now();
const recent = window.filter((at) => now - at < BUDGET_WINDOW_MS);
if (recent.length >= BUDGET_CALLS) {
- await this.sleep(Math.max(1, recent[0]! + BUDGET_WINDOW_MS - now));
+ await this.wait(Math.max(1, recent[0]! + BUDGET_WINDOW_MS - now));
return this.spend(locationId);
}
recent.push(now);
@@ -324,6 +335,7 @@ export class HighLevelClient {
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",
@@ -384,7 +396,7 @@ export class HighLevelClient {
if (response.status >= 500 && !retried5xx) {
await response.body?.cancel().catch(() => {});
retried5xx = true;
- await this.sleep(1_000);
+ await this.wait(1_000);
continue;
}
const body = await this.body(response, method, path, options);
@@ -406,7 +418,7 @@ export class HighLevelClient {
}
if (response.status === 429 && !waited) {
waited = true;
- await this.sleep(waitFromHeaders(response.headers, this.now()));
+ await this.wait(waitFromHeaders(response.headers, this.now()));
continue;
}
if (response.status === 401) {
diff --git a/server/highlevel/rpc.test.ts b/server/highlevel/rpc.test.ts
index a89df08795..f56cc3df35 100644
--- a/server/highlevel/rpc.test.ts
+++ b/server/highlevel/rpc.test.ts
@@ -153,7 +153,7 @@ describe("highlevelRpc", () => {
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()).toBe(2);
+ 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();
diff --git a/server/highlevel/rpc.ts b/server/highlevel/rpc.ts
index e06b086445..51b3805293 100644
--- a/server/highlevel/rpc.ts
+++ b/server/highlevel/rpc.ts
@@ -30,10 +30,11 @@ export async function highlevelRpc(
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(params.name);
+ const verdict = deps.authorize(name);
if (!verdict.ok) return highlevelErrorResult(verdict.text, { code: "refused" });
- const { result, write } = await runHighLevelTool(deps.client, params.name, args as Record<string, unknown>);
+ 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;