Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { randomUUID } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
import { z } from "zod";
import { ROOM_VIEW_ONLY } from "../../shared/app.ts";
import { approvalModeFor } from "../../shared/approval-mode.ts";
import { isPersistentQuestionCard } from "../../shared/ask-question.ts";
import { normalizeReaction, reactionAnswer } from "../../shared/reactions.ts";
import type { WidgetAction } from "../../shared/widget.ts";
import { parseFollowUp } from "../../shared/follow-up.ts";
import { personWait } from "../../shared/person-wait.ts";
import type { ResolvedSender } from "../../shared/wire.ts";
import { admit } from "../admission.ts";
import { dismissQuestionCard } from "../card-dismissal.ts";
import { AppMessageRate, appContextBlock, prepareAppMessage } from "../chat-apps.ts";
import { prepareWidgetPress, reopenCancelledPress } from "../chat-widgets.ts";
import type { ModelSelection, RequestOutcome, SteerOutcome } from "../contracts.ts";
import { parseDataContext, type DataContext } from "../data-context.ts";
import { OPEN_PAGE_BAD, openPageBlock } from "../open-page.ts";
import { preparePointed } from "../pointed.ts";
import type { Handoffs } from "../delta-context.ts";
import type { OneOnOneGoals } from "../host/one-on-one-goals.ts";
import type { ProviderRegistry } from "../harness/registry.ts";
import { spokenLineFields } from "../live-call-record.ts";
import { messageTextRefusal } from "../message-text.ts";
import { stopReachesLiveTurn } from "../person-stops.ts";
import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";
import type { ReplyTarget } from "../replies.ts";
import type { RequestAuth } from "../request-auth.ts";
import type { RoutineManager } from "../routines.ts";
import { acceptedSendMatch, parseSendId } from "../send-idempotency.ts";
import type { DirectSendInput, DirectSendReceipt } from "../direct-send.ts";
import { cancelSteeredMessage, holdSteeredQueue, queuedSteerSender, queuedSteeredMessage, restoreHeldSteeredQueue, settleHeldSteeredQueue } from "../steer-queue.ts";
import { routeRunOwners, type Actor, type RouteRunOwners } from "../host/run-owner.ts";
import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { extractSteerImages } from "../turn-images.ts";
import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";
import type { UsageTrigger } from "../usage-ledger.ts";
import { forgetSendingSession, noteSendingSession } from "../sending-sessions.ts";
import { ownWindowSendStarting } from "../own-window-sends.ts";
import { noteTypedSend } from "../typed-sends.ts";
import { engineSessionOutdated, startFresh } from "../fresh-start.ts";
import { parseMentionPicks } from "../../shared/room-mentions.ts";
import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";
import { refusalBody, refusalText, userError } from "../user-errors.ts";
import { PASS, type RouteHandler } from "./table.ts";
type RunningInstance = ReturnType<ProviderRegistry["get"]>;
type SkillResolution =
| { claimed: false }
| { claimed: true; status: number; error: string }
| { claimed: true; outcome: "allowed-once" | "rejected"; alreadySettled?: true };
type CardAnswer = { botId: string; botName?: string; threadId: string; requestId: string; behavior: string };
type Behavior = "allow" | "deny" | "answer";
export interface BotMessageRouteDeps {
store: Pick<Store,
| "activeLeaf" | "activePath" | "appendMessage" | "bot" | "botByThread" | "bots" | "groupByThread" | "messagesFor"
| "patchMessage" | "patchTask" | "projectBotForTask" | "setActiveLeaf" | "setTaskAskedAt" | "taskByThread" | "tasks">;
registry: Pick<ProviderRegistry, "get">;
/** On a team: the words for a turn with no AI to answer with, having told who can connect one. */
noAiRefusal?(threadId: string, sender: ResolvedSender | undefined, instanceId?: string): Error | null;
routines(): RoutineManager | null;
handoffs: Pick<Handoffs, "current" | "steered">;
/** The turn running in a thread now, as its runtime events name it. */
liveTurn(threadId: string): string | undefined;
phoneSecretSubmissions: Pick<PhoneSecretSubmissionRegistry, "hasThread">;
directTurnDispatchClaims: { get(threadId: string): { threadId: string } | undefined };
groupSpeakers: ReadonlyMap<string, { botId: string }>;
desktopManaged: boolean;
cloudHome: boolean;
DirectSendRefused: abstract new (...args: never[]) => { readonly status: number; readonly body: Record<string, unknown> };
acceptDirectSend(input: DirectSendInput, guardedStart?: (currentAtStart: BotRecord) => Promise<DirectSendReceipt>): Promise<DirectSendReceipt>;
directSendRefusal(botId: string, threadId: string): { status: number; body: Record<string, unknown> } | null;
startTurn(botId: string, text: string, opts?: {
threadId?: string; replyTo?: Message; sendId?: string; sender?: ResolvedSender; trigger?: UsageTrigger; relayed?: boolean;
dataContext?: DataContext; compactOnly?: boolean; cardContinuation?: boolean; editedMessageId?: string;
}): Promise<Message>;
/** Retry on a line a caller sent through the Bot API, run as that call ran (bot-api-host.ts); null for any other line. */
botApiRetry?(botId: string, threadId: string, source: Message, sendId?: string): Promise<Message | null>;
usageTriggerFor(auth: RequestAuth): UsageTrigger;
messageSender(auth: RequestAuth): ResolvedSender | undefined;
cloudGuestSendRefusal(auth: RequestAuth, threadId: string): string | null;
cloudThreadRefusal(auth: RequestAuth, threadId: string): string | null;
cardAnswerRefusal(auth: RequestAuth, threadId: string, requestId: string, behavior: string): string | null;
commandRememberRefusal(auth: RequestAuth, threadId: string, requestId: string, behavior: string): string | null;
requestBehavior(value: unknown): Behavior | null;
requestedTaskBot(botId: string, rawThreadId: unknown): BotRecord;
botForThread(botId: string, threadId: string): BotRecord | null;
threadBusy(botId: string, threadId: string): boolean;
botAtThreadCapacity(botId: string): boolean;
parksBehindCoordination(botId: string, threadId: string): boolean;
activeGroupTurnForBot(botId: string, threadId?: string): { group: GroupRecord; threadId: string } | null;
runningTurnInstance(bot: BotRecord | null | undefined, threadId: string): RunningInstance;
engineSteersImages(instance: RunningInstance | undefined): boolean;
resolveReplyTarget(threadId: string, value: unknown): Message | undefined;
turnSelection(botId: string, threadId: string): ModelSelection | undefined;
policyModelRefusal(instance: { instanceId: string; driverKind: string }): string | undefined;
clearUnattended(threadId: string): void;
drainQueuedSends(): void;
answeringCardAs(auth: RequestAuth, threadId: string, requestId: string, work: () => Promise<unknown>): Promise<void>;
resolveAndSendTrust(res: ServerResponse, threadId: string, requestId: string, behavior: Behavior): boolean;
resolveAndSendTeamSetup(res: ServerResponse, args: { botId: string; threadId: string; requestId: string; behavior: string }, ownerReview: boolean): Promise<boolean>;
resolveAndSendMcp(res: ServerResponse, args: { botId: string; threadId: string; requestId: string; behavior: string }, ownerReview: boolean): Promise<boolean>;
resolveAndSendRoutine(res: ServerResponse, args: CardAnswer): boolean;
resolveAndSendProfile(res: ServerResponse, args: CardAnswer): boolean;
resolveAndSendModel(res: ServerResponse, args: CardAnswer): boolean;
resolveSkillRequest(args: CardAnswer & { behavior: Behavior; reviewedSha256?: string }): SkillResolution;
sendSkillResolution(res: ServerResponse, result: SkillResolution): boolean;
answerRequest(
threadId: string, instanceId: string, requestId: string, behavior: Behavior, message?: string,
decidedFor?: { id: string; name: string }, always?: boolean, rememberCommand?: boolean,
): Promise<RequestOutcome>;
deliverLateQuestionAnswer(auth: RequestAuth, threadId: string, requestId: string, answer: string, cardMessage: Message, owner: BotRecord): Promise<{ queued: boolean }>;
stopThreadForPerson(botId: string, threadId: string, by?: ResolvedSender): Promise<void>;
/** Whoever asked owns the run, where several people write. */
runOwners?: RouteRunOwners;
runActor?(auth: RequestAuth): Actor;
cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): unknown;
revokeInternalCapabilitiesForThread(threadId: string): void;
cancelGroupTurnOperations(groupId: string, threadId: string): void;
closeOpenApprovals(threadId: string): void;
/** The outcome of a card the harness raised itself (a quota-switch offer); undefined for any other card. */
harnessCardOutcome(threadId: string, requestId: string, behavior: Behavior, message: unknown): Promise<string | undefined>;
/** What a press on one of the bot's own server-built cards is about, from the server's records; null leaves the press the person's plain answer. */
pressRecords(bot: BotRecord, action: WidgetAction): string | null;
/** A press the server answers itself, with no turn: handled, refused (not the owner or an admin), or null for an ordinary press. */
serverPress(bot: BotRecord, threadId: string, messageId: string, action: WidgetAction, auth: RequestAuth): "handled" | "refused" | null;
/** Shows a 👍 or 👎 relayed from another app on the message it answered, as that person's reaction. */
relayedReaction(threadId: string, messageId: string, person: { email?: string; name?: string }, emoji: string): void;
/** The conversation an answer to this card belongs to: a run's own, for the copy its automation posted in a chat. */
answeredIn(threadId: string, requestId: string): string;
/** The request came from one of the owner's registered phones. */
fromPhone(auth: RequestAuth): boolean;
/** Records a send a registered phone made, so the turn it starts knows the person is talking from the phone. */
notePhoneSend(sendId: string): void;
goals: Pick<OneOnOneGoals, "start">;
/** A Team Cloud: the person's reply to a line in their own inbox goes back where that line came from, with no turn
* here; null for any other message. */
/** On a team: the name of whoever connects its AI; empty until they have opened the team. */
teamAiOwnerName?(): string;
inboxReply?(auth: RequestAuth, threadId: string, replyToId: string, text: string, line: { sendId?: string; sender?: ResolvedSender }): { status: number; message?: Message; error?: string } | null;
/** A typed line that answers a bot's question card; null sends it as usual. */
typedCardAnswer?(auth: RequestAuth, threadId: string, text: string, target: Message | undefined, line: { sendId?: string; sender?: ResolvedSender }): Promise<{ status: number; message?: Message; error?: string } | null>;
/** On a Team Cloud: why the person a relayed message names may not chat with this bot; null when they may. */
relayRefusal?(bot: BotRecord, email: string | undefined): string | null;
/** The answer to someone's ask to chat with a team bot; null for any other card. */
resolveAccessRequest?(threadId: string, requestId: string, behavior: string, message: unknown): { status: number; body: unknown } | null;
}
/** External interfaces (the Slack worker) opt in. `onBehalfOf`, advertised by /api/health as
* capabilities.guardedOnBehalfOf, books the turn to that person; only this admin-scoped route reads it. `reaction`
* replaces `text` when the person reacted in that app: a 👍 or 👎 (Slack's name for it, or the emoji any platform
* sends) on the message in `replyToId`, made by `onBehalfOf`. */
const guardedSendSchema = z.object({
threadId: z.string().regex(/^[\w-]+$/),
sendId: z.string().regex(/^[A-Za-z0-9_-]{16,80}$/),
text: z.string().min(1).optional(),
reaction: z.string().max(64).optional(),
expectedActiveLeafId: z.string().regex(/^[\w-]+$/).nullable(),
expectedApprovalMode: z.enum(["ask", "full"]).optional(),
replyToId: z.string().optional(),
onBehalfOf: z.object({
email: z.string().trim().toLowerCase().max(254).pipe(z.email()).optional(),
name: z.string().trim().min(1).max(120).optional(),
}).strict().refine((who) => Boolean(who.email || who.name)).optional(),
}).strict().refine((send) => (send.text === undefined) !== (send.reaction === undefined));
/** Plain-send option: `answer: "never"` keeps the line from answering a card, and refuses while one waits. */
const ANSWER_NEVER = "never";
const WAITING_CARD_KINDS: ReadonlySet<string> = new Set(["question", "approval", "password", "sign-in"]);
/** A question, approval, sign-in or credential request still open in this conversation. */
const waitsOnCard = (messages: readonly Message[]): boolean =>
messages.some((message) => {
const wait = personWait(message);
return wait !== null && WAITING_CARD_KINDS.has(wait.kind);
});
const CARD_WAITING_BODY = {
error: "a question, approval, sign-in or credential request is waiting in this conversation, so nothing was sent; answer it, then send again",
code: "card_waiting",
};
const CONTEXT_BREAKDOWN_WAIT_MS = 5_000;
export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler {
const {
store, registry, handoffs, liveTurn, phoneSecretSubmissions, directTurnDispatchClaims, groupSpeakers,
desktopManaged: DESKTOP_MANAGED, cloudHome: CLOUD_HOME, DirectSendRefused,
acceptDirectSend, directSendRefusal, startTurn, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal,
cardAnswerRefusal, commandRememberRefusal, requestBehavior, requestedTaskBot, botForThread, threadBusy,
botAtThreadCapacity, parksBehindCoordination, activeGroupTurnForBot, runningTurnInstance, engineSteersImages, resolveReplyTarget,
turnSelection, policyModelRefusal, clearUnattended, drainQueuedSends, answeringCardAs, resolveAndSendTrust, resolveAndSendTeamSetup, resolveAndSendMcp,
resolveAndSendRoutine, resolveAndSendProfile, resolveAndSendModel, resolveSkillRequest, sendSkillResolution, answerRequest,
deliverLateQuestionAnswer, stopThreadForPerson, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,
cancelGroupTurnOperations, closeOpenApprovals, harnessCardOutcome, pressRecords, serverPress, relayedReaction, answeredIn, fromPhone, notePhoneSend, goals,
} = deps; const owners = routeRunOwners(deps.runOwners, deps.runActor);
const pinnedClientThread = pinnedClientThreadGuard(store);
/** Security: a bot's own shell must never approve its own card, so a local request counts only from the desktop app, or
* from a browser while every bot is idle. */
const ownerReview = (auth: RequestAuth, req: IncomingMessage) => auth.kind === "loopback"
? DESKTOP_MANAGED || Boolean(req.headers.origin) && !store.bots.some((bot) => bot.busy || activeGroupTurnForBot(bot.id))
: auth.scopes.includes("admin");
/** widget -> sendId of a press on its way in: a second tap before acceptance must not send a second answer. */
const pressesInFlight = new Map<string, string | undefined>();
const appMessageRate = new AppMessageRate();
const route: RouteHandler = async (ctx) => {
const { req, res, path, method, auth, json, readBody } = ctx;
let m: RegExpMatchArray | null = null;
const requirePinnedClientThread = pinnedClientThread(auth, req);
const routines = deps.routines();
m = path.match(/^\/api\/bots\/([\w-]+)\/messages(?:\/(guarded))?$/);
if (m && method === "POST") {
const guarded = m[2] === "guarded";
const body = await readBody(req);
if (!body || typeof body !== "object" || Array.isArray(body)) {
return json(res, 400, { error: "body must be a JSON object" });
}
const pressed = body.widgetAction !== undefined && body.widgetAction !== null;
if (guarded && pressed) return json(res, 400, { error: "guarded sends cannot answer a widget" });
const fromAnApp = body.appMessage !== undefined && body.appMessage !== null;
if (guarded && fromAnApp) return json(res, 400, { error: "guarded sends cannot speak for an app" });
if (pressed && fromAnApp) return json(res, 400, { error: "send widgetAction or appMessage, not both" });
if (body.answer !== undefined && body.answer !== ANSWER_NEVER) {
return json(res, 400, { error: `answer must be "${ANSWER_NEVER}" when set` });
}
const answerNever = body.answer === ANSWER_NEVER;
if (answerNever && (guarded || pressed || fromAnApp)) {
return json(res, 400, { error: `answer: "${ANSWER_NEVER}" applies only to a typed message` });
}
const pointing = body.pointed !== undefined && body.pointed !== null;
if (pointing && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can carry what the person pointed at" });
const pageOpen = body.openPage !== undefined && body.openPage !== null;
if (pageOpen && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can carry the page the person has open" });
const followUp = parseFollowUp(body.followUp);
if (followUp === null) return json(res, 400, { error: "followUp must be steer, queue or restart" });
const mentions = parseMentionPicks(body.mentions);
if (mentions === null) return json(res, 400, { error: "mentions must be a list of up to 20 bot ids" });
if (followUp && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can choose how it meets the running turn" });
// A distinct route, so an older server answers 404 instead of ignoring the safety preconditions.
const guardedBody = guarded ? guardedSendSchema.safeParse(body) : null;
if (guardedBody && !guardedBody.success) {
const onBehalfOfInvalid = guardedBody.error.issues.some((issue) => issue.path[0] === "onBehalfOf");
return json(res, 400, { error: onBehalfOfInvalid
? "onBehalfOf must name the person with an email address, a name, or both"
: "guarded sends require threadId, sendId, text (or a reaction) and expectedActiveLeafId" });
}
const relayed = guardedBody?.data?.reaction === undefined ? null : normalizeReaction(guardedBody.data.reaction);
if (guardedBody?.data?.reaction !== undefined && (!reactionAnswer(relayed) || !body.replyToId || !guardedBody.data.onBehalfOf)) {
return json(res, 400, { error: "a relayed reaction is a 👍 or 👎 on the message in replyToId, made by the person in onBehalfOf" });
}
const textRefused = pressed || fromAnApp ? null : messageTextRefusal(body.text);
if (textRefused) return json(res, 400, { error: textRefused });
const typed = pressed || fromAnApp ? "" : relayed ?? String(body.text ?? "").trim();
if (!pressed && !fromAnApp && !typed) return json(res, 400, { error: "text required" });
const bot = store.bot(m[1]);
if (!bot) return json(res, 404, { error: "no such bot" });
requirePinnedClientThread(bot.id, body.threadId);
if (body.threadId !== undefined && (typeof body.threadId !== "string" || !/^[\w-]+$/.test(body.threadId))) {
return json(res, 400, { error: "threadId must be a task id" });
}
const threadId = body.threadId ?? bot.threadId;
if ((pressed || fromAnApp) && store.groupByThread(threadId)) return json(res, 409, { error: ROOM_VIEW_ONLY });
const notYours = cloudGuestSendRefusal(auth, threadId);
if (notYours) return json(res, 403, { error: notYours });
if (body.mode !== undefined && body.mode !== "chat" && body.mode !== "goal") return json(res, 400, { error: "mode must be chat or goal" });
if (body.mode === "goal") {
if (guarded || pressed || fromAnApp || pointing) return json(res, 400, { error: "a goal is a plain typed message" });
if (!store.taskByThread(bot.id, threadId)) return json(res, 404, userError("serverError.chat.missingConversation"));
const goalRefused = directSendRefusal(bot.id, threadId);
if (goalRefused) return json(res, goalRefused.status, goalRefused.body);
const goalSendId = parseSendId(body.sendId);
const accepted = goalSendId ? acceptedSendMatch(store.messagesFor(threadId), goalSendId, typed, undefined, "goal") : null;
if (accepted?.kind === "conflict") return json(res, 409, { error: "sendId already belongs to another message" });
if (accepted?.kind === "match") return json(res, 202, { ok: true, threadId, message: accepted.message });
if (answerNever && waitsOnCard(store.activePath(threadId))) return json(res, 409, CARD_WAITING_BODY);
const message = goals.start(bot.id, threadId, typed, { sendId: goalSendId, sender: messageSender(auth) });
return json(res, 202, { ok: true, threadId, message });
}
const onBehalfOf = guardedBody?.data?.onBehalfOf;
const relayRefused = guardedBody && (onBehalfOf || auth.kind === "loopback") ? deps.relayRefusal?.(bot, onBehalfOf?.email) : null;
if (relayRefused) return json(res, 403, { error: relayRefused });
const trigger: UsageTrigger = onBehalfOf
? { kind: "user", ...(onBehalfOf.email ? { email: onBehalfOf.email } : {}), ...(onBehalfOf.name ? { label: onBehalfOf.name } : {}) }
: usageTriggerFor(auth);
// Security invariant: another bot's thread answers like a missing one, before anything reads a widget in it.
if (pressed && !store.taskByThread(bot.id, threadId)) return json(res, 409, { error: "the bot switched tasks before it could receive the message" });
const phone = fromPhone(auth);
// A phone's send without an id gets one, so the turn it starts can be known as the phone's.
const sendId = parseSendId(body.sendId) ?? (phone ? randomUUID() : undefined);
const press = pressed ? prepareWidgetPress(store, threadId, body.widgetAction, sendId) : null;
if (press && !press.ok) return json(res, press.status, { error: press.error });
const answered = press ? serverPress(bot, threadId, press.messageId, press.action, auth) : null;
if (answered === "handled") return json(res, 202, { ok: true, threadId, handled: true });
if (answered === "refused") return json(res, 403, userError("serverError.chat.ownerOrAdmin"));
// acceptDirectSend checks these again; nothing awaits between.
const refused = directSendRefusal(bot.id, threadId);
if (refused) return json(res, refused.status, refused.body);
const alreadySent = Boolean(sendId && (store.messagesFor(threadId).some((message) => message.sendId === sendId) || queuedSteeredMessage(bot.id, threadId, sendId)));
if (answerNever && !alreadySent && waitsOnCard(store.activePath(threadId))) return json(res, 409, CARD_WAITING_BODY);
const appSent = fromAnApp ? prepareAppMessage(store, threadId, body.appMessage) : null;
if (appSent && !appSent.ok) return json(res, appSent.status, { error: appSent.error });
const pointed = pointing ? preparePointed(store, threadId, body.pointed) : null;
if (pointed && !pointed.ok) return json(res, pointed.status, refusalBody(pointed));
const openPage = pageOpen ? openPageBlock(store, threadId, body.openPage) : null;
if (openPage === false) return json(res, 400, { error: OPEN_PAGE_BAD });
const text = press ? press.text : appSent ? appSent.text : typed;
const target = resolveReplyTarget(threadId, press ? press.messageId : appSent ? appSent.messageId : body.replyToId);
if (relayed && target?.role !== "bot") return json(res, 400, { error: "a relayed reaction answers a bot's message" });
const passedBack = !guarded && !press && !appSent && !pointed && target ? deps.inboxReply?.(auth, threadId, target.id, text, { sendId, sender: messageSender(auth) }) : null;
const queuedAgain = Boolean(sendId && queuedSteeredMessage(bot.id, threadId, sendId));
const typedAnswer = answerNever || passedBack || guarded || press || appSent || pointed || queuedAgain ? null : await deps.typedCardAnswer?.(auth, threadId, text, target, { sendId, sender: messageSender(auth) });
const answeredBack = passedBack ?? typedAnswer;
if (answeredBack) return json(res, answeredBack.status, answeredBack.message ? { ok: true, threadId, message: answeredBack.message } : refusalText(answeredBack.error ?? ""));
// Only a real press or reaction, or an app's own words, marks the reply; a typed reply to the same row never does, whatever its words.
const records = press && target ? pressRecords(bot, press.action) : null;
const replyTo: ReplyTarget | undefined = press && target ? { ...target, widgetPress: { label: press.label, action: press.action, ...(records ? { records } : {}) } }
: appSent && target ? { ...target, appMessage: { title: appSent.title, origin: appSent.origin } }
: relayed && target ? { ...target, reactedWith: relayed } : target;
const pressKey = press?.settles ? `${threadId}:${press.messageId}` : undefined;
if (pressKey && pressesInFlight.has(pressKey) && !(sendId && pressesInFlight.get(pressKey) === sendId)) {
return json(res, 409, userError("serverError.chat.answerSent"));
}
const dataContext = press || appSent ? undefined : parseDataContext(body.dataContext);
const retried = Boolean(sendId && (store.messagesFor(threadId).some((message) => message.sendId === sendId) || queuedSteeredMessage(bot.id, threadId, sendId)));
const slot = appSent ? appMessageRate.reserve(`${threadId}:${appSent.messageId}`, sendId) : null;
if (appSent && !slot) return json(res, 429, { error: "This app has sent too many messages. Wait a while, or type your message." });
// A relay is not the person at this screen: it never carries what their apps last showed.
const appContext = guarded || retried ? null : appContextBlock(store, threadId);
const context = `${appContext?.block ?? ""}${openPage ?? ""}${pointed?.block ?? ""}`;
const app = context || appSent || pointed
? {
...(context ? { context } : {}),
...(appSent ? { fromApp: { messageId: appSent.messageId, title: appSent.title } } : {}),
...(pointed ? { pointed: pointed.refs } : {}),
}
: undefined;
const sender = messageSender(auth);
const guardedStart = guarded
? async (currentAtStart: BotRecord): Promise<DirectSendReceipt> => {
// No await between these checks and startTurn: never steer or enqueue under stale permissions.
const expectedMode = body.expectedApprovalMode ?? "ask";
if (approvalModeFor(currentAtStart) !== expectedMode ||
(expectedMode === "ask" && (currentAtStart.autoApprove === true || currentAtStart.alwaysAllow?.length))) {
throw Object.assign(new Error("guarded sends require the exact expected approval mode; Ask cannot have remembered permissions"), { status: 409, code: "guarded_permissions" });
}
if (store.activeLeaf(threadId) !== body.expectedActiveLeafId) {
throw Object.assign(new Error("the conversation changed before this message could start"), { status: 409, code: "guarded_branch" });
}
const guardedAdmission = admit("guarded", {}, {
botBusy: currentAtStart.busy,
threadBusy: threadBusy(bot.id, threadId),
atCapacity: botAtThreadCapacity(bot.id),
parksBehindCoordination: parksBehindCoordination(bot.id, threadId),
groupTurn: Boolean(activeGroupTurnForBot(bot.id)),
});
if (guardedAdmission.action === "refuse") {
throw Object.assign(new Error("wait for a free thread slot before retrying this message"), { status: 409, code: "guarded_busy" });
}
// The relayed line is named after the person it is for; with no key it is nobody's own line and acts for nobody.
const message = await startTurn(bot.id, text, { threadId, replyTo, sendId, sender: onBehalfOf ? { name: onBehalfOf.name ?? onBehalfOf.email! } : sender, trigger, relayed: true, dataContext });
return { ok: true as const, threadId, message };
}
: undefined;
if (phone && sendId) notePhoneSend(sendId);
// The bot's own shell reaches this route on a headless server (loopback is the owner), so only a
// paired session or the desktop capability proves a person and lifts the webhook block.
const personPresent = auth.kind === "session" || DESKTOP_MANAGED;
if (personPresent && sendId && !guarded && !press && !appSent) noteTypedSend(threadId, sendId, text);
const notedSession = auth.kind === "session" && sendId ? noteSendingSession(threadId, sendId, auth.session.id) : false;
// The desktop app's own window: in the desktop app a loopback change needs its private capability.
// Only a new line the send itself adds: a repeat or a collision must not lend the proof to a line already there or waiting.
const ownWindowSend = DESKTOP_MANAGED && auth.kind === "loopback" && !auth.companionDevice && sendId && !guarded && !press && !appSent
&& !store.messagesFor(threadId).some((line) => line.sendId === sendId) && !queuedSteeredMessage(bot.id, threadId, sendId);
if (pressKey) pressesInFlight.set(pressKey, sendId);
const ownWindowSettled = ownWindowSend ? ownWindowSendStarting(threadId, sendId, text) : undefined;
try {
const receipt = await acceptDirectSend({
botId: bot.id, threadId, text, sendId, replyTo, sender, trigger, dataContext, ...(app ? { app } : {}),
personPresent, admin: owners.admin(auth), ...(followUp ? { followUp } : {}),
...(mentions?.length && !press && !appSent ? { mentions } : {}),
}, guardedStart);
ownWindowSettled?.(true);
press?.settle("queueId" in receipt ? receipt.queueId : undefined);
appContext?.deliver();
if (relayed && target && onBehalfOf) relayedReaction(threadId, target.id, onBehalfOf, relayed);
return json(res, 202, receipt);
} catch (error) {
slot?.release();
ownWindowSettled?.(false);
if (notedSession) forgetSendingSession(threadId, sendId!);
if (error instanceof DirectSendRefused) return json(res, error.status, error.body);
throw error;
} finally {
if (pressKey) pressesInFlight.delete(pressKey);
}
}
m = path.match(/^\/api\/bots\/([\w-]+)\/queue\/([\w-]+)$/);
if (m && method === "DELETE") {
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body?.threadId);
const queueId = m[2];
const waiting = queuedSteerSender(bot.id, bot.threadId, queueId);
const notYours = waiting && owners.removeRefusal(auth, bot.threadId, waiting.sender);
if (notYours) return json(res, 403, { error: notYours, code: "queued_not_yours" });
if (!cancelSteeredMessage(bot.id, queueId, bot.threadId)) {
return json(res, 404, { error: "no such queued message" });
}
reopenCancelledPress(store, bot.threadId, queueId);
return json(res, 200, { ok: true });
}
// Steers a queued message into the running turn without interrupting it; engines without live steer keep the queue.
m = path.match(/^\/api\/bots\/([\w-]+)\/queue\/([\w-]+)\/steer$/);
if (m && method === "POST") {
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body?.threadId);
// Hold the whole queue atomically: a racing settle drains it or this request steers it, never both.
const held = holdSteeredQueue(bot.id, bot.threadId, m[2]);
if (!held) return json(res, 404, { error: "no such queued message" });
const waitsItsTurn = owners.joinRefusal(auth, bot.threadId, held.items.map((item) => item.sender));
if (waitsItsTurn) {
restoreHeldSteeredQueue(held);
return json(res, 403, { error: waitsItsTurn, code: "waits_its_turn" });
}
const currentAtStart = store.projectBotForTask(bot.id, bot.threadId);
const instance = currentAtStart?.busy ? runningTurnInstance(currentAtStart, bot.threadId) : undefined;
const engineCanSteer = Boolean(currentAtStart?.busy && instance?.adapter.capabilities.queueing && instance.adapter.steer);
const steerInput = extractSteerImages(held.items.map((item) => item.prompt));
const steerAdmission = admit("direct-busy", {
carriesImages: !steerInput || steerInput.images.length > 0,
engineCanSteerImages: Boolean(steerInput) && engineSteersImages(instance),
engineCanSteer,
});
if (steerAdmission.action === "queue" && steerAdmission.blockedBy) {
restoreHeldSteeredQueue(held);
return json(res, 200, { ok: true, queued: true, threadId: bot.threadId, blockedBy: steerAdmission.blockedBy });
}
const prompt = (steerInput?.texts ?? held.items.map((item) => item.prompt)).join("\n\n");
const images = steerInput?.images ?? [];
const steerTarget = handoffs.current(bot.threadId);
let steered: SteerOutcome = "refused";
if (steerAdmission.action === "steer" && instance?.adapter.steer) {
steered = await (images.length > 0
? instance.adapter.steer(bot.threadId, prompt, images)
: instance.adapter.steer(bot.threadId, prompt))
.catch((): SteerOutcome => "indeterminate");
}
// The steer awaited adapter work: re-read every ownership invariant before writing anything.
const current = store.projectBotForTask(bot.id, bot.threadId);
// "indeterminate" never restores: the words may already be in the live turn, and a replay would run them twice.
if (
(steered === "steered" && current?.busy ||
steered === "indeterminate" && current) &&
store.taskByThread(bot.id, bot.threadId)
) {
if (auth.kind === "session" || DESKTOP_MANAGED) clearUnattended(bot.threadId);
const messages = held.items.map((item) => store.appendMessage(bot.threadId, {
role: "user",
kind: "text",
text: item.text,
replyToId: item.replyToId,
sendId: item.sendId,
...(item.dataContext ? { dataContext: item.dataContext } : {}),
queueId: item.messageId,
peerAsk: item.peerAsk,
steered: true,
sender: item.sender,
...spokenLineFields(item.via, item.callId),
...(item.fromApp ? { fromApp: item.fromApp } : {}),
}));
const asked = messages.filter((_, index) => !held.items[index]?.unattended && !held.items[index]?.peerAsk).at(-1);
if (asked) store.setTaskAskedAt(bot.id, bot.threadId, asked.at);
for (const message of messages) handoffs.steered(bot.threadId, steerTarget, instance?.instanceId, message.id);
const queueIds = held.items.map((item) => item.messageId);
settleHeldSteeredQueue(held);
return json(res, 200, { ok: true, steered: true, threadId: bot.threadId, messages, queueIds });
}
if (steered === "indeterminate") {
// No destination left: settle, so a restart cannot replay words a dead turn may have run.
settleHeldSteeredQueue(held);
if (!store.taskByThread(bot.id, bot.threadId)) {
throw Object.assign(new Error("the target task no longer exists"), { status: 409 });
}
throw Object.assign(new Error("no such bot"), { status: 404 });
}
restoreHeldSteeredQueue(held);
if (current && !current.busy) drainQueuedSends();
return json(res, 200, { ok: true, queued: true, threadId: bot.threadId });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/helper-followup$/);
if (m && method === "POST") {
const bot = store.bot(m[1]!);
if (!bot?.defaultBot || bot.hidden) return json(res, 404, { ...userError("serverError.setup.mausbotMissing") });
if (!mayFollowUp(bot, auth)) return json(res, 403, { ...userError("serverError.setup.mausbotOwnerOnly") });
const parsed = helperFollowupBody.safeParse(await readBody(req));
if (!parsed.success) return json(res, 400, { error: "body must be { ai, apps?, threadId? }" });
const threadId = parsed.data.threadId ?? bot.threadId;
if (store.botByThread(threadId)?.id !== bot.id) return json(res, 404, { error: "no such conversation" });
const connects = auth.scopes.includes("admin") ? undefined : deps.teamAiOwnerName?.();
const next = helperFollowup(store.messagesFor(threadId), () => followupFacts(bot, parsed.data, store.bots, routines?.listRoutines() ?? [], connects));
if (!next) return json(res, 409, { ...userError("serverError.setup.noIntroToFollowUp") });
if ("existing" in next) return json(res, 200, { message: next.existing });
return json(res, 201, { message: store.appendMessage(threadId, next.append) });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/compact$/);
if (m && method === "POST") {
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body?.threadId);
const notYours = cloudThreadRefusal(auth, bot.threadId);
if (notYours) return json(res, 403, { error: notYours });
await startTurn(bot.id, "Summarize conversation context", {
threadId: bot.threadId, compactOnly: true, cardContinuation: true, trigger: usageTriggerFor(auth),
});
return json(res, 202, { ok: true, threadId: bot.threadId });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/start-fresh$/);
if (m && method === "POST") {
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body?.threadId);
const notYours = cloudThreadRefusal(auth, bot.threadId);
if (notYours) return json(res, 403, { error: notYours });
// Synchronous from here: startTurn flips busy before the next request, so a turn cannot slip past this check.
if (threadBusy(bot.id, bot.threadId)) return json(res, 409, userError("serverError.chat.busyFresh"));
if (phoneSecretSubmissions.hasThread(bot.threadId)) return json(res, 409, userError("serverError.chat.savingCredential"));
return json(res, 200, { ok: true, message: startFresh(store, bot.id, bot.threadId), threadId: bot.threadId });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/context$/);
if (m && method === "POST") {
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body?.threadId);
const notYours = cloudThreadRefusal(auth, bot.threadId);
if (notYours) return json(res, 403, { error: notYours });
// The engine process answers for the conversation it last read, which the next turn may be about to replace:
// already when asked, or by a Start fresh, rewind or summary that lands while it counts.
const stale = () => engineSessionOutdated(store, bot.id, bot.threadId);
const breakdown = stale() ? null : await registry.get(bot.modelSelection.instanceId)?.adapter
.contextBreakdown?.(bot.threadId, { signal: AbortSignal.timeout(CONTEXT_BREAKDOWN_WAIT_MS) }) ?? null;
return json(res, 200, { threadId: bot.threadId, breakdown: stale() ? null : breakdown });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/messages\/([\w-]+)\/edit$/);
if (m && method === "POST") {
const messageId = m[2];
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body.threadId);
const notYours = owners.decidesRetry(bot.threadId) ? null : cloudThreadRefusal(auth, bot.threadId);
if (notYours) return json(res, 403, { error: notYours });
const textRefused = messageTextRefusal(body.text);
if (textRefused) return json(res, 400, { error: textRefused });
const text = String(body.text ?? "").trim();
if (!text) return json(res, 400, { error: "text required" });
const threadMessages = store.messagesFor(bot.threadId);
const source = threadMessages.find((msg) => msg.id === messageId);
if (!source || source.role !== "user" || source.kind !== "text") {
return json(res, 404, { error: "only user messages can be edited" });
}
const notYoursToRetry = owners.retryRefusal(auth, bot.threadId, source.sender);
if (notYoursToRetry) return json(res, 403, { error: notYoursToRetry, code: "retry_not_yours" });
// Before the busy guard: a retried edit's own fork is what is busy.
const sendId = parseSendId(body.sendId);
if (sendId) {
const accepted = acceptedSendMatch(threadMessages, sendId, text, source.replyToId);
if (accepted.kind === "conflict" || (accepted.kind === "match" && (accepted.message.parentId ?? null) !== (source.parentId ?? null))) {
return json(res, 409, { error: "sendId already belongs to another message" });
}
if (accepted.kind === "match") return json(res, 202, { ok: true, message: accepted.message });
}
// Synchronous from here: startTurn flips busy before the next request, so two racing edits cannot both pass.
if (threadBusy(bot.id, bot.threadId)) return json(res, 409, userError("serverError.chat.busyEdit"));
if (phoneSecretSubmissions.hasThread(bot.threadId)) {
return json(res, 409, userError("serverError.chat.savingCredential"));
}
const rerunSelection = turnSelection(bot.id, bot.threadId) ?? bot.modelSelection;
if (!registry.get(rerunSelection.instanceId)) {
const noAi = deps.noAiRefusal?.(bot.threadId, messageSender(auth), rerunSelection.instanceId);
if (noAi) throw noAi;
return json(res, 409, {
error: `provider instance "${rerunSelection.instanceId}" is unavailable — pick another model in settings`,
});
}
const rerunInstance = registry.get(rerunSelection.instanceId)!;
const rerunRefusal = policyModelRefusal(rerunInstance);
if (rerunRefusal) return json(res, 409, { error: rerunRefusal });
// The same words again on a caller's line: the caller's message again, never the person's own.
const apiRetry = source.via === "api" && text === source.text?.trim() ? await deps.botApiRetry?.(bot.id, bot.threadId, source, sendId) : null;
if (apiRetry) return json(res, 202, { ok: true, message: apiRetry });
const quoted = source.replyToId ? resolveReplyTarget(bot.threadId, source.replyToId) : undefined;
const replyTo: ReplyTarget | undefined = quoted && source.reaction && text === source.text ? { ...quoted, reactedWith: source.reaction } : quoted;
const dataContext = parseDataContext(body.dataContext) ?? (text === source.text ? source.dataContext : undefined);
const message = await startTurn(bot.id, text, { threadId: bot.threadId, editedMessageId: messageId, replyTo, sendId, trigger: usageTriggerFor(auth), dataContext,
...(CLOUD_HOME ? { sender: messageSender(auth) } : {}) });
return json(res, 202, { ok: true, message });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/active-branch$/);
if (m && method === "POST") {
const body = await readBody(req);
requirePinnedClientThread(m[1], body?.threadId);
const bot = requestedTaskBot(m[1], body.threadId);
const notYours = cloudThreadRefusal(auth, bot.threadId);
if (notYours) return json(res, 403, { error: notYours });
if (threadBusy(bot.id, bot.threadId)) return json(res, 409, userError("serverError.chat.busyVersion"));
if (phoneSecretSubmissions.hasThread(bot.threadId)) {
return json(res, 409, userError("serverError.chat.savingCredential"));
}
const leaf = store.setActiveLeaf(bot.threadId, String(body.messageId ?? ""));
if (!leaf) return json(res, 404, { error: "no such message" });
store.patchTask(bot.id, bot.threadId, { rewound: true });
return json(res, 200, { activeLeafId: leaf });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/respond$/);
if (m && method === "POST") {
const body = await readBody(req);
const selected = requestedTaskBot(m[1], body.threadId);
const answering = answeredIn(selected.threadId, String(body.requestId));
if (answering !== selected.threadId && !store.taskByThread(selected.id, answering)) {
return route({ ...ctx, path: `/api/threads/${selected.threadId}/respond`, readBody: async () => body });
}
const bot = botForThread(selected.id, answering)!;
const behavior = requestBehavior(body.behavior);
const reviewedSha256 = typeof body.reviewedSha256 === "string" ? body.reviewedSha256 : undefined;
if (!behavior) return json(res, 400, { error: "behavior must be allow, deny, or answer" });
const refusal = cardAnswerRefusal(auth, selected.threadId, String(body.requestId), behavior) ??
(selected.threadId === bot.threadId ? null : cardAnswerRefusal(auth, bot.threadId, String(body.requestId), behavior));
if (refusal) return json(res, 403, refusalText(refusal));
if (body.rememberCommand === true) {
const refusal = commandRememberRefusal(auth, bot.threadId, String(body.requestId), behavior);
if (refusal) return json(res, 403, { error: refusal });
}
return await answeringCardAs(auth, bot.threadId, String(body.requestId), async () => {
const access = deps.resolveAccessRequest?.(bot.threadId, String(body.requestId), behavior, body.message);
if (access) return json(res, access.status, access.body);
if (resolveAndSendTrust(res, bot.threadId, String(body.requestId), behavior)) return;
const answer = { botId: bot.id, threadId: bot.threadId, requestId: String(body.requestId), behavior };
if (await resolveAndSendTeamSetup(res, answer, ownerReview(auth, req))) return;
if (await resolveAndSendMcp(res, answer, ownerReview(auth, req))) return;
if (resolveAndSendRoutine(res, {
botId: bot.id,
botName: bot.name,
threadId: bot.threadId,
requestId: String(body.requestId),
behavior,
})) return;
if (resolveAndSendProfile(res, {
botId: bot.id,
botName: bot.name,
threadId: bot.threadId,
requestId: String(body.requestId),
behavior,
})) return;
if (resolveAndSendModel(res, {
botId: bot.id,
botName: bot.name,
threadId: bot.threadId,
requestId: String(body.requestId),
behavior,
})) return;
if (sendSkillResolution(res, resolveSkillRequest({
botId: bot.id,
botName: bot.name,
threadId: bot.threadId,
requestId: String(body.requestId),
behavior,
reviewedSha256,
}))) return;
const requestId = String(body.requestId);
const own = await harnessCardOutcome(bot.threadId, requestId, behavior, body.message);
if (own) return json(res, 200, { ok: true, outcome: own });
const pending = store.messagesFor(bot.threadId).find((message) => message.card?.requestId === requestId);
const dismissed = dismissQuestionCard(store, bot.threadId, pending, body);
if (dismissed) return json(res, dismissed.status, dismissed.body);
const outcome = await answerRequest(bot.threadId, bot.modelSelection.instanceId, requestId, behavior, body.message, { id: bot.id, name: bot.name }, body.always === true, body.rememberCommand === true);
if (outcome === "unavailable" && isPersistentQuestionCard(pending?.card) && behavior === "answer") {
if (!pending) return json(res, 404, userError("serverError.chat.questionGone"));
const answer = typeof body.message === "string" ? body.message.trim() : "";
if (!answer) return json(res, 400, { error: "a question answer is required" });
try {
const reply = await deliverLateQuestionAnswer(auth, bot.threadId, requestId, answer, pending, bot);
return json(res, 200, { ok: true, outcome: "answered", late: true, ...(reply.queued ? { queued: true } : {}) });
} catch (error) {
return json(res, 409, { error: error instanceof Error ? error.message : "the late answer could not be queued" });
}
}
return json(res, 200, { ok: true, outcome });
});
}
m = path.match(/^\/api\/threads\/([\w-]+)\/respond$/);
if (m && method === "POST") {
const body = await readBody(req);
const behavior = requestBehavior(body.behavior);
const reviewedSha256 = typeof body.reviewedSha256 === "string" ? body.reviewedSha256 : undefined;
if (!behavior) return json(res, 400, { error: "behavior must be allow, deny, or answer" });
const requestId = String(body.requestId);
const threadId = answeredIn(m[1], requestId);
const refusal = cardAnswerRefusal(auth, m[1], requestId, behavior) ?? (threadId === m[1] ? null : cardAnswerRefusal(auth, threadId, requestId, behavior));
if (refusal) return json(res, 403, refusalText(refusal));
if (body.rememberCommand === true) {
const refusal = commandRememberRefusal(auth, threadId, requestId, behavior);
if (refusal) return json(res, 403, { error: refusal });
}
return await answeringCardAs(auth, threadId, requestId, async () => {
const access = deps.resolveAccessRequest?.(threadId, requestId, behavior, body.message);
if (access) return json(res, access.status, access.body);
if (resolveAndSendTrust(res, threadId, requestId, behavior)) return;
const skillCard = store.messagesFor(threadId).find(
(message) => message.card?.requestId === requestId && message.card.skillRequest,
);
if (skillCard?.card?.skillRequest) {
const skillBotId = skillCard.from?.botId ?? store.botByThread(threadId)?.id;
if (!skillBotId) return json(res, 400, { error: "this skill request has no valid owner" });
const skillOwner = store.bot(skillBotId);
if (sendSkillResolution(res, resolveSkillRequest({
botId: skillBotId,
botName: skillOwner?.name,
threadId,
requestId,
behavior,
reviewedSha256,
}))) return;
}
const routineCard = store.messagesFor(threadId).find(
(message) => message.card?.requestId === requestId && message.card.routineRequest,
);
if (routineCard?.card?.routineRequest) {
// Derive the owner from the conversation, never from the payload being authorized.
const routineBotId = routineCard.from?.botId ?? store.botByThread(threadId)?.id;
if (!routineBotId) return json(res, 400, { error: "this routine request has no valid owner" });
const routineOwner = store.bot(routineBotId);
if (resolveAndSendRoutine(res, {
botId: routineBotId,
botName: routineOwner?.name,
threadId,
requestId,
behavior,
})) return;
}
const setupCard = store.messagesFor(threadId).find((message) => message.card?.requestId === requestId && message.card.teamSetupRequest);
if (setupCard) {
const setupBotId = setupCard.from?.botId ?? store.botByThread(threadId)?.id;
if (!setupBotId) return json(res, 400, { error: "This team setup has no valid owner" });
if (await resolveAndSendTeamSetup(res, { botId: setupBotId, threadId, requestId, behavior }, ownerReview(auth, req))) return;
}
const mcpCard = store.messagesFor(threadId).find((message) => message.card?.requestId === requestId && message.card.mcpRequest);
if (mcpCard) {
const mcpBotId = mcpCard.from?.botId ?? store.botByThread(threadId)?.id;
if (!mcpBotId) return json(res, 400, { error: "This MCP server card has no valid owner" });
if (await resolveAndSendMcp(res, { botId: mcpBotId, threadId, requestId, behavior }, ownerReview(auth, req))) return;
}
const profileCard = store.messagesFor(threadId).find(
(message) => message.card?.requestId === requestId && message.card.profileRequest,
);
if (profileCard?.card?.profileRequest) {
const profileBotId = profileCard.from?.botId ?? store.botByThread(threadId)?.id;
if (!profileBotId) return json(res, 400, { error: "this profile request has no valid owner" });
const profileOwner = store.bot(profileBotId);
if (resolveAndSendProfile(res, {
botId: profileBotId,
botName: profileOwner?.name,
threadId,
requestId,
behavior,
})) return;
}
const modelCard = store.messagesFor(threadId).find(
(message) => message.card?.requestId === requestId && message.card.modelRequest,
);
if (modelCard?.card?.modelRequest) {
const modelBotId = modelCard.from?.botId ?? store.botByThread(threadId)?.id;
if (!modelBotId) return json(res, 400, { error: "this model request has no valid owner" });
const modelOwner = store.bot(modelBotId);
if (resolveAndSendModel(res, {
botId: modelBotId,
botName: modelOwner?.name,
threadId,
requestId,
behavior,
})) return;
}
const own = await harnessCardOutcome(threadId, requestId, behavior, body.message);
if (own) return json(res, 200, { ok: true, outcome: own });
const group = store.groupByThread(threadId);
const pending = store.messagesFor(threadId).find((message) => message.card?.requestId === requestId);
const dismissed = dismissQuestionCard(store, threadId, pending, body);
if (dismissed) return json(res, dismissed.status, dismissed.body);
const persistentQuestion = isPersistentQuestionCard(pending?.card);
const owner = group
? persistentQuestion
? (pending?.from ? store.bot(pending.from.botId) : undefined)
: (groupSpeakers.get(threadId) ? store.bot(groupSpeakers.get(threadId)!.botId) : undefined) ??
(pending?.from ? store.bot(pending.from.botId) : undefined)
: store.botByThread(threadId);
// A surviving question belongs to its original asker, never a later speaker.
if (group && persistentQuestion && !owner) {
return json(res, 409, userError("serverError.chat.askerGone"));
}
if (!owner && !pending) return json(res, 404, { error: "nothing is waiting on an answer in this conversation" });
const requestOwner = owner ? botForThread(owner.id, threadId) : null;
const outcome = await answerRequest(threadId, requestOwner?.modelSelection.instanceId ?? "", requestId, behavior, body.message, owner ? { id: owner.id, name: owner.name } : undefined, body.always === true, body.rememberCommand === true);
if (outcome === "unavailable" && isPersistentQuestionCard(pending?.card) && behavior === "answer") {
if (!pending?.card) return json(res, 404, userError("serverError.chat.questionGone"));
const answer = typeof body.message === "string" ? body.message.trim() : "";
if (!answer) return json(res, 400, { error: "a question answer is required" });
if (!owner) return json(res, 409, userError("serverError.chat.askerGone"));
try {
const reply = await deliverLateQuestionAnswer(auth, threadId, requestId, answer, pending, owner);
return json(res, 200, { ok: true, outcome: "answered", late: true, ...(reply.queued ? { queued: true } : {}) });
} catch (error) {
return json(res, 409, { error: error instanceof Error ? error.message : "the late answer could not be queued" });
}
}
return json(res, 200, { ok: true, outcome });
});
}
m = path.match(/^\/api\/bots\/([\w-]+)\/interrupt$/);
if (m && method === "POST") {
const bot = store.bot(m[1]);
if (!bot) return json(res, 404, { error: "no such bot" });
const rawBody = await readBody(req);
if (rawBody !== null && (typeof rawBody !== "object" || Array.isArray(rawBody))) {
return json(res, 400, { error: "body must be a JSON object" });
}
const body = rawBody ?? {};
requirePinnedClientThread(bot.id, body.threadId);
const expectedThreadId = body.threadId;
if (expectedThreadId !== undefined && (typeof expectedThreadId !== "string" || !/^[\w-]+$/.test(expectedThreadId))) {
return json(res, 400, { error: "threadId must be a task id" });
}
// The turn the person saw running. Once it is over (the second click of a double click), the Stop is done:
// the turn after it, often their queued message, is not theirs to stop with it.
const turnId = typeof body.turnId === "string" ? body.turnId : undefined;
if (body.turnId !== undefined && (!turnId || turnId.length > 200)) {
return json(res, 400, { error: "turnId must name a turn" });
}
const stopRefused = (threadId: string): boolean => {
const refusal = owners.stopRefusal(auth, threadId);
if (refusal) json(res, 403, { error: refusal, code: "stop_not_yours" });
return refusal !== null;
};
if (typeof expectedThreadId === "string" && store.taskByThread(bot.id, expectedThreadId)) {
if (!stopReachesLiveTurn(turnId, liveTurn(expectedThreadId))) return json(res, 200, { ok: true, outcome: "already-stopped" });
if (stopRefused(expectedThreadId)) return;
await stopThreadForPerson(bot.id, expectedThreadId, messageSender(auth));
return json(res, 200, { ok: true });
}
const directClaim = directTurnDispatchClaims.get(bot.threadId);
const routineRun = routines!.activeBotRunForBot(bot.id);
if (routineRun) {
if (expectedThreadId !== undefined && routineRun.threadId !== expectedThreadId) {
return json(res, 409, userError("serverError.chat.routineElsewhere"));
}
cancelDirectTurnDispatch(bot.id, routineRun.threadId ?? expectedThreadId);
if (routineRun.threadId) {
revokeInternalCapabilitiesForThread(routineRun.threadId);
}
await routines!.cancelRun(routineRun.id);
return json(res, 200, { ok: true });
}
const instance = registry.get((botForThread(bot.id, expectedThreadId ?? bot.threadId) ?? bot).modelSelection.instanceId);
const busyGroup = activeGroupTurnForBot(bot.id, expectedThreadId);
if (busyGroup) {
if (expectedThreadId !== undefined && busyGroup.threadId !== expectedThreadId) {
return json(res, 409, userError("serverError.chat.busyInRoom", { room: busyGroup.group.name }));
}
if (stopRefused(busyGroup.threadId)) return;
cancelGroupTurnOperations(busyGroup.group.id, busyGroup.threadId);
revokeInternalCapabilitiesForThread(busyGroup.threadId);
await instance?.adapter.interruptTurn(busyGroup.threadId).catch(() => {});
closeOpenApprovals(busyGroup.threadId);
return json(res, 200, { ok: true });
}
if (
expectedThreadId !== undefined &&
!busyGroup &&
bot.threadId !== expectedThreadId &&
directClaim?.threadId !== expectedThreadId
) {
return json(res, 409, { error: "the bot switched tasks before it could be interrupted" });
}
if (!stopReachesLiveTurn(turnId, liveTurn(expectedThreadId ?? bot.threadId))) return json(res, 200, { ok: true, outcome: "already-stopped" });
if (stopRefused(expectedThreadId ?? bot.threadId)) return;
await stopThreadForPerson(bot.id, expectedThreadId ?? bot.threadId, messageSender(auth));
return json(res, 200, { ok: true });
}
return PASS;
};
return route;
}