Repository navigation
refactor(core): extract loop, llm, and tool into a DI-free package - #4820
Conversation
|
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. |
|
❌ Nix build failed |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f835a22d8d
ℹ️ 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".
| } from '#human/llm-requester/response-format'; | ||
| export type { ThinkingEffort, ThinkingRequestOptions } from '#human/llm-requester/thinking'; | ||
| } from '@moonshot-ai/core/llm-requester/response-format'; | ||
| export type { ThinkingEffort, ThinkingRequestOptions } from '@moonshot-ai/core/llm-requester/thinking'; |
There was a problem hiding this comment.
Bundle core types into the published SDK declarations
The public SDK re-exports ThinkingEffort from this line, but packages/node-sdk/scripts/build-dts.mjs only rewrites workspace references for agent-core-v2, oauth, and klient; @moonshot-ai/core is neither rewritten nor listed as a bundled package. API Extractor will therefore leave an import from @moonshot-ai/core in dist/index.d.mts, while that package is private and is not a dependency of the published SDK, so TypeScript consumers cannot resolve these declarations after installation. Add core to the declaration emission/rewriting pipeline or keep these public types behind a path the pipeline already bundles.
AGENTS.md reference: AGENTS.md:L122-L124
Useful? React with 👍 / 👎.
| if (llm.type === 'failed') { | ||
| return { type: 'failed', error: errorFromLlmOutcome(llm) }; | ||
| return { type: 'failed', error: llm.error }; |
There was a problem hiding this comment.
Preserve the complete LLM failure across the core boundary
When a provider returns 401/403, the failed outcome has error.kind === 'auth'; the old path passed the whole outcome to errorFromLlmOutcome, which deliberately converted auth to status. This now keeps only llm.error, and the later coerceLlmFailure calls errorFromLlmMessage, whose switch has no auth branch, so it returns undefined and the turn degrades to a generic Turn failed error instead of the provider-auth error expected by SDK/TUI handling. The same narrowing also discards rawError and diagnostics for unclassified provider failures; carry the full failure data to the v2 conversion boundary.
AGENTS.md reference: AGENTS.md:L126-L128
Useful? React with 👍 / 👎.
b9bf1c9 to
f95921c
Compare
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a4d94238f4
ℹ️ 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".
| generate: (modelId, input, params) => | ||
| streamCall('modelResolver', 'generate', [ | ||
| modelId, | ||
| coreInput, | ||
| input, | ||
| params, | ||
| ]) as AsyncIterable<ModelRequestEvent>; | ||
| return (async function* (): AsyncGenerator<GenerateEvent> { | ||
| for await (const event of events) { | ||
| if (event.type === 'part') { | ||
| yield { ...event, part: fromCorePart(event.part) }; | ||
| } else if (event.type === 'finish') { | ||
| yield { ...event, message: fromLlmMessage(fromCoreMessage(event.message)) }; | ||
| } else { | ||
| yield event as GenerateEvent; | ||
| } | ||
| } | ||
| })(); | ||
| }, | ||
| ]) as AsyncIterable<GenerateEvent>, |
There was a problem hiding this comment.
Preserve the public generate event vocabulary
Existing klient.global.kosong.generate consumers switch on part, usage, finish, and timing, but returning the raw stream here now exposes llm.streaming.* and llm.ended events instead; failures are also delivered inside a normal llm.ended outcome rather than rejecting the iterator. Such clients will silently ignore generated content or never observe completion, so retain the facade's compatibility projection or version this contract explicitly.
AGENTS.md reference: packages/klient/AGENTS.md:L9-L17
Useful? React with 👍 / 👎.
| const generateParamsSchema = z.object({ | ||
| cacheKey: z.string().optional(), | ||
| temperature: z.number().optional(), | ||
| topP: z.number().optional(), | ||
| thinkingEffort: z.string().optional(), | ||
| maxCompletionTokens: z.number().optional(), | ||
| protocol: z.unknown().optional(), | ||
| model: z.unknown().optional(), | ||
| endpoint: z.unknown().optional(), | ||
| }).optional(); |
There was a problem hiding this comment.
Continue accepting existing generation overrides
When an existing klient or IPC caller passes the previously supported { thinkingEffort, temperature, topP, maxCompletionTokens, cacheKey } parameters, this Zod object now treats every field as unknown and strips it, so generation silently runs with model defaults. Preserve and translate the flat fields to the new nested request shape, or introduce a versioned API instead of silently changing model behavior and token limits.
AGENTS.md reference: AGENTS.md:L126-L128
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: def10536be
ℹ️ 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".
| @@ -32,8 +32,8 @@ export function readLegacyStatus(agent: IAgentScopeHandle): LegacyStatusSnapshot | |||
| const context = agentContextOf(agent); | |||
| const usage = usageService.status(context); | |||
| const contextTokens = tokenCounting.statusSize(context); | |||
| const capabilities = profile.getModelCapabilities(); | |||
| let maxContextTokens = capabilities.max_input_tokens ?? capabilities.max_context_tokens; | |||
| const modelSpec = profile.getModel() === '' ? undefined : profile.resolveModelContext().model; | |||
There was a problem hiding this comment.
Keep status snapshots tolerant of removed model aliases
When a config hot reload removes or renames the model alias currently bound to a live session, resolveModelContext() calls modelCatalog.get() and throws. The previous getModelCapabilities() path used the safe tryResolveRawModel() fallback, so this change makes readLegacyStatus and the analogous SDK forwarding path in packages/node-sdk/src/v2/session-wiring.ts:298 fail while projecting subsequent status events instead of reporting an unknown maximum context. Preserve the prior fallback for status-only reads.
AGENTS.md reference: AGENTS.md:L112-L112
Useful? React with 👍 / 👎.
| provider: providerType ?? protocol, | ||
| name: wireName, | ||
| capability: capabilities, | ||
| thinking: { |
There was a problem hiding this comment.
Omit empty thinking metadata for non-thinking models
For a custom or unrecognized OpenAI model whose resolved capability.thinking is false, this always creates a thinking object even when the model declares no thinking metadata. resolveThinkingEffort() only rejects a concrete configured effort such as high when that object is absent, so the request now sends an unsupported reasoning_effort to the provider instead of producing the previous local thinking-unsupported error. Leave spec.thinking undefined when none of its metadata fields are configured.
AGENTS.md reference: AGENTS.md:L112-L112
Useful? React with 👍 / 👎.
| const requester = base.with({ | ||
| protocol: { options: protocolOptionsOf(model) }, | ||
| endpoint: provider.endpoint, | ||
| endpoint: { ...model.endpoint, ...provider.endpoint }, |
There was a problem hiding this comment.
Let model endpoints override provider defaults during ping
When a catalog model supplies its own endpoint.baseUrl or headers while its provider also has endpoint defaults, this spread order lets the provider overwrite the model values, so catalog.ping() probes the wrong URL or headers and can mark a working model as failed. The previous layering applied provider.endpoint first and the model-specific base URL and headers in the subsequent generate() request, where they won; preserve that precedence when constructing the new requester.
AGENTS.md reference: AGENTS.md:L112-L112
Useful? React with 👍 / 👎.
- move loop, llm, tool, history, and shared utilities into @moonshot-ai/core - unify request protocol, timing, request id, and credential recovery on core types - reapply provider, loop, and transport integrations on latest main
- remove the TurnExecution wrapper and request preparation pipeline - snapshot requester configuration at turn start while preserving next-turn requester changes - update host requester wiring and loop tests
- adapt prompt prediction to core llm types and outcome handling - include core declarations in the SDK type rollup
- extract loop, llm, and tool into the DI-free core package - use history entries at the high-level llm boundary and plain messages in attempts - construct assistant entries with actual model metadata during settlement - simplify loop requesters to snapshots and single generate calls - share turn-bound requester configuration and recovery memory - migrate direct generation, compaction, prediction, and client transports
- remove HistoryEntry/HistoryMessage/EntryMeta and packages/core/src/llm/history.ts, attaching optional MessageAttributes directly on Message - drop LlmProtocolRequest and LlmMessageContent, preserving MessageAttributes through resolvers and legalize passes until NativeModule conversion - align core/loop, agent-core-v2, klient, kap-server, cli, and core protocol fixture suites on unified Message and attributes contracts
d8e57e3 to
06cf18a
Compare
- restore modelCapabilities fallback in SDKRpcClientV2.importContext when no model is configured - map syntax LlmErrorMessage to provider.api_error in error payload serialization - omit HTTP statusCode when decoding OpenAI stream business errors - avoid duplicating already-rendered tool notes during context projection - align mock provider streaming, error awaiting, and non-retryable unmocked calls in test harness
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e0514624c
ℹ️ 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".
| read: (request) => (cached.get(routeKey(request)) ?? []).filter( | ||
| (entry) => entry.rewrite !== undefined && entry.rewrite(request) !== request, |
There was a problem hiding this comment.
Invalidate inherited media recovery when context changes
When a request triggers media degradation or stripping and a later compaction, undo, fork, or restore changes the history, this still restores the route-matching rewrite because the cache key has no history revision. The previous createMediaRecoveryStore keyed inherited recovery by (modelAlias, historyRevision) and refreshed the rewrite's captured display paths; now the rewrite runs before the current media resolver, so a smaller context can silently keep omitting images and relocated media can emit stale <image path="..."> tags. Scope reusable media recovery to the context revision and rebind it to the current media-path map.
AGENTS.md reference: AGENTS.md:L126-L128
Useful? React with 👍 / 👎.
- apply model-specific endpoints after provider defaults in connectivity probes - index the core LLM documentation by reader role
…end drift-allow - bun scripts/upstream-ledger.mjs --refresh: 148 new pending rows covering the 2.7.0 tail and upstream/main. - Mark MoonshotAI#5043/MoonshotAI#5037/MoonshotAI#5049 ported (26f22db, 0d20273, d61aacc) and MoonshotAI#5042 equivalent (multiline feedback editor already shipped, localized). - Refresh MoonshotAI#4820 evidence: the machine-architecture blocker retired with the 2.7.0 merge. - drift-allow: add the missing translated/renamed upstream files (media.ts, node-local hostServices/rgLocator/runRg, executor validate.ts, remaining vitest configs) so upstream-drift stops flagging deliberate removals. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
--refresh adds the 148 upstream commits that were missing from the ledger; the true open count is now 149, not 1. The refresh keeps the existing MoonshotAI#4820/MoonshotAI#4831/MoonshotAI#4352 corrections.
Requirement or Bug
loop、llm、tool 的实现与 DI/adapter 耦合,
agent-core-v2无法作为独立 core 被依赖;同时 requester 存在多层包装,HistoryEntry 与 plain Message 在 Loop 中反复转换,导致重复 prepare、隐藏的状态归属和不必要的step.model。这个 PR 把 loop、llm、tool 收进没有 DI、没有 adapter 的
@moonshot-ai/core,并进一步统一高层 HistoryEntry 请求/响应契约:一次generate()完成配置合并、usedTokens 估算、Entry→Message、attempts 和 AssistantEntry 输出。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心边界是:高层使用 HistoryEntry,attempts 与 protocol 使用 plain Message,settle 直接产出带实际 model 元数据的 AssistantEntry。
flowchart LR subgraph Host["agent-core-v2 / klient"] loop["LoopService / Turn binding"] direct["direct-generate / compaction / prediction"] end subgraph Core["@moonshot-ai/core"] requester["snapshot + generate"] run["runLlmRequest: usedTokens + Entry→Message"] attempts["resolvers / recovery / protocol / transport"] settle["settle: AssistantEntry + actual model"] end loop -->|HistoryEntry, profile, policy| requester direct -->|HistoryEntry| run requester --> run run --> attempts attempts --> settle settle -->|AssistantEntry| looppackages/core,@moonshot-ai/core,无 DI/adaptergenerate()request()预解析 + 公共prepare()+ 第二次 preparesnapshot + generate,policy 随 generate 传递with/requestbuilderstep.modelEntry 在
runLlmRequest → runAttempts之间且仅在这里剥离为 plain Message;protocol encode 是之后独立的供应商 wire 编码阶段。decoder 产生 part 后,settle 在流式过程中累积 AssistantMessage,并在每个 attempt 结束时构造 AssistantEntry。建议阅读顺序:
packages/core/src/llm/request.ts:高层 Entry 请求与 attempts 的 Message 请求边界。packages/core/src/llm/policy/policy.ts:usedTokens、Entry→Message、共享 recovery 和单次 generate。packages/core/src/llm/policy/settle.ts:流式 Message 累积和 AssistantEntry 生成。packages/core/src/loop/request.ts:Loop requester 的snapshot + generate最小接口。packages/agent-core-v2/src/agent/loop/loopService.ts:Turn config/binding、宿主观测和 direct operation 接线。packages/klient/src/core/facade/kosong-types.ts与packages/klient/src/transports/memory/dispatcher.ts:direct-generate 的 Entry 输入和传输。其余协议实现、provider patch、测试迁移、文档和重命名可略读。
Behavior Changes and Affected Users
LlmRequest.contentmessages: Message[]entries: HistoryMessage[]{ message, meta? };plain Message 仍用于 attempts/protocol,不保留第二个高层输入协议LlmOutcome与 retrying partial outputmessage: AssistantMessageentry: AssistantEntry,含实际 model 等 metadataoutcome.entry.message读取内容,用outcome.entry.meta读取元数据with()、request()预解析、generate()snapshot()+ 单次generate(),policy 随 rest 传入.with({ policy }).generate(rest)改为generate({ ...rest, policy })step.modelAssistantEntry.meta.modelrequestBuildMs和firstTokenLatencyMs起点settleLlmRequest进入时generate进入时streamDurationMs终点decoder.end()errorFromLlmOutcome,在 unknown 且有原始 Error 时使用rawErrorerrorFromLlmMessageLoop 命令、工具执行语义、既有 Wire 事件名、Turn 配置下一 Turn 生效规则、provider 协议和 credential recovery 保持。没有 prompt 文案改动,也没有新增 changeset;这是内部架构与协议重构。
验证覆盖:
lint:imports;相关 type-aware oxlint 为 0 error。unscheduled fetch,生产 transport 未改。验证命令与既有失败
pnpm --filter @moonshot-ai/core typecheckpnpm --filter @moonshot-ai/agent-core-v2 typecheckpnpm --filter @moonshot-ai/klient typecheckpnpm --filter @moonshot-ai/kimi-code-sdk buildpnpm --filter @moonshot-ai/agent-core-v2 buildpnpm --filter @moonshot-ai/agent-core-v2 lint:imports最终提交没有重新运行完整全量测试。此前全量记录中仍有 promptService 7 个、forkParity 1 个和 Registry statusCode 1 个既有失败;本轮没有扩大处理这些项目。首轮出现的 direct 输入迁移和 mock stream 调度问题已修复。
Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.