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
@@ -3,38 +3,32 @@ import { SETUP_SUPPORTED_FLAGS } from "../parsing.js";
3
3
  // Without it, `kimi -p` auto-approves tool calls, including from read-only
4
4
  // commands.
5
5
  //
6
- // Setup writes or refreshes a host-scoped BEGIN/END block containing the
7
- // canonical `'<absolute-node>' '<absolute-hook-script>'` command from
8
- // resolveNodeBinary/buildHookShellCommand. Both tokens are shell-quoted and the
9
- // absolute Node path avoids PATH dependence under sanitized launches. Setup
10
- // probes the hook directly with resolveNodeBinary and through `/bin/sh -c`
11
- // using the exact installed command bytes. It also warns about broad permission
12
- // denies, repairs orphan marker comments, and refuses remaining
13
- // duplicate, orphaned, or malformed managed blocks.
14
- //
15
- // Subcommands: install (default), --check, --uninstall [--all], and
16
- // --enable-review-gate/--disable-review-gate.
17
- //
18
- // Managed-block splicing is line-based and preserves user bytes outside owned
19
- // edits; whole-file validation and inline-hook normalization use the TOML parser.
6
+ // Setup atomically publishes the bundled self-contained approval hook to
7
+ // `<pluginRoot>/hook/approval-hook.js`, then writes or refreshes a single
8
+ // canonical BEGIN/END block in ~/.kimi-code/config.toml containing
9
+ // `'<absolute-node>' '<absolute-hook-script>'` from
10
+ // resolveNodeBinary/buildHookShellCommand. Setup probes the hook directly with
11
+ // the parsed Node binary and through `/bin/sh -c` using the exact installed bytes.
20
12
  import { spawn } from "node:child_process";
21
- import { access, mkdir, open, readFile, rename, unlink, } from "node:fs/promises";
13
+ import { access, chmod, mkdir, lstat, mkdtemp, open, readdir, readFile, readlink, realpath, rename, rm, symlink, unlink, writeFile, } from "node:fs/promises";
22
14
  import { constants as fsConstants, existsSync } from "node:fs";
23
15
  import { randomBytes } from "node:crypto";
24
16
  import path from "node:path";
25
- import { readPluginConfig, writePluginConfig } from "../config.js";
26
17
  import { RuntimeError } from "../errors.js";
18
+ import { HOOK_TIMEOUT_S } from "../hooks/hook-timing.js";
27
19
  import { normalizeTopLevelInlineHooks, validateKimiHookSetForEnvironment, withKimiConfigLock, } from "../hooks/config-safety.js";
28
- import { buildHookShellCommand, hostIdFromHookCommand, resolveHookScriptPath, resolveHostId, resolveNodeBinary, } from "../hooks/install-paths.js";
29
- import { decodeManagedCommandLine, effectiveHost, evaluateInstalled, findUnmanagedApprovalHookBlocks, markerCommentLines, MARKERS, ORPHAN_MARKER_REMEDY, parseManagedBlock, } from "../hooks/managed-block.js";
30
- import { formatVersionOutOfRangeWarning, probeKimiVersion, } from "../kimi-version-probe.js";
31
- import { isNativeV2CertifiedVersion, NATIVE_V2_ANY_OPERATION_VERSIONS, NATIVE_V2_NON_SWARM_VERSIONS, } from "../kimi-engine.js";
32
- import { resolveKimiHome } from "../kimi-home.js";
33
- import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
20
+ import { buildHookShellCommand, parseHookShellCommand, resolveBundledHookSourcePath, resolveHookScriptPath, resolveNodeBinary, verifyManagedHookArtifact, } from "../hooks/install-paths.js";
21
+ import { countCleanEntriesInFile, describeHookTimeout, evaluateInstalled, findShortHookTimeout, findUnmanagedApprovalHookBlocks, ORPHAN_MARKER_REMEDY, pairBlocks, parseManagedBlock, scanTomlLines, } from "../hooks/managed-block.js";
22
+ import { formatVersionOutOfRangeWarning, KIMI_MINIMUM_CERTIFIED_VERSION, probeKimiVersion, } from "../kimi-version-probe.js";
23
+ import { inspectPluginOwnedKimi, selectKimiBinary } from "../kimi-command.js";
24
+ import { isNativeV2CertifiedVersion, NATIVE_V2_ANY_OPERATION_VERSIONS, NATIVE_V2_CERTIFIED_VERSIONS, NATIVE_V2_NON_SWARM_VERSIONS, } from "../kimi-engine.js";
25
+ import { resolveKimiCodeConfigPath, resolveKimiHome } from "../kimi-home.js";
26
+ import { formatVersionChoice, kimiReleaseHas, kimiVersionsWith } from "../kimi-releases.js";
27
+ import { ensurePluginPaths, resolveKimiBinDir, resolvePluginPaths } from "../paths.js";
34
28
  import { KIMI_PLUGIN_CC_VERSION } from "../version.js";
35
29
  import { parse as parseToml } from "../vendor/smol-toml/parse.js";
36
30
  const BEGIN_MARKER_PREFIX = "# === BEGIN kimi-plugin-cc-managed";
37
- const DEFAULT_HOOK_TIMEOUT_S = 15;
31
+ const DEFAULT_HOOK_TIMEOUT_S = HOOK_TIMEOUT_S;
38
32
  // Probe timing. The direct script probe is local and fast; allow 5s for
39
33
  // node startup on cold CI runners. The shell probe adds /bin/sh fork
40
34
  // overhead but should still complete well within the same budget.
@@ -46,43 +40,36 @@ const PROBE_TIMEOUT_MS = 5_000;
46
40
  const PATH_FORBIDDEN_RE = /[\x00-\x1f"\\\n\r\t]/;
47
41
  export async function runSetup(argv, context) {
48
42
  const parsed = parseArgs(argv);
43
+ if (parsed.mode === "install-kimi") {
44
+ return await runInstallKimi(parsed.json, context);
45
+ }
49
46
  const paths = resolvePluginPaths(context.env);
50
47
  await ensurePluginPaths(paths);
51
- // Reconcile the review-gate flag first — it's independent of the
52
- // kimi-code hook and we want the answer reflected in the result even
53
- // if the rest of setup fails.
54
- const existingConfig = await readPluginConfig(paths);
55
- const reviewGateEnabled = parsed.enableReviewGate
56
- ? true
57
- : parsed.disableReviewGate
58
- ? false
59
- : existingConfig.reviewGateEnabled;
60
- if (reviewGateEnabled !== existingConfig.reviewGateEnabled) {
61
- await writePluginConfig(paths, { reviewGateEnabled });
62
- }
63
48
  const configPath = resolveKimiCodeConfigPath(context.env);
64
49
  const hookScriptPath = resolveHookScriptPath(context.env);
65
50
  assertHookPathTomlSafe(hookScriptPath);
66
- // Host id scopes each managed block so Claude Code and Codex can share one
67
- // ~/.kimi-code/config.toml without clobbering each other.
68
- const hostId = resolveHostId(context.env, hookScriptPath);
69
51
  const warnings = [];
70
52
  switch (parsed.mode) {
71
53
  case "uninstall":
72
- return await runUninstall(configPath, hookScriptPath, hostId, parsed.removeAllHosts, reviewGateEnabled, warnings, context);
54
+ return await runUninstall(configPath, hookScriptPath, warnings, context);
73
55
  case "check":
74
- return await runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context);
56
+ return await runCheck(configPath, hookScriptPath, warnings, context);
75
57
  case "install":
76
- return await runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context);
58
+ return await runInstall(paths, configPath, hookScriptPath, warnings, context);
77
59
  }
78
60
  }
79
61
  function parseArgs(argv) {
80
62
  let mode = "install";
81
- let enableReviewGate = false;
82
- let disableReviewGate = false;
83
- let removeAllHosts = false;
63
+ let installKimi = false;
64
+ let json = false;
84
65
  for (const token of argv) {
85
66
  switch (token) {
67
+ case "--install-kimi":
68
+ installKimi = true;
69
+ break;
70
+ case "--json":
71
+ json = true;
72
+ break;
86
73
  case "--check":
87
74
  if (mode === "uninstall") {
88
75
  throw new RuntimeError("INVALID_ARGS", "setup accepts at most one of --check, --uninstall.", "setup.parse");
@@ -95,29 +82,149 @@ function parseArgs(argv) {
95
82
  }
96
83
  mode = "uninstall";
97
84
  break;
98
- case "--all":
99
- removeAllHosts = true;
100
- break;
101
- case "--enable-review-gate":
102
- enableReviewGate = true;
103
- break;
104
- case "--disable-review-gate":
105
- disableReviewGate = true;
106
- break;
107
85
  default:
108
86
  throw new RuntimeError("INVALID_ARGS", `Unknown setup flag ${token}. Supported flags: ${SETUP_SUPPORTED_FLAGS}.`, "setup.parse");
109
87
  }
110
88
  }
111
- if (enableReviewGate && disableReviewGate) {
112
- throw new RuntimeError("INVALID_ARGS", "setup accepts either --enable-review-gate or --disable-review-gate, not both.", "setup.parse");
89
+ if (installKimi) {
90
+ if (argv.some((token) => token !== "--install-kimi" && token !== "--json")) {
91
+ throw new RuntimeError("INVALID_ARGS", "--install-kimi does not combine with other setup flags except --json.", "setup.parse");
92
+ }
93
+ return { mode: "install-kimi", json };
94
+ }
95
+ if (json) {
96
+ throw new RuntimeError("INVALID_ARGS", "--json is only valid with --install-kimi or --models.", "setup.parse");
97
+ }
98
+ return { mode, json };
99
+ }
100
+ async function assertNonSymlinkDirectory(target, label) {
101
+ let info;
102
+ try {
103
+ info = await lstat(target);
104
+ }
105
+ catch (err) {
106
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Unable to inspect ${label} at ${target}: ${err.message}`, "setup.hook-script", err instanceof Error ? { cause: err, details: { target } } : { details: { target } });
107
+ }
108
+ if (info.isSymbolicLink() || !info.isDirectory()) {
109
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Refusing to publish hook into ${label} at ${target}: path is a symlink or not a directory.`, "setup.hook-script", { details: { target } });
110
+ }
111
+ return await realpath(target);
112
+ }
113
+ async function assertAbsentOrRegularFile(target, label) {
114
+ let info;
115
+ try {
116
+ info = await lstat(target);
117
+ }
118
+ catch (err) {
119
+ if (err.code === "ENOENT")
120
+ return;
121
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Unable to inspect ${label} at ${target}: ${err.message}`, "setup.hook-script", err instanceof Error ? { cause: err, details: { target } } : { details: { target } });
113
122
  }
114
- if (removeAllHosts && mode !== "uninstall") {
115
- throw new RuntimeError("INVALID_ARGS", "--all is only valid with --uninstall (it removes EVERY host's managed block).", "setup.parse");
123
+ if (info.isSymbolicLink() || !info.isFile()) {
124
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Refusing to overwrite ${label} at ${target}: path is a symlink or not a regular file.`, "setup.hook-script", { details: { target } });
116
125
  }
117
- return { mode, enableReviewGate, disableReviewGate, removeAllHosts };
118
126
  }
119
- async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context) {
120
- await assertHookScriptExists(hookScriptPath);
127
+ async function publishHookArtifactIfManaged(paths, hookScriptPath, env) {
128
+ if (env.KIMI_PLUGIN_CC_HOOK_SCRIPT && env.KIMI_PLUGIN_CC_HOOK_SCRIPT.length > 0) {
129
+ return;
130
+ }
131
+ const sourcePath = resolveBundledHookSourcePath();
132
+ let sourceBytes;
133
+ try {
134
+ sourceBytes = await readFile(sourcePath, "utf8");
135
+ }
136
+ catch (err) {
137
+ throw new RuntimeError("SETUP_HOOK_SCRIPT_MISSING", `Bundled hook script ${sourcePath} is missing or unreadable. Run \`bun run build\` or reinstall the plugin.`, "setup.hook-script", err instanceof Error ? { cause: err, details: { sourcePath } } : { details: { sourcePath } });
138
+ }
139
+ if (sourceBytes.trim().length === 0) {
140
+ throw new RuntimeError("SETUP_HOOK_SCRIPT_MISSING", `Bundled hook script ${sourcePath} is empty. Run \`bun run build\` or reinstall the plugin.`, "setup.hook-script", { details: { sourcePath } });
141
+ }
142
+ // Validate pluginRoot before acquiring the hook lock or creating hookDir.
143
+ const pluginRootReal = await assertNonSymlinkDirectory(paths.pluginRoot, "plugin data directory");
144
+ await withKimiConfigLock(path.join(paths.pluginRoot, "hook"), async () => {
145
+ let hookDirExisted = true;
146
+ try {
147
+ const info = await lstat(paths.hookDir);
148
+ if (info.isSymbolicLink() || !info.isDirectory()) {
149
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Refusing to publish hook into ${paths.hookDir}: path is a symlink or not a directory.`, "setup.hook-script", { details: { hookDir: paths.hookDir } });
150
+ }
151
+ }
152
+ catch (err) {
153
+ if (err instanceof RuntimeError)
154
+ throw err;
155
+ if (err.code === "ENOENT") {
156
+ hookDirExisted = false;
157
+ }
158
+ else {
159
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Unable to inspect hook directory ${paths.hookDir}: ${err.message}`, "setup.hook-script", err instanceof Error ? { cause: err, details: { hookDir: paths.hookDir } } : { details: { hookDir: paths.hookDir } });
160
+ }
161
+ }
162
+ if (!hookDirExisted) {
163
+ await mkdir(paths.hookDir, { mode: 0o700 });
164
+ }
165
+ const hookDirReal = await assertNonSymlinkDirectory(paths.hookDir, "hook directory");
166
+ const expectedHookDirReal = path.join(pluginRootReal, "hook");
167
+ if (hookDirReal !== expectedHookDirReal) {
168
+ throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", `Hook directory ${paths.hookDir} resolves to ${hookDirReal}, outside ${expectedHookDirReal}.`, "setup.hook-script", { details: { hookDir: paths.hookDir, hookDirReal, expectedHookDirReal } });
169
+ }
170
+ if (process.platform !== "win32") {
171
+ await chmod(paths.hookDir, 0o700);
172
+ }
173
+ const livePackageJsonPath = path.join(paths.hookDir, "package.json");
174
+ await assertAbsentOrRegularFile(livePackageJsonPath, "hook package.json");
175
+ await assertAbsentOrRegularFile(hookScriptPath, "hook script");
176
+ const stagingDir = await mkdtemp(path.join(paths.hookDir, ".staging-"));
177
+ try {
178
+ if (process.platform !== "win32") {
179
+ await chmod(stagingDir, 0o700);
180
+ }
181
+ const stagedPackageJsonPath = path.join(stagingDir, "package.json");
182
+ const stagedHookScriptPath = path.join(stagingDir, "approval-hook.js");
183
+ await writeFileAtomic(stagedPackageJsonPath, '{"type":"module"}\n', 0o644);
184
+ await writeFileAtomic(stagedHookScriptPath, sourceBytes, 0o644);
185
+ const stagedCommand = buildHookShellCommand(stagedHookScriptPath, env);
186
+ const stagedProbe = await probeHook(stagedHookScriptPath, stagedCommand, env);
187
+ if (!stagedProbe.ok) {
188
+ throw new RuntimeError("SETUP_HOOK_PROBE_FAILED", `Staged hook probe failed before activation (${stagedProbe.reason}). Existing live hook and kimi-code config were left unchanged.`, "setup.hook-probe", { details: { sourcePath, hookScriptPath, reason: stagedProbe.reason } });
189
+ }
190
+ // Re-check targets immediately before atomic swap from the same directory.
191
+ await assertAbsentOrRegularFile(livePackageJsonPath, "hook package.json");
192
+ await assertAbsentOrRegularFile(hookScriptPath, "hook script");
193
+ await rename(stagedPackageJsonPath, livePackageJsonPath);
194
+ await rename(stagedHookScriptPath, hookScriptPath);
195
+ }
196
+ finally {
197
+ await rm(stagingDir, { recursive: true, force: true });
198
+ }
199
+ });
200
+ }
201
+ function assertManagedBlocksSafeToReplace(contents, blocks, configPath, stage) {
202
+ if (blocks.length === 0)
203
+ return;
204
+ const lines = splitPreservingEnding(contents);
205
+ const { tables } = scanTomlLines(contents);
206
+ for (const block of blocks) {
207
+ let hooksTables = 0;
208
+ for (let lineNo = block.beginLine + 1; lineNo < block.endLine; lineNo += 1) {
209
+ if (!tables.has(lineNo))
210
+ continue;
211
+ const trimmed = lines[lineNo].trim();
212
+ if (/^\[\[hooks\]\]\s*(?:#.*)?$/.test(trimmed)) {
213
+ hooksTables += 1;
214
+ if (hooksTables > 1) {
215
+ throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `kimi-code config at ${configPath} has a managed block (lines ${block.beginLine + 1}-${block.endLine + 1}) containing multiple [[hooks]] tables; refusing to overwrite or strip user content. Inspect and repair the block manually; the existing config was left unchanged.`, stage, { details: { configPath, beginLine: block.beginLine + 1, endLine: block.endLine + 1 } });
216
+ }
217
+ }
218
+ else {
219
+ throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `kimi-code config at ${configPath} has a managed block (lines ${block.beginLine + 1}-${block.endLine + 1}) containing a non-hooks TOML table at line ${lineNo + 1}; refusing to overwrite or strip user content. Inspect and repair the block manually; the existing config was left unchanged.`, stage, { details: { configPath, beginLine: block.beginLine + 1, endLine: block.endLine + 1, line: lineNo + 1 } });
220
+ }
221
+ }
222
+ }
223
+ }
224
+ async function runInstall(paths, configPath, hookScriptPath, warnings, context) {
225
+ if (context.env.KIMI_PLUGIN_CC_HOOK_SCRIPT && context.env.KIMI_PLUGIN_CC_HOOK_SCRIPT.length > 0) {
226
+ await assertHookScriptExists(hookScriptPath);
227
+ }
121
228
  const mutation = await withKimiConfigLock(configPath, async () => {
122
229
  const original = await readConfigSafe(configPath);
123
230
  const lineEnding = detectLineEnding(original);
@@ -141,57 +248,71 @@ async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled,
141
248
  }
142
249
  warnings.push(`Converted the top-level inline hooks array (${inlineHooks.entryCount} entr${inlineHooks.entryCount === 1 ? "y" : "ies"}) to canonical [[hooks]] tables before installing. Surrounding config bytes were preserved; formatting and comments inside that hooks assignment were normalized.`);
143
250
  }
144
- // Prune only this host's orphaned marker-less entries before computing
145
- // splice line numbers. Another host's marker-less table may be its live hook
146
- // after a config rewrite strips comments, so it must remain untouched.
147
251
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
148
- const { pruned, count: prunedCount, commands: prunedCommands } = pruneOrphanApprovalHooks(inlineHooks.contents, hostId, expectedCommand);
252
+ const shortBefore = findShortHookTimeout(inlineHooks.contents, expectedCommand);
253
+ const { pruned, count: prunedCount, commands: prunedCommands } = pruneOrphanApprovalHooks(inlineHooks.contents, expectedCommand);
149
254
  const existing = pruned;
150
255
  if (prunedCount > 0) {
151
256
  const readorned = prunedCommands.includes(expectedCommand);
152
257
  warnings.push(readorned
153
- ? `Re-adorned this host's managed-block markers: kimi-code rewrites its config on login/settings changes and strips all comments (markers included), leaving the hook enforcing but unmarked. Replaced the bare hook table with a freshly marked block (${prunedCount} table(s) refreshed). Enforcement was never interrupted.`
154
- : `Pruned ${prunedCount} stale marker-less kimi-plugin-cc hook block(s) left by this host's earlier installs. This is a cleanup — your active hook is unaffected.`);
258
+ ? shortBefore === null
259
+ ? `Re-adorned the managed-block markers: kimi-code rewrites its config on login/settings changes and strips all comments (markers included), leaving the hook enforcing but unmarked. Replaced ${prunedCount} bare hook table(s) with one freshly marked canonical block. Enforcement was never interrupted.`
260
+ : `Re-adorned the managed-block markers: replaced ${prunedCount} bare hook table(s) with one freshly marked canonical block.`
261
+ : `Pruned ${prunedCount} stale marker-less kimi-plugin-cc hook block(s) left by earlier installs. This is a cleanup — your active hook is unaffected.`);
155
262
  }
156
- const { state, blocks } = parseManagedBlock(existing, hostId);
263
+ const { state, blocks } = parseManagedBlock(existing);
157
264
  if (state.kind === "orphan") {
158
265
  throw new RuntimeError("SETUP_ORPHAN_MARKERS", [
159
266
  `kimi-code config at ${configPath} contains an orphaned ${state.detail} marker.`,
160
267
  "Inspect the managed marker comments and re-run setup.",
161
268
  ].join(" "), "setup.install", { details: { configPath, orphan: state.detail } });
162
269
  }
270
+ assertManagedBlocksSafeToReplace(existing, blocks, configPath, "setup.install");
271
+ const block = buildManagedBlock(expectedCommand, lineEnding);
272
+ let next;
163
273
  if (state.kind === "duplicate") {
164
- throw new RuntimeError("SETUP_DUPLICATE_BLOCKS", [
165
- `kimi-code config at ${configPath} contains ${state.beginLines.length} kimi-plugin-cc managed blocks for host ${hostId} (lines ${state.beginLines
166
- .map((line) => line + 1)
167
- .join(", ")}).`,
168
- "This usually means two /kimi:setup runs raced. Run `/kimi:setup --uninstall` to clear them, then `/kimi:setup` again.",
169
- ].join(" "), "setup.install", { details: { configPath, beginLines: state.beginLines } });
274
+ const hasLegacyBlock = blocks.some((entry) => entry.hostId !== null);
275
+ if (!hasLegacyBlock) {
276
+ throw new RuntimeError("SETUP_DUPLICATE_BLOCKS", [
277
+ `kimi-code config at ${configPath} contains ${state.beginLines.length} kimi-plugin-cc managed blocks (lines ${state.beginLines
278
+ .map((line) => line + 1)
279
+ .join(", ")}).`,
280
+ "Run `scripts/companion.sh setup --uninstall` to clear them, then re-run setup.",
281
+ ].join(" "), "setup.install", { details: { configPath, beginLines: state.beginLines } });
282
+ }
283
+ warnings.push(`Consolidated ${blocks.length} legacy host-scoped managed block(s) into one canonical block.`);
284
+ next = consolidateManagedBlocks(existing, blocks, block, lineEnding);
170
285
  }
171
- // Non-blocking note: other hosts (e.g. Codex) manage their own block in the
172
- // same shared config — surface so an operator understands the coexistence.
173
- const otherHosts = [
174
- ...new Set(blocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
175
- ];
176
- if (otherHosts.length > 0) {
177
- warnings.push(`Other host(s) also manage a block in this shared config: ${otherHosts.join(", ")}. ` +
178
- `They are left untouched — each host owns its own PreToolUse block.`);
286
+ else if (state.kind === "found") {
287
+ next = spliceBlock(existing, state.beginLine, state.endLine, block, lineEnding);
288
+ }
289
+ else {
290
+ next = appendBlock(existing, block, lineEnding);
179
291
  }
180
- const block = buildManagedBlock(hookScriptPath, context.env, lineEnding, hostId);
181
- const next = state.kind === "found"
182
- ? spliceBlock(existing, state.beginLine, state.endLine, block, lineEnding)
183
- : insertBlockNearManagedBlocks(existing, blocks, block, lineEnding);
184
292
  await assertKimiHookSetValid(next, configPath, "setup.install", context.env);
293
+ const shortAfter = findShortHookTimeout(next, expectedCommand);
294
+ if (shortAfter !== null) {
295
+ throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `kimi-code config at ${configPath} has another [[hooks]] entry with the hook command and ${describeHookTimeout(shortAfter.timeout)}; kimi-code runs only one entry per command and reads a hook that runs past its timeout as allow. Remove that entry before rerunning setup; the existing config was left unchanged.`, "setup.install", { details: { configPath, timeout: describeHookTimeout(shortAfter.timeout) } });
296
+ }
297
+ if (shortBefore !== null) {
298
+ warnings.push(`Rewrote hook entry from ${describeHookTimeout(shortBefore.timeout)} to timeout = ${HOOK_TIMEOUT_S}: kimi-code reads a hook that runs past its timeout as allow, so the earlier entry did not reliably enforce.`);
299
+ }
300
+ // Stage, probe, and atomically publish the managed hook artifact under the
301
+ // config lock (and inner hook lock) before writing config.toml so a failed
302
+ // staged probe leaves both the live hook and config.toml untouched.
303
+ await publishHookArtifactIfManaged(paths, hookScriptPath, context.env);
304
+ await assertHookScriptExists(hookScriptPath);
185
305
  const blockWritten = next !== original;
186
306
  if (blockWritten)
187
307
  await writeConfigAtomic(configPath, next);
188
- return { blockWritten, next };
308
+ return { blockWritten, next, expectedCommand };
189
309
  });
190
- const { blockWritten, next } = mutation;
310
+ const { blockWritten, next, expectedCommand } = mutation;
191
311
  collectPermissionRuleWarnings(next, warnings);
312
+ const kimiBinary = describeKimiBinary(context.env, warnings);
192
313
  await collectKimiVersionWarnings(context.env, warnings);
193
314
  await collectInstalledKimiPluginsNotice(context.env, warnings);
194
- const probe = await probeHook(hookScriptPath, context.env);
315
+ const probe = await probeHook(hookScriptPath, expectedCommand, context.env);
195
316
  const summary = probe.ok
196
317
  ? blockWritten
197
318
  ? `Installed kimi-plugin-cc PreToolUse hook in ${configPath}.`
@@ -207,149 +328,114 @@ async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled,
207
328
  probe: probe.ok ? "ok" : "failed",
208
329
  probeError: probe.ok ? undefined : probe.reason,
209
330
  warnings,
210
- reviewGateEnabled,
211
331
  nextStep: probe.ok
212
- ? "Run /kimi:review, /kimi:challenge, /kimi:ask, or /kimi:rescue. Codex users can invoke the matching $kimi-* skills."
213
- : "Re-run /kimi:setup after installing kimi-code and Node. If the probe keeps failing, run /kimi:setup --uninstall and inspect ~/.kimi-code/config.toml manually.",
332
+ ? "Run `kimi_read` / `kimi_write` via MCP or `scripts/companion.sh read` / `write`."
333
+ : "Re-run setup after installing kimi-code and Node >=22.5. If the probe keeps failing, run `scripts/companion.sh setup --uninstall` and inspect ~/.kimi-code/config.toml manually.",
214
334
  details: buildDetails({
215
335
  configPath,
216
336
  hookScriptPath,
217
- reviewGateEnabled,
218
337
  probe,
219
338
  warnings,
220
- hostId,
339
+ kimiBinary,
221
340
  }),
222
341
  };
223
342
  }
224
- async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context) {
343
+ async function runCheck(configPath, hookScriptPath, warnings, context) {
344
+ const failedCheck = (result) => ({
345
+ action: "check",
346
+ summary: result.summary,
347
+ configPath,
348
+ hookScriptPath,
349
+ blockWritten: false,
350
+ blockRemoved: false,
351
+ probe: "failed",
352
+ probeError: result.reason,
353
+ warnings,
354
+ nextStep: result.nextStep,
355
+ details: buildDetails({
356
+ configPath,
357
+ hookScriptPath,
358
+ probe: { ok: false, reason: result.detailReason ?? result.reason },
359
+ warnings,
360
+ kimiBinary,
361
+ }),
362
+ });
363
+ // Reported on every check path, including early failures.
364
+ const kimiBinary = describeKimiBinary(context.env, warnings);
225
365
  const existing = await readConfigSafe(configPath);
226
366
  const hookSet = await validateKimiHookSetForEnvironment(existing, context.env);
227
367
  if (!hookSet.valid) {
228
- const reason = hookSet.reason ?? "configured hooks failed validation";
229
- return {
230
- action: "check",
368
+ return failedCheck({
231
369
  summary: `kimi-code hook configuration is invalid; the configured hooks array will not load.`,
232
- configPath,
233
- hookScriptPath,
234
- blockWritten: false,
235
- blockRemoved: false,
236
- probe: "failed",
237
- probeError: reason,
238
- warnings,
239
- reviewGateEnabled,
240
- nextStep: "Repair or remove the invalid [[hooks]] entry named above, then run /kimi:setup --check again. No model call is required.",
241
- details: buildDetails({
242
- configPath,
243
- hookScriptPath,
244
- reviewGateEnabled,
245
- probe: { ok: false, reason },
246
- warnings,
247
- hostId,
248
- }),
249
- };
370
+ reason: hookSet.reason ?? "configured hooks failed validation",
371
+ nextStep: "Repair or remove the invalid [[hooks]] entry named above, then run setup --check again. No model call is required.",
372
+ });
250
373
  }
251
374
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
252
- // nodeExists refines mismatch prose into drift classification; hostId checks
253
- // only this host's block in the shared config.
254
375
  const installedCheck = evaluateInstalled(existing, expectedCommand, {
255
- hostId,
256
376
  nodeExists: (binPath) => existsSync(binPath),
257
377
  });
258
- // Non-blocking coexistence + cruft notices.
259
- const { blocks: allBlocks, foreignOrphans } = parseManagedBlock(existing, hostId);
260
- for (const orphan of foreignOrphans) {
261
- warnings.push(`Host "${orphan.hostId}" has an orphaned ${orphan.detail} managed marker at line ${orphan.line + 1}; that host's commands refuse until it is repaired. ${ORPHAN_MARKER_REMEDY}`);
262
- }
263
- const otherHosts = [
264
- ...new Set(allBlocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
265
- ];
266
- if (otherHosts.length > 0) {
267
- warnings.push(`Other host(s) also manage a block in this shared config: ${otherHosts.join(", ")} (coexisting, untouched).`);
268
- }
269
- // Config rewrites can strip markers while leaving each host's table enforcing.
270
- // Our exact-command table is live; our stale table is prunable; another host's
271
- // table is reported but left strictly alone.
272
378
  const bareTables = findUnmanagedApprovalHookBlocks(existing);
273
- const ownStale = bareTables.filter((t) => hostIdFromHookCommand(t.command) === hostId && t.command !== expectedCommand);
274
- const foreignHosts = [
275
- ...new Set(bareTables
276
- // Exact current command bytes identify this host even when a host-id
277
- // override disagrees with the path-derived host.
278
- .filter((t) => t.command !== expectedCommand)
279
- .map((t) => hostIdFromHookCommand(t.command))
280
- .filter((h) => h !== null && h !== hostId)),
281
- ];
282
- if (ownStale.length > 0) {
283
- warnings.push(`Found ${ownStale.length} stale marker-less kimi-plugin-cc hook block(s) from this host's earlier installs. ` +
284
- `Run /kimi:setup to refresh, or /kimi:setup --uninstall --all to clear everything.`);
285
- }
286
- for (const host of foreignHosts) {
287
- warnings.push(`Host "${host}" has a marker-less kimi-plugin-cc hook block (kimi-code config rewrites strip comments). ` +
288
- `It still enforces and is left untouched; run that host's setup to re-adorn its markers.`);
379
+ const staleBare = bareTables.filter((t) => t.command !== expectedCommand);
380
+ if (staleBare.length > 0) {
381
+ warnings.push(`Found ${staleBare.length} stale marker-less kimi-plugin-cc hook block(s) from earlier installs. Run setup to clean them up.`);
289
382
  }
290
383
  if (installedCheck.installed && installedCheck.note !== undefined) {
291
384
  warnings.push(`Note: ${installedCheck.note}`);
292
385
  }
293
386
  if (!installedCheck.installed) {
294
- return {
295
- action: "check",
296
- summary: installedCheck.state.kind === "absent"
297
- ? `kimi-plugin-cc managed block is NOT installed in ${configPath}.`
298
- : `kimi-plugin-cc managed block is present but invalid: ${installedCheck.reason}.`,
299
- configPath,
300
- hookScriptPath,
301
- blockWritten: false,
302
- blockRemoved: false,
303
- probe: "failed",
304
- probeError: installedCheck.reason ?? "managed block missing or invalid",
305
- warnings,
306
- reviewGateEnabled,
307
- nextStep: installedCheck.state.kind === "absent"
308
- ? "Run /kimi:setup (without --check) to install the managed block."
309
- : installedCheck.state.kind === "orphan"
310
- ? ORPHAN_MARKER_REMEDY
311
- : "Run /kimi:setup --uninstall, then /kimi:setup to repair.",
312
- details: buildDetails({
313
- configPath,
314
- hookScriptPath,
315
- reviewGateEnabled,
316
- probe: { ok: false, reason: installedCheck.reason ?? "block missing/invalid" },
317
- warnings,
318
- }),
319
- };
387
+ return failedCheck({
388
+ summary: installedCheck.timeoutTooShort === true
389
+ ? `kimi-plugin-cc PreToolUse hook in ${configPath} does not enforce: ${installedCheck.reason}`
390
+ : installedCheck.state.kind === "absent"
391
+ ? `kimi-plugin-cc managed block is NOT installed in ${configPath}.`
392
+ : `kimi-plugin-cc managed block is present but invalid: ${installedCheck.reason}.`,
393
+ reason: installedCheck.reason ?? "managed block missing or invalid",
394
+ detailReason: installedCheck.reason ?? "block missing/invalid",
395
+ nextStep: installedCheck.timeoutTooShort === true
396
+ ? "Run setup (without --check) to rewrite the hook timeout."
397
+ : installedCheck.state.kind === "absent"
398
+ ? "Run setup (without --check) to install the managed block."
399
+ : installedCheck.state.kind === "orphan"
400
+ ? ORPHAN_MARKER_REMEDY
401
+ : installedCheck.state.kind === "duplicate" &&
402
+ parseManagedBlock(existing).blocks.some((entry) => entry.hostId !== null)
403
+ ? 'Run `kimi_setup` (action "install") or `scripts/companion.sh setup` to consolidate legacy host-scoped blocks into one canonical block.'
404
+ : "Run setup --uninstall, then setup to repair.",
405
+ });
320
406
  }
321
407
  collectPermissionRuleWarnings(existing, warnings);
322
408
  await collectKimiVersionWarnings(context.env, warnings);
323
409
  await collectInstalledKimiPluginsNotice(context.env, warnings);
324
- // Block is structurally valid AND points at the resolved hook
325
- // script — now confirm the script itself still loads and behaves.
410
+ const artifact = await verifyManagedHookArtifact(context.env, hookScriptPath);
411
+ if (!artifact.ok) {
412
+ return failedCheck({
413
+ summary: artifact.kind === "sha256-mismatch"
414
+ ? `Managed hook script ${hookScriptPath} does not match the bundled hook artifact (SHA-256 mismatch).`
415
+ : artifact.kind === "unsafe-path"
416
+ ? `Managed hook path ${hookScriptPath} failed safety checks.`
417
+ : artifact.kind === "bundle-missing"
418
+ ? `Bundled hook artifact is missing or unreadable.`
419
+ : `Managed block references ${hookScriptPath} but that path is unreadable.`,
420
+ reason: artifact.reason,
421
+ nextStep: artifact.kind === "unsafe-path"
422
+ ? "Remove or replace the unsafe symlink/non-regular path under the plugin hook directory, then re-run setup."
423
+ : artifact.kind === "bundle-missing"
424
+ ? "Run `bun run build` or reinstall the plugin, then re-run setup."
425
+ : "Run setup (without --check) to republish the hook script and refresh the managed block.",
426
+ });
427
+ }
326
428
  try {
327
429
  await assertHookScriptExists(hookScriptPath);
328
430
  }
329
431
  catch (err) {
330
- const message = err instanceof Error ? err.message : String(err);
331
- return {
332
- action: "check",
432
+ return failedCheck({
333
433
  summary: `Managed block references ${hookScriptPath} but that path is unreadable.`,
334
- configPath,
335
- hookScriptPath,
336
- blockWritten: false,
337
- blockRemoved: false,
338
- probe: "failed",
339
- probeError: message,
340
- warnings,
341
- reviewGateEnabled,
342
- nextStep: "Reinstall the plugin so dist/hooks/approval-hook.js is present, or run /kimi:setup to refresh the managed block.",
343
- details: buildDetails({
344
- configPath,
345
- hookScriptPath,
346
- reviewGateEnabled,
347
- probe: { ok: false, reason: message },
348
- warnings,
349
- }),
350
- };
434
+ reason: err instanceof Error ? err.message : String(err),
435
+ nextStep: "Run setup (without --check) to republish the hook script and refresh the managed block.",
436
+ });
351
437
  }
352
- const probe = await probeHook(hookScriptPath, context.env);
438
+ const probe = await probeHook(hookScriptPath, expectedCommand, context.env);
353
439
  return {
354
440
  action: "check",
355
441
  summary: probe.ok
@@ -362,102 +448,96 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
362
448
  probe: probe.ok ? "ok" : "failed",
363
449
  probeError: probe.ok ? undefined : probe.reason,
364
450
  warnings,
365
- reviewGateEnabled,
366
451
  nextStep: !probe.ok
367
- ? "Run /kimi:setup to repair the managed block, or /kimi:setup --uninstall if you want to remove the integration."
452
+ ? "Run setup to repair the managed block, or setup --uninstall to remove the integration."
368
453
  : installedCheck.via === "bare-table"
369
- // Enforcement remains active through the marker-less table, but recommend
370
- // re-adorning rather than claiming no action is needed.
371
- ? "Enforcement is active. Run /kimi:setup to re-adorn this host's managed-block markers — kimi-code stripped them on its last config write (comments are not preserved). Your hook keeps working meanwhile."
454
+ ? "Enforcement is active. Run setup to re-adorn the managed-block markers — kimi-code stripped comments on its last config write. Your hook keeps working meanwhile."
372
455
  : "No action needed.",
373
456
  details: buildDetails({
374
457
  configPath,
375
458
  hookScriptPath,
376
- reviewGateEnabled,
377
459
  probe,
378
460
  warnings,
379
- hostId,
461
+ kimiBinary,
380
462
  }),
381
463
  };
382
464
  }
383
- async function runUninstall(configPath, hookScriptPath, hostId, removeAllHosts, reviewGateEnabled, warnings, context) {
384
- return await withKimiConfigLock(configPath, () => runUninstallLocked(configPath, hookScriptPath, hostId, removeAllHosts, reviewGateEnabled, warnings, context));
385
- }
386
- async function runUninstallLocked(configPath, hookScriptPath, hostId, removeAllHosts, reviewGateEnabled, warnings, context) {
387
- const existing = await readConfigSafe(configPath);
388
- if (existing.length === 0) {
465
+ async function runUninstall(configPath, hookScriptPath, warnings, context) {
466
+ return await withKimiConfigLock(configPath, async () => {
467
+ const existing = await readConfigSafe(configPath);
468
+ if (existing.length === 0) {
469
+ return {
470
+ action: "uninstall",
471
+ summary: `Nothing to remove — ${configPath} does not exist or is empty.`,
472
+ configPath,
473
+ hookScriptPath,
474
+ blockWritten: false,
475
+ blockRemoved: false,
476
+ probe: "skipped",
477
+ warnings,
478
+ nextStep: "Run setup to install the managed block again.",
479
+ details: buildDetails({
480
+ configPath,
481
+ hookScriptPath,
482
+ probe: { ok: true, reason: "no-op (config absent)" },
483
+ warnings,
484
+ }),
485
+ };
486
+ }
487
+ const lineEnding = detectLineEnding(existing);
488
+ const inlineHooks = normalizeTopLevelInlineHooks(existing, lineEnding);
489
+ if (inlineHooks.found && !inlineHooks.converted) {
490
+ throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `Could not safely convert the top-level inline hooks assignment in ${configPath} during uninstall; the existing config was left unchanged.`, "setup.uninstall", { details: { configPath } });
491
+ }
492
+ const working = inlineHooks.contents;
493
+ const { blocks } = pairBlocks(splitPreservingEnding(working));
494
+ assertManagedBlocksSafeToReplace(working, blocks, configPath, "setup.uninstall");
495
+ const { stripped: strippedMarkers, removedBlocks, orphansLeft } = stripManagedBlocks(working);
496
+ const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
497
+ const { pruned: stripped, count: prunedCount } = pruneOrphanApprovalHooks(strippedMarkers, expectedCommand);
498
+ const removedAnything = removedBlocks > 0 || orphansLeft.length > 0 || prunedCount > 0;
499
+ const finalContents = removedAnything ? stripped : existing;
500
+ if (evaluateInstalled(finalContents, expectedCommand).installed ||
501
+ countCleanEntriesInFile(finalContents, expectedCommand) > 0) {
502
+ throw new RuntimeError("SETUP_UNINSTALL_INCOMPLETE", `Could not safely remove all kimi-plugin-cc hook entries from ${configPath}; an active hook entry for this plugin still remains. Inspect ${configPath} manually; the existing config was left unchanged.`, "setup.uninstall", { details: { configPath } });
503
+ }
504
+ const changed = removedAnything && finalContents !== existing;
505
+ if (changed) {
506
+ if (inlineHooks.found) {
507
+ warnings.push(`Converted the top-level inline hooks array (${inlineHooks.entryCount} entr${inlineHooks.entryCount === 1 ? "y" : "ies"}) to canonical [[hooks]] tables while removing kimi-plugin-cc entries and preserving foreign hooks.`);
508
+ }
509
+ await writeConfigAtomic(configPath, finalContents);
510
+ }
511
+ if (orphansLeft.length > 0) {
512
+ warnings.push(`Detected ${orphansLeft.length} orphan marker line(s) at ${orphansLeft
513
+ .map((line) => `line ${line + 1}`)
514
+ .join(", ")}. Removed the marker line(s) but preserved surrounding user content — verify the config visually.`);
515
+ }
516
+ if (prunedCount > 0) {
517
+ warnings.push(`Pruned ${prunedCount} orphaned kimi-plugin-cc hook block(s) with no managed marker.`);
518
+ }
389
519
  return {
390
520
  action: "uninstall",
391
- summary: `Nothing to remove — ${configPath} does not exist or is empty.`,
521
+ summary: changed
522
+ ? `Removed ${removedBlocks} managed block(s)${prunedCount > 0 ? ` + ${prunedCount} orphan hook block(s)` : ""} from ${configPath}.`
523
+ : `No kimi-plugin-cc managed block to remove from ${configPath}.`,
392
524
  configPath,
393
525
  hookScriptPath,
394
526
  blockWritten: false,
395
- blockRemoved: false,
527
+ blockRemoved: changed,
396
528
  probe: "skipped",
397
529
  warnings,
398
- reviewGateEnabled,
399
- nextStep: "Run /kimi:setup to install the managed block again.",
530
+ nextStep: changed
531
+ ? "Run setup again to reinstall the hook, or leave the plugin uninstalled."
532
+ : "Run setup to install the hook.",
400
533
  details: buildDetails({
401
534
  configPath,
402
535
  hookScriptPath,
403
- reviewGateEnabled,
404
- probe: { ok: true, reason: "no-op (config absent)" },
536
+ probe: { ok: true, reason: changed ? `removed ${removedBlocks} block(s)` : "no-op (no markers)" },
405
537
  warnings,
406
538
  }),
407
539
  };
408
- }
409
- // Scoped uninstall removes only this host's marked and marker-less blocks;
410
- // other hosts' blocks and live marker-less tables remain intact. `--all` is
411
- // the explicit every-host sweep for all of this plugin's hook tables.
412
- const { stripped: strippedMarkers, removedBlocks, orphansLeft } = stripManagedBlocks(existing, hostId, removeAllHosts);
413
- // Exact current command bytes also identify this host's table when a host-id
414
- // override disagrees with path derivation or a dev path is outside the strict
415
- // ownership pattern.
416
- const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
417
- const { pruned: stripped, count: prunedCount } = pruneOrphanApprovalHooks(strippedMarkers, removeAllHosts ? undefined : hostId, expectedCommand);
418
- const changed = stripped !== existing;
419
- if (changed) {
420
- await writeConfigAtomic(configPath, stripped);
421
- }
422
- if (orphansLeft.length > 0) {
423
- warnings.push(`Detected ${orphansLeft.length} orphan marker line(s) at ${orphansLeft
424
- .map((line) => `line ${line + 1}`)
425
- .join(", ")}. Removed the marker line(s) but preserved surrounding user content — verify the config visually.`);
426
- }
427
- if (prunedCount > 0) {
428
- warnings.push(`Pruned ${prunedCount} orphaned kimi-plugin-cc hook block(s) with no managed marker.`);
429
- }
430
- const { blocks: remainingBlocks } = parseManagedBlock(stripped, hostId);
431
- const remainingHosts = [
432
- ...new Set(remainingBlocks.map((b) => effectiveHost(b, hostId))),
433
- ];
434
- if (!removeAllHosts && remainingHosts.length > 0) {
435
- warnings.push(`Left ${remainingHosts.length} other host block(s) in place: ${remainingHosts.join(", ")}. ` +
436
- `Use \`/kimi:setup --uninstall --all\` to remove every host's block.`);
437
- }
438
- return {
439
- action: "uninstall",
440
- summary: changed
441
- ? `Removed ${removedBlocks} managed block(s)${prunedCount > 0 ? ` + ${prunedCount} orphan hook block(s)` : ""} from ${configPath}.`
442
- : `No kimi-plugin-cc managed block to remove from ${configPath}.`,
443
- configPath,
444
- hookScriptPath,
445
- blockWritten: false,
446
- blockRemoved: changed,
447
- probe: "skipped",
448
- warnings,
449
- reviewGateEnabled,
450
- nextStep: changed
451
- ? "Run /kimi:setup again to reinstall the hook, or leave the plugin uninstalled."
452
- : "Run /kimi:setup to install the hook.",
453
- details: buildDetails({
454
- configPath,
455
- hookScriptPath,
456
- reviewGateEnabled,
457
- probe: { ok: true, reason: changed ? `removed ${removedBlocks} block(s)` : "no-op (no markers)" },
458
- warnings,
459
- }),
460
- };
540
+ });
461
541
  }
462
542
  // ----- Config IO ---------------------------------------------------------
463
543
  async function readConfigSafe(configPath) {
@@ -470,39 +550,28 @@ async function readConfigSafe(configPath) {
470
550
  throw new RuntimeError("SETUP_CONFIG_READ_FAILED", `Failed to read kimi-code config at ${configPath}: ${err.message}`, "setup.read-config", err instanceof Error ? { cause: err, details: { configPath } } : { details: { configPath } });
471
551
  }
472
552
  }
473
- async function writeConfigAtomic(configPath, contents) {
474
- // Write a unique sibling temp file and atomically rename it. O_EXCL prevents
475
- // concurrent operations from sharing an intermediate path.
476
- //
477
- // Pass 0o600 at creation, not in a later chmod: the config can contain
478
- // credentials, so the temp file must never exist with a wider umask-derived
479
- // mode.
480
- await mkdir(path.dirname(configPath), { recursive: true });
553
+ async function writeFileAtomic(targetPath, contents, mode) {
554
+ await mkdir(path.dirname(targetPath), { recursive: true });
481
555
  const suffix = randomBytes(8).toString("hex");
482
- const tmpPath = `${configPath}.kimi-plugin-cc.${process.pid}.${suffix}.tmp`;
556
+ const tmpPath = `${targetPath}.kimi-plugin-cc.${process.pid}.${suffix}.tmp`;
483
557
  const openFlags = fsConstants.O_WRONLY |
484
558
  fsConstants.O_CREAT |
485
559
  fsConstants.O_EXCL |
486
560
  (fsConstants.O_NOFOLLOW ?? 0);
487
561
  try {
488
- const handle = await open(tmpPath, openFlags, 0o600);
562
+ const handle = await open(tmpPath, openFlags, mode);
489
563
  try {
490
564
  if (process.platform !== "win32") {
491
- // Windows file modes are emulated; skip the chmod to avoid
492
- // platform-specific noise. The threat model excludes Windows.
493
- // Belt-and-suspenders alongside the create-time mode above,
494
- // matching createPrivateLockFile's pattern.
495
- await handle.chmod(0o600);
565
+ await handle.chmod(mode);
496
566
  }
497
567
  await handle.writeFile(contents, "utf8");
498
568
  }
499
569
  finally {
500
570
  await handle.close();
501
571
  }
502
- await rename(tmpPath, configPath);
572
+ await rename(tmpPath, targetPath);
503
573
  }
504
574
  catch (err) {
505
- // Best-effort cleanup so stale tmp files don't accumulate.
506
575
  try {
507
576
  await unlink(tmpPath);
508
577
  }
@@ -512,11 +581,15 @@ async function writeConfigAtomic(configPath, contents) {
512
581
  throw err;
513
582
  }
514
583
  }
584
+ async function writeConfigAtomic(configPath, contents) {
585
+ // Pass 0o600 at creation so credentials in config.toml never exist with wider mode.
586
+ await writeFileAtomic(configPath, contents, 0o600);
587
+ }
515
588
  async function assertKimiHookSetValid(contents, configPath, stage, env) {
516
589
  const validation = await validateKimiHookSetForEnvironment(contents, env);
517
590
  if (validation.valid)
518
591
  return;
519
- throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `${validation.reason ?? "Configured hooks failed validation"} Repair or remove that [[hooks]] entry before rerunning /kimi:setup; the existing config was left unchanged.`, stage, {
592
+ throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `${validation.reason ?? "Configured hooks failed validation"} Repair or remove that [[hooks]] entry before rerunning setup; the existing config was left unchanged.`, stage, {
520
593
  details: {
521
594
  configPath,
522
595
  hookEntry: validation.entry,
@@ -602,151 +675,49 @@ function splitPreservingEnding(contents) {
602
675
  // Remove only unpaired marker comments, never the intervening content. The
603
676
  // normal full-file validation still gates writes.
604
677
  function removeOrphanMarkers(contents) {
605
- const lines = splitPreservingEnding(contents);
606
- const orphans = [];
607
- const comments = markerCommentLines(contents);
608
- let open = null;
609
- for (let i = 0; i < lines.length; i += 1) {
610
- if (!comments.has(i))
611
- continue;
612
- const line = lines[i].trim();
613
- const begin = MARKERS.BEGIN_LINE_RE.exec(line);
614
- if (begin !== null) {
615
- if (open !== null)
616
- orphans.push(open);
617
- open = { index: i, host: begin[1]?.toLowerCase() ?? null };
618
- }
619
- else {
620
- const end = MARKERS.END_LINE_RE.exec(line);
621
- if (end === null)
622
- continue;
623
- const endMarker = { index: i, host: end[1]?.toLowerCase() ?? null };
624
- if (open === null)
625
- orphans.push(endMarker);
626
- else {
627
- if (open.host !== endMarker.host)
628
- orphans.push(open, endMarker);
629
- open = null;
630
- }
631
- }
632
- }
633
- if (open !== null)
634
- orphans.push(open);
635
- const remove = new Set(orphans.map((marker) => marker.index));
678
+ const remove = new Set(pairBlocks(splitPreservingEnding(contents)).orphans.map((marker) => marker.line));
636
679
  return remove.size === 0
637
680
  ? { contents, count: 0 }
638
- : { contents: contents.split(/(?<=\n)/).filter((_, index) => !remove.has(index)).join(""), count: remove.size };
681
+ : { contents: removeLines(contents, remove), count: remove.size };
682
+ }
683
+ function consolidateManagedBlocks(contents, blocks, replacement, lineEnding) {
684
+ const [first, ...rest] = blocks;
685
+ const spliced = spliceBlock(contents, first.beginLine, first.endLine, replacement, lineEnding);
686
+ const deltaLines = splitPreservingEnding(replacement).length - (first.endLine - first.beginLine + 1);
687
+ const remove = new Set();
688
+ for (const extra of rest) {
689
+ for (let i = extra.beginLine + deltaLines; i <= extra.endLine + deltaLines; i += 1) {
690
+ remove.add(i);
691
+ }
692
+ }
693
+ return removeLines(spliced, remove);
639
694
  }
640
695
  /**
641
- * Remove managed blocks owned by `currentHost`, or every host with `removeAll`.
642
- * Ownership comes from the marker suffix or a legacy command's derived host.
643
- * Orphan markers are removed individually so surrounding user content survives.
696
+ * Remove all managed blocks and orphan markers while preserving surrounding content.
644
697
  */
645
- function stripManagedBlocks(contents, currentHost, removeAll) {
698
+ function stripManagedBlocks(contents) {
646
699
  const lines = splitPreservingEnding(contents);
647
- const rawLines = contents.split(/(?<=\n)/);
648
- const markerLines = markerCommentLines(contents);
649
- const result = [];
650
- const orphansLeft = [];
700
+ const { blocks, orphans } = pairBlocks(lines);
701
+ const orphansLeft = orphans.map((orphan) => orphan.line);
702
+ const remove = new Set(orphansLeft);
651
703
  let removedBlocks = 0;
652
- // Suffixed blocks belong only to the matching host. Complete legacy blocks
653
- // use their command-derived host; an unattributable non-canonical command is
654
- // ambiguous and only --all removes it. Orphan marker lines have no command
655
- // and can be swept individually by a scoped uninstall.
656
- const shouldRemove = (markerHost, commandPath, isOrphanMarker) => {
657
- if (removeAll)
658
- return true;
659
- if (markerHost !== null)
660
- return markerHost === currentHost;
661
- if (isOrphanMarker)
662
- return true;
663
- const derived = commandPath !== null ? hostIdFromHookCommand(commandPath) : null;
664
- if (derived === null)
665
- return false;
666
- return derived === currentHost;
667
- };
668
- let i = 0;
669
- while (i < lines.length) {
670
- const line = lines[i];
671
- const trimmed = line.trim();
672
- const begin = markerLines.has(i) ? MARKERS.BEGIN_LINE_RE.exec(trimmed) : null;
673
- if (begin !== null) {
674
- const beginHost = begin[1]?.toLowerCase() ?? null;
675
- // Look ahead for the matching END, capturing the block's command en route.
676
- let endIdx = -1;
677
- let blockCommand = null;
678
- for (let j = i + 1; j < lines.length; j += 1) {
679
- const nextTrimmed = lines[j].trim();
680
- if (markerLines.has(j) && MARKERS.BEGIN_LINE_RE.test(nextTrimmed)) {
681
- // Two BEGINs in a row — the outer one is an orphan.
682
- break;
683
- }
684
- const end = markerLines.has(j) ? MARKERS.END_LINE_RE.exec(nextTrimmed) : null;
685
- if (end !== null) {
686
- if ((end[1]?.toLowerCase() ?? null) === beginHost)
687
- endIdx = j;
688
- break;
689
- }
690
- const decoded = decodeManagedCommandLine(nextTrimmed);
691
- if (decoded !== null)
692
- blockCommand = decoded;
693
- }
694
- if (endIdx === -1) {
695
- // Orphan BEGIN: drop only this line (if it's ours to remove).
696
- if (shouldRemove(beginHost, null, true)) {
697
- orphansLeft.push(i);
698
- i += 1;
699
- continue;
700
- }
701
- result.push(rawLines[i]);
702
- i += 1;
703
- continue;
704
- }
705
- if (shouldRemove(beginHost, blockCommand, false)) {
706
- // Complete pair we're removing — drop BEGIN..END inclusive.
707
- removedBlocks += 1;
708
- i = endIdx + 1;
709
- continue;
710
- }
711
- // Another host's block — keep it verbatim.
712
- for (let k = i; k <= endIdx; k += 1)
713
- result.push(rawLines[k]);
714
- i = endIdx + 1;
715
- continue;
716
- }
717
- const end = markerLines.has(i) ? MARKERS.END_LINE_RE.exec(trimmed) : null;
718
- if (end !== null) {
719
- const endHost = end[1]?.toLowerCase() ?? null;
720
- // Orphan END with no preceding BEGIN: drop only this line (if ours).
721
- if (shouldRemove(endHost, null, true)) {
722
- orphansLeft.push(i);
723
- i += 1;
724
- continue;
725
- }
726
- result.push(rawLines[i]);
727
- i += 1;
728
- continue;
729
- }
730
- result.push(rawLines[i]);
731
- i += 1;
704
+ for (const block of blocks) {
705
+ removedBlocks += 1;
706
+ for (let i = block.beginLine; i <= block.endLine; i += 1)
707
+ remove.add(i);
732
708
  }
733
- return { stripped: result.join(""), removedBlocks, orphansLeft };
709
+ return { stripped: removeLines(contents, remove), removedBlocks, orphansLeft };
710
+ }
711
+ function removeLines(contents, remove) {
712
+ return contents.split(/(?<=\n)/).filter((_, index) => !remove.has(index)).join("");
734
713
  }
735
714
  /**
736
- * Remove orphaned, marker-less `[[hooks]]` tables that are unambiguously this
737
- * plugin's approval hook (see `findUnmanagedApprovalHookBlocks`). Returns the
738
- * cleaned text, the count removed, and the decoded commands of the removed
739
- * tables (so install can distinguish "re-adorning this host's live hook after
740
- * a kimi-code comment strip" from "sweeping stale cruft"). A no-op (returns
741
- * the input unchanged) when there is nothing to prune, so callers can compare
742
- * identity cheaply.
743
- *
744
- * `ownedBy` restricts the prune to tables whose command path derives to that
745
- * host — REQUIRED for scoped install/uninstall so one host never disarms the
746
- * other's live (marker-stripped) hook. Omit only for `--uninstall --all`.
715
+ * Remove orphaned, marker-less `[[hooks]]` tables that belong to kimi-plugin-cc
716
+ * (see `findUnmanagedApprovalHookBlocks`). Returns the cleaned text, the count
717
+ * removed, and decoded commands so install can distinguish re-adorning from cleanup.
747
718
  */
748
- function pruneOrphanApprovalHooks(contents, ownedBy, alsoMatchCommand) {
749
- const ranges = findUnmanagedApprovalHookBlocks(contents, ownedBy, alsoMatchCommand);
719
+ function pruneOrphanApprovalHooks(contents, alsoMatchCommand) {
720
+ const ranges = findUnmanagedApprovalHookBlocks(contents, alsoMatchCommand);
750
721
  if (ranges.length === 0)
751
722
  return { pruned: contents, count: 0, commands: [] };
752
723
  const remove = new Set();
@@ -763,16 +734,11 @@ function pruneOrphanApprovalHooks(contents, ownedBy, alsoMatchCommand) {
763
734
  };
764
735
  }
765
736
  // ----- Block content -----------------------------------------------------
766
- function buildManagedBlock(hookScriptPath, env, lineEnding = "\n", hostId = "") {
767
- const shellCommand = buildHookShellCommand(hookScriptPath, env);
737
+ function buildManagedBlock(shellCommand, lineEnding = "\n") {
768
738
  const commandLine = `command = ${tomlBasicString(shellCommand)}`;
769
- const suffix = hostId.length > 0 ? `:${hostId}` : "";
770
739
  return [
771
- `${BEGIN_MARKER_PREFIX}${suffix} (v${KIMI_PLUGIN_CC_VERSION}) ===`,
772
- `# DO NOT EDIT — managed by /kimi:setup. Run /kimi:setup --uninstall to remove.`,
773
- `# Host: ${hostId.length > 0 ? hostId : "(legacy)"} — each host owns a separate block in this shared`,
774
- `# ~/.kimi-code/config.toml. Scoped setup/uninstall preserves other hosts;`,
775
- `# /kimi:setup --uninstall --all removes every host's block.`,
740
+ `${BEGIN_MARKER_PREFIX} (v${KIMI_PLUGIN_CC_VERSION}) ===`,
741
+ `# DO NOT EDIT — managed by kimi-plugin-cc setup. Run \`scripts/companion.sh setup --uninstall\` to remove.`,
776
742
  `# Purpose:`,
777
743
  `# kimi-code's \`kimi -p\` mode hard-codes permission='auto' and`,
778
744
  `# auto-approves every tool call. This hook enforces each managed command's`,
@@ -789,7 +755,7 @@ function buildManagedBlock(hookScriptPath, env, lineEnding = "\n", hostId = "")
789
755
  `event = "PreToolUse"`,
790
756
  commandLine,
791
757
  `timeout = ${DEFAULT_HOOK_TIMEOUT_S}`,
792
- `# === END kimi-plugin-cc-managed${suffix} ===`,
758
+ `# === END kimi-plugin-cc-managed ===`,
793
759
  ].join(lineEnding);
794
760
  }
795
761
  /**
@@ -820,9 +786,6 @@ function assertHookPathTomlSafe(hookScriptPath) {
820
786
  ].join(" "), "setup.hook-path", { details: { hookScriptPath } });
821
787
  }
822
788
  // ----- Path resolution ---------------------------------------------------
823
- function resolveKimiCodeConfigPath(env) {
824
- return path.join(resolveKimiHome(env), "config.toml");
825
- }
826
789
  async function assertHookScriptExists(hookScriptPath) {
827
790
  try {
828
791
  await access(hookScriptPath, fsConstants.R_OK);
@@ -834,22 +797,23 @@ async function assertHookScriptExists(hookScriptPath) {
834
797
  /**
835
798
  * Two-layer probe; both layers require exit 2 and a non-empty denial reason.
836
799
  *
837
- * 1. Directly spawn the hook with the absolute path from resolveNodeBinary,
838
- * catching missing/broken scripts and incorrect hook exit behavior without
839
- * relying on PATH.
840
- * 2. Execute the exact canonical command from buildHookShellCommand through
841
- * `/bin/sh -c`: two shell-quoted absolute tokens for Node and the script.
800
+ * 1. Directly spawn the hook with the absolute Node path parsed back from
801
+ * `command`, catching missing/broken scripts and incorrect hook exit
802
+ * behavior without relying on PATH.
803
+ * 2. Execute `command`, the exact canonical bytes from buildHookShellCommand,
804
+ * through `/bin/sh -c`: two shell-quoted absolute tokens for Node and the
805
+ * script.
842
806
  * This catches pinned-interpreter execution and quoting failures. It does
843
807
  * NOT test PATH discovery or compatibility of some other `node` on PATH.
844
808
  *
845
809
  * The shell layer is skipped where `/bin/sh` is unsupported; the runtime
846
810
  * otherwise assumes POSIX.
847
811
  */
848
- async function probeHook(hookScriptPath, env) {
849
- const directResult = await probeHookDirect(hookScriptPath, env);
812
+ async function probeHook(hookScriptPath, command, env) {
813
+ const directResult = await probeHookDirect(hookScriptPath, command, env);
850
814
  if (!directResult.ok)
851
815
  return directResult;
852
- const shellResult = await probeHookViaShell(hookScriptPath, env);
816
+ const shellResult = await probeHookViaShell(command, env);
853
817
  if (!shellResult.ok)
854
818
  return shellResult;
855
819
  return {
@@ -857,20 +821,20 @@ async function probeHook(hookScriptPath, env) {
857
821
  reason: `${directResult.reason}; shell probe also ok`,
858
822
  };
859
823
  }
860
- async function probeHookDirect(hookScriptPath, env) {
861
- const nodeBin = resolveNodeBinary(env);
824
+ async function probeHookDirect(hookScriptPath, command, env) {
825
+ // Parsed back from the command, never re-resolved; the fallback is unreachable.
826
+ const nodeBin = parseHookShellCommand(command)?.nodeBin ?? resolveNodeBinary(env);
862
827
  return await spawnProbe(nodeBin, [hookScriptPath], env, `direct probe via ${nodeBin}`);
863
828
  }
864
- async function probeHookViaShell(hookScriptPath, env) {
829
+ async function probeHookViaShell(shellCommand, env) {
865
830
  if (process.platform === "win32") {
866
831
  // The hook runner shells out via `/bin/sh -c` per agent-core; on
867
832
  // Windows the entire kimi-code launcher is unsupported. Skip the
868
833
  // shell probe so we don't false-fail on a platform we don't run on.
869
834
  return { ok: true, reason: "shell probe skipped (Windows)" };
870
835
  }
871
- // Reuse the exact command string the managed block wrote into
872
- // kimi-code's config so probe and runtime cannot drift.
873
- const shellCommand = buildHookShellCommand(hookScriptPath, env);
836
+ // The exact command string the managed block wrote into kimi-code's config,
837
+ // so probe and runtime cannot drift.
874
838
  return await spawnProbe("/bin/sh", ["-c", shellCommand], env, `shell probe via /bin/sh -c`);
875
839
  }
876
840
  function spawnProbe(command, args, env, label) {
@@ -952,6 +916,368 @@ function truncate(value, max) {
952
916
  return value;
953
917
  return `${value.slice(0, max)}…`;
954
918
  }
919
+ // ----- Plugin-owned kimi-code (--install-kimi) ---------------------------
920
+ const KIMI_PACKAGE = "@moonshot-ai/kimi-code";
921
+ const KIMI_INSTALL_TIMEOUT_MS = 300_000;
922
+ const KIMI_INSTALL_KILL_GRACE_MS = 2_000;
923
+ // First start of a fresh install loads a large bundle; allow more than the
924
+ // 5s job-time probe.
925
+ const KIMI_INSTALL_PROBE_TIMEOUT_MS = 30_000;
926
+ const STDERR_TAIL_BYTES = 2_000;
927
+ const STAGING_PREFIX = ".staging-";
928
+ // A staging directory younger than this may belong to a concurrent install
929
+ // still inside its npm timeout and probe window, so it is not stale yet.
930
+ const STALE_STAGING_AGE_MS = 2 * (KIMI_INSTALL_TIMEOUT_MS + KIMI_INSTALL_PROBE_TIMEOUT_MS);
931
+ /** Numeric, not lexical: "2.10.0" is above "2.9.0". */
932
+ export function highestCertifiedKimiVersion(versions = NATIVE_V2_CERTIFIED_VERSIONS) {
933
+ const parse = (v) => v.split(".").map(Number);
934
+ const sorted = [...versions].sort((a, b) => {
935
+ const [x, y] = [parse(a), parse(b)];
936
+ for (let i = 0; i < 3; i += 1) {
937
+ if (x[i] !== y[i])
938
+ return (x[i] ?? 0) - (y[i] ?? 0);
939
+ }
940
+ return 0;
941
+ });
942
+ const highest = sorted[sorted.length - 1];
943
+ if (highest === undefined || !/^\d+\.\d+\.\d+$/.test(highest)) {
944
+ throw new RuntimeError("KIMI_INSTALL_FAILED", "No exact certified kimi-code version is available to install.", "setup.install-kimi");
945
+ }
946
+ return highest;
947
+ }
948
+ function compareExactVersions(a, b) {
949
+ const [x, y] = [a.split(".").map(Number), b.split(".").map(Number)];
950
+ for (let i = 0; i < 3; i += 1) {
951
+ if (x[i] !== y[i])
952
+ return (x[i] ?? 0) - (y[i] ?? 0);
953
+ }
954
+ return 0;
955
+ }
956
+ async function runInstallKimi(json, context) {
957
+ let version = "";
958
+ try {
959
+ version = highestCertifiedKimiVersion();
960
+ const outcome = await installPluginOwnedKimi(version, context.env);
961
+ const selection = selectKimiBinary(context.env);
962
+ const jobsUseIt = selection.source === "plugin-owned" && selection.command === outcome.binary;
963
+ const summary = outcome.downloaded
964
+ ? `Installed kimi-code ${version} for kimi-plugin-cc.`
965
+ : `kimi-code ${version} is already installed for kimi-plugin-cc; nothing was downloaded.`;
966
+ const jobsLine = jobsUseIt
967
+ ? "Jobs will now use this binary."
968
+ : selection.source === "override"
969
+ ? `KIMI_PLUGIN_CC_KIMI_BIN is set, so jobs keep using ${selection.command} until it is unset.`
970
+ : `Jobs do not use this binary yet: ${selection.pluginOwned.reason ?? "selection did not pick it"}.`;
971
+ return installKimiResult({
972
+ summary,
973
+ failed: false,
974
+ details: [
975
+ `Version: ${version}`,
976
+ `Binary: ${outcome.binary}`,
977
+ `Current link: ${outcome.current} -> ${path.join(version, "node_modules", ".bin", "kimi")}`,
978
+ `Jobs: ${jobsLine}`,
979
+ ],
980
+ nextStep: jobsUseIt
981
+ ? "Run setup --check to confirm the hook and the selected binary."
982
+ : "Unset KIMI_PLUGIN_CC_KIMI_BIN to use the plugin-owned binary, then run setup --check.",
983
+ report: {
984
+ ok: true,
985
+ json,
986
+ version,
987
+ downloaded: outcome.downloaded,
988
+ binary: outcome.binary,
989
+ current: outcome.current,
990
+ selectedBinary: selection.command,
991
+ selectedSource: selection.source,
992
+ },
993
+ });
994
+ }
995
+ catch (error) {
996
+ const runtimeError = error instanceof RuntimeError
997
+ ? error
998
+ : new RuntimeError("KIMI_INSTALL_FAILED", error instanceof Error ? error.message : String(error), "setup.install-kimi");
999
+ return installKimiResult({
1000
+ summary: `Failed to install kimi-code${version ? ` ${version}` : ""} for kimi-plugin-cc; the selected binary is unchanged.`,
1001
+ failed: true,
1002
+ probeError: `[${runtimeError.code}] ${runtimeError.message}`,
1003
+ details: [`Error: [${runtimeError.code}] ${runtimeError.message}`],
1004
+ nextStep: "Fix the cause above and re-run setup --install-kimi. Jobs keep using the previously selected binary.",
1005
+ report: {
1006
+ ok: false,
1007
+ json,
1008
+ version,
1009
+ downloaded: false,
1010
+ error: { code: runtimeError.code, message: runtimeError.message, details: runtimeError.details },
1011
+ },
1012
+ });
1013
+ }
1014
+ }
1015
+ function installKimiResult(args) {
1016
+ return {
1017
+ action: "install-kimi",
1018
+ summary: args.summary,
1019
+ configPath: "",
1020
+ hookScriptPath: "",
1021
+ blockWritten: false,
1022
+ blockRemoved: false,
1023
+ // "failed" makes the companion exit 1; the hook itself is not probed here.
1024
+ probe: args.failed ? "failed" : "skipped",
1025
+ probeError: args.probeError,
1026
+ warnings: [],
1027
+ nextStep: args.nextStep,
1028
+ details: args.details,
1029
+ kimiInstall: args.report,
1030
+ };
1031
+ }
1032
+ /**
1033
+ * Install exactly `version` into `<data root>/kimi-plugin-cc/kimi-bin/<version>/` and point
1034
+ * `current` at it. A verified existing install is reused without network
1035
+ * access. Downloads stage in a sibling directory that is verified with the
1036
+ * exact-version probe before it is renamed into place; any failure removes
1037
+ * the staging directory and leaves `current` untouched.
1038
+ */
1039
+ async function installPluginOwnedKimi(version, env) {
1040
+ if (process.platform === "win32") {
1041
+ throw new RuntimeError("KIMI_INSTALL_UNSUPPORTED_PLATFORM", "setup --install-kimi is not supported on Windows. Install kimi-code yourself and set KIMI_PLUGIN_CC_KIMI_BIN to its path.", "setup.install-kimi");
1042
+ }
1043
+ const binDir = resolveKimiBinDir(env);
1044
+ await mkdir(binDir, { recursive: true });
1045
+ await removeStaleStaging(binDir);
1046
+ const versionDir = path.join(binDir, version);
1047
+ const binRelative = path.join(version, "node_modules", ".bin", "kimi");
1048
+ const binPath = path.join(binDir, binRelative);
1049
+ const currentPath = path.join(binDir, "current");
1050
+ const existing = await verifyKimiBinary(binPath, binDir, version, version, env);
1051
+ if (existing.ok) {
1052
+ await pointCurrentAt(binDir, binRelative, currentPath, env);
1053
+ return { version, downloaded: false, binary: await realpath(binPath), current: currentPath };
1054
+ }
1055
+ const staging = await mkdtemp(path.join(binDir, `${STAGING_PREFIX}${version}-`));
1056
+ let trash;
1057
+ try {
1058
+ await writeFile(path.join(staging, "package.json"), `${JSON.stringify({ name: "kimi-plugin-cc-kimi-bin", private: true })}\n`, "utf8");
1059
+ await runNpmInstall(staging, version, env);
1060
+ const staged = await verifyKimiBinary(path.join(staging, "node_modules", ".bin", "kimi"), binDir, path.basename(staging), version, env);
1061
+ if (!staged.ok) {
1062
+ throw new RuntimeError("KIMI_INSTALL_VERIFY_FAILED", `The installed kimi-code did not verify as exactly ${version}: ${staged.reason}.`, "setup.install-kimi", { details: { expected_version: version } });
1063
+ }
1064
+ if (await pathExists(versionDir)) {
1065
+ // A present but unverifiable version directory is set aside, not reused.
1066
+ trash = path.join(binDir, `.trash-${version}-${randomBytes(4).toString("hex")}`);
1067
+ await rename(versionDir, trash);
1068
+ }
1069
+ try {
1070
+ await rename(staging, versionDir);
1071
+ }
1072
+ catch (error) {
1073
+ if (trash) {
1074
+ await rename(trash, versionDir).catch(() => undefined);
1075
+ trash = undefined;
1076
+ }
1077
+ throw error;
1078
+ }
1079
+ await pointCurrentAt(binDir, binRelative, currentPath, env);
1080
+ return { version, downloaded: true, binary: await realpath(binPath), current: currentPath };
1081
+ }
1082
+ finally {
1083
+ await rm(staging, { recursive: true, force: true });
1084
+ if (trash)
1085
+ await rm(trash, { recursive: true, force: true });
1086
+ }
1087
+ }
1088
+ /** Remove staging directories an interrupted install left directly in kimi-bin/. */
1089
+ async function removeStaleStaging(binDir, now = Date.now()) {
1090
+ let entries;
1091
+ try {
1092
+ entries = await readdir(binDir);
1093
+ }
1094
+ catch {
1095
+ return;
1096
+ }
1097
+ for (const name of entries) {
1098
+ if (!name.startsWith(STAGING_PREFIX))
1099
+ continue;
1100
+ const entry = path.join(binDir, name);
1101
+ try {
1102
+ const info = await lstat(entry);
1103
+ if (!info.isDirectory() || now - info.mtimeMs < STALE_STAGING_AGE_MS)
1104
+ continue;
1105
+ await rm(entry, { recursive: true, force: true });
1106
+ }
1107
+ catch {
1108
+ // Best effort: a leftover never affects binary resolution.
1109
+ }
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Containment comes before execution: `binary` must resolve to an executable
1114
+ * regular file physically inside `<realpath(binDir)>/<dirName>/`, and only
1115
+ * that resolved path is probed. Anchoring at the real kimi-bin plus the
1116
+ * expected name rejects a version or staging directory that is itself a link.
1117
+ */
1118
+ async function verifyKimiBinary(binary, binDir, dirName, version, env) {
1119
+ let resolved;
1120
+ let root;
1121
+ try {
1122
+ resolved = await realpath(binary);
1123
+ root = path.join(await realpath(binDir), dirName);
1124
+ }
1125
+ catch {
1126
+ return { ok: false, reason: `${binary} is missing` };
1127
+ }
1128
+ if (!resolved.startsWith(`${root}${path.sep}`)) {
1129
+ return { ok: false, reason: `${binary} resolves to ${resolved}, outside ${root}${path.sep}` };
1130
+ }
1131
+ try {
1132
+ const info = await lstat(resolved);
1133
+ if (!info.isFile())
1134
+ return { ok: false, reason: `${resolved} is not a regular file` };
1135
+ await access(resolved, fsConstants.X_OK);
1136
+ }
1137
+ catch {
1138
+ return { ok: false, reason: `${resolved} is not executable` };
1139
+ }
1140
+ const probe = await probeKimiVersion({ kimiBin: resolved, env, timeoutMs: KIMI_INSTALL_PROBE_TIMEOUT_MS });
1141
+ if (probe.kind !== "ok")
1142
+ return { ok: false, reason: probe.reason };
1143
+ const observed = probe.version.replace(/^v/, "");
1144
+ return observed === version ? { ok: true } : { ok: false, reason: `\`--version\` reported ${probe.version}` };
1145
+ }
1146
+ /**
1147
+ * Atomically replace `current` (POSIX rename over the old link), then confirm
1148
+ * binary resolution accepts the new link; otherwise restore the old one.
1149
+ */
1150
+ async function pointCurrentAt(binDir, binRelative, currentPath, env) {
1151
+ let previous;
1152
+ try {
1153
+ previous = await readlink(currentPath);
1154
+ }
1155
+ catch {
1156
+ previous = undefined;
1157
+ }
1158
+ if (previous === binRelative && inspectPluginOwnedKimi(env).status === "active")
1159
+ return;
1160
+ const swap = async (target) => {
1161
+ const temp = path.join(binDir, `.current-${randomBytes(4).toString("hex")}`);
1162
+ await symlink(target, temp);
1163
+ try {
1164
+ await rename(temp, currentPath);
1165
+ }
1166
+ catch (error) {
1167
+ await rm(temp, { force: true });
1168
+ throw error;
1169
+ }
1170
+ };
1171
+ await swap(binRelative);
1172
+ const state = inspectPluginOwnedKimi(env);
1173
+ if (state.status !== "active") {
1174
+ if (previous !== undefined)
1175
+ await swap(previous);
1176
+ else
1177
+ await rm(currentPath, { force: true });
1178
+ throw new RuntimeError("KIMI_INSTALL_VERIFY_FAILED", `The new ${currentPath} link was not accepted by binary resolution: ${state.reason ?? state.status}. The previous link was restored.`, "setup.install-kimi");
1179
+ }
1180
+ }
1181
+ async function runNpmInstall(prefix, version, env) {
1182
+ // Never a global install, whatever the caller's npm environment says.
1183
+ const npmEnv = { ...env };
1184
+ for (const key of Object.keys(npmEnv)) {
1185
+ if (/^npm_config_(global|location|prefix)$/i.test(key))
1186
+ delete npmEnv[key];
1187
+ }
1188
+ const args = [
1189
+ "install",
1190
+ "--prefix", prefix,
1191
+ "--no-global",
1192
+ // kimi-code's postinstall only acts on global installs and no runtime
1193
+ // dependency declares an install script.
1194
+ "--ignore-scripts",
1195
+ "--no-audit",
1196
+ "--no-fund",
1197
+ "--no-update-notifier",
1198
+ "--save-exact",
1199
+ `${KIMI_PACKAGE}@${version}`,
1200
+ ];
1201
+ await new Promise((resolve, reject) => {
1202
+ let child;
1203
+ try {
1204
+ child = spawn("npm", args, { cwd: prefix, env: npmEnv, stdio: ["ignore", "ignore", "pipe"], detached: true });
1205
+ }
1206
+ catch (error) {
1207
+ reject(npmFailure(`could not start npm: ${error.message}`, version));
1208
+ return;
1209
+ }
1210
+ let stderr = "";
1211
+ child.stderr.setEncoding("utf8");
1212
+ child.stderr.on("data", (chunk) => {
1213
+ stderr = (stderr + chunk).slice(-STDERR_TAIL_BYTES);
1214
+ });
1215
+ let timedOut = false;
1216
+ const killGroup = (signal) => {
1217
+ try {
1218
+ if (child.pid !== undefined)
1219
+ process.kill(-child.pid, signal);
1220
+ }
1221
+ catch {
1222
+ }
1223
+ };
1224
+ const timer = setTimeout(() => {
1225
+ timedOut = true;
1226
+ killGroup("SIGTERM");
1227
+ setTimeout(() => killGroup("SIGKILL"), KIMI_INSTALL_KILL_GRACE_MS).unref();
1228
+ }, KIMI_INSTALL_TIMEOUT_MS);
1229
+ child.on("error", (error) => {
1230
+ clearTimeout(timer);
1231
+ reject(npmFailure(`could not start npm: ${error.message}`, version));
1232
+ });
1233
+ child.on("close", (code, signal) => {
1234
+ clearTimeout(timer);
1235
+ if (timedOut) {
1236
+ reject(npmFailure(`npm install timed out after ${KIMI_INSTALL_TIMEOUT_MS / 1000}s`, version, stderr));
1237
+ }
1238
+ else if (code !== 0) {
1239
+ reject(npmFailure(`npm install exited ${code ?? signal}`, version, stderr));
1240
+ }
1241
+ else {
1242
+ resolve();
1243
+ }
1244
+ });
1245
+ });
1246
+ }
1247
+ function npmFailure(reason, version, stderr = "") {
1248
+ return new RuntimeError("KIMI_INSTALL_FAILED", `Could not install ${KIMI_PACKAGE}@${version}: ${reason}.`, "setup.install-kimi", { details: { package: `${KIMI_PACKAGE}@${version}`, ...(stderr.trim() ? { npm_stderr_tail: stderr.trim() } : {}) } });
1249
+ }
1250
+ async function pathExists(target) {
1251
+ try {
1252
+ await access(target);
1253
+ return true;
1254
+ }
1255
+ catch {
1256
+ return false;
1257
+ }
1258
+ }
1259
+ /** Which binary jobs will use and why, plus a note when the plugin-owned one is stale or unusable. */
1260
+ function describeKimiBinary(env, warnings) {
1261
+ const selection = selectKimiBinary(env);
1262
+ const owned = selection.pluginOwned;
1263
+ const highest = highestCertifiedKimiVersion();
1264
+ if (owned.status === "active" && owned.version && compareExactVersions(owned.version, highest) < 0) {
1265
+ warnings.push(`NOTE: the plugin-owned kimi-code ${owned.version} is behind the highest certified version ${highest}. Run setup --install-kimi to install ${highest}.`);
1266
+ }
1267
+ if (owned.status === "rejected") {
1268
+ warnings.push(`The plugin-owned kimi-code install is not used: ${owned.reason}. Run setup --install-kimi to repair it.`);
1269
+ }
1270
+ switch (selection.source) {
1271
+ case "override":
1272
+ return `${selection.command} (KIMI_PLUGIN_CC_KIMI_BIN override)`;
1273
+ case "plugin-owned":
1274
+ return `${selection.command} (plugin-owned kimi-code ${owned.version} from setup --install-kimi)`;
1275
+ case "path":
1276
+ return owned.status === "absent"
1277
+ ? `kimi on PATH (no plugin-owned install; setup --install-kimi installs ${highest})`
1278
+ : `kimi on PATH (plugin-owned install ${owned.status}${owned.reason ? `: ${owned.reason}` : ""})`;
1279
+ }
1280
+ }
955
1281
  // ----- Permission rules scan --------------------------------------------
956
1282
  /**
957
1283
  * Warn only when the installed kimi is demonstrably outside the certified
@@ -963,33 +1289,32 @@ function truncate(value, max) {
963
1289
  async function collectKimiVersionWarnings(env, warnings) {
964
1290
  if (env.KIMI_PLUGIN_CC_SKIP_VERSION_PROBE === "1")
965
1291
  return;
1292
+ // The same binary jobs select (override, plugin-owned, then PATH).
966
1293
  const probe = await probeKimiVersion({
967
- kimiBin: env.KIMI_PLUGIN_CC_KIMI_BIN || undefined,
1294
+ kimiBin: selectKimiBinary(env).command,
968
1295
  env,
969
1296
  });
970
1297
  if (probe.kind === "failed") {
971
- // Don't warn about probe failure here — if kimi is genuinely
972
- // missing/broken, the hook probe path will catch it with a much
973
- // clearer message. Avoid double-noise.
1298
+ warnings.push(`WARNING: could not verify the selected kimi-code binary version (${probe.reason}). Model-spawning operations will refuse until a working kimi-code >= ${KIMI_MINIMUM_CERTIFIED_VERSION} binary is available; run \`kimi_setup\` (action "install_kimi") or \`scripts/companion.sh setup --install-kimi\`, or check KIMI_PLUGIN_CC_KIMI_BIN.`);
974
1299
  return;
975
1300
  }
976
- if (!probe.inTestedRange && !isNativeV2CertifiedVersion(probe.version)) {
977
- warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION, NATIVE_V2_ANY_OPERATION_VERSIONS));
1301
+ if (!isNativeV2CertifiedVersion(probe.version)) {
1302
+ warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION, NATIVE_V2_ANY_OPERATION_VERSIONS, env));
978
1303
  return;
979
1304
  }
980
- if (probe.version === "2.6.2" || probe.version === "2.6.3" || probe.version === "2.7.2" || probe.version === "2.7.3") {
1305
+ if (kimiReleaseHas(probe.version, "bounded-swarm")) {
981
1306
  warnings.push(`NOTE: kimi-code ${probe.version} is certified for all operations. Swarm uses bounded waves with concurrency 2 or more, and one direct worker at concurrency 1. The finite job budget stops the whole run.`);
982
1307
  return;
983
1308
  }
984
1309
  if (NATIVE_V2_NON_SWARM_VERSIONS.includes(probe.version)) {
985
- warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn on this exact release. Select exact kimi-code 2.6.2, 2.6.3, 2.7.2 or 2.7.3 for this plugin's certified bounded waves and single-worker path.`);
1310
+ warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn on this exact release. Select exact kimi-code ${formatVersionChoice(kimiVersionsWith("bounded-swarm"))} for this plugin's certified bounded waves and single-worker path.`);
986
1311
  }
987
1312
  }
988
1313
  /**
989
1314
  * Non-blocking notice for kimi-code's own enabled plugins from
990
1315
  * ~/.kimi-code/plugins/installed.json. Their tools can register on every
991
1316
  * session, but read-only commands deny everything outside READ_ONLY_TOOLS
992
- * (Read, Grep, Glob, ReadMediaFile, TaskList, TaskOutput), which can waste model
1317
+ * (Read, Grep, Glob, ReadMediaFile, TaskList, TaskOutput, WaitFor), which can waste model
993
1318
  * turns. Missing, unreadable, or malformed manifests produce no notice; setup
994
1319
  * never blocks on or mutates the plugin list.
995
1320
  */
@@ -1025,10 +1350,10 @@ async function collectInstalledKimiPluginsNotice(env, warnings) {
1025
1350
  warnings.push([
1026
1351
  `NOTE: ${enabledIds.length} kimi-code plugin(s) installed and enabled: ${enabledIds.join(", ")}.`,
1027
1352
  " kimi-code registers their tools (including MCP) on every session. Under kimi-plugin-cc's",
1028
- " read-only commands (/kimi:review, /kimi:challenge, /kimi:ask, and the review gate) the",
1029
- " PreToolUse hook denies any tool outside Read/Grep/Glob, so calls to these plugins' tools",
1353
+ " read-only operations (kimi_read and companion.sh read) the",
1354
+ " PreToolUse hook denies every tool that is not on its read-only list, so calls to these plugins' tools",
1030
1355
  " are blocked — safe, but they can waste model turns. This is expected; no action needed.",
1031
- " (/kimi:rescue and /kimi:swarm apply their own allowlists.) To avoid the turn-waste, disable",
1356
+ " (kimi_write, companion.sh write, and swarm modes apply their own allowlists.) To avoid the turn-waste, disable",
1032
1357
  " kimi-code plugins you don't need for delegated work in your kimi-code config.",
1033
1358
  ].join("\n"));
1034
1359
  }
@@ -1096,10 +1421,9 @@ function buildDetails(args) {
1096
1421
  const details = [
1097
1422
  `Companion runtime: Node ${process.version}`,
1098
1423
  `Plugin version: ${KIMI_PLUGIN_CC_VERSION}`,
1099
- ...(args.hostId ? [`Host id: ${args.hostId}`] : []),
1424
+ ...(args.kimiBinary ? [`Kimi binary: ${args.kimiBinary}`] : []),
1100
1425
  `Config file: ${args.configPath}`,
1101
1426
  `Hook script: ${args.hookScriptPath}`,
1102
- `Review gate: ${args.reviewGateEnabled ? "enabled" : "disabled"}`,
1103
1427
  `Probe: ${args.probe.ok ? "ok" : "failed"} — ${args.probe.reason}`,
1104
1428
  ];
1105
1429
  if (args.warnings.length > 0) {
@@ -1111,6 +1435,8 @@ function buildDetails(args) {
1111
1435
  return details;
1112
1436
  }
1113
1437
  export function renderSetupResult(result) {
1438
+ if (result.kimiInstall)
1439
+ return renderInstallKimiResult(result, result.kimiInstall);
1114
1440
  return [
1115
1441
  result.summary,
1116
1442
  "",
@@ -1118,7 +1444,6 @@ export function renderSetupResult(result) {
1118
1444
  `Block written: ${result.blockWritten ? "yes" : "no"}`,
1119
1445
  `Block removed: ${result.blockRemoved ? "yes" : "no"}`,
1120
1446
  `Probe: ${result.probe}${result.probeError ? ` (${result.probeError})` : ""}`,
1121
- `Review gate: ${result.reviewGateEnabled ? "enabled" : "disabled"}`,
1122
1447
  "",
1123
1448
  "Details:",
1124
1449
  ...result.details.map((detail) => `- ${detail}`),
@@ -1127,3 +1452,29 @@ export function renderSetupResult(result) {
1127
1452
  "Models: run setup --models to list configured aliases and provider setup guidance without making a model call.",
1128
1453
  ].join("\n");
1129
1454
  }
1455
+ function renderInstallKimiResult(result, report) {
1456
+ if (report.json) {
1457
+ return JSON.stringify({
1458
+ action: "install-kimi",
1459
+ ok: report.ok,
1460
+ version: report.version,
1461
+ downloaded: report.downloaded,
1462
+ binary: report.binary ?? null,
1463
+ current: report.current ?? null,
1464
+ selected_binary: report.selectedBinary ?? null,
1465
+ selected_source: report.selectedSource ?? null,
1466
+ error: report.error ?? null,
1467
+ next_step: result.nextStep,
1468
+ }, null, 2);
1469
+ }
1470
+ return [
1471
+ result.summary,
1472
+ "",
1473
+ `Action: ${result.action}`,
1474
+ "",
1475
+ "Details:",
1476
+ ...result.details.map((detail) => `- ${detail}`),
1477
+ "",
1478
+ `Next step: ${result.nextStep}`,
1479
+ ].join("\n");
1480
+ }