Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// The internal calls behind the agents server's x_* and research_* tools.
//
// The handler runs inside index.ts's /api/internal/ block, after the capability bearer is checked (the route table runs
// before that block). It re-checks the credential and the bot's own switch on every call: the tool list a bot was shown
// at the start of its turn is not permission to spend.
import type { ServerResponse } from "node:http";
import { z } from "zod";
import type { json as sendJson } from "../harness/http.ts";
import type { ServiceCredential } from "../included-services.ts";
import { costLine, createResearchClient, RESEARCH_ID, RESEARCH_SEARCH_MAX, type ResearchClient } from "../research.ts";
import {
createXClient,
DEFAULT_POSTS,
MAX_POSTS,
normalizeHandle,
parsePostRef,
X_MESSAGES,
XResearchError,
type XResearchClient,
type XResearchErrorCode,
} from "../x-research.ts";
import { PASS } from "./table.ts";
export interface XResearchDeps {
/** The person's own treg key, else the plan's relay credential (researchCredential), read per request. */
credential: () => ServiceCredential | null;
/** The bot's research switch: on unless switched off. */
botEnabled: (botId: string) => boolean;
/** Tests pass fakes; the server builds the real clients per call. */
client?: (credential: ServiceCredential) => XResearchClient;
research?: (credential: ServiceCredential) => ResearchClient;
/** This server is a Cloud home: a refused relay token is the Admin's to replace, not a sign-in to redo. */
cloudHome?: boolean;
/** The plan's relay refused a research call because research is off for this account. */
researchOff?: () => void;
}
export interface XInternalContext {
method: string;
path: string;
res: ServerResponse;
json: typeof sendJson;
/** The capability's own bot, never a body field. */
botId: string;
/** index.ts's readInternalBody: re-checks the capability after the read. */
readBody: () => Promise<unknown>;
}
const X_PREFIX = "/api/internal/x/";
const X_ACTIONS = new Set(["search", "user-posts", "post", "profile"]);
const RESEARCH_PREFIX = "/api/internal/research/";
const RESEARCH_ACTIONS = new Set(["search", "endpoint", "call"]);
/** 401 is never used: on internal routes it means the capability expired. */
function statusFor(code: XResearchErrorCode): number {
return code === "bad_input" ? 400 : code === "not_found" ? 404 : 502;
}
const limit = z.number().int().min(1).max(MAX_POSTS).optional();
const sinceId = z.string().regex(/^\d{1,25}$/, "sinceId must be the digits of an X post id, such as a newestId from an earlier call").optional();
const searchBody = z.object({ query: z.string().trim().min(1).max(512), sort: z.enum(["latest", "top"]).optional(), limit, sinceId });
const userPostsBody = z.object({ handle: z.string(), limit, sinceId, includeReplies: z.boolean().optional() });
const postBody = z.object({ post: z.string(), replies: z.boolean().optional() });
const profileBody = z.object({ handle: z.string() });
const researchId = z.string().regex(RESEARCH_ID, "id must be a research endpoint id from research_search, such as apollo.people.search");
const researchSearchBody = z.object({ job: z.string().trim().min(1).max(300), limit: z.number().int().min(1).max(RESEARCH_SEARCH_MAX).optional() });
const researchCallBody = z.object({
id: researchId,
params: z.union([z.record(z.string().max(200), z.unknown()), z.array(z.unknown()).max(1000)]).optional(),
query: z.record(z.string().min(1).max(200), z.unknown()).optional(),
});
function parse<T>(schema: z.ZodType<T>, body: unknown): T {
const parsed = schema.safeParse(body ?? {});
if (parsed.success) return parsed.data;
const issue = parsed.error.issues[0];
throw new XResearchError("bad_input", `${issue?.path.join(".") || "input"}: ${issue?.message ?? "invalid"}`);
}
function handleFrom(raw: string): string {
const handle = normalizeHandle(raw);
if (!handle) throw new XResearchError("bad_input", "handle must be an X handle such as @openmausbot, or an x.com profile link.");
return handle;
}
async function run(action: string, body: unknown, client: XResearchClient): Promise<unknown> {
if (action === "search") {
const input = parse(searchBody, body);
return client.search({ query: input.query, sort: input.sort ?? "latest", limit: input.limit ?? DEFAULT_POSTS, ...(input.sinceId ? { sinceId: input.sinceId } : {}) });
}
if (action === "user-posts") {
const input = parse(userPostsBody, body);
return client.userPosts({
handle: handleFrom(input.handle),
limit: input.limit ?? DEFAULT_POSTS,
includeReplies: input.includeReplies ?? false,
...(input.sinceId ? { sinceId: input.sinceId } : {}),
});
}
if (action === "post") {
const input = parse(postBody, body);
const ref = parsePostRef(input.post);
if (!ref) throw new XResearchError("bad_input", "post must be an x.com or twitter.com post link, or a post id.");
return client.post({ ...ref, replies: input.replies ?? false });
}
const input = parse(profileBody, body);
return client.profile(handleFrom(input.handle));
}
async function research(action: string, body: unknown, client: ResearchClient): Promise<unknown> {
if (action === "search") {
const input = parse(researchSearchBody, body);
return client.search({ job: input.job, limit: input.limit ?? 5 });
}
if (action === "endpoint") return client.endpoint(parse(z.object({ id: researchId }), body).id);
const input = parse(researchCallBody, body);
const answer = await client.call({ id: input.id, ...(input.params === undefined ? {} : { params: input.params }), ...(input.query ? { query: input.query } : {}) });
const cost = costLine(answer);
return { result: answer.result, ...(cost ? { cost } : {}), ...(answer.callId ? { callId: answer.callId } : {}), ...(answer.upstreamFailed ? { upstreamFailed: answer.upstreamFailed } : {}) };
}
export function createXResearchInternalRoutes(deps: XResearchDeps) {
const xClientFor = deps.client ?? ((credential: ServiceCredential) => createXClient(credential));
const researchClientFor = deps.research ?? ((credential: ServiceCredential) => createResearchClient(credential));
return async (ctx: XInternalContext): Promise<typeof PASS | void> => {
if (ctx.method !== "POST") return PASS;
const prefix = ctx.path.startsWith(X_PREFIX) ? X_PREFIX : ctx.path.startsWith(RESEARCH_PREFIX) ? RESEARCH_PREFIX : null;
const action = prefix ? ctx.path.slice(prefix.length) : "";
if (!prefix || !(prefix === X_PREFIX ? X_ACTIONS : RESEARCH_ACTIONS).has(action)) return PASS;
const credential = deps.credential();
if (!credential) return void ctx.json(ctx.res, 403, { error: X_MESSAGES.noKey });
if (!deps.botEnabled(ctx.botId)) return void ctx.json(ctx.res, 403, { error: X_MESSAGES.botOff });
const body = await ctx.readBody();
try {
ctx.json(ctx.res, 200, prefix === X_PREFIX ? await run(action, body, xClientFor(credential)) : await research(action, body, researchClientFor(credential)));
} catch (error) {
if (!(error instanceof XResearchError)) throw error;
if (error.code === "off" && prefix === RESEARCH_PREFIX) deps.researchOff?.();
const message = error.code === "bad_key" && deps.cloudHome && credential.included ? X_MESSAGES.homeBadKey : error.message;
ctx.json(ctx.res, statusFor(error.code), { error: message, code: error.code });
}
};
}