npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

pi-shepherd

v0.5.3

Published

Rules engine with context guardrails (line-count, compaction reminders, skill restore) for pi-coding-agent

Readme

English | 中文文档

📖 pi-atelier 实战指南 — 从零教会你使用 pi-atelier 扩展生态

pi-shepherd

源码仓库 | npm

pi-coding-agent 的 规则驱动行为守护系统 — 在工具调用、AI 回复、会话结束等关键节点,自动拦截、提醒或改写操作。

解决什么问题

AI 编程助手在长时间会话中容易跑偏:

  • 工具滥用:用 grep 搜符号名(应该用 code-graph)、用 bash cat 读文件(应该用 read)
  • 忘记收尾:改完代码不跑测试、不提交 git、不更新文档
  • 编码规范违反:TypeScript 用空格缩进(应该用 Tab)、Python 用 Tab(应该用空格)
  • 重复犯错:同一个错误反复出现,不知道翻看已有的踩坑记录
  • 压缩后失忆:上下文压缩把技能/设计文档正文挥发掉,AI 忘记自己拥有的能力 → 压缩后自动恢复(激活源:宿主 compaction readFiles,跨 resume 连续)

pi-shepherd 通过可配置的规则引擎,在这些关键节点自动介入,把最佳实践变成自动化的守护机制。

安装

pi install git:github.com/catlain/pi-shepherd

核心概念

钩子(Hook)

Shepherd 在 AI 工作流的 6 个关键节点插入钩子:

| 钩子 | 触发时机 | 典型用途 | |------|---------|---------| | tool_call | 工具即将执行前 | 拦截不当调用、改写命令 | | tool_result | 工具执行完成后 | 检查结果、触发后续动作 | | agent_end | AI 主动结束时 | 提醒提交 git、更新记忆 | | message_end | AI 每条回复完成后 | 检测回复中的问题模式 | | session_compact | 上下文压缩完成后 | 恢复挥发文档正文、压缩后提醒 | | session_shutdown | 会话关闭时 | 清理资源 |

动作(Action)

规则匹配后可以执行 4 种动作:

| 动作 | 效果 | |------|------| | block | 阻止工具执行,返回原因 | | notify | 弹出提醒,AI 可以选择忽略 | | steer | 注入下一轮对话,强制 AI 响应 | | rewrite | 改写工具参数后继续执行 |

条件匹配

单条件模式(简单场景):

{ "pattern": "\\bcat\\b", "flags": "" }

多条件模式(精确控制):

{
  "conditions": [
    { "field": "path", "pattern": "\\.ts$" },
    { "field": "text", "pattern": "\\n  [\\S ]" }
  ]
}

多个 conditions 默认是 AND 关系(全部满足才触发),可通过 conditionLogic: "or" 改为 OR。

内置条件(不需要正则):

| builtin | 检查内容 | |---------|---------| | git_dirty | 有已跟踪文件的未提交改动 | | git_untracked | 有未跟踪文件 | | has_edits | 本轮调用过 edit/write | | always | 始终匹配 |

有状态规则

通过 state 字段追踪工具调用统计,实现「N 次错误后提醒」等模式:

{
  "comment": "连续出错后提醒翻记忆",
  "hook": "tool_result",
  "action": "steer",
  "state": { "countKind": "errors", "gte": 5 },
  "reason": "工具反复出错,请检查记忆文件是否有踩坑记录"
}

支持三种计数方式:

  • calls:工具调用次数
  • errors:连续错误次数
  • chars:工具返回的字符量

配合 resetOn 可以在某个工具成功后重置计数(如测试通过后清零错误计数)。

规则格式

hook × action 支持矩阵(写错组合 = 写入被校验器拒绝;存量无效组合运行时仅警告):

| hook | 支持的 action | |------|--------------| | tool_call(缺省) | block / rewrite / notify | | tool_result | steer / notify | | message_end | steer / notify | | session_compact | steer | | agent_end / session_shutdown | notify |

  • hook 缺省归一化为 tool_call,action 缺省归一化为 block——校验与运行时同源(rules.ts HOOK_ACTION_SUPPORT)
  • tool 字段纯精确匹配(| 多值,无通配无后缀)——MCP 工具必须写全名 mcp__server__tool(写裸名永不命中)

完整的规则字段:

{
  "comment": "规则描述(必填,同时作为唯一标识)",
  "hook": "tool_call",
  "tool": "bash",
  "action": "block",
  "reason": "给 AI 看的提示信息",
  "pattern": "\\bcat\\b",
  "conditions": [{ "field": "path", "pattern": "\\.ts$" }],
  "conditionLogic": "and",
  "enabled": true,
  "state": { "countKind": "errors", "gte": 3 },
  "resetOn": ["bash"],
  "subagent": false,
  "requiresTools": ["code_graph_semantic_code_search"],
  "requireSuccess": true,
  "stopReason": ["stop"]
}

必填字段:comment、reason

可选字段说明:

  • enabled:false 禁用规则(默认 true,可省略)
  • subagent:false 表示子代理中跳过此规则
  • requiresTools:只有这些工具都可用时才触发
  • requireSuccess:true 表示跳过 isError 的 tool_result
  • stopReason:agent_end 专用,限制只在特定结束原因时触发

规则存放位置

全局规则:~/.pi/agent/extensions/shepherd/rules.json(所有项目生效)

项目规则:{cwd}/.pi/extensions/shepherd-rules.json(仅当前项目生效) 或 {cwd}/.pi/extensions/shepherd-rules-*.json(多文件)

项目规则和全局规则合并执行,项目规则可以补充或覆盖全局规则。

管理规则

使用 shepherd_rules 工具安全编辑规则(自动校验格式、备份、回滚):

# 列出所有规则
shepherd_rules(action: "list")

# 添加规则
shepherd_rules(action: "add", rule: { comment: "...", hook: "...", ... })

# 更新规则
shepherd_rules(action: "update", index: 2, changes: { enabled: false })

# 删除规则
shepherd_rules(action: "delete", index: 3)

update 分层校验与生效说明

update 采用分层校验:changes 中出现的字段严格校验(非法即拒绝);合并后规则里的历史遗留问题降级为警告(不阻塞写入),警告文本附修复指引。

注意生效时机:shepherd_rules 修改的是磁盘上的规则文件,运行中的匹配引擎仍用启动时加载的副本——源码或规则更新后需重载扩展(重启会话或触发扩展重载)才对后续工具调用生效。可用一条含 command field 的 update 冒烟验证新逻辑已生效。

/compact-config 命令

管理压缩行为配置(两段式子命令,无参查看现值与用法):

/compact-config                 # 查看:恢复注入配置 + 当前模型压缩触发点
/compact-config tokens 50000    # 设恢复注入预算 maxTokens(1000~400000)
/compact-config tokens on|off   # 开关压缩后恢复注入
/compact-config trigger 200000  # 设当前模型自动压缩触发点(达到即压缩)
/compact-config trigger         # 删当前模型触发点,回默认(接近满窗口触发)
  • tokens 写 shepherd.contextRestore(压缩后恢复注入的预算/开关)
  • trigger 以「触发点」语义管理 pi 内置自动压缩:内部换算 reserveTokens = contextWindow − trigger,写入全局 settings.json 的 compaction.modelOverrides["{provider}/{id}"](例:1M 窗口设 200000 → reserveTokens=800000,即 200k 触发压缩)。触发点有效区间随模型窗口变化
  • 配置改动新会话生效

实战示例

1. 编辑 Python 后自动跑测试

{
  "comment": "编辑 Python 后跑测试",
  "hook": "tool_result",
  "tool": "edit",
  "action": "notify",
  "conditions": [{ "field": "path", "pattern": "\\.py$" }],
  "reason": "编辑了 Python 文件,请运行 ruff check 和单元测试"
}

2. 会话结束前检查 git

{
  "comment": "会话结束检查 git",
  "hook": "agent_end",
  "action": "notify",
  "conditions": [
    { "builtin": "git_dirty" },
    { "builtin": "git_untracked" }
  ],
  "conditionLogic": "or",
  "reason": "Git 有未提交改动,请确认是否需要 commit + push"
}

3. 拦截 grep 搜代码,推荐 code-graph

{
  "comment": "推荐 code-graph 替代 grep",
  "hook": "tool_result",
  "tool": "grep",
  "action": "notify",
  "pattern": ".",
  "reason": "搜代码推荐用 code-graph:semantic_code_search(模糊)、get_ast_node(精确)、find_references(引用)",
  "requiresTools": ["code_graph_semantic_code_search"]
}

4. 拦截 AI 回复中的归因猜测

{
  "comment": "禁止归因猜测",
  "hook": "message_end",
  "action": "steer",
  "pattern": "(可能是|猜测|大概|也许是).*(jiti|缓存|工具链)",
  "reason": "不要猜测根因——先查自己的代码逻辑,搜索最佳实践,验证后再下结论"
}

5. 禁止直接编辑 settings.json

{
  "comment": "禁止直接编辑 settings.json",
  "hook": "tool_call",
  "tool": "edit|write",
  "action": "block",
  "conditions": [{ "field": "path", "pattern": "settings\\.json$" }],
  "reason": "直接编辑 settings.json 曾导致配置丢失,必须使用 settings_patch 工具"
}

架构

pi-shepherd/
├── index.ts              # 入口:注册所有钩子
├── shepherd/
│   ├── rules.ts          # 规则类型定义 + 加载/编译/匹配
│   ├── conditions.ts     # Condition 类型 + builtin 条件匹配
│   ├── state-tracker.ts  # 有状态规则的状态追踪器
│   ├── tool-hooks.ts     # tool_call / tool_result 钩子处理
│   ├── message-end.ts    # message_end 钩子处理
│   ├── rules-tool.ts     # shepherd_rules 工具注册
│   ├── rules-editor.ts   # 规则文件安全编辑(备份+校验)
│   ├── rules-validate.ts # 规则格式校验
│   ├── ephemeral.ts      # 提示缓冲区(pushWarning)
│   ├── git.ts            # git 状态检查工具函数
│   └── worktree-check.ts # worktree 环境检测
├── rules.json            # 默认全局规则
└── tests/                # 测试

依赖:

  • @pi-atelier/shared-utils — 配置 API、工具输出格式化
  • @earendil-works/pi-coding-agent — ExtensionAPI(peer)

License

MIT