Skip to content

fix(agent-core-v2): run external Stop hooks after turn completion - #4956

Merged
sailist merged 3 commits into
bug-370-11-15-release-fixesfrom
bug-373-11-15-external-stop-hook-not-triggered
Nov 15, 2026
Merged

sailist merged 3 commits into
bug-370-11-15-release-fixesfrom
bug-373-11-15-external-stop-hook-not-triggered

Conversation

@sailist

@sailist sailist commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

External Stop hooks were skipped when an agent finished naturally, so configured scripts did not run and their block/continuation behavior was unavailable. This PR executes Stop after a completed turn and starts a continuation when the hook returns a block reason.

The requirement and reproduction are described directly here; there is no separate issue link.

Bug Reproduction Steps

  1. Configure a Stop hook that returns a block reason on its first invocation and allows subsequent invocations.
  2. Submit a prompt that reaches a natural final response with no queued work.
  3. On the previous code, the hook runner receives no Stop invocation (stopInputs=[]) and only one model request occurs, so no continuation is produced.
  4. With this change, Stop runs once after the completed turn, the block reason produces one continuation turn, and the continuation does not recursively reenter Stop.

Root Cause

The loop runtime refactor in #4630 expanded hasPendingRequests to include the active turn. Stop was evaluated during step.stopping, while that turn was still active, so the guard was always true and the external runner was never called.

The same refactor made continuations independent turns, while the continuation-used flag was still reset on every TurnEnded, breaking reentry protection once the trigger issue was removed.

This is a fundamental fix in the external-hook adapter for the explicitly selected post-turn contract. The loop's public busy/settled semantics and the durable TurnEnded schema remain unchanged.

Code Changes

onDidFinishStep
  -> cache the final step's serializable facts

TurnEnded(completed), with no pending work
  -> execute Stop serially
       allow -> no continuation
       block -> notify a stop-hook continuation turn
                  -> suppress recursive Stop on that continuation
  • Cache turnId, step, firstStepOfTurn, finishReason, and usage for the final step instead of retaining the full AfterStepContext or its signal.
  • Include those fields in the Stop payload while preserving stopHookActive and the existing session facts.
  • Preserve queued-work suppression, including a notify turn that has already started by the time TurnEnded is projected.
  • Mark stop-hook continuations by origin so ordinary turns can use Stop again independently. Abort pending hooks on agent disposal and report asynchronous failures through the existing hook warning.
  • Rework the existing continuation test around the real loop, including filtered responses, a two-step turn, final-step payloads, one continuation, reentry protection, ordinary-turn rearming, and queued input. Update the dynamic-loading and cwd tests for the post-turn lifecycle.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Natural Stop timing Evaluated during step.stopping and skipped because the active turn counted as pending Runs after completed TurnEnded when no work is pending External Stop hook scripts and clients observing turn completion No pre-end compatibility mode; post-turn timing is the intended contract
Stop payload Session facts and stopHookActive Also includes turn_id, step, first_step_of_turn, finish_reason, and final-step usage External Stop hook scripts Additive fields; existing fields and their meanings are unchanged
Block continuation Stop did not run, and the old reset boundary could not protect reentry A block reason opens one notify continuation; recursive Stop is suppressed on that continuation and ordinary turns rearm independently Scripts using block reasons and the stop_hook origin Reason content and origin shape are unchanged
Failed or cancelled turns StopFailure and Interrupt Unchanged Scripts subscribed to failure/cancellation events N/A
Pending work Intended to suppress Stop Suppresses Stop for queued work and an already-started next turn Scripts that expect the next input to run first N/A

Affected modules are limited to the agent external-hook adapter, its integration tests, and the CLI changeset.

Verification:

  • corepack pnpm vitest run packages/agent-core-v2/test/features/externalHooks/integration.test.ts — 26/26 passed.
  • corepack pnpm --filter @moonshot-ai/agent-core-v2 typecheck — passed.
  • Focused oxlint — 0 errors and 5 pre-existing warnings in the touched implementation file.
  • The dynamic-loading test also launches a real Node hook through ExternalHooksRunnerService and verifies exit-code-2 blocking and continuation.
  • npm run build in docs/ — passed after updating both Stop hook references.
  • The initial implementation commit's full GitHub Actions checks passed; the documentation-only follow-up is covered by the docs build and subsequent PR checks.

Checklist

  • I have read the CONTRIBUTING document.
  • The requirement and reproduction are described directly in this PR; there is no separate issue link.
  • Updated regression tests prove the fix.
  • The behavior-change table above is complete; the post-turn timing and lack of a pre-end compatibility mode are explicitly documented for reviewer approval.
  • Added a patch changeset for @moonshot-ai/kimi-code.
  • Updated both English and Chinese Stop hook event references for post-turn timing and final-step payload fields.

@changeset-bot

changeset-bot Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 85d6a84

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

This PR includes changesets to release 1 package
Name Type
@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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-11-15T04:29:35.840043Z 94aca1f PR opened
ℹ️ 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@85d6a84
npx https://pkg.pr.new/@moonshot-ai/kimi-code@85d6a84

commit: 85d6a84

@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: 94aca1f665

ℹ️ 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 +431 to +432
this.stopHookQueue = this.stopHookQueue
.then(() => this.runStop(facts, stopHookContinuation))

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 Await Stop hooks before allowing print-mode shutdown

When a kimi -p user configures a Stop hook that does not finish immediately, this private promise is invisible to turn.result, IAgentLoopService.settled(), and quiescence. runNativeTurn therefore returns after the original turn and cleanup can acquire quiescence and dispose the agent while runStop is still executing, aborting the hook or silently discarding its block continuation; the new test's extra timer after loop.settled() demonstrates this lifecycle gap. Make the queued Stop work participate in loop/session settlement before advertising the turn as fully finished.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +477 to +478
this.stopHookContinuationUsed = true;
this.loop.notify({

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 Recheck pending work after the Stop hook returns

If a Stop script is slow and the user submits another prompt after the completed TurnEnded, the pending-work check at scheduling time has already passed. When the old hook later returns a block reason, this unconditional notification inserts that stale continuation into or after the newer turn, despite the stated contract that pending work suppresses Stop. Recheck the loop state after triggerBlock resolves, or keep the loop non-idle for the hook's full lifetime, before enqueueing the continuation.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +431 to +432
this.stopHookQueue = this.stopHookQueue
.then(() => this.runStop(facts, stopHookContinuation))

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 Update the documented Stop-hook timing

This moves Stop execution to after a completed TurnEnded, but both docs/en/customization/hooks.md:117 and docs/zh/customization/hooks.md:117 still tell hook authors that Stop runs when the model is about to end the turn and can stop the current operation. That timing distinction is observable to external scripts, especially now that the current turn is already complete and blocking starts a separate continuation, so update both event references rather than shipping a contradictory public contract.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 1a035ec into bug-370-11-15-release-fixes Nov 15, 2026
26 of 27 checks passed
@sailist
sailist deleted the bug-373-11-15-external-stop-hook-not-triggered branch November 15, 2026 04:53
sailist added a commit that referenced this pull request Nov 16, 2026
) (#4995)

* fix(agent-core-v2): run external Stop hooks after turn completion

* chore: add changeset for external Stop hooks

* docs: clarify post-turn Stop hook timing
wbxl2000 pushed a commit that referenced this pull request Nov 17, 2026
* fix: resume sessions with removed default models (#4982)

* fix(node-sdk): resume sessions with missing default model

* fix(cli): check auth for the resumed session model

* chore: add changeset for unavailable model recovery

* fix(agent-core-v2): stop rebuilding mismatched session indexes (#4980)

* fix(agent-core-v2): reject repeated model responses (#4977)

* fix(agent-core-v2): reject repeated model responses

* chore: add changeset for repeated model responses

---------

Co-authored-by: 7Sageer <[email protected]>

* fix(agent-core-v2): inline deferred tools without dynamic loading (#4971)

* fix(agent-core-v2): record restored task notifications without model requests (#4949) (#4989)

* fix(agent-core-v2): record restored task notifications without model requests

- queue restored task notifications as prompt-only turns after loop initialization
- preserve interrupted and queued turns during resume and fork
- complete reconciliation before initialization and reset return to keep Wire reads ordered
- run loop and container cleanup when reconciliation fails
- surface restored notification persistence failures

* chore: add changeset for restored task notifications

* fix(agent-core-v2): restore overflow recovery after LLM retries (#4950) (#4990)

* fix(agent-core-v2): restore step state after LLM retries

* test(agent-core-v2): scope retry event to overflow regression

* fix(config): allow sessions with invalid user config (#4951) (#4991)

* fix(agent-core-v2): tolerate config read failures for permission rules

* chore: add changeset for permission config recovery

* docs: document permission config recovery

* docs: qualify permission config recovery scope

* fix(config): surface read error diagnostics

* fix(config): allow sessions with invalid user config

* fix(config): preserve valid values and replay diagnostics

* fix(config): remove startup diagnostic replay

* fix(agent-core-v2): ignore non-user prompts during Tower wake (#4952) (#4992)

* fix(agent-core-v2): ignore non-user prompts during Tower wake

* chore: add Tower notification fix changeset

* fix(agent-core-v2): preserve slash prompts during Tower wake

* fix(agent-core-v2): route foreground shell events by origin (#4954) (#4994)

* fix(agent-core-v2): route foreground shell events by origin

* test(agent-core-v2): expect tool event origins in snapshots

* fix(klient): accept tool events from pre-origin hosts

* fix(agent-core-v2): run external Stop hooks after turn completion (#4956) (#4995)

* fix(agent-core-v2): run external Stop hooks after turn completion

* chore: add changeset for external Stop hooks

* docs: clarify post-turn Stop hook timing

* fix(agent-core-v2): wait for subagent quiescence (#4953) (#4993)

* fix(agent-core-v2): reject incomplete model streams (#5006)

* fix(agent-core-v2): preserve choice-level OpenAI token usage (#5017)

* fix(capability): confirm stopping WebBridge before Windows updates (#4999)

* fix(capability): confirm stopping WebBridge before Windows updates

* fix(capability): harden WebBridge update recovery

* fix(capability): restore WebBridge after startup failure

* fix(capability): wait for WebBridge process exit

* fix(capability): handle WebBridge confirmation edge cases

---------

Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>

* chore: sync release 2.6.3 back to main

* chore: finish release 2.6.3 backsync

* chore: sync node-sdk lockfile importer

* fix(sdk): preserve main core type dependencies

* fix: complete release 2.6.3 backsync

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: 7Sageer <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
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.

1 participant