Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(handoff): say plainly when a handed-off bot hit its AI limit partway
AdityaUmalee496e74cfb81
diff --git a/server/host/peer-limit-resend.test.ts b/server/host/peer-limit-resend.test.tsindex 008462aec1..6f32bb5f92 100644--- a/server/host/peer-limit-resend.test.ts+++ b/server/host/peer-limit-resend.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from "vitest";import type { Message } from "../store.ts";import { nothingRan } from "../turn-outcome.ts";-import { createPeerLimitResend, type PeerLimitResendDeps, type PeerTurnOpts } from "./peer-limit-resend.ts";+import { createPeerLimitResend, withLimitNote, type PeerLimitResendDeps, type PeerTurnOpts } from "./peer-limit-resend.ts";type Outcome = { ok: boolean; text: string };type Opts = PeerTurnOpts<Outcome> & { origin?: { kind: string } };@@ -129,6 +129,46 @@ describe("peer limit resend", () => {}});+ it("tells the asker plainly when the limit came after the turn had started: no resend, who takes the next work, send again what is left", () => {+ const handOff: Opts = { coordination: { id: "child" } };+ const started = fixture([ask, toolCall, failure]);+ started.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: handOff, userMessage: ask });+ const note = started.resend.ended(started.failed, "gen-1", false);+ expect(note).toContain("hit its AI usage limit partway through this work");+ expect(note).toContain("Its backup AI, codex (gpt), takes its next work.");+ expect(note).toContain("send again only what is left");+ expect(started.resend.hold("gen-1", { ok: false, text: "limit" })).toBe(false);+ expect(started.resend.resend("t1")).toBe(false);+ expect(started.startTurn).not.toHaveBeenCalled();++ const none = fixture([ask, reply, failure], { takeover: () => ({ weighBackups: () => ({ backups: [], skipped: [] }), passedOver: () => {}, carriedOn: () => [] }) } as never);+ none.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: handOff, userMessage: ask });+ expect(none.resend.ended(none.failed, "gen-1", false)).toContain("It can take new work once its limit resets or a backup AI is set for it.");++ // Its end came before the dispatch named the turn: the bind gives the same note.+ const early = fixture([ask, toolCall, failure]);+ early.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: handOff, userMessage: ask });+ early.resend.endedUnbound(early.failed, false);+ expect(early.resend.bound("t1", "turn-1", "gen-1")).toBe(note);++ expect(withLimitNote({ ok: false, text: "Stopped: limit" }, note)).toEqual({ ok: false, text: `Stopped: limit\n\n${note}` });+ const plain = { ok: false, text: "Stopped" };+ expect(withLimitNote(plain, undefined)).toBe(plain);+ });++ it("adds no note when nothing ran (the resend covers it), for a sign-out or another failure, or for an untracked turn", () => {+ const signedOut = { turnStops: { read: () => ({ error: "Not signed in" }), failureCause: () => "Not signed in" } } as never;+ const otherFailure = { turnStops: { read: () => ({ error: "Something broke" }), failureCause: () => "Something broke" } } as never;+ for (const [rows, overrides, stopReason] of [[[ask, failure], {}, "error"], [[ask, toolCall, failure], signedOut, "auth_required"], [[ask, toolCall, failure], otherFailure, "error"]] as const) {+ const { resend, failed } = fixture([...rows], overrides, stopReason);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });+ expect(resend.ended(failed, "gen-1", false), stopReason).toBeUndefined();+ }+ const person = fixture([ask, toolCall, failure]);+ person.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: {}, userMessage: { ...ask, peerAsk: undefined } as Message });+ expect(person.resend.ended(person.failed, "gen-1", false)).toBeUndefined();+ });+it("reports the held failure as before when no backup can take it or a newer turn took the thread", async () => {const none = fixture([ask, failure], { takeover: () => ({ weighBackups: () => ({ backups: [], skipped: [] }), passedOver: () => {}, carriedOn: () => [] }) } as never);none.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });diff --git a/server/host/peer-limit-resend.ts b/server/host/peer-limit-resend.tsindex 14e529661e..a117f3836e 100644--- a/server/host/peer-limit-resend.ts+++ b/server/host/peer-limit-resend.ts@@ -80,6 +80,11 @@ export interface PeerLimitResendDeps<Opts, Outcome> {startTurn(botId: string, text: string, opts: Opts): Promise<unknown>;}+/** A hand-off's outcome with the note ended() or bound() gave, if any. */+export function withLimitNote<O extends { text: string }>(outcome: O, note: string | undefined): O {+ return note ? { ...outcome, text: outcome.text ? `${outcome.text}\n\n${note}` : note } : outcome;+}+/*** Resends a bot-to-bot turn once to the bot's backup AI when its own AI hit a usage limit before anything ran. The* resend keeps the turn's options as they were (sender, provenance, the hand-off it answers), so it never gains authority.@@ -105,8 +110,31 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcomunbound.delete(turn.threadId);}- /** At the turn's end, before its hand-off hears the outcome: keeps it for a resend only for a usage limit met before anything ran. */- function ended(event: EndedTurn, generation: string, capped: boolean): void {+ /** The backup AI that takes this bot's next turn after `scope`'s limit, if one can. */+ function nextBackup(current: BotRecord, scope: Claimed<Opts, Outcome>["scope"], logSkipped: boolean) {+ const from = current.modelSelection, instance = registry.get(from.instanceId);+ const { backups, skipped } = deps.takeover().weighBackups(current.id, from, scope, approvalModeFor(current));+ if (logSkipped) deps.takeover().passedOver(current, from, scope, skipped);+ return backups.find(candidate => {+ const target = registry.get(candidate.instanceId);+ return target?.enabled && (candidate.instanceId !== from.instanceId || candidate.model !== from.model)+ && (candidate.instanceId === from.instanceId ? scope !== "engine" : !instance || limitBackupAllowed(instance, target, deps.providerConfigs()[candidate.instanceId]));+ });+ }++ /** For the asking bot: the limit came after the turn had done part of the work, so it is not resent (no double actions). */+ function partlyRanNote(botId: string, threadId: string, scope: Claimed<Opts, Outcome>["scope"]): string {+ const current = store.projectBotForTask(botId, threadId), backup = current && nextBackup(current, scope, false);+ const next = backup ? `Its backup AI, ${registry.get(backup.instanceId)?.displayName ?? backup.instanceId} (${backup.model}), takes its next work.`+ : "It can take new work once its limit resets or a backup AI is set for it.";+ return `The bot hit its AI usage limit partway through this work, after it had already done part of it, so it was not sent again automatically. ${next} Check what it finished and send again only what is left.`;+ }++ /**+ * At the turn's end, before its hand-off hears the outcome: keeps it for a resend only for a usage limit met before anything+ * ran. A limit met after the turn had done something returns the note its hand-off's outcome carries instead.+ */+ function ended(event: EndedTurn, generation: string, capped: boolean): string | undefined {const turn = running.get(event.threadId);if (turn?.generation !== generation) return;running.delete(event.threadId);@@ -115,7 +143,8 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom// Held only where the bot's own turn end resends it or reports the failure (never a room's thread).const stop = event.ok || capped || !store.botByThread(event.threadId) || !deps.quotaSwitchEnabled() ? undefined : deps.turnStops.read(event.threadId, event.turnId);const scope = stop && turnLimitScope(event, stop.flags, deps.turnStops.failureCause(event));- if (!scope || scope === "signed-out" || !nothingRan(store.activePath(event.threadId), turn.since, event.turnId, stop?.error)) return;+ if (!scope || scope === "signed-out") return;+ if (!nothingRan(store.activePath(event.threadId), turn.since, event.turnId, stop?.error)) return partlyRanNote(turn.botId, event.threadId, scope);claimed.set(event.threadId, { ...turn, scope, turnId: event.turnId, stopError: stop?.error });// The thread settled before the dispatch named this turn: resend now, once its hand-off has held the outcome.if (settled) setImmediate(() => resend(event.threadId));@@ -127,10 +156,10 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom}/** The dispatch named the turn after it had already ended: judges that end as ended() would have. */- function bound(threadId: string, turnId: string, generation: string): void {+ function bound(threadId: string, turnId: string, generation: string): string | undefined {const early = unbound.get(threadId);if (early?.event.turnId !== turnId) return;- ended(early.event, generation, early.capped);+ return ended(early.event, generation, early.capped);}/** Keeps the failed attempt's outcome for its hand-off while the resend is pending; false when none is. */@@ -169,14 +198,7 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom|| (turn.latestUser && store.activePath(threadId).findLast(m => m.role === "user" && m.kind === "text")?.id !== turn.latestUser)// A file the turn made lands after its end was judged: anything it left by now still means no resend.|| !nothingRan(store.activePath(threadId), turn.since, turn.turnId, turn.stopError)) return giveUp();- const from = current.modelSelection, instance = registry.get(from.instanceId);- const { backups, skipped } = deps.takeover().weighBackups(turn.botId, from, turn.scope, approvalModeFor(current));- deps.takeover().passedOver(current, from, turn.scope, skipped);- const backup = backups.find(candidate => {- const target = registry.get(candidate.instanceId);- return target?.enabled && (candidate.instanceId !== from.instanceId || candidate.model !== from.model)- && (candidate.instanceId === from.instanceId ? turn.scope !== "engine" : !instance || limitBackupAllowed(instance, target, deps.providerConfigs()[candidate.instanceId]));- });+ const from = current.modelSelection, instance = registry.get(from.instanceId), backup = nextBackup(current, turn.scope, true);if (!backup) return giveUp();const checked = deps.checkedTaskModelSwitch(current, backup, false, false, true);const target = checked.ok ? registry.get(checked.selection.instanceId) : null;diff --git a/server/index.ts b/server/index.tsindex e8b24b6a66..c507835b73 100644--- a/server/index.ts+++ b/server/index.ts@@ -212,7 +212,7 @@ import {} from "./contracts.ts";import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";import { chosenBackups, recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts"; import { outOfProcesses } from "./process-shortage.ts";-import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { createSignInResumeHost, signInWait } from "./host/sign-in-resume.ts"; import { ownRequest, quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts"; import { createRoomLimitTakeover } from "./host/room-limit-takeover.ts";+import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { createSignInResumeHost, signInWait } from "./host/sign-in-resume.ts"; import { ownRequest, quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend, withLimitNote } from "./host/peer-limit-resend.ts"; import { createRoomLimitTakeover } from "./host/room-limit-takeover.ts";import { decodeGeneratedImage } from "./generated-image.ts";import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";import {@@ -5025,7 +5025,7 @@ bus.subscribe((event: RuntimeEvent) => {...(handoffPath ? { cap: { note: STEP_CAP_NOTE, handoffPath } } : {}), ...(event.ok ? {} : { failure: { text: failure ?? "", stopReason: event.stopReason } }) };const owner = directFollowupTurns.complete(event.threadId, event.turnId, outcome);if (owner) {- peerLimitResend.ended(event, owner.generation, Boolean(handoffPath)); settleDirectCoordination(owner.generation, outcome);+ settleDirectCoordination(owner.generation, withLimitNote(outcome, peerLimitResend.ended(event, owner.generation, Boolean(handoffPath))));settleDirectFollowup(owner.generation);} else peerLimitResend.endedUnbound(event, Boolean(handoffPath));}@@ -8343,7 +8343,7 @@ async function beginTurn(if (directFollowupSettlers.has(dispatchClaimId) && dispatch.value.turnId &&!directFollowupTurns.bind(threadId, dispatchClaimId, dispatch.value.turnId)) {const outcome = directFollowupTurns.takeEarlyCompletion(threadId, dispatch.value.turnId);- if (outcome) { peerLimitResend.bound(threadId, dispatch.value.turnId, dispatchClaimId); settleDirectCoordination(dispatchClaimId, outcome); }+ if (outcome) settleDirectCoordination(dispatchClaimId, withLimitNote(outcome, peerLimitResend.bound(threadId, dispatch.value.turnId, dispatchClaimId)));settleDirectFollowup(dispatchClaimId);}clearDirectTurnDispatch(threadId, dispatchClaimId);