Skip to content

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

One list: a My Cloud bot's files pass through untouched by route, its video plays, and its downloads run to the end

milind-soni91b1c1842f87
diff --git a/server/places/place-proxy.test.ts b/server/places/place-proxy.test.ts
index a4cd2ffb2b..7f7f1117c1 100644
--- a/server/places/place-proxy.test.ts
+++ b/server/places/place-proxy.test.ts
@@ -6,7 +6,7 @@ import type { AddressInfo } from "node:net";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { json, readBody } from "../harness/http.ts";
-import { createPlaceProxy, frameForBot, parsePlaceSession, placedPath, type PlaceProxy } from "./place-proxy.ts";
+import { createPlaceProxy, frameForBot, parsePlaceSession, placedPath, relayFrames, type PlaceProxy } from "./place-proxy.ts";
const TOKEN = "omb_sess_test-token-0123456789";
const OWNER = "o".repeat(43);
@@ -276,14 +276,20 @@ describe("what the fix round closed", () => {
it("forwards a message's file, and hands back its media link on the conversation's place route", async () => {
await (await ask("/api/bots/cloud%3Ascout?messages=80")).text();
seen.length = 0;
- answerWith = (_req, res) => void res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ url: "/api/threads/t1/messages/m1/file?media=abc-123", mime: "video/mp4" }));
+ // What the gallery does for a video: ask for a link (the answer says it is one), check it is this message's own
+ // route, then let the <video> element fetch it in ranges.
+ answerWith = (_req, res) => void res.writeHead(200, { "content-type": "application/json", "x-openmausbot-media": "1" }).end(JSON.stringify({ url: "/api/threads/t1/messages/m1/file?media=abc-123", mime: "video/mp4" }));
const linked = await ask("/api/threads/cloud%3At1/messages/m1/file", { method: "POST", body: JSON.stringify({ path: "cloud--aa11-bb22.png", media: true }) });
expect(linked.status).toBe(200);
- expect(await linked.json()).toEqual({ url: "/api/threads/cloud%3At1/messages/m1/file?media=abc-123", mime: "video/mp4" });
+ expect(linked.headers.get("x-openmausbot-media")).toBe("1");
+ const link = await linked.json() as { url: string; mime: string };
+ expect(link).toEqual({ url: "/api/threads/cloud%3At1/messages/m1/file?media=abc-123", mime: "video/mp4" });
+ const route = `/api/threads/${encodeURIComponent("cloud:t1")}/messages/${encodeURIComponent("m1")}/file?media=`;
+ expect(link.url.startsWith(route) && /^[\w-]+$/.test(link.url.slice(route.length))).toBe(true);
expect(seen[0]).toMatchObject({ method: "POST", url: "/api/threads/t1/messages/m1/file" });
expect(JSON.parse(seen[0]!.body)).toEqual({ path: "/data/attachments/aa11-bb22.png", media: true });
answerWith = (_req, res) => void res.writeHead(206, { "content-type": "video/mp4", "content-range": "bytes 0-2/10", "accept-ranges": "bytes", "content-length": "3" }).end(Buffer.from([1, 2, 3]));
- const played = await ask("/api/threads/cloud%3At1/messages/m1/file?media=abc-123", { headers: { range: "bytes=0-2" } });
+ const played = await ask(link.url, { headers: { range: "bytes=0-2" } });
expect(played.status).toBe(206);
expect(played.headers.get("content-range")).toBe("bytes 0-2/10");
expect(seen.at(-1)).toMatchObject({ url: "/api/threads/t1/messages/m1/file?media=abc-123", range: "bytes=0-2" });
@@ -373,3 +379,63 @@ describe("what the fix round closed", () => {
stop.abort();
});
});
+
+describe("the delta round", () => {
+ it("passes a JSON file a bot made through byte for byte, as a download this origin never runs", async () => {
+ const file = JSON.stringify({ botId: "scout", threadId: "t1", path: "/data/x.json", url: "/api/threads/t1/messages/m1/file?media=a", source: "/Users/someone/x.json", nested: { fromBotId: "atlas" } }, null, 2);
+ answerWith = (_req, res) => void res.writeHead(200, { "content-type": "application/json; charset=utf-8", "content-disposition": "inline; filename=\"x.json\"" }).end(file);
+ for (const [path, init] of [["/api/attachments/cloud--x.json", {}], ["/api/threads/cloud%3At1/messages/m1/file", { method: "POST", body: JSON.stringify({ path: "/data/x.json" }) }]] as const) {
+ const answer = await ask(path, init);
+ expect(await answer.text(), path).toBe(file);
+ expect(answer.headers.get("content-disposition"), path).toBe('attachment; filename="x.json"');
+ expect(answer.headers.get("x-content-type-options"), path).toBe("nosniff");
+ expect(answer.headers.get("content-security-policy"), path).toBe("sandbox; default-src 'none'");
+ }
+ });
+
+ it("hands a range past the end, and any other refusal of a file, to the page with its own status", async () => {
+ answerWith = (_req, res) => void res.writeHead(416, { "content-type": "text/plain", "content-range": "bytes */10" }).end("");
+ const answer = await ask("/api/threads/cloud%3At1/messages/m1/file?media=abc", { headers: { range: "bytes=50-60" } });
+ expect(answer.status).toBe(416);
+ expect(answer.headers.get("content-range")).toBe("bytes */10");
+ answerWith = (_req, res) => void res.writeHead(404, { "content-type": "application/json" }).end(JSON.stringify({ error: "no such file" }));
+ const gone = await ask("/api/attachments/cloud--x.png");
+ expect(gone.status).toBe(404);
+ expect(await gone.json()).toEqual({ error: "no such file" });
+ });
+
+ it("bounds the wait for a file's answer, never the download itself while its bytes keep coming", async () => {
+ local.closeAllConnections();
+ await new Promise((done) => local.close(done));
+ proxy = createPlaceProxy({ requestMs: 1_000, idleMs: 2_000 });
+ proxy.setOwnerToken(OWNER);
+ proxy.setSession({ origin: cloudUrl, token: TOKEN });
+ local = createServer((req, res) => {
+ const url = new URL(req.url!, "http://127.0.0.1");
+ void proxy.route({ req, res, url, path: url.pathname, method: req.method!, auth: callerAuth, json, readBody });
+ });
+ localUrl = await listen(local);
+ answerWith = (_req, res) => {
+ res.writeHead(200, { "content-type": "application/zip" });
+ let sent = 0;
+ const tick = setInterval(() => { res.write(Buffer.alloc(1_000, sent)); if (++sent === 10) { clearInterval(tick); res.end(); } }, 300);
+ };
+ const answer = await ask("/api/attachments/cloud--big.zip");
+ expect((await answer.arrayBuffer()).byteLength).toBe(10_000);
+ });
+});
+
+describe("relaying the stream", () => {
+ it("writes nothing once the session went, even an event already read", async () => {
+ const stop = new AbortController();
+ const written: string[] = [];
+ async function* events() {
+ yield { id: "s:1", data: JSON.stringify({ kind: "message", threadId: "t1", message: { id: "a", text: "first" } }) };
+ stop.abort();
+ yield { id: "s:2", data: JSON.stringify({ kind: "message", threadId: "t1", message: { id: "b", text: "after" } }) };
+ }
+ await relayFrames(events(), { bot: "scout", threads: new Set(["t1"]), signal: stop.signal, write: async (chunk) => { written.push(chunk); return true; } });
+ expect(written.join("")).toContain("first");
+ expect(written.join("")).not.toContain("after");
+ });
+});
diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.ts
index eaeaa2d69b..5e9c1aad8f 100644
--- a/server/places/place-proxy.ts
+++ b/server/places/place-proxy.ts
@@ -29,6 +29,13 @@ const SESSION_TOKEN = /^omb_sess_[\w-]{8,256}$/;
const OWN_ID = /^[\w-]{1,128}$/;
/** How long one forwarded request may take: a send on a Cloud that has to start first takes about 20 s. */
const REQUEST_MS = 90_000;
+/** How long a file's bytes may stall once they started coming: a big download runs as long as it keeps moving. */
+const IDLE_MS = 60_000;
+/** My Cloud's routes that answer with a file's bytes (or a link or a list for one): never rewritten, always served as
+ * bytes this origin never runs. Everything else forwarded is the app's own JSON, rewritten into this page's ids. */
+const BYTE_ROUTE = /^\/api\/(?:threads\/[\w-]+\/messages\/[\w-]+\/(?:file|image)|attachments\/[\w-][\w.-]*)$/;
+/** Headers of My Cloud's file answers that the page reads: a folder's list, a link a player can play, a kept original. */
+const PAGE_FILE_HEADERS = ["x-openmausbot-folder", "x-openmausbot-media", "x-openmausbot-kept-original"];
const BODY_MAX = 4_000_000;
/** The most file names kept to send back a message that names one. */
const FILES_KEPT = 5_000;
@@ -159,6 +166,7 @@ export function servedFileHeaders(upstream: Pick<Response, "headers">): Record<s
const value = upstream.headers.get(name);
if (value && /^[\w ,=/*-]{1,200}$/.test(value)) headers[name] = value;
}
+ for (const name of PAGE_FILE_HEADERS) if (upstream.headers.get(name) === "1") headers[name] = "1";
if (!INLINE_IMAGE.test(type) && !INLINE_AUDIO.test(type)) {
const named = /filename\*?=(?:UTF-8'')?"?([^";]{1,200})"?/i.exec(upstream.headers.get("content-disposition") ?? "")?.[1];
const safe = named ? named.replace(/[^\w .()-]/g, "_") : "";
@@ -180,6 +188,21 @@ async function written(res: ServerResponse, chunk: string | Uint8Array): Promise
});
}
+/** My Cloud's stream events, as the page gets them: only the bot's frames, in its ids, each written once the page took
+ * the last. Nothing is written once `signal` aborts (the session changed or went), even an event already read. */
+export async function relayFrames(events: AsyncIterable<{ id: string | null; data: string }>, { bot, threads, signal, remember = () => {}, write }: {
+ bot: string; threads: Set<string>; signal: AbortSignal; remember?: (name: string, path: string) => void; write: (chunk: string) => Promise<boolean>;
+}): Promise<void> {
+ for await (const event of events) {
+ if (signal.aborted) return;
+ let frame: unknown;
+ try { frame = JSON.parse(event.data); } catch { continue; }
+ const kept = frameForBot(frame, bot, threads);
+ if (kept === null) continue;
+ if (!(await write(`${event.id ? `id: ${event.id}\n` : ""}data: ${JSON.stringify(intoPlace(kept, remember))}\n\n`))) return;
+ }
+}
+
/** Events in the text/event-stream format, one at a time as their blank line arrives: never held for more. */
export async function* sseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<{ id: string | null; data: string }> {
const reader = body.getReader();
@@ -216,7 +239,7 @@ export async function* sseEvents(body: ReadableStream<Uint8Array>): AsyncGenerat
* `fetch`: requests to My Cloud. The session arrives with `setSession` (main, over the private port) and goes with
* `setSession(null)`; the app's capability with `setOwnerToken`.
*/
-export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch }: { fetch?: Fetch } = {}) {
+export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch, requestMs = REQUEST_MS, idleMs = IDLE_MS }: { fetch?: Fetch; requestMs?: number; idleMs?: number } = {}) {
let session: PlaceSession | null = null;
/** Every live stream open on the session: a new session, or none, ends them all at once. */
const streams = new Set<AbortController>();
@@ -238,7 +261,7 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
/** My Cloud's answer in this page's terms. Its sleeping, sign-in and limit answers are said as My Cloud's, so this
* page never takes them for its own server going to sleep, its own sign-in ending or its own bot limit. */
- async function answer(ctx: RouteContext, upstream: Response): Promise<void> {
+ async function answer(ctx: RouteContext, upstream: Response, bytes = false, idle: () => void = () => {}): Promise<void> {
const { res, json } = ctx;
if (upstream.status === 503 && upstream.headers.get(CLOUD_POWER_HEADER) === "asleep") {
await upstream.body?.cancel().catch(() => {});
@@ -249,6 +272,7 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
return refuse(res, json, 502, "serverError.place.signIn", "place_signin");
}
const type = upstream.headers.get("content-type") ?? "";
+ if (bytes) return answerBytes(ctx, upstream, idle);
if (/^application\/json\b/i.test(type) || !upstream.ok) {
let body: unknown = null;
try { body = await upstream.json(); } catch { body = null; }
@@ -259,14 +283,30 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
const { code: _code, ...said } = placed;
return json(res, upstream.status === 403 ? 409 : upstream.status, { ...said, code: "place_refused" });
}
- // A folder a message names comes back as its list, marked so the page draws it as one.
- if (upstream.headers.get("x-openmausbot-folder") === "1") res.setHeader("x-openmausbot-folder", "1");
return json(res, upstream.status, placed);
}
- // A file or an image: its bytes as they come, kept by nobody, never run on this origin.
- res.writeHead(upstream.status, servedFileHeaders(upstream));
+ return answerBytes(ctx, upstream, idle);
+ }
+
+ /** A file route's answer, decided by the route and never by what My Cloud says the bytes are: passed on exactly as
+ * they came (a JSON file a bot made stays byte for byte its own), with the headers that keep this origin from running
+ * them. Only a link a player asked for moves onto the conversation's place route. A refusal (a range past the end,
+ * a file no longer there) reaches the page with its own status. */
+ async function answerBytes(ctx: RouteContext, upstream: Response, idle: () => void): Promise<void> {
+ const { res } = ctx;
+ const headers = servedFileHeaders(upstream);
+ if (upstream.headers.get("x-openmausbot-media") === "1" && upstream.ok) {
+ const said = await upstream.json().catch(() => null) as { url?: unknown; mime?: unknown } | null;
+ const placed = record(said) ? intoPlace({ url: said.url, mime: said.mime }) : {};
+ const body = Buffer.from(JSON.stringify(placed));
+ res.writeHead(upstream.status, { ...headers, "content-type": "application/json", "content-length": String(body.byteLength) });
+ res.end(body);
+ return;
+ }
+ res.writeHead(upstream.status, headers);
if (!upstream.body) { res.end(); return; }
for await (const chunk of upstream.body as unknown as AsyncIterable<Uint8Array>) {
+ idle();
if (!(await written(res, chunk))) { await upstream.body.cancel().catch(() => {}); return; }
}
res.end();
@@ -288,11 +328,15 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
const stop = new AbortController();
const gone = () => { if (!res.writableEnded) stop.abort(); };
res.once("close", gone);
+ const bytes = BYTE_ROUTE.test(path);
+ // The wait for My Cloud's answer is bounded; a file's bytes then run as long as they keep moving.
+ let timer = setTimeout(() => stop.abort(), requestMs);
+ const idle = () => { clearTimeout(timer); timer = setTimeout(() => stop.abort(), idleMs); };
let upstream: Response;
try {
upstream = await fetchImpl(`${own.origin}${path}${query}`, {
method, redirect: "error", cache: "no-store", body,
- signal: AbortSignal.any([stop.signal, AbortSignal.timeout(REQUEST_MS)]),
+ signal: stop.signal,
headers: {
accept: String(req.headers.accept ?? "application/json"), authorization: `Bearer ${own.token}`,
...(body !== undefined ? { "content-type": "application/json" } : {}),
@@ -301,11 +345,15 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
},
});
} catch {
+ clearTimeout(timer);
res.off("close", gone);
if (res.headersSent || res.destroyed) return;
return refuse(res, json, 502, "serverError.place.offline", "place_offline");
}
- try { await answer(ctx, upstream); } finally { res.off("close", gone); }
+ if (bytes) idle();
+ try { await answer(ctx, upstream, bytes, idle); } catch {
+ if (!res.headersSent) refuse(res, json, 502, "serverError.place.offline", "place_offline"); else res.destroy();
+ } finally { clearTimeout(timer); res.off("close", gone); }
}
/** The bot's live stream: My Cloud's own stream, opened as the person, cut to this bot's frames and passed on frame by
@@ -353,14 +401,7 @@ export function createPlaceProxy({ fetch: fetchImpl = globalThis.fetch as Fetch
// Not awaited: the request is answered, and the stream runs on until either side closes it.
void (async () => {
try {
- for await (const event of sseEvents(upstream.body!)) {
- if (stop.signal.aborted) break;
- let frame: unknown;
- try { frame = JSON.parse(event.data); } catch { continue; }
- const kept = frameForBot(frame, bot, threads);
- if (kept === null) continue;
- if (!(await written(res, `${event.id ? `id: ${event.id}\n` : ""}data: ${JSON.stringify(intoPlace(kept, remember))}\n\n`))) break;
- }
+ await relayFrames(sseEvents(upstream.body!), { bot, threads, signal: stop.signal, remember, write: (chunk) => written(res, chunk) });
} catch {
// The end of either side ends the stream; the page reconnects.
} finally {
diff --git a/shared/place-ids.test.ts b/shared/place-ids.test.ts
index 5e28403f2e..e4d6653878 100644
--- a/shared/place-ids.test.ts
+++ b/shared/place-ids.test.ts
@@ -37,4 +37,14 @@ describe("ids and files cross the boundary, words never do", () => {
expect(intoPlace({ url: "/api/threads/t1/messages/m1/file?media=abc" })).toEqual({ url: "/api/threads/cloud%3At1/messages/m1/file?media=abc" });
expect(intoPlace({ message: { url: "/api/threads/t1/messages/m1/file?media=abc" } })).toEqual({ message: { url: "/api/threads/t1/messages/m1/file?media=abc" } });
});
+
+ it("leaves a card's own data alone: a routine run's, a data result's and a burst's", () => {
+ const message = { threadId: "t1", routineRun: { data: { botId: "x", threadId: "y" } }, dataResult: { botId: "x", cardId: "c" }, burst: { extra: { fromThreadId: "z" } } };
+ const placed = intoPlace(message) as typeof message;
+ expect(placed.threadId).toBe("cloud:t1");
+ expect(placed.routineRun).toEqual(message.routineRun);
+ expect(placed.dataResult).toEqual(message.dataResult);
+ expect(placed.burst).toEqual(message.burst);
+ expect(outOfPlace({ dataResult: { botId: "cloud:x" } })).toEqual({ dataResult: { botId: "cloud:x" } });
+ });
});
diff --git a/shared/place-ids.ts b/shared/place-ids.ts
index 7a5be6eb4e..175b6113e2 100644
--- a/shared/place-ids.ts
+++ b/shared/place-ids.ts
@@ -19,16 +19,20 @@ export const placeId = (id: string): string => (isPlaceId(id) ? id : `${PREFIX}$
/** The id My Cloud itself knows, from the one this page names. */
export const ownId = (id: string): string => (isPlaceId(id) ? id.slice(PREFIX.length) : id);
-/** The keys whose values are a bot's or a conversation's id, or a list of them: `botId`, `threadId`, `fromThreadId`,
- * `mainThreadId`, `botIds`… Only these are rewritten, never words: a message that starts with "cloud:" stays as written. */
-export const ID_KEY = /^(?:[a-z][a-zA-Z]*(?:Bot|Thread)|bot|thread)Ids?$/;
+/** The keys, in the frames and bodies a conversation uses, whose values are a bot's or a conversation's id (or a list
+ * of them). Only these are rewritten, and never inside what anyone wrote or a card's own data (WRITTEN): a message that
+ * starts with "cloud:" stays as written, and a key a bot or a routine chose is never taken for an id. */
+const ID_KEYS = new Set(["botId", "threadId", "mainThreadId", "fromBotId", "fromThreadId", "withBotId", "busyBotId", "waitingForBotId", "fallbackBotId", "botIds", "threadIds"]);
+const idKey = (key: string | null): boolean => key !== null && ID_KEYS.has(key);
/** A picture of My Cloud's this page shows by its address: a bot's own avatar. */
const FILE_URL_KEYS = new Set(["avatarUrl"]);
const FILE_URL = /^\/api\/attachments\/([\w-][\w.-]*)$/;
/** A link My Cloud's file route gives a <video> or <audio> element: on the conversation's own route. */
const MEDIA_URL = /^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/file\?media=([\w-]+)$/;
/** What a bot or a person wrote, or an engine's own words and tool calls: never rewritten, whatever keys they hold. */
-const WRITTEN = new Set(["text", "widget", "app", "tool", "card", "digest", "compaction", "summary", "content", "markdown", "html", "input", "output", "args", "result"]);
+const WRITTEN = new Set(["text", "widget", "app", "tool", "card", "digest", "compaction", "summary", "content", "markdown", "html", "input", "output", "args", "result",
+ // A card's own data: a routine run's, a data result's, a burst's, a goal run's, a settings card's.
+ "data", "extra", "dataResult", "routineRun", "burst", "goalRun", "settingsCard", "automation"]);
const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
const basename = (path: string): string => path.split(/[\\/]/).pop() ?? "";
@@ -38,9 +42,9 @@ type Way = { ids: Ids; path: (path: string) => string; url: (url: string) => str
function rewrite(value: unknown, way: Way, key: string | null, depth: number): unknown {
if (depth > 64) return value;
- if (typeof value === "string") return key !== null && ID_KEY.test(key) ? way.ids(value) : value;
+ if (typeof value === "string") return idKey(key) ? way.ids(value) : value;
if (Array.isArray(value)) {
- const listOfIds = key !== null && ID_KEY.test(key);
+ const listOfIds = idKey(key);
return value.map((item) => (listOfIds && typeof item === "string" ? way.ids(item) : rewrite(item, way, key === "bots" ? "bot" : key === "attachments" ? "attachment" : null, depth + 1)));
}
if (!record(value)) return value;
diff --git a/src/lib/place-chat-live.test.ts b/src/lib/place-chat-live.test.ts
index 616f7034de..34408d7c1d 100644
--- a/src/lib/place-chat-live.test.ts
+++ b/src/lib/place-chat-live.test.ts
@@ -66,15 +66,18 @@ it("a dropped stream retries only after main says My Cloud is awake, and never k
expect(made).toHaveLength(2);
});
-it("a stream that never opens gives the bot to My Cloud's page after its tries", async () => {
+it("a first open that never connects tries again at once, even while the Admin's word lags, then opens My Cloud's page", async () => {
const cannot = vi.fn();
- awake.mockResolvedValue(true);
keepLive("cloud:scout", cannot, platform());
- for (let i = 0; i < 3; i++) {
- made.at(-1)!.onerror?.();
- await vi.advanceTimersByTimeAsync(20_000);
- }
+ made[0]!.onerror?.();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(made).toHaveLength(2);
+ made[1]!.onerror?.();
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(made).toHaveLength(3);
+ made[2]!.onerror?.();
expect(cannot).toHaveBeenCalledOnce();
+ expect(awake).not.toHaveBeenCalled();
});
it("reads the bot again as background work when the stream starts over", async () => {
diff --git a/src/lib/place-chat.ts b/src/lib/place-chat.ts
index 8eeb5298fd..703ae3b80f 100644
--- a/src/lib/place-chat.ts
+++ b/src/lib/place-chat.ts
@@ -163,6 +163,9 @@ export function keepLive(key: string, cannot: () => void, platform: Platform = b
/** Opens the stream again once main says My Cloud is awake. `retry`: the stream's own retry, not the person. */
const look = async (retry: boolean) => {
if (stopped || source || looking || !platform.visible()) return;
+ // Before the stream has ever opened, main has just readied the session (My Cloud answered it, woken by the click):
+ // the Admin's word may lag behind that, so the first tries go straight on, and after them My Cloud's page opens.
+ if (retry && !opened) { connect(); return; }
if (!retry && performance.now() - lookedAt < AWAKE_LOOK_MS) return;
looking = true;
lookedAt = performance.now();