kimi-plugin-cc 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -14
  3. package/README.md +428 -572
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +4 -2
  7. package/dist/cli-client.js +105 -66
  8. package/dist/commands/ask.js +27 -12
  9. package/dist/commands/cancel.js +4 -13
  10. package/dist/commands/cli-helpers.js +1 -1
  11. package/dist/commands/pursue.js +3 -2
  12. package/dist/commands/registry.js +7 -26
  13. package/dist/commands/repair-sessions.js +7 -4
  14. package/dist/commands/replay.js +4 -3
  15. package/dist/commands/rescue.js +17 -5
  16. package/dist/commands/review.js +18 -5
  17. package/dist/commands/setup.js +283 -265
  18. package/dist/commands/swarm.js +20 -7
  19. package/dist/companion.js +142 -18
  20. package/dist/help.js +11 -7
  21. package/dist/hook-escape.js +7 -16
  22. package/dist/hooks/approval-hook.js +1762 -124
  23. package/dist/hooks/approval-policy.js +15 -10
  24. package/dist/hooks/config-safety.js +15 -24
  25. package/dist/hooks/hook-timing.js +1 -1
  26. package/dist/hooks/install-paths.js +224 -112
  27. package/dist/hooks/install.js +64 -169
  28. package/dist/hooks/managed-block.js +52 -101
  29. package/dist/job-store.js +117 -49
  30. package/dist/jobs.js +53 -1
  31. package/dist/kimi-engine.js +68 -92
  32. package/dist/kimi-errors.js +1 -1
  33. package/dist/kimi-journal.js +3 -2
  34. package/dist/kimi-releases.js +28 -49
  35. package/dist/kimi-timeouts.js +1 -15
  36. package/dist/kimi-version-probe.js +24 -72
  37. package/dist/logging.js +12 -7
  38. package/dist/mcp/binding.js +13 -4
  39. package/dist/mcp/job-control.js +386 -89
  40. package/dist/mcp/launcher.js +1 -1
  41. package/dist/mcp/operations.js +387 -193
  42. package/dist/mcp/protocol.js +116 -27
  43. package/dist/mcp/skills.js +130 -0
  44. package/dist/mcp/stdio.js +15 -2
  45. package/dist/native-v2-preflight.js +127 -35
  46. package/dist/parsing.js +45 -11
  47. package/dist/paths.js +20 -10
  48. package/dist/plugin-data.js +28 -83
  49. package/dist/read-scope.js +2 -2
  50. package/dist/render.js +13 -38
  51. package/dist/session-references.js +216 -0
  52. package/dist/session-title.js +1 -1
  53. package/dist/surface-routing.js +92 -5
  54. package/dist/swarm-activation.js +26 -137
  55. package/dist/version.js +1 -1
  56. package/docs/migration.md +46 -227
  57. package/docs/models.md +24 -66
  58. package/docs/safety.md +195 -400
  59. package/docs/session-visibility.md +24 -14
  60. package/docs/swarm-recovery.md +26 -20
  61. package/dsh/index.json +54 -0
  62. package/mcp_config.json +10 -0
  63. package/package.json +23 -82
  64. package/plugin.json +19 -0
  65. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  66. package/plugins/kimi-codex/.mcp.json +2 -3
  67. package/plugins/kimi-codex/dist/background-spawn.js +4 -2
  68. package/plugins/kimi-codex/dist/cli-client.js +105 -66
  69. package/plugins/kimi-codex/dist/commands/ask.js +27 -12
  70. package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
  71. package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
  72. package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
  73. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  74. package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
  75. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  76. package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
  77. package/plugins/kimi-codex/dist/commands/review.js +18 -5
  78. package/plugins/kimi-codex/dist/commands/setup.js +283 -265
  79. package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
  80. package/plugins/kimi-codex/dist/companion.js +142 -18
  81. package/plugins/kimi-codex/dist/help.js +11 -7
  82. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  83. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
  84. package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
  85. package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
  86. package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
  87. package/plugins/kimi-codex/dist/hooks/install-paths.js +224 -112
  88. package/plugins/kimi-codex/dist/hooks/install.js +64 -169
  89. package/plugins/kimi-codex/dist/hooks/managed-block.js +52 -101
  90. package/plugins/kimi-codex/dist/job-store.js +117 -49
  91. package/plugins/kimi-codex/dist/jobs.js +53 -1
  92. package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
  93. package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
  94. package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
  95. package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
  96. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
  97. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
  98. package/plugins/kimi-codex/dist/logging.js +12 -7
  99. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  100. package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
  101. package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
  102. package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
  103. package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
  104. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  105. package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
  106. package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
  107. package/plugins/kimi-codex/dist/parsing.js +45 -11
  108. package/plugins/kimi-codex/dist/paths.js +20 -10
  109. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  110. package/plugins/kimi-codex/dist/read-scope.js +2 -2
  111. package/plugins/kimi-codex/dist/render.js +13 -38
  112. package/plugins/kimi-codex/dist/session-references.js +216 -0
  113. package/plugins/kimi-codex/dist/session-title.js +1 -1
  114. package/plugins/kimi-codex/dist/surface-routing.js +92 -5
  115. package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
  116. package/plugins/kimi-codex/dist/version.js +1 -1
  117. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  118. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  119. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  120. package/scripts/companion.sh +4 -15
  121. package/skills/kimi/SKILL.md +77 -0
  122. package/skills/kimi/agents/openai.yaml +6 -0
  123. package/CHANGELOG.md +0 -1402
  124. package/agents/kimi-pursue.md +0 -93
  125. package/agents/kimi-review.md +0 -86
  126. package/agents/kimi-swarm.md +0 -88
  127. package/agents/kimi-task.md +0 -93
  128. package/commands/README.md +0 -14
  129. package/commands/cancel.md +0 -17
  130. package/commands/pursue.md +0 -41
  131. package/commands/replay.md +0 -13
  132. package/commands/result.md +0 -13
  133. package/commands/review.md +0 -40
  134. package/commands/setup.md +0 -25
  135. package/commands/status.md +0 -13
  136. package/commands/swarm.md +0 -45
  137. package/commands/task.md +0 -40
  138. package/dist/commands/review-gate.js +0 -391
  139. package/dist/config.js +0 -22
  140. package/dist/dsh/companion.js +0 -177
  141. package/dist/dsh/index.js +0 -167
  142. package/dist/hooks/review-gate-stop.js +0 -19
  143. package/dist/schemas/review-gate-output.js +0 -41
  144. package/docs/registry-releases.md +0 -228
  145. package/docs/upstream-2.4.1-certification.md +0 -54
  146. package/docs/upstream-2.5.0-certification.md +0 -52
  147. package/docs/upstream-2.5.1-certification.md +0 -47
  148. package/docs/upstream-2.5.2-certification.md +0 -40
  149. package/docs/upstream-2.5.3-certification.md +0 -73
  150. package/docs/upstream-2.6.0-certification.md +0 -65
  151. package/docs/upstream-2.6.2-certification.md +0 -144
  152. package/docs/upstream-2.6.3-certification.md +0 -100
  153. package/docs/upstream-2.7.2-certification.md +0 -113
  154. package/docs/upstream-2.7.3-certification.md +0 -95
  155. package/docs/windows-validation.md +0 -39
  156. package/hooks/README.md +0 -9
  157. package/hooks/hooks.json +0 -16
  158. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
  159. package/plugins/kimi-codex/dist/config.js +0 -22
  160. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  161. package/plugins/kimi-codex/dist/dsh/index.js +0 -167
  162. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  163. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  165. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  166. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  167. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  168. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  169. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  170. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  171. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  172. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  173. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
  174. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  175. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
  176. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  177. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  178. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  179. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
  180. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  181. package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
  182. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
  183. package/plugins/kimi-dsh/LICENSE +0 -201
  184. package/plugins/kimi-dsh/README.md +0 -84
  185. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  186. package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
  187. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  188. package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
  189. package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
  190. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
  191. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
  192. package/plugins/kimi-dsh/dist/commands/models.js +0 -139
  193. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
  194. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  195. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  196. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
  197. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  198. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
  199. package/plugins/kimi-dsh/dist/commands/result.js +0 -72
  200. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
  201. package/plugins/kimi-dsh/dist/commands/review.js +0 -217
  202. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
  203. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  204. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
  205. package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
  206. package/plugins/kimi-dsh/dist/companion.js +0 -99
  207. package/plugins/kimi-dsh/dist/config.js +0 -22
  208. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  209. package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
  210. package/plugins/kimi-dsh/dist/errors.js +0 -40
  211. package/plugins/kimi-dsh/dist/git.js +0 -216
  212. package/plugins/kimi-dsh/dist/help.js +0 -43
  213. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  214. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
  215. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
  216. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
  217. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
  218. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  219. package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
  220. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
  221. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  222. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  223. package/plugins/kimi-dsh/dist/job-store.js +0 -631
  224. package/plugins/kimi-dsh/dist/jobs.js +0 -212
  225. package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
  226. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
  227. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
  228. package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
  229. package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
  230. package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
  231. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  232. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
  233. package/plugins/kimi-dsh/dist/logging.js +0 -22
  234. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  235. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
  236. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
  237. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
  238. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
  239. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  240. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
  241. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  242. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  243. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  244. package/plugins/kimi-dsh/dist/model-command.js +0 -34
  245. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
  246. package/plugins/kimi-dsh/dist/package.json +0 -1
  247. package/plugins/kimi-dsh/dist/parsing.js +0 -554
  248. package/plugins/kimi-dsh/dist/paths.js +0 -35
  249. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  250. package/plugins/kimi-dsh/dist/process-tree.js +0 -597
  251. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  252. package/plugins/kimi-dsh/dist/read-scope.js +0 -435
  253. package/plugins/kimi-dsh/dist/render.js +0 -214
  254. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
  255. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
  256. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  257. package/plugins/kimi-dsh/dist/session-title.js +0 -313
  258. package/plugins/kimi-dsh/dist/stream-json.js +0 -344
  259. package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
  260. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
  261. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
  262. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
  263. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  264. package/plugins/kimi-dsh/dist/types.js +0 -1
  265. package/plugins/kimi-dsh/dist/util.js +0 -28
  266. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  267. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  268. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  269. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  270. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  271. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  272. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  273. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  274. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  275. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  276. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  277. package/plugins/kimi-dsh/dist/version.js +0 -7
  278. package/plugins/kimi-dsh/package.json +0 -78
  279. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  280. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  281. package/scripts/review-gate-hook.sh +0 -32
package/docs/safety.md CHANGED
@@ -1,49 +1,44 @@
1
1
  # Safety
2
2
 
3
- This guide describes the current checkout runtime. Read-only tasks deny file writes and shell commands. Rescue and pursue can edit your workspace. Write-swarm returns a patch from a temporary Git worktree.
3
+ This guide explains how kimi-plugin-cc 3.1.1 constrains every Kimi session it starts. Read-only operations deny file writes and shell commands. Rescue and pursue edit files only inside your workspace and never mutate Git. Write-swarm (`swarm_patch`) edits inside a temporary Git worktree and returns an unapplied patch.
4
4
 
5
- The plugin makes promises about the sessions it launches. It does not police your own Kimi configuration. One mechanism keeps those promises: the managed PreToolUse hook, which denies every tool call the running command's policy does not permit. Plan mode stays closed, because Kimi's plan-file approval is the one path that bypasses hooks. Where a setting of yours would break a promise, the plugin neutralizes it for its own children or refuses; where it would not, the plugin runs and tells the caller with a warning.
5
+ The plugin makes promises about the sessions it launches. It does not police your own interactive Kimi configuration. One mechanism enforces every promise: a single bundled PreToolUse hook that denies every tool call outside the running operation's allowlist. Plan mode stays closed across every release as defense in depth even though Kimi Code 2.8.0 runs the hook before the plan guard. Where a Kimi setting would break a promise, the plugin neutralizes it for its own children or refuses before spawn; where it would not, the plugin runs and surfaces a launch warning.
6
6
 
7
- Native agent-core-v2 uses the no-plan construction on exact reviewed versions. The [runtime release table](../runtime/kimi-releases.ts) controls routing and operation scope; an unlisted 2.x release runs only the read-only operations (see [Running a newer Kimi than the plugin certifies](#running-a-newer-kimi-than-the-plugin-certifies)). Exact 2.6.0 remains limited to review, challenge, ask, rescue, review gate and pursue. Plugin 2.6.2 adds the bounded swarm construction described below for exact stock CLI 2.6.2; its [certification receipt](upstream-2.6.2-certification.md) records validation status. Plugin 2.6.3 certifies exact CLI 2.6.3 under the same construction with a separate [release receipt](upstream-2.6.3-certification.md); the immutable GitHub/npm release and fresh registry verification are complete. Plugin 2.7.2 certifies exact CLI 2.7.2 with separate [certification evidence](upstream-2.7.2-certification.md). Plugin 2.7.3 adds exact CLI 2.7.3 under the same construction with a separate [certification record](upstream-2.7.3-certification.md); publication does not update installed hosts or operator pins. Older full-operation rows through 2.5.3 retain their known rate-limit-recovery limitation. The hook is not an operating-system sandbox.
7
+ Plugin 3.1.0 uses a rolling compatibility window with floor `>= 2.8.0`. The [runtime release table](../runtime/kimi-releases.ts) is the single authority: exact Kimi Code `2.8.0` is certified for all 7 model operations ([2.8.0 certification record](upstream-2.8.0-certification.md)), unlisted plain `2.y.z` releases strictly above `2.8.0` run read-only operations (`ask`, `review`, `challenge`) with a warning, and releases below `2.8.0` (including `legacy-v1`) refuse before spawn. The hook is not an operating-system sandbox.
8
8
 
9
- ## Why the safety story is hook-based
9
+ ## Why enforcement is hook-based
10
10
 
11
- kimi-code's `kimi -p` mode hard-codes `permission: 'auto'` and registers an auto-approve handler for every tool call. There is no argv flag to disable this — `-p` is a non-interactive batch mode and assumes the caller wants tools to run unattended. That's a sensible default for a coding agent invoked directly from a terminal. It's the wrong default when a plugin is forwarding a read-only review request and the user expects no shell or file mutations to happen.
11
+ Kimi Code's `kimi -p` mode hard-codes `permission: "auto"` and approves every tool call automatically. There is no command-line flag to turn this off because `-p` is a non-interactive batch mode. That works for a standalone CLI run, but it breaks read-only reviews and bounded fixes launched from another assistant.
12
12
 
13
- The plugin installs a `PreToolUse` hook in Kimi's `config.toml`. Each host has its own hook entry. The plugin sets `KIMI_PLUGIN_CC_CMD` for each child process so the hook can select the operation's policy.
14
-
15
- On certified native-v2 versions, every tool call reaches the hook because plugin-managed sessions never activate plan mode. The preflight, tool policy, and resume checks enforce that condition. See the no-plan construction below. An explicitly pinned legacy-v1 binary uses the earlier permission-policy chain.
13
+ The plugin therefore publishes a self-contained ESM hook to `<pluginRoot>/hook/approval-hook.js` (default `~/.local/share/kimi-plugin-cc/hook/approval-hook.js`) and installs one canonical `PreToolUse` entry in `~/.kimi-code/config.toml`. On every spawn, the runtime sets `KIMI_PLUGIN_CC_CMD` on the child process so the hook applies that operation's policy. Out-of-plugin `kimi` runs leave `KIMI_PLUGIN_CC_CMD` unset and stay unrestricted.
16
14
 
17
15
  ```
18
- ┌──────────────────────┐ KIMI_PLUGIN_CC_CMD=review ┌──────────────────────┐
19
- │ /kimi:review │ ───────────────────────────────► │ kimi -p │
20
- │ (companion.sh) │ │ (permission:auto) │
21
- └──────────────────────┘ └─────────┬────────────┘
22
- │
23
- │ PreToolUse:
24
- │ Bash
25
- ▼
26
- ┌──────────────────────┐
27
- │ approval-hook.js │
28
- │ reads env var, │
29
- │ applies policy, │
30
- │ exits 2 + stderr │
31
- │ (deny) │
32
- └──────────────────────┘
16
+ ┌───────────────────────────┐ KIMI_PLUGIN_CC_CMD=review ┌──────────────────────┐
17
+ │ kimi_read / companion.sh │ ────────────────────────────► │ kimi -p │
18
+ │ (MCP or CLI) │ │ (permission: auto) │
19
+ └───────────────────────────┘ └──────────┬───────────┘
20
+ │
21
+ │ PreToolUse:
22
+ │ Bash
23
+ ▼
24
+ ┌──────────────────────┐
25
+ │ approval-hook.js │
26
+ │ reads env var, │
27
+ │ applies policy, │
28
+ │ exits 2 + stderr │
29
+ │ (deny) │
30
+ └──────────────────────┘
33
31
  ```
34
32
 
35
- If the hook is missing or invalid, **every model-spawning command fails closed before Kimi starts**: rescue/pursue/swarm already refused, and v1.8 extends the same rule to ask/review/challenge. The review gate cannot safely block a host Stop event without enforcement, so it skips visibly instead of spawning an un-enforced Kimi turn. `/kimi:setup` also runs a two-layer probe before reporting success so missing-Node-on-PATH and broken-quoting failures surface up front instead of at first tool call. `KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1` remains an explicit tests/diagnostics escape hatch for hook verification; it accepts kimi-code's unsafe `permission: auto` posture but **does not** bypass `CLI_V2_HOOK_ORDER_UNSAFE` and is never a repair path. Damaged marker comments alone do not stop a job: when the real TOML parser proves a clean, byte-exact managed entry, the job runs with a warning that the markers need repair (see the marker grammar below).
33
+ If the hook is missing, drifted, or invalid, every model-spawning operation fails closed before Kimi starts. `kimi_setup({ action: "install" })` and `scripts/companion.sh setup` run a two-layer probe before reporting success so missing-Node and shell-quoting errors surface immediately. `KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1` is a test and diagnostic bypass for hook verification only; it never bypasses engine certification, provenance checks, or the native-v2 preflight, and it is never a repair path. Damaged marker comments alone do not stop a job when the real TOML parser proves a clean, byte-exact enforcing hook entry; the job runs with a warning asking you to run setup.
36
34
 
37
- ## The managed block
35
+ ## The canonical managed block and bundled hook
38
36
 
39
- `/kimi:setup` writes a marker-delimited block to `~/.kimi-code/config.toml`:
37
+ Running `kimi_setup({ action: "install" })` or `scripts/companion.sh setup` verifies `pluginRoot` and `hook/` via `lstat`/`realpath` (rejecting symlinks and non-directories), stages `package.json` (`{"type":"module"}`) and the self-contained bundled ESM `dist/hooks/approval-hook.js` in a unique staging subdirectory, probes the staged candidate before activating `<pluginRoot>/hook/approval-hook.js` (preserving any working hook on failure), and writes one canonical block in `~/.kimi-code/config.toml` inside the serialized config lock:
40
38
 
41
39
  ```toml
42
- # === BEGIN kimi-plugin-cc-managed:claude-code (vX.Y.Z) ===
43
- # DO NOT EDIT — managed by /kimi:setup. Run /kimi:setup --uninstall to remove.
44
- # Host: claude-code — each host owns a separate block in this shared
45
- # ~/.kimi-code/config.toml. Scoped setup/uninstall preserves other hosts;
46
- # /kimi:setup --uninstall --all removes every host's block.
40
+ # === BEGIN kimi-plugin-cc-managed (v3.1.1) ===
41
+ # DO NOT EDIT — managed by kimi-plugin-cc setup. Run `scripts/companion.sh setup --uninstall` to remove.
47
42
  # Purpose:
48
43
  # kimi-code's `kimi -p` mode hard-codes permission='auto' and
49
44
  # auto-approves every tool call. This hook enforces each managed command's
@@ -58,445 +53,245 @@ If the hook is missing or invalid, **every model-spawning command fails closed b
58
53
  # LaunchAgents, etc.).
59
54
  [[hooks]]
60
55
  event = "PreToolUse"
61
- command = "'/abs/path/to/node' '/abs/path/to/dist/hooks/approval-hook.js'"
56
+ command = "'/abs/path/to/node' '/abs/path/to/kimi-plugin-cc/hook/approval-hook.js'"
62
57
  timeout = 15
63
- # === END kimi-plugin-cc-managed:claude-code ===
58
+ # === END kimi-plugin-cc-managed ===
64
59
  ```
65
60
 
66
- The `vX.Y.Z` marker is replaced with the live plugin version by
67
- `runtime/commands/setup.ts`. Both the node binary path and the hook
68
- script path are shell-quoted via `runtime/hooks/install-paths.ts`
69
- before they reach the config (so a path containing spaces or quotes
70
- can't bypass the safety contract through argv splitting).
71
-
72
- Key constraints (verified by [`runtime/hooks/managed-block.ts`](../runtime/hooks/managed-block.ts) on both install and verify):
73
-
74
- 1. **No `matcher` line.** kimi-code compiles the matcher field via `new RegExp(matcher)`. An empty matcher means "fire for every tool." `new RegExp("*")` throws, which kimi-code catches and treats as "no matcher" → silently disables the hook. The installer omits the field intentionally; the verifier rejects any block that contains a `matcher = ...` line.
75
- 2. **Absolute Node path.** kimi-code spawns hook commands via `/bin/sh -c "<command>"`. If we wrote bare `node`, the shell would resolve it against kimi-code's PATH at execution time. On a system where kimi-code launches from a GUI/LaunchAgent with a sanitized PATH (nvm/asdf/mise users), bare `node` would exit 127 → hook protocol treats non-{0,2} as **allow** → safety contract collapses with no user-visible signal.
76
- 3. **TOML basic-string escaping.** The command field is a TOML basic string. Quotes, backslashes, newlines, and control characters in the resolved hook path are escaped during install; paths containing characters that cannot be safely escaped (literal `"`, raw control chars) are rejected up front with `SETUP_HOOK_PATH_UNSAFE`.
77
- 4. **Exact marker grammar.** `setup` and `setup --check` reject duplicate blocks and orphan or mismatched host markers. Install removes lexically proven unpaired marker comments across hosts, preserving surrounding content and all foreign hook tables, and warns. Text inside TOML strings is not a marker. At job time markers are bookkeeping, not the boundary: a duplicate or orphan marker state does not refuse when the whole hook set validates and the real parser finds a clean, unconditional `PreToolUse` entry with the byte-exact command. The job runs and carries the warning `The managed kimi-code PreToolUse hook is installed and enforcing, but its config markers need repair: <reason>`; run plain `/kimi:setup` to repair them.
78
- 5. **Exact command equality, per host.** The verifier reconstructs the canonical command byte string from the current env and equality-checks the installed `command` (never a substring — a crafted `true # /path/to/approval-hook.js` runs only `true` and would auto-allow). This holds *per host id* (below): each host verifies its own block.
79
- 6. **Full-config parse and whole-hook-array validation.** The verifier parses the complete file with vendored `smol-toml@1.9.1` with upstream fixes included and no local JavaScript modifications (see `runtime/vendor/smol-toml/README.md`), before inspecting the managed block. It then applies upstream's strict config schema to every configured hook (`event`, optional string `matcher`, non-empty `command`, optional integer `timeout` 1–600, no extra fields). A malformed unrelated TOML value or one invalid foreign hook can make kimi-code discard enforcement; both therefore fail verification. A kimi-plugin-cc hook entry counts as installed only if kimi-code waits at least 15 seconds for it (a missing `timeout` means kimi-code's 30-second default), because kimi-code treats a hook that times out as allowing the call; every copy of the command must meet this, since kimi-code runs only the first one. A shorter entry fails with `this host's hook entry has timeout = 1; kimi-code reads a hook that runs past its timeout as allow, so the entry needs a timeout of at least 15 seconds. Run /kimi:setup to rewrite it; setup leaves the config unchanged and names any copy it cannot rewrite.` Jobs refuse and `setup --check` fails on it. `setup` rewrites its own block in place, or throws `SETUP_INVALID_HOOKS_CONFIG` and leaves the config unchanged when a copy it cannot prune remains.
80
- 7. **Serialized, identity-bound setup mutations.** Install and uninstall hold a private `0o600` sibling lock across the complete read-modify-write transaction. The candidate lock is published atomically; lock reads are no-follow, nonblocking, regular-file-only, and capped at 4 KiB. Acquisition is bounded, live owners are never stolen, stale recovery is guarded by a nonrecursive recovery lease, and inode/token ownership is rechecked before config mutation or lock removal. Simultaneous Claude Code/Codex setup runs therefore cannot lose either host's block, and a replaced lock is never treated as ours. A newly created Kimi home is `0o700`; atomic config writes remain `0o600`.
81
- 8. **Inline hook arrays are normalized before insertion.** kimi-code accepts both `hooks = [...]` and `[[hooks]]`, but appending a managed array-of-tables block after an inline assignment can produce a conflicting document. Setup converts a valid inline hook array to canonical `[[hooks]]` tables before inserting the host block and emits an explicit warning that formatting and comments inside that assignment are normalized. Surrounding config bytes are preserved.
82
-
83
- ### Host scoping (all hosts share one config)
84
-
85
- Claude Code and Codex install this plugin to **different, version-stamped
86
- paths** (`~/.claude/plugins/cache/…` vs `~/.codex/plugins/cache/…`), while DSH
87
- uses its own profile package path. All read the **same**
88
- `~/.kimi-code/config.toml`. So the managed block is **host-scoped**:
89
- its marker carries a `:<host-id>` suffix, and each host owns, verifies, and
90
- uninstalls only its **own** block.
91
-
92
- - **Host id** (`runtime/hooks/install-paths.ts::resolveHostId`) is derived
93
- version-independently from the hook path: `~/.claude/…` → `claude-code`,
94
- `~/.codex/…` → `codex`, else a stable `host-<sha1>` for dev checkouts. DSH
95
- explicitly pins `dsh`. A plugin upgrade *refreshes* the same host's block
96
- rather than adding a new one.
97
- - **No clobbering.** `/kimi:setup` (Claude), `$kimi-setup` (Codex), and
98
- `/kimi-setup` (DSH) each write their own block and leave the others
99
- byte-identical. Before v1.7.0 there was
100
- a single block exact-matched to the running host, so the two hosts overwrote
101
- each other and the loser's write-commands refused with "hook path drift."
102
- - **Every hook checks every job.** kimi-code runs every `[[hooks]]` entry
103
- for every tool call, and any denial wins. Every installed kimi-plugin-cc
104
- hook checks every labelled job; no hook steps aside for another host's job.
105
- The redundancy matters because kimi-code reads a hook that times out,
106
- crashes or cannot be spawned as allow: another host's hook still checks a
107
- job whose own hook has died. For a labelled call the hook denies if it has
108
- not decided within 10 s, below the 15 s installed `timeout`; out-of-plugin
109
- calls are unchanged. Each job launch and each setup warns about every other
110
- host's kimi-plugin-cc hook that is older than this plugin (prereleases and
111
- unreadable versions count as older), because its rules still apply. A
112
- drifted own block is still caught at the per-command verify gate, which
113
- prompts a re-setup for that host only.
114
- - **Migration + cleanup.** A pre-v1.7.0 un-suffixed block is adopted and
115
- converted in place by the current host on its next `/kimi:setup`. Orphaned,
116
- marker-less `[[hooks]]` entries that are unambiguously our approval hook
117
- (canonical command, `approval-hook.js` under a kimi-marketplace/kimi-plugin-cc/
118
- dsh-kimi-plugin-cc tree) are pruned **host-scoped** (v1.8.2): install and scoped uninstall touch
119
- only tables whose command path derives to the *current* host. `/kimi:setup
120
- --uninstall` removes only the current host's block (plus legacy + this host's
121
- orphans); `/kimi:setup --uninstall --all` removes every host's block and every
122
- plugin-owned table. Hand-rolled user hooks are never touched.
123
- - **Markers are not durable — verification does not depend on them (v1.8.2).**
124
- kimi-code persists its config via smol-toml `stringify(parse(...))` on every
125
- login/settings write, which deletes ALL comments — the managed-block BEGIN/END
126
- markers included — while the `[[hooks]]` table (data) survives and keeps
127
- enforcing. When this host's marked block is absent, the verifier falls back to
128
- a marker-less table whose decoded `command` is **byte-identical** to the
129
- canonical expected command, under the same strict grammar (PreToolUse event,
130
- no matcher, no keys beyond event/command/timeout). Anything weaker — drifted
131
- path, matcher-bearing table, foreign keys — still refuses. In setup and
132
- `setup --check` the fallback never applies over duplicate/orphan/invalid
133
- marked states; at job time duplicate and orphan states follow the marker
134
- rule in item 4 above. The next `/kimi:setup`
135
- re-adorns the markers; the other host's marker-less table is that host's LIVE
136
- hook and is left byte-untouched (pre-v1.8.2, the host-blind prune here caused
137
- each host's setup to disarm the other after any kimi login — the "seesaw").
138
-
139
- ## DeepSeek Harness providers
140
-
141
- DSH's host and any profile-local harness packages must use patched `zod >=4.6.6` and `undici >=8.12.2`. The plugin treats DSH services as optional host-provided peers; it does not install the harness for other hosts or rewrite an existing DSH installation. Audit the actual host installation as well as the profile. See [patched DSH setup](./registry-releases.md#patched-dsh-host-and-profiles).
142
-
143
- The DSH bundle keeps one provider per operation, seven in all: `kimi_ask`, `kimi_review`, `kimi_challenge`, `kimi_rescue`, `kimi_pursue`, `kimi_swarm`, and `kimi_swarm_write`. DSH's tool adapter takes fixed parameters, so it cannot express the `kimi_review` mode that replaces `kimi_challenge` on the MCP server; the operations are the same as on the other hosts. Each activation starts the existing companion through DSH's managed subprocess service and uses the same `kimi -p` transport, hook verification, exact-version certification, job store, and response or safety budgets. ACP is not used.
144
-
145
- Run `/kimi-setup` explicitly before delegating. Installing or enabling the bundle does not modify Kimi configuration. DSH uses host id `dsh` and `$DSH_HOME/plugin-data/kimi-plugin-cc` unless an absolute data-root override selects another store. Its provider-owned environment clears other-host roots/data, hook/script overrides, trusted roots, and verification bypasses instead of inheriting them.
146
-
147
- The parent receives only complete successful stdout. stderr remains on the host, and nonzero, empty, or truncated output becomes a bounded diagnostic rather than partial prose. Cancellation terminates the managed process range and waits for quiescence. DSH activation ids are distinct from companion job ids; use `/kimi-status`, `/kimi-result`, or `/kimi-cancel` for the persisted job.
148
-
149
- Write boundaries are identical to the companion commands: rescue and pursue edit the real selected workspace, ask/review/challenge and read-only swarm deny writes and shell commands, and swarm-write works from born HEAD in a temporary worktree and returns a patch without applying or committing it. `/kimi-setup --uninstall` removes only the DSH managed block; the all-host uninstall flag is not exposed.
150
-
151
- ## Host surfaces and the operations they run
152
-
153
- Claude Code has four model commands with four matching agents, Codex has the same four as skills, and the MCP server has six model tools. Each surface runs one of seven operations, and the operation selects the hook label below. Plugin 3.0.0 changed the surface names; the operations, hook labels and session-title prefixes did not change.
154
-
155
- | Operation (hook label) | Claude Code command and agent | MCP tool | Name before 3.0.0 |
156
- |---|---|---|---|
157
- | `ask` (`ask`) | `/kimi:task`, agent `kimi-task` | `kimi_ask` | `/kimi:ask`, agent `kimi-ask` |
158
- | `rescue` (`rescue`) | `/kimi:task --write`, agent `kimi-task` with `--write` | `kimi_rescue` | `/kimi:rescue`, agent `kimi-rescue` |
159
- | `review` (`review`) | `/kimi:review`, agent `kimi-review` | `kimi_review` | unchanged |
160
- | `challenge` (`challenge`) | `/kimi:review --challenge`, agent `kimi-review` with `--challenge` | `kimi_review` with `mode: "challenge"` | `/kimi:challenge`, agent `kimi-challenge`, tool `kimi_challenge` |
161
- | `pursue` (`rescue`) | `/kimi:pursue`, agent `kimi-pursue` | `kimi_pursue` | unchanged |
162
- | `swarm` (`swarm`) | `/kimi:swarm`, agent `kimi-swarm` | `kimi_swarm` | unchanged |
163
- | `swarm --write` (`swarm-write`) | `/kimi:swarm --write`, agent `kimi-swarm` with `--write` | `kimi_swarm_write` | agent `kimi-swarm-write` |
164
-
165
- Codex skills carry the agent names (`$kimi-task`, `$kimi-review`, `$kimi-pursue`, `$kimi-swarm`); only `$kimi-review` is implicitly invocable. The runtime, not the host wrapper, picks the operation (`runtime/surface-routing.ts`): `ask` with a leading `--write` runs rescue, and `review` with a leading `--challenge` runs challenge. Only flags before the first prompt word count, so `--write` inside the prompt or after `--` keeps the read-only operation. MCP calls always pass the prompt after `--`, so the tool name alone decides the operation. The old companion spellings `task rescue`, `task challenge` and `task swarm --write` still work.
166
-
167
- ## The hook's per-command policy
168
-
169
- [`runtime/hooks/approval-policy.ts`](../runtime/hooks/approval-policy.ts) is the single source of truth:
170
-
171
- | `KIMI_PLUGIN_CC_CMD` | Allowed tools | Denied tools |
172
- |---|---|---|
173
- | unset / empty | everything | nothing (kimi was invoked outside the plugin) |
174
- | `ask` | `Read`, `Grep`, `Glob`, `ReadMediaFile`, `TaskList`, `TaskOutput`; with `--read-root` or `--network` the four read tools are confined to the workspace and the named roots; with `--network`, also `WebSearch` and `FetchURL` to public hosts | everything else, including `Bash`, `Write`, `Edit`; `WebSearch` and `FetchURL` without `--network` |
175
- | `review`, `challenge` | same as `ask` | same as `ask` |
176
- | `review_gate` | same as `ask`; the gate never sets scope flags, so reads are unconfined | same as `ask`, including both web tools |
177
- | `rescue` | governed by [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts) against the plugin-owned `KIMI_PLUGIN_CC_WORKSPACE_ROOT` — workspace-bound shell allowlist, workspace file operations, symlink-aware path containment, mutating-flag detection on `git`/`find`/`sed`, etc. | missing-root writes and every shell command, file edit, or write that the allowlist rejects |
178
- | `swarm` | same as `ask`, including scope; exact `AgentSwarm` subject to the version-specific wave guard | everything else, including singular `Agent`, shell, and writes |
179
- | `swarm-write` | read-only set + admitted `AgentSwarm` on parallel paths; `Write`/`Edit`/`Bash` only through the rescue evaluator against the trusted ephemeral-worktree root | singular `Agent`, missing-root writes, and everything the rescue evaluator rejects |
180
- | unknown label | `Read`, `Grep`, `Glob`, `ReadMediaFile`, `TaskList`, `TaskOutput` | everything else (conservative-deny for stale/misconfigured callers) |
181
-
182
- `EnterPlanMode` and `ExitPlanMode` are explicitly denied before any per-label write evaluator for every managed label. Denied tool calls exit the hook with code 2 and write a reason to stderr. kimi-code surfaces the reason to the model, which can adapt and try a different approach (e.g., use `Read` instead of `Bash cat`).
183
-
184
- ### Read scope and network access
185
-
186
- Kimi approves its read and web tools itself in every mode, so the managed hook is the only place they can be scoped. The caller sets scope for one call on `ask`, `review`, `challenge` or read-only `swarm`, with the flags below or the MCP arguments `read_roots` and `network`:
187
-
188
- - No flag: read tools can read any path, and `WebSearch` and `FetchURL` are denied. The denial names `--network`.
189
- - `--read-root <absolute-directory>` (repeatable): `Read`, `Grep`, `Glob` and `ReadMediaFile` are confined to the workspace and those directories.
190
- - `--network`: `WebSearch` and `FetchURL` are allowed, and the read tools are confined to the workspace and any read roots. A job that can send data out may read only what you named.
191
-
192
- The workspace is the realpath of the directory Kimi runs in, so a job started in a subdirectory is confined to that subdirectory. Under confinement the hook denies a path or glob pattern with a backslash or a leading drive letter, a path outside the roots after symlink resolution, an argument it does not recognize, `~`, a URL-style path such as `kimi-file://`, a dangling link, a glob containing `..`, and an absolute glob outside the roots. That includes Kimi's own spill files for very large tool output whenever they lie outside the roots. `FetchURL` accepts only `http:` and `https:` URLs without embedded credentials whose host is a public name or a canonical global unicast IP address. Local names (`localhost`, `.localhost`, `.local`, `.internal`) and numerically encoded hosts are denied. So are IPv4 this-network, private, shared (carrier-grade NAT), loopback, link-local, IETF protocol, documentation, benchmarking, 6to4 relay anycast (`192.88.99.0/24`), multicast and reserved addresses, and every IPv6 address outside `2000::/3` or in its IETF, Teredo, documentation (`2001:db8::/32`, `3fff::/20`) or 6to4 blocks; a NAT64 address is judged by the IPv4 address it embeds. A `--read-root` that contains a backslash refuses with `INVALID_ARGS`, and a scoped job whose workspace contains one refuses with `READ_SCOPE_INVALID`.
193
-
194
- The hook reads only two variables the plugin sets on each spawn, `KIMI_PLUGIN_CC_READ_ROOTS` and `KIMI_PLUGIN_CC_NETWORK`. The plugin deletes both before setting them, so an inherited value cannot widen scope, and a malformed value means nothing is readable and the network is off. Scope belongs to one call: a resumed or follow-up job does not inherit it. `--network` refuses on an uncertified release, and on a resumed ask session unless every earlier turn this plugin recorded for that session ran with confined reads whose roots (its workspace plus its read roots) lie inside this call's. Otherwise it refuses with `INVALID_ARGS`: `ask --network cannot resume session <id>: an earlier turn in it ran without confined reads, or could read outside this call's workspace and --read-root directories (or its history is not recorded), so those reads could be sent out. Start a fresh session instead: ask --fresh --network [--read-root <dir>] <prompt>.` `rescue`, `pursue` and `swarm --write` reject both flags, because their allowlisted shell commands can read files. A job's scope appears in two places only: the `read_scope` field of `status` JSON, and a `Scope:` line at the top of stdout and the saved artifact (and so in the `body` of `result --json`, which has no separate scope key).
195
-
196
- ### Native agent-core-v2: the no-plan construction (v1.10.0)
197
-
198
- agent-core-v2 awaits external PreToolUse hooks on ordinary tool calls, but it registers `AgentPlanService` before `AgentExternalHooksService`, and the plan guard final-allows a `Write`/`Edit` whose only write access is the exact current plan file — ending listener iteration before the managed hook runs. Upstream documents no ordering contract; kimi-code 0.42.0 deleted the legacy-v1 engine, so the pin the plugin used since v1.9.6 is inert there.
199
-
200
- The plugin therefore certifies native v2 on a different, explicitly amended basis (see [`native-v2-certification-provenance.md` §2](native-v2-certification-provenance.md#2-native-v2-entry-gate)): the plan guard is the engine's **only** chain-breaking final allow, it fires **only while plan mode is active**, and plugin-managed sessions never arm plan mode:
201
-
202
- - The default-plan-mode setting — under EVERY spelling upstream's config loader normalizes to the `defaultPlanMode` domain (`default_plan_mode`, `defaultPlanMode`, mixed; the preflight mirrors upstream's `snakeToCamel` verbatim) — lives only in `<KIMI_CODE_HOME>/config.toml` and is read once inside session creation, never on resume. The plugin parses that same file just before spawn and again at the spawn boundary. On exact 2.4.0 through 2.7.3, a fresh `kimi -p` cancels the create-time plan entry before any turn, so a set value no longer refuses ask, review, challenge, the review gate, rescue or pursue, fresh or resumed. It still refuses swarm and write-swarm at every concurrency, including the concurrency-1 direct worker, older certified versions and uncertified releases (`CLI_V2_PLAN_MODE_CONFIGURED`, remedy: set it to `false` or remove it — never `/kimi:setup`).
203
- - `EnterPlanMode` and `ExitPlanMode` are denied by the managed hook for every label. Nothing final-allows them, and the auto-approve gate uses a non-terminal `pass()`, so the deny wins. Verified live on 0.42.0.
204
- - A session is resumed only when it is proven native-v2 plugin lineage AND a raw scan of every agent `wire.jsonl` finds no `plan_mode.*`/`plan.*` record (`KIMI_SESSION_PLAN_TAINTED`); unknown-provenance rows refuse (`KIMI_SESSION_LINEAGE_UNKNOWN`). The one exception, on 2.4.0 through 2.7.3 for non-swarm resumes, is the main agent's create-time `plan_mode.enter` immediately followed by its cancel, before any activity, in a journal with no undo or branch switch. Nothing saved is modified.
205
- - Tower and subagent fork stay off. Every child the plugin starts gets `KIMI_CODE_EXPERIMENTAL_TOWER=0` and `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK=0`, which outrank both `[experimental]` config and the master flag upstream, and native-v2 children never receive the master `KIMI_CODE_EXPERIMENTAL_FLAG`. Enabling them in your own config therefore no longer refuses certified versions. An uncertified release still refuses an enabled selector or master flag.
206
-
207
- What the headline claim is: **every executed tool call in a plugin-managed session passes the managed hook, and the engine's sole final allow is never armed.** What it is not: a claim that the hook precedes every final allow. Because plan mode is never armed, the property does not depend on listener order at all. It is re-proven per certified tag by a mechanized source scan (`tests/audit/v2-tag-scan.test.ts`) and a live plan-mode-ON control that must still show the bypass (proving the refusal is load-bearing rather than vacuous).
208
-
209
- Provenance: a native-v2 plan requires the `system.version` marker as the first stream-json line and requires it to equal the probed version; a legacy plan still refuses that marker. Either mismatch tears down the owned process tree before any record reaches the caller (`CLI_ENGINE_PROVENANCE_MISMATCH`). Certification is per exact version and per operation. See the current version list at the start of this guide.
210
-
211
- Residuals, unchanged from v1 and stated plainly: `config.toml` and the session journals are trusted operator state (an actor who can write them could already delete the `[[hooks]]` entry); the upstream hook runner fails open on its own internal errors; the plan-path comparison does not realpath (a symlink there would need a prior hook-allowed write). Native plan mode, tower, subagent fork, Remote Control and `--add-dir` are out of scope.
212
-
213
- In CLI 2.3.0 and later, stale-session retry can reread those same journals. Do not concurrently operate on or edit a plugin-managed session from another client. The upstream session lock is not a security boundary; no parent-side rescan can make that reload atomic.
214
-
215
- CLI 2.3.1 adds `KIMI_CODE_SESSION_LOCK=0` and explicit TUI/SDK/REST lock-takeover paths, which can disable or break mutual exclusion. Plugin children inherit an ambient lock-disable setting; print mode itself reports occupancy and does not take over. The prohibition on concurrent clients still applies. During POSIX lock contention, upstream can also execute bare `ps` with the child's inherited PATH and cwd outside PreToolUse; a PATH containing the workspace is therefore part of the internal-helper trust boundary. Legacy workspace-trust migration recognizes more old path spellings and can enable project MCP for those already trusted roots. Trust-store read failure can suppress the initial MCP load, an availability/diagnostics change rather than a trust fail-open.
216
-
217
- ## The rescue allowlist
218
-
219
- For the `rescue` operation (`/kimi:task --write`, formerly `/kimi:rescue`), the hook delegates to [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts). The allowlist has been extended since the original Wire-transport implementation. Highlights:
220
-
221
- - **File edits** (`Write`, `Edit`, `MultiEdit`): the file path must resolve inside the workspace (`realpath`-based check), must not be inside `.git/`, and must not be a symlink that escapes the workspace. An existing regular file with more than one hard link is refused, because writing it in place changes every other name for it.
222
- - **Path spellings**: Write/Edit/MultiEdit paths (`path` and `file_path`) and `Bash.cwd` refuse any backslash, NUL, leading `~`, drive-letter prefix or URL scheme, because kimi-code resolves those with `pathe` and home expansion differently from the hook. Write targets and `Bash.cwd` also refuse `.git` in any letter case or with trailing dots or spaces, at any path component; an existing target is compared under its realpath. On macOS and Linux, rescue, pursue and swarm-write refuse to start (`CLI_TRUSTED_WORKSPACE_ROOT_INVALID`) when the run directory or trusted root, or its realpath, contains a backslash, and the hook denies every tool for such a root.
223
- - **Command length**: a rescue Bash command longer than 16,384 characters is refused before it is checked, so checking always finishes well inside the hook's deadline.
224
- - **Shell commands** (`Bash`): the command is parsed with `shell-quote`. Pipelines are split and each stage validated independently. Mutating flags on `git` (`commit`, `push`, `reset --hard`, ...), `find` (`-delete`, `-exec`), and `sed` (`-i`) are rejected.
225
- - **Package-manager scripts**: `npm/pnpm/yarn/bun/uv run <script>` is rejected because `package.json` scripts can run anything. The `<pm> test` shorthand IS allowed (npm/pnpm/yarn test, bun test, uv test) — under the assumption that test runs are intentional and the developer trusts their own workspace's test config. If you don't, use direct test invocations (`pytest`, `tsc --noEmit`, `eslint`, …) instead and have your tooling refuse the `<pm> test` form.
226
- - **Output-to-file flags**: every shell command — regardless of which binary — is rejected if its argv contains `--output`, `--output-file`, `--output-directory`, `--output-dir`, or any `<flag>=<path>` prefix form. These flags let a command write to an arbitrary path through its own report-output mechanism, bypassing the file-edit path containment check (e.g. `git diff --output=/etc/passwd`, `curl --output /tmp/payload`, `eslint . --output-file=/tmp/exfil.json`). The bare `-o` short form is NOT blanket-banned (too many read-only tools use it, e.g. `rg -o` for `--only-matching`), but the per-tool validator rejects it where the binary's semantics make it a write flag (`eslint -o`, `go -o`, `ruff check -o`, `sort -o`). `uniq IN OUT` (which writes its second operand) is rejected in pipelines.
227
- - **Exec-delegating flags**: every shell command is rejected if its argv contains a flag whose *value* is run as a command or external tool — `--open-files-in-pager` (`git grep --open-files-in-pager=touch /tmp/x needle` makes git execute `touch`; same class as the pre-subcommand `git -c core.pager=` smuggle, just via a subcommand flag — also the `-O` short form under `git`), `-vettool` / `-toolexec` / `-exec` (`go vet -vettool=<bin>`, `go test -exec <bin>`). These were the CRITICAL/HIGH findings of the 2026-05-28 allowlist audit (report 43). Known gap: `-exec` and `-execdir` match only as exact tokens, so `go test -exec=<bin>` and `--exec` are approved; test runners already execute repository code (below).
228
- - **File operations**: `rm`, `mv`, `cp` and `mkdir` may run inside the workspace. Only exact flag tokens pass: `rm` takes `-f`, `-r`, `-R`, `-rf` or `-fr`; `mkdir` takes `-p`; `mv` takes `-f` or `-n`; `cp` takes `-R`, `-r`, `-p`, `-f` or `-n`. Flags are accepted only before the first operand, where `--` ends them; any later token, `--` included, is an operand. Every operand must be an absolute path inside the workspace after symlink resolution, outside any `.git` (in any letter case, with or without trailing dots or spaces), not a symlink itself, free of `..`, and made only of ordinary path characters (no glob, brace, tilde, `$` or `=`). A relative operand, including `.` and `./x`, is denied with `Rescue requires absolute paths for <cmd>; use paths under <root>: <command>`, so the check never depends on the shell's working directory. `rm`, and the sources of `mv` and `cp`, may not name the workspace root. `rm -r` operands, directory `mv` sources and `cp -R` sources must all contain no `.git` entry at any depth. The scan does not follow symlinks, stays on the operand's filesystem, inspects at most 20,000 entries and runs at most 3 s; crossing to another filesystem, reaching either limit or a directory it cannot read refuses. A recursive `cp` of a directory must create its destination, and a file copied or moved into an existing directory may not land on a symlink. Every `mv` and `cp` source must exist, no source may lie under or equal another source's landing path, and no destination may lie inside a source. A command may hold only one `rm`, `mv`, `cp` or `mkdir`; rescue also refuses `&&` and `;`, so `mkdir -p d && cp a d/` must be two separate commands. `cp` refuses a destination that is an existing regular file with more than one hard link; `mv` and `rm` are unaffected. These commands are refused on Windows. Deletions are permanent: the plugin keeps no copy.
229
- - **Search and Git reads**: `grep -i` and `git --no-pager <read-only subcommand>` are allowed. `rg -i`, `rg -w` and `grep -w` are still rejected.
230
- - **Report-writing flags on type/test tools**: `mypy --junit-xml`/`--*-report` and `pytest --junitxml`/`--result-log`/`--report-log` write to arbitrary paths and are rejected.
231
- - **Read-safe commands** (`ls`, `cat`, `head`, `tail`, `rg`, `pwd`, `wc`, `git status`, `git diff`, ...): allowed.
232
- - **`.git/`**: every file-edit path check excludes anything inside `.git/`. Shell commands cannot include `git commit`, `git push`, `git reset --hard`, etc. Branch and commit ownership stays with the main thread.
233
-
234
- ### Effective working directory (`Bash.cwd`, v1.10.0)
61
+ All 5 hosts (Claude Code, Codex, Antigravity, DeepSeek Harness, and Magpie) share this single canonical data directory and single managed block. Because the hook lives at the stable `<pluginRoot>/hook/approval-hook.js` path rather than a per-host cache directory, hosts no longer overwrite each other or leave stale older-host hooks behind. Running `setup` once after upgrading from 3.0 automatically consolidates any legacy `:<host-id>` blocks (`:claude-code`, `:codex`, `:dsh`) into this single block.
235
62
 
236
- agent-core-v2's `Bash` tool accepts a separate `cwd` argument and executes there without asserting workspace membership; the hook payload's top-level `cwd` is the kimi process cwd, not the Bash cwd. The allowlist therefore validates `tool_input.cwd` before the command string: absent → the session work dir (the trusted root); present → must be an existing, non-symlinked directory whose realpath is inside the trusted root and not under `.git`. Everything else is denied, and the command-string policy still applies afterwards.
63
+ Constraints enforced by [`runtime/hooks/managed-block.ts`](../runtime/hooks/managed-block.ts) and [`runtime/hooks/config-safety.ts`](../runtime/hooks/config-safety.ts):
237
64
 
238
- ### Trust boundary: test runners execute workspace code
65
+ 1. No `matcher` key in any TOML spelling. Kimi Code compiles `matcher` with `new RegExp(matcher)`; omitting it fires on every tool, while `"*"` throws and silently disables the hook.
66
+ 2. Absolute, stable Node binary path. Kimi Code spawns hooks through `/bin/sh -c "<command>"`. Under GUI or LaunchAgent launches with a sanitized `PATH`, bare `node` exits 127, which upstream reads as allow. Both tokens are POSIX single-quoted via `runtime/hooks/install-paths.ts`.
67
+ 3. TOML basic-string escaping. Unsafe control characters, raw quotes, or backslashes in the hook path are rejected upfront with `SETUP_HOOK_PATH_UNSAFE`.
68
+ 4. Exact marker grammar and non-durable markers. Kimi Code rewrites `config.toml` through `smol-toml` on login and settings changes, stripping all comments (including BEGIN/END markers) while leaving `[[hooks]]` tables intact. In the absent state only, verification falls back to a whole-file `smol-toml@1.9.1` parse proving a clean enforcing table with `event = "PreToolUse"`, the byte-exact canonical `command`, no `matcher`, no extra keys, and `timeout >= 15` seconds. At job time, duplicate or orphan markers with that parser proof run with a warning; `setup` and `setup --check` still fail closed on duplicate or orphan markers.
69
+ 5. Full-config parse, whole-hook-array schema validation, bundle SHA-256 verification, and timeout floor. Verification parses the complete TOML file with vendored `smol-toml@1.9.1` and validates every configured `[[hooks]]` entry (`event`, optional string `matcher`, non-empty `command`, optional integer `timeout` from 1 to 600, no unknown keys). Additive events (`PermissionRequest`, `PermissionResult`, `Interrupt`) require an exact certified `>= 2.8.0` `hook-schema` row. When `KIMI_PLUGIN_CC_HOOK_SCRIPT` is unset, `verifyHookInstalled` and `setup --check` also check `lstat` (rejecting symlinked managed hook paths) and compare the SHA-256 of `<pluginRoot>/hook/approval-hook.js` against the bundled `dist/hooks/approval-hook.js`; any mismatch (stale bundle after upgrade or cross-host downgrade) fails `setup --check` and refuses jobs with `retryable_after_setup: true`. Because upstream treats a timed-out hook as allow and runs only the first entry per command, every PreToolUse copy of the canonical command must give Kimi at least 15 seconds (an omitted `timeout` uses upstream's 30-second default). Meanwhile, the hook itself denies any labelled call still undecided at 10 seconds (`HOOK_DECISION_DEADLINE_MS`).
70
+ 6. Serialized, atomic config edits and private plugin directories. Install, hook publication, and uninstall hold a private mode `0600` sibling lock (`config.toml.kimi-plugin-cc.lock`) across read-modify-write. Candidate locks publish atomically via hard link; reads are no-follow, nonblocking, regular-file-only, and capped at 4 KiB; live owners are never stolen; stale recovery uses an ABA-safe recovery lease; inode and token ownership are rechecked before mutation and release. Newly created Kimi homes and plugin-owned directories (`pluginRoot`, `logs/`, `artifacts/`, `hook/`) use mode `0700` on POSIX; atomic config writes and stream logs use mode `0600`.
71
+ 7. Inline hook normalization and strict ownership pruning. Valid top-level inline `hooks = [...]` arrays are converted to `[[hooks]]` tables with a warning before insertion and before uninstall pruning. Paired managed blocks containing extra TOML table headers refuse (`SETUP_INVALID_HOOKS_CONFIG`) instead of deleting foreign content. Install removes lexically proven orphan marker comments and prunes only exact known install layouts of `approval-hook.js`, never touching custom or hand-rolled user hooks.
239
72
 
240
- Rescue intentionally allows test/build runners (`go test`, `cargo test`, `pytest`, `python -m pytest`, `<pm> test`). **Running tests runs the workspace's own code** — test functions, `build.rs`, `conftest.py`, fixtures. The allowlist rejects known output and report-writing flags. It cannot confine arbitrary code executed by a test runner; that code may write outside the workspace or access the network. This is the same trust the developer already extends to their own repo. If you run `/kimi:task --write` in a workspace you do not trust, assume any allowed test runner can execute arbitrary code from that workspace.
73
+ ## Universal hosts and collapsed surfaces
241
74
 
242
- The full table lives in `runtime/rescue-approval.ts`. Test coverage is in `tests/runtime/rescue-approval.test.ts` — every accept-shape and every reject-shape has at least one regression test.
75
+ All 5 hosts (Claude Code, Codex, Antigravity, DeepSeek Harness via root `cordis.patch.yml`, and Magpie) connect to the same MCP server (`scripts/companion.sh mcp`) and `kimi` skill (`skills/kimi/SKILL.md`, served over `SEP-2640` as `skill://kimi/SKILL.md`). Every surface runs the same 7 operations and selects the same hook labels:
243
76
 
244
- ### Trust boundary: kimi-code 0.31 custom agents and system prompts
77
+ | Operation (hook label) | MCP tool and mode | Primary CLI command | Write boundary |
78
+ | --- | --- | --- | --- |
79
+ | `ask` (`ask`) | `kimi_read` (`mode: "ask"`, default) | `companion.sh read` | Read-only |
80
+ | `review` (`review`) | `kimi_read` (`mode: "review"`) | `companion.sh read --mode review` | Read-only |
81
+ | `challenge` (`challenge`) | `kimi_read` (`mode: "challenge"`) | `companion.sh read --mode challenge` | Read-only |
82
+ | `swarm` (`swarm`) | `kimi_read` (`mode: "swarm"`) | `companion.sh read --mode swarm` | Read-only parallel fan-out |
83
+ | `rescue` (`rescue`) | `kimi_write` (`mode: "rescue"`, default) | `companion.sh write` | Workspace files only, never Git |
84
+ | `pursue` (`rescue`) | `kimi_write` (`mode: "pursue"`) | `companion.sh write --mode pursue` | Workspace files only, never Git |
85
+ | `swarm-write` (`swarm-write`) | `kimi_write` (`mode: "swarm_patch"`) | `companion.sh write --mode swarm-patch` | Ephemeral Git worktree; returns patch |
245
86
 
246
- kimi-code 0.31.0 brings custom-agent discovery and plugin system-prompt contributions to the default v1 print engine. It discovers project profiles under `<git-root>/.kimi-code/agents` and `<git-root>/.agents/agents` as well as user and enabled-plugin sources. A profile declaring `override: true` can replace a builtin name such as `agent` or `coder`; `~/.kimi-code/SYSTEM.md` can replace the default main-agent prompt, and enabled plugins can append system instructions. The bound catalog/profile is snapshotted into the upstream session, so resume preserves the selected instructions rather than proving the current repository files are unchanged.
87
+ `routeSurfaceAliases` (`runtime/surface-routing.ts`) parses `--mode` (and legacy `ask --write` or `review --challenge`) strictly from leading flags before `--` or the first positional token. Prompt text never switches a read-only call into a write operation. MCP calls always place prompts after `--`.
247
88
 
248
- Treat these files as **trusted model instructions** before using write-capable rescue, pursue, or swarm-write in an unfamiliar repository. They can redirect the task, remove expected tools, or replace the builtin `coder` prompt; the exact-0.31 smoke proves confinement, not task fidelity. Agent-profile fields and system-prompt text cannot themselves set hook definitions, permission mode, or cwd, cannot enlarge `runtime/hooks/approval-policy.ts`, and cannot escape swarm-write's env-pinned ephemeral root. Enabled plugins may separately contribute hooks; kimi-code's any-block-wins aggregation lets those hooks add denials but not override this plugin's managed denial. Read-only labels remain write-denying even under a hostile profile. This is an intent/prompt-injection boundary, not authority to skip the managed hook or widen the write allowlist.
89
+ For DeepSeek Harness, the root `cordis.patch.yml` mounts DSH's built-in `@deepseek-ai/dsh-mcp-client` and `@deepseek-ai/dsh-skill-filesystem`.
249
90
 
250
- ## Autonomous goal mode (`/kimi:pursue`, experimental)
91
+ ### Patched DSH host and profiles
251
92
 
252
- `/kimi:pursue` (v1.1 prototype) hands Kimi an objective to pursue across multiple continuation turns via kimi-code's headless goal mode (`kimi -p "/goal -- <objective>"`, kimi-code 0.8.0+). It is **write-capable and reuses the rescue trust boundary**: it runs with `KIMI_PLUGIN_CC_CMD=rescue`, so the PreToolUse hook applies the exact same workspace allowlist above, and it cannot mutate git state.
93
+ DSH `0.2.1-rc.5` and `0.2.2-alpha.2` pin vulnerable `zod` and `undici` versions. See the [upstream dependency report](https://github.com/deepseek-ai/deepseek-harness/discussions/10847) for background. Install and run DSH from a patched host project with `zod >=4.6.6` and `undici >=8.12.2` on Node.js `24.9` or newer. The plugin never modifies your DSH host or profiles automatically, and a profile override alone does not patch a separate global DSH CLI.
253
94
 
254
- Pursue also needs to settle its current goal. The child receives `KIMI_PLUGIN_CC_OPERATION` from its immutable execution plan, overwriting any inherited value. With the rescue label, operation `pursue`, and a trusted workspace root, the hook allows only `GetGoal {}` and `UpdateGoal {status: "complete" | "blocked"}`. These calls read or terminally update session goal metadata. Extra fields, goal creation, reactivation and budget changes are denied. `--turns` remains a soft instruction; the plugin's wall-clock budget is the hard bound.
95
+ Create a dedicated npm host project and use its DSH binary for plugin installation and launch:
255
96
 
256
- If another installed host still runs an older hook, that hook may veto these goal calls: Kimi runs all matching hooks and any denial wins. Each host must be updated separately under the operator's authorization. Running setup repairs a stale path; it does not add missing permissions to old code. Never skip or remove an enforcing hook to work around this.
257
-
258
- > **Goal-mode entry gate (changed in 0.12.0).** Headless goal mode is reached by a `/goal`-prefixed prompt. On kimi-code 0.8–0.11 it is *additionally* gated by the `goal-command` experimental flag, which `pursue.ts` sets per-spawn (`KIMI_CODE_EXPERIMENTAL_GOAL_COMMAND=1`). kimi-code 0.12.0 (PR #569) **removed that experimental-flag gate**, so the `/goal` prefix alone triggers goal mode. This does not weaken plugin safety: read-only commands (review/challenge/ask/review_gate) hard-prefix an English instruction line, so their trimmed prompt never starts with `/goal` and they cannot enter goal mode on any version; and the managed PreToolUse hook denies every write under a read-only label regardless (see § Native agent-core-v2 for why the hook cannot be pre-empted). The env var `pursue.ts` sets is now redundant on 0.12.0 but harmless, and is kept for 0.8–0.11 compat.
259
-
260
- - **The hook fires on every tool call in every continuation turn.** On native v2 every tool execution passes `prepareToolCall` → `fireBeforeExecute`, where the external-hooks listener vetoes ahead of any terminal allow (the auto-approve gate uses non-terminal `pass()`; the engine's only `allow()` is the plan-file guard, never armed in a plugin-managed session — see § Native agent-core-v2). (On legacy-v1 ≤ 0.41 the same guarantee came from `PreToolCallHookPermissionPolicy` sitting at policy index 0.) Goal continuation turns are ordinary turns — there is no autonomous-continuation path that bypasses per-tool approval (verified against kimi-code 0.9.0, audit report 58; re-verified through 0.12.0 by the goal-mode real-binary smoke, reports 61-65). A goal-mode run is exactly as write-gated as a single-turn rescue. This is locked by a real-binary smoke (`tests/runtime/real-binary-smoke.test.ts`, run via `KIMI_PLUGIN_CC_SMOKE=1 bun test ... -t "goal mode"`): it runs real headless goal mode under a read-only label, asserts that the entire workspace is empty at settlement, and requires same-call managed error denials in at least two distinct turns. It does not prove that no transient file ever existed.
261
- - **The only new risk is unboundedness, and the plugin bounds it.** Headless goal create sets no token/turn budget, and the managed hook denies `SetGoalBudget`; the plugin's external wall-clock stop is therefore the guaranteed bound. `/kimi:pursue` enforces a **mandatory finite wall-clock ceiling** via its AbortController (`--budget`, default 45m) — the SIGTERM→SIGKILL descendant-reaping cancellation reaps the whole goal process tree. `--turns` is a *soft* instruction injected into the objective, never a request to call the denied `SetGoalBudget` tool; it is not enforceable headless, and stopping at that soft hint is not proof of completion. Treat `--budget` as the real bound.
262
- - **Loop runaway is now also capped upstream.** kimi-code 0.8.0 (#364) detects repeated identical tool calls and force-stops a turn at a repeat streak. This benefits rescue, ask and pursue alike: a force-stopped turn ends *normally* (exit 0, flows through the plugin's success path — not a failure), reducing the chance an autonomous run spins against the wall-clock budget. It is a complement to, not a replacement for, the wall-clock ceiling.
263
- - **Resume is intentionally not exposed yet.** In goal mode `goal.summary` emits a *goalId* distinct from the resume-hint *sessionId*; `kimi -r <sessionId>` re-enters the session but not necessarily the goal continuation. The plugin captures and surfaces the goalId but does not offer `--resume` for pursue until that split is reconciled upstream — exposing it now would be a silent-failure trap. **Re-verified against kimi-code 0.26.0 (2026-07-16):** the headless CLI still has no argv, prompt syntax, or session-resume path that calls `resumeGoal()`. `parseHeadlessGoalCreate` (`apps/kimi-code/src/cli/goal-prompt.ts`) accepts only the `/goal <objective>` *create* shape on both the v1 and experimental-v2 drivers, and upstream's own docs (`docs/en/guides/goals.md`, § "Use goal mode carefully") state that in non-interactive prompt mode *only goal creation is supported* — goal management is a TUI/kimi-web control. PR #552 makes a plain `-r <sessionId>` correctly *restore* the paused goal snapshot, but nothing in the headless path *acts* on it; the real `resumeGoal()` is wired only to the TUI (`/goal resume`) and kimi-web RPC (PR #1693, web-only). Implementing `--resume` would therefore require either prompt-injected model compliance (rejected — the plugin bounds autonomy with hard limits, not model goodwill) or abandoning the subprocess model for kimi-web's RPC. Re-check if upstream ever ships a headless `goal resume` verb.
264
- - **A model-invocable `kimi-pursue` agent (v1.3) wraps this command.** The main thread can dispatch autonomous goal mode, not just the human-typed `/kimi:pursue` — the same command↔agent mirror as task/review/swarm. Auto-dispatch does NOT widen the blast radius: pursue runs under `commandLabel: "rescue"`, so the managed PreToolUse hook + workspace allowlist gate every tool call on every continuation turn (no git mutation), and the mandatory `--budget` wall-clock ceiling bounds the autonomy regardless of who launched it. Because it is write-capable AND autonomous — the plugin's highest blast radius — the agent's description requires an explicit user request for hands-off multi-turn pursuit, steers single bounded tasks to `kimi-task --write`, and never auto-promotes a fix or a question into a goal loop. Like the command, it refuses without the hook and offers no `--resume`.
265
-
266
- ## Swarm activation on CLI 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.6.0, 2.6.2, 2.6.3, 2.7.2 and 2.7.3
267
-
268
- For interrupted runs, see [durable recovery and its explicit limits](swarm-recovery.md).
269
-
270
- Upstream 2.3.2 removes model self-activation of `AgentSwarm` in fresh print sessions. A rejected call can therefore coexist with zero child journals and a successful exit; a tool-call record, aggregate denial, or coordinator-produced patch does not prove fan-out. The plugin does not use prompt workarounds or replace its print transport with general RPC.
97
+ ```sh
98
+ mkdir -p ~/.local/share/kimi-dsh-host
99
+ cd ~/.local/share/kimi-dsh-host
100
+ npm init -y
101
+ npm pkg set 'overrides.zod=^4.6.6' 'overrides.undici=^8.12.2'
102
+ npm install @deepseek-ai/dsh@0.2.1-rc.5
103
+ npm audit --omit=dev --audit-level=high
104
+ ./node_modules/.bin/dsh plugin --profile web add kimi-plugin-cc
105
+ ./node_modules/.bin/dsh plugin --profile web audit --prod --audit-level high
106
+ ./node_modules/.bin/dsh web --no-open
107
+ ```
271
108
 
272
- For parallel paths requiring activation (exact 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1, 2.5.2, 2.5.3 and 2.6.2/2.6.3/2.7.2/2.7.3), both slash-command and MCP swarm operations use the same `runSwarm` implementation and one ordinary `kimi -p -r` prompt runner per job, bracketed by short-lived host-managed web lifecycles:
109
+ The host project lives outside `$DSH_HOME/profiles/web`. Always run that project's `./node_modules/.bin/dsh` binary so the audited host executes your profile. The commands above install the published npm package; pass a validated local tarball or checkout path when testing an unpublished build.
273
110
 
274
- 1. Earlier paths start `web --no-open --host 127.0.0.1 --port 0 --log-level error` and require the expected loopback ready URL with backend v2, exact planned version, and no auth bypass in `/api/v1/meta`. Exact 2.7.2/2.7.3 instead starts `web --json` with an in-memory ephemeral token, validates the loopback origin and `/api/v1/ws`, and requires KAP 1.0.0 plus WebSocket capability without a legacy backend field. The child environment sets `KIMI_CODE_SESSION_IDLE_RECLAIM_MS=0`, so ambient idle-session reclamation cannot disrupt the plugin-owned lifecycle. Tokens stay in memory and out of logs. The plugin uses the explicit model or environment-model alias, otherwise reading the default alias from `/api/v1/config`; creates a session in the job cwd; on exact 2.5.0/2.5.1/2.5.2/2.5.3 and the bounded 2.6.2/2.6.3/2.7.2/2.7.3 paths explicitly binds `environment_id:"local"` and the job cwd, then verifies that binding through authenticated `/environment` before either profile mutation; binds the selected model with `permission_mode:auto` and `swarm_mode:true`; verifies those settings and `plan_mode:false` through `/status` on earlier versions, protocol-v2 authenticated WebSocket state on 2.5.0/2.5.1/2.5.2/2.5.3, or direct-subscription state on 2.6.2/2.6.3/2.7.2/2.7.3; closes that channel before validating the latest frame; verifies clean shutdown; and requires the main journal's manual `swarm_mode.enter` record. Swarm activation and deactivation read the main-agent journal with the same framing as kimi-code's replay, and a corrupt line makes the swarm state unreadable, so no later record can confirm activation or deactivation.
275
- 2. The ordinary stream-json print runner resumes that session with `kimi -p -r`. The job records `kimi_session_id_source:"preactivated"`, and the session returned by print must exactly match the preactivated id. Every coordinator and child tool call remains governed by the same managed PreToolUse hook and operation allowlist.
276
- 3. After the print run, a second web lifecycle rechecks the local binding on 2.5.0/2.5.1/2.5.2/2.5.3/2.6.0/2.6.2/2.6.3/2.7.2/2.7.3, sets `swarm_mode:false`, verifies the version-appropriate state proof, shuts down cleanly, and requires `swarm_mode.exit` in the main journal. Activation consumes part of the same finite job budget rather than extending it. `runSwarm` solely owns session deactivation: normal cleanup uses the remaining budget, while failure recovery has a separate two-second cancellation-aware bound and is never retried. Print/session failures stay primary, with exit codes and cleanup diagnostics preserved. Cancellation aborts the owned lifecycle and never starts a fresh cleanup server. Every post-mutation failure retains the session identity; process/group uncertainty is marked without inventing an ID; process groups are rechecked after teardown, unknown survivors are unverified, unproven groups are never signalled, and a same-PID/start-token process that changes PGID remains active but is not a validated signal target. Root loss requires a previously observed matching identity; first-missing roots and actual probe errors/timeouts remain unverified. Reparenting and PGID moves preserve the current verified child identity for revalidation rather than treating it as exited. Unverified cleanup prevents success and preserves raw output, structured diagnostics, and the write worktree for recovery.
111
+ If an existing profile installs its own DSH packages, patch and audit that profile too:
277
112
 
278
- Older certified versions keep the direct `kimi -p` path. The web processes are narrow, planned lifecycle helpers, not a second model runner and not a general RPC transport.
113
+ ```sh
114
+ dsh plugin --profile web pkg set 'pnpm.overrides.zod=^4.6.6' 'pnpm.overrides.undici=^8.12.2'
115
+ dsh plugin --profile web install
116
+ dsh plugin --profile web audit --prod --audit-level high
117
+ ```
279
118
 
280
- ## Bounded swarm on exact CLI 2.6.2/2.6.3/2.7.2/2.7.3
119
+ Replace `web` with your target profile name and run these commands with your patched host binary. The DSH package gate creates a clean patched host and audits both the host and profile for high or critical advisories. It verifies the 4 MCP tools and `kimi` skill and boots `dsh web`, without claiming upstream fixes for low or moderate advisories.
281
120
 
282
- `--max-concurrency` defaults to 4 for read-only work and 1 for write work. On exact native-v2 2.6.2/2.6.3/2.7.2/2.7.3, the runtime chooses one of two paths:
121
+ ## The hook's per-command policy
283
122
 
284
- - **Two or more:** the canonical hook admits only waves whose fresh items plus resumed entries fit the requested concurrency. Forks, malformed requests and fresh singleton waves are denied. Group odd numbers of targets into at least two disjoint entries per fresh wave, or resume an existing child for the remaining work. The hard bound covers simultaneous Kimi child-agent turns, excluding their coordinator. Fresh children cannot activate another swarm; resumes stay within the new job's own session.
285
- - **One:** a single worker runs directly in fresh print, without activating native swarm or launching children. Both delegation tools are denied. It keeps the same read-only restrictions or confined worktree writes and patch output.
123
+ [`runtime/hooks/approval-policy.ts`](../runtime/hooks/approval-policy.ts) is the single source of truth:
286
124
 
287
- The plugin forces `KIMI_CODE_SWARM_TIMEOUT_MS=2147483647` on bounded spawns, overriding saved or ambient short child timeouts. This value exceeds the plugin's maximum 24-hour job budget. A short native swarm-child timeout is unsafe here: it can return a wave result before a retry stops. A slow or stuck child therefore holds its wave until it completes or the finite whole-job budget or explicit cancellation stops the run. Environment value `0` is ignored upstream and is not used as a timeout override.
125
+ | `KIMI_PLUGIN_CC_CMD` | Allowed tools | Denied tools |
126
+ | --- | --- | --- |
127
+ | unset or empty | everything | nothing (Kimi invoked outside the plugin) |
128
+ | `ask`, `review`, `challenge` | `Read`, `Grep`, `Glob`, `ReadMediaFile`, `TaskList`, `TaskOutput`, `WaitFor`; with `--read-root` or `--network` the 4 read tools stay inside workspace and roots; with `--network`, also `WebSearch` and `FetchURL` to public hosts | everything else, including `Bash`, `Write`, `Edit`, `Agent`, `AgentSwarm`, and web tools without `--network` |
129
+ | `rescue` | governed by [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts) against `KIMI_PLUGIN_CC_WORKSPACE_ROOT`; under `operationKind: "pursue"` with a trusted root, also exact `GetGoal {}` and `UpdateGoal { status: "complete" | "blocked" }` | missing-root writes, Git mutation, `SetGoalBudget`, and every shell command or edit the allowlist rejects |
130
+ | `swarm` | same as `ask` (including read scope and `--network`), plus admitted `AgentSwarm` waves at concurrency 2 or more | everything else, including singular `Agent`, shell, writes, forks, and delegation at concurrency 1 |
131
+ | `swarm-write` | read-only set plus admitted `AgentSwarm` waves at concurrency 2 or more; `Write`, `Edit`, `MultiEdit`, and `Bash` only through `evaluateRescueHookRequest` against the trusted ephemeral-worktree root | singular `Agent`, missing-root writes, explicit background Bash, delegation at concurrency 1, and anything the rescue evaluator rejects |
132
+ | unknown label | `Read`, `Grep`, `Glob`, `ReadMediaFile`, `TaskList`, `TaskOutput`, `WaitFor` | everything else (fail-closed default) |
288
133
 
289
- For the parallel path, the plugin disables `TaskStop` in its fresh owned native session after the activation web process has shut down and before print starts. The managed hook already denies that tool; disabling it in native policy also removes the complete `TaskList`/`TaskOutput`/`TaskStop` set that stock 2.6.2/2.6.3/2.7.2/2.7.3 requires for Bash backgrounding. This closes both explicit backgrounding and automatic detachment after a foreground timeout, whose completion could otherwise wake a finished child. The hook separately denies explicit `Bash.run_in_background:true` on both bounded paths. The escape monitor receives the same trusted wave policy as the hook; a native mode-off rejection on the direct-worker path can still be a harmless mismatch diagnostic, not proof of execution.
134
+ `WaitFor` is in the read-only set because it waits (up to upstream's 90-second cap) on tasks that already exist and cannot start or stop one. Only write labels can start a background task inside plugin-managed runs. Like `TaskOutput`, `WaitFor` reads the session's task history and is not confined by `--read-root` or `--network`.
290
135
 
291
- With parallel backgrounding disabled, native Bash uses a 60-second default foreground timeout and a 300-second maximum; commands that exceed their timeout are killed rather than detached. Use `--max-concurrency 1` for longer tests. That direct-worker path still permits native automatic timeout-to-background behavior, although explicit background requests are denied. Its root-agent turns remain sequential, and whole-job settlement still gates the result; the limit of one is an agent-turn bound, not a promise of one OS process.
136
+ `EnterPlanMode` and `ExitPlanMode` are denied for every managed label before any per-label evaluator runs. Denied tool calls exit 2 with the denial reason on stderr so Kimi can adapt.
292
137
 
293
- The native `TaskStop` policy remains in the plugin-owned session after deactivation. The plugin does not restore it or claim the same bounded behavior if a user later resumes that historical session interactively outside the managed job.
138
+ ### Read scope and network access
294
139
 
295
- Normal print exit and terminal cancellation both wait for identity-verified owned-process settlement before artifacts or write patches are captured. A native timeout on an individual Bash call does not prove arbitrary command descendants have stopped before the next wave. An allowed repository test can itself start many OS subprocesses; the concurrency limit counts Kimi child-agent turns, not those processes. The whole-job settlement barrier stops verified owned tails and refuses success when quiescence cannot be established.
140
+ Kimi auto-approves its own read and web tools, so the managed hook is the sole place they can be scoped. Callers set scope per invocation on `ask`, `review`, `challenge`, and read-only `swarm` (CLI `--read-root <abs-dir>` and `--network`; MCP `read_roots` and `network`):
296
141
 
297
- Process-tree settlement applies on POSIX; Windows retains direct-child-only cleanup. Job-end cleanup also stops observed, identity-verified build/test daemon descendants, so services started by the job are not preserved. Process sampling retains the trusted-repository boundary and does not provide universal OS daemon containment.
142
+ - Default (no flags): read tools can read any path, and `WebSearch` and `FetchURL` are denied.
143
+ - `--read-root <absolute-directory>` (repeatable): `Read`, `Grep`, `Glob`, and `ReadMediaFile` are confined to the workspace realpath and the listed directories.
144
+ - `--network`: allows `WebSearch` and `FetchURL` to public hosts and confines the 4 read tools to the workspace and any listed read roots, so a job with web access can read only what you named.
298
145
 
299
- `--cap` stays a soft lifetime-total hint, separate from concurrency. Sequential waves can process more targets than the concurrency limit. The finite budget bounds duration, not dollars or total tokens. This construction does not change the existing trust boundary for test runners or other allowed commands that execute repository code.
146
+ Under confinement, the hook denies paths or globs containing a backslash or drive letter, symlink escapes outside the roots, unrecognized argument keys, `~`, URL-style paths (`kimi-file://`), dangling symlinks, globs containing `..`, and absolute out-of-root globs. `FetchURL` allows only `http:` and `https:` URLs without embedded credentials targeting a public hostname or canonical global unicast IP address (denying `localhost`, `.localhost`, `.local`, `.internal`, numeric hosts, private/CGNAT/loopback/link-local/IETF/documentation/benchmarking/`192.88.99.0/24`/multicast/reserved IPv4, non-`2000::/3` or IETF/Teredo/`2001:db8::/32`/`3fff::/20`/6to4 IPv6, and NAT64 addresses embedding non-global IPv4). A `--read-root` containing a backslash refuses (`INVALID_ARGS`), and a scoped job whose workspace contains one refuses (`READ_SCOPE_INVALID`).
300
147
 
301
- The construction is exact-version-specific. Older certified versions retain normal-launch limits and the inherited recovery overrun; exact 2.6.0 remains non-swarm-only. The upstream 2.6.2, 2.6.3, 2.7.2 and 2.7.3 binaries are unmodified. Validation state and evidence are recorded in the [2.6.2 certification record](upstream-2.6.2-certification.md), [2.6.3 checkout record](upstream-2.6.3-certification.md), [2.7.2 checkout record](upstream-2.7.2-certification.md) and [2.7.3 checkout record](upstream-2.7.3-certification.md).
148
+ The hook reads only per-spawn `KIMI_PLUGIN_CC_READ_ROOTS` and `KIMI_PLUGIN_CC_NETWORK`, both deleted before setting; malformed values fail closed. Scope is never inherited across turns. Naming an earlier session with `--reference-session` (MCP `referenced_sessions`) adds that session's validated `agents/main` directory (its log, saved tool outputs, and plans) to a scoped call's read roots; with `--network`, that content can reach the web. `--network` refuses on uncertified releases (`> 2.8.0`) and on resumed `ask` sessions unless every earlier plugin-recorded turn ran with confined roots inside the current call's roots. Write operations reject both scope flags because allowlisted shell commands can read files. Scope appears in `job status` JSON (`read_scope`) and as an opening `Scope:` line in stdout and saved artifacts.
302
149
 
303
- ## Read-only swarm (`/kimi:swarm`)
150
+ ### Native agent-core-v2 and the no-plan closures
304
151
 
305
- `/kimi:swarm` (v1.2) fans a **read-only** review out across subagents using kimi-code's `AgentSwarm` tool (kimi-code 0.12.0+). The coordinator launches one subagent per target (file/module/question); each inspects the workspace with read tools and reports findings, which the coordinator consolidates into one markdown report. It opens **zero new write surface**.
152
+ At Kimi Code `2.8.0`, upstream runs external `PreToolUse` hooks in `legacyHook` ahead of every `registerHook` hook (including the plan guard) and zero production code calls `event.allow()`. A live plan-ON control confirmed the hook denies plan-file Writes. Because upstream issue MoonshotAI/kimi-code#3431 remains open and no ordering promise is documented, all four plugin-owned no-plan closures remain active on every release:
306
153
 
307
- - **The hook label is `swarm`, and it allows the read-only tool set PLUS `AgentSwarm`.** On parallel paths the coordinator may call an admitted `AgentSwarm`, but no write/edit/shell tool is allowed; the exact-2.6.2/2.6.3/2.7.2/2.7.3 direct-worker path denies delegation too. The exact allowed tool name is `AgentSwarm` (verified at 0.42.0 against `packages/agent-core-v2/src/features/swarm/tools/agent-swarm/agentSwarmTool.ts`: `'AgentSwarm'`, strict schema). The singular `Agent` tool is deliberately *not* allowed — swarm is the fan-out surface, not arbitrary delegation.
308
- - **Every subagent inherits the `swarm` label and fires the same hook.** On native v2 (0.42.0) `AgentSwarm` children run in-process in a child DI scope with their OWN eager external-hooks service, so every child tool call passes the same before-execute channel and the same managed hook — there is no sub-vs-main branch and no deny-all shortcut on the swarm route. So a subagent's `Write`/`Edit`/`Bash` is denied exactly like a single-turn review's. The swarm listener in that channel is non-terminal and nothing auto-approves `AgentSwarm` ahead of the hook. (Legacy-v1 ≤ 0.41 reached the same result by placing the hook policy at index 0 of every agent's permission stack.) **Required for parallel-path certification evidence** (`tests/runtime/real-binary-smoke.test.ts`, run via `bun run smoke:real`): distinct child journals must exist, and each assigned Write/Edit `path` must be correlated through its `toolCallId` with the managed denial in that exact tool result; unrelated denials and coordinator-only reports are insufficient. On 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1, 2.5.2 and 2.5.3, targeted controls also prove that direct OFF produces no children while the preactivated ON path produces the real child journals and denials.
309
- - **The managed hook is the read-only boundary; no `explore`-profile second layer is assumed.** Production deliberately omits `subagent_type` for read-only swarm rather than selecting kimi-code's `explore` profile. Every coordinator and subagent tool call is enforced by the same managed hook.
310
- - **Swarm refuses without the hook, like every model-spawning command.** A swarm makes the reason especially acute: it asks for up to `--cap` subagents, but this total-count hint is advisory, so a missing hook would remove enforcement from all of them at once. `KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1` remains an explicit tests/diagnostics escape hatch, not a recovery path.
311
- - **Concurrency and total count are separate.** Every swarm has a finite `--budget` (default 30m). Exact 2.6.2/2.6.3/2.7.2/2.7.3 follows the bounded-wave/direct-worker construction above; `--max-concurrency` defaults to 4 for read-only work. Older certified binaries use `KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY` for normal launches on 0.18.0+ and can exceed it during rate-limit recovery. `--cap` is only a soft lifetime-total hint: a stateless per-wave guard does not make it a total-count limit. A time budget is not a dollar or token cap. Keep all three controls distinct.
312
- - **A model-invocable `kimi-swarm` agent (v1.3) wraps this command.** The `/kimi:swarm` slash command is human-only (`disable-model-invocation: true`, the blanket convention for *all* commands), but the `kimi-swarm` subagent lets the main thread *dispatch* a read-only fan-out on its own judgement — the same human-command + model-invocable-agent split that `kimi-task` and `kimi-review` use. Swarm is a safe candidate for an agent precisely because it is **read-only (zero write surface)**: the only thing auto-dispatch adds is COST exposure, already bounded by the finite `--budget` and the version-specific `--max-concurrency` bound that defaults to 4 for read-only work — so an auto-dispatched fan-out is bounded by construction, not by ignorable agent prose (the agent additionally restricts backgrounding to explicit user requests). `/kimi:pursue` ALSO gains a model-invocable agent (`kimi-pursue`, v1.3 — see the Autonomous goal mode section above): it is write-capable, but auto-dispatch widens no write surface (the rescue workspace allowlist + the managed PreToolUse hook gate every tool call on every continuation turn, and it cannot mutate git state) and removes no bound (the mandatory `--budget` ceiling holds), so its agent path is exactly as confined as its command path. Because it is the plugin's highest-autonomy surface, its agent description demands an explicit hands-off-autonomy request and steers single bounded tasks to `kimi-task --write`.
154
+ - Default plan mode preflight: `runtime/native-v2-preflight.ts` parses `<KIMI_CODE_HOME>/config.toml` under every spelling upstream normalizes to `defaultPlanMode`. On exact `2.8.0` (`print-cancels-plan`), fresh `kimi -p` cancels create-time plan entry before any turn, so configured `default_plan_mode` no longer refuses non-swarm launches; it still refuses swarm, write-swarm (including concurrency 1), and uncertified releases (`CLI_V2_PLAN_MODE_CONFIGURED`).
155
+ - Plan tool denials: `EnterPlanMode` and `ExitPlanMode` are denied by the managed hook for every label.
156
+ - Resume lineage, plan-taint, and tower scans: resume requires proven `native-v2` lineage (`KIMI_SESSION_LINEAGE_UNKNOWN` or `KIMI_SESSION_ENGINE_MISMATCH` otherwise) and scans every agent `wire.jsonl` raw for `plan_mode.*` and `plan.*` records (`KIMI_SESSION_PLAN_TAINTED`). On exact `2.8.0` non-swarm resumes, the single create-time `plan_mode.enter` followed by its cancel before any activity in a linear journal is tolerated, allowing only Kimi's 3 MCP bookkeeping records (`mcp.tools_discovered`, `mcp.server_failed`, `mcp.server_failure_resolved`) between them. The same scan refuses any session whose main journal leaves the main agent in tower mode (`KIMI_SESSION_TOWER_ACTIVE`).
157
+ - Experimental selector forcing: every child receives `KIMI_CODE_EXPERIMENTAL_TOWER=0` and `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK=0` and never receives `KIMI_CODE_EXPERIMENTAL_FLAG`. On certified releases this forcing is silent; on uncertified `> 2.8.0` releases it runs with a launch warning naming every switched-on experimental selector.
313
158
 
314
- ## Write-capable swarm (`/kimi:swarm --write`)
159
+ Provenance: every native-v2 launch requires `system.version` as the first stream-json line matching the probed version (`CLI_ENGINE_PROVENANCE_MISMATCH` tears down the process tree before any record reaches the caller).
315
160
 
316
- `/kimi:swarm --write` (v1.4) is the first WRITE mode for swarm: the coordinator and `coder` (write-capable) subagents EDIT files in parallel. It is **designed to keep direct edits in a throwaway Git worktree, subject to the test-runner trust boundary above**, and the result is handed back as a patch the user reviews before anything touches their branch.
161
+ Residuals stated plainly: `config.toml` and session journals are trusted operator state; upstream's hook runner fails open on its own internal errors; concurrent external edits to an active plugin-managed session are unsupported (the upstream session lock is not a security boundary). Native plan mode, tower, Remote Control, and `--add-dir` are out of scope.
317
162
 
318
- - **One ephemeral worktree for the whole swarm (Design A).** kimi-code runs `AgentSwarm` subagents **in-process**, all sharing the coordinator's session workspace (at 0.42.0 a child DI scope under `features/swarm/`; pre-0.42 `subagent-host.ts:362`, `cwd: parent.config.cwd`) — so "a worktree per subagent" is impossible without abandoning `AgentSwarm`. Instead the plugin creates ONE detached worktree off HEAD (under its own data dir, never inside the user repo) and spawns the coordinator `kimi -p` with cwd = that worktree. Every subagent inherits it. The worktree is disposable: a botched run is thrown away.
319
- - **Writes are confined by the hook to a forge-proof trusted root.** The `swarm-write` hook label routes write/edit/shell through the **rescue allowlist verbatim** (workspace check, symlink/realpath reject, mutating-flag + exec-delegating-flag detector, git-mutation deny), but scoped to `KIMI_PLUGIN_CC_WORKSPACE_ROOT` — the worktree path the plugin exports on the spawn — **NOT** the hook payload `cwd`. The model running inside kimi cannot set an env var on its already-spawned process, so confinement does not depend on how upstream derives the payload cwd for an in-process subagent. A missing trusted root **fails closed** (all writes denied). An out-of-worktree write (absolute path into the user's real tree) is rejected by the allowlist's `isWithin` check; a write to the worktree's `.git` pointer is rejected by the `.git`-segment check.
320
- - **`coder` subagents really can write, and the hook is the sole boundary.** Verified at kimi-code 0.42.0: swarm subagents get their own eager external-hooks service under the standard before-execute channel — there is no deny-all path on the swarm route (the `btw` side-question path is separate). Write-swarm's `coder` subagents DO have edit tools, and the managed PreToolUse hook is the **only** write boundary — which is why the trusted-root confinement above is load-bearing and gated tightly.
321
- - **The plugin never touches git; the main thread owns the merge.** Subagents cannot run git (allowlist denies mutation). The plugin captures the change set with `git add -N` (intent-to-add, so new files appear in the diff WITHOUT writing loose objects into the shared object DB) + `git diff --binary` (untruncated, applyable), writes it to a `swarm-write-<jobId>.patch` artifact, and prints the path. It does **not** `git apply`, commit, or move any ref — the user/main thread reviews the patch and applies it (`git apply <path>`). The worktree shares the main repo's object DB and refs, but no ref/HEAD is ever moved, so the user's repository state is untouched.
322
- - **The patch is captured on every terminal path, before cleanup.** Success, cancel, budget-expiry, and failure all capture the (possibly partial) patch BEFORE `git worktree remove --force` discards the tree, so a cancelled run never silently loses the work the subagents already did. If capture itself fails, the job fails instead of completing and the worktree is retained with its path in the error details for recovery. That guarantee covers the plugin's own terminal paths, including `companion.sh cancel`. It does **not** cover a harness interrupt: Esc/TaskStop delivers SIGTERM then SIGKILL after ~1.35s (measured, process-group-wide), which is shorter than the 1500ms child escalation plus quiescence plus patch capture — so a hard interrupt can kill the companion mid-teardown and lose the patch. `companion.sh cancel` signals from a separate process not racing that deadline and is the work-preserving stop. Abandoned worktrees are retained, never age-deleted. Use the preview/apply recovery procedure in [swarm-recovery.md](swarm-recovery.md); uncertain ownership refuses automatic cleanup.
323
- - **Gated tightly.** Requires an exact certified CLI (write mode additionally requires at least 0.18.0), a Git repository with committed HEAD, and a verified managed hook. A dirty-tree warning explains that the worktree starts from HEAD and does not contain uncommitted edits. Default concurrency 1 uses a direct worker on exact 2.6.2/2.6.3/2.7.2/2.7.3; larger values use bounded waves. Older certified versions retain normal-launch serialization with the disclosed recovery limitation. Disjoint targets remain prompt guidance, and Git mutation stays denied.
324
- - **Required for final certification evidence on parallel paths.** `tests/runtime/real-binary-smoke.test.ts` runs the real `runSwarm --write` and requires the POSITIVE end-to-end: distinct child journals contain their assigned edits with `Write`/`Replaced` results on the same `toolCallId`, those child-authored changes land in the worktree and captured patch, the user's real tree is byte-identical + git-clean, and the worktree is cleaned up. A patch without per-call child provenance is not accepted as fan-out evidence. The NEGATIVE lane correlates each absolute out-of-root `path` and `toolCallId` with its managed denial. It is the check that catches `tool_input` field-name drift — `Write`/`Edit` carry `path`, not `file_path`, and reading the wrong key denies every real write silently.
325
- - **The single-worker path needs separate evidence.** At concurrency 1 on exact 2.6.2/2.6.3/2.7.2/2.7.3, require fresh print with no web activation or child journals, managed delegation denials, a confined main-agent write captured in the patch, unchanged user tree, and cancellation/budget settlement. Coordinator-only patches are valid for this explicit path, never substitutes for parallel child evidence.
326
- - **Model-invocable through the `kimi-swarm` agent, patch-only by construction.** The `kimi-swarm` agent takes a leading `--write` so the main thread can dispatch a write fan-out on its own judgement (a separate `kimi-swarm-write` agent did this before 3.0.0). Auto-dispatch is a safe extension here because it widens **no** write surface and retains the documented bounds: the agent path runs the identical `runSwarm --write` code, so edits still land only in the throwaway worktree, the managed hook still gates every `coder` subagent, the patch is still handed back for the user to apply (**the plugin never applies or commits**), and `--budget` + default `--max-concurrency` 1 + the hook requirement still apply, with the rate-limit-recovery qualification above. In fact write-swarm is a *less* dangerous agent than the `kimi-pursue` agent already shipped: pursue writes directly into the workspace, whereas write-swarm's output is a patch the human reviews before anything reaches a real tree. Because it is still a write surface, the agent description allows `--write` only when the user explicitly asked for edits across many disjoint targets, and never promotes a single edit into a swarm. Default `--max-concurrency` stays **1**; raising it (concurrent writers) remains a deliberate, human-or-explicitly-requested choice.
163
+ ## The rescue allowlist
327
164
 
328
- ## MCP transport and long-running jobs
165
+ For `rescue`, `pursue`, and `swarm-write`, the hook delegates to [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts) against `KIMI_PLUGIN_CC_WORKSPACE_ROOT`:
329
166
 
330
- The plugin also bundles an MCP stdio server for Claude Code and Codex. This is an additive transport, not a second execution engine or a way around the managed hook. The six model tools run the same certified companion operations, exact-version checks, native-v2 preflight, workspace allowlists, finite budgets, and artifact rendering as the slash commands and skills. The review gate remains a separate Stop-hook feature.
167
+ - File edits (`Write`, `Edit`, `MultiEdit`): paths must resolve inside the trusted root (`realpath`), stay outside `.git` in any case or with trailing dots/spaces, never escape via symlinks, and never target an existing regular file with more than one hard link.
168
+ - Path spellings: `path`, `file_path`, and `Bash.cwd` refuse backslashes, NUL bytes, leading `~`, drive letters, and URL schemes. On macOS and Linux, write operations refuse to launch (`CLI_TRUSTED_WORKSPACE_ROOT_INVALID`) when the workspace path or realpath contains a backslash, and the hook denies every tool for such a root.
169
+ - Command length: Bash commands over 16,384 characters are denied before evaluation so checks always finish well inside the 10-second hook deadline.
170
+ - Shell commands (`Bash`): parsed with `shell-quote`; pipeline stages validate independently. Mutating `git` subcommands (`commit`, `push`, `reset --hard`, and so on), `find -delete`/`-exec`, and `sed -i` are denied.
171
+ - Package-manager scripts: `npm/pnpm/yarn/bun/uv run <script>` is denied; `<pm> test` is allowed under the test-runner trust boundary below.
172
+ - Output-to-file flags: `--output`, `--output-file`, `--output-directory`, and `--output-dir` (and `=` forms) are denied on every binary. Per-tool `-o` is denied where it writes (`eslint -o`, `go -o`, `ruff check -o`, `sort -o`), and `uniq IN OUT` is denied in pipelines.
173
+ - Exec-delegating flags: `--open-files-in-pager` (plus git `-O`), `-vettool`, `-toolexec`, and `-exec` are denied on every binary. Known gap: `-exec` and `-execdir` match as exact tokens only (`go test -exec=<bin>` and `--exec` still pass).
174
+ - File operations: `rm` (`-f`, `-r`, `-R`, `-rf`, `-fr`), `mkdir` (`-p`), `mv` (`-f`, `-n`), and `cp` (`-R`, `-r`, `-p`, `-f`, `-n`) are allowed on absolute in-root non-`.git` paths only (never on Windows; relative operands are denied; one file op per command; `&&` and `;` stay denied). `rm` operands and `mv`/`cp` sources cannot name the workspace root. Recursive/directory sources scan for `.git` entries at any depth without following symlinks, staying on one filesystem, capped at 20,000 entries and 3 seconds. `mv`/`cp` sources must exist, destinations cannot lie inside sources or collide with another source's landing path, recursive `cp` must create its destination, and `cp` refuses existing destinations with more than one hard link. Deletions are permanent.
175
+ - Search, Git reads, and report flags: `grep -i` and `git --no-pager <read-only>` pass; `rg -i`, `rg -w`, `grep -w`, and report-writing flags on `mypy` and `pytest` are denied.
176
+ - `.git/`: excluded from every file edit, file operation, and `Bash.cwd`. Branch and commit decisions stay with the calling host.
331
177
 
332
- `kimi_review` takes `mode: "defects"` (the default) or `mode: "challenge"`; there is no separate challenge tool. `kimi_ask`, `kimi_review` and `kimi_swarm` take `read_roots` (an array of absolute directories) and `network` (a boolean). The server only type-checks them and passes them on as `--read-root` and `--network`, so the runtime applies the same scope rules as on the command line. The `initialize` and `server/discover` results carry an `instructions` string that tells the calling model which tools are read-only and which write, that jobs keep running after a disconnect, and that results may carry warnings to relay to the user.
178
+ ### Effective working directory (`Bash.cwd`)
333
179
 
334
- Claude Code task-capable calls return durable MCP task IDs and use `tasks/get` and `tasks/cancel`. Codex currently consumes ordinary MCP tool results, not this task extension: after attachment, model tools return a job handle when the job is still running or its terminal result when already settled. `kimi_job_status`, `kimi_job_result`, and `kimi_job_cancel` provide polling and cancellation. Do not describe the Codex path as native MCP tasks.
180
+ Because Kimi's `Bash` tool executes in `tool_input.cwd` without asserting workspace membership, the allowlist validates `Bash.cwd` before the command string: absent defaults to the trusted root; present must be an existing, non-symlinked directory whose realpath lies inside the trusted root and outside `.git`.
335
181
 
336
- Claude supplies its project directory as the default workspace. A configured host workspace is a containment boundary: an explicit workspace must be that directory or a descendant, not an arbitrary override. Codex calls normally supply an absolute `workspace` on the initial operation because its packaged stdio server runs from the plugin root; that explicit path is the operation's trust choice. Subsequent job control can use the persisted binding. Job controls manage only MCP-launched jobs, require the same canonical workspace and repository, and cannot inspect or cancel an arbitrary CLI job by ID.
182
+ ### Trust boundary for test runners and custom agents
337
183
 
338
- Attachment waits for the operation to install cancellation handlers, with a 60-second bound. Verified teardown can close a stalled launch; missing identity or inconclusive termination evidence keeps it starting and recoverable by ID. `kimi_pid` is recorded at actual spawn rather than inferred from a later process-list match.
184
+ Rescue, pursue, and write-swarm intentionally allow test and build runners (`go test`, `cargo test`, `pytest`, `<pm> test`). Running tests executes code from the repository (`build.rs`, `conftest.py`, fixtures), which the allowlist cannot confine. Similarly, Kimi discovers project agent profiles and system prompts (`<git-root>/.kimi-code/agents`, `<git-root>/.agents/agents`); while they cannot alter hooks, cwd, or allowlists, they can steer model intent. Run write operations only in repositories you trust.
339
185
 
340
- The MCP task/job ID is preassigned and bound to the job's real `operation_kind`, not merely its lineage. `mcp_tasks` stores launch and ownership metadata; the normal `jobs` table remains the outcome authority. Failed jobs, including budget timeouts, produce completed tasks with `isError:true` and the failed-job artifact, so partial output is not mistaken for a final answer. Supervisor and protocol failures are distinct from ordinary Kimi failures.
186
+ ## Autonomous goal mode (`pursue`, experimental)
341
187
 
342
- Closing an MCP connection does not cancel work. A later server reopens the same store and resumes status/result handling by ID. Generic stale sweeps skip MCP-owned rows, and direct CLI cancellation refuses them; use MCP job controls for those jobs. Companion and observed Kimi-descendant identities include start tokens and process groups; MCP cancellation and stale cleanup revalidate them rather than signalling a recycled PID. Cancellation remains cooperative and does not roll back edits. Pursue teardown and write-swarm patch capture still run through the existing companion path; write-swarm captures its patch on every terminal path before removing the worktree.
188
+ `kimi_write({ mode: "pursue" })` (CLI `companion.sh write --mode pursue`) runs headless goal mode (`kimi -p "/goal -- <objective>"`) under `commandLabel: "rescue"`. Every continuation turn passes the managed PreToolUse hook and workspace allowlist with no Git mutation.
343
189
 
344
- ## Response budgets and partial output (2.2.0)
190
+ The child receives `KIMI_PLUGIN_CC_OPERATION=pursue` from its immutable plan. With a trusted root, the hook allows only exact `GetGoal {}` and terminal `UpdateGoal { status: "complete" | "blocked" }`; goal creation, reactivation, and `SetGoalBudget` stay denied. The mandatory finite wall-clock `--budget` (default 45m, max 24h) is the hard stop; `--turns` is a soft hint. Resume is not exposed because upstream `goalId` and `sessionId` remain separate. Exit codes 0 (complete), 3 (blocked), and 6 (paused) are terminal non-failures and require `system.version` provenance.
345
191
 
346
- Every single-turn command runs under a wall-clock budget: ask, review and
347
- challenge default to 30 minutes, rescue to 45, and `--budget <dur>` (at most
348
- 24h) overrides it per job. The budget is persisted on the job row, so a detached
349
- worker and a same-operation resume use the same ceiling. For these commands the
350
- budget is a response-time limit, not a safety bound: a timeout is a safe
351
- failure. The job stays `failed`; whatever assistant prose had settled is written
352
- into the artifact under a heading that says it is NOT a final answer, and
353
- `result <jobId> --json` reports `partial_output: true` when prose exists.
354
- Cancellation and nonzero exits do not capture partial output. A session ID is kept if Kimi announced it or, on a native-v2 budget timeout, recovered from the session store when exactly one session matches this spawn — created between spawn and settlement in the same directory AND whose journal opens with this job's exact prompt; `result --json` identifies the source in `kimi_session_id_source`, and `error.details.session_recovery` says why no ID was recovered (`none`, `journal_missing:<n>`, `digest_mismatch:<n>`, `ambiguous:<n>`, `enumeration_capped`, `engine_unobserved`). Recovery is bounded and refuses ambiguity, incomplete enumeration, and IDs already used by another job on this host. The prompt binding is what makes attribution proof rather than probability: a concurrent interactive session in the same directory, another host's finished job (host stores cannot see each other's IDs) or a `state.json` planted by repository code running under rescue all fail it unless they carry the exact prompt, and a planted clean journal could otherwise replay attacker-written turns into the next resume. Recovery is skipped when the run never emitted the `system.version` marker, since resume would refuse the row as lineage-unknown anyway. Recovered sessions still require proven native-v2 lineage and the raw plan-taint scan before resume. Inherited budgets are printed to stderr at launch; status and `result --json` expose `budget_source` (`explicit`, `inherited`, or `default`; old non-null budgets report `unknown`).
192
+ ## Bounded swarm on 2.8.0 and newer
355
193
 
356
- Pursue and swarm keep their ceilings as the sole hard bound on autonomy and
357
- cost. One nuance: a run whose process exits cleanly in the same event-loop tick
358
- as the budget timer is accepted as a success rather than discarded, so a goal
359
- can complete at most one tick past its ceiling — teardown has already settled by
360
- then, and nothing runs longer.
194
+ `--max-concurrency` defaults to 4 for read-only swarms (`kimi_read`, `mode: "swarm"`) and 1 for write-swarm (`kimi_write`, `mode: "swarm_patch"`). On exact `2.8.0`:
361
195
 
362
- Every spawn also deletes `KIMI_CODE_TRUST_WORKSPACE` from the child
363
- environment (kimi-code 2.2.0): a trusted workspace boots repo-defined project
364
- MCP servers at bootstrap, outside the PreToolUse hook, and an inherited value
365
- would have trusted every plugin spawn including swarm-write's throwaway
366
- worktree. A directory the operator trusted interactively in the Kimi TUI still
367
- has that property; that persisted-trust route is a documented residual, not
368
- something the plugin can close.
196
+ - Concurrency 1 runs one direct worker in fresh print with no `kimi web` activation and delegation tools denied, preserving read-only or ephemeral-worktree patch rules.
197
+ - Concurrency 2 or more uses short-lived loopback `kimi web --json` activation with an in-memory ephemeral token (`KIMI_CODE_SESSION_IDLE_RECLAIM_MS=0`), explicitly binds `environment_id: "local"` and canonical cwd, verifies direct WebSocket subscription state, disables native `TaskStop` in that fresh owned session (closing automatic Bash backgrounding), runs one `kimi -p -r` print job (`kimi_session_id_source: "preactivated"`), and deactivates swarm mode afterward.
369
198
 
370
- Plugin-managed execution must remain local. Unused remote declarations can remain in operator config. A configured `[environments] default` does not refuse an ask, review, challenge, review gate, rescue or pursue launch on exact 2.5.0 through 2.7.3, fresh or resumed. Upstream reads the default only when it creates a session: a fresh launch passes `--environment local`, which wins over the default, and a resume uses the binding stored with the session, which the plugin still requires to be local and inside the trusted root (`KIMI_SESSION_ENVIRONMENT_UNSAFE`). It still refuses swarm and write-swarm, older certified versions and uncertified releases (`CLI_V2_ENVIRONMENT_UNSAFE`). Setting `[workspace] require_trust = false` is your choice: jobs run with the warning `Workspace trust is disabled in kimi-code's config: MCP servers configured by this repository can start outside the plugin's hook.` A value that is not a boolean, or a `[workspace]` that is not a table, still refuses (`CLI_V2_WORKSPACE_TRUST_UNSAFE`). Launcher environment selectors are reserved. Fresh exact 2.5.0/2.5.1/2.5.2/2.5.3/2.6.0/2.6.2/2.6.3/2.7.2/2.7.3 print selects `--environment local`; resume instead inspects persisted metadata and every agent journal and refuses nonlocal or wrong-root records against the expected execution root (the isolated worktree for swarm-write); older sessions without environment records do not fail this check merely for lacking them.
199
+ Every coordinator and subagent call passes the canonical PreToolUse hook. At concurrency 2 or more, the hook admits `AgentSwarm` only when fresh `items` plus `resume_agent_ids` fit within the concurrency limit; singular `Agent`, forks, malformed calls, fresh singleton waves, and explicit `Bash.run_in_background: true` are denied. `KIMI_CODE_SWARM_TIMEOUT_MS=2147483647` prevents a short child timeout from overlapping waves. Parallel Bash commands have a 60-second default and 300-second maximum foreground timeout (use concurrency 1 for longer tests). Normal exit and cancellation both require identity-verified POSIX process-tree quiescence before capturing artifacts or patches. `--cap` remains a soft lifetime-total hint.
371
200
 
372
- ## Running a newer Kimi than the plugin certifies
201
+ ### Write-capable swarm (`swarm_patch`)
373
202
 
374
- A new Kimi release no longer stops the plugin. When the selected binary is an unlisted plain `2.y.z` release newer than 2.0.0 (a release after 2.7.3, or a gap such as 2.7.0), `ask`, `review`, `challenge` and the review gate run with this warning:
203
+ Write-swarm creates one detached worktree off born `HEAD` under `<pluginRoot>/worktrees/` (never inside your repository), runs Kimi with cwd = that worktree and `KIMI_PLUGIN_CC_WORKSPACE_ROOT` pinned to it, and captures an untruncated binary `.patch` (`git add -N` + `git diff --binary`, no loose objects written) on every terminal path before removing the worktree. Capture or cleanup failure fails the job and retains the worktree. The plugin never applies or commits patches. Use explicit cancellation (`kimi_job({ action: "cancel" })` or `companion.sh job cancel`) rather than interrupting the host so patch capture completes. See [swarm recovery](swarm-recovery.md) for interrupted runs.
375
204
 
376
- ```
377
- kimi-code <version> is not certified by this plugin release; running <operation> read-only with <row> mechanics.
378
- ```
205
+ ## MCP transport, `SEP-2640` skills, and long-running jobs
379
206
 
380
- `<row>` is the highest certified release at or below yours. The plugin borrows only that release's `--environment local` argument. It does not borrow the hook schema, swarm support or any of the relaxations that rest on a proven upstream fact, so on an uncertified release these still refuse: `rescue`, `pursue`, `swarm` and `swarm --write` (`KIMI_CAPABILITY_NOT_CERTIFIED`); `--network`; a configured `default_plan_mode` or `[environments] default`; an enabled tower or subagent-fork selector; a set master experimental flag; and user hooks for `PermissionRequest`, `PermissionResult` or `Interrupt` events. Versions with a pre-release or build suffix and other major versions refuse every operation. Set `KIMI_PLUGIN_CC_STRICT_VERSIONS=1` to make read-only operations refuse uncertified releases too.
207
+ `scripts/companion.sh mcp` runs one dependency-free NDJSON stdio server exposing 4 tools (`kimi_read`, `kimi_write`, `kimi_job`, `kimi_setup`) plus full `SEP-2640` `skills/list`, `skills/get` (returning `frontmatter` and `resources` SHA-256 digests and sizes for `SKILL.md` and `agents/openai.yaml`), `resources/list`, and `resources/read` (with `ttlMs: 0` and `cacheScope: "private"` on `2026-07-28`). It is a thin transport over the exact same certified execution plans, preflights, hooks, budgets, and SQLite store.
381
208
 
382
- To keep every operation available while you track `@latest`, give the plugin its own certified binary by running setup with `--install-kimi` (in Claude Code, `/kimi:setup --install-kimi`; add `--json` for structured output). This installs the highest certified kimi-code into the plugin's data directory, under `kimi-plugin-cc/kimi-bin/<version>/`, and points `kimi-bin/current` at it. It runs npm with install scripts disabled, checks that the installed binary reports exactly that version, and switches `current` only after the check passes; a failure leaves the previous binary in use. It executes a candidate binary only after it resolves to an executable regular file inside the expected kimi-bin version or staging directory. An existing verified install is reused without downloading. This is the only setup command that uses the network. It is not supported on Windows.
209
+ - Modern `2026-07-28` calls carrying per-request `io.modelcontextprotocol/tasks` return native task handles (`tasks/get` and `tasks/cancel`, both requiring an `mcp_tasks` row).
210
+ - Standard `tools/call` requests on `kimi_read` and `kimi_write` default to `wait: true` with a 50-second default `wait_timeout_ms` (configurable up to `86_400_000` ms) and return prose directly. Client disconnect or `notifications/cancelled` stops polling without cancelling the durable Kimi job. Pass `wait: false` to always receive the launch handle (`{ job_id, ... }`) immediately even if already terminal, then poll or cancel with `kimi_job`.
211
+ - Every model tool runs in a supervised detached `mcp-child <uuid>` process (60-second attachment bound, `kimi_pid` recorded at spawn). Disconnects never cancel running jobs; a new server reattaches by durable `job_id`.
212
+ - A configured `KIMI_PLUGIN_CC_MCP_WORKSPACE` acts as a containment boundary (explicit `workspace` must equal it or be a descendant), and `kimi_job` enforces strict canonical `realpath` workspace containment with scoped stale-job sweeps (no cross-workspace monorepo listing or cross-repo sweeps). When absent (as in Codex or generic stdio hosts), callers pass an absolute `workspace`.
213
+ - Direct CLI `cancel` refuses MCP-owned jobs; use `kimi_job({ action: "cancel" })` or `tasks/cancel`, which revalidate recorded companion and Kimi process identities before signalling (including persisted CLI identities for CLI-launched jobs). Failed jobs return `isError: true` with their artifact preserving partial output on budget timeouts.
383
214
 
384
- Jobs choose a binary in this order: `KIMI_PLUGIN_CC_KIMI_BIN` if set; the plugin-owned `current` if it resolves to an executable file inside `kimi-bin/<version>/`; then `kimi` on `PATH`. `/kimi:setup --check` prints a `Kimi binary:` line that names the binary jobs use and why, and warns when the plugin-owned copy is behind the newest certified version or was rejected. Each host keeps its own data directory, so Claude Code, Codex and DSH each need their own `--install-kimi`. Run it again after a plugin update that certifies a newer kimi-code. Old version directories are kept.
215
+ ## Response budgets, local execution, and newer Kimi releases
385
216
 
386
- Every binary shares `~/.kimi-code` (login, config, hook), so nothing else changes. Every spawn exports `KIMI_CODE_NO_AUTO_UPDATE=1`, which suppresses passive updates; a manually staged replacement is detected by the exact probe and first-line version marker, not prevented or rolled back. `NATIVE_V2_CERTIFIED_VERSIONS` in `dist/kimi-engine.js` lists the full-operation certified versions; it excludes narrowed releases such as 2.6.0. `NATIVE_V2_ANY_OPERATION_VERSIONS` is the separate scoped union.
217
+ Single-turn operations default to 30 minutes (`ask`, `review`, `challenge`) or 45 minutes (`rescue`), overridable up to 24 hours with `--budget` / `budget`. Budget timeouts save partial settled prose under a clearly marked NOT-a-final-answer heading (`partial_output: true`) and recover a uniquely matched native-v2 session ID via exact `prompt_digest` binding when no ID was announced. Cancellation never captures partial output.
387
218
 
388
- ## The setup probe
219
+ Every spawn deletes `KIMI_CODE_TRUST_WORKSPACE` and requires local execution. On exact `2.8.0`, configured `[environments] default` is neutralized on fresh non-swarm launches by `--environment local` and checked against stored local bindings on resume; it still refuses swarm and uncertified launches (`CLI_V2_ENVIRONMENT_UNSAFE`). `[workspace] require_trust = false` runs with a launch warning.
389
220
 
390
- `/kimi:setup` runs a two-layer probe before reporting success:
221
+ ### Running a newer Kimi than the plugin certifies
391
222
 
392
- 1. **Direct probe.** Spawns the hook with the absolute Node path parsed back from the installed hook command, without a shell. Sends synthetic PreToolUse stdin with `KIMI_PLUGIN_CC_CMD=review` + a Bash tool request. Asserts exit 2 + non-empty stderr.
393
- 2. **Shell probe.** Re-runs the same payload via `/bin/sh -c "<command>"` — the exact spawn shape kimi-code's hook runner uses. Same assertion.
394
-
395
- Both must pass. The shell probe catches the case where that Node path works directly but `/bin/sh` can't resolve the path through quoting (a `KIMI_PLUGIN_CC_NODE_BIN` override pointing at a binary in a shell-unsafe path, for example). If either probe fails, setup reports failure with the captured stderr and the user can act on a clear signal rather than discover the gap by accident.
396
-
397
- ## How to verify the install yourself
223
+ When your selected binary is an unlisted plain `2.y.z` strictly above `2.8.0`, read-only operations (`ask`, `review`, `challenge`) run with this warning:
398
224
 
225
+ ```text
226
+ kimi-code <version> is not certified by this plugin release; running <operation> read-only with 2.8.0 mechanics.
399
227
  ```
400
- /kimi:setup --check
401
- ```
402
-
403
- Reports the current state without writing. The output line you want to see is `Probe: ok`. If the probe is failing, the `Details:` section shows which layer failed and what stderr was captured.
404
228
 
405
- `/kimi:setup --check` is strict and exits nonzero on failure. It rejects an unloadable TOML file, any invalid configured hook, and any managed block that doesn't pass the [`parseManagedBlock`](../runtime/hooks/managed-block.ts) grammar (missing `[[hooks]]` table, wrong event, present `matcher = ...` line, duplicate blocks, orphan markers, or a stale hook-script path). `/kimi:setup` (without `--check`) can replace a malformed managed block, but it will not overwrite or silently work around invalid foreign config: if the complete candidate file would not load, setup leaves the existing file unchanged and identifies the bad hook or TOML line.
229
+ Uncertified releases borrow only `--environment local`. Write operations, swarm operations, `--network`, configured `default_plan_mode`, configured `[environments] default`, and additive hook events (`PermissionRequest`, `PermissionResult`, `Interrupt`) all refuse. Set `KIMI_PLUGIN_CC_STRICT_VERSIONS=1` to refuse uncertified releases for read-only operations too. Releases below `2.8.0`, pre-release/build-suffixed versions, and other majors refuse every operation.
406
230
 
407
- In Codex, ask `$kimi-setup` to check the active installation. Use its sanitized output for routine diagnosis. Do not print raw `config.toml` or OAuth files: they can contain credentials. Missing comment markers alone do not mean the hook is missing; the verifier also accepts a valid marker-less entry.
231
+ To keep every operation working independently of your `PATH` `kimi`, run `kimi_setup({ action: "install_kimi" })` or `scripts/companion.sh setup --install-kimi`. It installs the newest certified release (`2.8.0`) into `<pluginRoot>/kimi-bin/<version>/` with `--ignore-scripts`, verifies containment and exact `--version`, and swaps `kimi-bin/current` atomically. One install serves all 5 hosts through the shared data directory. Jobs pick `KIMI_PLUGIN_CC_KIMI_BIN`, then `kimi-bin/current`, then `kimi` on `PATH`.
408
232
 
409
- Follow the reported remedy. Only run setup and retry automatically when `retryable_after_setup` is literally `true` and setup succeeds.
233
+ ## Setup probe, verification, and opt-out
410
234
 
411
- ## How to opt out
412
-
413
- ```
414
- /kimi:setup --uninstall
415
- ```
235
+ `setup` and `setup --check` run a two-layer probe:
416
236
 
417
- Removes the managed block from `~/.kimi-code/config.toml`. Subsequent kimi-plugin-cc command invocations:
237
+ 1. Direct probe: spawns `<nodeBin> <hookScriptPath>` using the Node token parsed back from the canonical command with synthetic `KIMI_PLUGIN_CC_CMD=review` `Bash` JSON on stdin, requiring exit 2 and non-empty stderr.
238
+ 2. Shell probe (POSIX): runs the exact canonical command string via `/bin/sh -c "<command>"` with the same payload and assertion.
418
239
 
419
- - Every model-spawning command will refuse before Kimi starts with its command-specific `*_HOOK_NOT_INSTALLED` error. The execution plan checks the hook again: a definite missing or invalid hook refuses with the same command-gate error before any job row exists, and an unverifiable check still proceeds. Rescue, pursue and swarm build their plan before creating a job row, so their refusals leave no row; a row-persisted refusal remains only when the hook disappears after the plan.
420
- - The review gate will skip visibly and allow the host to stop; it will not run an un-enforced model turn.
240
+ Run `kimi_setup({ action: "check" })` or `scripts/companion.sh setup --check` to verify readiness without modifying config. Look for `Probe: ok`. Never read or paste raw `~/.kimi-code/config.toml` or `~/.kimi-code/credentials/` for routine checks.
421
241
 
422
- For tests or deliberate diagnostics only, `KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1` bypasses verification.
242
+ To opt out, run `scripts/companion.sh setup --uninstall`. It removes all canonical and legacy managed blocks, orphan markers, and strictly owned bare hook tables while leaving foreign hooks untouched. Afterward, all 7 model operations refuse before spawn until you run `setup` again.
423
243
 
424
- This diagnostic option bypasses hook verification only. It does not disable an installed hook or bypass engine certification, provenance checks, or the native-v2 preflight. Never use it to repair a failed setup.
244
+ <a id="refusal-codes-of-the-native-v2-contract-v1100"></a>
245
+ ## Native-v2 refusal codes
425
246
 
426
- ## Refusal codes of the native-v2 contract (v1.10.0)
427
-
428
- Every refusal below is raised BEFORE a kimi process is created (or, for the provenance mismatch, before any record reaches the caller) and is **not** repaired by `/kimi:setup` — the remedy is the named setting, binary, or a fresh session. Agents must not retry through setup on these. Every row says so explicitly with `retryable_after_setup: false` in `details` (since 1.10.1; in 1.10.0 `CLI_V2_HOOK_ORDER_UNSAFE`, `INVALID_ENV` and the legacy-v1 form of `KIMI_CAPABILITY_NOT_CERTIFIED` omitted it). The retry gate keys on the field being literally `true`, so an ABSENT field is treated as non-retryable — wrappers must do the same and never assert the field's presence.
247
+ Every refusal below occurs before Kimi starts (or, for provenance mismatch, before any record reaches the caller) and carries `retryable_after_setup: false`. Never retry through `setup` on these codes.
429
248
 
430
249
  | Code | Raised when | Remedy |
431
- |---|---|---|
432
- | `KIMI_CAPABILITY_NOT_CERTIFIED` | the probed `kimi --version` is not in the operation's exact certified set and the operation cannot run uncertified: rescue, pursue, swarm or write-swarm on an unlisted release, any operation on a pre-release, build-suffixed or other-major version, or any operation with `KIMI_PLUGIN_CC_STRICT_VERSIONS=1` | run setup with `--install-kimi`, update kimi-plugin-cc to a release certifying that version, or point `KIMI_PLUGIN_CC_KIMI_BIN` at a certified binary |
433
- | `CLI_V2_PLAN_MODE_CONFIGURED` | `<KIMI_CODE_HOME>/config.toml` sets the default-plan-mode key (any spelling normalizing to `defaultPlanMode`) to anything but literal `false`, and the launch is swarm, write-swarm, on a certified version older than 2.4.0, or on an uncertified release | set it to `false` or remove it |
434
- | `CLI_V2_CONFIG_UNREADABLE` | that config cannot be read safely (symlink, oversized, unparseable TOML, I/O error) — plan mode cannot be verified off. The message gives only `syntax error at line N, column M`, never config text | fix or remove the unreadable file |
435
- | `CLI_V2_ENVIRONMENT_UNSAFE` | `[environments]` is not a table, or `[environments] default` is set and the launch is swarm, write-swarm, on a certified version older than 2.5.0, or on an uncertified release | remove `environments.default`, or use a non-swarm operation on a certified version |
436
- | `CLI_V2_WORKSPACE_TRUST_UNSAFE` | `[workspace]` is not a table, or `require_trust` is not a boolean | fix the value; `false` is accepted with a warning |
437
- | `CLI_V2_EXPERIMENTAL_UNSAFE` | on an uncertified release only: `[experimental] tower` / `subagent_fork` (config) or `KIMI_CODE_EXPERIMENTAL_TOWER` / `…_SUBAGENT_FORK` (env) is truthy | unset the listed selector(s), or use a certified binary |
438
- | `CLI_V2_HOOK_ORDER_UNSAFE` | on a legacy-v1 or uncertified plan only: the master `KIMI_CODE_EXPERIMENTAL_FLAG` is truthy (`1|true|yes|on`) | unset it, or use a certified binary |
439
- | `KIMI_SESSION_PLAN_TAINTED` | the session to resume has a `plan_mode.*`/`plan.*` record in any agent `wire.jsonl`, other than the cancelled create-time pair tolerated on 2.4.0 through 2.7.3 | start a fresh session (nothing saved is modified) |
440
- | `KIMI_SESSION_JOURNAL_UNAVAILABLE` | the session's journals cannot be found or read safely (missing dir, symlinked entry, oversized, not a regular file) | start a fresh session |
441
- | `KIMI_SESSION_LINEAGE_UNKNOWN` | the job to resume has no proven engine provenance, no recorded source job, or a source that owns a different session | start a fresh session; the old job's status/result/replay remain available |
442
- | `KIMI_SESSION_ENGINE_MISMATCH` | the source session ran on a different engine than the selected one | start a fresh session |
443
- | `CLI_ENGINE_PROVENANCE_MISMATCH` | the started engine contradicts the plan: no leading `system.version` marker on a v2 plan, a marker on a v1 plan, a marker whose version is malformed or ≠ the probed version, or any line (meta, unknown-role, malformed) ahead of the marker | the process tree is torn down before any record is delivered; check for a binary swap (`KIMI_PLUGIN_CC_KIMI_BIN`, auto-update) |
444
- | `INVALID_ENV` (`reserved_flag`) | `KIMI_PLUGIN_CC_KIMI_PREFIX_ARGS` carries a kimi root flag (session, prompt, permission/plan, model/profile/roots, or `-V`/`-h`) — the prefix is a launcher shim only | remove the flag from the prefix |
445
- | `CLI_TRUSTED_WORKSPACE_ROOT_INVALID` | on macOS or Linux, a rescue, pursue or swarm-write launch whose run directory or trusted root, or its realpath, contains a backslash, which kimi-code reads as a path separator; details `command_label` and `path`, with no `retryable_after_setup` field (absent means non-retryable) | run from a directory whose path has no backslash |
446
- | `KIMI_HOOK_SET_INVALID` | the configured hooks are invalid for the release the job's execution plan probed (checked with that probe), so kimi-code would drop the whole hooks array and run no hook; stage `kimi-engine.plan`, details `config_path` and `kimi_version`. Setup and the pre-plan command gate probe for themselves | repair or remove the named `[[hooks]]` entry in that config and retry |
447
- | `READ_SCOPE_INVALID` | a job's stored read scope is unreadable, a scope reaches the spawn of a write-capable or uncertified-network job, or a scoped spawn's workspace contains a backslash | start the call again with valid `--read-root`/`--network` flags on a read-only operation |
448
-
449
- ## What this safety story does NOT cover
450
-
451
- - **Repository Git configuration and internal subprocesses.** The managed hook gates tool calls, not every internal subprocess. Upstream's explorer profile builds Git context with `git status` and `git log` outside the child tool hook. On 2.0.2 and 2.1.1, repository settings such as `core.fsmonitor` can execute a helper there, including during read-only swarm startup. Version 2.1.0 hardens these Git invocations; 2.1.1 rolls that hardening back to the previously certified behavior. Use trusted repositories and Git configuration. Certification does not establish a sandbox for hostile repositories or arbitrary Git helpers.
452
- - **Malicious kimi-code binaries.** The threat model assumes the user trusts the kimi-code binary they installed. A hostile binary can ignore the hook entry in its own config.
453
- - **TOCTOU between path check and edit.** The rescue allowlist resolves and checks paths at allowlist time. Between that check and the actual file write, an attacker with workspace write access could swap a symlink. The mitigation is workspace-write-trust — if untrusted code can edit your workspace, you have bigger problems than this plugin.
454
- - **Custom kimi-code skill libraries that bypass the hook.** Hooks fire on tool calls, not on skill activations. A skill that calls `Bash` will be hooked; a skill that performs file ops via a Node binding that doesn't surface as a tool call won't be. The default kimi-code skill catalog uses the standard tool surface.
455
- - **The calling host.** The plugin constrains its Kimi subprocesses. Claude Code and Codex have their own tool permissions; this hook does not govern the host's other tools.
456
- - **Compute exhaustion (no per-turn step cap on kimi-code ≥ 0.6.0).** kimi-code 0.6.0 (PR #186) removed the default 1000-step-per-turn ceiling; absent an explicit `max_steps_per_turn` in config, a turn can loop tool calls without an upstream bound. This is **not a write bypass** — every tool call still passes the PreToolUse hook and (for rescue) the workspace allowlist. The plugin bounds wall-clock and reaps the descendant process tree via its AbortController budget + SIGTERM→SIGKILL cancellation, so a runaway rescue (`/kimi:task --write`) is cancellable; but if you want a hard step ceiling, set `max_steps_per_turn` in your kimi-code config.
457
- - **A poisoned `KIMI_MODEL_*` child environment.** kimi-code 0.6.0 (PR #212) added an opt-in env channel: when `KIMI_MODEL_NAME` is set, kimi synthesizes a provider (base URL + API key) as the default model. `kimi -p` inherits the plugin's parent environment, so a pre-poisoned `KIMI_MODEL_BASE_URL`/`KIMI_MODEL_API_KEY` could reroute model traffic (which may carry workspace file contents from review/ask). The plugin does not sanitize the child environment — this is the same parent-env trust the host already extends. It does **not** touch hook or permission config: kimi-code only writes the synthesized provider/model/thinking entries (never `hooks`), and strips them on any config write-back, so `/kimi:setup`'s managed hook block can neither clobber nor be clobbered by it.
458
- - **Out-of-band binary drift (kimi-code self-upgrades by default on ≥ 0.8.0).** kimi-code 0.8.0 (PR #334) added background automatic upgrades, enabled by default (`autoInstall: true`). The plugin's own `kimi -p` spawns are unaffected — in print mode the install source is forced `unsupported`, so a plugin spawn never swaps the binary mid-flight — but a user who *also* runs the interactive `kimi` TUI can be silently upgraded to a kimi-code the plugin has not compat-audited. This is a *version-assurance* boundary, not permission to guess. Jobs prefer the plugin-owned binary from `--install-kimi` over `PATH`, so this drift reaches only operators without one. Setup emits an "outside tested range" warning and can complete, while every model-spawning command independently probes the exact command tuple: an unlisted plain 2.x runs only the read-only operations, with a warning, and everything else refuses before Kimi starts (`KIMI_CAPABILITY_NOT_CERTIFIED`; certification is per EXACT version on native v2 and per minor on legacy-v1). See [Running a newer Kimi than the plugin certifies](#running-a-newer-kimi-than-the-plugin-certifies). `KIMI_PLUGIN_CC_SKIP_VERSION_PROBE` is tests/smoke only. Legacy-v1 uses the tested minors through 0.41.x, with per-operation minimums, for an explicitly pinned binary.
459
- - **Reads are unconfined by default.** Without `--read-root` or `--network`, read-only operations and rescue can read any file the user can read, including files outside the workspace. Read-only operations still cannot send data out, because the web tools are denied. Confinement is opt-in per call.
460
- - **What `FetchURL` really reaches.** The hook checks only the URL as written. It cannot see DNS resolution or HTTP redirects, so a public name that resolves to, or redirects to, a private address is not caught.
461
- - **`--read-root /`.** A read root of `/` removes the confinement while web access stays on. That is the caller's choice; the plugin does not refuse it.
462
- - **What the read scope covers.** The read scope limits Kimi's tool reads only. A review's status summary and diff cover the whole repository, even when the review starts in a subdirectory, and reach the model whatever the roots are. So do Kimi's own instruction files: `~/.kimi-code/AGENTS.md`, `~/.agents/AGENTS.md`, and `AGENTS.md` or `.kimi-code/AGENTS.md` in each directory from the Git root down to the working directory. Untracked files are not embedded; Kimi reads them with tools, so any outside the roots are denied.
463
- - **Turns the networked-resume check cannot see.** The networked-resume check sees only the turns this host's plugin job store recorded for the session; a turn added to the same session directly in Kimi, or through another host's plugin install, is invisible to it, so its reads can be carried into a `--network` turn.
464
- - **Hard links into a read root.** A hard link inside a read root counts as inside the root, even when another name for the same file lies outside it.
465
- - **Another host's older hook.** Kimi runs every configured hook and any denial wins, so until another host (for example Codex next to Claude Code) updates the plugin and runs setup, its older hook still checks every plugin job by its own rules and can deny what this version allows, such as `WebSearch` and `FetchURL` under `--network`, or `rm`, `mv`, `cp` and `mkdir` under rescue. Each job launch and each setup then carries the warning `The <host> host's kimi-plugin-cc hook (version <x> | an unknown version) also checks this job with its older rules; it can deny what this version allows. Update the plugin in <host> and run its setup.`
466
- - **The session preview race.** After a run settles, the plugin sets the native session's preview to that run's request. A Desktop turn that finishes after the plugin's run and before this sync has its preview overwritten.
467
- - **Your own Kimi settings outside plugin jobs.** The plugin neutralizes or refuses settings only for the children it starts. Plan mode, tower, subagent fork, a remote default environment or disabled workspace trust in your own interactive Kimi sessions are yours to manage.
468
- - **New permission approval hook events are observability, not a decision surface.** kimi-code 0.8.0 (PR #336) added `PermissionRequest`/`PermissionResult` hook events. A user *can* register `[[hooks]]` blocks for them in `config.toml`, but they fire fire-and-forget (the result is discarded) and only inside the interactive approval/ask path — which `kimi -p` auto mode shadows. They **cannot** approve a tool the PreToolUse hook denied, cannot run on the plugin's `-p` path, and live in a disjoint event bucket from the managed `PreToolUse` block (no impersonation). Setup validates every configured hook against the reviewed schema for the probed CLI version. Version 2.0.0 has an explicitly reviewed schema; unknown major-version schemas fail closed.
469
-
470
- ## Known limitation: Node version manager switches
471
-
472
- The verifier does exact equality on the installed `command = "..."` against the canonical command built by `runtime/hooks/install-paths.ts`. It prefers a stable absolute Node path when that path resolves to the running interpreter. If you use `nvm`, `asdf`, `mise`, or `fnm` and switch the active Node version after `/kimi:setup`, the canonical command's Node binary path changes and the verifier rejects the previously-installed block. Every model-spawning command will refuse; the review gate will skip.
473
-
474
- The workaround is to re-run `/kimi:setup` after any Node version switch. The strict behavior is deliberate — loosening the exact-equality check to "survive" Node moves would reopen the crafted-command bypass the audit closed (reports 27/28), so it stays strict by design.
475
-
476
- **Soft-recovery (H4):** to make that strict failure *legible* instead of cryptic, the verifier classifies a command mismatch when the block is otherwise valid. Rather than dumping the raw expected-vs-got command, it reports the drift class — e.g. *"Node binary drift: the installed hook pins `/opt/homebrew/Cellar/node/26.0.0/bin/node`, which no longer exists on disk (this companion runs `…/26.3.0/…`) — the classic Node-upgrade / version-manager drift … Run /kimi:setup to re-pin"*, or *"Hook script path drift … likely a plugin update or move"* when the version-stamped plugin path moved instead. A gone interpreter is the unambiguous signal. The same classified reason surfaces from `/kimi:setup --check`. This changes only the message; the strict installed/not-installed decision is unchanged.
477
-
478
- **Stable Node path (v1.9.0).** `process.execPath` is fully symlink-resolved, so under Homebrew it names `…/Cellar/node/<version>/bin/node` — a path that changes on every `brew upgrade node` and therefore invalidated **both** hosts' blocks at once, with no user-visible cause. `resolveNodeBinary` now prefers `process.argv0` (the name the interpreter was actually invoked with; `companion.sh` resolves `node` through the stable `/opt/homebrew/bin/node` symlink), **but only when that path is absolute AND `realpath`-identical to `process.execPath`**. The guard is the safety argument: the substitution can pick a more stable *name* for the interpreter already running, and provably never a *different* binary. Any doubt falls back to `execPath`. Exact-equality verification, absolute-path enforcement, and the shell probe are unchanged. It also keeps hook and companion on one interpreter by construction — previously the companion could run a freshly upgraded Node while the hook stayed pinned to a Cellar path `brew` had deleted, which fails to spawn and (exit 127) is read as **allow**. Version-manager users (nvm/asdf/mise/fnm) expose version-stamped paths directly, so `argv0 === execPath` and the limitation above still applies to them unchanged.
479
-
480
- ## Hook-path drift is repaired by the caller, never by the verifier (v1.9.0)
481
-
482
- Plugin install paths are version-stamped (`…/kimi-marketplace/kimi/<version>/dist/hooks/approval-hook.js`), so a plugin update moves the hook script and the recorded command stops matching. That refusal is correct and fail-closed, but it is also routine, so refusals now carry a **machine-readable** classification alongside the prose reason:
483
-
484
- `HookInstallStatus.drift` = `{axis: "hook-script" | "node-bin" | "both", installedCommand, expectedCommand}`, surfaced in every refusal's `RuntimeError.details` as `drift_axis` / `retryable_after_setup`. It is populated **only** when a structurally sound block's command names different paths, and is derived **after** byte-exact equality has already failed — it can never influence the installed decision, exactly like the H4 prose classification. Refusals that re-pinning cannot fix (unresolvable command, unreadable config, invalid hook set, duplicate/orphan markers, missing script) carry no drift at all.
485
-
486
- Agents use `retryable_after_setup`, not `drift_axis` alone. They run setup for the affected host and retry once only when that field is literally `true` and setup exits successfully. This includes a moved hook script and a Node path spelling change proven to name the same interpreter. A different interpreter is not automatically retryable. `node-bin-not-executable` requires fixing the reported Node path; setup alone is not its remedy.
487
-
488
- **The verifier never repairs the config itself.** An in-verifier auto-repin was specified and rejected after two independent adversarial reviews found: a lock self-deadlock (the repin path and the install transaction both take a non-reentrant lock); a false "target cannot be steered" premise (`KIMI_PLUGIN_CC_HOOK_SCRIPT`/`NODE_BIN`/`HOST_ID` override resolution, and every proposed gate reads the same env, so they corroborate nothing); no version-monotonicity bound, letting a stale session pin the *global* block down to a pre-1.0.3 hook carrying the CRITICAL exec-delegation bypass; and a write→spawn TOCTOU in which one session repins to a deleted path inside another's spawn window, producing exit 127 → allow → an unenforced `rescue` run. Keeping repair in the caller makes it a **visible, permission-gated action in the transcript** instead of a silent mutation of a security surface. Full analysis: `.claude/hook-pin-durability-spec-2026-07-25.md`.
250
+ | --- | --- | --- |
251
+ | `KIMI_CAPABILITY_NOT_CERTIFIED` | probed `kimi --version` is below `2.8.0` (including `legacy-v1`), is a write/swarm call on an unlisted `> 2.8.0` release, is a pre-release/build-suffixed or non-2.x version, or `KIMI_PLUGIN_CC_STRICT_VERSIONS=1` is set on an uncertified release | run `kimi_setup({ action: "install_kimi" })` / `setup --install-kimi`, update the plugin, or set `KIMI_PLUGIN_CC_KIMI_BIN` to `>= 2.8.0` |
252
+ | `CLI_V2_PLAN_MODE_CONFIGURED` | `<KIMI_CODE_HOME>/config.toml` sets any spelling of `default_plan_mode` to non-`false` on a swarm, write-swarm, or uncertified launch | set `default_plan_mode = false` or remove it |
253
+ | `CLI_V2_CONFIG_UNREADABLE` | config cannot be read safely (symlink, oversized, unparseable TOML showing only `syntax error at line N, column M`) | fix or remove the unreadable file |
254
+ | `CLI_V2_ENVIRONMENT_UNSAFE` | `[environments]` is not a table, or `[environments] default` is set on a swarm, write-swarm, or uncertified launch | remove `environments.default` or use a non-swarm op on a certified release |
255
+ | `CLI_V2_WORKSPACE_TRUST_UNSAFE` | `[workspace]` is not a table, or `require_trust` is not a boolean | fix the value (`false` is allowed with a warning) |
256
+ | `CLI_V2_EXPERIMENTAL_UNSAFE` | plan-less launch with truthy `[experimental]` `tower`/`subagent_fork` or matching per-flag env (or unreadable config on an uncertified release) | unset the listed selectors |
257
+ | `CLI_V2_HOOK_ORDER_UNSAFE` | plan-less launch with truthy `KIMI_CODE_EXPERIMENTAL_FLAG` | unset `KIMI_CODE_EXPERIMENTAL_FLAG` |
258
+ | `KIMI_SESSION_PLAN_TAINTED` | resumed session has a `plan_mode.*`/`plan.*` record in any agent `wire.jsonl` outside the tolerated cancelled create-time pair (allowing only the 3 MCP bookkeeping records between enter and cancel) | start a fresh session |
259
+ | `KIMI_SESSION_TOWER_ACTIVE` | resumed session's main journal leaves the main agent in tower mode | run `/tower` in that session to turn tower mode off, or start a fresh session |
260
+ | `KIMI_SESSION_JOURNAL_UNAVAILABLE` | session journals are missing, symlinked, oversized, or non-regular files | start a fresh session |
261
+ | `KIMI_SESSION_LINEAGE_UNKNOWN` | resumed job has no proven engine provenance, no source job, or a mismatched session binding | start a fresh session; old job `status`/`result`/`replay` still work |
262
+ | `KIMI_SESSION_ENGINE_MISMATCH` | resumed source session is proven `legacy-v1` while 3.1.0 launches only `native-v2` | start a fresh session |
263
+ | `CLI_ENGINE_PROVENANCE_MISMATCH` | first stream-json line is missing `system.version`, mismatches the probed version, or has another line ahead of it | process tree is torn down; check for a binary swap |
264
+ | `INVALID_ENV` (`reserved_flag`) | `KIMI_PLUGIN_CC_KIMI_PREFIX_ARGS` contains a plugin-owned Kimi root flag (`-r`, `-p`, `--plan`, `--environment`, and so on) | remove the flag from the launcher prefix |
265
+ | `CLI_TRUSTED_WORKSPACE_ROOT_INVALID` | POSIX write launch whose run directory or trusted root (or realpath) contains a backslash | run from a path without backslashes |
266
+ | `KIMI_HOOK_SET_INVALID` | configured hooks fail validation for the execution plan's probed CLI release so Kimi would drop all hooks | fix or remove the named `[[hooks]]` entry in `config.toml` |
267
+ | `READ_SCOPE_INVALID` | corrupt stored `read_scope`, scope on a write/uncertified-network spawn, or backslash in a scoped workspace | re-run with valid scope flags on a read-only operation |
268
+
269
+ ## What this safety story does not cover
270
+
271
+ - Repository Git configuration and internal subprocesses: the hook gates model tool calls, not internal Git helpers (`core.fsmonitor`) or POSIX lock-contention `ps` calls executed by Kimi itself.
272
+ - Malicious `kimi-code` binaries: the threat model assumes you trust your installed Kimi binary.
273
+ - TOCTOU between path check and file write: an attacker who already has write access to your workspace can swap symlinks after validation.
274
+ - Custom Kimi skill libraries that bypass tools via native bindings.
275
+ - The calling host's own tools outside Kimi subprocesses.
276
+ - Compute exhaustion without `max_steps_per_turn`: the plugin bounds wall-clock time via finite budgets, not token spend; set `max_steps_per_turn` in Kimi config for a step cap.
277
+ - Pre-poisoned `KIMI_MODEL_*` parent environment variables that reroute API traffic.
278
+ - Unconfined default reads: without `--read-root` or `--network`, read-only and rescue jobs can read any file your user account can read.
279
+ - `FetchURL` DNS resolution and HTTP redirects: the hook inspects only the URL as written, and `--read-root /` removes read confinement if you pass it.
280
+ - Non-tool content in scoped calls: review diffs cover the repository and Kimi's own `AGENTS.md` files still reach the model; hard links inside a read root count as inside it; turns added directly in Kimi outside the plugin store are invisible to the networked-resume check.
281
+ - Un-consolidated legacy hooks: if an older 3.0 install left a `:<host-id>` hook block in `config.toml`, run `setup` once in 3.1.0 to consolidate it so old rules cannot veto new operations.
282
+ - Session preview race: a Kimi Desktop turn finishing between plugin exit and preview sync can have its preview overwritten.
283
+ - Your interactive Kimi sessions outside plugin jobs.
284
+
285
+ ## Node version switches and caller-only drift repair
286
+
287
+ The verifier checks exact command equality against the canonical command built from the resolved Node binary and `<pluginRoot>/hook/approval-hook.js`. `preferStableNodePath` prefers `process.argv0` over `process.execPath` only when absolute and `realpath`-identical (preventing Homebrew Cellar upgrades from breaking the pin). If you switch Node versions with `nvm`, `asdf`, `mise`, or `fnm`, the pinned Node path changes and commands refuse until you run `setup` again.
288
+
289
+ When a structurally valid block has a mismatched command, `HookInstallStatus.drift` classifies the axis (`hook-script`, `node-bin`, or `both`) and sets `retryable_after_setup: true` only when setup can safely re-pin it (a moved hook script, or a Node path spelling proven to name the same file). When `KIMI_PLUGIN_CC_DATA` overrides the data directory while the installed block already points at the default shared canonical hook, drift marks `retryable_after_setup: false` and instructs unsetting `KIMI_PLUGIN_CC_DATA` and restarting the host instead of re-pinning the shared block. Agents may run setup and retry once only when `retryable_after_setup` is literally `true` and setup exits 0. `node-bin-not-executable` requires repairing the Node binary. The verifier never auto-repins `config.toml` itself (rejected due to lock deadlock, env-steering, downgrade, and spawn-window TOCTOU risks).
290
+
291
+ ## Hook-escape monitor (detection evidence)
292
+
293
+ `runtime/hook-escape.ts` replays pure hook denials against streamed tool results. A result matching the managed denial (exact or followed only by upstream repeat-breaker `<system-reminder>` blocks) clears the pending call. Any other result records `mismatch` with a 200-character excerpt; a missing result at settlement records `unresolved`. Findings are logged (`hook_escape`), persisted in `hook_escapes`, printed as a stderr `safety hook notice`, and returned in `job status` and `job result --json`, but never fail the job because print-mode tool records lack an outcome field. Treat a finding as a cue to run `setup --check` and inspect the excerpt.
489
294
 
490
295
  ## Reporting safety issues
491
296
 
492
- If you find a way to coax a read-only operation (`/kimi:task` without `--write`, `/kimi:review` with or without `--challenge`, read-only `/kimi:swarm`, or the review gate) into running a non-read tool — or to make `/kimi:task --write` mutate `.git/` or escape the workspace — please open a GitHub security advisory rather than a public issue.
493
-
494
- ## Hook-escape monitor: detection evidence
495
-
496
- **Hook-escape monitor** (§1): the cli-client replays the pure hook policy on every streamed `tool_calls` entry; a call the policy denies whose tool result is not the hook's denial (byte-exact, or with upstream's repeat-breaker `<system-reminder>` decoration / handoff text) is recorded as `mismatch`, and a denied call still without a result at settlement as `unresolved`. Findings are **detection evidence, never a failure**: logged (`hook_escape`), persisted on the job row (`hook_escapes`, JSON), exposed by `status`/`result --json`, printed as a stderr `safety hook notice`, and carried in timeout details; the run continues, the job's outcome is unchanged, and the review gate stays fail-open and only annotates. The stream has no outcome field, so a mismatch is equally an upstream pre-hook rejection (unknown tool, disabled tool, invalid args, sensitive path, per-tool resolve errors), a coexisting hook or permission policy blocking first, or hook drift — failing the job needs positive execution evidence this stream does not provide. Streamed calls under read-only labels are covered (swarm subagents are in-process, not streamed); write labels only for the pure denials (plan/goal tools).
497
-
498
- A denied attempt alone is not a finding: the hook's denial text in the corresponding tool result (byte-exact, or carrying upstream's repeat-breaker decoration) proves enforcement and clears it. Anything else is recorded as `mismatch` with a 200-character excerpt; a denied call with no result at settlement as `unresolved`. **What a finding means:** the model received something other than the managed denial. On certified 2.2.0 that is produced just as readily by calls upstream rejects before the hook runs (`Tool "LS" not found`, `Invalid args for tool …`, the sensitive-path `PathSecurityError` for `.env`, per-tool resolve errors, `Tool skipped because a previous tool call stopped the turn.`), by a coexisting PreToolUse hook ahead of the managed block or an upstream permission policy blocking first, or by a cancel/budget abort landing before the result — none of which executed anything — as by a hook that failed open. Because the stream carries no outcome field, the plugin cannot tell these apart, so it reports and does not fail: the job completes or fails on its own merits, `status`/`result --json` carry `hook_escapes`, stderr prints a `safety hook notice`, and the review gate annotates `systemMessage` without changing its decision. Treat a finding as a prompt to run `/kimi:setup --check` and read the excerpt, not as proof of a breach; treat a *recurring* `mismatch` whose excerpt looks like tool output (`Wrote N bytes to …`) as a drifted hook. Coverage is streamed calls under read-only labels and pure denials under write labels — not filesystem-dependent rescue allowlist decisions, not swarm subagent calls (in-process, never streamed). Non-vacuous live control (CLI 2.2.0, 2026-10-15): with the hook command pointed at a nonexistent script upstream failed open, `Write` created the file, and the finding was `mismatch` with excerpt `Wrote 7 bytes to ESCAPE.txt`; with the hook intact the same prompt produced the byte-exact denial and no finding. Enforcement (stopping the run, failing the job) is deliberately not shipped: it needs positive execution evidence. The upstream ask, filed as MoonshotAI/kimi-code#4241, is an `outcome: executed|vetoed|rejected` field on print-mode tool records; a plugin-side alternative is a per-job trace the hook writes before it exits.
499
-
500
- ## Review-gate thinking request
501
-
502
- The gate requests `off` through `KIMI_MODEL_THINKING_EFFORT` by default. `KIMI_PLUGIN_CC_REVIEW_GATE_THINKING=inherit` leaves the ambient environment alone; any other non-empty value matching `/^[a-z][a-z0-9-]{0,31}$/` is passed verbatim. This is best-effort, never an enforced latency guarantee: non-trait-driven/BYO providers ignore it silently, an already-off base remains off, and an always-thinking model receives `off` unnormalized and may continue reasoning. Stream-json has no thinking deltas, so honouring the request cannot be observed. The 8 s budget and fail-open-on-timeout contract are unchanged; a hook-escape finding only annotates the gate's `systemMessage`. `KIMI_PLUGIN_CC_REVIEW_GATE_THINKING` is lowercased like `--thinking`.
297
+ If you find a way to make a read-only operation run a non-read tool, or make a write operation mutate `.git/` or escape its trusted root, open a GitHub security advisory rather than a public issue.