Skip to content

refactor(core): extract hook registries - #5157

Merged
sailist merged 2 commits into
mainfrom
refact-404-11-19-core-hook-module
Nov 20, 2026
Merged

sailist merged 2 commits into
mainfrom
refact-404-11-19-core-hook-module

Conversation

@sailist

@sailist sailist commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Loop 与 ToolExecutor 分别维护 hook 注册表和 chain 组合逻辑,使生命周期事件、失败处理及 non-blocking 能力难以统一。这个 PR 将 core 的 hook 注册与执行收敛到独立模块,并让 v2 在保持现有服务门面和 hook 行为的前提下接入统一实现。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路是由 Registry 统一持有注册项、执行 chain 并发出生命周期事件,Loop 与 ToolExecutor 只接收单个 hook 视图。现有 hook 全部保持 blocking;non-blocking 仅作为新的 Registry 注册能力提供。

flowchart LR
    V2[v2 loop / toolExecutor services] --> Registry[core hook registries]
    Registry --> LoopHook[Single Loop hook view]
    Registry --> ToolHook[Single ToolExecutor hook]
    LoopHook --> Loop[Loop]
    ToolHook --> Executor[ToolExecutor]
    Registry --> Lifecycle[registry.subscribe lifecycle events]
    Loop --> Failed[Loop hook.failed event]
Loading

旧路径功能清单

旧路径职责 新位置与行为
Loop 注册、暂停、恢复、删除、list 与生命周期事件 通用 Registry;事件改由 registry.subscribe 发出,并携带 blocking mode
turn.starting、message.appending、step.starting、tool.batch-starting、step.stopping、step.continuing hook/loop chain;保留顺序、逐条改写、first-decision 短路、cause 签名及 pause/block 失败策略
validating、starting、permitting、beforeExecute、afterExecute、observe hook/tool-executor chain;保留同步 validating、reject 短路、args 改写、skipPermitting、结果替换及 observe 异常隔离
hook.failed 与 hookFailureMessage hook/loop/failure 与 Loop actor;保留原事件和消息形状
v2 注册门面 loopService / toolExecutorService;registerToolBatchStarting、registerHook、registerLegacyStarting 签名和注册顺序不变

同步 hook 的 first-decision 与 step-ending 路径直接返回结果,只有实际返回 Promise 时才进入异步续链。这保留了原有 token counting 与 turn.ended 的事件顺序,而不是仅保证 decision 结果一致。

阅读顺序建议:先看 packages/core/src/hook/registry.ts 了解注册与通知模型,再看 hook/loop/registry.ts、hook/tool-executor/registry.ts 的分点 chain,最后看两个 v2 service 的接线。hook/loop/run.ts 与 loop-actor.ts 负责把 chain result 和失败暂停接回现有 Loop 流程。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Core Loop hook 注入 CreateLoopOptions.hooks 数组和 Loop.hooks 注册表 构造只接收单个 hook;注册由外部 createLoopHookRegistry 管理 core API 调用方;仓库内旧面消费为 v2 loopService 与 core 测试 使用新的 LoopHookRegistry,并将其 hook 视图传给 Loop;该公共面调整已在任务契约中明确批准
Loop 生命周期事件 hook.added/paused/resumed/removed 进入 Loop 事件流 改由 registry.subscribe 发出;Loop 只保留 hook.failed Loop 事件订阅者;排查未发现 core 之外的旧事件消费方 订阅对应 Registry;事件含 blocking mode
Loop chain 行为 Loop 内部 registry/run 执行六个 hook 点 统一 Loop chain 执行相同六个 hook 点 v2 turn/message/step 处理、maxSteps、swarm batch gate 决策、改写、失败暂停和 cause 形状保持不变,由原有及新增回归覆盖
ToolExecutor hook 组合 composeToolExecutorHooks 组合 hook 数组 ToolExecutorHookRegistry 生成单个 hook fileHistory、permissionGate、shellCommand、MCP、toolDedupe、task 等 v2 hook 注册方 v2 registerHook 门面不变;直接使用 composer 的 core 调用方迁移到 ToolExecutorHookRegistry
non-blocking 注册 不支持 blocking: false 先触发且不等待,参数只读、返回值不影响结果;失败暂停并发 Registry 事件 新 Registry 的外部使用方;现有 hook 全部仍为 blocking 不使用该选项即保持原 blocking 行为
core hook 公共导出 无独立入口 新增 @moonshot-ai/core/hook 及既有深层子路径 core 库调用方 原深层子路径继续可用

KAP、node-sdk、ACP、配置文件、环境变量、会话持久化格式和 CLI/Desktop/VS Code 用户界面均未改变。没有提示词文本变化,也没有旧会话数据迁移。

覆盖

  • Loop 注册、改写、短路、pause/block 失败、step-ending 事件顺序:Loop core hooks 19 个用例;v2 Loop/service 及相关 feature 回归。
  • ToolExecutor 同步 validating、reject、改写、skipPermitting、afterExecute、observe 与 non-blocking 生命周期:core tool 91 个用例及 v2 ToolExecutor 回归。
  • permissionGate、plan、btw、externalHooks、swarm、task 等注册方均纳入远程回归。
验证明细
  • pnpm lint:通过。
  • packages/core 与 packages/agent-core-v2 的 tsc --noEmit:均通过。
  • 本地三组聚焦测试:91/91,通过。
  • Linux 远程 core test/tool:5 个文件、91/91,通过。
  • Linux 远程 agent-core-v2 相关回归:27 个文件、533/533,通过;其中 text-only turn 的原事件顺序快照也通过。
  • 测试声明总数未净增:core tool 15→15,Loop core hooks 19→19。

Checklist

  • I have read the CONTRIBUTING document.
  • No GitHub issue; the requirement and architecture context are described above.
  • I have added or migrated tests that prove the new Registry and existing behavior work.
  • The behavior-change table above is complete; removed APIs and events have migration paths and were explicitly approved in the task contract.
  • Changeset omission is intentional at the requester’s explicit instruction, not a claim that this PR is exempt from the repository requirement.
  • No user documentation update is needed: there is no CLI, Desktop, VS Code, KAP, configuration, or session-format change; API migration is described in this PR.

@changeset-bot

changeset-bot Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 1fdb95d

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 20, 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-20T03:05:04.411303Z 1fdb95d 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.

@pkg-pr-new

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

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

commit: 1fdb95d

@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: 1fdb95dd27

ℹ️ 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 +192 to +194
suspend(item) {
setPaused(item.id, item.point, true, 'failed');
},

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 Suspend only the failed registration

When an asynchronous hook is removed while still pending and a replacement is registered with the same ID and hook point before the original invocation rejects, suspend looks up the current group by ID/point and pauses the replacement rather than the failed item. The same race exists for non-blocking hooks through failNonBlocking, so the newly registered hook can be silently disabled; verify that the exact HookItem is still registered before pausing it.

AGENTS.md reference: AGENTS.md:L210-L212

Useful? React with 👍 / 👎.

Comment on lines +166 to +169
const invokeHook = (item: HookItem, args: readonly unknown[]): unknown => {
const hook = item.hook as (...args: readonly unknown[]) => unknown;
return hook(...args);
};

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 Preserve the registered hook receiver

For callers migrating from composeToolExecutorHooks, registering an object method such as policy.validating now invokes it as a bare function, so hooks that use this receive undefined and fail even though the old composer explicitly called each method with its owning hook object. The migrated test only passes because its helper manually binds every method, masking this lost contract; retain the receiver in registrations or provide an object-level registration API that performs the binding.

AGENTS.md reference: AGENTS.md:L206-L208

Useful? React with 👍 / 👎.

Comment on lines +24 to +25
}): D {
return { [hookChainResultMarker]: true, ...result } as D;

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 Return the declared decision from registry hooks

The exported loop registry exposes hook as LoopHooks, but wrapHookChainResult casts an internal envelope to the declared decision type and returns that envelope at runtime. A direct call such as registry.hook['turn.starting'](...) therefore receives { decision, failures, ... } instead of the promised TurnStartingVerdict, and using one registry's hook as a hook in another registry either loses the decision or reports it as invalid. Keep the failure metadata out of the public hook result or expose a distinct internal hook type rather than masquerading the envelope as D.

Useful? React with 👍 / 👎.

@sailist
sailist merged commit c6c7177 into main Nov 20, 2026
16 checks passed
@sailist
sailist deleted the refact-404-11-19-core-hook-module branch November 20, 2026 03:08
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Port c6c7177.

packages/core/src/hook/loop now owns the loop hook registry, chain runners,
failure helpers and the max-steps builtin, and hook/index.ts is reachable
through a new ./hook package entry. LoopActor takes Partial<LoopHooks> instead
of building a per-loop registry; Loop.hooks, HookRegistration, HookInfo and
HookLifecycleEvent are gone, and CreateLoopOptions.hooks became
hook?: Partial<LoopHooks>. tool/hook-composer.ts is deleted in favor of
createToolExecutorHookRegistry, and AgentToolExecutorService composes through
that registry.

Fork adaptations:
- hook/result.ts only gains rewrittenBy; the fork's later (MoonshotAI#5211) HookFailure
  shape with suspend stays, and the chain failures suspend through it.
- hook/loop/{failure,registry,run}.ts import Message from
  @moonshot-ai/core/llm/message like loop/contract/hook.ts already does: the
  agent-core-v2 tsconfig maps #/llm/message to src/human/llm/message, which
  would otherwise split the Message identity.
- AgentLoopService registers turn.starting, message.appending, step.starting,
  step.stopping and max-steps once on a createLoopHookRegistry() field and
  keeps the fork's bypassStep max-steps condition; registerToolBatchStarting
  adds and removes by id.
- AgentToolExecutorService keeps the fork-only forkHook in the chain.
- test/harness/toolHooks.ts, the tool executor stubs and the hook-registry
  test were already ported; test/agent/task/stubs.ts needs no change because
  the fork carries no composeToolExecutorHooks there.

Verified:
- packages/core: typecheck clean; bun test --isolate test/tool/ 89 pass.
- packages/agent-core-v2: typecheck clean and 25 pass (loop core
  hooks/record/requester/wait), 18 (hooks.test alone, including the new
  step.stopping block-policy case), 19 (coreLoopService), 64 (toolExecutor),
  55 (toolScheduler + taskService), run through a temporary worktree-local
  node_modules junction so @moonshot-ai/core resolves to this worktree.
- check:no-comments OK (2414 files), check-deep-imports OK, agent-core-v2
  lint:imports OK (2058 files), scoped oxlint 0 errors.
- test/agent/loop/loop.test.ts 65 pass / 3 fail: pre-existing snapshot drift
  (loopEnd missing from those snapshots, system-reminder wrapper text differs
  from src/agent/toolSelect/dynamicTools.ts), untouched by this port.
- scripts/checks/ratchet.mjs aborts on pre-existing .oxlintrc vs
  .oxlintrc.ratchet.json ignorePatterns drift; both files are untouched here.
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