Skip to content

refactor(core): unify llm event stream and harden behavior tests - #5130

Merged
sailist merged 1 commit into
mainfrom
refact-393-11-18-llm-event-hardening
Nov 19, 2026
Merged

sailist merged 1 commit into
mainfrom
refact-393-11-18-llm-event-hardening

Conversation

@sailist

@sailist sailist commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

LLM consumers previously had to reconcile run-level lifecycle events, per-attempt control events, and streaming data events with different ownership and ordering rules. This PR unifies that public event stream and strengthens the behavioral coverage around it.

This is deliberately split from the deferred-tool work: deferred-tool legalization and ToolSelect disclosure behavior are not included in this PR.

Bug Reproduction Steps

N/A — this is a lifecycle refactor and test-hardening change, not a bug-fix PR.

Root Cause

LlmRunEvent mixed run boundaries, attempt boundaries, and incremental response data. generate() also emitted internal attempt.* events while settle() produced public llm.* events, making retry resets and request ownership difficult for Loop, agent-core-v2, and klient consumers to interpret consistently.

This is a fundamental lifecycle refactor rather than a compatibility-layer workaround.

Code Changes

The resulting public sequence is:

llm.started
  -> llm.notice / llm.requested / llm.delta.*
  -> [llm.retry -> llm.requested -> llm.delta.*] (0..N)
  -> llm.ended
  • Establish one llm.started and one final llm.ended per generation, emit llm.requested for each actual attempt, and move incremental response facts to llm.delta.*.
  • Return generation failures directly, use a decoder callback for tool-call boundaries, and keep message accumulation and outcome construction in settle().
  • Represent both backoff and recovery with llm.retry, allowing consumers to clear the current attempt before the next request.
  • Migrate core Loop, agent-core-v2 journal/turn projection/request observation, and klient to the unified vocabulary.
  • Replace fake transport handling with aimock-backed provider requests, add lifecycle/delta coverage, restore applicable historical LLM behavior tests, and update affected snapshots and the Nix dependency hash.

Start with packages/core/src/llm/response.ts, generate.ts, policy/policy.ts, and policy/settle.ts, then follow the consumers in packages/core/src/loop/ and packages/agent-core-v2/src/agent/loop/.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Run boundaries llm.started waited for initial resolution; run and attempt events were interleaved Every generation has one run-entry llm.started and one final llm.ended Loop, v2 turn projection, klient, event observers Migrate consumers to the new run boundaries
Attempt request events llm.sent and internal attempt.sending llm.requested once per actual attempt, using the legacy summary without full messages/tools/native bodies Request observation, debugging tools, event consumers Use llm.requested; no dual emission
Incremental response events llm.streaming.* and llm.timing llm.delta.* for parts, metadata, usage, finish, tool-call end, and timing Streaming UI, Loop, v2 journal, klient Use the new event names
Retry events llm.retrying, with separate internal attempt control llm.retry for both backoff and recovery, followed by a fresh llm.requested Retry/reset handling in Loop and v2 Use llm.retry; old llm.retrying is not emitted
Generation and tool-call failures Internal attempt.failed and attempt.tool_call_end Failures return directly; tool-call boundaries use a decoder callback and normalized public delta Core request execution and settlement Migrate to the direct return/callback contracts
Deferred tools and ToolSelect Existing conversion and disclosure behavior Unchanged in this PR Deferred MCP tools, ToolSelect, dynamic model capability handling No behavior migration in this PR
Non-streaming responses Complete responses replayed through the shared decoder Same behavior, now covered by the unified event assertions Direct protocol and klient consumers No migration beyond the event vocabulary

The removed event names are not dual-emitted. Event-order snapshots now place run-start-derived events earlier, matching the new lifecycle contract.

Validation

  • corepack pnpm vitest run --reporter=agent packages/core: 30 files, 288/288 passed.
  • Agent-core-v2 and related consumers: 987/990 passed; only the three previously recorded subagent 30-second timeout cases reproduced.
  • @moonshot-ai/klient test: 144 passed, 11 skipped (live-server tests skipped without credentials).
  • Typecheck passed for packages/core, packages/agent-core-v2, and packages/klient.
  • Standard pnpm lint passed, including comment, oxlint, import-boundary, guard, ratchet, and instruction checks.

Checklist

  • I have read the CONTRIBUTING document.
  • The requirement and scope are described above; no external issue is linked.
  • I have added tests that prove the lifecycle refactor and affected consumers work.
  • The behavior-change table above is complete; no changeset is included for this split refactor PR, consistent with the original task's delivery decision.
  • Changeset handling is explicitly stated above.
  • English and Chinese LLM/event documentation is updated; no additional product documentation is needed for the deferred-tool behavior because it is excluded.

- unify run boundaries, request summaries, delta events, retries, and outcomes
- migrate Loop, agent-core-v2, and klient consumers to the unified event vocabulary
- add aimock-backed transport coverage and restore historical LLM behavior tests
- update the Nix dependency hash and affected snapshots
@changeset-bot

changeset-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5361716

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-19T12:15:33.653682Z 5361716 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 19, 2026

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

commit: 5361716

@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: 53617164a4

ℹ️ 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 +164 to +168
export type LlmDeltaEvent =
| { readonly type: 'llm.delta.response_header'; readonly headers: Record<string, string> }
| { readonly type: 'llm.delta.request_id'; readonly requestId: string }
| ({ readonly type: 'llm.delta.timing' } & LlmTiming)
| { readonly type: 'llm.delta.part'; readonly part: StreamedMessagePart; readonly block?: number }

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 changesets for the renamed public event contract

This commit intentionally replaces the existing llm.streaming.*, llm.sent, and llm.retrying contract without dual emission, but it adds no changeset. When these library changes ship, event consumers will be forced to migrate without a package changelog or version signal; add technical changesets for both @moonshot-ai/core and @moonshot-ai/agent-core-v2, following the required approval workflow if the breaking change warrants a major bump.

AGENTS.md reference: AGENTS.md:L168-L170

Useful? React with 👍 / 👎.

Comment on lines +522 to +523
describe('Google error decoding', () => {
it('as an API consumer, I want stream business 503 errors to remain retryable without an HTTP status', () => {

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 Restore the stream-iteration abort guard

When the @google/genai async response iterator itself throws an AbortError without the caller signal already being aborted, the parent test suite asserted that runGenerate produced exactly one aborted llm.ended outcome. This rewrite removes the only test of that path while changing the generate/settle abort plumbing; the replacement lifecycle test aborts the caller signal during an OpenAI stream and therefore cannot catch iterator failures becoming failed or retried outcomes. Restore the Google iterator-failure assertion using the new event names.

AGENTS.md reference: AGENTS.md:L100-L101

Useful? React with 👍 / 👎.

Comment on lines +1 to +2
// Historical coverage: PR #101 (stream timing), PR #1448 (request trace), PR #3624 (retry lifecycle), PR #4820 (DI-free LLM core).
import { describe, expect, it } from 'vitest';

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 Split the oversized lifecycle and test refactor

Excluding the lockfile, this commit changes 3,553 lines and combines the lifecycle contract rewrite with a broad test-suite reorganization. That exceeds the repository's 2,000-line review limit, and the description only says deferred-tool work was split out rather than explaining why the remaining lifecycle, fixture, and test changes cannot be separated. Split the change into reviewable commits/PRs, or document why this particular combination is inseparable as required.

AGENTS.md reference: AGENTS.md:L107-L108

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 7895ce4 into main Nov 19, 2026
17 checks passed
@sailist
sailist deleted the refact-393-11-18-llm-event-hardening branch November 19, 2026 12:19
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Port upstream 7895ce4. The core LLM
event vocabulary becomes llm.started / requested / queued / notice /
delta.* / retry / ended: LlmStreamEvent splits into LlmDeltaEvent and
LlmNoticeEvent, llm.streaming.headers becomes llm.delta.response_header
and llm.timing becomes llm.delta.timing, llm.sent is replaced by the
per-attempt llm.requested summary, LlmRetrying becomes LlmRetry, and
generate() returns an LlmGenerateFailure instead of emitting attempt.*
events, with tool-call boundaries delivered through onToolCallEnd.
runLlmRequest emits llm.started once at run entry (before resolvers) and
one llm.requested per attempt; resolver notices are no longer buffered.
agent-core-v2 renames its journal, turn projection, request observation
and loop subscription cases, and resets a step's streamed output before
the recovery early return, not only for backoff retries.

Fork adaptations. The fork's agent-core-v2 loop still drives the
src/human/llm stack, so AgentLoopService.coreRequester synthesizes the
unified events: a new AgentLLMRequestOverrides.onRequest callback hands
the recorded LlmRequestPayload to the adapter, which emits llm.started
once per run from the first attempt's summary and one llm.requested per
actual send (payload minus agentId, attempt from the loop counter). That
summary only exists after ToolSelect resolution, so the journal's
step.begin record keeps its place after tool_select.initialized instead
of moving ahead of it as upstream's core-side emission does. Fork-only
behavior is preserved: the invalid_tool_arguments retry reason and its
zero delay, tool-argument validation against the visible tool view, the
tool-argument correction message, and the invalid tool_call_end
suppression in settle. packages/core/test/llm/settle.test.ts is kept
(upstream deleted it) because it carries that fork coverage. The klient
example and conformance helper reference no core event names in this
fork and needed no change; the aimock transport harness, the pnpm
lockfile and the flake.nix hash do not apply. The oxlint ratchet entry
for settle.ts is dropped because the file now reports zero findings.

Verified: core test/llm 199 pass, packages/core typecheck clean;
agent-core-v2 typecheck clean with @moonshot-ai/core mapped to this
worktree's package (the shared node_modules junction otherwise resolves
the main checkout); targeted agent-core-v2 suites 469 pass / 10 fail,
and all 10 reproduce at the port base - 3 loop.test.ts inline snapshots
predate loopEnd and the unwrapped loadable-tools reminder, the rest are
the same config/tool/plan failures measured without this diff; klient
ipc+memory 35 pass (its typecheck fails at base on duplicate
agent-core-v2 type identities across the worktree junction); apps/
kimi-code token-speed 6 pass; check:no-comments, import boundaries and
deep-import checks green. The oxlint ratchet cannot run at base because
.oxlintrc.ratchet.json and .oxlintrc.json disagree on ignorePatterns.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Port the deferred-tool half of upstream 253212d (MoonshotAI#5142 stack); the LLM
event-stream half is already the ledger row for MoonshotAI#5130.

- core: `convert` keeps every declared tool instead of dropping deferred
  ones; `runPipeline` applies `withProtocolCapabilities` at the encode entry
  and `generate.ts` drops its duplicate merge; `legalizeTools` was already
  ported, so it is unchanged; `llm.started` toolsHash and the persisted
  llm.tools_snapshot hash every tool, deferred included.
- resolver: `requestTools(base, disclosure)` removes deferred entries when
  disclosing and otherwise removes `select_tools` and strips the `deferred`
  metadata. The loop request calls it with the baseline when a request
  carries no profile tools, and `dynamicTools` is removed from the requester
  contract.
- flags: the `tool_select` flag, `KIMI_CODE_EXPERIMENTAL_TOOL_SELECT`, the
  desktop forced env, the Agent tool gate, the `[experimental]` doc rows and
  the reference/MCP prose are removed; disclosure is capability-only. The
  fork's flag defaulted to true, so this is behaviourally neutral for capable
  models and only drops an explicit opt-out.
- `toolSelectPolicy` is ported to upstream's typed `shapeToolSelectRequest`;
  it stays upstream-dead per test/lint/unreachable-modules.txt, but its test
  double now uses the real two-argument signature.

Fork adaptations:

- The step reminder provider keeps supplying the initial loadable-tools
  announcement; upstream projects that snapshot from the resolver instead.
  `shapeHistory` still projects it for callers that pass the pre-shaping
  deferred baseline (request previews and the browser request-view test).
- Because the provider is the production source, snapshot announcements that
  list tools are suppressed when disclosure is off and baseline names are
  excluded from legacy deltas, so a model that cannot load tools is not told
  about a catalog it cannot use. The empty-set snapshot is kept: the loop
  history tests assert it.
- The fork-only MCP retrieval shortlist and its announcement are untouched.
- kap-server meta tests move to `notify_user`; `subagent_fork` no longer
  exists here.
- Comment gates: no comment added inside agent-core-v2; the response.ts
  timing comment is allowlisted in .commentignore.

Verification (targeted, one suite at a time):

- packages/core: 71 pass / 0 fail across test/llm/lifecycle/run.test.ts and
  the anthropic/openai/openai-responses/google-genai/kimi encode suites.
- agent-core-v2 test/agent/toolSelect: 133 pass / 0 fail.
- toolSelect.e2e: 11 pass / 1 fail — the inline-tool wire assertion fails at
  HEAD too, and the file is excluded from the default run by bunfig.
- fullCompaction: 130 pass / 0 fail. llmRequester + coreLoopService +
  dynamicActiveTools + undo: 79 pass / 0 fail. tool.test: 151 pass / 1 fail —
  the loadable-tools snapshot wrapper case fails at HEAD too.
- test/agent/loop + test/session/subagent: 292 pass / 7 fail, exactly the
  seven failures HEAD reports (four turn.ended.loopEnd snapshots, three 5s
  subagent timeouts).
- kap-server meta + context: 23 pass / 0 fail. desktop vitest (browser,
  embedded-server, shell-env, ipc register): 109 pass / 1 fail — the browser
  loadableToolsAnnouncement assertion fails at HEAD too.
- typecheck clean: core, agent-core-v2, kap-server, apps/kimi-code.
  apps/desktop reports one unrelated pre-existing TS2488 in
  tests/main/browser/browser-aot.test.ts.
- bun run lint: 0 errors. check:no-comments, check:locale-keys and
  check:t-coverage: OK.
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.

2 participants