Skip to content

refactor(core): extract loop, llm, and tool into a DI-free package - #4820

Merged
sailist merged 9 commits into
mainfrom
refact-346-11-11-core-loop-llm-tool
Nov 12, 2026
Merged

sailist merged 9 commits into
mainfrom
refact-346-11-11-core-loop-llm-tool

Conversation

@sailist

@sailist sailist commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

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| loop
Loading
决策 选择 没选 理由
core 包 packages/core,@moonshot-ai/core,无 DI/adapter 继续由 v2 承载 engine 实现 loop、llm、tool 可以独立复用,依赖只朝一个方向
高层消息契约 HistoryEntry 输入、AssistantEntry 输出 Loop 在 Message 与 Entry 之间重复适配 usage、origin、isError 等元数据一直保留到最终 profile 已知
请求执行 一次 generate() request() 预解析 + 公共 prepare() + 第二次 prepare usedTokens 在实际 profile 已知后计算,Step 不再重复组装
Loop requester snapshot + generate,policy 随 generate 传递 每个 Step 重新实现 with/request builder 配置在 Turn/operation 边界绑定,Step 只提供当前内容
响应元数据 settle 用最终 request 写入实际 model、usage、finish、messageId Loop 预读 model 并保存到 step.model 成功、失败、中断和 retrying partial output 共用同一套 Entry 构造
recovery 派生 requester 共享 execution memory,每次 generate 独立 ledger;reset 成功后清空 Loop 外部保存并逐步传 ledger,或共享一个正在执行的可变 ledger 普通 Turn 与并发 operation 可以复用恢复规则而不互相污染

Entry 在 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

Behavior Before After Who relies on the old behavior Escape hatch
高层 LlmRequest.content messages: Message[] entries: HistoryMessage[] direct-generate、klient facade、provider/catalog 调用方 改为传 { message, meta? };plain Message 仍用于 attempts/protocol,不保留第二个高层输入协议
LlmOutcome 与 retrying partial output message: AssistantMessage entry: AssistantEntry,含实际 model 等 metadata Loop history、compaction、prediction、klient/IPC 消费方 用 outcome.entry.message 读取内容,用 outcome.entry.meta 读取元数据
Loop requester 调用面 with()、request() 预解析、generate() snapshot() + 单次 generate(),policy 随 rest 传入 LoopService、PromptCacheGuard、operation 调用方 将 .with({ policy }).generate(rest) 改为 generate({ ...rest, policy })
实际 model 的记录 每 Step 预解析并保存到 step.model settle 从最终 request 写入 AssistantEntry.meta.model assistant history、failed/aborted partial history 不再由 Step 预读;消费者改读 Entry metadata
recovery 生命周期 Loop/外部 media ledger 同步;reset 可能继承旧媒体 rewrite execution memory 共享,generate-local ledger 隔离;成功 reset 清空 普通 Turn、并发 operation、Undo/clear/fork 普通 recovery 继续共享;Undo/clear/fork 使用 reset 后的新历史
requestBuildMs 和 firstTokenLatencyMs 起点 settleLlmRequest 进入时 generate 进入时 读取 step/turn timing 的 TUI、desktop、web、遥测 无;属于计时边界调整
streamDurationMs 终点 settle 组完 outcome 后 decoder.end() 同上 无;属于计时边界调整
未分类 LLM 失败的 Error 转换 errorFromLlmOutcome,在 unknown 且有原始 Error 时使用 rawError errorFromLlmMessage 客户端错误展示、journal、turn projection 无;协议错误保留分类、requestId、diagnostics 和原始字段

Loop 命令、工具执行语义、既有 Wire 事件名、Turn 配置下一 Turn 生效规则、provider 协议和 credential recovery 保持。没有 prompt 文案改动,也没有新增 changeset;这是内部架构与协议重构。

验证覆盖:

  • core Loop、Undo recovery、full compaction、ToolSelect、媒体、prediction:14 个文件,468/468。
  • klient memory 与 IPC facade/contract:62/62,包含 Entry 输入、AssistantEntry 和 metadata。
  • direct requester 与 Loop requester:11/11;direct-generate catalog:1/1。
  • core、v2、klient、Node SDK、kap-server、acp-server、vis-server typecheck;v2 build、Node SDK build/API Extractor;lint:imports;相关 type-aware oxlint 为 0 error。
  • 直接 stream 的测试 mock 改用 resolver 登记响应,修复 unscheduled fetch,生产 transport 未改。
验证命令与既有失败
  • pnpm --filter @moonshot-ai/core typecheck
  • pnpm --filter @moonshot-ai/agent-core-v2 typecheck
  • pnpm --filter @moonshot-ai/klient typecheck
  • pnpm --filter @moonshot-ai/kimi-code-sdk build
  • pnpm --filter @moonshot-ai/agent-core-v2 build
  • pnpm --filter @moonshot-ai/agent-core-v2 lint:imports
  • 远端 vitest:核心 14 个文件 468/468;klient memory + IPC 62/62。

最终提交没有重新运行完整全量测试。此前全量记录中仍有 promptService 7 个、forkParity 1 个和 Registry statusCode 1 个既有失败;本轮没有扩大处理这些项目。首轮出现的 direct 输入迁移和 mock stream 调度问题已修复。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • 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 Nov 11, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 109c283

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 11, 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-12T14:35:00.187419Z 109c283 New commits
ℹ️ 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.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

❌ Nix build failed

    kimi-code>     at onLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46097:7)
    kimi-code>     at file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:21383:32
    kimi-code>     at Object.logger [as onLog] (file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:23378:9)
    kimi-code>     at ModuleLoader.handleInvalidResolvedId (file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:22122:26)
    kimi-code>     at file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:22080:26
    kimi-code> file:///build/source/apps/kimi-code/scripts/build-vis-asset.mjs:35
    kimi-code>   throw new Error(
    kimi-code>         ^
    kimi-code> 
    kimi-code> Error: [build-vis-asset] failed to run the vis-web single-file build via pnpm (is pnpm on PATH?): Command failed: pnpm --filter @moonshot-ai/vis-web exec vite build
    kimi-code>     at file:///build/source/apps/kimi-code/scripts/build-vis-asset.mjs:35:9
    kimi-code>     at ModuleJob.run (node:internal/modules/esm/module_job:561:25)
    kimi-code>     at async node:internal/modules/esm/loader:647:26
    kimi-code>     at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
    kimi-code> 
    kimi-code> Node.js v24.21.0
    kimi-code> Command failed: /nix/store/fisi9algzl2pcxb2xfhgp2yw5mzjfdwg-nodejs-slim-24.21.0/bin/node /build/source/apps/kimi-code/scripts/build-vis-asset.mjs
    kimi-code> ✗ Build failed in 484ms
    kimi-code> error during build:
    kimi-code> [vite]: Rollup failed to resolve import "@moonshot-ai/core/llm/protocol/kit/media" from "/build/source/apps/vis/server/src/lib/agent-record-types.ts".
    kimi-code> This is most likely unintended because it can break your application at runtime.
    kimi-code> If you do want to externalize this module explicitly add it to
    kimi-code> `build.rollupOptions.external`
    kimi-code>     at viteLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46399:15)
    kimi-code>     at file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46457:18
    kimi-code>     at onwarn (file:///build/source/node_modules/.pnpm/@[email protected][email protected]_@[email protected][email protected][email protected][email protected][email protected]_/node_modules/@vitejs/plugin-react/dist/index.js:90:7)
    kimi-code>     at file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46455:7
    kimi-code>     at onRollupLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46447:5)
    kimi-code>     at onLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46097:7)
    kimi-code>     at file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:21383:32
    kimi-code>     at Object.logger [as onLog] (file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:23378:9)
    kimi-code>     at ModuleLoader.handleInvalidResolvedId (file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:22122:26)
    kimi-code>     at file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:22080:26
    kimi-code> file:///build/source/apps/kimi-code/scripts/build-vis-asset.mjs:35
    kimi-code>   throw new Error(
    kimi-code>         ^
    kimi-code> 
    kimi-code> Error: [build-vis-asset] failed to run the vis-web single-file build via pnpm (is pnpm on PATH?): Command failed: pnpm --filter @moonshot-ai/vis-web exec vite build
    kimi-code>     at file:///build/source/apps/kimi-code/scripts/build-vis-asset.mjs:35:9
    kimi-code>     at ModuleJob.run (node:internal/modules/esm/module_job:561:25)
    kimi-code>     at async node:internal/modules/esm/loader:647:26
    kimi-code>     at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
    kimi-code> 
    kimi-code> Node.js v24.21.0
    kimi-code> 
    kimi-code> /build/source/apps/kimi-code:
    kimi-code>  ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL  @moonshot-ai/[email protected] build:native:sea: `node scripts/native/build.mjs --profile=local`
    kimi-code> Exit status 1
    error: Cannot build '/nix/store/2jc9w24ys1r4pljkh34zs5rynkjbxrwi-kimi-code-2.5.3.drv'.
           Reason: builder failed with exit code 1.
           Output paths:
             /nix/store/gbhvkylicggm5qdrn5pr6n4skkri1z1c-kimi-code-2.5.3
           Last 25 log lines:
           >     at viteLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46399:15)
           >     at file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46457:18
           >     at onwarn (file:///build/source/node_modules/.pnpm/@[email protected][email protected]_@[email protected][email protected][email protected][email protected][email protected]_/node_modules/@vitejs/plugin-react/dist/index.js:90:7)
           >     at file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46455:7
           >     at onRollupLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46447:5)
           >     at onLog (file:///build/source/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-Dq2t6Dq0.js:46097:7)
           >     at file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:21383:32
           >     at Object.logger [as onLog] (file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:23378:9)
           >     at ModuleLoader.handleInvalidResolvedId (file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:22122:26)
           >     at file:///build/source/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:22080:26
           > file:///build/source/apps/kimi-code/scripts/build-vis-asset.mjs:35
           >   throw new Error(
           >         ^
           >
           > Error: [build-vis-asset] failed to run the vis-web single-file build via pnpm (is pnpm on PATH?): Command failed: pnpm --filter @moonshot-ai/vis-web exec vite build
           >     at file:///build/source/apps/kimi-code/scripts/build-vis-asset.mjs:35:9
           >     at ModuleJob.run (node:internal/modules/esm/module_job:561:25)
           >     at async node:internal/modules/esm/loader:647:26
           >     at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
           >
           > Node.js v24.21.0
           >
           > /build/source/apps/kimi-code:
           >  ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL  @moonshot-ai/[email protected] build:native:sea: `node scripts/native/build.mjs --profile=local`
           > Exit status 1
           For full logs, run:
             nix log /nix/store/2jc9w24ys1r4pljkh34zs5rynkjbxrwi-kimi-code-2.5.3.drv

@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: 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".

Comment thread packages/agent-core-v2/src/index.ts Outdated
} 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';

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 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 👍 / 👎.

Comment on lines 424 to +425
if (llm.type === 'failed') {
return { type: 'failed', error: errorFromLlmOutcome(llm) };
return { type: 'failed', error: llm.error };

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 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 👍 / 👎.

@sailist
sailist force-pushed the refact-346-11-11-core-loop-llm-tool branch from b9bf1c9 to f95921c Compare November 11, 2026 14:00
@pkg-pr-new

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

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

commit: 109c283

@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: 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".

Comment on lines +521 to +526
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>,

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 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 👍 / 👎.

Comment on lines 56 to 60
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();

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 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 👍 / 👎.

@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: 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;

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 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: {

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 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 },

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 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
@sailist
sailist force-pushed the refact-346-11-11-core-loop-llm-tool branch from d8e57e3 to 06cf18a Compare November 12, 2026 12:12
- 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
@sailist

sailist commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@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: 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".

Comment on lines +96 to +97
read: (request) => (cached.get(routeKey(request)) ?? []).filter(
(entry) => entry.rewrite !== undefined && entry.rewrite(request) !== request,

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 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
@sailist
sailist merged commit aced52f into main Nov 12, 2026
26 of 28 checks passed
@sailist
sailist deleted the refact-346-11-11-core-loop-llm-tool branch November 12, 2026 15:04
devin-ai-integration Bot added a commit to 7723qqq/kimi-code that referenced this pull request Nov 24, 2026
…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>
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 24, 2026
--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.
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