Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(openai-compat): finalize review and locale parity checks
jonathanwxh-cellce17166c5f74
diff --git a/server/compaction-summary.test.ts b/server/compaction-summary.test.tsindex e10da5d408..5dc7507da6 100644--- a/server/compaction-summary.test.ts+++ b/server/compaction-summary.test.ts@@ -203,3 +203,17 @@ it("says it is summarizing from the start of a summary until it is written, failawait draftSummary(history, { signal: new AbortController().signal, onSummarizing, generateText: () => Promise.reject(new Error("helper down")) });expect(seen).toEqual([true, false, true, false, true, false]);});++it("forwards threadId to generateText when compacting a conversation thread", async () => {+ const received: Array<{ threadId?: string }> = [];+ const summary = await draftSummary(history, {+ signal: new AbortController().signal,+ threadId: "thr-compact-1",+ generateText: async (_prompt, options) => {+ received.push({ threadId: options?.threadId });+ return "Thread summary.";+ },+ });+ expect(summary).toContain("Thread summary.");+ expect(received).toEqual([{ threadId: "thr-compact-1" }]);+});diff --git a/server/compaction-summary.ts b/server/compaction-summary.tsindex dd5266fa25..5a07291fea 100644--- a/server/compaction-summary.ts+++ b/server/compaction-summary.ts@@ -41,9 +41,10 @@ export function summaryPrompt(history: readonly ReplayEntry[]): string {}interface SummaryOptions {- generateText?: (prompt: string, options?: { signal?: AbortSignal }) => Promise<string>;+ generateText?: (prompt: string, options?: { signal?: AbortSignal; threadId?: string }) => Promise<string>;signal: AbortSignal;timeoutMs?: number;+ threadId?: string;/** Told true when the summary starts and false once it is written, failed or stopped. */onSummarizing?: (active: boolean) => void;}@@ -71,7 +72,7 @@ async function summarize(history: readonly ReplayEntry[], options: SummaryOptionmodel = await new Promise<string>((resolve, reject) => {abort = () => reject(signal.reason);signal.addEventListener("abort", abort, { once: true });- Promise.resolve().then(() => options.generateText!(summaryPrompt(history), { signal }))+ Promise.resolve().then(() => options.generateText!(summaryPrompt(history), { signal, ...(options.threadId ? { threadId: options.threadId } : {}) })).then(resolve, reject);});} catch {}diff --git a/server/contracts.ts b/server/contracts.tsindex dbefbf8ffa..5d16c9c7f0 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -590,6 +590,8 @@ export interface TextGenerationUsage {export interface TextGenerationOptions {signal?: AbortSignal;+ /** Optional conversation thread identifier for one-shot calls tied to a thread (e.g. compaction summaries). */+ threadId?: string;onUsage?: (usage: TextGenerationUsage) => void;/** One of this instance's models instead of the driver's quick-call choice: the helper model setting, and the setup* card's quick model (side-jobs.ts). */diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex ad5fbfff63..be1c05ab9f 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -906,7 +906,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)threadId: turn.threadId, turnId, model,usage, hasUsage, failure, toolCalls: seenCalls.size,task: turn.text, updates: deliveredAsides,- messages: request ? messages.slice(messages.indexOf(request) + 1) : [],+ messages: request ? messages.slice(messages.indexOf(request) + 1).map((msg) => JSON.parse(JSON.stringify(msg, (_key, part) => typeof part === "string" ? safeText(part) : part))) : [],});if (handoffPath) emit({ ...base(turn.threadId, turnId), type: "cap.exhausted", handoffPath, reason: continuable });}@@ -974,13 +974,14 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)return () => listeners.delete(listener);},},- generateText: async (prompt, { signal, onUsage, model: named, checkModel } = {}) => {+ generateText: async (prompt, { signal, onUsage, model: named, checkModel, threadId } = {}) => {const model = named ?? options.generateModel?.() ?? options.models().default;signal?.throwIfAborted();checkModel?.(model);- const headerSecrets = customHeaderSecrets(options.customHeaders, { providerInstanceId: input.instanceId });+ const headerContext: RuntimeHeaderContext = { ...(threadId ? { threadId } : {}), providerInstanceId: input.instanceId };+ const headerSecrets = customHeaderSecrets(options.customHeaders, headerContext);try {- const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage, undefined, undefined, { providerInstanceId: input.instanceId });+ const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage, undefined, threadId, headerContext);if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");return maskCustomSecrets(text.trim() ? text : reasoning, headerSecrets);} catch (error) {diff --git a/server/drivers/openai-compat-headers.test.ts b/server/drivers/openai-compat-headers.test.tsindex 4f3b7bc903..e43b2ad244 100644--- a/server/drivers/openai-compat-headers.test.ts+++ b/server/drivers/openai-compat-headers.test.ts@@ -44,7 +44,7 @@ describe("OpenAI-compatible custom headers config & resolution", () => {headers: [{ name: "X-Thread", value: "{threadId}" }, { name: "x-thread", value: "{botId}" }],})).toThrow(/duplicate/i);- for (const badValue of ["", " ", "val\r\nX-Inject: 1", "val\nnext", "val\0zero", "{unknownVar}", "prefix-{thredId}"]) {+ for (const badValue of ["", " ", "val\r\nX-Inject: 1", "val\nnext", "val\0zero", "東京", "em—dash", "{unknownVar}", "prefix-{thredId}"]) {expect(() => decodeCustomHeaders({ enabled: true, headers: [{ name: "X-Ok", value: badValue }] })).toThrow(CustomHeaderValidationError);}});@@ -76,6 +76,8 @@ describe("OpenAI-compatible custom headers config & resolution", () => {.toThrow(CustomHeaderError);expect(() => resolveCustomHeaders(on, { threadId: "t1\r\nInject: 1", turnId: "turn-1", providerInstanceId: "p1" })).toThrow(CustomHeaderError);+ expect(() => resolveCustomHeaders(on, { threadId: "thr-東京", turnId: "turn-1", providerInstanceId: "p1" }))+ .toThrow(CustomHeaderError);});it("auto-detects sensitive headers, redacts summaries, preserves keepExisting secrets on patch, and collects log secrets", () => {diff --git a/server/drivers/openai-compat-headers.ts b/server/drivers/openai-compat-headers.tsindex 0c317d8a48..091f16b3d3 100644--- a/server/drivers/openai-compat-headers.ts+++ b/server/drivers/openai-compat-headers.ts@@ -58,6 +58,10 @@ const MAX_HEADER_NAME_LENGTH = 128;const MAX_HEADER_VALUE_LENGTH = 2048;const HEADER_TOKEN_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;const CONTROL_CHARS = /\p{Cc}/u;+const hasNonByteChar = (value: string): boolean => {+ for (let i = 0; i < value.length; i++) if (value.charCodeAt(i) > 0xff) return true;+ return false;+};const PLACEHOLDER_RE = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;const PLACEHOLDER_TEST = /\{[A-Za-z_][A-Za-z0-9_]*\}/;const KNOWN_VARS = new Set<string>(RUNTIME_HEADER_VARIABLES);@@ -102,8 +106,8 @@ function validateHeaderName(raw: unknown): string {function validateHeaderValue(raw: unknown, name: string): string {if (typeof raw !== "string") throw new CustomHeaderValidationError(`Header "${name}" value must be a string.`);- if (CONTROL_CHARS.test(raw)) {- throw new CustomHeaderValidationError(`Header "${name}" value cannot contain CR, LF, or control characters.`);+ if (CONTROL_CHARS.test(raw) || hasNonByteChar(raw)) {+ throw new CustomHeaderValidationError(`Header "${name}" value cannot contain CR, LF, control characters, or characters above U+00FF.`);}const value = raw.trim();if (!value) throw new CustomHeaderValidationError(`Header "${name}" value cannot be empty.`);@@ -255,8 +259,8 @@ export function resolveCustomHeaders(}continue;}- if (CONTROL_CHARS.test(value)) {- throw new CustomHeaderError(`Cannot send custom header "${rule.name}": resolved value contains unsafe control characters.`);+ if (CONTROL_CHARS.test(value) || hasNonByteChar(value)) {+ throw new CustomHeaderError(`Cannot send custom header "${rule.name}": resolved value contains unsafe control characters or characters above U+00FF.`);}resolved[rule.name] = value;}diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex 658db17982..247306edcc 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -1417,10 +1417,12 @@ describe("opt-in custom OpenAI-compatible request headers", () => {expect(completed.some((e) => JSON.stringify(e).includes("gw-secret-token-xyz"))).toBe(false);expect(completed.some((e) => JSON.stringify(e).includes("[redacted]"))).toBe(true);- // 3. Non-streaming generateText without threadId fails cleanly when {threadId} is required, never sending an empty header+ // 3. Non-streaming generateText without threadId fails cleanly when {threadId} is required, and succeeds when compaction passes threadIdconst countBeforeFail = seenRequests.length;await expect(onInst.generateText!("summarize")).rejects.toThrow(/threadId/);expect(seenRequests).toHaveLength(countBeforeFail);+ await expect(onInst.generateText!("summarize", { threadId: "thread-compact" })).resolves.toBe("non-stream ok");+ expect(seenRequests.at(-1)!.headers["x-maus-thread-id"]).toBe("thread-compact");// Non-streaming generateText with optional {threadId} omits it cleanly and still sends static/{providerInstanceId} headersconst optInst = await OpenAICompatDriver.create({diff --git a/server/host/conversation-compaction.ts b/server/host/conversation-compaction.tsindex 92e24e8b2a..3e0bfea901 100644--- a/server/host/conversation-compaction.ts+++ b/server/host/conversation-compaction.ts@@ -63,7 +63,7 @@ export interface ConversationCompactionDeps {resumesSession(input: CompactConversationInput, session: string): boolean;/** The engine instance and model the conversation's next turn would run on now. */currentSelection(botId: string, threadId: string): { instanceId: string; model: string | null } | undefined;- generateText(botId: string, instance: CompactionInstance): ((prompt: string, options?: { signal?: AbortSignal }) => Promise<string>) | undefined;+ generateText(botId: string, instance: CompactionInstance): ((prompt: string, options?: { signal?: AbortSignal; threadId?: string }) => Promise<string>) | undefined;claimIsCurrent(botId: string, generation: string, threadId: string): boolean;controllers: Map<string, { generation: string; controller: AbortController }>;cancelled(reason: string): Error;@@ -126,7 +126,7 @@ export function createConversationCompaction(deps: ConversationCompactionDeps) {if (engine !== "skipped") return;if (seededFloor && manual) store.patchTask(bot.id, threadId, { contextFloor: floor });if (!idle && deps.summarizing) { shown = true; deps.summarizing(threadId, true); }- const summary = await draftSummary(fold.folded, { signal: controller.signal, generateText: deps.generateText(bot.id, instance) });+ const summary = await draftSummary(fold.folded, { signal: controller.signal, threadId, generateText: deps.generateText(bot.id, instance) });if (!idle && !deps.claimIsCurrent(bot.id, generation, threadId)) throw deps.cancelled("context summarization stopped");controller.signal.throwIfAborted();if (prefix !== JSON.stringify(sinceFreshStart(store.activePath(threadId)).slice(0, messages.length))) {diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.tsindex 6ef0e5cec4..133135f412 100644--- a/server/routes/instances.test.ts+++ b/server/routes/instances.test.ts@@ -456,6 +456,46 @@ describe("a server's reply wait", () => {method: "PATCH", headers: { "content-type": "application/json" },body: JSON.stringify({ customHeaders: { enabled: true, headers: [] } }),})).status).toBe(403);++ const inheritedCfg = {+ openaiCompat: {+ url: "https://gw.example/v1",+ customHeaders: {+ enabled: true,+ headers: [{ name: "X-Workspace-Secret", value: "ws-secret-value-123", required: true, secret: true }],+ },+ },+ instances: { openaiCompat: { driver: "openai-compat", config: {} } },+ };+ const inheritedPersisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];+ const inheritedSrv = await serve({+ cfg: inheritedCfg as unknown as AppConfig,+ persistProviderInstance: async (_id: string, instances: typeof inheritedPersisted[number]) => {+ inheritedPersisted.push(structuredClone(instances));+ (inheritedCfg as { instances: unknown }).instances = instances;+ },+ });+ await inheritedSrv.call("PATCH", "/api/instances/openaiCompat", { replyWaitMinutes: 15 });+ expect(inheritedPersisted.at(-1)!.openaiCompat!.config).toEqual({ replyWaitMinutes: 15 });+ await inheritedSrv.call("PATCH", "/api/instances/openaiCompat", {+ customHeaders: {+ enabled: true,+ headers: [+ { name: "X-Workspace-Secret", keepExisting: true, secret: true },+ { name: "X-Maus-Thread-ID", value: "{threadId}" },+ ],+ },+ });+ expect(inheritedPersisted.at(-1)!.openaiCompat!.config).toMatchObject({+ replyWaitMinutes: 15,+ customHeaders: {+ enabled: true,+ headers: [+ { name: "X-Workspace-Secret", value: "ws-secret-value-123", required: true, secret: true },+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },+ ],+ },+ });});});diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex 2d084ce421..813fa5b1d8 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -27,7 +27,7 @@ import {withClaudeBedrockInfo,} from "../claude-bedrock.ts";import { updateClaudeCli } from "../claude-update.ts";-import { persistableInstanceConfigs, saveConfig, withInstanceCli, type AppConfig } from "../config.ts";+import { instanceConfigs, persistableInstanceConfigs, saveConfig, withInstanceCli, type AppConfig } from "../config.ts";import { addEndpoint, addEndpointSchema, changeEndpointAddress, endpointBaseUrl, endpointModelsReadable, isAddedEndpoint, localServerAlreadyAdded, withEndpointUrls } from "../openai-compat-endpoints.ts";import { CustomHeaderValidationError, mergeCustomHeadersPatch } from "../drivers/openai-compat-headers.ts";import { findOllama, probeOllama } from "../drivers/ollama.ts";@@ -536,10 +536,13 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can configure custom headers." });if (entry.driver !== "openai-compat") return json(res, 400, { error: "Custom request headers are available for OpenAI-compatible instances only." });const { customHeaders: previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;+ const effectivePrevious = previous ?? (isAddedEndpoint(instanceId, entry)+ ? undefined+ : (instanceConfigs(cfg)[instanceId]?.config as { customHeaders?: unknown } | undefined)?.customHeaders);try {entry.config = body.customHeaders === null? rest- : { ...rest, customHeaders: mergeCustomHeadersPatch(body.customHeaders, previous) };+ : { ...rest, customHeaders: mergeCustomHeadersPatch(body.customHeaders, effectivePrevious) };} catch (error) {if (error instanceof CustomHeaderValidationError) return json(res, 400, { error: error.message });throw error;diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 2de8f01381..27bcb9820d 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7199,6 +7199,25 @@"apiInstances.replyWaitHint": "Quanto tempo esperar pelas próximas palavras de uma resposta antes de desistir. Modelos locais podem demorar para responder em um computador lento.","apiInstances.replyWaitDefault": "Espera: padrão","apiInstances.replyWaitMinutes": "Esperar {minutes} min",+ "apiInstances.customHeadersTitle": "Cabeçalhos personalizados da requisição",+ "apiInstances.customHeadersEnable": "Ativar cabeçalhos personalizados da requisição",+ "apiInstances.customHeadersEnableFor": "Ativar cabeçalhos personalizados da requisição para {name}",+ "apiInstances.customHeadersHint": "Enviados a cada requisição de modelo quando ativados. Aceita {vars}, resolvidos com segurança pelo OpenMausBot no momento da requisição.",+ "apiInstances.customHeadersAdd": "Adicionar cabeçalho",+ "apiInstances.customHeadersSave": "Salvar cabeçalhos",+ "apiInstances.customHeadersSaving": "Salvando…",+ "apiInstances.customHeadersRemove": "Remover cabeçalho {index}",+ "apiInstances.customHeaderNameAria": "Nome do cabeçalho {index}",+ "apiInstances.customHeaderValueAria": "Valor do cabeçalho {index}",+ "apiInstances.customHeaderVariableAria": "Inserir variável de execução {index}",+ "apiInstances.customHeaderVarPlaceholder": "Inserir variável…",+ "apiInstances.customHeadersKeepSecret": "Segredo salvo (deixe vazio para manter)",+ "apiInstances.customHeadersRequired": "Obrigatório",+ "apiInstances.customHeadersSecret": "Segredo",+ "apiInstances.customHeadersVarThreadId": "{threadId} — ID da conversa",+ "apiInstances.customHeadersVarBotId": "{botId} — ID do bot",+ "apiInstances.customHeadersVarTurnId": "{turnId} — ID do turno",+ "apiInstances.customHeadersVarProviderId": "{providerInstanceId} — ID do provedor","botOverview.loading": "Carregando…","botOverview.refreshError": "Não foi possível atualizar. Mostrando o último resumo carregado.","botOverview.readAll": "Ler tudo",