Repository navigation
refactor(core): unify llm event stream and harden behavior tests - #5130
Conversation
- 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
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 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".
| 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 } |
There was a problem hiding this comment.
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 👍 / 👎.
| describe('Google error decoding', () => { | ||
| it('as an API consumer, I want stream business 503 errors to remain retryable without an HTTP status', () => { |
There was a problem hiding this comment.
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 👍 / 👎.
| // 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'; |
There was a problem hiding this comment.
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 👍 / 👎.
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.
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.
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
LlmRunEventmixed run boundaries, attempt boundaries, and incremental response data.generate()also emitted internalattempt.*events whilesettle()produced publicllm.*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.startedand one finalllm.endedper generation, emitllm.requestedfor each actual attempt, and move incremental response facts tollm.delta.*.settle().llm.retry, allowing consumers to clear the current attempt before the next request.Start with
packages/core/src/llm/response.ts,generate.ts,policy/policy.ts, andpolicy/settle.ts, then follow the consumers inpackages/core/src/loop/andpackages/agent-core-v2/src/agent/loop/.Behavior Changes and Affected Users
llm.startedwaited for initial resolution; run and attempt events were interleavedllm.startedand one finalllm.endedllm.sentand internalattempt.sendingllm.requestedonce per actual attempt, using the legacy summary without full messages/tools/native bodiesllm.requested; no dual emissionllm.streaming.*andllm.timingllm.delta.*for parts, metadata, usage, finish, tool-call end, and timingllm.retrying, with separate internal attempt controlllm.retryfor both backoff and recovery, followed by a freshllm.requestedllm.retry; oldllm.retryingis not emittedattempt.failedandattempt.tool_call_endThe 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.@moonshot-ai/klient test: 144 passed, 11 skipped (live-server tests skipped without credentials).packages/core,packages/agent-core-v2, andpackages/klient.pnpm lintpassed, including comment, oxlint, import-boundary, guard, ratchet, and instruction checks.Checklist