Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(routines): only a safety-floor block after the reply completes a run
milind-soniba5c2c50e338
diff --git a/packages/phone-protocol/src/runtime-events.ts b/packages/phone-protocol/src/runtime-events.tsindex 70afef14ad..625c6b782c 100644--- a/packages/phone-protocol/src/runtime-events.ts+++ b/packages/phone-protocol/src/runtime-events.ts@@ -197,7 +197,9 @@ export type RuntimeEvent = RuntimeEventBase &// `limit`: a usage limit refused this turn: the account's on this engine ("engine"), one model's own window// ("model"), or that model's extra usage credits ("credits"); the engine's other models still work for the last two.// `limitModels`: the models a "model" limit holds, when one allowance is shared (OpenCode's free models).- | { type: "runtime.error"; message: string; partial?: boolean; setup?: boolean; terminal?: boolean; claudeUpdate?: boolean; trialCredit?: "used_up" | "ended" | "paused" | "too_low";+ // `blockedAfterReply` (with `partial`): every call that failed was blocked by the safety floor, so it ran nothing,+ // after the bot's answer text had come back.+ | { type: "runtime.error"; message: string; partial?: boolean; blockedAfterReply?: boolean; setup?: boolean; terminal?: boolean; claudeUpdate?: boolean; trialCredit?: "used_up" | "ended" | "paused" | "too_low";stalled?: boolean; limitResetsAt?: number; limit?: "engine" | "model" | "credits"; limitModels?: string[];/** `message` as a `chat.notice.*` key and params, when it is one of the server's fixed sentences. */text?: ServerText }diff --git a/server/drivers/openai-chat-safety-floor.test.ts b/server/drivers/openai-chat-safety-floor.test.tsindex 61ea2cf333..7eb4cdab58 100644--- a/server/drivers/openai-chat-safety-floor.test.ts+++ b/server/drivers/openai-chat-safety-floor.test.ts@@ -42,7 +42,7 @@ createInterface({ input: process.stdin }).on("line", (line) => {reply(request.id, { tools: [{ name: "exec", description: "Records the command it is handed. Runs nothing.", inputSchema: schema }] });} else if (request.method === "tools/call") {appendFileSync(join(directory, "handed.ndjson"), JSON.stringify(request.params.arguments.command) + "\\n");- reply(request.id, { content: [{ type: "text", text: "Recorded, not run." }] });+ reply(request.id, { content: [{ type: "text", text: "Recorded, not run." }], ...(request.params.arguments.command === "false" ? { isError: true } : {}) });} else if (request.id !== undefined && request.method === "ping") reply(request.id, {});});`;@@ -64,8 +64,9 @@ function sse(response: ServerResponse, delta: unknown, finishReason: string) {}/** A chat-completions provider that asks for one `shell_exec` call per- * command, in order, then answers; and the fixture MCP server it calls. */-async function fixture(commands: string[]) {+ * command, in order (a step may say something first), then answers; and the+ * fixture MCP server it calls, where the command `false` fails. */+async function fixture(commands: Array<string | { say: string; command: string }>) {const directory = mkdtempSync(join(tmpdir(), "omb-chat-floor-"));const requests: ChatRequest[] = [];const server = createServer(async (request, response) => {@@ -79,9 +80,10 @@ async function fixture(commands: string[]) {if (request.method !== "POST") { response.writeHead(404); response.end(); return; }for await (const part of request) data += part.toString();requests.push(JSON.parse(data) as ChatRequest);- const command = commands[requests.length - 1];- if (command === undefined) return sse(response, { content: "Done." }, "stop");- sse(response, { content: null, tool_calls: [{+ const step = commands[requests.length - 1];+ if (step === undefined) return sse(response, { content: "Done." }, "stop");+ const { say = null, command } = typeof step === "string" ? { command: step } : step;+ sse(response, { content: say, tool_calls: [{index: 0, id: `call_${requests.length}`, type: "function",function: { name: "shell_exec", arguments: JSON.stringify({ command }) },}] }, "tool_calls");@@ -116,6 +118,7 @@ async function fixture(commands: string[]) {threadId, botId: "bot-floor", text: "Tidy up.", model: "fixture-model", integrations, ...input,}),completed: () => recorder.until((event) => event.type === "turn.completed"),+ errors: () => recorder.events.filter((event) => event.type === "runtime.error"),cards: () => recorder.events.filter((event) => event.type === "request.opened"),notices: () => recorder.events.flatMap((event) => event.type === "runtime.notice" ? [event.message] : []),/** What the model was handed back for one call, in the last request it@@ -174,6 +177,36 @@ describe("the safety floor in the chat runtime", () => {]);});+ it("says a turn's only failure was a block after its answer came back, and nothing else", async () => {+ bindSafetyFloor(() => ({ safetyFloor: { enabled: true } }), undefined, HOST);+ const REPORT = "Here is the weekly report.";+ // The answer came first, then the floor blocked the clean-up: the turn stops on it, marked as blocked after the reply.+ const after = await fixture([{ say: REPORT, command: WIPE }]);+ await after.start({ approvalMode: "full" });+ expect(await after.completed()).toMatchObject({ ok: false, stopReason: "tool_error", denials: ["shell_exec"] });+ expect(after.handed()).toEqual([]);+ expect(after.errors()).toEqual([expect.objectContaining({ partial: true, blockedAfterReply: true })]);+ // Blocked before the bot said anything: partly done at most, never blocked after the reply.+ const before = await fixture([WIPE]);+ await before.start({ approvalMode: "full" });+ expect(await before.completed()).toMatchObject({ ok: false, stopReason: "tool_error" });+ expect(before.errors()).toEqual([expect.objectContaining({ partial: true })]);+ expect(before.errors()[0]).not.toHaveProperty("blockedAfterReply");+ // A step that broke beside the block: not only a block.+ const broke = await fixture([{ say: REPORT, command: WIPE }, "false"]);+ await broke.start({ approvalMode: "full" });+ expect(await broke.completed()).toMatchObject({ ok: false, stopReason: "tool_error" });+ expect(broke.handed()).toEqual(["false"]);+ expect(broke.errors()[0]).not.toHaveProperty("blockedAfterReply");+ // A person's no on a card, after the answer: not the floor.+ const denied = await fixture([{ say: REPORT, command: WIPE }]);+ await denied.start({ approvalMode: "ask" });+ const card = await denied.recorder.until((event) => event.type === "request.opened");+ await denied.instance.adapter.respondToRequest(denied.threadId, card.requestId!, { behavior: "deny" });+ expect(await denied.completed()).toMatchObject({ ok: false, stopReason: "tool_error", denials: ["shell_exec"] });+ expect(denied.errors()[0]).not.toHaveProperty("blockedAfterReply");+ });+it("refuses a command the floor cannot read, because this gate has no card to show at Full access", async () => {const errors = vi.spyOn(console, "error").mockImplementation(() => {});try {diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 15b3fc52a5..9dd188cf4e 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -588,7 +588,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)let stopReason: string | null = null;let failure: string | undefined;let failureText: ReturnType<typeof runtimeErrorText>;- let toolFailed = false;+ let toolFailed = false, spoke = false, unfloored = 0, blockedAfterReply = false; // unfloored: failed calls the safety floor did not block after the bot spokelet correctiveRounds = 0;const denials: string[] = [], failedCalls: string[] = [];const seenCalls = new Set<string>();@@ -744,7 +744,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)}// Reasoning on a tool-call round belongs to the protocol, not a final reply.const reply = completion.text.trim() ? completion.text : completion.toolCalls.length || unreadable ? "" : completion.reasoning;- if (reply.trim()) emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: safeText(reply) });+ if (reply.trim()) { spoke = true; emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: safeText(reply) }); }abort.signal.throwIfAborted();if (unreadable) {askedAgain = true;@@ -763,7 +763,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)messages.push({ role: "user", content: CORRECTIVE_ROUND });continue;}- stopReason = "tool_error";+ stopReason = "tool_error"; blockedAfterReply = failedCalls.length > 0 && unfloored === 0;throw new ChatProtocolError(toolFailureMessage(failedCalls, denials.filter((name) => name !== ASK_USER_TOOL)));}if (options.nudgeAnnouncedAction && tools.definitions.length && announcesAction(completion.text)) {@@ -798,13 +798,13 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)// A failure stays pending only until the bot runs tools again: one that went on to use more tools has read the error// and reacted (a wrong guess, a bad query, then the right call), so its turn is not failed for it, on any model. The// failed step still shows as failed; a failure in the last calls before the answer, or a person's no, still ends it.- if (!denials.length) { toolFailed = false; failedCalls.length = 0; }+ if (!denials.length) { toolFailed = false; failedCalls.length = 0; unfloored = 0; }const screenshotParts: ChatContentPart[] = [];for (const call of completion.toolCalls) {abort.signal.throwIfAborted();let result: ChatToolResult;let started = false;- let fatal: Error | undefined, title = call.function.name, skipRepeatCount = false;+ let fatal: Error | undefined, title = call.function.name, skipRepeatCount = false, flooredAfterReply = false;try {const args = toolArguments(call.function.arguments, safeText);const inputPreview = preview(args);@@ -860,7 +860,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)}}} else {- denials.push(shown.title);+ denials.push(shown.title); flooredAfterReply = Boolean(floored) && spoke;result = { ok: false, text: refusal(floored, (message) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message })) };}}@@ -875,7 +875,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const text = safeText(result.text);const output = preview({ ok: result.ok, result: text });emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "tool", itemId: call.id, ok: result.ok, output });- if (!result.ok) { toolFailed = true; failedCalls.push(title); }+ if (!result.ok) { toolFailed = true; failedCalls.push(title); if (!flooredAfterReply) unfloored += 1; }messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ ok: result.ok, result: repeatNote ? `${text}\n\n${repeatNote}` : text }) });screenshotParts.push(...chatToolImages(call.id, result.images));abort.signal.throwIfAborted();@@ -905,7 +905,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)// "upstream" (an OpenAI-compatible URL) names no provider, and the Cloud trial credit reads its raw line.const words = options.httpErrorLabel === "upstream" ? { message: failure } : plainFailure(options.httpErrorLabel, failure);const replyShownFirst = stopReason === "tool_error";- emit({ ...base(turn.threadId, turnId), type: "runtime.error", ...words, ...(!cleanupFailed && failureText ? { text: failureText } : {}), terminal: !abort.signal.aborted, ...(replyShownFirst ? { partial: true } : {}) });+ emit({ ...base(turn.threadId, turnId), type: "runtime.error", ...words, ...(!cleanupFailed && failureText ? { text: failureText } : {}), terminal: !abort.signal.aborted, ...(replyShownFirst ? { partial: true, ...(blockedAfterReply ? { blockedAfterReply: true } : {}) } : {}) });}if (!ok && !abort.signal.aborted) {const continuable = classifyContinuable(stopReason, failure);diff --git a/server/routine-recovery.ts b/server/routine-recovery.tsindex 780bb2a87c..2a21399d65 100644--- a/server/routine-recovery.ts+++ b/server/routine-recovery.ts@@ -38,6 +38,9 @@ export interface RoutineFailureFacts {text?: ServerText;/** The turn's reply came back; only a step it ran failed or wasn't allowed (the runtime error's `partial`). */partial?: boolean;+ /** With `partial`: the only failed calls were blocked by the safety floor after the reply came back (the runtime+ * error's `blockedAfterReply`). Such a run completes, partly done; any other failed step still fails it. */+ blockedAfterReply?: boolean;}/** On a failed run that only the owner's AI account could have let through: it spent nothing, so it does not count@@ -135,8 +138,8 @@ export function retriesTeammateThread(failure: string, facts: RoutineFailureFactreturn classifyRoutineFailure(failure, facts).kind === "retry";}-export function engineFacts({ setup, stalled, trialCredit, limitResetsAt, limit, partial, text }: RuntimeEvent & { type: "runtime.error" }): RoutineFailureFacts {- return { setup, stalled, trialCredit, limitResetsAt, limit, partial, text };+export function engineFacts({ setup, stalled, trialCredit, limitResetsAt, limit, partial, blockedAfterReply, text }: RuntimeEvent & { type: "runtime.error" }): RoutineFailureFacts {+ return { setup, stalled, trialCredit, limitResetsAt, limit, partial, blockedAfterReply, text };}/** Host-local, with its zone: on a Cloud home the host's zone need not be the reader's. */diff --git a/server/routines.test.ts b/server/routines.test.tsindex 1cf1f981d2..9269aee539 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -301,25 +301,33 @@ describe("bounded scheduled overlap and run health", () => {await h.manager.tick();});- it("does not fail a run whose reply came back before its last tool call went wrong: it completes partly done", async () => {+ it("keeps a run that failed only on a step, after its reply came back, failed but marked partly done; only a safety-floor block after the reply completes it", async () => {const h = harness(start);const routine = h.manager.create({ ...input(), enabled: false });const event = (threadId: string, patch: Record<string, unknown>) => h.manager.handleRuntimeEvent({ eventId: `e-${Math.random()}`, provider: "fake", threadId, createdAt: new Date().toISOString(), ...patch } as Parameters<typeof h.manager.handleRuntimeEvent>[0]);- const attempt = async (threadId: string, partial: boolean, { reply = true, cutOff = false, stopReason }: { reply?: boolean; cutOff?: boolean; stopReason?: string } = {}) => {+ const attempt = async (threadId: string, partial: boolean, { reply = true, cutOff = false, stopReason, blocked = false }: { reply?: boolean; cutOff?: boolean; stopReason?: string; blocked?: boolean } = {}) => {h.manager.runNow(routine.id); await h.manager.tick();if (reply) event(threadId, { type: "item.completed", itemType: "assistant_text", itemId: "reply", text: "Here is the summary." });- event(threadId, { type: "runtime.error", message: "Stopped because the tool call “read_file” failed.", terminal: true, ...(partial ? { partial: true } : {}) });+ const message = blocked ? "Stopped because the tool call “shell_exec” wasn't allowed." : "Stopped because the tool call “read_file” failed.";+ event(threadId, { type: "runtime.error", message, terminal: true, ...(partial ? { partial: true } : {}), ...(blocked ? { blockedAfterReply: true } : {}) });if (cutOff) h.manager.failThread(threadId, "Provider settings changed");- else event(threadId, { type: "turn.completed", ok: false, stopReason: stopReason ?? (partial ? "tool_error" : "refusal") });+ else event(threadId, { type: "turn.completed", ok: false, stopReason: stopReason ?? (partial ? "tool_error" : "refusal"), ...(blocked ? { denials: ["shell_exec"] } : {}) });};await attempt("thread-1", true);await attempt("thread-2", false);await attempt("thread-3", true, { reply: false });await attempt("thread-4", true, { cutOff: true });- await attempt("thread-5", true, { stopReason: "refusal" });- const [done, failed, silent, cutOff, limited] = h.manager.listRuns().sort((a, b) => a.threadId!.localeCompare(b.threadId!));- expect(done).toMatchObject({ status: "completed", partial: true, output: "Here is the summary.", error: expect.stringContaining("read_file") });- expect([failed, silent, cutOff, limited].map((run) => [run.status, run.partial])).toEqual([["failed", undefined], ["failed", undefined], ["queued", undefined], ["failed", true]]);+ await attempt("thread-5", true, { blocked: true });+ await attempt("thread-6", true, { blocked: true, reply: false });+ await attempt("thread-7", true, { blocked: true, stopReason: "refusal" });+ const [partly, failed, silent, cutOff, blocked, blockedSilent, blockedOtherStop] = h.manager.listRuns().sort((a, b) => a.threadId!.localeCompare(b.threadId!));+ // A step that broke after the reply: the reply is no proof, so the run fails, marked partly done.+ expect(partly).toMatchObject({ status: "failed", partial: true, output: "Here is the summary.", error: expect.stringContaining("read_file") });+ expect([failed, silent, cutOff].map((run) => [run.status, run.partial])).toEqual([["failed", undefined], ["failed", undefined], ["queued", undefined]]);+ // Every failed call was blocked by the safety floor after the reply: nothing ran, the run completes partly done.+ expect(blocked).toMatchObject({ status: "completed", partial: true, output: "Here is the summary.", error: expect.stringContaining("shell_exec"), denials: ["shell_exec"] });+ // With no reply, or another stop, a block still fails the run.+ expect([blockedSilent, blockedOtherStop].map((run) => [run.status, run.partial])).toEqual([["failed", undefined], ["failed", true]]);});it("tells of a failure once per streak, and again when it changes or after a run completes", async () => {diff --git a/server/routines.ts b/server/routines.tsindex 54db9f4752..ff79ddc7f2 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -1289,8 +1289,8 @@ export class RoutineManager {if (event.cost != null) run.cost = (run.cost ?? 0) + event.cost;if (event.denials?.length) run.denials = [...new Set([...(run.denials ?? []), ...event.denials])];const facts = { ...this.failureFacts.get(run.id), stopReason: event.stopReason };- // A last tool call that failed after the reply was delivered (partial) leaves a finished deliverable: the run completes partly done, its failing step kept in its error line. Any other stop fails it.- const delivered = !event.ok && event.stopReason === "tool_error" && facts.partial === true && Boolean(run.output);+ // The bot's reply is no proof, so a failed step fails the run. Only one clear case completes it, partly done with the step kept in its error line: every failed call was blocked by the safety floor (it ran nothing) after the reply came back.+ const delivered = !event.ok && event.stopReason === "tool_error" && facts.partial === true && facts.blockedAfterReply === true && Boolean(run.output);if (!event.ok && !delivered) { this.settleFailure(run, routineFailure(run.error, event.stopReason), facts); return cloneRun(run); }this.failureFacts.delete(run.id);const waitsOnTeammates = this.options.hasPendingDelegations?.(event.threadId) === true, handoffRefused = waitsOnTeammates ? null : this.options.refusedHandoff?.(event.threadId);