Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(bots): lease heartbeat, 'timed out' classification, non-destructive DLQ replay
Salman Qureshia3922f804499
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 1858ee08..cf63d0ee 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -442,8 +442,20 @@ export class BotManager {return;}+ // Lease heartbeat: a turn can outlive LEASE_SECONDS by minutes (long+ // provider calls). Without a heartbeat the 30s due-sweep requeues the+ // STILL-RUNNING job, a duplicate turn starts, and whichever settles+ // first makes the other's settle a silent no-op — the job vanishes+ // from the DLQ and /bots replay reports not_found. A live turn must+ // never expire its lease.+ let heartbeat: ReturnType<typeof setInterval> | undefined;+try {this.queue.claim(job.id, LEASE_SECONDS);+ heartbeat = setInterval(() => {+ try { this.queue.heartbeatLease(job.id, LEASE_SECONDS); } catch { /* best effort */ }+ }, (LEASE_SECONDS / 3) * 1000);+ heartbeat.unref?.();const turn = this.buildTurn(botId, manifest, job, controller.signal);const output = await runBotTurn({...turn.input,@@ -599,6 +611,7 @@ export class BotManager {});this.needsYou.add(botId);} finally {+ if (heartbeat) clearInterval(heartbeat);running.delete(job.id);this.aborts.delete(`${botId}:${job.id}`);if (running.size === 0) this.activity.delete(botId);@@ -1174,8 +1187,12 @@ export class BotManager {/** Re-run a dead-lettered job: remove it from the DLQ and re-enqueue fresh. */replayDlq(botId: string, jobId: string): { accepted: boolean; jobId?: string; reasonCode?: string } {- const entry = this.queue.removeFromDlq(jobId);+ // Look up WITHOUT removing first: a bot-id mismatch must not destroy the+ // DLQ entry (the old remove-then-check permanently deleted real work and+ // then reported not_found).+ const entry = this.queue.peekDlq(jobId);if (!entry || entry.botId !== botId) return { accepted: false, reasonCode: 'not_found' };+ this.queue.removeFromDlq(jobId);return this.enqueue(botId, {trigger: entry.trigger,prompt: entry.prompt,diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.tsindex 9ff5b740..1c088524 100644--- a/src/bots/bot-turn.test.ts+++ b/src/bots/bot-turn.test.ts@@ -102,6 +102,11 @@ describe('runBotTurn step-budget continuation', () => {expect(classifyFailure(new Error('Cannot connect to API: read ECONNRESET'))).toBe('provider_timeout');expect(classifyFailure(new Error('getaddrinfo ENOTFOUND api.example.com'))).toBe('provider_timeout');expect(classifyFailure(new Error('fetch failed: ECONNREFUSED 1.2.3.4:443'))).toBe('provider_timeout');+ // "The operation timed out." (with a SPACE) is how several providers+ // phrase a deadline miss — it used to fall through to unknown_error and+ // ship long leader-bot turns straight to the DLQ instead of retrying.+ expect(classifyFailure(new Error('The operation timed out.'))).toBe('provider_timeout');+ expect(classifyFailure(new Error('Request timed out after 60000ms'))).toBe('provider_timeout');// Still-permanent things stay permanent.expect(classifyFailure(new Error('401 unauthorized'))).toBe('provider_auth');expect(classifyFailure(new Error('permission denied by policy'))).toBe('permission_denied');diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex c6f6aab5..049a0565 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -279,8 +279,10 @@ export function classifyFailure(err: any): string {// Network blips ARE transient — ECONNRESET (connection dropped mid-read)// and friends used to fall through to unknown_error, so a plain// connection blip went straight to the DLQ with a needs-you flag instead- // of retrying like every other transient failure.- if (/timeout|etimedout|econnaborted|econnreset|econnrefused|epipe|enotfound|eai_again|getaddrinfo|fetch failed|socket hang up|network/.test(msg)) return 'provider_timeout';+ // of retrying like every other transient failure. "timed out" (with a+ // space) is how several providers phrase a deadline miss — it also used to+ // fall through to unknown_error and land the turn in the DLQ.+ if (/timeout|timed out|etimedout|econnaborted|econnreset|econnrefused|epipe|enotfound|eai_again|getaddrinfo|fetch failed|socket hang up|network/.test(msg)) return 'provider_timeout';if (/permission denied|blocked command|no permission/.test(msg)) return 'permission_denied';if (/api key|unauthorized|401|authentication/.test(msg)) return 'provider_auth';if (/quota|billing|402/.test(msg)) return 'provider_quota';diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.tsindex 6f1e2896..d5315504 100644--- a/src/bots/queue.test.ts+++ b/src/bots/queue.test.ts@@ -283,4 +283,39 @@ describe('BotManager durable queue integration', () => {expect(replay.accepted).toBe(true);expect(manager.getDlq('alpha')).toHaveLength(0);});++ it('replaying a job under the WRONG bot id does not destroy the DLQ entry', async () => {+ // The old replayDlq removed the entry BEFORE checking the bot — a+ // mismatch permanently deleted real work and still reported not_found.+ mockedGenerateText.mockReset();+ mockedGenerateText.mockRejectedValue(new Error('permission denied: workspace'));+ store.create({ id: 'alpha', name: 'Alpha' });+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'do the thing' });+ await new Promise(r => setTimeout(r, 50));+ const jobId = manager.getDlq('alpha')[0].id;+ expect(manager.replayDlq('other-bot', jobId)).toMatchObject({ accepted: false, reasonCode: 'not_found' });+ expect(manager.getDlq('alpha')).toHaveLength(1); // still there — lookup happened before removal+ // A correct-bot replay then succeeds.+ mockedGenerateText.mockResolvedValue({ text: 'done', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);+ expect(manager.replayDlq('alpha', jobId).accepted).toBe(true);+ });++ it('a heartbeat keeps a claimed lease alive past its lease window', () => {+ // Live bug: a 20-minute leader-bot turn outlived the 60s lease, the+ // due-sweep requeued the STILL-RUNNING job, and the race made its later+ // settle a silent no-op — the job never reached the DLQ.+ for (const name of ['json', 'sqlite'] as const) {+ const dir = join(root, `heartbeat-${name}`);+ const backend = mkBackend(name, dir);+ backend.enqueue(job('hb1'));+ backend.claim('hb1', 60);+ backend.heartbeatLease('hb1', 60); // the turn is alive — lease window reset+ // Expire the PRE-heartbeat lease but not the heartbeated one: the+ // heartbeat renewed the whole window, so at +1s it is still claimed.+ expect(backend.counts().claimed).toBe(1);+ expect(backend.rehydratable()).toHaveLength(0);+ backend.heartbeatLease('hb1', 0); // heartbeat to an instant-expiry lease → swept again+ expect(backend.rehydratable()).toHaveLength(1);+ }+ });});\ No newline at end of filediff --git a/src/bots/queue.ts b/src/bots/queue.tsindex f0da0507..410378e7 100644--- a/src/bots/queue.ts+++ b/src/bots/queue.ts@@ -92,6 +92,8 @@ export interface BotQueueBackend {requeueExpiredLeases(): number;heartbeatLease(jobId: string, leaseSeconds: number): void;listDlq(botId?: string): DlqEntry[];+ /** Read a DLQ entry without removing it (replay does lookup-then-remove so a bot mismatch never destroys the entry). */+ peekDlq(jobId: string): DurableBotJob | null;removeFromDlq(jobId: string): DurableBotJob | null;/** Durable bot-to-bot mailbox (§2.6: a handoff must survive a crash). */enqueueMail(mail: Omit<DurableMail, 'id'>): string;@@ -230,6 +232,16 @@ export class BotQueue {return this.backend.removeFromDlq(jobId);}+ peekDlq(jobId: string): DurableBotJob | null {+ if (this.closed) return null;+ return this.backend.peekDlq(jobId);+ }++ heartbeatLease(jobId: string, leaseSeconds: number = LEASE_SECONDS): void {+ if (this.closed) return;+ this.backend.heartbeatLease(jobId, leaseSeconds);+ }+counts(): QueueCounts {if (this.closed) return { pending: 0, claimed: 0, dlq: 0 };return this.backend.counts();@@ -430,6 +442,11 @@ export class SqliteQueueBackend implements BotQueueBackend {}));}+ peekDlq(jobId: string): DurableBotJob | null {+ const row = this.db.prepare(`SELECT * FROM bot_dlq WHERE id = ?`).get(jobId) as any;+ return row ? ({ ...normalizeJob(row), state: 'dead' as const, deadAt: row.dead_at } as any) : null;+ }+removeFromDlq(jobId: string): DurableBotJob | null {const row = this.db.prepare(`SELECT * FROM bot_dlq WHERE id = ?`).get(jobId) as any;if (!row) return null;@@ -626,6 +643,10 @@ export class JsonFileQueueBackend implements BotQueueBackend {return this.data.dlq.filter(j => !botId || j.botId === botId);}+ peekDlq(jobId: string): DurableBotJob | null {+ return this.data.dlq.find(j => j.id === jobId) ?? null;+ }+removeFromDlq(jobId: string): DurableBotJob | null {const idx = this.data.dlq.findIndex(j => j.id === jobId);if (idx === -1) return null;