Skip to content

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

Train P: replay a turn only to the bot that sent it, and cover a continued reply

milind-soni76bc99a4c935
diff --git a/server/drivers/openai-chat-prefix.test.ts b/server/drivers/openai-chat-prefix.test.ts
index 016f0612d7..a105e42d71 100644
--- a/server/drivers/openai-chat-prefix.test.ts
+++ b/server/drivers/openai-chat-prefix.test.ts
@@ -164,6 +164,46 @@ describe("a conversation's requests to an OpenAI-compatible model", () => {
expect(recorder.events).toContainEqual(expect.objectContaining({ type: "thread.token-usage.updated", contextTokens: 3002, contextWindow: 4096 }));
});
+ it("only grow at the end after a reply cut at the output limit and continued, which the app stores as one reply", async () => {
+ const requests: ChatRequest[] = [];
+ const server = createServer(async (request, response) => {
+ if (request.method !== "POST") { response.setHeader("content-type", "application/json"); response.end('{"data":[]}'); return; }
+ let data = "";
+ for await (const part of request) data += part.toString();
+ const body = JSON.parse(data) as { messages: Array<{ role?: string; content?: unknown }> };
+ requests.push({ messages: body.messages });
+ const continuing = String(body.messages.at(-1)?.content).includes("cut at the output limit");
+ sse(response, { content: continuing ? " and the rest." : "The first part" }, continuing ? "stop" : "length");
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("fixture did not bind TCP");
+ const instance = await OpenAICompatDriver.create({
+ instanceId: randomUUID(), displayName: "Cut fixture", enabled: true,
+ config: { url: `http://127.0.0.1:${address.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY", tools: false }, environment: { FIXTURE_CHAT_KEY: "fixture-credential-5b0f3c" },
+ });
+ const recorder = recordEvents(instance.adapter);
+ cleanups.push(async () => {
+ recorder.stop();
+ await instance.dispose();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+ const threadId = randomUUID();
+ const transcript: Transcript = [];
+ for (const text of ["First question", "Second question"]) {
+ const done = recorder.events.length;
+ await instance.adapter.sendTurn({ threadId, botId: "cut-bot", text, model: "fixture-model", system: "Rules", transcript: [...transcript] });
+ expect(await recorder.until((event) => event.type === "turn.completed" && recorder.events.indexOf(event) >= done)).toMatchObject({ ok: true });
+ const replies = recorder.events.slice(done).flatMap((event) => event.type === "item.completed" && event.itemType === "assistant_text" ? [event.text!] : []);
+ expect(replies).toEqual(["The first part and the rest."]);
+ transcript.push({ role: "user", text }, ...replies.map((reply) => ({ role: "assistant" as const, text: reply })));
+ }
+ expect(requests).toHaveLength(4);
+ expect(changes(requests)).toEqual([]);
+ expect(requests[2]!.messages.map((message) => message.role)).toEqual(["system", "user", "assistant", "user", "assistant", "user"]);
+ });
+
it("only grow at the end across turns that call tools, while the changing instructions move on", async () => {
const lookup = await mcp("lookup");
const chat = await conversation("lookup_get");
diff --git a/server/drivers/openai-chat-replay.ts b/server/drivers/openai-chat-replay.ts
index d132120bd2..c8c018d339 100644
--- a/server/drivers/openai-chat-replay.ts
+++ b/server/drivers/openai-chat-replay.ts
@@ -75,8 +75,8 @@ export function createChatReplay() {
const delivered = new Map<string, DeliveredUserMessage[]>();
const lastSent = new Map<string, { tools: string; messages: string[] }>();
return {
- replay(threadId: string, transcript: readonly TranscriptEntry[], model: string) {
- const found = replayDelivered(transcript, delivered.get(threadId) ?? [], model);
+ replay(conversation: string, transcript: readonly TranscriptEntry[], model: string) {
+ const found = replayDelivered(transcript, delivered.get(conversation) ?? [], model);
const history: OpenAIChatMessage[] = [];
for (let index = 0; index < transcript.length; index++) {
history.push({ role: transcript[index]!.role, content: found.content.get(index) ?? transcript[index]!.text });
@@ -85,7 +85,7 @@ export function createChatReplay() {
}
const record = (request: Pick<DeliveredUserMessage, "text" | "sent" | "volatile">): DeliveredUserMessage => {
const kept = { ...request, after: transcript.length ? fingerprint(transcript.at(-1)!.text) : "" };
- keepRecent(delivered, threadId, [...found.matched, kept]);
+ keepRecent(delivered, conversation, [...found.matched, kept]);
return kept;
};
return { history, volatile: found.volatile, record };
@@ -101,10 +101,10 @@ export function createChatReplay() {
}
},
/** How much of the conversation's previous request this one starts with: all a provider's prompt cache can reuse. */
- repeated(threadId: string, messages: readonly OpenAIChatMessage[], tools: readonly ChatToolDefinition[]) {
+ repeated(conversation: string, messages: readonly OpenAIChatMessage[], tools: readonly ChatToolDefinition[]) {
const sent = { tools: fingerprint(JSON.stringify(tools)), messages: messages.map((message) => fingerprint(JSON.stringify(message))) };
- const before = lastSent.get(threadId);
- keepRecent(lastSent, threadId, sent);
+ const before = lastSent.get(conversation);
+ keepRecent(lastSent, conversation, sent);
if (!before) return {};
const changed = before.messages.findIndex((hash, index) => sent.messages[index] !== hash);
return { repeats: { messages: changed < 0 ? before.messages.length : changed, of: before.messages.length, tools: before.tools === sent.tools } };
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 6a46bc3547..8ac74343d6 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -432,10 +432,12 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const seesImages = (turn: SendTurnInput) =>
options.imageInput?.(turn.model || options.models().default) ?? true;
+ /** Thread ids may coincide across bots, so what one bot sent is never replayed to another. */
+ const conversationKey = (turn: SendTurnInput) => JSON.stringify([turn.threadId, turn.botId ?? null]);
const messagesFor = (turn: SendTurnInput, model: string): { messages: OpenAIChatMessage[]; record: DeliveredUserMessage } => {
const halves = promptHalves(turn);
const transcript = turn.transcript ?? [];
- const replay = conversations.replay(turn.threadId, transcript, model);
+ const replay = conversations.replay(conversationKey(turn), transcript, model);
const volatile = halves.volatile.trim();
const note = halves.stable === null || (!turn.mentionTurn && replay.volatile === volatile) ? ""
: volatileContextNote(volatile, Boolean(replay.volatile));
@@ -482,7 +484,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
dir, source: options.nativeLog.source,
msg: JSON.parse(JSON.stringify(msg, (_key, part) => typeof part === "string" ? safeText(part) : part)),
});
- const grantsKey = JSON.stringify([turn.threadId, turn.botId ?? null]);
+ const grantsKey = conversationKey(turn);
const granted = sessionGrants.get(grantsKey) ?? new Set<string>();
keepRecent(sessionGrants, grantsKey, granted);
const approval = createChatToolApproval({
@@ -571,7 +573,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
// Servers still starting join between rounds, never once the tools were dropped (none left while ask_user is allowed).
const joined = !questionAllowed || tools.definitions.length ? await joinLateChatTools(tools, [ASK_USER_TOOL_DEFINITION]) : undefined;
for (const message of joined ?? []) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
- native("out", { ...object(options.nativeLog.outgoing(turn, messages, model, tools.definitions)), ...conversations.repeated(turn.threadId, messages, tools.definitions),
+ native("out", { ...object(options.nativeLog.outgoing(turn, messages, model, tools.definitions)), ...conversations.repeated(conversationKey(turn), messages, tools.definitions),
...(process.env.OPENMAUS_LOG_CHAT_REQUESTS === "1" ? { messages, tools: tools.definitions } : {}) });
let attempt = 0;
let resends = 0;