Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): an interrupted run resumes where it stopped

Salman Qureshi3a6d4197d364
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 5fa3ddb1..eece45f1 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -1002,8 +1002,11 @@ export class BotManager {
setTimeout(() => this.resumeDueJobs(), delay).unref?.();
} else if (turnLimited) {
this.queue.settle(job.id, 'done');
+ this.store.clearCheckpoint(botId, job.id);
} else if (output.status === 'failed') {
this.queue.settle(job.id, 'dead', output.reasonCode);
+ // A replay from the dead-letter queue starts fresh: the failure may be in the conversation itself.
+ this.store.clearCheckpoint(botId, job.id);
this.needsYou.add(botId);
logger.warn({ botId, jobId: job.id, reasonCode: output.reasonCode }, 'Bot turn failed permanently — moved to DLQ (replayable via /bots dlq)');
// A routine failing again and again tells the owner once, on the first
@@ -1018,6 +1021,7 @@ export class BotManager {
setTimeout(() => this.resumeDueJobs(), 2000).unref?.();
} else {
this.queue.settle(job.id, 'done');
+ this.store.clearCheckpoint(botId, job.id);
}
// Deliver the outcome — the bot thread is the ONLY local surface
@@ -1232,6 +1236,9 @@ export class BotManager {
provider: resolveProvider(this.providers, manifest, this.config),
tokenBudget: this.tokenBudget,
abortSignal: signal,
+ // Pick up an interrupted run of this job where it stopped; checkpoint every step.
+ resume: this.store.readCheckpoint(botId, job.id) as Parameters<typeof runBotTurn>[0]['resume'],
+ onCheckpoint: (messages) => this.store.writeCheckpoint(botId, job.id, messages),
},
cleanup: () => { /* per-bot registries are persistent, nothing to restore */ },
};
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index ba5d499b..46f631ec 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -102,6 +102,14 @@ export interface BotTurnInput {
/** Durable job id — correlates activity events with the run. */
jobId?: string;
prompt: string;
+ /**
+ * The conversation of an interrupted run of this job (a retry after a
+ * provider error, a step-budget pause, a restart mid-run): the turn picks up
+ * from it instead of redoing every finished step.
+ */
+ resume?: ModelMessage[];
+ /** After every finished step: the conversation so far (without the system prompt), to resume from. */
+ onCheckpoint?: (messages: ModelMessage[]) => void;
/**
* Photos and PDFs for this turn, already on disk. The runtime reads them here:
* a caption-less photo becomes `(Attached: names)` because a provider rejects an
@@ -182,6 +190,10 @@ export interface BotTurnOutput {
const MAX_STEPS_DEFAULT = 25;
+/** Said to the model when a run resumes from its checkpoint. */
+const RESUME_NOTE = '[Resumed] This run was interrupted (an error, a pause or a restart) and continues here. '
+ + 'Everything above already happened: do not redo finished steps or deliver a file twice. Carry on from where it stopped, then close the run as usual.';
+
/** 'thinking' tail emission cadence — a live preview, not a firehose. */
const THINKING_EMIT_INTERVAL_MS = 300;
/** Rolling tail cap per field; surfaces render the tail bottom-anchored. */
@@ -246,12 +258,16 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
...(prompt.volatile ? [{ role: 'system', content: prompt.volatile } as ModelMessage] : []),
];
const leadingSystem = messages.length;
+ const resuming = (input.resume?.length ?? 0) > 0;
- for (const m of input.mail) {
+ if (resuming) {
+ messages.push(...input.resume!, { role: 'user', content: RESUME_NOTE });
+ }
+ for (const m of resuming ? [] : input.mail) {
messages.push({ role: 'user', content: `Message from 🤖 ${m.from}:\n\n${m.content}` });
}
- const files = input.attachments ?? [];
- const caption = turnCaption(input.prompt, files);
+ const files = resuming ? [] : input.attachments ?? [];
+ const caption = resuming ? '' : turnCaption(input.prompt, files);
if (caption) {
messages.push({ role: 'user', content: caption });
}
@@ -339,6 +355,9 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
try {
emit({ kind: 'turn-start', stepIndex: 0, label: input.prompt ? input.prompt.slice(0, 80) : 'Checking inbox' });
while (stepsRemaining > 0 && !governor.signal.aborted) {
+ // This round's steps (assistant tool calls + tool results), cumulative: what the next
+ // round and a resumed run need to see, not just the round's last words.
+ let roundMessages: ModelMessage[] = [];
// streamText, not generateText: the deltas are the real-time feedback
// inside the bot's thread (reasoning + reply tails). Same options and
// step-count semantics; the result's final promises preserve the old
@@ -375,9 +394,13 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
elapsedMs: typeof durationMs === 'number' ? durationMs : undefined,
});
},
- onStepFinish: ({ usage, toolCalls, toolResults }: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[] }) => {
+ onStepFinish: ({ usage, toolCalls, toolResults, response }: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[]; response?: { messages?: unknown[] } }) => {
if (governor.signal.aborted) return;
stepsRemaining--;
+ if (Array.isArray(response?.messages)) {
+ roundMessages = response.messages as ModelMessage[];
+ try { input.onCheckpoint?.([...messages.slice(leadingSystem), ...roundMessages]); } catch { /* a checkpoint is best effort */ }
+ }
if (usage) {
tokensIn += usage.inputTokens ?? 0;
tokensOut += usage.outputTokens ?? 0;
@@ -445,7 +468,9 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
throw new Error('Generation was interrupted before completion (no finish signal from provider)');
}
- if (result.text) {
+ if (roundMessages.length > 0) {
+ messages.push(...roundMessages);
+ } else if (result.text) {
messages.push({ role: 'assistant', content: result.text });
}
diff --git a/src/bots/bots2.test.ts b/src/bots/bots2.test.ts
index 152780dc..87eea2ef 100644
--- a/src/bots/bots2.test.ts
+++ b/src/bots/bots2.test.ts
@@ -251,3 +251,39 @@ describe('deliveries', () => {
expect(second.path).toBe(first.path);
});
});
+
+describe('resuming an interrupted run', () => {
+ it('a retry after a network error continues from the last finished step instead of starting over', async () => {
+ const { manager, store } = makeManager();
+ store.create({ id: 'scout', name: 'Scout' });
+ const seen: Array<Array<{ role?: string; content: unknown }>> = [];
+ let call = 0;
+ const toolCall = { role: 'assistant', content: [{ type: 'tool-call', toolCallId: 'c1', toolName: 'web_search', input: { q: 'oxide' } }] };
+ const toolResult = { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'c1', toolName: 'web_search', output: { type: 'text', value: 'Oxide raised a Series D' } }] };
+ mockedGenerateText.mockImplementation((async (opts: Opts) => {
+ seen.push(opts.messages ?? []);
+ call++;
+ if (call === 1) {
+ // One step done (a search and its result), then the connection drops.
+ opts.onStepFinish?.({ usage: { inputTokens: 100, outputTokens: 5 }, toolCalls: [], toolResults: [], response: { messages: [toolCall, toolResult] } });
+ throw new Error('read ECONNRESET');
+ }
+ const r = await opts.tools.bot_report.execute({ summary: 'Oxide raised a Series D.' }, {});
+ opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 1 }, toolCalls: [{ toolName: 'bot_report', toolCallId: 'r' }], toolResults: [{ toolCallId: 'r', output: { type: 'text', value: r } }] });
+ return { text: '', finishReason: 'stop', usage: {} };
+ }) as never);
+
+ manager.enqueue('scout', { trigger: 'api', prompt: 'any news on Oxide?' });
+ await vi.waitFor(() => expect(call).toBe(2), { timeout: 5000 });
+ await idle(manager, 'scout');
+
+ const retry = seen[1];
+ // The search and its result are there: nothing to redo.
+ expect(retry.some((m) => JSON.stringify(m.content).includes('Oxide raised a Series D'))).toBe(true);
+ expect(retry.some((m) => m.role === 'user' && String(m.content).startsWith('[Resumed]'))).toBe(true);
+ expect(manager.inbox.list()[0]).toMatchObject({ kind: 'result', summary: 'Oxide raised a Series D.' });
+ // Settled: the checkpoint is gone.
+ const [row] = manager.getJournal('scout', 1);
+ expect(store.readCheckpoint('scout', row.runId)).toBeUndefined();
+ });
+});
diff --git a/src/bots/store.ts b/src/bots/store.ts
index e7b9df6e..921487d1 100644
--- a/src/bots/store.ts
+++ b/src/bots/store.ts
@@ -30,6 +30,12 @@ export const BOT_TRANSCRIPTS_DIRNAME = 'transcripts';
export const BOT_STATE_FILENAME = 'state.md';
/** Routine state (paused routines, no-outcome streaks) — ADR-020. */
export const BOT_ROUTINE_STATE_FILENAME = 'routine-state.json';
+/** Per-job conversation checkpoints (resume an interrupted run). */
+export const BOT_CHECKPOINTS_DIRNAME = 'checkpoints';
+const CHECKPOINT_MAX_BYTES = 4 * 1024 * 1024;
+function safeJobId(jobId: string): string {
+ return jobId.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
+}
/** Fleet-level list of bots the owner stopped. */
export const BOT_HELD_FILENAME = 'stopped.json';
/**
@@ -38,7 +44,7 @@ export const BOT_HELD_FILENAME = 'stopped.json';
* used to copy their own profile folders into sandbox/ and outputs/ as
* "mirrors", which the scan then reported as duplicate bots on every boot.
*/
-export const BOT_DATA_DIRNAMES: ReadonlySet<string> = new Set([BOT_SANDBOX_DIRNAME, 'outputs', 'skills', BOT_TRANSCRIPTS_DIRNAME]);
+export const BOT_DATA_DIRNAMES: ReadonlySet<string> = new Set([BOT_SANDBOX_DIRNAME, 'outputs', 'skills', BOT_TRANSCRIPTS_DIRNAME, 'checkpoints']);
export interface BotRoutineState {
/**
@@ -318,6 +324,34 @@ export class BotStore {
atomicWrite(file, state + '\n');
}
+ /**
+ * A job's conversation so far, written after every finished step so an
+ * interrupted run (provider error, pause, restart) resumes instead of
+ * starting over. Removed when the job is settled. Oversized ones are skipped.
+ */
+ writeCheckpoint(id: string, jobId: string, messages: unknown[]): void {
+ try {
+ const body = JSON.stringify({ at: Date.now(), messages });
+ if (body.length > CHECKPOINT_MAX_BYTES) return;
+ const dir = join(this.botDir(id), BOT_CHECKPOINTS_DIRNAME);
+ mkdirSync(dir, { recursive: true });
+ atomicWrite(join(dir, `${safeJobId(jobId)}.json`), body);
+ } catch { /* best effort */ }
+ }
+
+ readCheckpoint(id: string, jobId: string): unknown[] | undefined {
+ try {
+ const raw = JSON.parse(readFileSync(join(this.botDir(id), BOT_CHECKPOINTS_DIRNAME, `${safeJobId(jobId)}.json`), 'utf-8')) as { messages?: unknown[] };
+ return Array.isArray(raw.messages) && raw.messages.length > 0 ? raw.messages : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+
+ clearCheckpoint(id: string, jobId: string): void {
+ try { rmSync(join(this.botDir(id), BOT_CHECKPOINTS_DIRNAME, `${safeJobId(jobId)}.json`), { force: true }); } catch { /* gone */ }
+ }
+
/** Bots the owner stopped (/bots stop, the app's Stop). Durable: a restart must not undo a stop. */
readHeld(): Set<string> {
try {