Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(goal): one retry policy for failed Task runs and main Agent turns (#20431)

Arvin Xu3851714fc1fc
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 650498e96ef..9c054fbe8bc 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -49,6 +49,7 @@ import {
import { GoalExplorationPlanner } from './explorationPlanner';
import { GoalService } from './index';
import { DEVICE_OFFLINE_GATE_REASON, VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';
+import * as scheduler from './scheduler';
import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';
import type { GoalTickObservation } from './traceObservation';
@@ -3862,6 +3863,112 @@ describe('GoalService', () => {
});
});
+ describe('a Task its usage window refused', () => {
+ const SESSION_LIMIT = "You've hit your session limit · resets 4:30am";
+
+ const setup = async (title: string, resetsAtMs: number) => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { maxAttemptsPerTask: 3 } },
+ title,
+ tasks: ['Run on the external Agent'],
+ });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+
+ const operationModel = new AgentOperationModel(serverDB, userId);
+ await operationModel.recordStart({ operationId: 'op-quota', taskId: created.taskId });
+ await operationModel.recordCompletion('op-quota', {
+ completedAt: new Date(),
+ completionReason: 'error',
+ error: {
+ body: {
+ code: 'rate_limit',
+ rateLimitInfo: { resetsAt: Math.floor(resetsAtMs / 1000), status: 'rejected' },
+ },
+ category: 'quota',
+ message: SESSION_LIMIT,
+ },
+ status: 'error',
+ });
+ vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([
+ { operationId: 'op-quota' } as never,
+ ]);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: SESSION_LIMIT });
+ return { created, graph, service };
+ };
+
+ it('waits for the reset instead of asking a person', async () => {
+ const schedule = vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();
+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');
+ const resetsAt = Date.now() + 2 * 60 * 60 * 1000;
+ const { created, graph, service } = await setup('Session limit', resetsAt);
+
+ const waiting = await service.tick(graph.goal.id);
+
+ expect(waiting).toMatchObject({
+ message: expect.stringContaining('usage window to reset'),
+ outcome: 'waiting_external',
+ taskId: created.taskId,
+ });
+ expect(schedule).toHaveBeenLastCalledWith(
+ expect.objectContaining({ goalId: graph.goal.id, trigger: 'wake' }),
+ );
+ expect(schedule.mock.lastCall![0].delay).toBeGreaterThanOrEqual(2 * 60 * 60);
+
+ // More ticks before the reset (the sweep, Task events) queue no more wakes,
+ // and a policy edit from a stale snapshot does not drop the armed receipt.
+ await service.tick(graph.goal.id);
+ await new GoalModel(serverDB, userId).update(graph.goal.id, {
+ config: { recovery: { maxAttemptsPerTask: 3 } },
+ });
+ expect((await service.graph(graph.goal.id)).goal.config?.quotaRetryWakeAt).toBeDefined();
+ await service.tick(graph.goal.id);
+ expect(schedule.mock.calls.filter(([params]) => params.trigger === 'wake')).toHaveLength(1);
+ expect(runSpy).not.toHaveBeenCalled();
+ const after = await service.graph(graph.goal.id);
+ expect(after.decisions).toHaveLength(0);
+ expect(after.goal.config?.supervisorState?.incidents ?? []).toHaveLength(0);
+ });
+
+ it('retries through ordinary recovery once the window has reset', async () => {
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockResolvedValue({ operationId: 'op-after-reset', success: true } as never);
+ const { created, graph, service } = await setup(
+ 'Session limit over',
+ Date.now() - 2 * 60 * 1000,
+ );
+
+ const retried = await service.tick(graph.goal.id);
+
+ expect(runSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),
+ );
+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });
+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);
+ });
+
+ it('does not start the retry once the Goal deadline has passed', async () => {
+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');
+ const { graph, service } = await setup(
+ 'Reset after the deadline',
+ Date.now() - 2 * 60 * 1000,
+ );
+ await serverDB
+ .update(goals)
+ .set({
+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{schedule}', ${JSON.stringify({ deadline: new Date(Date.now() - 60_000).toISOString() })}::jsonb)`,
+ })
+ .where(eq(goals.id, graph.goal.id));
+
+ await service.tick(graph.goal.id);
+
+ expect(runSpy).not.toHaveBeenCalled();
+ });
+ });
+
describe('a Task whose runs its device lost', () => {
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index bddcdb2c24b..c26ac3da0db 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -69,12 +69,14 @@ import {
import { experimentResults, exploreGraph } from './exploreGraph';
import { answeredProblem, GoalManagerService, problemKey } from './manager';
import {
+ classifyRunFailure,
countConsecutiveDeviceOfflineRuns,
DEFAULT_MANAGER_MAX_TURNS,
DEVICE_OFFLINE_GATE_REASON,
isDeviceUnavailableFailure,
managerTurnsSpent,
nextDeviceOfflineRetryAt,
+ QUOTA_RESET_MARGIN_MS,
resolveMaxConcurrentTasks,
resolveOperationLeaseTimeout,
resolveTaskMaxSteps,
@@ -2344,7 +2346,9 @@ export class GoalService {
}
case 'failure_decision': {
- const waiting = await this.waitForDevice(graph, acting!.id, task, effects);
+ const waiting =
+ (await this.waitForDevice(graph, acting!.id, task, effects)) ??
+ (await this.waitForQuotaReset(graph, acting!.id, task, effects));
if (waiting) return observe(waiting);
const supervision = await new GoalSupervisorService(
this.db,
@@ -3086,6 +3090,70 @@ export class GoalService {
return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);
};
+ /**
+ * Hold a Task whose run a usage window refused until that window reopens.
+ *
+ * An external Agent past its session limit refuses every run until the reset
+ * its error reports. The supervisor used to read that as "spending requires
+ * user action" and open a gate, which then waited on a person to press Retry
+ * long after the window had reset. The coordinator now waits out the reset
+ * itself and retries through the ordinary recovery path, which charges the
+ * attempt as before. That bounds a window that keeps refusing.
+ */
+ private waitForQuotaReset = async (
+ graph: GoalGraphSnapshot,
+ nodeId: string,
+ task: TaskItem,
+ effects: GoalAdvanceEffect[],
+ ): Promise<GoalTickResult | undefined> => {
+ if (task.status !== 'paused') return;
+ const [latest] = await this.taskTopicModel.findWithHandoff(task.id, 1);
+ if (!latest?.operationId) return;
+ const operation = await new AgentOperationModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findById(latest.operationId);
+ const failure = classifyRunFailure(operation?.error, task.error ?? '');
+ if (failure.kind !== 'quota_reset') return;
+ const retryAt = failure.resetsAt! + QUOTA_RESET_MARGIN_MS;
+ if (retryAt <= Date.now()) {
+ // The retry is a paid run, and recovery only checks the Task's own attempts
+ // and cost. Past the Goal's deadline, rounds or spend it is not this path's
+ // to start: ordinary failure handling takes it, and that gates it.
+ const budget = await this.evaluateBudget(graph.goal, graph);
+ if (budget.costLimitReached || budget.roundLimitReached || budget.deadlinePassed) return;
+ return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);
+ }
+ // The sweep would get here too, but only on its own cadence; the reset is a
+ // known time, so ask for that tick directly. One wake per Goal: the claim
+ // fails while an earlier-or-equal wake is still pending. A reset further out
+ // than the queue's longest delay is re-armed when the capped wake fires.
+ const target = new Date(retryAt).toISOString();
+ const armed = GoalWaitService.arm(target);
+ // Claim on the reset itself, not on `armedUntil`: that rounds the delay up to
+ // whole seconds from each tick's own clock, so two ticks before the same reset
+ // would read as different wakes. Only a capped wake stores its earlier fire time.
+ const capped = Date.parse(armed.armedUntil) < retryAt;
+ if (
+ await new GoalModel(this.db, this.userId, this.workspaceId).armQuotaRetryWake(
+ graph.goal.id,
+ capped ? armed.armedUntil : target,
+ )
+ )
+ await new GoalWaitService(this.db, this.userId, this.workspaceId).schedule(
+ graph.goal.id,
+ armed.delay,
+ );
+ return {
+ goalId: graph.goal.id,
+ message: `Task ${task.identifier} is waiting for its usage window to reset at ${new Date(retryAt).toISOString()}`,
+ nodeId,
+ outcome: 'waiting_external',
+ taskId: task.id,
+ };
+ };
+
/**
* The offline retry schedule. Offline runs are not charged to the attempt
* budget, so this is what bounds them: each consecutive one pushes the next
diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.md
index ae4229e667b..4962282187e 100644
--- a/apps/server/src/services/goal/manager.README.md
+++ b/apps/server/src/services/goal/manager.README.md
@@ -137,7 +137,24 @@ Read `config.managerState` in the Goal graph for the current receipt and Topic.
Wakeups use the existing Goal scheduler (queued mode for restart durability).
After a confirmed terminal main operation without a plan, another turn can
-reread the durable graph within the turn budget. An unconfirmed running/missing
+reread the durable graph within the turn budget. A turn that ended in an error
+gates the next one through `managerState.retryAfter`. The error is classified by
+`classifyRunFailure` (`recoveryPolicy.ts`), the same classifier Task recovery
+uses:
+
+- A quota rejection that reports its reset, such as an external Agent's session
+ limit, waits for that reset. The refused turn is not charged to the budget.
+- A device that cannot be reached follows the Task offline schedule: 30 minutes,
+ doubling to 8 hours, over six retries. These turns are not charged, and seeing
+ the device online again ends the wait early. When the schedule runs out, the
+ Goal pauses.
+- Credentials, spend, permission or configuration errors pause the Goal at once.
+- Anything else backs off exponentially from one minute up to 30 minutes and is
+ charged. Five such turns in a row pause the Goal on the last error.
+
+A pause clears these streaks, so resuming starts a fresh schedule. Before this, a
+failing Agent was re-dispatched on every tick and spent the whole turn budget in
+minutes. An unconfirmed running/missing
operation times out after 20 minutes and pauses without launching a replacement;
confirm its exit before resuming. Parked human/async-tool operations retain
ownership; a human wait is surfaced without starting another planning turn.
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index f813c1f4e85..ee6e87b5962 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -28,8 +28,9 @@ import { goalRouter } from '@/server/routers/lambda/goal';
import { AiAgentService } from '@/server/services/aiAgent';
import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';
+import { deviceGateway } from '../deviceGateway';
import { GoalService } from './index';
-import { GoalManagerService } from './manager';
+import { decideFailedTurn, GoalManagerService, MAX_FAILED_MANAGER_TURNS } from './manager';
import * as scheduler from './scheduler';
import { GoalWaitService } from './wait';
@@ -739,7 +740,7 @@ describe('CLI main Agent planning', () => {
completionReason: 'error',
error: { message: 'transport error' },
});
- expect((await service().tick(id)).outcome).toBe('advanced');
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
expect((await service().tick(id)).outcome).toBe('no_progress');
expect((await model().findById(id))!.status).toBe('paused');
expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
@@ -750,6 +751,9 @@ describe('CLI main Agent planning', () => {
await ops().recordCompletion(op.id, { status: 'error' });
await service().tick(id);
const stale = await service().graph(id);
+ // Past the backoff the failed turn set, so the next turn may start.
+ const now = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(now + 2 * 60_000);
await service().tick(id);
const second = (await model().findById(id))!.config!.managerState!;
await ops().recordCompletion(second.operationId!, { status: 'error' });
@@ -761,6 +765,171 @@ describe('CLI main Agent planning', () => {
expect((await model().findById(id))!.status).toBe('paused');
});
+ describe('a turn that fails without a plan', () => {
+ const quotaError = (resetsAt: number) => ({
+ message: "You've hit your session limit",
+ category: 'quota',
+ body: {
+ code: 'rate_limit',
+ rateLimitInfo: { status: 'rejected', resetsAt, rateLimitType: 'five_hour' },
+ },
+ });
+
+ it('waits for a quota reset without charging the refused turn', async () => {
+ const { id, op } = await start(3);
+ const now = Date.now();
+ const resetsAt = Math.floor(now / 1000) + 600;
+ await ops().recordCompletion(op.id, { status: 'error', error: quotaError(resetsAt) });
+
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+ const state = (await model().findById(id))!.config!.managerState!;
+ expect(state.turns).toBe(0);
+ expect(Date.parse(state.retryAfter!)).toBe(resetsAt * 1000 + 60_000);
+ expect(vi.mocked(scheduler.scheduleGoalAdvance)).toHaveBeenLastCalledWith(
+ expect.objectContaining({ goalId: id, delay: expect.any(Number) }),
+ );
+ expect(
+ vi.mocked(scheduler.scheduleGoalAdvance).mock.lastCall![0].delay,
+ ).toBeGreaterThanOrEqual(600);
+
+ // The sweep and Task events keep ticking before the reset; none of them
+ // may dispatch a turn that would be refused the same way.
+ for (let i = 0; i < 10; i++)
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
+
+ vi.spyOn(Date, 'now').mockReturnValue(resetsAt * 1000 + 61_000);
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(2);
+ expect((await model().findById(id))!.config!.managerState!.turns).toBe(1);
+ });
+
+ it('backs off and pauses on the error after consecutive failed turns', async () => {
+ const { id, op } = await start(20);
+ let now = Date.now();
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ let operationId = op.id;
+ for (let failed = 1; failed <= MAX_FAILED_MANAGER_TURNS; failed++) {
+ await ops().recordCompletion(operationId, {
+ status: 'error',
+ error: { message: 'spawn claude ENOENT' },
+ });
+ const result = await service().tick(id);
+ const state = (await model().findById(id))!.config!.managerState!;
+ if (failed === MAX_FAILED_MANAGER_TURNS) {
+ expect(result.outcome).toBe('no_progress');
+ expect(result.message).toContain('spawn claude ENOENT');
+ // Whoever resumes the Goal starts from a fresh schedule.
+ expect(state.failedTurns).toBeUndefined();
+ break;
+ }
+ expect(state.failedTurns).toBe(failed);
+ expect(result.outcome).toBe('waiting_external');
+ expect(Date.parse(state.retryAfter!) - now).toBe(60_000 * 2 ** (failed - 1));
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(failed);
+ now = Date.parse(state.retryAfter!) + 1;
+ await service().tick(id);
+ operationId = (await model().findById(id))!.config!.managerState!.operationId!;
+ }
+ clock.mockRestore();
+ expect((await model().findById(id))!.status).toBe('paused');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(
+ MAX_FAILED_MANAGER_TURNS,
+ );
+ });
+
+ it('waits for an offline device on the Task schedule without charging the turn', async () => {
+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);
+ const list = vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);
+ const { id, op } = await start(3);
+ const now = Date.now();
+ await ops().recordCompletion(op.id, {
+ status: 'error',
+ error: {
+ deviceRoute: { deviceId: 'device-laptop', userId },
+ message: 'DEVICE_OFFLINE (HTTP 503)',
+ },
+ });
+
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+ const state = (await model().findById(id))!.config!.managerState!;
+ expect(state.turns).toBe(0);
+ expect(state.offlineTurns).toBe(1);
+ expect(state.failedTurns).toBeUndefined();
+ expect(Date.parse(state.retryAfter!) - now).toBeGreaterThanOrEqual(30 * 60_000 - 1000);
+
+ // Still offline: no turn.
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
+ expect(list).toHaveBeenCalledWith(userId, undefined);
+
+ // Back online before the scheduled retry: plan right away.
+ list.mockResolvedValue([{ deviceId: 'device-laptop' } as never]);
+ await service().tick(id);
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(2);
+ });
+
+ it('pauses at once on an error only a person can fix', async () => {
+ const { id, op } = await start(10);
+ await ops().recordCompletion(op.id, {
+ status: 'error',
+ error: { category: 'quota', message: 'Insufficient balance' },
+ });
+
+ const result = await service().tick(id);
+ expect(result.outcome).toBe('no_progress');
+ expect(result.message).toContain('Insufficient balance');
+ expect((await model().findById(id))!.status).toBe('paused');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
+ });
+
+ it('pauses in the same transaction that consumes the failed turn', async () => {
+ const { id, op } = await start(10);
+ await ops().recordCompletion(op.id, {
+ status: 'error',
+ error: { category: 'auth', message: 'Invalid API key' },
+ });
+ // A concurrent tick that lands right after the settling transaction commits.
+ const original = db.transaction.bind(db);
+ let raced = false;
+ vi.spyOn(db, 'transaction').mockImplementation((async (
+ ...args: Parameters<typeof db.transaction>
+ ) => {
+ const result = await original(...args);
+ const goal = await model().findById(id);
+ if (!raced && goal?.config?.managerState?.consumed) {
+ raced = true;
+ await manager().advance(await service().graph(id));
+ }
+ return result;
+ }) as typeof db.transaction);
+
+ expect((await service().tick(id)).outcome).toBe('no_progress');
+ expect(raced).toBe(true);
+ expect((await model().findById(id))!.status).toBe('paused');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a running turn plan valid when a Task arms its quota wake', async () => {
+ const { id, state, op } = await start();
+ expect(
+ await model().armQuotaRetryWake(id, new Date(Date.now() + 3_600_000).toISOString()),
+ ).toBe(true);
+ await expect(manager().submit(id, state.token, op.id, taskPlan)).resolves.toBeDefined();
+ });
+
+ it('does not hold back the next turn after a committed plan whose run errored', async () => {
+ const { id, state, op } = await start();
+ await manager().submit(id, state.token, op.id, taskPlan);
+ await ops().recordCompletion(op.id, { status: 'error', error: { message: 'late crash' } });
+ expect((await service().tick(id)).outcome).not.toBe('no_progress');
+ const settled = (await model().findById(id))!.config!.managerState!;
+ expect(settled.retryAfter).toBeUndefined();
+ expect(settled.failedTurns).toBeUndefined();
+ });
+ });
+
it.each(['waiting_for_human', 'waiting_for_async_tool'] as const)(
'retains ownership of a parked %s operation and requires confirmed cancellation',
async (status) => {
@@ -1939,3 +2108,71 @@ describe('durable manager continuation', () => {
).rejects.toMatchObject({ code: 'CONFLICT' });
});
});
+
+describe('decideFailedTurn', () => {
+ const now = Date.parse('2026-10-05T19:49:30Z');
+
+ it('waits for the reported quota reset and does not charge the turn', () => {
+ const resetsAt = Math.floor(now / 1000) + 3600;
+ expect(
+ decideFailedTurn(
+ { category: 'quota', body: { code: 'rate_limit', rateLimitInfo: { resetsAt } } },
+ { failedTurns: 2 },
+ now,
+ ),
+ ).toMatchObject({
+ action: 'retry',
+ charged: false,
+ failedTurns: 2,
+ retryAfter: new Date(resetsAt * 1000 + 60_000).toISOString(),
+ });
+ });
+
+ it('follows the Task offline schedule for an unreachable device, then pauses', () => {
+ const offline = { message: 'DEVICE_OFFLINE' };
+ const delays = [0, 1, 2, 3, 4, 5].map((offlineTurns) => {
+ const decision = decideFailedTurn(offline, { offlineTurns }, now);
+ expect(decision).toMatchObject({ action: 'retry', charged: false });
+ return decision.action === 'retry' ? Date.parse(decision.retryAfter) - now : 0;
+ });
+ const HOUR = 60 * 60_000;
+ expect(delays).toEqual([HOUR / 2, HOUR, 2 * HOUR, 4 * HOUR, 8 * HOUR, 8 * HOUR]);
+ expect(decideFailedTurn(offline, { offlineTurns: 6 }, now).action).toBe('pause');
+ });
+
+ it('restarts the offline schedule after a failure that reached the device', () => {
+ const between = decideFailedTurn({ message: 'boom' }, { offlineTurns: 3 }, now);
+ expect(between).toMatchObject({ action: 'retry', offlineTurns: 0 });
+ const next = decideFailedTurn({ message: 'DEVICE_OFFLINE' }, { offlineTurns: 0 }, now);
+ expect(next.action === 'retry' && Date.parse(next.retryAfter) - now).toBe(30 * 60_000);
+ });
+
+ it('pauses at once when a person has to act', () => {
+ for (const error of [
+ { category: 'auth', message: 'Invalid API key' },
+ { category: 'quota', message: 'Insufficient balance' },
+ // A session limit without a reset time cannot be waited out.
+ { body: { code: 'rate_limit' }, category: 'quota', message: 'session limit' },
+ ])
+ expect(decideFailedTurn(error, {}, now).action).toBe('pause');
+ });
+
+ it('backs off transient and unknown errors, then pauses on the fifth in a row', () => {
+ const delays = [0, 1, 2, 3].map((failedTurns) => {
+ const decision = decideFailedTurn({ message: 'boom' }, { failedTurns }, now);
+ expect(decision).toMatchObject({ action: 'retry', charged: true });
+ return decision.action === 'retry' ? Date.parse(decision.retryAfter) - now : 0;
+ });
+ expect(delays).toEqual([60_000, 120_000, 240_000, 480_000]);
+ expect(
+ decideFailedTurn({ category: 'capacity', message: '429' }, { failedTurns: 4 }, now),
+ ).toMatchObject({ action: 'pause', reason: expect.stringContaining('5 turns') });
+ });
+
+ it('charges a quota error whose reset has already passed like any other failure', () => {
+ const past = Math.floor(now / 1000) - 600;
+ expect(
+ decideFailedTurn({ category: 'quota', body: { rateLimitInfo: { resetsAt: past } } }, {}, now),
+ ).toMatchObject({ action: 'retry', charged: true });
+ });
+});
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index e92056c0f33..9e98a6c2e4e 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -24,10 +24,19 @@ import { TopicModel } from '@/database/models/topic';
import { goals } from '@/database/schemas/goal';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
+import { readDeviceDispatchRoute } from '@/server/services/aiAgent/helpers/heteroErrors';
import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { TERMINAL_GOAL_STATUSES as finishedGoalStatuses } from './goalTraceRecorder';
-import { countDeviceOfflineRuns, DEFAULT_MANAGER_MAX_TURNS } from './recoveryPolicy';
+import {
+ classifyRunFailure,
+ countDeviceOfflineRuns,
+ DEFAULT_MANAGER_MAX_TURNS,
+ nextDeviceOfflineRetryAt,
+ QUOTA_RESET_MARGIN_MS,
+ type RunFailure,
+} from './recoveryPolicy';
import { scheduleGoalAdvance } from './scheduler';
import { recoveryEligibility } from './supervisor/policy';
import { goalWaitSchema, GoalWaitService } from './wait';
@@ -80,6 +89,99 @@ const TIMEOUT_MS = 20 * 60_000;
const FEEDBACK_NOTE_LIMIT = 20;
/** Source message id prefix of a dispatched planning turn; the suffix is its token. */
const MANAGER_SOURCE_MESSAGE_PREFIX = 'msg_goal_manager_';
+/** Consecutive charged turns that errored without a plan before the Goal pauses. */
+export const MAX_FAILED_MANAGER_TURNS = 5;
+const FAILED_TURN_BASE_BACKOFF_MS = 60_000;
+const FAILED_TURN_MAX_BACKOFF_MS = 30 * 60_000;
+
+export type FailedTurnDecision =
+ | { action: 'pause'; failure: RunFailure; reason: string }
+ | {
+ action: 'retry';
+ /** Whether the failed turn counts toward the manager turn budget. */
+ charged: boolean;
+ failure: RunFailure;
+ failedTurns: number;
+ offlineTurns: number;
+ retryAfter: string;
+ };
+
+/**
+ * What to do after a planning turn ended in an error without committing a plan.
+ *
+ * It follows the same classification as Task recovery (`classifyRunFailure`):
+ * - A usage window that reports its reset waits for that reset. The refused
+ * turn did no work, so it is not charged.
+ * - A device that is not reachable follows the Task offline schedule
+ * (30 min, doubling to 8 h, six retries). It is not charged, and the Goal
+ * pauses once the device stays away.
+ * - Credentials, spend or permission pause at once, because no retry fixes them.
+ * - Anything else backs off exponentially from 1 min to 30 min and is charged.
+ * `MAX_FAILED_MANAGER_TURNS` in a row pause the Goal.
+ *
+ * Before this, every failure re-dispatched on the next tick. That is how one Goal
+ * spent its whole 100-turn budget on a session limit in 20 minutes.
+ */
+export const decideFailedTurn = (
+ error: unknown,
+ streak: { failedTurns?: number; offlineTurns?: number },
+ now = Date.now(),
+): FailedTurnDecision => {
+ const failure = classifyRunFailure(error);
+ const failedTurns = streak.failedTurns ?? 0;
+ // `offlineTurns` counts turns that never reached their device back to back. Any
+ // other ending reached it, so only a device failure carries the streak forward.
+ const offlineTurns = failure.kind === 'device_unavailable' ? (streak.offlineTurns ?? 0) : 0;
+ const message = (error as { message?: unknown } | undefined)?.message;
+ const detail = typeof message === 'string' && message ? `: ${message}` : '';
+
+ if (failure.kind === 'quota_reset' && failure.resetsAt! + QUOTA_RESET_MARGIN_MS > now)
+ return {
+ action: 'retry',
+ charged: false,
+ failedTurns,
+ failure,
+ offlineTurns,
+ retryAfter: new Date(failure.resetsAt! + QUOTA_RESET_MARGIN_MS).toISOString(),
+ };
+ if (failure.kind === 'device_unavailable') {
+ const retryAt = nextDeviceOfflineRetryAt(offlineTurns + 1, new Date(now));
+ if (!retryAt)
+ return { action: 'pause', failure, reason: `Main Agent device stayed offline${detail}` };
+ return {
+ action: 'retry',
+ charged: false,
+ failedTurns,
+ failure,
+ offlineTurns: offlineTurns + 1,
+ retryAfter: retryAt.toISOString(),
+ };
+ }
+ if (failure.kind === 'needs_user')
+ return {
+ action: 'pause',
+ failure,
+ reason: `Main Agent needs credentials, spend or permission fixed${detail}`,
+ };
+ if (failedTurns + 1 >= MAX_FAILED_MANAGER_TURNS)
+ return {
+ action: 'pause',
+ failure,
+ reason: `Main Agent failed ${failedTurns + 1} turns in a row without a plan${detail}`,
+ };
+ const backoff = Math.min(
+ FAILED_TURN_MAX_BACKOFF_MS,
+ FAILED_TURN_BASE_BACKOFF_MS * 2 ** failedTurns,
+ );
+ return {
+ action: 'retry',
+ charged: true,
+ failedTurns: failedTurns + 1,
+ failure,
+ offlineTurns,
+ retryAfter: new Date(now + backoff).toISOString(),
+ };
+};
/**
* The token a planning turn is keyed by, carrying the Goal it belongs to.
@@ -94,7 +196,9 @@ const managerTurnToken = (goalId: string) => `${goalId}_${randomUUID()}`;
/** Excludes only the manager's own receipt. Concurrent policy/graph changes invalidate its plan. */
export const managerSnapshot = (graph: GoalGraphSnapshot) => {
- const { managerState: _state, ...config } = graph.goal.config ?? {};
+ // Coordinator receipts are not planning input: arming a Task's quota wake while a
+ // turn runs must not make that turn's plan stale.
+ const { managerState: _state, quotaRetryWakeAt: _quotaWake, ...config } = graph.goal.config ?? {};
return createHash('sha256')
.update(
JSON.stringify({
@@ -528,6 +632,14 @@ export class GoalManagerService {
return { goalId, outcome: 'waiting_external', message };
};
+ /** Whether the device the last turn could not reach is connected again. */
+ private offlineDeviceIsBack = async (state: GoalManagerState) => {
+ const route = state.offlineDevice;
+ if (!route || !deviceGateway.isConfigured) return false;
+ const devices = await deviceGateway.queryDeviceList(route.userId, route.workspaceId);
+ return devices.some((device) => device.deviceId === route.deviceId);
+ };
+
private pause = async (goalId: string, message: string): Promise<GoalTickResult> => {
await this.db.transaction(async (db) => {
const model = new GoalModel(db, this.userId, this.workspaceId);
@@ -709,19 +821,69 @@ export class GoalManagerService {
}
return this.wait(goal.id, 'Waiting for main Agent CLI planning turn');
}
- await this.db.transaction(async (db) => {
+ const failed = await this.db.transaction(async (db) => {
const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goal.id);
- if (
- fresh?.config?.managerState?.token === state.token &&
- !fresh.config.managerState.consumed
- ) {
- await this.save(db, goal.id, {
- ...fresh.config.managerState,
- operationId: operation?.id ?? state.operationId,
- consumed: true,
- });
+ const current = fresh?.config?.managerState;
+ if (current?.token !== state.token || current.consumed) return;
+ const settled: GoalManagerState = {
+ ...current,
+ operationId: operation?.id ?? state.operationId,
+ consumed: true,
+ };
+ const cleared = {
+ failedTurns: undefined,
+ offlineDevice: undefined,
+ offlineTurns: undefined,
+ retryAfter: undefined,
+ };
+ // A committed plan is progress whatever the run's ending; only an errored
+ // turn that committed nothing gates the next dispatch.
+ if (current.submitted || operation?.status !== 'error') {
+ await this.save(db, goal.id, { ...settled, ...cleared });
+ return;
+ }
+ const decision = decideFailedTurn(operation.error, current);
+ if (decision.action === 'pause') {
+ // The person who resumes the Goal gets a fresh retry schedule. Pause in
+ // this same transaction: committing the consumed receipt first would
+ // let a concurrent tick claim and dispatch a replacement turn before
+ // the pause took the row lock.
+ await this.save(db, goal.id, { ...settled, ...cleared });
+ const message = `${decision.reason}. Resume with: lh goal resume ${goal.id}`;
+ if (activeStatuses.has(fresh!.status)) {
+ await new GoalModel(db, this.userId, this.workspaceId).updateStatus(goal.id, 'paused');
+ await this.graph(db).recordGoalStatus(goal.id, fresh!.status, 'paused', message);
+ }
+ return { ...decision, reason: message };
}
+ await this.save(db, goal.id, {
+ ...settled,
+ failedTurns: decision.failedTurns || undefined,
+ offlineDevice:
+ decision.failure.kind === 'device_unavailable'
+ ? readDeviceDispatchRoute(operation.error)
+ : undefined,
+ offlineTurns: decision.offlineTurns || undefined,
+ retryAfter: decision.retryAfter,
+ turns: decision.charged ? current.turns : Math.max(0, current.turns - 1),
+ });
+ return decision;
});
+ if (failed?.action === 'pause')
+ return { goalId: goal.id, outcome: 'no_progress', message: failed.reason };
+ if (failed) {
+ await scheduleGoalAdvance({
+ goalId: goal.id,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ delay: GoalWaitService.arm(failed.retryAfter).delay,
+ });
+ return {
+ goalId: goal.id,
+ outcome: 'waiting_external',
+ message: `Main Agent turn failed without a plan (${failed.failure.kind}); the next turn starts after ${failed.retryAfter}`,
+ };
+ }
return {
goalId: goal.id,
outcome: 'advanced',
@@ -802,6 +964,21 @@ export class GoalManagerService {
if (problem) return null;
return this.pause(goal.id, 'Goal or main Agent turn budget exhausted');
}
+ // The previous turn failed without a plan. Its settlement already queued the
+ // wakeup for this time, so a tick arriving earlier (the sweep, a Task event)
+ // only reports the wait instead of queueing another one. An invited turn
+ // waits too: it would fail the same way, and the problem is still there later.
+ // A device seen back online ends the wait early, as it does for Tasks.
+ if (
+ state?.retryAfter &&
+ Date.parse(state.retryAfter) > Date.now() &&
+ !(await this.offlineDeviceIsBack(state))
+ )
+ return {
+ goalId: goal.id,
+ outcome: 'waiting_external',
+ message: `Main Agent turn deferred until ${state.retryAfter} after a failed turn`,
+ };
const claimed = await this.db.transaction(async (db) => {
const model = new GoalModel(db, this.userId, this.workspaceId);
const fresh = await model.lockById(goal.id);
@@ -871,6 +1048,9 @@ export class GoalManagerService {
: {}),
...(state?.adoptedOperationId && { adoptedOperationId: state.adoptedOperationId }),
...(previousTopicIds.length > 0 && { previousTopicIds }),
+ // Failure streaks span turns; settling a turn that did not error resets them.
+ ...(freshState?.failedTurns && { failedTurns: freshState.failedTurns }),
+ ...(freshState?.offlineTurns && { offlineTurns: freshState.offlineTurns }),
reviewSnapshot: reviews.hash,
topicId,
turns: (state?.turns ?? 0) + 1,
diff --git a/apps/server/src/services/goal/recoveryPolicy.test.ts b/apps/server/src/services/goal/recoveryPolicy.test.ts
index 4e3476714a4..5a7fd768283 100644
--- a/apps/server/src/services/goal/recoveryPolicy.test.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.test.ts
@@ -2,6 +2,7 @@ import type { GoalItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import {
+ classifyRunFailure,
countChargedTaskAttempts,
countConsecutiveDeviceOfflineRuns,
DEFAULT_MANAGER_MAX_TURNS,
@@ -78,3 +79,48 @@ describe('offline run accounting', () => {
expect(resolveFailedRunStatus('Delivery did not pass verification.')).toBe('failed');
});
});
+
+describe('classifyRunFailure', () => {
+ it('reads a usage window reset from the structured error', () => {
+ expect(
+ classifyRunFailure({
+ body: { code: 'rate_limit', rateLimitInfo: { resetsAt: 1_791_232_200 } },
+ category: 'quota',
+ message: "You've hit your session limit",
+ }),
+ ).toEqual({ kind: 'quota_reset', resetsAt: 1_791_232_200_000 });
+ });
+
+ it('ignores a window the provider allowed, which a later unrelated failure can carry', () => {
+ expect(
+ classifyRunFailure({
+ body: {
+ code: 'rate_limit',
+ rateLimitInfo: { resetsAt: 1_791_232_200, status: 'allowed' },
+ },
+ message: 'fetch failed: ECONNRESET',
+ }).kind,
+ ).toBe('transient');
+ });
+
+ it.each([
+ [{ message: 'DEVICE_OFFLINE (HTTP 503)' }, '', 'device_unavailable'],
+ [undefined, 'DEVICE_NOT_FOUND', 'device_unavailable'],
+ [{ category: 'quota', message: 'Insufficient balance' }, '', 'needs_user'],
+ [{ category: 'auth', message: 'Invalid API key' }, '', 'needs_user'],
+ [
+ { body: { code: 'rate_limit' }, category: 'quota', message: 'session limit' },
+ '',
+ 'needs_user',
+ ],
+ [{ message: 'approval required' }, '', 'needs_user'],
+ [{ category: 'capacity', message: 'upstream busy' }, '', 'transient'],
+ [{ message: 'fetch failed: ECONNRESET' }, '', 'transient'],
+ [{ message: 'Too Many Requests (429)' }, '', 'transient'],
+ [{ message: 'DEVICE_GATEWAY_ERROR (HTTP 500)' }, '', 'transient'],
+ [{ message: 'spawn claude ENOENT' }, '', 'unknown'],
+ [undefined, '', 'unknown'],
+ ])('classifies %j / %s as %s', (error, text, kind) => {
+ expect(classifyRunFailure(error, text).kind).toBe(kind);
+ });
+});
diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.ts
index 0d07db07d7c..5b319b63eb2 100644
--- a/apps/server/src/services/goal/recoveryPolicy.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.ts
@@ -163,6 +163,76 @@ export const isDeviceUnavailableFailure = (error?: string | null): boolean =>
export const resolveFailedRunStatus = (error?: string | null): string =>
isDeviceUnavailableFailure(error) ? DEVICE_OFFLINE_RUN_STATUS : 'failed';
+/**
+ * What a failed run's error says about retrying it.
+ *
+ * - `quota_reset`: a usage window rejected the run and reports when it reopens
+ * (`resetsAt`, epoch ms). Retrying earlier fails the same way.
+ * - `device_unavailable`: the run never reached its device; a reconnect fixes it.
+ * - `needs_user`: credentials, permission, spend or a cancellation. Retrying
+ * cannot help until a person acts.
+ * - `transient`: network, gateway 5xx or provider capacity. A later retry can work.
+ * - `unknown`: nothing above matched.
+ *
+ * One classification for Task runs and main Agent turns, so the two lanes stop
+ * disagreeing about the same error. Earlier, a Task waited a day for an offline
+ * device while a planning turn on that device was re-dispatched every few seconds.
+ */
+export type RunFailureKind =
+ 'device_unavailable' | 'needs_user' | 'quota_reset' | 'transient' | 'unknown';
+
+/** A retry after a quota reset waits this much longer, so the window has actually reopened. */
+export const QUOTA_RESET_MARGIN_MS = 60_000;
+
+export interface RunFailure {
+ kind: RunFailureKind;
+ /** Only on `quota_reset`: when the usage window reopens, epoch ms. */
+ resetsAt?: number;
+}
+
+const NEEDS_USER_PATTERN =
+ /auth|credential|api.?key|permission|approv|forbidden|unauthor|usage.?limit|session limit|quota|billing|budget|insufficient|balance|cancel|用户|授权|凭据|额度|余额/i;
+const TRANSIENT_PATTERN =
+ /ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|network error|socket hang up|service unavailable|bad gateway|gateway timeout|\b50[234]\b|\b429\b|too many requests|overloaded|upstream.?busy|concurrency.?limit|DEVICE_GATEWAY_ERROR|DEVICE_GATEWAY_UNREACHABLE|DEVICE_GATEWAY_RATE_LIMITED/i;
+/** `ErrorCategory` values from the model-runtime taxonomy. */
+const NEEDS_USER_CATEGORIES = new Set(['auth', 'config', 'quota']);
+const TRANSIENT_CATEGORIES = new Set(['capacity', 'network']);
+
+/**
+ * Classify a failed run from its operation error and any stored error text.
+ * The structured fields win over text; text is all a Task run that failed at
+ * dispatch leaves behind.
+ */
+export const classifyRunFailure = (error: unknown, text = ''): RunFailure => {
+ const e = (error ?? {}) as {
+ body?: { code?: unknown; rateLimitInfo?: { resetsAt?: unknown; status?: unknown } };
+ category?: unknown;
+ message?: unknown;
+ type?: unknown;
+ };
+ const category = typeof e.category === 'string' ? e.category : undefined;
+ const info = e.body?.rateLimitInfo;
+ const resetsAt = Number(info?.resetsAt) * 1000;
+ // Anthropic stamps rolling-window metadata on calls it allowed too, and a later
+ // unrelated failure can carry it (see `isUserQuotaRateLimit` in the Claude Code
+ // adapter). Only a rejected window, or a legacy record without a status, says
+ // the run was refused until that reset.
+ if (
+ (category === 'quota' || e.body?.code === 'rate_limit') &&
+ (info?.status === undefined || info.status === 'rejected') &&
+ Number.isFinite(resetsAt) &&
+ resetsAt > 0
+ )
+ return { kind: 'quota_reset', resetsAt };
+ const message = `${typeof e.type === 'string' ? e.type : ''} ${typeof e.message === 'string' ? e.message : ''} ${text}`;
+ if (isDeviceUnavailableFailure(message)) return { kind: 'device_unavailable' };
+ if ((category && NEEDS_USER_CATEGORIES.has(category)) || NEEDS_USER_PATTERN.test(message))
+ return { kind: 'needs_user' };
+ if ((category && TRANSIENT_CATEGORIES.has(category)) || TRANSIENT_PATTERN.test(message))
+ return { kind: 'transient' };
+ return { kind: 'unknown' };
+};
+
/** Whether a goal's main Agent has used every turn its policy allows. */
export const managerTurnsSpent = (config: GoalItem['config']): boolean =>
!!config?.manager &&
diff --git a/apps/server/src/services/goal/supervisor/README.md b/apps/server/src/services/goal/supervisor/README.md
index dd079f2041d..0c62c734d69 100644
--- a/apps/server/src/services/goal/supervisor/README.md
+++ b/apps/server/src/services/goal/supervisor/README.md
@@ -9,7 +9,11 @@ independent Topic, incidents, operation links and metrics with
their original behavior.
The first version covers confirmed transport failures of a failed Task's latest
-error operation. It does not automatically resolve an existing human Gate,
+error operation. That includes provider capacity errors such as 429 or an
+upstream overload. It also covers a usage window that has reset: the
+coordinator holds a Task refused by a session limit until the reset its error
+reports (`waitForQuotaReset`), and only then retries it. Before this, the Task
+went straight to a human Gate. It does not automatically resolve an existing human Gate,
recover credentials, increase budgets, replace providers, change acceptance,
repair/deploy the platform or diagnose arbitrary failures. This is a subset of
the proposed general Goal supervisor, not a claim of unattended long-horizon
diff --git a/apps/server/src/services/goal/supervisor/policy.test.ts b/apps/server/src/services/goal/supervisor/policy.test.ts
index 9581a578fe1..5acd46a2dbf 100644
--- a/apps/server/src/services/goal/supervisor/policy.test.ts
+++ b/apps/server/src/services/goal/supervisor/policy.test.ts
@@ -37,6 +37,28 @@ describe('supervisor recovery authority', () => {
expect(recoveryEligibility(graph, { ...task, error }, operation).eligible).toBe(false);
});
+ it('lets a Task retry once its usage window has reset', () => {
+ expect(
+ recoveryEligibility(graph, task, {
+ ...operation,
+ error: {
+ body: { code: 'rate_limit', rateLimitInfo: { resetsAt: 1_791_232_200 } },
+ category: 'quota',
+ message: "You've hit your session limit",
+ },
+ }).eligible,
+ ).toBe(true);
+ });
+
+ it('treats provider capacity as a transient failure', () => {
+ expect(
+ recoveryEligibility(graph, task, {
+ ...operation,
+ error: { category: 'capacity', message: 'upstream busy' },
+ }).eligible,
+ ).toBe(true);
+ });
+
it.each(['paused', 'canceled', 'achieved', 'review'])('respects Goal %s', (status) => {
expect(
recoveryEligibility(
diff --git a/apps/server/src/services/goal/supervisor/policy.ts b/apps/server/src/services/goal/supervisor/policy.ts
index e114efcb95f..65987d8178c 100644
--- a/apps/server/src/services/goal/supervisor/policy.ts
+++ b/apps/server/src/services/goal/supervisor/policy.ts
@@ -9,7 +9,11 @@ import { isAgentOperationInFlight } from '@lobechat/types';
import type { AgentOperationItem } from '@/database/schemas/agentOperations';
import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';
-import { countChargedTaskAttempts, resolveTaskAttemptBudget } from '../recoveryPolicy';
+import {
+ classifyRunFailure,
+ countChargedTaskAttempts,
+ resolveTaskAttemptBudget,
+} from '../recoveryPolicy';
export const SUPERVISOR_DIAGNOSIS_TIMEOUT_MS = 10 * 60 * 1000;
export const MAX_SUPERVISION_INCIDENTS = 100;
@@ -126,11 +130,13 @@ export const recoveryEligibility = (
return { eligible: false, reason: 'Task attempt budget exhausted' };
}
const error = `${operation?.error?.type ?? ''} ${operation?.error?.message ?? ''} ${task.error ?? ''}`;
- if (
- /auth|credential|api.?key|permission|approv|forbidden|unauthor|usage.?limit|quota|billing|budget|cancel|用户|授权|凭据|额度/i.test(
- error,
- )
- ) {
+ const failure = classifyRunFailure(operation?.error, task.error ?? '');
+ // A usage window that reports its reset is not a person's call: the coordinator
+ // holds the Task until the reset (`waitForQuotaReset`) and only then lets it here.
+ if (failure.kind === 'quota_reset') {
+ return { eligible: true, reason: 'Usage window has reset; retry within existing authority' };
+ }
+ if (failure.kind === 'needs_user') {
return {
eligible: false,
reason: 'Credentials, permission, cancellation or spending requires user action',
@@ -141,12 +147,7 @@ export const recoveryEligibility = (
// an actor can author — a Task marked failed through the API, a settled run someone
// reopened — arrives looking exactly like a dropped dispatch. Recognising the
// failures instead keeps an authored decision with the person who made it.
- if (
- !isRetryableDispatchFailure(error) &&
- !/ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|network error|socket hang up|service unavailable|bad gateway|gateway timeout|\b50[234]\b/i.test(
- error,
- )
- ) {
+ if (!isRetryableDispatchFailure(error) && failure.kind !== 'transient') {
return {
eligible: false,
reason: 'Failure is outside the recognised transport recovery policy',
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index f47a3b4f377..2c55f319afe 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -142,6 +142,36 @@ export class GoalModel {
return row as GoalItem | undefined;
};
+ /**
+ * Claim the queued wake for a Task waiting on a usage-window reset, so that
+ * repeated ticks before the reset (the sweep, Task events, manual advances)
+ * queue one callback instead of one each. Succeeds only when no wake is armed,
+ * the armed one already fired, or this one fires earlier; the caller queues the
+ * callback only then. Patches `config.quotaRetryWakeAt` alone, like
+ * `updatePauseReason`, in one conditional statement so concurrent ticks cannot
+ * both claim it.
+ */
+ armQuotaRetryWake = async (id: string, at: string): Promise<boolean> => {
+ const armed = sql`(${goals.config} #>> '{quotaRetryWakeAt}')::timestamptz`;
+ const rows = await this.db
+ .update(goals)
+ .set({
+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{quotaRetryWakeAt}', ${JSON.stringify(at)}::jsonb)`,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(goals.id, id),
+ this.ownership(),
+ sql`(NOT (COALESCE(${goals.config}, '{}'::jsonb) ? 'quotaRetryWakeAt')
+ OR ${armed} <= NOW()
+ OR ${armed} > ${at}::timestamptz)`,
+ ),
+ )
+ .returning({ id: goals.id });
+ return rows.length > 0;
+ };
+
/**
* Patch only `config.understanding`, for the same reason as
* `updatePauseReason`: decomposition writes it while the user may be editing
@@ -191,13 +221,14 @@ export class GoalModel {
// policy edits cannot replace the concurrently written incident ledger.
...(value.config !== undefined
? {
- config: sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol' - 'supervisorState' - 'managerState' - 'understanding')
+ config: sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol' - 'supervisorState' - 'managerState' - 'understanding' - 'quotaRetryWakeAt')
|| jsonb_strip_nulls(jsonb_build_object(
'planningCheckpoint', ${goals.config}->'planningCheckpoint',
'planningProtocol', ${goals.config}->'planningProtocol',
'supervisorState', ${goals.config}->'supervisorState',
'managerState', ${goals.config}->'managerState',
- 'understanding', ${goals.config}->'understanding'
+ 'understanding', ${goals.config}->'understanding',
+ 'quotaRetryWakeAt', ${goals.config}->'quotaRetryWakeAt'
))`,
}
: {}),
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 02cfe7c076d..140186db95a 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -271,6 +271,23 @@ export interface GoalManagerState {
* owner can edit.
*/
dispatchNeverStarted?: boolean;
+ /**
+ * Consecutive turns that ended in an error without committing a plan. Reset by
+ * a turn that commits a plan or ends without an error. Reaching the limit
+ * pauses the Goal on the last error instead of re-dispatching an Agent that
+ * keeps failing the same way.
+ */
+ failedTurns?: number;
+ /**
+ * The device the last turn could not reach, when it failed as unavailable.
+ * Seeing it online again ends the `retryAfter` wait early.
+ */
+ offlineDevice?: { deviceId: string; userId: string; workspaceId?: string };
+ /**
+ * Consecutive turns that never reached their device. They are not charged to
+ * the turn budget and follow the Task offline retry schedule instead.
+ */
+ offlineTurns?: number;
operationId?: string;
/**
* Management conversations this Goal planned in before a handoff moved it to
@@ -292,6 +309,13 @@ export interface GoalManagerState {
problemTaskId?: string;
readyForAcceptance?: boolean;
replanReason?: string;
+ /**
+ * Earliest time the next turn may be dispatched after one failed without a
+ * plan: the provider's quota reset when the error carries one, otherwise an
+ * exponential backoff. Without it a failing Agent was re-dispatched on every
+ * tick and spent the whole turn budget in minutes.
+ */
+ retryAfter?: string;
reviewSnapshot?: string;
snapshot: string;
startedAt: string;
@@ -358,6 +382,11 @@ export interface GoalConfig {
planningCheckpoint?: { expiresAt: string; token: string };
/** Retained after release to distinguish lease-aware retries from legacy planners. */
planningProtocol?: 'lease-v1';
+ /**
+ * Coordinator-owned: when the queued wake for a Task waiting on a usage-window
+ * reset fires. One wake per Goal, so ticks before the reset do not queue more.
+ */
+ quotaRetryWakeAt?: string;
recovery?: GoalRecoveryPolicy;
/** Coordinator-owned receipt of the latest wrap-up report dispatch. */
report?: GoalReportDispatch;