Skip to content

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

feat(bot-api): not on the Starter plan; answer before a proxy drops the wait

milind-soni0fc7e097c928
diff --git a/docs/bot-api.md b/docs/bot-api.md
index 5bea71c18a..87b8a0fead 100644
--- a/docs/bot-api.md
+++ b/docs/bot-api.md
@@ -13,6 +13,13 @@ the old one stop working); switching the card off forgets it. Only someone who
may edit the bot can switch it on, mint a key or switch it off; each of those
is a **Bot API** row in Settings → Activity.
+## Plans
+
+Bot API isn't part of a Cloud's Starter plan. There the card shows one line and
+Upgrade; a new key is refused, and a key left from a higher plan answers `403`
+with an upgrade message. An upgrade works at once, with the same key. Desktop and
+self-hosted servers aren't affected.
+
## Calling it
```sh
@@ -33,7 +40,9 @@ The JSON body takes:
- `thread` (optional): the `thread` an earlier answer returned, to go on in the
same conversation. Only a thread the API opened can be continued this way.
- `wait` (optional, seconds, at most 300): how long to wait for the reply
- before answering `working`. The default is the maximum.
+ before answering `working`. The default is 50, under the 60 seconds of silence
+ Fly's proxy is reported to allow; a longer wait is for a path you know keeps a
+ quiet connection open.
Answers:
@@ -60,13 +69,9 @@ computer the app runs on. The thread always asks, whatever the bot's own level
answers an approval for the caller, and the person's answer in the app is for
that one request. On a Team Cloud the turn also runs confined, as a webhook's does.
-Approvals guard actions, not everything the bot can read: what the bot can read
-without asking, its memory and files included, can reach a key holder through its
-reply. Give a key only to something you would let talk to this bot.
-
-If something between the caller and this address drops a silent connection before
-the reply is ready, pass a shorter `wait` and read the thread with `GET`: an answer
-that never arrived also never gave the caller its thread id.
+A key is like a password: whoever holds it can read what this bot can read.
+Approvals guard actions, not reads, so its memory, files and read-only tools can
+reach a key holder through its reply.
Each call is kept with the bot's API settings and shown on the card (count, last
call, recent calls) to those who can manage the key. Refused calls roll up into
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index c4dc90b754..bae4a490da 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1678,8 +1678,11 @@ before the engines are read again.
**`POST /api/cloud/plan`**, signed over its JSON body like the sleep request:
`{"v":1,"cancelled":true}` when the customer cancels, `{"v":1,"cancelled":false}`
-when renewal is back on. `200 {"ok":true}`; `400 {"error":"invalid_plan"}`
-without a boolean `cancelled`. The Admin does not send it yet.
+when renewal is back on, and `{"v":1,"tier":"starter"}` for which plan this Cloud
+is on now (either or both). `200 {"ok":true}`; `400 {"error":"invalid_plan"}`
+without one of them, or with a malformed one. The tier is kept across restarts
+(`server/host/cloud-plan-tier.ts`) and counts at once; a home that was never told
+is not Starter. Bot API uses it. The Admin does not send any of this yet.
## What the desktop reads from the Admin
diff --git a/server/bot-api-host.test.ts b/server/bot-api-host.test.ts
index 3b8a715283..e3ae311210 100644
--- a/server/bot-api-host.test.ts
+++ b/server/bot-api-host.test.ts
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { BotApiManager } from "./bot-api.ts";
-import { createBotApiHost, type BotApiHostDeps, type BotApiTurnOptions } from "./bot-api-host.ts";
+import { BOT_API_DEFAULT_WAIT_MS, createBotApiHost, type BotApiHostDeps, type BotApiTurnOptions } from "./bot-api-host.ts";
import type { RequestAuth } from "./request-auth.ts";
import type { Message } from "./store.ts";
import { createWebhookIngressHandler } from "./webhook-ingress.ts";
@@ -65,7 +65,7 @@ const replies = (text: string): Script => (fake, _botId, _prompt, opts) => {
}, 30);
};
-async function harness(script: Script, options: { waitMs?: number; full?: boolean } = {}) {
+async function harness(script: Script, options: { waitMs?: number; full?: boolean; included?: () => boolean } = {}) {
const dir = mkdtempSync(join(tmpdir(), "omb-bot-api-host-"));
dirs.push(dir);
const fake = fakeStore();
@@ -86,6 +86,7 @@ async function harness(script: Script, options: { waitMs?: number; full?: boolea
},
threadBusy: (botId, threadId) => fake.bots.get(botId)?.tasks.find((task) => task.threadId === threadId)?.busy === true,
canStart: () => !options.full,
+ ...(options.included ? { included: options.included } : {}),
hooksBaseUrl: () => "https://bots.example.test",
manageRefusal: (auth) => (auth.scopes.includes("admin") ? null : "Only people who can edit Scout can change this."),
record: (_auth, row) => recorded.push(row),
@@ -315,6 +316,48 @@ describe("the Bot API door on the webhook receiver", () => {
expect((await h.app("GET", "/api/bots/b1/bot-api", undefined, false)).body.calls).toEqual([]);
});
+ it("on Starter refuses a new key, turns a leftover key away with the upgrade words, and an upgrade works at once", async () => {
+ let starter = false;
+ const h = await harness(replies("ok"), { included: () => !starter });
+ const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;
+ expect((await h.call("b1", key, { message: "Before" })).status).toBe(200);
+ const threadId = h.fake.bots.get("b1")!.tasks[0]!.threadId;
+
+ starter = true;
+ const words = { error: "Bot API comes with a higher plan. Upgrade this Cloud to use it." };
+ const before = h.turns.length;
+ expect(await h.call("b1", key, { message: "After" })).toEqual({ status: 403, body: words });
+ expect(await h.call("b1", key, undefined, { method: "GET", query: `?thread=${threadId}` })).toEqual({ status: 403, body: words });
+ expect(h.turns).toHaveLength(before);
+ // Only a key holder learns about the plan: a stranger still gets the wrong-key answer.
+ expect(await h.call("b1", `${key}x`, { message: "Hi" })).toEqual({ status: 401, body: { error: "Invalid key" } });
+ expect(await h.app("POST", "/api/bots/b1/bot-api/new-key")).toMatchObject({ status: 403, body: { ...words, upgrade: true } });
+ expect(await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).toMatchObject({ status: 403, body: { ...words, upgrade: true } });
+ expect((await h.app("GET", "/api/bots/b1/bot-api")).body).toMatchObject({ included: false, enabled: true });
+ expect(h.manager.authorize("b1", key)).toBe(true);
+
+ starter = false;
+ expect((await h.call("b1", key, { message: "Upgraded" })).status).toBe(200);
+ expect((await h.app("GET", "/api/bots/b1/bot-api")).body).toMatchObject({ included: true });
+
+ // Turning it off stays possible on Starter, and it can't be turned back on there.
+ starter = true;
+ expect((await h.app("POST", "/api/bots/b1/bot-api", { enabled: false })).status).toBe(200);
+ expect((await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).status).toBe(403);
+ });
+
+ it("answers within the proxy's idle limit by default, and a caller may ask for longer", async () => {
+ expect(BOT_API_DEFAULT_WAIT_MS).toBeLessThan(60_000);
+ const h = await harness((fake, _botId, _prompt, opts) => {
+ setTimeout(() => { fake.store.appendMessage(opts.threadId, { role: "bot", kind: "text", text: "Late" }); opts.onSettled({ ok: true, text: "Late" }); }, 300);
+ }, { waitMs: 50 });
+ const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;
+ expect((await h.call("b1", key, { message: "Default" })).body).toMatchObject({ status: "working" });
+ await new Promise((resolve) => setTimeout(resolve, 350));
+ expect((await h.call("b1", key, { message: "Longer", wait: 5 })).body).toMatchObject({ reply: "Late" });
+ expect((await h.call("b1", key, { message: "Too long", wait: 301 })).status).toBe(400);
+ });
+
it("forgets a deleted bot's key and calls", async () => {
const h = await harness(replies("ok"));
const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;
diff --git a/server/bot-api-host.ts b/server/bot-api-host.ts
index 06dc5a30dc..72fb865f33 100644
--- a/server/bot-api-host.ts
+++ b/server/bot-api-host.ts
@@ -5,7 +5,7 @@
import { z } from "zod";
import { redactSecretsInText } from "../shared/redact.ts";
-import { botApiEndpoint, type BotApiReply } from "../shared/bot-api.ts";
+import { BOT_API_UPGRADE, botApiEndpoint, type BotApiReply } from "../shared/bot-api.ts";
import type { AdminActionRow } from "./admin-activity.ts";
import { BOT_API_MAX_MESSAGE_CHARS, BOT_API_MAX_PENDING, BotApiManager, botApiPrompt, withoutAttachedImages, type BotApiAttempt, type BotApiStatus } from "./bot-api.ts";
import type { RequestAuth } from "./request-auth.ts";
@@ -14,8 +14,10 @@ import { parseJson, schemaIssue } from "./schema.ts";
import type { Message, Store } from "./store.ts";
import { bearerSecret, header, json, readRawBody, type IngressDoor } from "./webhook-ingress.ts";
-/** How long a call waits for the reply before answering "working". */
-export const BOT_API_DEFAULT_WAIT_MS = 5 * 60_000;
+/** How long a call waits by default before answering "working" with its thread id. Under the 60 s that Fly's proxy is reported
+ * (community.fly.io, staff replies, 2022-2024) to allow a connection with no bytes: a dropped answer would lose the thread id. */
+export const BOT_API_DEFAULT_WAIT_MS = 50_000;
+const BOT_API_MAX_WAIT_MS = 5 * 60_000;
const POLL_MS = 250;
const PUBLIC_PATH = /^\/hooks\/api\/bots\/([\w-]{1,128})\/messages$/;
const APP_PATH = /^\/api\/bots\/([\w-]{1,128})\/bot-api(?:\/(new-key))?$/;
@@ -23,8 +25,8 @@ const APP_PATH = /^\/api\/bots\/([\w-]{1,128})\/bot-api(?:\/(new-key))?$/;
const callSchema = z.object({
message: z.string().min(1).max(BOT_API_MAX_MESSAGE_CHARS),
thread: z.string().regex(/^[\w-]{1,128}$/).optional(),
- /** Seconds to wait for the reply, within the default. */
- wait: z.number().min(0).max(BOT_API_DEFAULT_WAIT_MS / 1000).optional(),
+ /** Seconds to wait for the reply, for a caller that knows nothing in its path drops a quiet connection. */
+ wait: z.number().min(0).max(BOT_API_MAX_WAIT_MS / 1000).optional(),
});
const switchSchema = z.object({ enabled: z.boolean() });
@@ -45,6 +47,8 @@ export interface BotApiHostDeps {
threadBusy(botId: string, threadId: string): boolean;
/** Whether a new turn would start now, before anything is written. */
canStart(botId: string, threadId: string): boolean;
+ /** False on a plan that doesn't include the Bot API; asked on every call, so an upgrade counts at once. Absent: included. */
+ included?(): boolean;
/** A thread the API just opened: whose it is on a Cloud. */
opened?(threadId: string): void;
/** The webhook receiver's public base, as the app advertises it for webhooks. */
@@ -95,6 +99,7 @@ export function createBotApiHost(deps: BotApiHostDeps) {
const running = new Map<string, Set<string>>();
deps.store.onChange((change) => { if (change.type === "bot.deleted") manager.removeForBot(change.botId); });
+ const included = () => deps.included?.() !== false;
const pendingFor = (botId: string) => {
const set = running.get(botId);
for (const threadId of set ?? []) if (!deps.threadBusy(botId, threadId)) set!.delete(threadId);
@@ -153,7 +158,7 @@ export function createBotApiHost(deps: BotApiHostDeps) {
fail(busy ? 409 : 502, busy ? BUSY : COULD_NOT_ANSWER, error instanceof Error ? error.message : String(error));
}
turnStarted();
- const deadline = Date.now() + Math.min(waitMs, call.wait === undefined ? waitMs : call.wait * 1000);
+ const deadline = Date.now() + (call.wait === undefined ? waitMs : call.wait * 1000);
for (;;) {
if (dispatchError !== undefined) fail(502, COULD_NOT_ANSWER, dispatchError);
if (settled) break;
@@ -191,6 +196,11 @@ export function createBotApiHost(deps: BotApiHostDeps) {
json(res, 401, { error: "Invalid key" });
return true;
}
+ if (!included()) {
+ manager.recordRefused(botId, 403, BOT_API_UPGRADE);
+ json(res, 403, { error: BOT_API_UPGRADE });
+ return true;
+ }
if (req.method === "GET") {
const threadId = url.searchParams.get("thread") ?? "";
const task = /^[\w-]{1,128}$/.test(threadId) ? deps.store.taskByThread(botId, threadId) : undefined;
@@ -240,9 +250,9 @@ export function createBotApiHost(deps: BotApiHostDeps) {
};
/** What callers sent is for the people who manage the key, not everyone who can see the bot. */
- const view = (botId: string, auth: RequestAuth): BotApiStatus & { url: string; canManage: boolean; calls: BotApiAttempt[] } => {
+ const view = (botId: string, auth: RequestAuth): BotApiStatus & { included: boolean; url: string; canManage: boolean; calls: BotApiAttempt[] } => {
const canManage = deps.manageRefusal(auth, botId) === null;
- return { ...manager.status(botId), url: botApiEndpoint(deps.hooksBaseUrl(), botId), canManage, calls: canManage ? manager.listAttempts(botId).slice(-10).reverse() : [] };
+ return { included: included(), ...manager.status(botId), url: botApiEndpoint(deps.hooksBaseUrl(), botId), canManage, calls: canManage ? manager.listAttempts(botId).slice(-10).reverse() : [] };
};
const routes: RouteHandler = async ({ req, res, path, method, auth, json: answer, readBody }) => {
@@ -258,6 +268,7 @@ export function createBotApiHost(deps: BotApiHostDeps) {
const target = { kind: "bot", id: bot.id, name: bot.name };
try {
if (match[2] === "new-key") {
+ if (!included()) return answer(res, 403, { error: BOT_API_UPGRADE, upgrade: true });
if (!manager.enabled(botId)) return answer(res, 409, { error: "The Bot API is off for this bot" });
const minted = manager.enable(botId);
deps.record?.(auth, { category: "bot-api", action: "bot-api.new-key", target });
@@ -267,6 +278,7 @@ export function createBotApiHost(deps: BotApiHostDeps) {
if (!parsed.success) return answer(res, 400, { error: schemaIssue(parsed.error, "Send {\"enabled\": true | false}") });
if (parsed.data.enabled) {
// Already on keeps its key: only New key replaces one an app may be using.
+ if (!included()) return answer(res, 403, { error: BOT_API_UPGRADE, upgrade: true });
if (manager.enabled(botId)) return answer(res, 200, view(botId, auth));
const minted = manager.enable(botId);
deps.record?.(auth, { category: "bot-api", action: "bot-api.on", target });
diff --git a/server/cloud-team-bot-access.e2e.test.ts b/server/cloud-team-bot-access.e2e.test.ts
index a9078befed..eef4eb49de 100644
--- a/server/cloud-team-bot-access.e2e.test.ts
+++ b/server/cloud-team-bot-access.e2e.test.ts
@@ -239,6 +239,28 @@ describe("a team bot shared with a level per person", () => {
await until(idle);
});
+ it("follows the Admin's signed plan on Bot API without a restart, and an Admin that sends none means not Starter", async () => {
+ const path = `/api/bots/${mirror.id}/bot-api`;
+ expect((await team.signed("POST", "/api/cloud/plan", { v: 1, cancelled: false })).status).toBe(200);
+ expect((await as("ada", "GET", path)).body).toMatchObject({ included: true });
+ const key = (await as("ada", "POST", path, { enabled: true })).body.key as string;
+ const hooks = `${team.base.replace(/:(\d+)$/, (_, port) => `:${Number(port) + 1}`)}/hooks/api/bots/${mirror.id}/messages`;
+ const send = () => fetch(hooks, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify({ message: "Plan check", wait: 0 }) });
+
+ expect((await team.signed("POST", "/api/cloud/plan", { v: 1, tier: "starter" })).status).toBe(200);
+ expect((await as("ada", "GET", "/api/config")).body).toMatchObject({ cloudStarter: true });
+ const refused = await send();
+ expect(refused.status).toBe(403);
+ expect(await refused.json()).toEqual({ error: "Bot API comes with a higher plan. Upgrade this Cloud to use it." });
+ expect((await as("ada", "POST", `${path}/new-key`)).status).toBe(403);
+
+ expect((await team.signed("POST", "/api/cloud/plan", { v: 1, tier: "pro" })).status).toBe(200);
+ expect((await as("ada", "GET", "/api/config")).body).toMatchObject({ cloudStarter: false });
+ expect((await send()).status).toBeLessThan(300);
+ await until(idle);
+ expect((await as("ada", "POST", path, { enabled: false })).status).toBe(200);
+ });
+
it("relays another app's message only for a person who can chat with the bot", async () => {
const relay = async (email: string | undefined, n: number) => {
const leaf = (await as("ada", "GET", `/api/threads/${payroll.threadId}/messages?limit=1`)).body.activeLeafId ?? null;
diff --git a/server/host/cloud-plan-tier.test.ts b/server/host/cloud-plan-tier.test.ts
new file mode 100644
index 0000000000..1dcc4eb955
--- /dev/null
+++ b/server/host/cloud-plan-tier.test.ts
@@ -0,0 +1,46 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { CLOUD_PLAN_TIER_FILE, createCloudPlanTier } from "./cloud-plan-tier.ts";
+
+const dirs: string[] = [];
+const dir = () => { const made = mkdtempSync(join(tmpdir(), "omb-plan-tier-")); dirs.push(made); return made; };
+afterEach(() => { for (const made of dirs.splice(0)) rmSync(made, { recursive: true, force: true }); });
+
+describe("which plan this Cloud is on", () => {
+ it("is not Starter until the Admin says so, and follows what it says at once, across a restart", () => {
+ const dataDir = dir();
+ let changes = 0;
+ const plan = createCloudPlanTier({ dataDir, cloudHome: true, changed: () => { changes += 1; } });
+ expect(plan.tier()).toBeUndefined();
+ expect(plan.starter()).toBe(false);
+ plan.set("starter");
+ expect(plan.starter()).toBe(true);
+ expect(createCloudPlanTier({ dataDir, cloudHome: true }).starter()).toBe(true);
+ plan.set("starter");
+ expect(changes).toBe(1);
+ plan.set("pro");
+ expect(plan.starter()).toBe(false);
+ expect(changes).toBe(2);
+ expect(JSON.parse(readFileSync(join(dataDir, CLOUD_PLAN_TIER_FILE), "utf8"))).toEqual({ v: 1, tier: "pro" });
+ });
+
+ it("treats Personal, a damaged file, a malformed tier and a server that is no Cloud as not Starter", () => {
+ const dataDir = dir();
+ const plan = createCloudPlanTier({ dataDir, cloudHome: true });
+ plan.set("personal");
+ expect(plan.starter()).toBe(false);
+ plan.set("NOT A TIER");
+ expect(plan.tier()).toBe("personal");
+ writeFileSync(join(dataDir, CLOUD_PLAN_TIER_FILE), "{broken");
+ expect(createCloudPlanTier({ dataDir, cloudHome: true }).starter()).toBe(false);
+ const desktop = createCloudPlanTier({ dataDir: dir(), cloudHome: false });
+ desktop.set("starter");
+ expect(desktop.starter()).toBe(false);
+ const leftover = dir();
+ writeFileSync(join(leftover, CLOUD_PLAN_TIER_FILE), JSON.stringify({ v: 1, tier: "starter" }));
+ expect(createCloudPlanTier({ dataDir: leftover, cloudHome: false }).starter()).toBe(false);
+ });
+});
diff --git a/server/host/cloud-plan-tier.ts b/server/host/cloud-plan-tier.ts
new file mode 100644
index 0000000000..e8c4b3fd97
--- /dev/null
+++ b/server/host/cloud-plan-tier.ts
@@ -0,0 +1,45 @@
+// Which plan this Cloud is on, as the Admin last said in its signed POST /api/cloud/plan. Kept in a file so a restart keeps
+// it. An Admin that never said, a damaged file, and anything that is not a Cloud home all read as not Starter: a limit never
+// lands on someone by accident of a missing signal.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { z } from "zod";
+
+import { writeFileAtomic } from "../atomic.ts";
+
+export const CLOUD_PLAN_TIER_FILE = "cloud-plan-tier.json";
+export const CLOUD_TIER = /^[a-z][a-z0-9_-]{0,31}$/;
+const fileSchema = z.object({ v: z.literal(1), tier: z.string().regex(CLOUD_TIER) });
+
+export interface CloudPlanTier {
+ tier(): string | undefined;
+ starter(): boolean;
+ set(tier: string): void;
+}
+
+export function createCloudPlanTier(deps: { dataDir: string; cloudHome: boolean; changed?: () => void }): CloudPlanTier {
+ const file = join(deps.dataDir, CLOUD_PLAN_TIER_FILE);
+ let tier: string | undefined;
+ if (deps.cloudHome) {
+ try {
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
+ if (parsed.success) tier = parsed.data.tier;
+ } catch {
+ // none yet, or unreadable: not Starter
+ }
+ }
+ return {
+ tier: () => tier,
+ starter: () => tier === "starter",
+ set(next) {
+ if (!deps.cloudHome || !CLOUD_TIER.test(next) || next === tier) return;
+ tier = next;
+ try {
+ writeFileAtomic(file, `${JSON.stringify({ v: 1, tier: next })}\n`, { mode: 0o600 });
+ } catch (error) {
+ console.warn(`cloud plan: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ deps.changed?.();
+ },
+ };
+}
diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.ts
index 959cf68296..1cb4cb5aaf 100644
--- a/server/host/cloud-signed-host.ts
+++ b/server/host/cloud-signed-host.ts
@@ -24,6 +24,8 @@ export interface CloudSignedHostDeps {
policyChanged?: () => void;
/** The plan was cancelled, or renews again (the Admin's signed request): routines wait while it is cancelled. */
plan?: (cancelled: boolean) => void;
+ /** Which plan this Cloud is on now (the Admin's signed request). */
+ planTier?: (tier: string) => void;
}
export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth: CloudHealth | null; cloudSigned: ReturnType<typeof createCloudSignedRoutes> | null } {
@@ -31,7 +33,7 @@ export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth:
const cloudSigned = deps.cloudHome && cloudHealth
? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,
...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}),
- ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}) })
+ ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}), ...(deps.planTier ? { planTier: deps.planTier } : {}) })
: null;
return { cloudHealth, cloudSigned };
}
diff --git a/server/index.ts b/server/index.ts
index a3240b70dc..e805385ff1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -474,7 +474,7 @@ import { createOutboundHold, OUTBOUND_HOLD_MS, type OutboundHoldAnswer } from ".
import { connectorCallsIn, outboundCallsIn } from "../shared/outbound.ts";
import { connectorAccessDecision, describeConnectorScopes } from "../shared/connector-scopes.ts";
import { bindThreadLogCapProvider } from "./thread-log-rotation.ts";
-import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"; import { createBotApiHost } from "./bot-api-host.ts";
+import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"; import { createBotApiHost } from "./bot-api-host.ts"; import { createCloudPlanTier } from "./host/cloud-plan-tier.ts";
import { addressFor } from "./webhook-address.ts";
import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";
import { WebhookManager } from "./webhooks.ts";
@@ -2887,8 +2887,8 @@ const phones = createPhones({
mint: (botId, turn) => mintInternalCapability({ botId, ...turn, kind: "device", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }),
active: (turn) => internalCapabilityIsActive(turn as InternalCapability),
});
-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), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { 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,
+const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); 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) => { 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: () => highlevelHost.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() } : {}) } });
@@ -9640,7 +9640,7 @@ const webhooks = new WebhookManager({
if (!forceNew && trigger.resultsThreadId && store.taskByThread(trigger.botId, trigger.resultsThreadId)) return trigger.resultsThreadId;
return store.createTask(trigger.botId, "Updates", false)?.threadId;
}, ...createWebhookRoomPost({ store, cfg, roomTalks }) });
-const webhookRequests = new WebhookRequestService({ store, webhooks, botName: (botId) => store.bot(botId)?.name ?? "the bot" }); const botApi = createBotApiHost({ store, startTurn, threadBusy, canStart: canAdmitDirectTurn, opened: (threadId) => { if (CLOUD_OWNER_KEY) threadStarters.set(threadId, CLOUD_OWNER_KEY); }, hooksBaseUrl: () => webhookIngressStatus().baseUrl, manageRefusal: (auth, botId) => auth.scopes.includes("admin") || (CLOUD_TEAM && levelOf(auth, botId) === "edit") ? null : refusalFor(store.bot(botId)?.name ?? "this bot", "edit"), claimRequest: () => { cloudPower?.arrived("/hooks", {}); moveFreeze.assertTurns(); return workspaceMaintenance.request(); }, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) });
+const webhookRequests = new WebhookRequestService({ store, webhooks, botName: (botId) => store.bot(botId)?.name ?? "the bot" }); const botApi = createBotApiHost({ store, startTurn, threadBusy, canStart: canAdmitDirectTurn, included: () => !cloudPlanTier.starter(), opened: (threadId) => { if (CLOUD_OWNER_KEY) threadStarters.set(threadId, CLOUD_OWNER_KEY); }, hooksBaseUrl: () => webhookIngressStatus().baseUrl, manageRefusal: (auth, botId) => auth.scopes.includes("admin") || (CLOUD_TEAM && levelOf(auth, botId) === "edit") ? null : refusalFor(store.bot(botId)?.name ?? "this bot", "edit"), claimRequest: () => { cloudPower?.arrived("/hooks", {}); moveFreeze.assertTurns(); return workspaceMaintenance.request(); }, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) });
const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => webhookIngressStatus().baseUrl, routines: () => routines!, botState: unattendedDispatchState, timeZone: routineTimeZone, emit: broadcast, connectionMode: () => composio.connectionMode(cfg),
access: composio.brokerAccess, connectedApps: () => composio.connectedServices(cfg), visibleBot: (auth, botId) => visibleTo(viewerFor(auth)).bot(botId),
audit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });
@@ -11872,7 +11872,7 @@ function configStatus() {
const eventLogMaxBytes = threadEventLogMaxBytes(cfg);
const eventLogRetentionDays = threadEventLogRetentionDays(cfg);
return {
- xai: keyStatus(cfg.xai?.key),
+ cloudStarter: cloudPlanTier.starter(), xai: keyStatus(cfg.xai?.key),
mistral: keyStatus(cfg.mistral?.key),
cerebras: keyStatus(cfg.cerebras?.key),
groq: keyStatus(cfg.groq?.key), greenference: keyStatus(cfg.greenference?.key),
diff --git a/server/routes/cloud-signed-plan.test.ts b/server/routes/cloud-signed-plan.test.ts
index 4f7592fdd8..5f96553a42 100644
--- a/server/routes/cloud-signed-plan.test.ts
+++ b/server/routes/cloud-signed-plan.test.ts
@@ -14,14 +14,14 @@ const secret = "S".repeat(43);
function routes(withPlan = true) {
let counter = 0;
const now = () => 1_800_000_000_000;
- const told: boolean[] = [];
+ const told: boolean[] = [], tiers: string[] = [];
const sessions = new SessionRegistry({ file: join(DATA_DIR, "sessions.json"), now });
const health = createCloudHealth({
store: { onChange: () => () => {}, botByThread: () => null, bots: [] }, bus: { subscribe: () => () => {} },
engines: () => [], dataDir: DATA_DIR, eventsDir: DATA_DIR, version: "0.1.0", image: undefined, connectors: () => null,
browser: () => ({ available: true, installing: false, interrupted: 0 }), now,
});
- const handle = createCloudSignedRoutes({ secret, sessions, health, now, ...(withPlan ? { plan: (cancelled: boolean) => { told.push(cancelled); } } : {}) });
+ const handle = createCloudSignedRoutes({ secret, sessions, health, now, ...(withPlan ? { plan: (cancelled: boolean) => { told.push(cancelled); }, planTier: (tier: string) => { tiers.push(tier); } } : {}) });
const sign = (body: string, key = secret, method = "POST") => {
const timestamp = String(Math.floor(now() / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;
return { "content-type": "application/json", "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,
@@ -36,10 +36,31 @@ function routes(withPlan = true) {
(req as unknown as PassThrough).end(body);
return { answered: await answered, status, body: text ? JSON.parse(text) : null };
};
- return { sign, send, told };
+ return { sign, send, told, tiers };
}
describe("POST /api/cloud/plan", () => {
+ it("takes which plan this Cloud is on, alone or with the cancelled word, and leaves it alone when an older Admin says nothing of it", async () => {
+ const { sign, send, told, tiers } = routes();
+ const post = (value: unknown) => { const body = JSON.stringify(value); return send("POST", sign(body), body); };
+ expect((await post({ v: 1, tier: "starter" })).status).toBe(200);
+ expect(tiers).toEqual(["starter"]);
+ expect(told).toEqual([]);
+ expect((await post({ v: 1, cancelled: false })).status).toBe(200);
+ expect(tiers).toEqual(["starter"]);
+ expect(told).toEqual([false]);
+ expect((await post({ v: 1, cancelled: true, tier: "pro" })).status).toBe(200);
+ expect(tiers).toEqual(["starter", "pro"]);
+ for (const bad of [{ v: 1 }, { v: 1, tier: "NOT A TIER" }, { v: 1, tier: 3 }, { v: 1, cancelled: false, tier: "../x" }, { v: 1, cancelled: "yes", tier: "pro" }]) {
+ expect(await post(bad)).toMatchObject({ status: 400, body: { error: "invalid_plan" } });
+ }
+ expect(tiers).toEqual(["starter", "pro"]);
+ expect(told).toEqual([false, true]);
+ const forged = JSON.stringify({ v: 1, tier: "max" });
+ expect((await send("POST", sign(forged, "F".repeat(43)), forged)).status).toBe(401);
+ expect(tiers).toEqual(["starter", "pro"]);
+ });
+
it("takes the Admin's signed word that the plan was cancelled, or renews again", async () => {
const { sign, send, told } = routes();
const cancelled = JSON.stringify({ v: 1, cancelled: true });
diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.ts
index fb9ca9969d..3c490f6942 100644
--- a/server/routes/cloud-signed.ts
+++ b/server/routes/cloud-signed.ts
@@ -2,6 +2,7 @@
// log their headers, bodies or codes. A bad pairing signature counts against the pairing lockout; a health or power read
// opens nothing, so each route has its own nonces and never locks the Admin out of pairing. The power routes are the sleep
// handshake of a plan that sleeps (server/cloud-power.ts); the Admin calls them for no other plan.
+import { CLOUD_TIER } from "../host/cloud-plan-tier.ts";
import type { IncomingMessage, ServerResponse } from "node:http";
import type { BoxReport } from "../bot-box/box.ts";
import { boxSummary } from "../cloud-health.ts";
@@ -24,8 +25,8 @@ export const CLOUD_BOX_PATH = "/api/cloud/box";
* theirs alone is deleted here (host/team-member-left.ts). */
export const CLOUD_TEAM_MEMBER_LEFT_PATH = "/api/cloud/team/member-left";
-/** The plan was cancelled, or renews again: `{"v":1,"cancelled":true|false}`, signed with the body like the sleep request.
- * While it is cancelled the home's routines wait (host/routine-holds-host.ts). */
+/** The Admin's word on the plan, signed with the body like the sleep request: `{"v":1,"cancelled":true|false}`, `{"v":1,"tier":"starter"}`,
+ * or both. While it is cancelled the home's routines wait (host/routine-holds-host.ts); the tier is kept by host/cloud-plan-tier.ts. */
export const CLOUD_PLAN_PATH = "/api/cloud/plan";
export function createCloudSignedRoutes(deps: {
@@ -46,6 +47,8 @@ export function createCloudSignedRoutes(deps: {
policyChanged?: (() => void) | null;
/** The plan was cancelled (true) or renews again (false); absent on a server that is not a Cloud home. */
plan?: ((cancelled: boolean) => void) | null;
+ /** Which plan this Cloud is on now; absent on a server that is not a Cloud home. */
+ planTier?: ((tier: string) => void) | null;
now?: () => number;
}) {
const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, now: deps.now });
@@ -62,7 +65,7 @@ export function createCloudSignedRoutes(deps: {
const power = path === CLOUD_POWER_PATH || path === CLOUD_POWER_SLEEP_PATH ? deps.power?.() ?? null : null;
const teamAdmin = path === CLOUD_TEAM_ADMIN_PATH && deps.team ? deps.teamAdmin ?? null : null;
const memberLeft = path === CLOUD_TEAM_MEMBER_LEFT_PATH && deps.team ? deps.memberLeft ?? null : null;
- const plan = path === CLOUD_PLAN_PATH ? deps.plan ?? null : null;
+ const plan = path === CLOUD_PLAN_PATH && (deps.plan || deps.planTier) ? true : null;
const policyChanged = path === CLOUD_TEAM_POLICY_CHANGED_PATH && deps.team ? deps.policyChanged ?? null : null;
if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan && !policyChanged) return false;
res.setHeader("cache-control", "no-store");
@@ -128,9 +131,11 @@ export function createCloudSignedRoutes(deps: {
if (!verdict.ok) { console.warn(`cloud plan request refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }
let parsed: unknown;
try { parsed = JSON.parse(body.toString("utf8")); } catch { json(res, 400, { error: "invalid_body" }); return true; }
- const cancelled = (parsed as { cancelled?: unknown } | null)?.cancelled;
- if (typeof cancelled !== "boolean") { json(res, 400, { error: "invalid_plan" }); return true; }
- plan(cancelled);
+ const { cancelled, tier } = (parsed ?? {}) as { cancelled?: unknown; tier?: unknown };
+ const saysCancelled = typeof cancelled === "boolean", saysTier = typeof tier === "string" && CLOUD_TIER.test(tier);
+ if ((cancelled !== undefined && !saysCancelled) || (tier !== undefined && !saysTier) || (!saysCancelled && !saysTier)) { json(res, 400, { error: "invalid_plan" }); return true; }
+ if (saysCancelled) deps.plan?.(cancelled);
+ if (saysTier) deps.planTier?.(tier);
json(res, 200, { ok: true });
return true;
}
diff --git a/shared/bot-api.ts b/shared/bot-api.ts
index 856ed50f9a..1c36759fe4 100644
--- a/shared/bot-api.ts
+++ b/shared/bot-api.ts
@@ -1,6 +1,8 @@
/** The Bot API's public address and the command the app shows for it. The receiver that takes webhooks
* (`<base>/hooks/…`) takes these calls too, so a Cloud and a self-hosted edge need no second route. */
export const BOT_API_KEY_PLACEHOLDER = "YOUR_KEY";
+/** What a caller or a person is told on the Starter plan. */
+export const BOT_API_UPGRADE = "Bot API comes with a higher plan. Upgrade this Cloud to use it.";
export function botApiEndpoint(hooksBaseUrl: string, botId: string): string {
return `${hooksBaseUrl.replace(/\/+$/, "")}/hooks/api/bots/${encodeURIComponent(botId)}/messages`;
diff --git a/src/components/bot-settings/BotApiCard.dom.test.ts b/src/components/bot-settings/BotApiCard.dom.test.ts
index a239e41509..5965a55d86 100644
--- a/src/components/bot-settings/BotApiCard.dom.test.ts
+++ b/src/components/bot-settings/BotApiCard.dom.test.ts
@@ -8,15 +8,20 @@ import { setLocale } from "@/lib/i18n";
import type { Bot } from "@/state/store";
const URL_ = "https://scout.example.test/hooks/api/bots/b1/messages";
-const fixture = vi.hoisted(() => ({ view: null as Record<string, unknown> | null, sent: [] as Array<{ path: string; body?: unknown }>, dispatched: [] as unknown[], copied: [] as string[], minted: 0 }));
+const fixture = vi.hoisted(() => ({ view: null as Record<string, unknown> | null, sent: [] as Array<{ path: string; body?: unknown }>, read: [] as string[], dispatched: [] as unknown[], copied: [] as string[], minted: 0, starter: false, bridge: true, upgrades: 0 }));
+vi.mock("../CloudUsageMeter", () => ({
+ NoteLine: () => null,
+ useCloudUsage: () => (fixture.bridge ? { usage: { tier: "starter" }, bridge: {} } : { usage: null, bridge: undefined }),
+ useUpgrade: () => ({ busy: null, note: null, dialog: null, start: () => { fixture.upgrades += 1; } }),
+}));
vi.mock("@/lib/copy-text", () => ({ copyText: async (text: string) => { fixture.copied.push(text); return "copied"; } }));
vi.mock("@/state/store", async (importOriginal) => {
const original = await importOriginal<typeof import("@/state/store")>();
return {
...original,
- useStore: () => ({ state: { webhooks: [{ botId: "b1" }, { botId: "b1" }, { botId: "b2" }] }, dispatch: (action: unknown) => fixture.dispatched.push(action) }),
+ useStore: () => ({ state: { config: { cloudStarter: fixture.starter }, webhooks: [{ botId: "b1" }, { botId: "b1" }, { botId: "b2" }] }, dispatch: (action: unknown) => fixture.dispatched.push(action) }),
api: async (path: string, init?: { method?: string; body?: string }) => {
- if (init?.method !== "POST") return fixture.view;
+ if (init?.method !== "POST") { fixture.read.push(path); return fixture.view; }
fixture.sent.push({ path, body: init.body ? JSON.parse(init.body) : undefined });
const wants = init.body ? (JSON.parse(init.body) as { enabled: boolean }).enabled : true;
fixture.view = { ...fixture.view, enabled: wants };
@@ -38,7 +43,7 @@ const click = async (id: string) => { flushSync(() => find(id)!.click()); await
beforeEach(() => {
setLocale("en");
- Object.assign(fixture, { view: { enabled: false, url: URL_, canManage: true, callCount: 0, calls: [] }, sent: [], dispatched: [], copied: [], minted: 0 });
+ Object.assign(fixture, { view: { enabled: false, url: URL_, canManage: true, callCount: 0, calls: [] }, sent: [], read: [], dispatched: [], copied: [], minted: 0, starter: false, bridge: true, upgrades: 0 });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -46,6 +51,36 @@ beforeEach(() => {
afterEach(() => { flushSync(() => root.unmount()); host.remove(); });
describe("the Bot API card", () => {
+ it("on Starter is one line and the usual Upgrade: no switch, no key, no command, and nothing asked of the server", async () => {
+ fixture.starter = true;
+ Object.assign(fixture.view!, { enabled: true });
+ await mount({ webhooksLink: true });
+ expect(find("bot-api-starter")!.textContent).toBe("Bot API comes with a higher plan.");
+ for (const gone of ["bot-api-switch", "bot-api-curl", "bot-api-copy", "bot-api-new-key", "bot-api-key-note", "bot-api-webhooks"]) expect(find(gone), gone).toBeNull();
+ expect(fixture.read).toEqual([]);
+ await click("bot-api-upgrade");
+ expect(fixture.upgrades).toBe(1);
+ });
+
+ it("on Starter with no way to change the plan from this page, shows the line alone", async () => {
+ fixture.starter = true;
+ fixture.bridge = false;
+ await mount();
+ expect(find("bot-api-starter")).not.toBeNull();
+ expect(find("bot-api-upgrade")).toBeNull();
+ });
+
+ it("comes back as soon as the plan is no longer Starter, and says a key is like a password", async () => {
+ fixture.starter = true;
+ Object.assign(fixture.view!, { enabled: true });
+ await mount();
+ expect(find("bot-api-switch")).toBeNull();
+ fixture.starter = false;
+ await mount({ className: "x" });
+ expect(find("bot-api-switch")).not.toBeNull();
+ expect(find("bot-api-password")!.textContent).toBe("A key is like a password: whoever holds it can read what this bot can read.");
+ });
+
it("is off with no command until switched on", async () => {
await mount();
expect(find("bot-api")!.textContent).toContain("Bot API");
diff --git a/src/components/bot-settings/BotApiCard.tsx b/src/components/bot-settings/BotApiCard.tsx
index c32a295d69..5a4246e15d 100644
--- a/src/components/bot-settings/BotApiCard.tsx
+++ b/src/components/bot-settings/BotApiCard.tsx
@@ -6,7 +6,8 @@ import { copyText } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { relativeTime } from "@/lib/memory";
import { api, useStore, type Bot } from "@/state/store";
-import { BOT_API_KEY_PLACEHOLDER, botApiCurl } from "../../../shared/bot-api";
+import { BOT_API_KEY_PLACEHOLDER, BOT_API_UPGRADE, botApiCurl } from "../../../shared/bot-api";
+import { NoteLine, useCloudUsage, useUpgrade } from "../CloudUsageMeter";
import { Switch } from "../SettingsPrimitives";
export interface BotApiCall {
@@ -39,8 +40,9 @@ export function callsLine(view: Pick<BotApiView, "callCount" | "lastCalledAt">,
return view.callCount === 1 ? t("botApi.callsOne", { when }) : t("botApi.calls", { count: view.callCount, when });
}
-export function callWords(call: Pick<BotApiCall, "outcome" | "statusCode" | "repeats">): string {
- const words = call.statusCode === 200 ? t("botApi.call.replied")
+export function callWords(call: Pick<BotApiCall, "outcome" | "statusCode" | "repeats" | "reason">): string {
+ const words = call.reason === BOT_API_UPGRADE ? t("botApi.starter")
+ : call.statusCode === 200 ? t("botApi.call.replied")
: call.statusCode === 202 ? t("botApi.call.accepted")
: call.statusCode === 401 ? t("botApi.call.wrongKey")
: call.statusCode === 403 ? t("botApi.call.off")
@@ -58,8 +60,31 @@ export function webhooksLine(count: number): string {
return count === 0 ? t("botApi.webhooksNone") : count === 1 ? t("botApi.webhooksOne") : t("botApi.webhooks", { count });
}
+/** Starter: one line and the usual Upgrade (its preview, then the person's confirmation). Where this page has no way to change the
+ * plan, a browser tab on the Cloud's own address, the line stands alone. */
+function BotApiStarter({ className }: { className?: string }) {
+ const { usage, bridge } = useCloudUsage();
+ const upgrade = useUpgrade(bridge, usage, "app_settings");
+ return (
+ <div className={cn("rounded-xl bg-card p-4", className)} data-testid="bot-api">
+ <div className="text-[15px] font-medium text-ink">{t("botApi.title")}</div>
+ <div className="mt-0.5 text-[13px] text-ink-secondary" data-testid="bot-api-starter">{t("botApi.starter")}</div>
+ {bridge && usage && (
+ <button type="button" onClick={() => upgrade.start()} disabled={upgrade.busy !== null} className={cn(buttonCls, "mt-3")} data-testid="bot-api-upgrade">{t("roomCard.upgrade")}</button>
+ )}
+ {upgrade.note && <div className="mt-2"><NoteLine note={upgrade.note} /></div>}
+ {upgrade.dialog}
+ </div>
+ );
+}
+
/** The Bot API, the same in the bot panel and in Bot settings: a switch, the key once, the command to paste. */
-export function BotApiCard({ bot, webhooksLink = false, className }: { bot: Bot; webhooksLink?: boolean; className?: string }) {
+export function BotApiCard(props: { bot: Bot; webhooksLink?: boolean; className?: string }) {
+ const { state } = useStore();
+ return state.config?.cloudStarter === true ? <BotApiStarter className={props.className} /> : <BotApiSection {...props} />;
+}
+
+function BotApiSection({ bot, webhooksLink = false, className }: { bot: Bot; webhooksLink?: boolean; className?: string }) {
const { state, dispatch } = useStore();
const [view, setView] = useState<BotApiView | null>(null);
const [freshKey, setFreshKey] = useState<string | null>(null);
@@ -131,6 +156,7 @@ export function BotApiCard({ bot, webhooksLink = false, className }: { bot: Bot;
<div className={cn("text-[12px]", freshKey ? "text-warning" : "text-ink-secondary")} data-testid="bot-api-key-note">
{freshKey ? t("botApi.keyOnce") : t("botApi.keyHidden")}
</div>
+ <div className="text-[12px] text-ink-secondary" data-testid="bot-api-password">{t("botApi.password")}</div>
{onlyThisComputer(view.url) && <div className="text-[12px] text-ink-secondary" data-testid="bot-api-local">{t("botApi.localOnly")}</div>}
{canManage && (
confirmingNewKey ? (
diff --git a/src/locales/de.json b/src/locales/de.json
index cc1b1b01e6..8c5582d61e 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -2867,5 +2867,7 @@
"botApi.call.wrongKey": "Falscher Schlüssel",
"botApi.call.off": "Abgewiesen: Bot API war aus",
"botApi.call.busy": "Abgewiesen: der Bot war beschäftigt",
- "botApi.call.failed": "Der Bot konnte nicht antworten"
+ "botApi.call.failed": "Der Bot konnte nicht antworten",
+ "botApi.starter": "Bot API ist in einem höheren Tarif enthalten.",
+ "botApi.password": "Ein Schlüssel ist wie ein Passwort: Wer ihn hat, kann lesen, was dieser Bot lesen kann."
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 1d238aa1dc..f2f31709db 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7409,5 +7409,7 @@
"botApi.call.wrongKey": "Wrong key",
"botApi.call.off": "Turned away: Bot API was off",
"botApi.call.busy": "Turned away: the bot was busy",
- "botApi.call.failed": "The bot couldn't answer"
+ "botApi.call.failed": "The bot couldn't answer",
+ "botApi.starter": "Bot API comes with a higher plan.",
+ "botApi.password": "A key is like a password: whoever holds it can read what this bot can read."
}
diff --git a/src/locales/es.json b/src/locales/es.json
index 99bd3f5060..769b45eee5 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -5762,5 +5762,7 @@
"botApi.call.wrongKey": "Clave incorrecta",
"botApi.call.off": "Rechazada: Bot API estaba desactivada",
"botApi.call.busy": "Rechazada: el bot estaba ocupado",
- "botApi.call.failed": "El bot no pudo responder"
+ "botApi.call.failed": "El bot no pudo responder",
+ "botApi.starter": "Bot API viene con un plan superior.",
+ "botApi.password": "Una clave es como una contraseña: quien la tenga puede leer lo que este bot puede leer."
}
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 5bbfa75ed4..03db13df0d 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -2813,5 +2813,7 @@
"botApi.call.wrongKey": "Clé incorrecte",
"botApi.call.off": "Refusé : Bot API était désactivé",
"botApi.call.busy": "Refusé : le bot était occupé",
- "botApi.call.failed": "Le bot n’a pas pu répondre"
+ "botApi.call.failed": "Le bot n’a pas pu répondre",
+ "botApi.starter": "Bot API est inclus dans une offre supérieure.",
+ "botApi.password": "Une clé est comme un mot de passe : qui la détient peut lire ce que ce bot peut lire."
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index df02e98fda..c719631924 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -2813,5 +2813,7 @@
"botApi.call.wrongKey": "गलत कुंजी",
"botApi.call.off": "लौटाया गया: Bot API बंद था",
"botApi.call.busy": "लौटाया गया: बॉट व्यस्त था",
- "botApi.call.failed": "बॉट जवाब नहीं दे सका"
+ "botApi.call.failed": "बॉट जवाब नहीं दे सका",
+ "botApi.starter": "Bot API ऊँचे प्लान के साथ आता है।",
+ "botApi.password": "कुंजी पासवर्ड जैसी है: जिसके पास यह है, वह वह सब पढ़ सकता है जो यह बॉट पढ़ सकता है।"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index 2a566f8864..1bc7a589d7 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -6459,5 +6459,7 @@
"botApi.call.wrongKey": "Chiave errata",
"botApi.call.off": "Rifiutata: Bot API era disattivata",
"botApi.call.busy": "Rifiutata: il bot era occupato",
- "botApi.call.failed": "Il bot non ha potuto rispondere"
+ "botApi.call.failed": "Il bot non ha potuto rispondere",
+ "botApi.starter": "Bot API è incluso in un piano superiore.",
+ "botApi.password": "Una chiave è come una password: chi la possiede può leggere ciò che questo bot può leggere."
}
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 974f5aa3a9..520ff8073c 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -6685,5 +6685,7 @@
"botApi.call.wrongKey": "キーが違います",
"botApi.call.off": "拒否: Bot API はオフでした",
"botApi.call.busy": "拒否: ボットは取り込み中でした",
- "botApi.call.failed": "ボットは返事できませんでした"
+ "botApi.call.failed": "ボットは返事できませんでした",
+ "botApi.starter": "Bot API は上位プランで使えます。",
+ "botApi.password": "キーはパスワードと同じです。持っている人は、このボットが読めるものを読めます。"
}
diff --git a/src/locales/ko.json b/src/locales/ko.json
index 038030a2bd..3b1f249188 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -7187,5 +7187,7 @@
"botApi.call.wrongKey": "잘못된 키",
"botApi.call.off": "거부됨: Bot API가 꺼져 있었음",
"botApi.call.busy": "거부됨: 봇이 바빴음",
- "botApi.call.failed": "봇이 답할 수 없었음"
+ "botApi.call.failed": "봇이 답할 수 없었음",
+ "botApi.starter": "Bot API는 상위 요금제에 포함됩니다.",
+ "botApi.password": "키는 비밀번호와 같습니다. 키를 가진 사람은 이 봇이 읽을 수 있는 것을 읽을 수 있습니다."
}
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 111847a132..bb0b615f1e 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -6582,5 +6582,7 @@
"botApi.call.wrongKey": "Zły klucz",
"botApi.call.off": "Odrzucono: Bot API było wyłączone",
"botApi.call.busy": "Odrzucono: bot był zajęty",
- "botApi.call.failed": "Bot nie mógł odpowiedzieć"
+ "botApi.call.failed": "Bot nie mógł odpowiedzieć",
+ "botApi.starter": "Bot API jest dostępne w wyższym planie.",
+ "botApi.password": "Klucz jest jak hasło: kto go ma, może czytać to, co może czytać ten bot."
}
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index a133d50411..674e2ff2ee 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -6443,5 +6443,7 @@
"botApi.call.wrongKey": "Chave errada",
"botApi.call.off": "Recusada: Bot API estava desligada",
"botApi.call.busy": "Recusada: o bot estava ocupado",
- "botApi.call.failed": "O bot não conseguiu responder"
+ "botApi.call.failed": "O bot não conseguiu responder",
+ "botApi.starter": "A Bot API vem com um plano superior.",
+ "botApi.password": "Uma chave é como uma senha: quem a tem pode ler o que este bot pode ler."
}
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 31609031db..54045c610e 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -6663,5 +6663,7 @@
"botApi.call.wrongKey": "Неверный ключ",
"botApi.call.off": "Отклонено: Bot API был выключен",
"botApi.call.busy": "Отклонено: бот был занят",
- "botApi.call.failed": "Бот не смог ответить"
+ "botApi.call.failed": "Бот не смог ответить",
+ "botApi.starter": "Bot API входит в более высокий тариф.",
+ "botApi.password": "Ключ — как пароль: у кого он есть, тот может читать то, что может читать этот бот."
}
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 42fc759d5f..1a7dc1d138 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5253,5 +5253,7 @@
"botApi.call.wrongKey": "Yanlış anahtar",
"botApi.call.off": "Reddedildi: Bot API kapalıydı",
"botApi.call.busy": "Reddedildi: bot meşguldü",
- "botApi.call.failed": "Bot yanıtlayamadı"
+ "botApi.call.failed": "Bot yanıtlayamadı",
+ "botApi.starter": "Bot API daha yüksek bir planla gelir.",
+ "botApi.password": "Anahtar parola gibidir: ona sahip olan, bu botun okuyabildiğini okuyabilir."
}
diff --git a/src/locales/uk.json b/src/locales/uk.json
index 1a46266f57..bd2b2ffd0e 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -3256,5 +3256,7 @@
"botApi.call.wrongKey": "Неправильний ключ",
"botApi.call.off": "Відхилено: Bot API було вимкнено",
"botApi.call.busy": "Відхилено: бот був зайнятий",
- "botApi.call.failed": "Бот не зміг відповісти"
+ "botApi.call.failed": "Бот не зміг відповісти",
+ "botApi.starter": "Bot API входить до вищого плану.",
+ "botApi.password": "Ключ — як пароль: хто його має, може читати те, що може читати цей бот."
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 2e29aa55b7..53d79a22ec 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5253,5 +5253,7 @@
"botApi.call.wrongKey": "Sai khóa",
"botApi.call.off": "Bị từ chối: Bot API đang tắt",
"botApi.call.busy": "Bị từ chối: bot đang bận",
- "botApi.call.failed": "Bot không trả lời được"
+ "botApi.call.failed": "Bot không trả lời được",
+ "botApi.starter": "Bot API có trong gói cao hơn.",
+ "botApi.password": "Khóa giống như mật khẩu: ai giữ khóa đều đọc được những gì bot này đọc được."
}
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 93d96155a5..45a34cb9b8 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4644,5 +4644,7 @@
"botApi.call.wrongKey": "金鑰錯誤",
"botApi.call.off": "已拒絕:Bot API 已關閉",
"botApi.call.busy": "已拒絕:機器人忙碌中",
- "botApi.call.failed": "機器人無法回答"
+ "botApi.call.failed": "機器人無法回答",
+ "botApi.starter": "Bot API 包含在更高的方案中。",
+ "botApi.password": "金鑰就像密碼:持有它的人可以讀取此機器人能讀取的內容。"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 889218054e..1205d6124a 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -7387,5 +7387,7 @@
"botApi.call.wrongKey": "密钥错误",
"botApi.call.off": "已拒绝:Bot API 已关闭",
"botApi.call.busy": "已拒绝:机器人正忙",
- "botApi.call.failed": "机器人无法回答"
+ "botApi.call.failed": "机器人无法回答",
+ "botApi.starter": "Bot API 包含在更高的套餐中。",
+ "botApi.password": "密钥就像密码:持有它的人可以读取此机器人能读取的内容。"
}
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index 337c057f67..0d6e5814a1 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -135,6 +135,8 @@ export interface ConfigStatus {
/** This server is an OMB Cloud home: it offers no "this computer" and no
* Local VM (server/cloud-home.ts). Absent everywhere else. */
cloudHome?: boolean;
+ /** This Cloud is on the Starter plan, as the Admin last said; absent or false otherwise. */
+ cloudStarter?: boolean;
/** A Team Cloud: the team this server is the home of, and the Plan page (MausBot Cloud) where its people and plan
* are managed. Absent everywhere else. */
team?: { id: string; name: string; cloudPage?: string };