Skip to content

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

Turn dispatch: decide whether a turn resumes its session in one place

laijsg1d3a725df9e76
diff --git a/server/host/resume-check.ts b/server/host/resume-check.ts
new file mode 100644
index 0000000000..e8bd4e37ac
--- /dev/null
+++ b/server/host/resume-check.ts
@@ -0,0 +1,33 @@
+import { createHash } from "node:crypto";
+import { DEFAULT_REBUILD_BYTES, replayToolCalls, selectReplay } from "../context-rebuild.ts";
+import type { ContextMessage } from "../delta-context.ts";
+import type { BotRecord, Message } from "../store.ts";
+
+type Compaction = NonNullable<Parameters<typeof selectReplay>[1]>["compaction"];
+
+export interface ResumeCheckDeps {
+ directContext(bot: BotRecord, threadId: string, messages: Message[]): ContextMessage[];
+ latestCompaction(messages: readonly Message[]): Compaction;
+ context(): { rebuildBytes?: number; replayToolHistory?: boolean } | undefined;
+ everyBotRules(): string | undefined;
+ sectionPrompt(section: string | undefined): string;
+}
+
+export function createResumeCheck(deps: ResumeCheckDeps) {
+ const replayInputs = (bot: BotRecord, threadId: string, activeMessages: Message[], skip: ReadonlySet<string>) => {
+ const context = deps.directContext(bot, threadId, activeMessages);
+ const record = deps.latestCompaction(activeMessages);
+ const settings = deps.context();
+ const selection = selectReplay(context, { budgetBytes: settings?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, excludedIds: skip, compaction: record, tools: replayToolCalls(activeMessages, settings) });
+ return { context, replayable: context.filter((m) => !skip.has(m.id)), record, selection };
+ };
+
+ // What a resumed session keeps from its launch; Codex reasserts model and provider on resume, but an in-flight turn and an omitted effort keep the prior selection.
+ const sessionConfigFor = (bot: BotRecord, driverKind: string, model: string | undefined, effort: string | undefined) => {
+ const rules = deps.everyBotRules()?.trim();
+ const persistentConfig = [bot.name, bot.title, bot.description, deps.sectionPrompt(bot.section), ...(rules ? [rules] : []), ...(driverKind === "codex" ? [model, effort ?? null] : [])];
+ return (soul: string | undefined): string => createHash("sha256").update(JSON.stringify([...persistentConfig, soul])).digest("hex").slice(0, 16);
+ };
+
+ return { replayInputs, sessionConfigFor };
+}
diff --git a/server/index.ts b/server/index.ts
index 68d67b9f4f..caaedb681b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -13,8 +13,8 @@ import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts";
import { basename, join } from "node:path";
import { authorizeExternalRuntime, externalRuntimeIsActive, type ExternalRuntimeGrant } from "./external-runtime.ts";
import { z } from "zod";
-import { selectReplay, replayToolCalls, DEFAULT_REBUILD_BYTES } from "./context-rebuild.ts";
-import { claudeCompactionDisabled, createConversationCompaction } from "./host/conversation-compaction.ts";
+import { DEFAULT_REBUILD_BYTES } from "./context-rebuild.ts";
+import { claudeCompactionDisabled, createConversationCompaction } from "./host/conversation-compaction.ts"; import { createResumeCheck } from "./host/resume-check.ts";
import { compactionReading } from "./context-budget.ts";
import { autoCompactWindow } from "./drivers/claude.ts";
import { RoomContextTracker, roomResetNote } from "./room-context.ts";
@@ -328,8 +328,8 @@ import { narrateTool, toUtterances } from "./tts/speech-text.ts";
import { createTtsRoutes } from "./routes/tts.ts";
import { turnStartLogLine } from "./turn-log.ts";
import { TurnStops, outwardActions, stoppedTurnOutcome, turnEvidence } from "./turn-outcome.ts";
-import { buildRecoveryText, buildTurnContext, engineIsFresh, replaysNatively } from "./turn-context.ts";
-import { Handoffs, handedStateUsable, isContextMessage, recordHanded, renderUnseen, sessionStart, unseenMessages, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";
+import { buildRecoveryText, buildTurnContext, replaysNatively } from "./turn-context.ts"; import { resumePlan } from "./resume-plan.ts";
+import { Handoffs, isContextMessage, recordHanded, renderUnseen, sessionStart, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";
import { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";
import { callTitleExcerpt } from "./thread-title.ts";
import { generateThreadTitle } from "./thread-title-generate.ts";
@@ -6965,6 +6965,7 @@ function peerReplayText(m: Message, name: string, text: string): string {
}
const { lineLabels, personPrompt, routineRunNote } = createLineLabels({ sharedChat: (threadId) => sharedMembership() && !store.groupByThread(threadId) && audienceMember(teamHost.audienceOf(threadId)) === null, userName: userNameFor, teamRole: (key) => (teamOwners.people?.list() ?? []).find((one) => personKey({ id: "", email: one.email }) === key)?.role, routineName: (threadId) => { const run = routines?.runForThread(threadId); return routines?.listRoutines().find((one) => one.id === run?.routineId)?.name; } });
+const { replayInputs, sessionConfigFor } = createResumeCheck({ directContext, latestCompaction, context: () => cfg.context, everyBotRules: () => cfg.everyBotRules, sectionPrompt: sectionContextSystemPrompt });
const compactConversation = createConversationCompaction({
store, context: () => cfg.context, directContext, latestCompaction,
nativeCompactTokens: (instance, model) => nativeCompactTokens(instance, model),
@@ -7705,37 +7706,20 @@ async function beginTurn(
if ((m.roomRequest.phase === "request" && m.roomRequest.id === opts.coordination.id) ||
(m.roomRequest.phase === "result" && coordinationChildren?.has(m.roomRequest.id))) skipTranscript.add(m.id);
}
- const context = directContext(bot, threadId, activeMessages);
+ const { context, replayable, record, selection } = replayInputs(bot, threadId, activeMessages, skipTranscript);
const contextOrder = context.map(m => m.id);
- const replayable = context.filter(m => !skipTranscript.has(m.id));
- const record = latestCompaction(activeMessages);
- const selection = selectReplay(context, { budgetBytes: cfg.context?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, excludedIds: skipTranscript, compaction: record, tools: replayToolCalls(activeMessages, cfg.context) });
const transcript = selection.transcript.map(({ role, text }) => ({ role, text }));
- const contextReset = selection.compacted > 0 && record?.id !== task.appliedCompactionId;
- if (contextReset) store.patchTask(bot.id, threadId, { resumeCursors: {} });
// Engines keep a session in the folder it started in, so a thread that follows its bot to the bot's working folder starts a new one there.
- const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: guestConfined || cloudGuestOpened(threadId) }); if (followed) store.patchTask(bot.id, threadId, { cwd: followed, resumeCursors: {} });
-
- // After a rewind the native session still holds the abandoned branch; the flag clears only once dispatched, or a failed dispatch loses the next attempt's history.
- const rewound = Boolean(task.rewound);
- const externalContextMarker = isExternalContextMarker(task.lastInstanceId)
- ? task.lastInstanceId
- : undefined;
- const fresh =
- !rewound &&
- !externalContextMarker &&
- engineIsFresh({ instanceId, lastInstanceId: task.lastInstanceId, resumeCursors: task.resumeCursors, transcript: replayable });
+ const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: guestConfined || cloudGuestOpened(threadId) });
const strictResume = instance.adapter.capabilities.strictResume === true;
- const cursor = task.resumeCursors[instanceId];
- const handed = strictResume && !rewound && !contextReset && !fresh && !externalContextMarker && cursor !== undefined
- ? task.handedMessages?.[instanceId] : undefined;
- const unseen = handed && handedStateUsable(handed, cursor, contextOrder) ? unseenMessages(replayable, contextOrder, handed) : undefined;
- const externalUpdate = Boolean(opts?.coordination?.resumed || unseen?.some((m) => m.keep));
- // What a resumed session keeps from its launch; Codex reasserts model and provider on resume, but an in-flight turn and an omitted effort keep the prior selection.
- const persistentConfig = [bot.name, bot.title, bot.description, sectionContextSystemPrompt(bot.section), ...(cfg.everyBotRules?.trim() ? [cfg.everyBotRules.trim()] : []),
- ...(instance.driverKind === "codex" ? [model, effort ?? null] : [])];
- const sessionConfig = (soul: string | undefined) =>
- createHash("sha256").update(JSON.stringify([...persistentConfig, soul])).digest("hex").slice(0, 16);
+ const externalContextMarker = isExternalContextMarker(task.lastInstanceId) ? task.lastInstanceId : undefined;
+ const resuming = resumePlan({ task, instanceId, strictResume, compacted: selection.compacted, recordId: record?.id, folderChanged: followed !== undefined,
+ contextOrder, replayable, externalMarker: externalContextMarker, coordinationResumed: Boolean(opts?.coordination?.resumed), effort });
+ // After a rewind the native session still holds the abandoned branch; the flag clears only once dispatched, or a failed dispatch loses the next attempt's history.
+ const { contextReset, rewound, fresh, unseen, externalUpdate } = resuming;
+ if (contextReset) store.patchTask(bot.id, threadId, { resumeCursors: {} });
+ if (followed) store.patchTask(bot.id, threadId, { cwd: followed, resumeCursors: {} });
+ const sessionConfig = sessionConfigFor(bot, instance.driverKind, model, effort);
const plannedConfig = sessionConfig(bot.soul);
const skillAuthoring = skillAuthoringEnabled(cfg) && agentsMounted;
const skillCommandText = supportsWorkspaceFiles(instance.driverKind)
@@ -7751,9 +7735,7 @@ async function beginTurn(
? extractReplayImages(selection.inline, turnImages, {}, turnVideos)
: { transcript: selection.inline, images: [] };
const decideContext = (config: string) => {
- // A Codex thread keeps the last effort it was sent and no turn can clear it, so one holding a level is rebuilt, not resumed.
- const effortHeld = !effort && typeof handed?.effort === "string";
- const handedStale = Boolean(handed && (!unseen || effortHeld || (externalUpdate && handed.config !== config)));
+ const handedStale = resuming.stale(config);
const { block: unseenBlock, placed } = unseen && !handedStale ? renderUnseen(unseen) : { block: "", placed: [] };
const { turnText: contextTurnText, resume } = buildTurnContext({
text: userTurnText,
diff --git a/server/resume-plan.ts b/server/resume-plan.ts
new file mode 100644
index 0000000000..d4add5273c
--- /dev/null
+++ b/server/resume-plan.ts
@@ -0,0 +1,37 @@
+import { handedStateUsable, unseenMessages, type ContextMessage, type HandedState } from "./delta-context.ts";
+import { canResume, engineIsFresh } from "./turn-context.ts";
+
+export interface ResumePlanInput {
+ task: { resumeCursors: Record<string, unknown>; lastInstanceId?: string; handedMessages?: Record<string, HandedState>; rewound?: boolean; appliedCompactionId?: string };
+ instanceId: string;
+ strictResume: boolean;
+ compacted: number;
+ recordId: string | undefined;
+ folderChanged: boolean;
+ contextOrder: readonly string[];
+ replayable: Array<ContextMessage>;
+ externalMarker: string | undefined;
+ coordinationResumed: boolean;
+ effort: string | undefined;
+}
+
+export function resumePlan(input: ResumePlanInput) {
+ const { task, instanceId, externalMarker } = input;
+ const contextReset = input.compacted > 0 && input.recordId !== task.appliedCompactionId;
+ const cursors = contextReset || input.folderChanged ? {} : task.resumeCursors;
+ const rewound = Boolean(task.rewound);
+ const fresh = !rewound && !externalMarker && engineIsFresh({ instanceId, lastInstanceId: task.lastInstanceId, resumeCursors: cursors, transcript: input.replayable });
+ const cursor = cursors[instanceId];
+ const handed = input.strictResume && !rewound && !contextReset && !fresh && !externalMarker && cursor !== undefined ? task.handedMessages?.[instanceId] : undefined;
+ const unseen = handed && handedStateUsable(handed, cursor, input.contextOrder) ? unseenMessages(input.replayable, input.contextOrder, handed) : undefined;
+ const externalUpdate = Boolean(input.coordinationResumed || unseen?.some((m) => m.keep));
+ /** A Codex thread keeps the last effort it was sent and no turn can clear it, so one holding a level is rebuilt, not resumed. */
+ const stale = (config: string): boolean => {
+ const effortHeld = !input.effort && typeof handed?.effort === "string";
+ return Boolean(handed && (!unseen || effortHeld || (externalUpdate && handed.config !== config)));
+ };
+ return {
+ contextReset, rewound, fresh, cursor, handed, unseen, externalUpdate, stale,
+ resumes: (config: string): boolean => canResume({ rewound, fresh: fresh || contextReset, externallyUpdated: Boolean(externalMarker) || stale(config) }),
+ };
+}
diff --git a/server/turn-context.ts b/server/turn-context.ts
index d3c9656940..cb37a3d713 100644
--- a/server/turn-context.ts
+++ b/server/turn-context.ts
@@ -54,12 +54,16 @@ export function buildRecoveryText(input: {
].join("\n");
}
+/** Whether a turn carries on its engine's session rather than rebuilding it from the transcript. */
+export const canResume = (input: Pick<TurnContextInput, "rewound" | "fresh" | "externallyUpdated">): boolean =>
+ !input.rewound && !input.fresh && !input.externallyUpdated;
+
export function buildTurnContext(input: TurnContextInput): {
turnText: string;
resume: boolean;
} {
- const { text, transcript, rewound, fresh, externallyUpdated, replaysNatively } = input;
- const resume = !rewound && !fresh && !externallyUpdated;
+ const { text, transcript, rewound, externallyUpdated, replaysNatively } = input;
+ const resume = canResume(input);
const replay = !resume && !replaysNatively && transcript.length > 0;
if (!replay) return { turnText: text, resume };
return {