kimi-plugin-cc 2.7.3 → 3.1.0

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 (317) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -16
  3. package/README.md +428 -515
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +14 -19
  7. package/dist/cli-client.js +163 -105
  8. package/dist/commands/ask.js +44 -96
  9. package/dist/commands/cancel.js +11 -59
  10. package/dist/commands/cli-helpers.js +102 -1
  11. package/dist/commands/models.js +2 -3
  12. package/dist/commands/pursue.js +8 -21
  13. package/dist/commands/registry.js +7 -26
  14. package/dist/commands/repair-sessions.js +121 -12
  15. package/dist/commands/replay.js +4 -3
  16. package/dist/commands/rescue.js +29 -87
  17. package/dist/commands/result.js +7 -1
  18. package/dist/commands/review.js +28 -18
  19. package/dist/commands/setup.js +813 -462
  20. package/dist/commands/status.js +2 -2
  21. package/dist/commands/swarm.js +112 -125
  22. package/dist/commands/worker.js +1 -2
  23. package/dist/companion.js +145 -19
  24. package/dist/git.js +1 -9
  25. package/dist/help.js +13 -9
  26. package/dist/hook-escape.js +7 -16
  27. package/dist/hooks/approval-hook.js +1766 -87
  28. package/dist/hooks/approval-policy.js +86 -19
  29. package/dist/hooks/config-safety.js +31 -64
  30. package/dist/hooks/hook-timing.js +48 -0
  31. package/dist/hooks/install-paths.js +179 -107
  32. package/dist/hooks/install.js +126 -53
  33. package/dist/hooks/managed-block.js +121 -127
  34. package/dist/job-store.js +206 -166
  35. package/dist/jobs.js +66 -19
  36. package/dist/kimi-command.js +74 -1
  37. package/dist/kimi-engine.js +198 -127
  38. package/dist/kimi-errors.js +15 -70
  39. package/dist/kimi-home.js +6 -0
  40. package/dist/kimi-journal.js +42 -0
  41. package/dist/kimi-releases.js +123 -0
  42. package/dist/kimi-timeouts.js +2 -16
  43. package/dist/kimi-version-probe.js +24 -108
  44. package/dist/logging.js +12 -7
  45. package/dist/mcp/binding.js +13 -4
  46. package/dist/mcp/job-control.js +390 -95
  47. package/dist/mcp/launcher.js +13 -7
  48. package/dist/mcp/operations.js +405 -179
  49. package/dist/mcp/protocol.js +124 -33
  50. package/dist/mcp/skills.js +130 -0
  51. package/dist/mcp/stdio.js +18 -4
  52. package/dist/model-command.js +5 -3
  53. package/dist/native-v2-preflight.js +243 -80
  54. package/dist/parsing.js +211 -243
  55. package/dist/paths.js +28 -10
  56. package/dist/plugin-data.js +28 -83
  57. package/dist/process-tree.js +35 -24
  58. package/dist/read-scope.js +435 -0
  59. package/dist/render.js +58 -46
  60. package/dist/rescue-approval.js +461 -84
  61. package/dist/session-references.js +216 -0
  62. package/dist/session-title.js +26 -6
  63. package/dist/stream-json.js +1 -3
  64. package/dist/surface-routing.js +108 -0
  65. package/dist/swarm-activation.js +74 -188
  66. package/dist/swarm-policy.js +2 -1
  67. package/dist/swarm-recovery.js +2 -1
  68. package/dist/util.js +28 -0
  69. package/dist/version.js +1 -1
  70. package/docs/migration.md +45 -206
  71. package/docs/models.md +24 -66
  72. package/docs/safety.md +198 -353
  73. package/docs/session-visibility.md +25 -13
  74. package/docs/swarm-recovery.md +26 -20
  75. package/dsh/index.json +54 -0
  76. package/mcp_config.json +10 -0
  77. package/package.json +23 -82
  78. package/plugin.json +19 -0
  79. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  80. package/plugins/kimi-codex/.mcp.json +3 -3
  81. package/plugins/kimi-codex/dist/background-spawn.js +14 -19
  82. package/plugins/kimi-codex/dist/cli-client.js +163 -105
  83. package/plugins/kimi-codex/dist/commands/ask.js +44 -96
  84. package/plugins/kimi-codex/dist/commands/cancel.js +11 -59
  85. package/plugins/kimi-codex/dist/commands/cli-helpers.js +102 -1
  86. package/plugins/kimi-codex/dist/commands/models.js +2 -3
  87. package/plugins/kimi-codex/dist/commands/pursue.js +8 -21
  88. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  89. package/plugins/kimi-codex/dist/commands/repair-sessions.js +121 -12
  90. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  91. package/plugins/kimi-codex/dist/commands/rescue.js +29 -87
  92. package/plugins/kimi-codex/dist/commands/result.js +7 -1
  93. package/plugins/kimi-codex/dist/commands/review.js +28 -18
  94. package/plugins/kimi-codex/dist/commands/setup.js +813 -462
  95. package/plugins/kimi-codex/dist/commands/status.js +2 -2
  96. package/plugins/kimi-codex/dist/commands/swarm.js +112 -125
  97. package/plugins/kimi-codex/dist/commands/worker.js +1 -2
  98. package/plugins/kimi-codex/dist/companion.js +145 -19
  99. package/plugins/kimi-codex/dist/git.js +1 -9
  100. package/plugins/kimi-codex/dist/help.js +13 -9
  101. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  102. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1766 -87
  103. package/plugins/kimi-codex/dist/hooks/approval-policy.js +86 -19
  104. package/plugins/kimi-codex/dist/hooks/config-safety.js +31 -64
  105. package/plugins/kimi-codex/dist/hooks/hook-timing.js +48 -0
  106. package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
  107. package/plugins/kimi-codex/dist/hooks/install.js +126 -53
  108. package/plugins/kimi-codex/dist/hooks/managed-block.js +121 -127
  109. package/plugins/kimi-codex/dist/job-store.js +206 -166
  110. package/plugins/kimi-codex/dist/jobs.js +66 -19
  111. package/plugins/kimi-codex/dist/kimi-command.js +74 -1
  112. package/plugins/kimi-codex/dist/kimi-engine.js +198 -127
  113. package/plugins/kimi-codex/dist/kimi-errors.js +15 -70
  114. package/plugins/kimi-codex/dist/kimi-home.js +6 -0
  115. package/plugins/kimi-codex/dist/kimi-journal.js +42 -0
  116. package/plugins/kimi-codex/dist/kimi-releases.js +123 -0
  117. package/plugins/kimi-codex/dist/kimi-timeouts.js +2 -16
  118. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -108
  119. package/plugins/kimi-codex/dist/logging.js +12 -7
  120. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  121. package/plugins/kimi-codex/dist/mcp/job-control.js +390 -95
  122. package/plugins/kimi-codex/dist/mcp/launcher.js +13 -7
  123. package/plugins/kimi-codex/dist/mcp/operations.js +405 -179
  124. package/plugins/kimi-codex/dist/mcp/protocol.js +124 -33
  125. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  126. package/plugins/kimi-codex/dist/mcp/stdio.js +18 -4
  127. package/plugins/kimi-codex/dist/model-command.js +5 -3
  128. package/plugins/kimi-codex/dist/native-v2-preflight.js +243 -80
  129. package/plugins/kimi-codex/dist/parsing.js +211 -243
  130. package/plugins/kimi-codex/dist/paths.js +28 -10
  131. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  132. package/plugins/kimi-codex/dist/process-tree.js +35 -24
  133. package/plugins/kimi-codex/dist/read-scope.js +435 -0
  134. package/plugins/kimi-codex/dist/render.js +58 -46
  135. package/plugins/kimi-codex/dist/rescue-approval.js +461 -84
  136. package/plugins/kimi-codex/dist/session-references.js +216 -0
  137. package/plugins/kimi-codex/dist/session-title.js +26 -6
  138. package/plugins/kimi-codex/dist/stream-json.js +1 -3
  139. package/plugins/kimi-codex/dist/surface-routing.js +108 -0
  140. package/plugins/kimi-codex/dist/swarm-activation.js +74 -188
  141. package/plugins/kimi-codex/dist/swarm-policy.js +2 -1
  142. package/plugins/kimi-codex/dist/swarm-recovery.js +2 -1
  143. package/plugins/kimi-codex/dist/util.js +28 -0
  144. package/plugins/kimi-codex/dist/version.js +1 -1
  145. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  146. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  147. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  148. package/scripts/companion.sh +4 -15
  149. package/skills/kimi/SKILL.md +77 -0
  150. package/skills/kimi/agents/openai.yaml +6 -0
  151. package/CHANGELOG.md +0 -1333
  152. package/agents/kimi-ask.md +0 -89
  153. package/agents/kimi-challenge.md +0 -86
  154. package/agents/kimi-pursue.md +0 -93
  155. package/agents/kimi-rescue.md +0 -92
  156. package/agents/kimi-review.md +0 -86
  157. package/agents/kimi-swarm-write.md +0 -96
  158. package/agents/kimi-swarm.md +0 -86
  159. package/commands/README.md +0 -16
  160. package/commands/ask.md +0 -38
  161. package/commands/cancel.md +0 -17
  162. package/commands/challenge.md +0 -35
  163. package/commands/pursue.md +0 -41
  164. package/commands/replay.md +0 -13
  165. package/commands/rescue.md +0 -38
  166. package/commands/result.md +0 -13
  167. package/commands/review.md +0 -35
  168. package/commands/setup.md +0 -23
  169. package/commands/status.md +0 -13
  170. package/commands/swarm.md +0 -44
  171. package/dist/commands/not-implemented.js +0 -4
  172. package/dist/commands/review-gate.js +0 -390
  173. package/dist/config.js +0 -22
  174. package/dist/dsh/companion.js +0 -177
  175. package/dist/dsh/index.js +0 -169
  176. package/dist/hooks/review-gate-stop.js +0 -19
  177. package/dist/schemas/review-gate-output.js +0 -43
  178. package/docs/registry-releases.md +0 -228
  179. package/docs/upstream-2.4.1-certification.md +0 -54
  180. package/docs/upstream-2.5.0-certification.md +0 -52
  181. package/docs/upstream-2.5.1-certification.md +0 -47
  182. package/docs/upstream-2.5.2-certification.md +0 -40
  183. package/docs/upstream-2.5.3-certification.md +0 -73
  184. package/docs/upstream-2.6.0-certification.md +0 -65
  185. package/docs/upstream-2.6.2-certification.md +0 -144
  186. package/docs/upstream-2.6.3-certification.md +0 -100
  187. package/docs/upstream-2.7.2-certification.md +0 -113
  188. package/docs/upstream-2.7.3-certification.md +0 -83
  189. package/docs/windows-validation.md +0 -39
  190. package/hooks/README.md +0 -9
  191. package/hooks/hooks.json +0 -16
  192. package/plugins/kimi-codex/dist/commands/not-implemented.js +0 -4
  193. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -390
  194. package/plugins/kimi-codex/dist/config.js +0 -22
  195. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  196. package/plugins/kimi-codex/dist/dsh/index.js +0 -169
  197. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  198. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -43
  199. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  200. package/plugins/kimi-codex/skills/kimi-ask/SKILL.md +0 -35
  201. package/plugins/kimi-codex/skills/kimi-ask/agents/openai.yaml +0 -6
  202. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  203. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  204. package/plugins/kimi-codex/skills/kimi-challenge/SKILL.md +0 -34
  205. package/plugins/kimi-codex/skills/kimi-challenge/agents/openai.yaml +0 -6
  206. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  207. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  208. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  209. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  210. package/plugins/kimi-codex/skills/kimi-rescue/SKILL.md +0 -34
  211. package/plugins/kimi-codex/skills/kimi-rescue/agents/openai.yaml +0 -6
  212. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  213. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  214. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -34
  215. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  216. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -34
  217. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  218. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  219. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  220. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -35
  221. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  222. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +0 -36
  223. package/plugins/kimi-codex/skills/kimi-swarm-write/agents/openai.yaml +0 -6
  224. package/plugins/kimi-dsh/LICENSE +0 -201
  225. package/plugins/kimi-dsh/README.md +0 -83
  226. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  227. package/plugins/kimi-dsh/dist/background-spawn.js +0 -216
  228. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  229. package/plugins/kimi-dsh/dist/cli-client.js +0 -1078
  230. package/plugins/kimi-dsh/dist/commands/ask.js +0 -336
  231. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -216
  232. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -201
  233. package/plugins/kimi-dsh/dist/commands/models.js +0 -140
  234. package/plugins/kimi-dsh/dist/commands/not-implemented.js +0 -4
  235. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -307
  236. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  237. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  238. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -160
  239. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  240. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -347
  241. package/plugins/kimi-dsh/dist/commands/result.js +0 -66
  242. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -390
  243. package/plugins/kimi-dsh/dist/commands/review.js +0 -220
  244. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1129
  245. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  246. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -849
  247. package/plugins/kimi-dsh/dist/commands/worker.js +0 -25
  248. package/plugins/kimi-dsh/dist/companion.js +0 -97
  249. package/plugins/kimi-dsh/dist/config.js +0 -22
  250. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  251. package/plugins/kimi-dsh/dist/dsh/index.js +0 -169
  252. package/plugins/kimi-dsh/dist/errors.js +0 -40
  253. package/plugins/kimi-dsh/dist/git.js +0 -224
  254. package/plugins/kimi-dsh/dist/help.js +0 -43
  255. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  256. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -104
  257. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -233
  258. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -665
  259. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  260. package/plugins/kimi-dsh/dist/hooks/install.js +0 -210
  261. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -684
  262. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  263. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  264. package/plugins/kimi-dsh/dist/job-store.js +0 -659
  265. package/plugins/kimi-dsh/dist/jobs.js +0 -217
  266. package/plugins/kimi-dsh/dist/kimi-command.js +0 -71
  267. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -675
  268. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -260
  269. package/plugins/kimi-dsh/dist/kimi-home.js +0 -9
  270. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  271. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -234
  272. package/plugins/kimi-dsh/dist/logging.js +0 -22
  273. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  274. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -345
  275. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -257
  276. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -301
  277. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -275
  278. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  279. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -78
  280. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  281. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  282. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  283. package/plugins/kimi-dsh/dist/model-command.js +0 -32
  284. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -525
  285. package/plugins/kimi-dsh/dist/package.json +0 -1
  286. package/plugins/kimi-dsh/dist/parsing.js +0 -620
  287. package/plugins/kimi-dsh/dist/paths.js +0 -27
  288. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  289. package/plugins/kimi-dsh/dist/process-tree.js +0 -586
  290. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  291. package/plugins/kimi-dsh/dist/render.js +0 -177
  292. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -865
  293. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -43
  294. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  295. package/plugins/kimi-dsh/dist/session-title.js +0 -293
  296. package/plugins/kimi-dsh/dist/stream-json.js +0 -346
  297. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1197
  298. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -73
  299. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -165
  300. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  301. package/plugins/kimi-dsh/dist/types.js +0 -1
  302. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  303. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  304. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  305. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  306. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  307. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  308. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  309. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  310. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  311. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  312. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  313. package/plugins/kimi-dsh/dist/version.js +0 -7
  314. package/plugins/kimi-dsh/package.json +0 -78
  315. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  316. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  317. package/scripts/review-gate-hook.sh +0 -32
package/docs/safety.md CHANGED
@@ -1,52 +1,49 @@
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.0 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
- Native agent-core-v2 uses the no-plan construction on exact reviewed versions. The [runtime certification table](../runtime/kimi-engine.ts) controls routing and operation scope. 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.
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
- ## Why the safety story is hook-based
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
- 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.
9
+ ## Why enforcement is hook-based
10
10
 
11
- 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.
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
- 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.
14
14
 
15
15
  ```
16
- ┌──────────────────────┐ KIMI_PLUGIN_CC_CMD=review ┌──────────────────────┐
17
- │ /kimi:review │ ───────────────────────────────► │ kimi -p │
18
- │ (companion.sh) │ │ (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
- └──────────────────────┘
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
+ └──────────────────────┘
31
31
  ```
32
32
 
33
- 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.
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.
34
34
 
35
- ## The managed block
35
+ ## The canonical managed block and bundled hook
36
36
 
37
- `/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:
38
38
 
39
39
  ```toml
40
- # === BEGIN kimi-plugin-cc-managed:claude-code (vX.Y.Z) ===
41
- # DO NOT EDIT — managed by /kimi:setup. Run /kimi:setup --uninstall to remove.
42
- # Host: claude-code — Claude Code and Codex each own a separate block in this
43
- # shared ~/.kimi-code/config.toml; setup in one host never touches the other's.
40
+ # === BEGIN kimi-plugin-cc-managed (v3.1.0) ===
41
+ # DO NOT EDIT — managed by kimi-plugin-cc setup. Run `scripts/companion.sh setup --uninstall` to remove.
44
42
  # Purpose:
45
43
  # kimi-code's `kimi -p` mode hard-codes permission='auto' and
46
- # auto-approves every tool call. This hook enforces /kimi:review,
47
- # /kimi:challenge, /kimi:review_gate, and /kimi:ask as read-only,
48
- # and applies the workspace-bound rescue allowlist for /kimi:rescue.
49
- # Without this block the plugin's safety contract collapses.
44
+ # auto-approves every tool call. This hook enforces each managed command's
45
+ # read-only or workspace-bound approval policy. Without this block,
46
+ # the plugin's safety contract collapses.
50
47
  # Matcher field is intentionally OMITTED — kimi-code compiles the
51
48
  # matcher with `new RegExp(...)`. An empty/missing matcher means
52
49
  # "fire for every tool". The string "*" would throw and silently
@@ -56,397 +53,245 @@ If the hook is missing or invalid, **every model-spawning command fails closed b
56
53
  # LaunchAgents, etc.).
57
54
  [[hooks]]
58
55
  event = "PreToolUse"
59
- 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'"
60
57
  timeout = 15
61
- # === END kimi-plugin-cc-managed:claude-code ===
58
+ # === END kimi-plugin-cc-managed ===
62
59
  ```
63
60
 
64
- The `vX.Y.Z` marker is replaced with the live plugin version by
65
- `runtime/commands/setup.ts`. Both the node binary path and the hook
66
- script path are shell-quoted via `runtime/hooks/install-paths.ts`
67
- before they reach the config (so a path containing spaces or quotes
68
- can't bypass the safety contract through argv splitting).
69
-
70
- Key constraints (verified by [`runtime/hooks/managed-block.ts`](../runtime/hooks/managed-block.ts) on both install and verify):
71
-
72
- 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.
73
- 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.
74
- 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`.
75
- 4. **Exact marker grammar.** The verifier rejects 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. The verifier remains fail-closed until repair and full validation succeed.
76
- 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.
77
- 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.
78
- 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`.
79
- 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.
80
-
81
- ### Host scoping (all hosts share one config)
82
-
83
- Claude Code and Codex install this plugin to **different, version-stamped
84
- paths** (`~/.claude/plugins/cache/…` vs `~/.codex/plugins/cache/…`), while DSH
85
- uses its own profile package path. All read the **same**
86
- `~/.kimi-code/config.toml`. So the managed block is **host-scoped**:
87
- its marker carries a `:<host-id>` suffix, and each host owns, verifies, and
88
- uninstalls only its **own** block.
89
-
90
- - **Host id** (`runtime/hooks/install-paths.ts::resolveHostId`) is derived
91
- version-independently from the hook path: `~/.claude/…` → `claude-code`,
92
- `~/.codex/…` → `codex`, else a stable `host-<sha1>` for dev checkouts. DSH
93
- explicitly pins `dsh`. A plugin upgrade *refreshes* the same host's block
94
- rather than adding a new one.
95
- - **No clobbering.** `/kimi:setup` (Claude), `$kimi-setup` (Codex), and
96
- `/kimi-setup` (DSH) each write their own block and leave the others
97
- byte-identical. Before v1.7.0 there was
98
- a single block exact-matched to the running host, so the two hosts overwrote
99
- each other and the loser's write-commands refused with "hook path drift."
100
- - **Enforcement is redundant-safe.** kimi-code fires *every* `[[hooks]]` entry
101
- and aggregates **any-block-wins** (first `block` wins). Both hosts' hooks run
102
- the same allowlist logic, so the current host's live hook always enforces —
103
- even if another host's path is stale (a stale path fails open, but the live
104
- one still denies). A drifted *own* block is still caught at the per-command
105
- verify gate, which prompts a re-setup for that host only.
106
- - **Migration + cleanup.** A pre-v1.7.0 un-suffixed block is adopted and
107
- converted in place by the current host on its next `/kimi:setup`. Orphaned,
108
- marker-less `[[hooks]]` entries that are unambiguously our approval hook
109
- (canonical command, `approval-hook.js` under a kimi-marketplace/kimi-plugin-cc/
110
- dsh-kimi-plugin-cc tree) are pruned **host-scoped** (v1.8.2): install and scoped uninstall touch
111
- only tables whose command path derives to the *current* host. `/kimi:setup
112
- --uninstall` removes only the current host's block (plus legacy + this host's
113
- orphans); `/kimi:setup --uninstall --all` removes every host's block and every
114
- plugin-owned table. Hand-rolled user hooks are never touched.
115
- - **Markers are not durable — verification does not depend on them (v1.8.2).**
116
- kimi-code persists its config via smol-toml `stringify(parse(...))` on every
117
- login/settings write, which deletes ALL comments — the managed-block BEGIN/END
118
- markers included — while the `[[hooks]]` table (data) survives and keeps
119
- enforcing. When this host's marked block is absent, the verifier falls back to
120
- a marker-less table whose decoded `command` is **byte-identical** to the
121
- canonical expected command, under the same strict grammar (PreToolUse event,
122
- no matcher, no keys beyond event/command/timeout). Anything weaker — drifted
123
- path, matcher-bearing table, foreign keys — still refuses. The fallback never
124
- applies over duplicate/orphan/invalid marked states. The next `/kimi:setup`
125
- re-adorns the markers; the other host's marker-less table is that host's LIVE
126
- hook and is left byte-untouched (pre-v1.8.2, the host-blind prune here caused
127
- each host's setup to disarm the other after any kimi login — the "seesaw").
128
-
129
- ## DeepSeek Harness providers
130
-
131
- 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).
132
-
133
- The DSH bundle exposes the same seven operations as the other hosts: `kimi_ask`, `kimi_review`, `kimi_challenge`, `kimi_rescue`, `kimi_pursue`, `kimi_swarm`, and `kimi_swarm_write`. 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.
134
-
135
- 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.
136
-
137
- 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.
138
-
139
- 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.
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.
140
62
 
141
- ## The hook's per-command policy
142
-
143
- [`runtime/hooks/approval-policy.ts`](../runtime/hooks/approval-policy.ts) is the single source of truth:
144
-
145
- | `KIMI_PLUGIN_CC_CMD` | Allowed tools | Denied tools |
146
- |---|---|---|
147
- | unset / empty | everything | nothing (kimi was invoked outside the plugin) |
148
- | `ask` | `Read`, `Grep`, `Glob`, `ReadMediaFile`, `TaskList`, `TaskOutput` | everything else, including `Bash`, `Write`, `Edit` |
149
- | `review`, `challenge`, `review_gate` | same as `ask` | same as `ask` |
150
- | `rescue` | governed by [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts) against the plugin-owned `KIMI_PLUGIN_CC_WORKSPACE_ROOT` — workspace-bound shell allowlist, 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 |
151
- | `swarm` | same read-only set as `ask`; exact `AgentSwarm` subject to the version-specific wave guard | everything else, including singular `Agent`, shell, and writes |
152
- | `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 |
153
- | unknown label | `Read`, `Grep`, `Glob`, `ReadMediaFile`, `TaskList`, `TaskOutput` | everything else (conservative-deny for stale/misconfigured callers) |
154
-
155
- `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`).
156
-
157
- ### Native agent-core-v2: the no-plan construction (v1.10.0)
158
-
159
- 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.
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):
160
64
 
161
- 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:
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.
162
72
 
163
- - 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) — is refused before spawn by `runtime/native-v2-preflight.ts` (`CLI_V2_PLAN_MODE_CONFIGURED`, remedy: set it to `false` or remove it — never `/kimi:setup`). The key lives only in `<KIMI_CODE_HOME>/config.toml` and is read once inside session creation; the plugin parses that same file just before spawn and again at the spawn boundary.
164
- - `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.
165
- - 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`). Nothing saved is modified.
166
- - v2-only experimental features the plugin does not certify (`tower`, `subagent_fork`, whether from `[experimental]` config or per-flag env) and the master `KIMI_CODE_EXPERIMENTAL_FLAG` are refused before spawn.
167
-
168
- 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).
169
-
170
- 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.
171
-
172
- 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.
173
-
174
- 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.
175
-
176
- 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.
177
-
178
- ## The rescue allowlist
73
+ ## Universal hosts and collapsed surfaces
179
74
 
180
- For `/kimi:rescue`, the hook delegates to [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts). The allowlist has been extended since the original Wire-transport implementation. Highlights:
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:
181
76
 
182
- - **File edits** (`Write`, `Edit`): 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.
183
- - **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.
184
- - **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.
185
- - **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.
186
- - **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).
187
- - **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.
188
- - **Read-safe commands** (`ls`, `cat`, `head`, `tail`, `rg`, `pwd`, `wc`, `git status`, `git diff`, ...): allowed.
189
- - **`.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.
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 |
190
86
 
191
- ### Effective working directory (`Bash.cwd`, v1.10.0)
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 `--`.
192
88
 
193
- 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.
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`.
194
90
 
195
- ### Trust boundary: test runners execute workspace code
91
+ ### Patched DSH host and profiles
196
92
 
197
- `/kimi: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:rescue` in a workspace you do not trust, assume any allowed test runner can execute arbitrary code from that workspace.
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.
198
94
 
199
- 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.
95
+ Create a dedicated npm host project and use its DSH binary for plugin installation and launch:
200
96
 
201
- ### Trust boundary: kimi-code 0.31 custom agents and system prompts
202
-
203
- 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.
204
-
205
- 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.
206
-
207
- ## Autonomous goal mode (`/kimi:pursue`, experimental)
208
-
209
- `/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.
210
-
211
- 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.
212
-
213
- If another installed host still points to 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.
214
-
215
- > **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.
216
-
217
- - **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.
218
- - **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.
219
- - **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 `/kimi:rescue`, `/kimi:ask`, and `/kimi: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.
220
- - **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.
221
- - **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 rescue/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-rescue`, 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`.
222
-
223
- ## 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
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
+ ```
224
108
 
225
- For interrupted runs, see [durable recovery and its explicit limits](swarm-recovery.md).
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.
226
110
 
227
- 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.
111
+ If an existing profile installs its own DSH packages, patch and audit that profile too:
228
112
 
229
- 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:
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
+ ```
230
118
 
231
- 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.
232
- 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.
233
- 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.
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.
234
120
 
235
- 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.
121
+ ## The hook's per-command policy
236
122
 
237
- ## Bounded swarm on exact CLI 2.6.2/2.6.3/2.7.2/2.7.3
123
+ [`runtime/hooks/approval-policy.ts`](../runtime/hooks/approval-policy.ts) is the single source of truth:
238
124
 
239
- `--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:
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) |
240
133
 
241
- - **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.
242
- - **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.
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`.
243
135
 
244
- 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.
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.
245
137
 
246
- 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.
138
+ ### Read scope and network access
247
139
 
248
- 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.
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`):
249
141
 
250
- 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.
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.
251
145
 
252
- 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.
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`).
253
147
 
254
- 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.
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.
255
149
 
256
- `--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.
150
+ ### Native agent-core-v2 and the no-plan closures
257
151
 
258
- 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).
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:
259
153
 
260
- ## Read-only swarm (`/kimi:swarm`)
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.
261
158
 
262
- `/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**.
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).
263
160
 
264
- - **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.
265
- - **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.
266
- - **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.
267
- - **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.
268
- - **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.
269
- - **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-review`/`kimi-challenge`/`kimi-ask`/`kimi-rescue` already 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-rescue`.
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.
270
162
 
271
- ## Write-capable swarm (`/kimi:swarm --write`)
163
+ ## The rescue allowlist
272
164
 
273
- `/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.
165
+ For `rescue`, `pursue`, and `swarm-write`, the hook delegates to [`evaluateRescueHookRequest`](../runtime/rescue-approval.ts) against `KIMI_PLUGIN_CC_WORKSPACE_ROOT`:
274
166
 
275
- - **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.
276
- - **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.
277
- - **`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.
278
- - **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.
279
- - **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.
280
- - **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.
281
- - **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.
282
- - **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.
283
- - **Model-invocable agent (v1.5), patch-only by construction.** Following the field-proof above, `--write` now has a `kimi-swarm-write` subagent so the main thread can dispatch a write fan-out on its own judgement — the same human-command + model-invocable-agent split the rest of the suite uses. 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 demands BOTH signals — many disjoint write targets AND explicit fan-out intent — and steers single edits to `kimi-rescue`, read-only fan-outs to `kimi-swarm`, and autonomous loops to `kimi-pursue`. Default `--max-concurrency` stays **1**; raising it (concurrent writers) remains a deliberate, human-or-explicitly-requested choice.
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.
284
177
 
285
- ## MCP transport and long-running jobs
178
+ ### Effective working directory (`Bash.cwd`)
286
179
 
287
- 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 seven 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.
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`.
288
181
 
289
- 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.
182
+ ### Trust boundary for test runners and custom agents
290
183
 
291
- 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.
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.
292
185
 
293
- 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.
186
+ ## Autonomous goal mode (`pursue`, experimental)
294
187
 
295
- 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.
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.
296
189
 
297
- 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.
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.
298
191
 
299
- ## Response budgets and partial output (2.2.0)
192
+ ## Bounded swarm on 2.8.0 and newer
300
193
 
301
- Every single-turn command runs under a wall-clock budget: ask, review and
302
- challenge default to 30 minutes, rescue to 45, and `--budget <dur>` (at most
303
- 24h) overrides it per job. The budget is persisted on the job row, so a detached
304
- worker and a same-operation resume use the same ceiling. For these commands the
305
- budget is a response-time limit, not a safety bound: a timeout is a safe
306
- failure. The job stays `failed`; whatever assistant prose had settled is written
307
- into the artifact under a heading that says it is NOT a final answer, and
308
- `result <jobId> --json` reports `partial_output: true` when prose exists.
309
- 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`).
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`:
310
195
 
311
- Pursue and swarm keep their ceilings as the sole hard bound on autonomy and
312
- cost. One nuance: a run whose process exits cleanly in the same event-loop tick
313
- as the budget timer is accepted as a success rather than discarded, so a goal
314
- can complete at most one tick past its ceiling — teardown has already settled by
315
- then, and nothing runs longer.
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.
316
198
 
317
- Every spawn also deletes `KIMI_CODE_TRUST_WORKSPACE` from the child
318
- environment (kimi-code 2.2.0): a trusted workspace boots repo-defined project
319
- MCP servers at bootstrap, outside the PreToolUse hook, and an inherited value
320
- would have trusted every plugin spawn including swarm-write's throwaway
321
- worktree. A directory the operator trusted interactively in the Kimi TUI still
322
- has that property; that persisted-trust route is a documented residual, not
323
- something the plugin can close.
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.
324
200
 
325
- Plugin-managed execution must remain local. Unused remote declarations can remain in operator config, but a configured remote default refuses before spawn. Disabling workspace trust through `[workspace] require_trust = false` also refuses, because it would enable project MCP outside the managed hook. 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.
201
+ ### Write-capable swarm (`swarm_patch`)
326
202
 
327
- ## Running a newer Kimi than the plugin certifies
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.
328
204
 
329
- The plugin refuses any kimi-code version it has not certified, so an operator
330
- who tracks `@latest` loses every `/kimi:*` command until the next certification.
331
- The clean way to have both is to give the plugin its own binary: install the
332
- highest certified version somewhere stable and point `KIMI_PLUGIN_CC_KIMI_BIN`
333
- at it (the runtime resolves that path instead of `kimi` on `PATH`; every spawn
334
- still exports `KIMI_CODE_NO_AUTO_UPDATE=1`, suppressing passive updates; a manually staged replacement is detected by the exact probe and first-line version marker, not prevented or rolled back).
205
+ ## MCP transport, `SEP-2640` skills, and long-running jobs
335
206
 
336
- ```sh
337
- PIN=~/.local/share/kimi-plugin-cc/kimi-bin/2.5.3
338
- mkdir -p "$PIN" && cd "$PIN" && printf '{"name":"kimi-plugin-cc-pin","private":true}\n' > package.json
339
- npm install @moonshot-ai/kimi-code@2.5.3
340
- export KIMI_PLUGIN_CC_KIMI_BIN="$PIN/node_modules/.bin/kimi" # e.g. in ~/.zshenv
341
- ```
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.
342
208
 
343
- Both binaries share `~/.kimi-code` (login, config, hook), so nothing else
344
- changes. The full-operation certified maximum can be read from the installed
345
- plugin (`NATIVE_V2_CERTIFIED_VERSIONS` in `dist/kimi-engine.js`), which lets an
346
- upgrade script bump the full-swarm pin automatically after each full-operation
347
- certification. That export excludes narrowed releases such as 2.6.0 and includes exact 2.6.2/2.6.3/2.7.2/2.7.3
348
- under its certified bounded-swarm construction. `NATIVE_V2_ANY_OPERATION_VERSIONS`
349
- is the separate scoped union, so an automatic full-swarm pin does not silently
350
- become a non-swarm-only pin.
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.
351
214
 
352
- ## The setup probe
215
+ ## Response budgets, local execution, and newer Kimi releases
353
216
 
354
- `/kimi:setup` runs a two-layer probe before reporting success:
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.
355
218
 
356
- 1. **Direct probe.** Spawns the hook with the same Node binary (`process.execPath`) the companion is running under. Sends synthetic PreToolUse stdin with `KIMI_PLUGIN_CC_CMD=review` + a Bash tool request. Asserts exit 2 + non-empty stderr.
357
- 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.
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.
358
220
 
359
- Both must pass. The shell probe catches the case where `process.execPath` works 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.
221
+ ### Running a newer Kimi than the plugin certifies
360
222
 
361
- ## 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:
362
224
 
225
+ ```text
226
+ kimi-code <version> is not certified by this plugin release; running <operation> read-only with 2.8.0 mechanics.
363
227
  ```
364
- /kimi:setup --check
365
- ```
366
-
367
- 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.
368
228
 
369
- `/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.
370
230
 
371
- 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`.
372
232
 
373
- 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
374
234
 
375
- ## How to opt out
235
+ `setup` and `setup --check` run a two-layer probe:
376
236
 
377
- ```
378
- /kimi:setup --uninstall
379
- ```
380
-
381
- Removes the managed block from `~/.kimi-code/config.toml`. Subsequent kimi-plugin-cc command invocations:
382
-
383
- - Every model-spawning command will refuse before Kimi starts with its command-specific `*_HOOK_NOT_INSTALLED` error.
384
- - The review gate will skip visibly and allow the host to stop; it will not run an un-enforced model turn.
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.
385
239
 
386
- For tests or deliberate diagnostics only, `KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1` bypasses verification.
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.
387
241
 
388
- 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.
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.
389
243
 
390
- ## Refusal codes of the native-v2 contract (v1.10.0)
244
+ <a id="refusal-codes-of-the-native-v2-contract-v1100"></a>
245
+ ## Native-v2 refusal codes
391
246
 
392
- 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.
393
248
 
394
249
  | Code | Raised when | Remedy |
395
- |---|---|---|
396
- | `KIMI_CAPABILITY_NOT_CERTIFIED` | the probed `kimi --version` is not in the operation's exact certified set (for example, an interactive CLI update installed an uncertified version) | update kimi-plugin-cc to a release certifying that version, or point `KIMI_PLUGIN_CC_KIMI_BIN` at a certified binary |
397
- | `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` | set it to `false` or remove it |
398
- | `CLI_V2_CONFIG_UNREADABLE` | that config cannot be read safely (symlink, oversized, unparseable TOML, I/O error) — plan mode cannot be verified off | fix or remove the unreadable file |
399
- | `CLI_V2_EXPERIMENTAL_UNSAFE` | `[experimental] tower` / `subagent_fork` (config) or `KIMI_CODE_EXPERIMENTAL_TOWER` / `…_SUBAGENT_FORK` (env) is truthy | unset the listed selector(s) |
400
- | `CLI_V2_HOOK_ORDER_UNSAFE` | the master `KIMI_CODE_EXPERIMENTAL_FLAG` is truthy (`1|true|yes|on`) | unset it |
401
- | `KIMI_SESSION_PLAN_TAINTED` | the session to resume has a `plan_mode.*`/`plan.*` record in any agent `wire.jsonl` | start a fresh session (nothing saved is modified) |
402
- | `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 |
403
- | `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 |
404
- | `KIMI_SESSION_ENGINE_MISMATCH` | the source session ran on a different engine than the selected one | start a fresh session |
405
- | `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) |
406
- | `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 |
407
-
408
- ## What this safety story does NOT cover
409
-
410
- - **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.
411
- - **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.
412
- - **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.
413
- - **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.
414
- - **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.
415
- - **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 `/kimi:rescue` is cancellable; but if you want a hard step ceiling, set `max_steps_per_turn` in your kimi-code config.
416
- - **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.
417
- - **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. Setup emits an "outside tested range" warning and can complete, while every model-spawning command independently probes the exact command tuple and refuses an uncertified version before Kimi starts (`KIMI_CAPABILITY_NOT_CERTIFIED`; certification is per EXACT version on native v2 and per minor on legacy-v1). Update the plugin to a release that certifies the new version or point `KIMI_PLUGIN_CC_KIMI_BIN` at a certified binary; `KIMI_PLUGIN_CC_SKIP_VERSION_PROBE` is tests/smoke only. The current native-v2 versions are listed at the start of this guide. Legacy-v1 uses the tested minors through 0.41.x, with per-operation minimums, for an explicitly pinned binary. Every spawn probes the exact tuple and refuses an uncertified version (`KIMI_CAPABILITY_NOT_CERTIFIED`, see the refusal-code table above).
418
- - **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.
419
-
420
- ## Known limitation: Node version manager switches
421
-
422
- 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.
423
-
424
- 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.
425
-
426
- **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.
427
-
428
- **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.
429
-
430
- ## Hook-path drift is repaired by the caller, never by the verifier (v1.9.0)
431
-
432
- 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:
433
-
434
- `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.
435
-
436
- 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.
437
-
438
- **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). 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.
439
294
 
440
295
  ## Reporting safety issues
441
296
 
442
- If you find a way to coax /kimi:review, /kimi:challenge, /kimi:review_gate, or /kimi:ask into running a non-read tool — or to make /kimi:rescue mutate `.git/` or escape the workspace — please open a GitHub security advisory rather than a public issue.
443
-
444
- ## Hook-escape monitor: detection evidence
445
-
446
- **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).
447
-
448
- 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.
449
-
450
- ## Review-gate thinking request
451
-
452
- 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.