本篇覆盖 crates/atomcode-capabilities 中除 MCP(第 16 篇)以及 tools、codeintel、session、compaction、memory、migration、provider、subagent、team、setup、world、notify、atomgit、file_index、worktree_status、datalog 之外的所有能力模块:
| 能力 | 位置 | feature |
|---|---|---|
| 插件市场与安装 | src/plugin/(11 个文件,约 6.4k 行) |
plugin |
| Skills 发现、渲染与调用 | src/skills/(8 个文件,约 5.4k 行) |
skills |
| Claude Code 兼容外部 hooks | src/cc_hooks.rs(3086 行)+ src/cc_hooks/inspection.rs(378 行) |
cc-hooks |
| 线路日志 hooks | src/hooks.rs |
总是编译 |
| 杂项基础设施 | reminder、jsonc、product_dirs、process_utils、git_branch、pathnorm、pathutil、proxy、fs、image_normalize、instructions、search、model_cards、askpass/ |
见 §3 |
这三大能力有一个共同点:它们都在把 Claude Code(CC)生态资产“无改动地”搬到 AtomCode 中使用。CC 的 marketplace 和 plugin 清单、SKILL.md 和 commands/*.md、CC hooks 的 JSON 协议(hookSpecificOutput、退出码 2)都被原样接受。同时,针对“第三方代码执行”这一风险,AtomCode 增加了三道 CC 原本没有的闸门:
源码基线:AtomCode 5.2.8。行号以该版本为准。
| 模块 | 负责 | 不负责 |
|---|---|---|
plugin |
marketplace 的 git clone / pull、插件安装(user / project / local 三种 scope)、首启引导、24h 节流自动更新、插件资产(skills / commands / hooks)枚举、hooks 内容哈希信任 | 不执行 hook(由 cc_hooks 执行),不解析 skill(由 skills 解析) |
skills |
从调用方给定的目录扫描 *.md / */SKILL.md、frontmatter 解析、模板展开($ARGUMENTS、${CLAUDE_SKILL_DIR}、!`cmd`)、预算化目录渲染、use_skill / list_skills 工具、调试类 skill 自动加载判定 |
标准目录优先级由“驱动方”决定(standard_skill_dirs 只是一个可选的默认值) |
cc_hooks |
8 个 CC 事件、hooks.json 加载、matcher、子进程执行与超时、决策折叠、required_approval 外部审批、插件脚本入口校验 |
不负责插件信任存储(在 plugin::hook_trust 中) |
| 杂项 | 产品目录注入、路径规范化、代理与 TLS 策略、原子写、图片压缩、项目指令三层加载、CJK 关键词评分、sudo / ssh askpass | — |
L1 约束:capabilities 不能依赖 atomcode-core。因此 pathnorm、pathutil、process_utils、proxy、fs 都是从 core “复制一份”的本地版本(pathnorm.rs 文件头明确写了这一点:“capabilities keeps its own copies”)。
graph TD
subgraph 驱动方
tui[atomcode-tuix<br/>/plugin /skills /hooks]
cli[atomcode-cli<br/>plugin/hooks 子命令]
coding[atomcode-coding<br/>prepare/mount]
daemon[atomcode-daemon]
end
subgraph capabilities
boot[plugin::bootstrap]
mp[plugin::marketplace]
inst[plugin::installer]
loader[plugin::loader]
ht[plugin::hook_trust]
man[plugin::manifest]
skreg[skills::registry]
sk[skills::skill]
render[skills::render]
hook[skills::catalog_hook]
auto[skills::auto_load]
us[skills::use_skill]
cch[cc_hooks::CCExternalHooks]
insp[cc_hooks::inspection]
rem[reminder]
jsonc[jsonc]
pd[ProductDirs]
fs[fs::atomic_write]
pu[process_utils]
end
kernel[atomcode-kernel<br/>LifecycleHooks / ToolMiddleware / Tool]
cfg[atomcode-config<br/>Config.plugin / endpoints]
auth[atomcode-auth<br/>登录 token]
tui & cli --> boot & mp & inst
coding --> loader & skreg & cch & hook
boot --> mp & inst
mp --> auth
inst --> mp & man
loader --> man & ht & skreg
ht --> fs
ht -.cc-hooks.-> cch
cch --> jsonc & rem & pu
cch --> kernel
skreg --> sk & render
hook --> render & kernel
us --> skreg & kernel
auto --> skreg
sk --> pu
boot --> cfg
关键依赖方向:
plugin::loader 产出与 cc_hooks 无关的中性数据 PluginCcHook,由驱动方转换成 HookConfig::from_plugin_spec,再通过 CCExternalHooks::load_with_extra 传入(cc_hooks.rs:132 的注释写明“L1 cannot reach the plugin loader”)。skills::SkillRegistry 保持来源中立,插件 skill 目录由 plugin::loader::reload_skill_registry 叠加上去(loader.rs:387)。| 文件 | 行数 | 职责 |
|---|---|---|
mod.rs |
57 | 公开 API 和 PluginJobEvent(TUI 后台任务结果:MarketplaceAdded/Updated、PluginInstalled/Updated、PluginAlreadyInstalled、Failed{op,msg}、GitNotFound) |
manifest.rs |
534 | MarketplaceManifest、PluginEntry、PluginSource(Inline / External / Unknown)、ExternalSource(url / git / github / git-subdir / local)、GitPin、PluginManifest、CC hooks 类型 |
paths.rs |
212 | <user>/plugins/{marketplaces/, marketplaces.json, installed_plugins.json}、项目 scope 路径、scope_state_file_aliases_user_scope |
state.rs |
170 | InstallScope、MarketplacesFile、InstalledPluginsFile 的 JSON 读写,plugin_id = "<plugin>@<marketplace>" |
url.rs |
237 | validate_git_url(https / http / ssh / git@host: / file)、名称推断、host_is_trusted、scheme_host_prefix |
marketplace.rs |
1410 | find_git、add_marketplace、update_marketplace(pull --ff-only)、remove_marketplace、list_marketplaces;加固过的 git 命令;对受信 host 注入登录凭据重试 |
installer.rs |
1719 | install、ensure_plugin_installed、uninstall、list_installed;外部源 clone / sparse checkout / 本地拷贝 |
bootstrap.rs |
613 | run_startup_hooks:首启安装默认 marketplace、24h 节流自动更新 |
loader.rs |
1035 | iter_installed_plugin_assets_for、installed_plugin_cc_hooks(仅返回已信任的 hooks)、installed_plugin_hook_trust_status、installed_plugin_skill_dirs、reload_skill_registry |
hook_trust.rs |
366 | plugin_hook_set_hash、plugin_content_hash、hook_trust.json |
test_support.rs |
32 | 测试辅助 |
| 文件 | 行数 | 职责 |
|---|---|---|
mod.rs |
58 | 导出、skill_tool_names()、register_skill_tools |
registry.rs |
1717 | SkillRegistry(扫描、索引、诊断、get 别名解析)、standard_skill_dirs、skill_install_dirs、SkillRoots |
skill.rs |
1218 | Skill、AutoLoad、frontmatter 解析、expand / expand_for_injection / expand_static_for_injection |
render.rs |
524 | === AVAILABLE SKILLS === 目录渲染:8000 字节预算、来源排序 |
use_skill.rs |
424 | UseSkillTool、ListSkillsTool(风险等级 Safe) |
auto_load.rs |
687 | 保守的任务分类:调试类或浏览器类 skill 的自动选择 |
spelling.rs |
169 | 编辑距离为 1 的拼写建议(只提示,不纠正) |
catalog_hook.rs |
128 | SkillCatalogHook:会话开始时注入目录 system 消息 |
| 文件 | 行数 | feature / cfg | 职责 |
|---|---|---|---|
cc_hooks.rs |
3086 | cc-hooks |
HookEvent、HookConfig、HooksFileStatus、CCExternalHooks(同时实现 LifecycleHooks 和 ToolMiddleware) |
cc_hooks/inspection.rs |
378 | cc-hooks |
atomcode hooks list/paths/test 的只读检查与测试执行(30s 上限) |
hooks.rs |
266 | 总是 | WireLogHooks:在 on_request / on_model_response 中输出中性的请求与响应日志 |
reminder.rs |
81 | 总是 | <system-reminder> 约定的唯一实现 |
jsonc.rs |
188 | 总是 | strip_comments(不允许尾逗号);migration feature 下另有允许尾逗号的版本 |
product_dirs.rs |
108 | 总是 | ProductDirs { user, project_dir_name }:产品目录由宿主注入 |
process_utils.rs |
477 | 总是 | Windows CREATE_NO_WINDOW、Job Object、taskkill_tree、shell_command、UTF-8 locale、is_running_as_admin |
git_branch.rs |
81 | 总是 | 不启动 git 进程,直接解析 .git/HEAD 得到分支名 |
pathnorm.rs |
133 | 总是 | 去掉 Windows \\?\ 前缀、path_case_key、to_display(正斜杠) |
pathutil.rs |
257 | 总是(pub(crate)) | SKIP_DIRS、~ 展开、real_home_dir |
proxy.rs |
123 | provider / web / atomgit / grape / mcp 任一开启 | ATOMCODE_PROXY_MODE、ATOMCODE_TLS_MAX |
fs.rs |
114 | plugin 或 mcp | atomic_write(path, bytes, mode) |
image_normalize.rs |
554 | tools |
长边上限 1568px,目标约 512KiB,fail-open |
instructions.rs |
387 | instructions |
GLOBAL / PROJECT / USER 三层指令 |
search.rs |
274 | search |
CJK bigram 关键词评分 |
model_cards.rs |
94 | 总是 | 离线模型评测目录(include_str!("../../../data/model-cards.json")) |
askpass/ |
612 | cfg(unix) |
Unix socket 加 wrapper 脚本,把 sudo / ssh 的密码提示转到宿主 UI |
plugin/manifest.rs、plugin/state.rs)pub struct MarketplaceManifest { pub name: String, pub plugins: Vec<PluginEntry> }
pub struct PluginEntry { pub name: String, pub source: PluginSource,
pub description: Option<String>, pub version: Option<String> }
#[serde(untagged)]
pub enum PluginSource {
Inline(String), // "./"、"plugins/foo":marketplace 仓库内的路径
External(ExternalSource), // {"source": "url|git|github|git-subdir|local", ...}
Unknown(serde_json::Value), // 未知类型:跳过这一项,不让整个目录解析失败
}
#[serde(tag = "source", rename_all = "kebab-case")]
pub enum ExternalSource {
Url { url, #[flatten] pin: GitPin }, Git { url, pin },
Github { repo, pin }, // → https://github.com/<repo>.git
GitSubdir { url, path, pin }, // sparse + partial clone
Local { path },
}
pub struct GitPin { branch, tag, #[alias="sha"] commit, #[rename="ref"] git_ref }
pub struct PluginManifest { // 所有字段都可选
name, version, description,
skills: Option<PathOrList>, // "skills" | ["./skills/a", "./skills/b"]
commands: Option<PathOrList>,
hooks: Option<HooksField>, // "hooks.json" | 内联 CC hooks map
}
pub type CCHooksMap = BTreeMap<String /*PascalCase 事件*/, Vec<CCHookGroup>>;
pub struct CCHookGroup { matcher: Option<String>, hooks: Vec<CCHookSpec> }
pub struct CCHookSpec { #[rename="type"] kind /*="command"*/, command, args: Vec<String>,
timeout: Option<u64> /*秒*/ }
pub enum InstallScope { User /*默认*/, Project, Local }
PluginSource::Unknown 的来由:manifest.rs 注释引用了 anthropics/claude-plugins-official#585——一个 git-subdir 条目曾让只认识旧标签的客户端整个目录都解析失败。
清单查找顺序(找到第一个即停止;文件存在但无法解析则报错,fail-closed):
| 清单 | 顺序 |
|---|---|
| marketplace | .atomcode-plugin/marketplace.json → .claude-plugin/marketplace.json → 都没有时进入单插件模式(marketplace 名 = 插件名 = 目录名) |
| plugin | .atomcode-plugin/plugin.json → .claude-plugin/plugin.json → plugin.json → 都没有时用默认清单 |
另外,loader.rs 有一条自动探测规则:如果没有清单,而插件目录下直接有 SKILL.md,就把 skills 设为 "./"。这是为了兼容从 CC marketplace 用 git-subdir 安装、目录本身就是一个 skill 的情况。
<user>/plugins/ (= ~/.atomcode/plugins)
├── marketplaces.json {"version":1,"marketplaces":{"<name>":{source,added_at,git_commit,plugins:[..]}}}
├── installed_plugins.json {"version":1,"plugins":{"<plugin>@<mp>":{marketplace,plugin,plugin_dir,installed_at,scope}}}
├── hook_trust.json {"<plugin>@<mp>":"<sha256 hex>"} (atomic_write 0600)
├── .hook_trust_migrated 迁移边界标记
├── marketplaces/<mp>/ git clone 的 marketplace 仓库
│ └── .tmp-<pid>-<nanos>/ add 过程中的临时 clone
└── installed/<mp>/<plugin>/ External 源的独立 clone 或拷贝
<project>/.atomcode/plugins/ Project scope(提交到 git)
<project>/.atomcode/plugins/local/ Local scope(git-ignored)
<user>/.plugin_bootstrap_v2 首启引导标记
<user>/.marketplaces_refreshed_at RFC3339 时间戳,24h 节流
<user>/stderr.log 引导失败日志(直接写文件,不写 stderr)
plugin_dir 是相对于 plugins 根目录的路径,例如 marketplaces/foo/plugin-a 或 installed/foo/bar/sub。scope_state_file_aliases_user_scope:在 $HOME 下运行时,项目目录 ~/.atomcode 就是用户树,两份状态文件其实是同一个文件。需要跳过这种情况,否则每个插件会被列出两次。state.rs 使用普通的 std::fs::write 而非 atomic_write。只有 hook_trust.json 使用原子写和 0600 权限。marketplace.rs:172 add_marketplace)validate_git_url(url) // 只接受 https/http/ssh/git@host:/file,且必须有 host 和仓库路径
url_tail = infer_marketplace_name_from_url(url)
git_clone(url, marketplaces/.tmp-<pid>-<nanos>)
└─ git_command(): GIT_TERMINAL_PROMPT=0, GCM_INTERACTIVE=never,
GIT_SSH_COMMAND="ssh -oBatchMode=yes", stdin=null
└─ 匿名 clone 失败且属于认证失败 + host_is_trusted(url) + 已登录:
删除半成品 → 加 -c http.<scheme://host>.extraHeader="Authorization: Basic <user:token>" 重试一次
commit = git rev-parse HEAD
manifest = load_marketplace_manifest(tmp)
mp_name = sanitize_name(manifest.name 或 url_tail) // 防止 "../"、绝对路径逃逸
同名已注册 / 目标目录已存在 → 报错(不覆盖)
rename(tmp → marketplaces/<mp_name>) // 原子落位
marketplaces.json 中写入 {source, added_at, git_commit, plugins}
两个安全要点:
GIT_TERMINAL_PROMPT=0 的原因(见 marketplace.rs:313 的注释):TUI 处于 raw mode 时,git 会直接打开 /dev/tty 询问用户名,导致整个 UI 死锁,连 Ctrl-C 都不起作用。atomcode_config::endpoints::is_trusted_host 白名单内的 host。注入用 http.<scheme://host>.extraHeader 限定作用域,跨 host 重定向时不会泄露凭据。installer.rs:560 install)flowchart TD
A[install(dirs, plugin, mp, scope)] --> B{mp 已注册? plugin 在 entry.plugins?}
B -- 否 --> X1[Err]
B -- 是 --> C[load_marketplace_manifest 找到 PluginEntry]
C --> D{source}
D -- Inline --> D1[validate_plugin_source<br/>plugin_dir = marketplaces/mp/sub]
D -- External 且 URL 等于 marketplace 源且无 pin --> D2[复用 marketplace clone]
D -- External --> D3[install_external → installed/mp/plugin<br/>url/git/github: git clone + pin<br/>git-subdir: clone --filter=blob:none --no-checkout --depth 1<br/>+ sparse-checkout set --no-cone + checkout<br/>local: validate_copy_paths + copy_plugin_tree]
D -- Unknown --> X2[Err: unsupported source type]
D1 & D2 & D3 --> E{scope}
E -- User --> F[installed_plugins.json<br/>已存在且目录还在 → AlreadyInstalledError]
E -- Project/Local --> G[把文件拷贝到 <project>/.atomcode/plugins[/local]/<br/>并写项目级 installed_plugins.json]
ensure_plugin_installed(installer.rs:779)是一个幂等的组合操作:先 add marketplace(忽略 “already exists”),marketplace 目录丢失时重新 clone,然后以 User scope 安装。
bootstrap.rs:118 run_startup_hooks)find_git() 失败 → 写 stderr.log,返回 [GitNotFound](两项计划都跳过)
Plan A(config.plugin.auto_install_default_skills,默认 true):
.plugin_bootstrap_v2 不存在时:
for url in endpoints::plugin_marketplaces():
已注册 → 复用;否则 add_marketplace
若 url ∈ endpoints::plugin_auto_install():安装其所有插件
写入标记(无论成功或失败都写,只尝试一次)
Plan B(config.plugin.auto_update_marketplaces,默认 true;非离线;距上次超过 24h):
对每个已安装的 marketplace 执行 git pull --ff-only;HEAD 变化时补装新增的插件
多条失败合并为一条摘要(collapse_auto_update_failures)
写入 .marketplaces_refreshed_at(未来时间戳也视为“到期”,避免卡死)
$ATOMCODE_HOME/stderr.log,不用 eprintln!。原因是 Windows raw mode 下,stderr 的输出会出现在 TUI 的输入框里。git.exe 会触发 Windows 杀毒软件的启发式检测(“remote thread injection”)。_v2)。需要“让所有老用户重新引导一次”时,只要改版本号即可。hook_trust.rs + loader.rs:187)sequenceDiagram
participant D as 驱动方 (prepare)
participant L as loader::installed_plugin_cc_hooks
participant H as hook_trust
participant C as cc_hooks::validate_plugin_hook
D->>L: dirs
loop 每个已安装插件
L->>L: plugin_all_cc_hooks(manifest 内联 + hooks 文件,去重)
L->>H: plugin_hook_set_hash(hooks)
H->>H: sha256(排序后的 (event, matcher, command, args),每个字段带长度前缀)
H->>H: + plugin_content_hash(root):遍历包内所有文件(跳过 .git,链接不得逃出根目录)
H->>C: 逐个校验入口(cc-hooks feature)
alt 校验失败
H-->>L: "invalid:<meta>: <reason>"
L->>L: warn,并扣下该插件的全部 hooks
else
H-->>L: hex hash
L->>H: is_trusted(trust_map, "<plugin>@<mp>", hash)
alt 已信任
L-->>D: 返回该插件的 hooks
else 未信任
L-->>D: 不返回(直到用户执行 atomcode plugin trust)
end
end
end
plugin-hook-argv-v1\0 域前缀;没有 args 时保持旧哈希不变,以兼容旧版本。ensure_migrated 只写迁移标记,不会把旧的“只按命令文本授权”的信任转换成内容授权(需要显式重新信任)。HookConfig.plugin_content_hash 记录的是加载时的内容哈希。每次执行前 plugin_hook_command 会重新计算(在 spawn_blocking 中,受 timeout 限制);内容不一致时返回 {"decision":"block"},即 fail-closed。iter_installed_plugin_assets_for(dirs, working_dir)
User scope: <user>/plugins/installed_plugins.json
Project / Local scope: <project>/.atomcode/plugins[/local]/installed_plugins.json
(若与 User scope 是同一文件则跳过)
plugin_dir 不存在的条目直接跳过(容忍手动删除)
→ InstalledPluginAssets { plugin, marketplace, plugin_dir, manifest, scope }
skills_dirs() = manifest.skills_paths()(默认 ["skills"])
commands_dir() = manifest.commands_path()(默认 "commands")
hooks_file() = manifest.hooks_path()(默认 "hooks.json";也会找 hooks/ 子目录)
→ installed_plugin_skill_dirs:(dir, namespace=plugin 名, TemplateKind::Command|Skill),同一目录去重
→ reload_skill_registry:先 registry.reload(标准目录),再对每个插件目录调用
load_template_dir(dir, Some(plugin), kind)
插件 skill 的名称形如 <plugin>:<skill>,带命名空间。
pub enum AutoLoad { Unspecified, Debugging, BrowserUse, Never } // skill.rs:14
pub struct Skill { // skill.rs:23
pub name: String, // 小写;make_name 把 '/' 换成 '-';有命名空间时为 "ns:name"
pub display_name: Option<String>, // 只用于展示,不参与解析
pub description: String, // 缺省取正文首段
pub template: String,
pub allowed_tools: Vec<String>, // 本回合内宿主可以预授权的工具(不是排他清单)
pub user_invocable: bool, // false 时不出现在 / 菜单,但模型仍可调用
pub auto_load: AutoLoad,
pub args_requirement: ArgsRequirement, // Unspecified|Required|Optional|None
pub skill_dir: PathBuf, pub source_path: PathBuf,
}
pub enum TemplateKind { Skill, Command }
pub type TemplateDirectory = (PathBuf, String /*namespace*/, TemplateKind);
pub struct SkillRoots<'a> { home: &Path, project: &Path, dirs: &ProductDirs }
frontmatter(skill.rs:425 parse_frontmatter)是逐行解析的,不依赖 YAML 库,支持 ---\n 和 ---\r\n。可识别的键:
| 键 | 说明 |
|---|---|
name: |
覆盖默认名称。校验规则:1~64 个 Unicode 字符;只允许字母数字和 -_/;不能以 / 或 - 开头或结尾;不能有 // 或 -- |
display-name: |
展示标题 |
description: |
描述 |
allowed-tools: / allowed_tools: |
支持单行列表或 YAML 块列表。嵌套列表、一行多个工具、重复声明都视为错误:拒绝加载该 skill,而不是降级成宽松的授权 |
auto-load: |
debugging / browser-use / off;未知值或重复声明会产生诊断,并只关闭自动加载 |
user-invocable: |
布尔值 |
args: |
required / optional / none,大小写不敏感 |
版本化安装目录(例如 atomgit-1.0.0)会去掉版本号,得到可调用名称 atomgit(unversioned_install_name)。
registry.rs:957 standard_skill_dirs,从低到高优先级)1 ~/.claude/commands
2 <user>/commands (~/.atomcode/commands)
3 ~/.claude/skills
4 ~/.agents/skills 跨 agent 约定(opencode 等);放在 .claude 与自家目录之间
5 <user>/skills
6 <project>/.claude/commands
7 <project>/.atomcode/commands
8 <project>/.claude/skills
9 <project>/.agents/skills
10 <project>/.atomcode/skills ← 最高
(另有 config.toml 中的 [skills] extra_dirs:在标准目录之前扫描,同名时标准目录优先;extra_dirs 之间,靠后的优先)
(再加上插件目录,带命名空间)
skill_install_dirs 返回 (<user>/skills, <project>/.atomcode/skills),即同级中“会胜出”的目录。测试 install_dirs_are_the_winning_dirs_of_the_standard_list 把两者绑定在一起,防止它们分别演变后不一致。
扫描规则(scan_skill_dir,registry.rs:600 起):
*.md 是平铺的命令或 skill(commands 目录下为 TemplateKind::Command)。SKILL.md 就是一个 skill,不再向下递归(目录里的其它文件视为资源)。SKILL.md 的子目录是分组目录,继续递归,最大深度 MAX_DEPTH = 8。.venv、venv、node_modules、.git、.hg、.svn、__pycache__、.pytest_cache、.mypy_cache、.ruff_cache、.tox、.nox。注意不是跳过所有隐藏目录,.system 之类的分组仍会被扫描。symlink_metadata 识别悬空链接或 FIFO 形式的 SKILL.md,并给出诊断,而不是让它静默消失。名称解析(registry.rs:771 get):
精确匹配 → "skills:<bare>" 别名 → 名称含 ':' 则返回 None
→ 按后缀 ":<name>" 匹配:只有一个命中则返回它
多个命中但其中只有一个 user_invocable 则返回该个
否则视为歧义,返回 None
skill.rs:61 expand)——替换顺序是一条安全边界1. 先替换受信变量:${CLAUDE_SESSION_ID}、${CLAUDE_SKILL_DIR}
2. 再执行模板自带的 !`cmd`(sh -c,UTF-8 locale,Windows 下不弹窗)
3. 最后单次从左到右替换参数:$ARGUMENTS[N]、$N、$ARGUMENTS
替换进去的值不会被再次扫描(参数里含 $1 或 !`rm` 也只是普通文本)
4. 模板中没有 $ARGUMENTS 且参数非空时:在末尾追加 "\n\nARGUMENTS: <args>"
expand_for_injection:如果 skill 来自目录形式的 SKILL.md,在正文前加一段 <system-reminder>,说明“本 skill 安装在 X,scripts/ 和 references/ 相对于该目录解析,不要在工作目录中搜索”。
expand_static_for_injection(自动加载专用)在以下情况拒绝展开:
| 条件 | 返回 |
|---|---|
模板含 !` |
dynamic_shell |
需要参数(args: required、模板含 $ARGUMENTS 或 $<数字>) |
arguments_required |
| 模板超过 12KiB,或展开结果超过 16KiB | body_budget |
use_skill {name, arguments?}:风险等级为 Safe(skill 被视为受信的用户内容)。名称未找到时返回所有可用名称,并提示“不要猜测其它名称”。展开放在 spawn_blocking 中执行,因为可能要运行 shell。list_skills:列出全部 skill,用于发现在目录中被省略的 skill。SkillCatalogHook(catalog_hook.rs):在 session_start 时,把 render_catalog() 的结果作为 Role::System 消息插入到开头连续的 system 消息之后。用 CATALOG_HEADER 标识该消息,--resume 时原地刷新,不会重复累积;没有 skill 时删掉旧的目录消息。目录在会话期间冻结。render.rs):
CATALOG_BYTE_BUDGET = 8000,单条描述上限 PER_SKILL_DESC_CAP = 1024。source_rank 排序保留:0 = 原生(自家用户树或项目树)、1 = .claude、2 = .agents、3 = 其它;被省略时提示调用 list_skills。render_catalog_prioritizing(instruction_text):在项目指令里被精确提到的 skill 排在最前。GUIDANCE 段落要求模型:描述匹配时,必须先 use_skill 再采取任何行动;bug、失败的测试也算匹配;不要猜名称;尊重用户“不要用 skill”的要求。auto_load.rs:416 select)browser = browser_task_reason(prompt).is_ok() 且存在 AutoLoad::BrowserUse 的 skill
非 browser 时:task_reason(prompt) 必须是明确的故障表达
(例如“测试失败”“Fix this regression”);
以下情况跳过:改名、格式化、翻译、报错只出现在引用或代码块里、
用户写了 [no-auto-skills] 或明确说不要使用技能
候选等级:Debugging=2;Unspecified 只兼容名称为 systematic-debugging 或
atomcode-workflows:debug、且描述中含 debug/bug/test fail/调试/故障 的 skill,等级 1;
Never 跳过
取最高等级:只有一个候选则 Load(skill),多个候选则 Skip("ambiguous_skills")
自动加载的内容通过 harness 的 StepDecision → Injected(Reminder) 写入会话日志(见 docs/automatic-skills.md)。它不会激活 allowed-tools,也不执行 shell。日志 target 为 atomcode_skills。宿主可以用 HostPlugins 的 [[patch]] id="skills" config={auto_load=false} 关闭此功能。
spelling.rs:支持单字符增、删、改,相邻字符交换,以及大小写、-、_ 的差异,最多给出 3 个候选。只用于提示,从不自动纠正或加载。
cc_hooks.rs)HookEvent |
解析名(两种写法都接受) | 触发点(kernel 接缝) | 能否阻断 | stdin 载荷主要字段 |
|---|---|---|---|---|
PreToolUse |
PreToolUse / pre_tool_use |
ToolMiddleware::before |
能(deny / ask / allow / 改写参数) | session_id, hook_event_name, call_id, tool_name, tool_input(对象), cwd |
PostToolUse |
PostToolUse / post_tool_use |
ToolMiddleware::after(!is_error) |
能(decision:block);可改写输出 |
call_id, tool_name, tool_response |
PostToolUseFailure |
同上加 _failure |
after(is_error) |
同上 | 同上 |
SessionStart |
SessionStart / session_start |
LifecycleHooks::session_start |
否;stdout 作为上下文注入 | session_id, hook_event_name, cwd |
SessionEnd |
… | session_end |
否,仅观察 | 同上 |
UserPromptSubmit |
… | user_prompt_submit(&mut String) |
能(block → Err) | prompt |
Stop |
… | turn_complete(非失败结束) |
否 | transcript_path, stop_hook_active, stop_reason |
StopFailure |
… | turn_complete(ProviderError / InternalError / Timeout) |
否 | 同上 |
每个 turn 结束时,Stop 和 StopFailure 恰好触发其中一个。工具中途出错不算 StopFailure。stop_hook_active 表示“同一事件是否还有其它 hook 也会触发”,用于防止 hook 递归触发自己。
未实现:PreCompact、子 agent、批量事件等 CC 事件,原因是需要新的 kernel 接缝。
// $ATOMCODE_HOME/hooks.json(全局)与 <project>/.hooks.json(项目),两者都加载并拼接
{
"hooks": {
"audit-bash": { // key 只用于用户自己组织,加载后不保留
"event": "PreToolUse",
"matcher": "bash|edit_*|mcp__github__*",
"command": "python3 \"$ATOMCODE_PROJECT_DIR\"/hooks/audit.py",
"timeout_ms": 10000, // 默认 10000
"disabled": false,
"required_approval": false // 只对 PreToolUse 生效
}
}
}
jsonc::strip_comments 容忍注释,但尾逗号仍会导致整个文件被丢弃。此时 warn 会给出路径和原因,atomcode hooks list 显示 ⚠。HooksFileStatus:Missing / Unreadable{error} / Malformed{error} / Loaded{hooks, disabled, unknown_events}。CLI 用它区分“文件存在”和“hooks 真的会运行”。{Event:[{matcher, hooks:[{type:"command", command, args, timeout(秒)}]}]},由 HookConfig::from_plugin_spec 转换(秒乘以 1000,默认 10s)。examples/hooks/hooks.toml(trigger = "post_tool" 这种 TOML 格式)和 docs/hook-architecture.md 描述的都是已移除的 HookEngine 架构,在当前运行时中不会触发。docs/hook-architecture.md 自己也标注了“已过时”。matcher 语义(matches_tool / glob_match):
None、空串或 * 匹配所有工具。| 分隔多个备选;每个备选是 glob,其中只有 * 是通配符,其它字符都按字面匹配。.、[..] 等按字面处理,因此通常匹配不上。run_command_hook,cc_hooks.rs:650)普通 hook: sh -c "<command>"(Windows 下为 cmd /C);带 args 时直接 exec(不经 shell)
插件 hook: plugin_hook_command(见 6.5),在 spawn_blocking 中执行且受 timeout 限制;失败时视为 {"decision":"block"}
环境变量: ATOMCODE_PROJECT_DIR、CLAUDE_PROJECT_DIR(工作目录存在时才 cd 进去)
CLAUDE_PLUGIN_ROOT、ATOMCODE_PLUGIN_ROOT(插件 hook)
Unix 下设置 UTF-8 locale;Windows 下使用 CREATE_NO_WINDOW
stdio: stdin 写入 JSON 载荷后 shutdown(容忍 EPIPE);收集 stdout / stderr;kill_on_drop
超时: tokio::time::timeout(timeout_ms);超时 → None → 当作静默继续
stdout 的最后一个非空行按 JSON 解析为 Decision,同时兼容 CC 与 AtomCode 旧格式:
{ "action": "allow|block|modify", "args": {...}, // AtomCode 旧格式
"decision": "block", "reason": "...", // CC 顶层格式
"hookSpecificOutput": {
"permissionDecision": "allow|deny|ask",
"permissionDecisionReason": "...",
"updatedInput": {...}, // PreToolUse 改写参数
"updatedToolOutput": "...", // PostToolUse 改写结果
"additionalContext": "..." } } // SessionStart / UserPromptSubmit 注入上下文
退出码契约(exit_requests_block、deliberate_block_reason):
| 情况 | 结果 |
|---|---|
| 有可解析的 JSON 决策 | 以 JSON 为准 |
| 退出码为 2,且 stdout 或 stderr 中有原因 | 阻断,原因即该文本 |
退出码为 2,但没有任何输出,或 stderr 命中启动失败特征(can't open file、command not found、cannot execute、ModuleNotFoundError、No module named、ImportError) |
视为坏掉的 hook,不阻断 |
| 其它非零退出码、超时、spawn 失败 | 不阻断,继续 |
stdout 有内容但不是 JSON(例如 Windows cmd /C echo '{..}' 保留了引号) |
在决策点 warn “hook stdout is not a JSON decision”,然后忽略 |
PreToolUse 折叠(pre_tool_gate,cc_hooks.rs:1318):
按配置顺序依次执行匹配的普通 hook(顺序执行,便于短路,并保证改写结果确定):
改写:updatedInput 或 action=modify 时用 args 替换 call.arguments(最后一个生效)
判定:deny/block → Deny;ask → Ask;allow → Allow;否则 Proceed
gate = stronger(gate, this),优先级 Deny(3) > Ask(2) > Allow(1) > Proceed(0);DenyTurn 为 4
一旦 Deny 立即返回
然后执行 required_approval hook(看到的是改写后的最终参数,自身不能改写):
只有 exit 0 + 明确 allow + 不带 updatedInput 或 modify 才算 Allow,其余全部 Deny
(超时、spawn 失败、空输出、非零退出都 Deny)
最后在 before() 中:gate 为 Ask 时调用 request_approval_decision,复用通用审批线协议
Null(驱动方已断开 / 超时)→ 按拒绝处理(fail-closed);AllowAlways 也只当作一次性允许(不记忆)
Allow 会让后续的自动批准 gate 短路,确保 hook 要求的 ask 一定弹出审批
note_call_for_post:只有未被 Deny 的调用才记录 call_id → tool_name,供 PostToolUse 匹配
UserPromptSubmit 中所有匹配的 hook 并发执行(join_all),按配置顺序折叠:第一个 block 生效;其它 hook 的 additionalContext,或非阻断时的纯 stdout,用 \n\n 拼接到 prompt 末尾。
SessionStart 也并发执行,其 stdout 通过 reminder::synthetic_system_reminder 以 user 角色加上来源标记推入会话。这样 UI 不会把它当作用户气泡重放,同时兼容各 provider 和前缀缓存。
PostToolUse 顺序执行:最后一个 updatedToolOutput 生效;decision:block 会产生 AfterOutcome::Block。
--require-approval-hook(load_with_required_approval,cc_hooks.rs:983):要求用户全局 hooks.json 中存在一个启用的、覆盖所有工具的 required_approval PreToolUse hook,否则返回 PermissionDenied。项目和插件的 hooks 不能满足这一要求。该开关与 --dangerously-skip-permissions 互斥。
plugin_hook_command)1. 识别两种固定的 Node 包装写法(只做字符串匹配,从不执行其中的 JS),提取其中的脚本路径
2. 校验当前内容哈希等于授权时的哈希,否则拒绝("plugin content changed since authorization")
3. 去掉 ${CLAUDE_PLUGIN_ROOT} 等 6 种占位写法后,若出现以下任一字符则拒绝:
控制字符 ; | & ` $ ( ) > < \n \r % ^
4. 按引号分词,追加清单中的 args(不得含 NUL)
5. 首词为 python / python3 / node / sh / bash 时视为解释器(Windows 下只在 PATH 的绝对目录中找 .exe/.com)
6. 脚本路径必须是相对路径:不能以 '-' 开头,不能含 ':',不能有 '..';canonicalize 后必须位于插件根目录内、
必须是普通文件,且不能位于 .git 中
7. 用 Command::new(interpreter).arg(script).args(rest) 精确执行检查过的路径;
设置 PYTHONDONTWRITEBYTECODE=1(避免 .pyc 改变包内容哈希)
validate_plugin_hook 在计算信任哈希时复用这套检查,所以不合规的插件 hook 根本无法被授权(trust() 遇到 invalid: 前缀会报错)。
cc_hooks/inspection.rs)atomcode hooks list | paths | test <NAME>:
test 按事件名或命令子串选择 hook,使用 test_payload(event, cwd) 生成的合成载荷,复用与运行时相同的执行器,并有 30s 总上限(test_deadline)。old_selection_cannot_execute_edited_or_other_project_configuration 保证:选中某个 hook 之后,如果配置被编辑,就不会执行编辑后的内容。| 模块 | 关键 API | 要点 |
|---|---|---|
product_dirs.rs |
ProductDirs::new(user, project_dir_name)、.user()、.project(root)、with_home_dir_name |
产品目录名由宿主注入,本 crate 中不出现硬编码的 .atomcode(由 gates/product-dir.sh 检查)。动机有两个:一个 fork 改名需要修改约 240 个文件;嵌入方以前只能通过设置 ATOMCODE_HOME 来重定位,漏设时会读错用户树。忘记传入会直接编译失败 |
reminder.rs |
SYSTEM_REMINDER_TAG、system_reminder(body)、synthetic_system_reminder(body) -> Message、is_system_reminder |
所有注入方必须通过这里构造提醒。曾有日期行没加包裹,被模型当成了用户原话 |
jsonc.rs |
strip_comments |
把 // 和 /* */ 替换为空白(保持字节位置,错误行列号不变),字符串内容不受影响;尾逗号仍然非法。.mcp.json 和 .hooks.json 共用这一实现 |
hooks.rs |
WireLogHooks::stderr() / with_sink / compact() / to_file(path) |
在 on_request 中输出投影后的 messages、冻结的 tools 和 options;在 on_model_response 中输出 assistant 消息。记录的是中性的 kernel 视图,也就是前缀缓存的键,适合排查缓存问题 |
process_utils.rs |
suppress_console_window[_sync]、assign_child_to_kill_on_close_job、JobHandle::{terminate, preserve_descendants}、taskkill_tree、kill_windows_tree、shell_command、is_running_as_admin、apply_utf8_locale_env |
Windows:无控制台的父进程(daemon)启动子进程时会闪出控制台窗口,需要 CREATE_NO_WINDOW;用 Job Object 实现进程树级的终止 |
git_branch.rs |
read(cwd) -> Option<String> |
直接读 .git/HEAD,支持 worktree 中的 gitdir: 文件,不启动 git 进程(用于状态栏显示) |
pathnorm.rs |
strip_verbatim[_path]、canonicalize、path_case_key、to_display |
内部标识使用不带 \\?\ 前缀的原生路径;跨越边界(给 LLM、写入环境变量块、显示在 UI)时统一用正斜杠,因为 Git Bash 会把 \U、\t 当作转义 |
pathutil.rs |
SKIP_DIRS(node_modules、.git、target、dist、build、.venv、.claude、tmp 等 20 项)、skip_dir_for(dirs)、expand_tilde、real_home_dir |
tools 与 codeintel 共用同一份跳过列表和 ~ 展开规则,保证 read_file("~/x") 与 shell 的行为一致 |
proxy.rs |
apply_async_proxy_policy、apply_blocking_proxy_policy |
只有 ATOMCODE_PROXY_MODE=no_proxy 时才调用 .no_proxy();未设置时遵循系统代理(企业代理用户的默认需求)。ATOMCODE_TLS_MAX=1.2 把 TLS 版本上限设为 1.2 |
fs.rs |
atomic_write(path, bytes, mode) |
同目录 tempfile → fsync → persist(Windows 下为 MoveFileEx)→ 父目录 fsync |
image_normalize.rs |
normalize_image_base64、sendable_image、normalize_image_raw、base64_image_media_type、dib_to_rgba |
长边上限 1568px(Anthropic 内部也会缩放到这个尺寸),目标 512KiB;优先 PNG,必要时降为 JPEG;解码限制 50MP、单边 20000、分配 300MiB;失败时原样返回(fail-open)。动机:超大截图每轮都会重发,在网关上表现为反复出现的“网络连接失败”,无法自行恢复 |
instructions.rs |
load_instructions(home, project) -> LoadedInstructions、render_instructions |
三层指令:GLOBAL <home>/ATOMCODE.md;PROJECT 取 .atomcode.md > ATOMCODE.md > AGENTS.md > CLAUDE.md > claude.md 中第一个存在的,其余标为 Shadowed;USER .atomcode.user.md。单个文件上限 1MiB;状态有 Loaded / Missing / Empty / Shadowed 等,并能检测磁盘变化;渲染为 === {scope} INSTRUCTIONS (path) === 块 |
search.rs |
tokenize(query)、score(hay_lc, terms) -> Score、best_first |
纯函数:CJK bigram 展开、去掉连接词(“关于”“以及”)、按覆盖率优先排序;按时间打破平局的逻辑由调用方负责 |
model_cards.rs |
catalog()、resolve_id(wire)、status(wire)、score_label |
编译时嵌入的离线模型评测快照,只读 |
askpass/ |
server::start(cache, home_dir_name) -> (AskpassEnv, Receiver<AskpassPrompt>, Guard)、set_env / current_env、wrapper::write_askpass_script、cache::PasswordCache(TTL,Zeroizing)、protocol::{Request{token,prompt}, Response{password}}(NDJSON) |
仅 Unix。socket 所在目录权限 0700,socket 本身 0600,脚本 0700(exec "<exe>" __askpass "$@")。key_for_prompt 把提示归类为 sudo 或 ssh:<host>,用作缓存键。bash 工具通过读取 current_env() 注入 SUDO_ASKPASS / SSH_ASKPASS |
| 项 | 位置 | 默认 | 作用 |
|---|---|---|---|
[plugin] auto_install_default_skills |
config.toml(atomcode-config/src/config/mod.rs:861) |
true | 首启时安装默认 marketplace |
[plugin] auto_update_marketplaces |
同上,:868 |
true | 24h 节流 git pull |
[skills] extra_dirs |
config.toml(:599) |
[] |
额外的 skill 根目录 |
HostPlugins [[patch]] id="skills" config={auto_load=false} |
宿主层 | — | 关闭自动加载 |
endpoints::plugin_marketplaces() / plugin_auto_install() / is_trusted_host() |
atomcode-config |
发行版内置 | 默认 marketplace、自动安装列表、可注入 token 的 host |
ATOMCODE_HOME |
环境变量 | ~/.atomcode |
用户树根目录(由宿主转换成 ProductDirs) |
ATOMCODE_PROJECT_DIR / CLAUDE_PROJECT_DIR |
hook 子进程 | — | 项目目录 |
CLAUDE_PLUGIN_ROOT / ATOMCODE_PLUGIN_ROOT |
插件 hook 子进程 | — | 插件根目录(不替换进命令文本) |
${CLAUDE_SESSION_ID} / ${CLAUDE_SKILL_DIR} |
skill 模板 | — | 受信变量 |
GIT_TERMINAL_PROMPT=0、GCM_INTERACTIVE=never、GIT_SSH_COMMAND=ssh -oBatchMode=yes |
git 子进程 | 强制设置 | 禁止交互式凭据输入 |
ATOMCODE_PROXY_MODE |
进程 | 未设置时遵循系统代理 | no_proxy 表示绕过代理 |
ATOMCODE_TLS_MAX |
进程 | — | 1.2 表示 TLS 上限设为 1.2 |
PYTHONDONTWRITEBYTECODE=1 |
插件 hook | 强制设置 | 避免写出 .pyc,从而不改变内容哈希 |
| 扩展点 | 方式 |
|---|---|
| 新的插件来源类型 | 在 ExternalSource 中新增变体,并在 install_external 中实现;未知类型自动落到 Unknown,不会破坏现有目录 |
| 新的 marketplace / 插件清单位置 | 修改 load_marketplace_manifest / load_plugin_manifest 的候选列表 |
| skill 来源 | 驱动方自行组装 SkillRegistry::reload_dirs(dirs, namespaced) 或 load_template_dir(dir, ns, kind);standard_skill_dirs 只是默认值 |
| 目录渲染 | render_skill_catalog(entries) / render_catalog_prioritizing(text) |
| 新的 hook 事件 | 需要先在 kernel 中增加接缝,再在 HookEvent::parse / cc_name 和 CCExternalHooks 中实现 |
| 外部 hook 来源 | 用 HookConfig::from_plugin_spec 或直接构造 HookConfig,然后 CCExternalHooks::load_with_extra |
| harness 组装方式 | pre_tool_gate 返回未解析的 Ask,post_tool 和 note_call_for_post 都是公开的。kernel 链路与 harness 两种组装方式只在“如何把 ask 转成审批”这一行上不同 |
| 线路日志的输出位置 | WireLogHooks::with_sink(Arc<dyn Fn(&str)>) |
| 场景 | 行为 |
|---|---|
| git 不可用 | 启动钩子只发出一个 GitNotFound(友好提示,不是错误);手动操作时报 GIT_NOT_FOUND 文案 |
| 引导或自动更新失败 | 写入 stderr.log 并吞掉错误,多条失败合并为一条 Failed{op:"auto-update"} |
| 清单无法解析 | 返回 Err(fail-closed);目录中单个未知来源只跳过该项 |
| 重复安装 | AlreadyInstalledError{id} → PluginAlreadyInstalled,提示如何重装 |
| 信任存储损坏 | 视为空(全部不信任) |
| 插件 hook 配置不兼容 | 哈希前缀为 invalid:,hooks 被扣下,并且不可授权 |
| 插件内容被改动 | 执行时返回 block(fail-closed),提示重新加载并重新信任 |
| skill 解析失败或目录不可读 | 记录为 SkillDiagnostic / FailedAsset,不影响其它 skill;take_new_warnings 只报告新出现的问题 |
| skill 名称歧义或不存在 | get 返回 None → use_skill 返回错误并列出可用名称 |
!`cmd` 执行失败 |
替换为 stdout 加 stderr,或 [error: ..];不中断展开 |
| hooks 文件损坏 | 整个文件被丢弃,并 warn;其它文件不受影响 |
| hook 超时、崩溃或输出非 JSON | 继续执行(只有 required_approval hook 会因此拒绝) |
| hook 的 ask 但审批通道断开 | 拒绝 |
数量(#[test] 与 #[tokio::test]):plugin/ 134 个,skills/ 93 个,cc_hooks.rs 51 个,cc_hooks/inspection.rs 7 个。
插件相关(部分):
round_trips_marketplaces_file、scope_state_file_aliases_user_scope_when_cwd_is_home、accepts_supported_schemes、rejects_malformed_ssh_shorthand、infers_name_from_ssh_shorthand、strips_only_one_dot_git_suffix_when_inferring_name、trusted_hosts_and_subdomains、untrusted_or_malformed_is_false、scheme_host_prefix_strips_pathhash_is_stable_and_order_independent、hash_changes_on_command_change_not_on_timeout、hash_no_collision_across_field_boundaries、script_and_imported_helper_changes_invalidate_authorization、changing_argv_invalidates_authorization_and_preserves_argument_boundaries、incompatible_entry_points_cannot_be_authorized、incompatible_authorization_errors_do_not_dump_hashes_or_commandsfile_cc_hooks_parses_cc_schema_from_hooks_subdir、file_cc_hooks_falls_back_to_root_hooks_json、file_cc_hooks_parses_wrapped_settings_format、custom_hooks_path_malformed_does_not_fall_back_to_default、dedup_collapses_none_and_empty_matcherrefresh_due_on_future_marker_never_wedges、refresh_due_exactly_at_interval_boundary、collapse_auto_update_failures_multiple_collapse_to_one_summary、marker_path_uses_versioned_filename、auto_install_failure_msg_keeps_recovery_hint_on_first_lineinstall_git_subdir_clones_only_subtree(git < 2.25 时跳过)、dedup_skipped_when_pin_set、normalize_git_url_strips_suffix_and_slashSkills 相关(部分):
fresh_inserts_after_leading_system_run、resume_refreshes_in_place_no_growth、resume_prunes_stale_when_no_skills_leftsource_rank_tiers、a_relocated_tree_still_outranks_third_party_dirs、the_upstream_name_confers_nothing、hundreds_of_skills_share_budget_without_losing_names、identity_only_overflow_keeps_priority_and_discovery_notice、explicit_instruction_reference_outranks_source_tier、equal_descriptions_receive_round_robin_prefixesargument_shell_injection_is_not_executed、shell_injection_runs、expand_arguments_full_and_positional、dollar_n_boundary、appends_args_when_no_arguments_token、malformed_tool_lists_do_not_become_bare_tool_grants、duplicate_tool_declarations_refuse_loading_instead_of_overriding_grants、frontmatter_rejects_unknown_args_value、static_expansion_is_bounded_and_never_executes_dynamic_blocksclear_reports_match_and_simple_or_quoted_tasks_do_not、explicit_opt_out_is_unquoted_and_direct_change_is_not_an_opt_out、explicit_metadata_wins_and_ties_do_not_pick_an_arbitrary_skill、browser_mentions_examples_code_and_refusals_do_not_triggerversioned_installs_and_display_titles_have_safe_invocation_names、install_dirs_are_the_winning_dirs_of_the_standard_listcc_hooks 相关(部分):
parse_event_both_spellings、matcher_semantics、matcher_alternation_and_glob、stop_vs_stop_failure_terminal_mappinga_commented_hooks_file_loads、a_malformed_hooks_file_is_skipped_not_fatal、the_status_tells_a_broken_file_from_an_empty_one、a_hooks_path_that_cannot_be_read_is_not_missingdecision_precedence_deny_beats_allow、parses_cc_pretooluse_decision、a_hook_that_printed_text_instead_of_a_decision_is_told_apart、quoting_a_decision_away_yields_no_decisionrequired_approval_accepts_only_successful_explicit_allow、required_approval_times_out_without_authorizing_call、required_approval_sees_rewritten_inputa_loaded_plugin_cannot_execute_changed_content、node_path_wrapper_is_a_checked_script_entry_point、channel_import_wrappers_and_polyglot_batch_files_use_checked_interpreters、plugin_argv_preserves_literals_and_still_checks_the_entry_pointinspection_preserves_disabled_unknown_and_parse_errors_without_execution、old_selection_cannot_execute_edited_or_other_project_configuration、test_deadline_cancels_a_late_continuation、synthetic_payloads_keep_event_specific_fieldsaskpass:set_then_current_returns_env,以及 socket 和目录权限(0600 / 0700)、脚本可执行位的断言。
CLAUDE_PLUGIN_ROOT 全部兼容,同时增加了内容哈希信任和“只允许脚本入口”两道门槛。CC 插件中用 bash -c "a && b" 写的 hook 在 AtomCode 中会被拒绝授权,需要改成一个脚本文件。can't open file 这类启动失败(否则装了一个坏插件的所有人都会被卡住)。相反,required_approval 是 fail-closed 的。两种语义并存,配置时必须分清。Deny > Ask > Allow > Proceed,PreToolUse 顺序执行,一旦 Deny 就停止,不再启动后续 hook。use_skill 传入 !`rm -rf`,也不会被执行。list_skills。有 60 多个社区 skill 时,也不会挤掉少数高价值的流程类 skill。[no-auto-skills] 关闭。GIT_TERMINAL_PROMPT=0、GCM_INTERACTIVE=never、ssh BatchMode、stdin=null,四者缺一不可。sanitize_name,避免出现 key 与目录名不一致或路径逃逸。marketplaces.json 和 installed_plugins.json 使用 std::fs::write,并发安装时可能出现后写覆盖先写的情况(待确认上游是否打算修复);只有信任库是原子写。examples/hooks/hooks.toml 和 docs/hook-architecture.md 描述的是已移除的 TOML 引擎。<project>/.hooks.json,不是 .atomcode/hooks.json。PathOrList 的注释说“只取第一个”,但 skills_paths() 实际返回全部路径,commands_path() 仍然只取第一个。ProductDirs 依赖注入:任何持久化能力都必须显式接收目录,编译器会强制检查。这消除了“某个入口忘了设置 ATOMCODE_HOME,导致读错用户树”这一类 bug。<system-reminder> 只有一个构造入口,synthetic_system_reminder 还会带上来源标记,避免 UI 把 hook 输出重放成用户气泡。OpenTMD 现状:internal/skill(SKILL.md,按行解析的 frontmatter,只有 $ARGUMENTS 一种替换,~/.opentmd/skills → 从根到工作目录各级的 .opentmd/skills / .atomcode/skills);internal/hook(hooks.json,事件 PreToolUse / PostToolUse / UserPromptSubmit / SessionStart,通过环境变量 OPENTMD_HOOK_* 传上下文,{"action":"allow|block|modify"});internal/project/instructions.go(OPENTMD.md > CLAUDE.md > …)。可借鉴的点:
OPENTMD_HOOK_* 环境变量的同时,把 JSON 载荷写入 stdin(session_id、hook_event_name、call_id、tool_name、tool_input 对象、cwd),并解析 stdout 最后一行中的 hookSpecificOutput.permissionDecision / updatedInput / additionalContext,以及退出码 2。这样可以直接复用 CC 生态的 hooks。修改后需同步更新 docs/architecture/hooks.md。exit 2 但无输出,或 stderr 中含 can't open file、command not found 时,不阻断。这个函数在 Go 中十几行即可实现,能避免坏 hook 卡住每一轮。deny > ask > allow > proceed,PreToolUse 顺序执行,遇到 deny 短路;最后一个 modify 或 updatedInput 生效;ask 交给现有的 permission 审批 UI,并且在“自动批准”分类之前处理。Stop / StopFailure 事件。在 runLoop 结束时恰好触发其中一个(provider 错误或超时时触发 StopFailure),并带上 stop_hook_active,可用于审计和通知类 hook。required_approval 外部审批 hook:只有 exit 0 加明确 allow 才放行,其余全部拒绝,可对接企业审批服务。| 分隔的备选加只含 * 的线性 glob。比正则安全,也与 CC 的写法一致。opentmd hooks list 区分 Missing / Unreadable / Malformed / Loaded,并在文件损坏时明确 warn。!`cmd` 或 ${SKILL_DIR},必须按“受信变量 → shell → 参数(单次扫描、不再重扫)”的顺序处理。use_skill 返回内容前加一段 <system-reminder>This skill is installed at <dir>; resolve scripts/ references/ there</system-reminder>。这能显著减少模型在工作目录中盲目搜索。.opentmd 和用户树优先,.claude、.agents 次之);超预算时提示调用 list_skills。目前 OpenTMD 的 “Available Skills” 部分没有预算,可以直接借鉴。.claude/skills、.claude/commands、.agents/skills。在 internal/skill 的加载顺序中加入这些目录(低优先级),同时更新 copilot-instructions 中关于加载顺序的说明,以及 docs/user-guide。- 和 / 的位置);allowed-tools 格式错误时拒绝加载而不是放宽授权;用 user-invocable: false 控制是否在菜单中隐藏。atomic_write 0600 保存信任库,文件损坏时视为空。GIT_TERMINAL_PROMPT=0、GCM_INTERACTIVE=never、GIT_SSH_COMMAND="ssh -oBatchMode=yes"、cmd.Stdin = nil。这对 Bubble Tea 的 TUI 同样适用(raw mode 下 git 读 tty 会导致死锁)。.git/HEAD 和 worktree 的 gitdir: 文件。fileio 读取图片或 TUI 粘贴图片的入口,防止大图在每一轮都被重发。<system-reminder> 构造函数:internal/agent 中所有运行时注入(plan 模式提示、日期、hook 上下文)都通过同一个函数包裹,避免漏加标签,让模型把注入内容误认为用户原话。ProductDirs,把 ~/.opentmd 和 .opentmd 作为结构体传入 config.Ensure 之后的各模块,而不是到处读取 os.UserHomeDir(),方便测试和二次分发。