Skip to content

[建议 / Feature] 需要完整的 Hooks 系统 + 自运行TypeScript插件系统 Complete Hooks System Support + TypeScript Self-Running Runtime #167

Open

Description

@cocacocca

提交前确认 · Pre-submission checklist

  • 我已搜索过现有 issue,确认这不是重复提议 / I searched existing issues and confirmed this isn't a duplicate.
  • 我已阅读 CONTRIBUTING.md / I've read CONTRIBUTING.md.

问题类别 · Category

对话 / Agent 交互 · Agent chat / interaction

涉及的 Agent 框架 · Agent framework

ZCode Agent(自研)

使用场景 · Use case

当前状态

我基于 ZCode / OpenCode 开发了自己的 SAP(SDD 工程框架插件,github公开思想且使用在ZCode中),实现了多个 hook 覆盖 16 种事件类型,包括:

层级 事件 功能 检测状态
入口 SessionStart 注入 SAP 元路由
入口 UserPromptSubmit 场景识别
前置 PreToolUse (Read/Edit/Write) 敏感文件保护、规则注入
后置 PostToolUse (Edit/Write/Task) 硬门禁、格式校验、skill 遵循
后置 PostToolUseFailure 失败记录、重试
后置 PostToolBatch 批处理一致性
通知 Notification 阶段完成检测
压缩 PreCompact / PostCompact 压缩前后状态保存
任务 TaskCreated / TaskCompleted 任务生命周期
子智能体 SubagentStart / SubagentStop 子智能体注入、结果收集
文件 FileChanged 文件变更感知
会话 Stop / SessionEnd 状态保存

在使用OpenCode的过程中是没有问题的,我设计的每一个agents,每一个hooks,每个stages,每个skills,sap下内置的issues、feature系统都是能够使用到的,也遵循了我的开发设计;而后我改用了ZCode,尝试移植了OpenCode插件,除了hooks,其他的都是能正常的,那么基于我自己规划的SAP,以下是以我自己开发插件及自己的使用视角去赘述一些问题

具体痛点

1. 事件检测不完整

以下事件(仅列举部分js)在 hooks.json 中注册后无法被 ZCode 运行时检测:

{ "event": "SubagentStart", "file": "hooks/subagent-start.js" },
{ "event": "SubagentStop", "file": "hooks/subagent-stop.js" },
{ "event": "Notification", "file": "hooks/notification.js" },
{ "event": "PreCompact", "file": "hooks/pre-compact.js" },
{ "event": "PostCompact", "file": "hooks/post-compact.js" },
{ "event": "TaskCreated", "file": "hooks/task-lifecycle.js" },
{ "event": "TaskCompleted", "file": "hooks/task-lifecycle.js" },
{ "event": "FileChanged", "file": "hooks/file-changed.js" },
{ "event": "SessionEnd", "file": "hooks/session-end.js" }

影响:SAP 的 GAN 轮转审查、子智能体规则注入、阶段完成检测等核心功能无法实现。

2. Hook 触发不可见

开发者无法看到:

  • 哪些 hook 在当前 session 中注册成功
  • 每次 hook 触发的具体时机和执行耗时
  • hook 执行结果(成功/失败/跳过)

调试方式:只能在 hook 文件中添加 console.log,然后在大量日志中搜索。效率极低。

3. 不支持多轮触发(RULE 动态更新问题)

SAP 的串行 SDD 流程(P0-P1-P2-P3-P4)中,RULE 文件在每个阶段都可能被更新:

P0: brainstorm-agent 更新 RULE_FRONTEND.md
    |
P0.5: spec-coordinator 更新 RULE_API.md
    |
P2: craftsman 更新 RULE_MODULE.md
    |
P3: QE 审查发现新问题,更新 RULE_SECURITY.md

当前问题:rules-injector.js 只在 PreToolUse 时触发一次,后续 RULE 更新无法感知。

4. 无法指定触发条件

ZCode 的 hooks.json matcher 只支持精确字符串匹配(如 "Edit|Write"),不支持:

  • 权限规则语法(如 "Edit(*.ts)" 仅对 TypeScript 触发)
  • 正则表达式
  • 组合条件(AND / OR)

当前 workaround(及其代价)

  1. 逻辑合并:将 SubagentStart/Stop 的注入逻辑合并到 PostToolUse Task 中,但丢失了"启动时注入"的精确时机。

  2. 轮询补偿:在 PostToolUse 中增加 RULE 文件 mtime 检测,但 PostToolUse 本身也不被检测,导致 workaround 也失效。

  3. 过度日志:在每个 hook 文件中添加 console.log 输出,但 ZCode 的日志系统没有过滤功能,调试时被淹没。

  4. 放弃部分功能:因事件无法检测,GAN 轮转审查的"子智能体启动注入"功能被迫搁置。

不方便之处

  • 开发效率:一个功能需要 3-5 层 workaround,代码复杂度指数级上升
  • 稳定性:workaround 依赖 hook 触发时序,竞态条件频发
  • 可维护性:无法在 UI 中看到 hook 注册状态,排查问题耗时

5. TypeScript 自运行时缺失(核心痛点)

现状:当前 ZCode 插件的 hook 处理程序只能执行编译后的 JavaScript(.js),无法直接运行 TypeScript(.ts)。

对比 opencode 插件系统:

维度 opencode ZCode(当前)
运行时 Bun(原生 TS) Node.js(仅 JS,需编译)
插件入口 src/index.ts(直接运行) dist/index.js(需编译)
Hook 处理 .ts 直接执行 必须编译为 .js,hooks用node调用触发js文件

对 SAP 插件的影响:

SAP 包含 多个 TypeScript 文件,全部需要编译为 JS 才能运行:

zcode-sap/
├── agents/          # 13 个 agent(.md)
├── hooks/           # 26 个 hook(.js/ts)
├── stages/          # 16 个 stage(.js/ts)
├── skills/          # n 个 skill(.md)
├── commands/        # 9 个 command(.md)
├── issues/          # 问题追踪系统(.ts)
├── feature/         # 功能规划系统(.ts)
└── eval/            # 文件评估系统(.ts)

当前 workflow:

修改 .ts -> tsc 编译为 .js -> node xxx.js -> 测试

期望 workflow(同 opencode):

修改 .ts -> 自动热重载 -> 即时测试

具体要求:

  1. 支持 Bun 运行时(推荐)

    • Bun 原生支持 TypeScript,无需编译
    • 性能优于 Node.js(启动快 3-5x)
    • 与 opencode 插件系统一致
  2. 或支持任何能自运行 TS 的运行时

    • tsx、ts-node、deno 等也可作为 fallback
    • 关键:插件入口能直接是 .ts 文件
  3. 热重载支持

    • 修改 .ts 文件后自动重新加载
    • 无需手动重启 ZCode

ZCode 如果支持同样的能力,SAP 的 40+ 个 .ts 文件可以直接运行,无需编译步骤。

建议方案 · Proposal

1. 全事件类型支持

确保插件 hooks.json 中注册的所有事件能被运行时检测:

事件 触发时机 对 SAP 的价值(作为参考,假如说有一套合理的Harness并且需要使用到hooks,且肯定不止我列举的这些)
SessionStart 会话开始/恢复 注入 SAP 元路由(已实现)
UserPromptSubmit 用户提交 prompt 场景识别(已实现)
PreToolUse 工具调用前 敏感文件保护、规则注入(已实现)
PostToolUse 工具调用后 硬门禁、格式校验(已实现)
SubagentStart 子智能体启动 注入该 agent 的 allowedSkills + rule
SubagentStop 子智能体结束 收集结果、更新 pipeline state
Notification 系统通知 检测 [PHASE_COMPLETE:P{N}] 标记
PreCompact 压缩前 保存 pipeline state 到文件
PostCompact 压缩后 恢复 state,显示当前 stage
TaskCreated 任务创建 初始化 taskProgress 条目
TaskCompleted 任务完成 标记 status=pass,触发 GAN 轮转
FileChanged 文件变更 检测 SKILL.md/RULE.md 更新
Stop Claude 结束响应 保存 pipeline state 到 .json 文件
SessionEnd 会话终止 清理临时文件、归档

2. Hook 触发可视化

UI 视图(/hooks 菜单):

Hook Registration Status
----------------------------------------------------------
  SessionStart          session-start.js
  UserPromptSubmit      user-prompt-submit.js
  PreToolUse (Read)     sensitive-file-guard.js
  PreToolUse (Edit|Write) rules-injector.js
  PostToolUse (Edit|Write) brainstorm-gate.js
  SubagentStart         subagent-start.js
  SubagentStop          subagent-stop.js
  Notification          notification.js
  PreCompact            pre-compact.js
  PostCompact           post-compact.js
  TaskCreated           task-lifecycle.js
  TaskCompleted         task-lifecycle.js
  FileChanged           file-changed.js
  Stop                  session-end.js
  SessionEnd            session-end.js

触发日志(每次 hook 触发时输出):

[HOOK] SubagentStart -> subagent-start.js [45ms] SUCCESS
[HOOK] PostToolUse:Edit -> rules-injector.js [120ms] SUCCESS [RULE_API injected]
[HOOK] Notification -> notification.js [8ms] SKIPPED [no phase marker]

3. 多轮 Hook 触发机制

基于 mtime 的变更检测:

在 PostToolUse 中自动检测 RULE/skill 文件是否在两次 hook 之间被更新:

function shouldReinject(rulePath) {
  const currentMtime = fs.statSync(rulePath).mtimeMs;
  const lastMtime = mtimeCache.get(rulePath);
  if (currentMtime > lastMtime) {
    mtimeCache.set(rulePath, currentMtime);
    return true;  // 文件已更新,需要重注入
  }
  return false;
}

触发时机:

Hook 点 检测内容 重注入动作
PreToolUse Edit|Write RULE 文件 mtime 注入最新 RULE
PostToolUse Edit|Write RULE 文件 mtime 检测变更,输出 delta
SubagentStart 该 stage 的 RULE + skill references 注入最新内容
FileChanged SKILL.md / RULE.md 更新 触发相关 hook 重注入

4. 指定触发条件(if 字段 + matcher 增强)

权限规则语法:

{
  "event": "PreToolUse",
  "matcher": "Edit|Write",
  "hooks": [{
    "type": "command",
    "if": "Edit(src/api/*.ts)",
    "command": "node hooks/rules-injector.js"
  }]
}

Matcher 增强:

Matcher 说明 示例
精确匹配 当前行为 "Edit|Write"
权限规则 工具名 + 参数 glob "Edit(*.ts)", "Bash(git *)"
正则表达式 完整路径匹配 "^src/api/.*\\.ts$"
组合条件 AND / OR "Edit AND *.ts", "Bash(git OR npm)"

预期价值 · Expected value

量化收益

维度 当前 实现后 提升
可检测事件数 6 / 16 16 / 16 167%
Hook 调试时间 30-60 min 5-10 min 80%
RULE 更新延迟 整个 session 实时 即时
开发者信心 低(workaround 多) 高(官方支持) 质的飞跃

对 SAP 插件的具体价值

  1. GAN 轮转审查完整实现:SubagentStart 注入 QE 规则 → SubagentStop 收集结果 → PostToolUse Task 触发裁决
  2. 阶段状态持久化:PreCompact/PostCompact 保存/恢复 pipeline state,避免 context 压缩丢失进度
  3. 动态规则更新:FileChanged hook 检测 RULE 更新 → 自动重注入,确保 agent 始终遵守最新规则
  4. 透明调试:开发者可在 UI 中看到每个 hook 的触发状态,快速定位问题

你认为的优先级 · Your perceived priority

高 · High

你使用的 ZCode 版本 / 环境 · ZCode version / environment

3.3.6

补充材料 · Additional context

https://code.claude.com/docs/zh-CN/hooks

Activity

  1. added
    status: 待评估
    type: 功能建议
    on Jul 21, 2026
  2. github-actions commented on Jul 21, 2026

    @github-actions

    👋 感谢你的反馈,我们已经收到。

    • 维护者会在 3 个工作日内 给出首次响应。
    • 状态保持为 status: 待评估,你可以随时补充信息。
    • 信息不全时我们会打上 needs: 更多信息 标签并 @ 你。

    👋 Thanks — we've received your issue.

    • A maintainer will respond within 3 business days.
    • Status stays at status: 待评估 (Triage); feel free to add context.
    • If we need more details, we'll add needs: 更多信息 and ping you.
  3. cocacocca commented on Jul 21, 2026

    @cocacocca
    Author
    "SubagentStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node C:\\Dev\\coca_plugin\\sap\\hooks\\subagent-start.js",
            "async": false
          },
          {
            "type": "command",
            "command": "node C:\\Dev\\coca_plugin\\sap\\hooks\\rules-injector.js",
            "async": false
          }
        ]
      }
    ],
    

    hooks.json其中的一块,现在启动都是这样的,如果我不去写log我都不清楚能不能调用,相比之下trae ide的hooks触发器很好,但是也缺少了完整能力

  4. panda920 commented on Aug 17, 2026

    @panda920
    Collaborator

    📌 已把重复反馈合并到这条

    以下 issue 反映的是同一个问题,已合并到这里统一跟进:#32、#154、#185

    共同根因:hooks 在配置/插件里注册成功、UI 也显示已加载,但运行时多个事件(Stop、PreToolUse、SubagentStart/Stop 等)从不触发,导致依赖 hook 的插件(dcg、SAP 等)整体失效。

    独立反馈人数:4

    优先级已从 P2 调整为 P1。

    后续进展只会更新在这条 issue 下,被合并的几条已关闭并打上 duplicate。如果你认为其中某条其实是另一个问题,在那条下面回复,我们会重新拆出来。


    📌 Duplicate reports consolidated here

    The following issues describe the same problem and are now tracked here: #32, #154, #185

    Shared root cause: Hooks register successfully in config/plugins and show as loaded in the UI, but several events (Stop, PreToolUse, SubagentStart/Stop, …) never fire at runtime, which breaks any plugin built on hooks (dcg, SAP, and others).

    Distinct reporters: 4

    Priority raised from P2 to P1.

    Updates will only be posted on this issue; the merged ones are closed and labelled duplicate. If you think one of them is actually a different problem, reply there and we'll split it back out.

  5. added
    priority: P1
    and removed
    priority: P2
    on Aug 17, 2026
  6. ivbrajkovic commented on Aug 17, 2026

    @ivbrajkovic

    Additional root cause + reproduction for the "hooks never fire" family — subagent sessions (Windows 11, engine 0.16.3, build 81fa9054)

    Complementing the reports consolidated here, we isolated a subagent-specific propagation gap that is narrower and more precisely diagnosable than the general event-detection problem — with a one-line fix candidate.

    Observed split: user-scope hooks in ~/.zcode/cli/config.json fire correctly for main-agent tool calls, but never for subagent tool calls — for every event, not only the ones missing from the runtime.

    Root cause (de-minified zcode.cjs 0.16.3):

    1. Every tool-event hook dispatch no-ops unless the session has a hookRunner.
    2. A session gets a runner only if its own config has hooks.enabled and an executionPort exists.
    3. The subagent_child runtime is constructed with a field-by-field config literal that includes executionPort but omits hooks — so the child never gets a runner, even with user-scope hooks fully enabled.

    Reproduction (2026-08-16): enable a user-scope PostToolUse hook (no matcher) that appends {session_id, tool_name, tool_use_id} to a JSONL file; in one fresh session, ask the agent to Read a file, then to spawn a subagent that Reads the same file. Observed: one log entry — the main agent's Read. The subagent's Read executed (its reply quotes the content; the call is present in ~/.zcode/cli/rollout/model-io-sess_<child>.jsonl) but produced no hook entry.

    Fix candidate: include the parent's hooks config in the child config projection (hooks: this.config.hooks) for subagent_child (and the workflow_child sites). We run a local proof-of-concept patch that does exactly this, filtered to PostToolUse — a Stop/continue hook would make every subagent loop forever, and PreToolUse in a child would race the parent's gating — verified working on engine 0.16.3 (local, win32) and 0.15.0 (CDN-deployed remote, darwin-arm64). Happy to share the patch and the probe harness that demonstrates both the gap and the fix.

    Related: even with propagation, hook payloads carry no agent_type, so consumers must reverse-engineer child session ids (sess_subagent_agent_*) to attribute activity — the payload-contract enrichment tracked in #44 would cover that.

  7. ChiahungTai commented on Aug 24, 2026

    @ChiahungTai

    补充一个本家族之外的精确变体(已单独开 #357):同一注册条目 startup source 正常派发、仅 /compact 后零派发(engine 0.16.5,主 session 非 subagent,matcher 变因已用无 matcher 注册排除)。与「注册成功但从不触发」的根因描述不同——SessionStart 事件本身是活的,问题定位可能在 compact 流程未走 SessionStart 派发路径。若你们判断应并入本条统一跟进也可以,证据链在 #357。

  8. Arteiimis commented on Sep 4, 2026

    @Arteiimis

    +1,补充一个具体的受影响案例,供评估参考:

    ponytail 的规则注入依赖 SessionStart(主会话)与 SubagentStart(子代理)两个事件:前者已通过 hookSpecificOutput JSON 输出修复并实测可用(ponytail#799);后者在 ZCode 下注册即被运行时静默丢弃——主 agent 派出的子代理收不到任何已注入规则。

    与 #361 互补的是:即便用 PreToolUse + Agent matcher 在派发侧注入,#361 表明子代理内部的工具调用也不经过钩子,子代理仍是钩子盲区。

    诉求(二选一即可):

    1. 支持 SubagentStart / SubagentStop,与 Claude Code 语义对齐;
    2. 或在官方文档明确替代方案,并说明 PreToolUse 的 additionalContext 能否到达子代理上下文。

    环境:ZCode 3.10.2 / Windows 11。

  9. Josephur commented on Sep 19, 2026

    @Josephur

    +1 specifically for PreCompact / PostCompact. I want to run an external context reducer (typesafe.ai) at the compaction boundary — it is significantly faster and more accurate than the built-in summarizer for my sessions — and there is currently no event to attach it to. PreCompact is the standard name for this in the Claude Code hook vocabulary this system is otherwise modelled on, so aligning here costs little in design and unblocks an entire category of context-management plugins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: P1status: 待评估type: 功能建议

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions