Skip to content

fix(agent-core-v2): back off goal continuations that make no progress - #2499

Open
xy200303 wants to merge 1 commit into
MoonshotAI:mainfrom
xy200303:fix/goal-idle-continuation-loop
Open

xy200303 wants to merge 1 commit into
MoonshotAI:mainfrom
xy200303:fix/goal-idle-continuation-loop

Conversation

@xy200303

@xy200303 xy200303 commented Aug 1, 2026 •

Copy link
Copy Markdown

Related Issue

Resolve #1977

Problem

See linked issue. In short: while a goal waits on an external condition it cannot accelerate, every continuation turn re-injects the goal reminder plus the full objective and produces a no-op reply. One real session reached 160+ continuation turns in ~3 hours.

What changed

This PR was originally written against packages/agent-core. That engine has since been replaced by packages/agent-core-v2, and the two files the original revision touched (src/agent/turn/index.ts, test/harness/goal-session.test.ts) no longer exist, so a merge was not possible. The behaviour is re-implemented against the v2 goal service:

  • Record per-turn tool progress from the toolCompleted hook, and count goal turns that end in a row without executing a tool.
  • From the second such turn onward, delay the next continuation instead of launching it immediately, on the same ladder as before: 60s, then 5min, then 15min, capped by the goal's remaining wall-clock budget (computeBudgetReport(...).remainingWallClockMs).
  • Reset the streak when a turn runs a tool, and also on goal creation and resume.
  • Wake the pending delay immediately when a non-continuation turn starts (steered input), restarting the ladder.
  • Drop the continuation when the goal is no longer active once the delay elapses.

The delay only applies when the backoff is actually active: with no delay the continuation is still requested synchronously, so turns that make progress keep their existing timing.

Tests

Added to packages/agent-core-v2/test/features/goal/goal.test.ts:

  • the 60s → 5min → 15min ladder after consecutive no-progress turns
  • a turn that runs a tool resets the streak and continues without waiting
  • steered input during a backoff wakes the continuation

One existing test (runs a ten-turn goal chain with WaitFor in a continuation turn) drives a chain with eight consecutive text-only turns, so it now advances the backoff with fake timers; its assertions are unchanged.

Verification:

  • vitest run test/features/goal — 172 passed (169 before this change, +3 new)
  • tsc -p tsconfig.json --noEmit — clean
  • node scripts/check-no-comments.mjs — clean
  • Full agent-core-v2 suite compared against a clean baseline: the deterministic failure set is identical (the remaining failures reproduce without this change, in this environment -- Windows path separators, POSIX file modes, sandbox watch EPERM, network stalls)

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue, or explained the problem above.
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 740ae06

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@xy200303
xy200303 force-pushed the fix/goal-idle-continuation-loop branch from 24de5f7 to e5411d8 Compare September 15, 2026 10:30
@xy200303 xy200303 changed the title fix(agent-core): back off idle goal continuations fix(agent-core-v2): back off goal continuations that make no progress Sep 15, 2026
@xy200303

Copy link
Copy Markdown
Author

Ported this to agent-core-v2 and force-pushed, so the PR is mergeable again instead of conflicting.

Why it had to be rewritten

The branch targeted packages/agent-core:

  • packages/agent-core/src/agent/turn/index.ts and packages/agent-core/test/harness/goal-session.test.ts no longer exist on main — the engine was replaced by packages/agent-core-v2, and the goal logic now lives in packages/agent-core-v2/src/features/goal/goalService.ts (class TurnFlow is gone).
  • The gap the PR describes is still there: v2's handleTurnEnded unconditionally calls launchContinuationTurn, so a goal whose turns produce text and no tool call keeps re-invoking the model.

How the v2 version works

  • toolCompleted records which turns executed a tool; clearTurnTracking reports that back for the turn that just ended.
  • handleTurnEnded increments consecutiveIdleTurns for a turn with no tool progress, resets it otherwise, and only starts waiting from the second consecutive one.
  • The wait reuses the same ladder (60s / 5min / 15min), capped by the goal's remaining wall-clock budget, and re-checks that the goal is still active before continuing.
  • A non-continuation turn starting during the wait wakes it immediately and restarts the ladder, so a user typing something never sits behind a 15-minute timer.
  • createGoal and resumeGoal reset the counter.

Turns that make progress keep the old timing exactly: with no delay the continuation is still requested synchronously.

Verification

  • vitest run test/features/goal → 172 passed (169 on main, plus 3 new)
  • tsc --noEmit, scripts/check-no-comments.mjs → clean
  • Full agent-core-v2 suite run against a clean baseline of the same checkout: the deterministic failure set is byte-identical, i.e. none of those failures come from this change. They are environment issues on this machine (Windows path separators, POSIX 0700 mode assertions, sandbox watch EPERM, a stalled download in host.test.ts).

One existing test needed updating rather than the implementation: runs a ten-turn goal chain with WaitFor in a continuation turn drives eight consecutive text-only turns, which is exactly the pattern that now backs off, so it advances time with fake timers. Its assertions are unchanged.

agent-core-v2 is a comment-free zone, so the diff contains no comments.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e5411d8932

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +712 to +713
const current = context.runtime.getState().goal;
return current !== null && current.status === 'active' && current.goalId === goalId;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Invalidate delayed continuations across pause/resume

If an idle continuation is waiting and the caller pauses then resumes the same goal before the delay expires, this check sees the original goal ID active again and launches the stale continuation. This bypasses the default resumeGoal() behavior that intentionally does not continue a paused goal, and it can also enqueue a duplicate request when continueIfPaused already launched one. The pending wait should be cancelled or generation-invalidated whenever the goal leaves the active lifecycle.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 740ae06: delayed idle continuations are now cancelled and generation-invalidated whenever the goal leaves or re-enters the active lifecycle (pause, block, completion, cancellation, replay normalization, or disposal), with regression tests covering pause/block + default resume and continueIfPaused.

A goal keeps re-invoking the model for as long as it stays active, so a model
that answers every continuation turn with text and no tool call produced an
unbounded chain of no-op turns, each one spending tokens and context.

Track per-turn tool progress from finished step tool calls and count how many
goal turns in a row ended without executing a tool. Starting from the second
such turn, delay the next continuation through the goal deadline scheduler
instead of launching it immediately, using 60s, then 5min, then 15min, capped
by the goal's remaining wall-clock budget.

A turn that runs any tool resets the counter, and so do goal creation and
resume, so ordinary work never waits. User input during a backoff wakes the
continuation immediately and restarts the ladder, and leaving the active
lifecycle cancels and invalidates any pending delayed continuation across
pause, block, completion, cancellation, and resume.

Requesting the continuation without a delay still happens synchronously, so the
existing continuation timing is unchanged for turns that make progress.
@xy200303
xy200303 force-pushed the fix/goal-idle-continuation-loop branch from e5411d8 to 740ae06 Compare December 1, 2026 10:46
@xy200303

xy200303 commented Dec 1, 2026

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-01T12:29:33.669088Z 740ae06 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 740ae06f2b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +693 to +694
idleDelayMs > 0 &&
!(await waitForGoalContinuation(context, lifecycleGoalId, generation, state, idleDelayMs))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retain sessions while continuation backoff is pending

In kap-server deployments that set KIMI_CODE_SESSION_IDLE_RECLAIM_MS below a backoff step (for example, 10 minutes), this await leaves the loop idle for up to 15 minutes. I checked packages/kap-server/src/services/sessionIdleReaper.ts:9-20, which accepts such a timeout, and SessionManagerService.retained() at packages/agent-core-v2/src/app/sessionManager/sessionManagerService.ts:362-369, which only retains busy, interactive, or cron sessions; the reaper therefore closes the session before the callback, and createGoalEffectHandlers().closing pauses the active goal and cancels this wait. Treat a pending continuation delay as retained session activity so this existing environment setting does not terminate autonomous goals.

AGENTS.md reference: AGENTS.md:L194-L196

Useful? React with 👍 / 👎.

Comment on lines +117 to +118
const GOAL_IDLE_TURNS_BEFORE_BACKOFF = 2;
const GOAL_IDLE_CONTINUATION_DELAYS_MS = [60_000, 5 * 60_000, 15 * 60_000] as const;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve an opt-out for immediate continuations

These hard-coded defaults unconditionally replace the previous immediate continuation after two tool-free turns with 1-, 5-, and 15-minute waits. A repo-wide search for the new idle/backoff identifiers found no config, environment variable, or flag outside this implementation and its tests, so existing CLI, Desktop, KAP, ACP, and SDK users cannot retain the old timing; the changesets also describe only the new backoff rather than the immediate behavior being lost. Add an escape hatch and a regression test for it, or record the explicit maintainer sign-off required for removing this behavior.

AGENTS.md reference: AGENTS.md:L198-L200

Useful? React with 👍 / 👎.

@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add the desktop product changeset

This engine behavior also reaches Desktop goal workflows: apps/desktop/package.json:47 depends on agent-core-v2 and packages/app-client/src/client/useKimiWebClient.ts:3083 exposes goal creation/control, but this product changeset lists only @moonshot-ai/kimi-code. Desktop builds will therefore receive the changed continuation scheduling without a kimi-code-app release entry; add the corresponding patch entry for that affected product.

AGENTS.md reference: AGENTS.md:L172-L174

Useful? React with 👍 / 👎.

}

function prepareForGoalCreation(context: GoalOperationContext, replace: boolean): void {
context.effects.consecutiveIdleTurns = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset the idle streak only after creation succeeds

When an active goal already exists and a direct caller invokes createGoal without replace (as applySessionAgentConfig can at packages/kap-server/src/routes/sessionAgentConfig.ts:141-145), this assignment runs before GOAL_ALREADY_EXISTS is thrown. A currently scheduled delay remains alive but its counter becomes zero, so after it fires subsequent no-tool turns run immediately and the rejected request has mutated the old goal's backoff state; move the reset after the existence check or accepted replacement.

Useful? React with 👍 / 👎.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Goal mode: no-op continuation turns fire indefinitely while waiting on external conditions, burning tokens and context

1 participant