kimi-plugin-cc 3.0.0 → 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 (281) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -14
  3. package/README.md +428 -572
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +4 -2
  7. package/dist/cli-client.js +105 -66
  8. package/dist/commands/ask.js +27 -12
  9. package/dist/commands/cancel.js +4 -13
  10. package/dist/commands/cli-helpers.js +1 -1
  11. package/dist/commands/pursue.js +3 -2
  12. package/dist/commands/registry.js +7 -26
  13. package/dist/commands/repair-sessions.js +7 -4
  14. package/dist/commands/replay.js +4 -3
  15. package/dist/commands/rescue.js +17 -5
  16. package/dist/commands/review.js +18 -5
  17. package/dist/commands/setup.js +277 -262
  18. package/dist/commands/swarm.js +20 -7
  19. package/dist/companion.js +142 -18
  20. package/dist/help.js +11 -7
  21. package/dist/hook-escape.js +7 -16
  22. package/dist/hooks/approval-hook.js +1762 -124
  23. package/dist/hooks/approval-policy.js +15 -10
  24. package/dist/hooks/config-safety.js +15 -24
  25. package/dist/hooks/hook-timing.js +1 -1
  26. package/dist/hooks/install-paths.js +179 -107
  27. package/dist/hooks/install.js +44 -166
  28. package/dist/hooks/managed-block.js +44 -95
  29. package/dist/job-store.js +117 -49
  30. package/dist/jobs.js +53 -1
  31. package/dist/kimi-engine.js +68 -92
  32. package/dist/kimi-errors.js +1 -1
  33. package/dist/kimi-journal.js +3 -2
  34. package/dist/kimi-releases.js +28 -49
  35. package/dist/kimi-timeouts.js +1 -15
  36. package/dist/kimi-version-probe.js +24 -72
  37. package/dist/logging.js +12 -7
  38. package/dist/mcp/binding.js +13 -4
  39. package/dist/mcp/job-control.js +386 -89
  40. package/dist/mcp/launcher.js +1 -1
  41. package/dist/mcp/operations.js +387 -193
  42. package/dist/mcp/protocol.js +116 -27
  43. package/dist/mcp/skills.js +130 -0
  44. package/dist/mcp/stdio.js +15 -2
  45. package/dist/native-v2-preflight.js +127 -35
  46. package/dist/parsing.js +45 -11
  47. package/dist/paths.js +20 -10
  48. package/dist/plugin-data.js +28 -83
  49. package/dist/read-scope.js +2 -2
  50. package/dist/render.js +13 -38
  51. package/dist/session-references.js +216 -0
  52. package/dist/session-title.js +1 -1
  53. package/dist/surface-routing.js +92 -5
  54. package/dist/swarm-activation.js +26 -137
  55. package/dist/version.js +1 -1
  56. package/docs/migration.md +45 -227
  57. package/docs/models.md +24 -66
  58. package/docs/safety.md +195 -400
  59. package/docs/session-visibility.md +24 -14
  60. package/docs/swarm-recovery.md +26 -20
  61. package/dsh/index.json +54 -0
  62. package/mcp_config.json +10 -0
  63. package/package.json +23 -82
  64. package/plugin.json +19 -0
  65. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  66. package/plugins/kimi-codex/.mcp.json +2 -3
  67. package/plugins/kimi-codex/dist/background-spawn.js +4 -2
  68. package/plugins/kimi-codex/dist/cli-client.js +105 -66
  69. package/plugins/kimi-codex/dist/commands/ask.js +27 -12
  70. package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
  71. package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
  72. package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
  73. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  74. package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
  75. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  76. package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
  77. package/plugins/kimi-codex/dist/commands/review.js +18 -5
  78. package/plugins/kimi-codex/dist/commands/setup.js +277 -262
  79. package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
  80. package/plugins/kimi-codex/dist/companion.js +142 -18
  81. package/plugins/kimi-codex/dist/help.js +11 -7
  82. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  83. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
  84. package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
  85. package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
  86. package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
  87. package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
  88. package/plugins/kimi-codex/dist/hooks/install.js +44 -166
  89. package/plugins/kimi-codex/dist/hooks/managed-block.js +44 -95
  90. package/plugins/kimi-codex/dist/job-store.js +117 -49
  91. package/plugins/kimi-codex/dist/jobs.js +53 -1
  92. package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
  93. package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
  94. package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
  95. package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
  96. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
  97. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
  98. package/plugins/kimi-codex/dist/logging.js +12 -7
  99. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  100. package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
  101. package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
  102. package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
  103. package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
  104. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  105. package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
  106. package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
  107. package/plugins/kimi-codex/dist/parsing.js +45 -11
  108. package/plugins/kimi-codex/dist/paths.js +20 -10
  109. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  110. package/plugins/kimi-codex/dist/read-scope.js +2 -2
  111. package/plugins/kimi-codex/dist/render.js +13 -38
  112. package/plugins/kimi-codex/dist/session-references.js +216 -0
  113. package/plugins/kimi-codex/dist/session-title.js +1 -1
  114. package/plugins/kimi-codex/dist/surface-routing.js +92 -5
  115. package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
  116. package/plugins/kimi-codex/dist/version.js +1 -1
  117. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  118. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  119. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  120. package/scripts/companion.sh +4 -15
  121. package/skills/kimi/SKILL.md +77 -0
  122. package/skills/kimi/agents/openai.yaml +6 -0
  123. package/CHANGELOG.md +0 -1402
  124. package/agents/kimi-pursue.md +0 -93
  125. package/agents/kimi-review.md +0 -86
  126. package/agents/kimi-swarm.md +0 -88
  127. package/agents/kimi-task.md +0 -93
  128. package/commands/README.md +0 -14
  129. package/commands/cancel.md +0 -17
  130. package/commands/pursue.md +0 -41
  131. package/commands/replay.md +0 -13
  132. package/commands/result.md +0 -13
  133. package/commands/review.md +0 -40
  134. package/commands/setup.md +0 -25
  135. package/commands/status.md +0 -13
  136. package/commands/swarm.md +0 -45
  137. package/commands/task.md +0 -40
  138. package/dist/commands/review-gate.js +0 -391
  139. package/dist/config.js +0 -22
  140. package/dist/dsh/companion.js +0 -177
  141. package/dist/dsh/index.js +0 -167
  142. package/dist/hooks/review-gate-stop.js +0 -19
  143. package/dist/schemas/review-gate-output.js +0 -41
  144. package/docs/registry-releases.md +0 -228
  145. package/docs/upstream-2.4.1-certification.md +0 -54
  146. package/docs/upstream-2.5.0-certification.md +0 -52
  147. package/docs/upstream-2.5.1-certification.md +0 -47
  148. package/docs/upstream-2.5.2-certification.md +0 -40
  149. package/docs/upstream-2.5.3-certification.md +0 -73
  150. package/docs/upstream-2.6.0-certification.md +0 -65
  151. package/docs/upstream-2.6.2-certification.md +0 -144
  152. package/docs/upstream-2.6.3-certification.md +0 -100
  153. package/docs/upstream-2.7.2-certification.md +0 -113
  154. package/docs/upstream-2.7.3-certification.md +0 -95
  155. package/docs/windows-validation.md +0 -39
  156. package/hooks/README.md +0 -9
  157. package/hooks/hooks.json +0 -16
  158. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
  159. package/plugins/kimi-codex/dist/config.js +0 -22
  160. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  161. package/plugins/kimi-codex/dist/dsh/index.js +0 -167
  162. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  163. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  165. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  166. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  167. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  168. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  169. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  170. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  171. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  172. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  173. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
  174. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  175. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
  176. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  177. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  178. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  179. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
  180. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  181. package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
  182. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
  183. package/plugins/kimi-dsh/LICENSE +0 -201
  184. package/plugins/kimi-dsh/README.md +0 -84
  185. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  186. package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
  187. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  188. package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
  189. package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
  190. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
  191. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
  192. package/plugins/kimi-dsh/dist/commands/models.js +0 -139
  193. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
  194. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  195. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  196. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
  197. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  198. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
  199. package/plugins/kimi-dsh/dist/commands/result.js +0 -72
  200. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
  201. package/plugins/kimi-dsh/dist/commands/review.js +0 -217
  202. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
  203. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  204. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
  205. package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
  206. package/plugins/kimi-dsh/dist/companion.js +0 -99
  207. package/plugins/kimi-dsh/dist/config.js +0 -22
  208. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  209. package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
  210. package/plugins/kimi-dsh/dist/errors.js +0 -40
  211. package/plugins/kimi-dsh/dist/git.js +0 -216
  212. package/plugins/kimi-dsh/dist/help.js +0 -43
  213. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  214. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
  215. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
  216. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
  217. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
  218. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  219. package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
  220. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
  221. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  222. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  223. package/plugins/kimi-dsh/dist/job-store.js +0 -631
  224. package/plugins/kimi-dsh/dist/jobs.js +0 -212
  225. package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
  226. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
  227. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
  228. package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
  229. package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
  230. package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
  231. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  232. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
  233. package/plugins/kimi-dsh/dist/logging.js +0 -22
  234. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  235. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
  236. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
  237. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
  238. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
  239. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  240. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
  241. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  242. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  243. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  244. package/plugins/kimi-dsh/dist/model-command.js +0 -34
  245. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
  246. package/plugins/kimi-dsh/dist/package.json +0 -1
  247. package/plugins/kimi-dsh/dist/parsing.js +0 -554
  248. package/plugins/kimi-dsh/dist/paths.js +0 -35
  249. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  250. package/plugins/kimi-dsh/dist/process-tree.js +0 -597
  251. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  252. package/plugins/kimi-dsh/dist/read-scope.js +0 -435
  253. package/plugins/kimi-dsh/dist/render.js +0 -214
  254. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
  255. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
  256. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  257. package/plugins/kimi-dsh/dist/session-title.js +0 -313
  258. package/plugins/kimi-dsh/dist/stream-json.js +0 -344
  259. package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
  260. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
  261. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
  262. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
  263. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  264. package/plugins/kimi-dsh/dist/types.js +0 -1
  265. package/plugins/kimi-dsh/dist/util.js +0 -28
  266. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  267. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  268. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  269. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  270. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  271. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  272. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  273. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  274. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  275. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  276. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  277. package/plugins/kimi-dsh/dist/version.js +0 -7
  278. package/plugins/kimi-dsh/package.json +0 -78
  279. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  280. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  281. package/scripts/review-gate-hook.sh +0 -32
@@ -3,35 +3,23 @@ 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 the Node binary parsed back from that command
11
- // and through `/bin/sh -c` 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],
16
- // --enable-review-gate/--disable-review-gate, and the explicit, network-using
17
- // --install-kimi [--json], which installs the highest certified kimi-code into
18
- // plugin data. Nothing else in setup or any job installs or downloads.
19
- //
20
- // Managed-block splicing is line-based and preserves user bytes outside owned
21
- // 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.
22
12
  import { spawn } from "node:child_process";
23
- import { access, mkdir, lstat, mkdtemp, open, readdir, readFile, readlink, realpath, rename, rm, symlink, unlink, writeFile, } 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";
24
14
  import { constants as fsConstants, existsSync } from "node:fs";
25
15
  import { randomBytes } from "node:crypto";
26
16
  import path from "node:path";
27
- import { readPluginConfig, writePluginConfig } from "../config.js";
28
17
  import { RuntimeError } from "../errors.js";
29
18
  import { HOOK_TIMEOUT_S } from "../hooks/hook-timing.js";
30
- import { olderHostHookWarnings } from "../hooks/install.js";
31
19
  import { normalizeTopLevelInlineHooks, validateKimiHookSetForEnvironment, withKimiConfigLock, } from "../hooks/config-safety.js";
32
- import { buildHookShellCommand, hostIdFromHookCommand, parseHookShellCommand, resolveHookScriptPath, resolveHostId, resolveNodeBinary, } from "../hooks/install-paths.js";
33
- import { decodeManagedCommandLine, describeHookTimeout, effectiveHost, evaluateInstalled, findShortHookTimeout, findUnmanagedApprovalHookBlocks, ORPHAN_MARKER_REMEDY, pairBlocks, parseManagedBlock, } from "../hooks/managed-block.js";
34
- import { formatVersionOutOfRangeWarning, probeKimiVersion, } from "../kimi-version-probe.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";
35
23
  import { inspectPluginOwnedKimi, selectKimiBinary } from "../kimi-command.js";
36
24
  import { isNativeV2CertifiedVersion, NATIVE_V2_ANY_OPERATION_VERSIONS, NATIVE_V2_CERTIFIED_VERSIONS, NATIVE_V2_NON_SWARM_VERSIONS, } from "../kimi-engine.js";
37
25
  import { resolveKimiCodeConfigPath, resolveKimiHome } from "../kimi-home.js";
@@ -57,39 +45,21 @@ export async function runSetup(argv, context) {
57
45
  }
58
46
  const paths = resolvePluginPaths(context.env);
59
47
  await ensurePluginPaths(paths);
60
- // Reconcile the review-gate flag first — it's independent of the
61
- // kimi-code hook and we want the answer reflected in the result even
62
- // if the rest of setup fails.
63
- const existingConfig = await readPluginConfig(paths);
64
- const reviewGateEnabled = parsed.enableReviewGate
65
- ? true
66
- : parsed.disableReviewGate
67
- ? false
68
- : existingConfig.reviewGateEnabled;
69
- if (reviewGateEnabled !== existingConfig.reviewGateEnabled) {
70
- await writePluginConfig(paths, { reviewGateEnabled });
71
- }
72
48
  const configPath = resolveKimiCodeConfigPath(context.env);
73
49
  const hookScriptPath = resolveHookScriptPath(context.env);
74
50
  assertHookPathTomlSafe(hookScriptPath);
75
- // Host id scopes each managed block so Claude Code and Codex can share one
76
- // ~/.kimi-code/config.toml without clobbering each other.
77
- const hostId = resolveHostId(context.env, hookScriptPath);
78
51
  const warnings = [];
79
52
  switch (parsed.mode) {
80
53
  case "uninstall":
81
- return await runUninstall(configPath, hookScriptPath, hostId, parsed.removeAllHosts, reviewGateEnabled, warnings, context);
54
+ return await runUninstall(configPath, hookScriptPath, warnings, context);
82
55
  case "check":
83
- return await runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context);
56
+ return await runCheck(configPath, hookScriptPath, warnings, context);
84
57
  case "install":
85
- return await runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context);
58
+ return await runInstall(paths, configPath, hookScriptPath, warnings, context);
86
59
  }
87
60
  }
88
61
  function parseArgs(argv) {
89
62
  let mode = "install";
90
- let enableReviewGate = false;
91
- let disableReviewGate = false;
92
- let removeAllHosts = false;
93
63
  let installKimi = false;
94
64
  let json = false;
95
65
  for (const token of argv) {
@@ -112,38 +82,149 @@ function parseArgs(argv) {
112
82
  }
113
83
  mode = "uninstall";
114
84
  break;
115
- case "--all":
116
- removeAllHosts = true;
117
- break;
118
- case "--enable-review-gate":
119
- enableReviewGate = true;
120
- break;
121
- case "--disable-review-gate":
122
- disableReviewGate = true;
123
- break;
124
85
  default:
125
86
  throw new RuntimeError("INVALID_ARGS", `Unknown setup flag ${token}. Supported flags: ${SETUP_SUPPORTED_FLAGS}.`, "setup.parse");
126
87
  }
127
88
  }
128
- if (enableReviewGate && disableReviewGate) {
129
- throw new RuntimeError("INVALID_ARGS", "setup accepts either --enable-review-gate or --disable-review-gate, not both.", "setup.parse");
130
- }
131
- if (removeAllHosts && mode !== "uninstall") {
132
- throw new RuntimeError("INVALID_ARGS", "--all is only valid with --uninstall (it removes EVERY host's managed block).", "setup.parse");
133
- }
134
89
  if (installKimi) {
135
90
  if (argv.some((token) => token !== "--install-kimi" && token !== "--json")) {
136
91
  throw new RuntimeError("INVALID_ARGS", "--install-kimi does not combine with other setup flags except --json.", "setup.parse");
137
92
  }
138
- return { mode: "install-kimi", json, enableReviewGate, disableReviewGate, removeAllHosts };
93
+ return { mode: "install-kimi", json };
139
94
  }
140
95
  if (json) {
141
96
  throw new RuntimeError("INVALID_ARGS", "--json is only valid with --install-kimi or --models.", "setup.parse");
142
97
  }
143
- return { mode, json, enableReviewGate, disableReviewGate, removeAllHosts };
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 } });
122
+ }
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 } });
125
+ }
126
+ }
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
+ }
144
223
  }
145
- async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context) {
146
- await assertHookScriptExists(hookScriptPath);
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
+ }
147
228
  const mutation = await withKimiConfigLock(configPath, async () => {
148
229
  const original = await readConfigSafe(configPath);
149
230
  const lineEnding = detectLineEnding(original);
@@ -167,66 +248,66 @@ async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled,
167
248
  }
168
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.`);
169
250
  }
170
- // Prune only this host's orphaned marker-less entries before computing
171
- // splice line numbers. Another host's marker-less table may be its live hook
172
- // after a config rewrite strips comments, so it must remain untouched.
173
251
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
174
252
  const shortBefore = findShortHookTimeout(inlineHooks.contents, expectedCommand);
175
- const { pruned, count: prunedCount, commands: prunedCommands } = pruneOrphanApprovalHooks(inlineHooks.contents, hostId, expectedCommand);
253
+ const { pruned, count: prunedCount, commands: prunedCommands } = pruneOrphanApprovalHooks(inlineHooks.contents, expectedCommand);
176
254
  const existing = pruned;
177
255
  if (prunedCount > 0) {
178
256
  const readorned = prunedCommands.includes(expectedCommand);
179
257
  warnings.push(readorned
180
258
  ? shortBefore === null
181
- ? `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.`
182
- : `Re-adorned this host's managed-block markers: replaced the bare hook table with a freshly marked block (${prunedCount} table(s) refreshed).`
183
- : `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.`);
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.`);
184
262
  }
185
- const { state, blocks } = parseManagedBlock(existing, hostId);
263
+ const { state, blocks } = parseManagedBlock(existing);
186
264
  if (state.kind === "orphan") {
187
265
  throw new RuntimeError("SETUP_ORPHAN_MARKERS", [
188
266
  `kimi-code config at ${configPath} contains an orphaned ${state.detail} marker.`,
189
267
  "Inspect the managed marker comments and re-run setup.",
190
268
  ].join(" "), "setup.install", { details: { configPath, orphan: state.detail } });
191
269
  }
270
+ assertManagedBlocksSafeToReplace(existing, blocks, configPath, "setup.install");
271
+ const block = buildManagedBlock(expectedCommand, lineEnding);
272
+ let next;
192
273
  if (state.kind === "duplicate") {
193
- throw new RuntimeError("SETUP_DUPLICATE_BLOCKS", [
194
- `kimi-code config at ${configPath} contains ${state.beginLines.length} kimi-plugin-cc managed blocks for host ${hostId} (lines ${state.beginLines
195
- .map((line) => line + 1)
196
- .join(", ")}).`,
197
- "This usually means two /kimi:setup runs raced. Run `/kimi:setup --uninstall` to clear them, then `/kimi:setup` again.",
198
- ].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);
285
+ }
286
+ else if (state.kind === "found") {
287
+ next = spliceBlock(existing, state.beginLine, state.endLine, block, lineEnding);
199
288
  }
200
- // Non-blocking note: other hosts (e.g. Codex) manage their own block in the
201
- // same shared config — surface so an operator understands the coexistence.
202
- const otherHosts = [
203
- ...new Set(blocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
204
- ];
205
- if (otherHosts.length > 0) {
206
- warnings.push(`Other host(s) also manage a block in this shared config: ${otherHosts.join(", ")}. ` +
207
- `They are left untouched — each host owns its own PreToolUse block.`);
289
+ else {
290
+ next = appendBlock(existing, block, lineEnding);
208
291
  }
209
- const block = buildManagedBlock(expectedCommand, lineEnding, hostId);
210
- const next = state.kind === "found"
211
- ? spliceBlock(existing, state.beginLine, state.endLine, block, lineEnding)
212
- : insertBlockNearManagedBlocks(existing, blocks, block, lineEnding);
213
292
  await assertKimiHookSetValid(next, configPath, "setup.install", context.env);
214
- // Setup rewrites only its own block and prunable tables. Any other copy of
215
- // this command (e.g. one with a matcher) can be the entry kimi-code runs.
216
293
  const shortAfter = findShortHookTimeout(next, expectedCommand);
217
294
  if (shortAfter !== null) {
218
- throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `kimi-code config at ${configPath} has another [[hooks]] entry with this host's 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 /kimi:setup; the existing config was left unchanged.`, "setup.install", { details: { configPath, timeout: describeHookTimeout(shortAfter.timeout) } });
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) } });
219
296
  }
220
297
  if (shortBefore !== null) {
221
- warnings.push(`Rewrote this host's 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.`);
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.`);
222
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);
223
305
  const blockWritten = next !== original;
224
306
  if (blockWritten)
225
307
  await writeConfigAtomic(configPath, next);
226
308
  return { blockWritten, next, expectedCommand };
227
309
  });
228
310
  const { blockWritten, next, expectedCommand } = mutation;
229
- warnings.push(...await olderHostHookWarnings(next, hostId, expectedCommand));
230
311
  collectPermissionRuleWarnings(next, warnings);
231
312
  const kimiBinary = describeKimiBinary(context.env, warnings);
232
313
  await collectKimiVersionWarnings(context.env, warnings);
@@ -247,22 +328,19 @@ async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled,
247
328
  probe: probe.ok ? "ok" : "failed",
248
329
  probeError: probe.ok ? undefined : probe.reason,
249
330
  warnings,
250
- reviewGateEnabled,
251
331
  nextStep: probe.ok
252
- ? "Run /kimi:task, /kimi:review, /kimi:pursue or /kimi:swarm. Codex users can invoke the matching $kimi-* skills."
253
- : "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.",
254
334
  details: buildDetails({
255
335
  configPath,
256
336
  hookScriptPath,
257
- reviewGateEnabled,
258
337
  probe,
259
338
  warnings,
260
- hostId,
261
339
  kimiBinary,
262
340
  }),
263
341
  };
264
342
  }
265
- async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context) {
343
+ async function runCheck(configPath, hookScriptPath, warnings, context) {
266
344
  const failedCheck = (result) => ({
267
345
  action: "check",
268
346
  summary: result.summary,
@@ -273,15 +351,12 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
273
351
  probe: "failed",
274
352
  probeError: result.reason,
275
353
  warnings,
276
- reviewGateEnabled,
277
354
  nextStep: result.nextStep,
278
355
  details: buildDetails({
279
356
  configPath,
280
357
  hookScriptPath,
281
- reviewGateEnabled,
282
358
  probe: { ok: false, reason: result.detailReason ?? result.reason },
283
359
  warnings,
284
- hostId: result.hostId,
285
360
  kimiBinary,
286
361
  }),
287
362
  });
@@ -293,49 +368,17 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
293
368
  return failedCheck({
294
369
  summary: `kimi-code hook configuration is invalid; the configured hooks array will not load.`,
295
370
  reason: hookSet.reason ?? "configured hooks failed validation",
296
- nextStep: "Repair or remove the invalid [[hooks]] entry named above, then run /kimi:setup --check again. No model call is required.",
297
- hostId,
371
+ nextStep: "Repair or remove the invalid [[hooks]] entry named above, then run setup --check again. No model call is required.",
298
372
  });
299
373
  }
300
374
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
301
- // nodeExists refines mismatch prose into drift classification; hostId checks
302
- // only this host's block in the shared config.
303
375
  const installedCheck = evaluateInstalled(existing, expectedCommand, {
304
- hostId,
305
376
  nodeExists: (binPath) => existsSync(binPath),
306
377
  });
307
- // Non-blocking coexistence + cruft notices.
308
- const { blocks: allBlocks, foreignOrphans } = parseManagedBlock(existing, hostId);
309
- for (const orphan of foreignOrphans) {
310
- 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}`);
311
- }
312
- const otherHosts = [
313
- ...new Set(allBlocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
314
- ];
315
- if (otherHosts.length > 0) {
316
- warnings.push(`Other host(s) also manage a block in this shared config: ${otherHosts.join(", ")} (coexisting, untouched).`);
317
- }
318
- warnings.push(...await olderHostHookWarnings(existing, hostId, expectedCommand));
319
- // Config rewrites can strip markers while leaving each host's table enforcing.
320
- // Our exact-command table is live; our stale table is prunable; another host's
321
- // table is reported but left strictly alone.
322
378
  const bareTables = findUnmanagedApprovalHookBlocks(existing);
323
- const ownStale = bareTables.filter((t) => hostIdFromHookCommand(t.command) === hostId && t.command !== expectedCommand);
324
- const foreignHosts = [
325
- ...new Set(bareTables
326
- // Exact current command bytes identify this host even when a host-id
327
- // override disagrees with the path-derived host.
328
- .filter((t) => t.command !== expectedCommand)
329
- .map((t) => hostIdFromHookCommand(t.command))
330
- .filter((h) => h !== null && h !== hostId)),
331
- ];
332
- if (ownStale.length > 0) {
333
- warnings.push(`Found ${ownStale.length} stale marker-less kimi-plugin-cc hook block(s) from this host's earlier installs. ` +
334
- `Run /kimi:setup to refresh, or /kimi:setup --uninstall --all to clear everything.`);
335
- }
336
- for (const host of foreignHosts) {
337
- warnings.push(`Host "${host}" has a marker-less kimi-plugin-cc hook block (kimi-code config rewrites strip comments). ` +
338
- `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.`);
339
382
  }
340
383
  if (installedCheck.installed && installedCheck.note !== undefined) {
341
384
  warnings.push(`Note: ${installedCheck.note}`);
@@ -350,19 +393,38 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
350
393
  reason: installedCheck.reason ?? "managed block missing or invalid",
351
394
  detailReason: installedCheck.reason ?? "block missing/invalid",
352
395
  nextStep: installedCheck.timeoutTooShort === true
353
- ? "Run /kimi:setup (without --check) to rewrite the hook timeout."
396
+ ? "Run setup (without --check) to rewrite the hook timeout."
354
397
  : installedCheck.state.kind === "absent"
355
- ? "Run /kimi:setup (without --check) to install the managed block."
398
+ ? "Run setup (without --check) to install the managed block."
356
399
  : installedCheck.state.kind === "orphan"
357
400
  ? ORPHAN_MARKER_REMEDY
358
- : "Run /kimi:setup --uninstall, then /kimi:setup to repair.",
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.",
359
405
  });
360
406
  }
361
407
  collectPermissionRuleWarnings(existing, warnings);
362
408
  await collectKimiVersionWarnings(context.env, warnings);
363
409
  await collectInstalledKimiPluginsNotice(context.env, warnings);
364
- // Block is structurally valid AND points at the resolved hook
365
- // 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
+ }
366
428
  try {
367
429
  await assertHookScriptExists(hookScriptPath);
368
430
  }
@@ -370,7 +432,7 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
370
432
  return failedCheck({
371
433
  summary: `Managed block references ${hookScriptPath} but that path is unreadable.`,
372
434
  reason: err instanceof Error ? err.message : String(err),
373
- nextStep: "Reinstall the plugin so dist/hooks/approval-hook.js is present, or run /kimi:setup to refresh the managed block.",
435
+ nextStep: "Run setup (without --check) to republish the hook script and refresh the managed block.",
374
436
  });
375
437
  }
376
438
  const probe = await probeHook(hookScriptPath, expectedCommand, context.env);
@@ -386,26 +448,21 @@ async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, w
386
448
  probe: probe.ok ? "ok" : "failed",
387
449
  probeError: probe.ok ? undefined : probe.reason,
388
450
  warnings,
389
- reviewGateEnabled,
390
451
  nextStep: !probe.ok
391
- ? "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."
392
453
  : installedCheck.via === "bare-table"
393
- // Enforcement remains active through the marker-less table, but recommend
394
- // re-adorning rather than claiming no action is needed.
395
- ? "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."
396
455
  : "No action needed.",
397
456
  details: buildDetails({
398
457
  configPath,
399
458
  hookScriptPath,
400
- reviewGateEnabled,
401
459
  probe,
402
460
  warnings,
403
- hostId,
404
461
  kimiBinary,
405
462
  }),
406
463
  };
407
464
  }
408
- async function runUninstall(configPath, hookScriptPath, hostId, removeAllHosts, reviewGateEnabled, warnings, context) {
465
+ async function runUninstall(configPath, hookScriptPath, warnings, context) {
409
466
  return await withKimiConfigLock(configPath, async () => {
410
467
  const existing = await readConfigSafe(configPath);
411
468
  if (existing.length === 0) {
@@ -418,29 +475,38 @@ async function runUninstall(configPath, hookScriptPath, hostId, removeAllHosts,
418
475
  blockRemoved: false,
419
476
  probe: "skipped",
420
477
  warnings,
421
- reviewGateEnabled,
422
- nextStep: "Run /kimi:setup to install the managed block again.",
478
+ nextStep: "Run setup to install the managed block again.",
423
479
  details: buildDetails({
424
480
  configPath,
425
481
  hookScriptPath,
426
- reviewGateEnabled,
427
482
  probe: { ok: true, reason: "no-op (config absent)" },
428
483
  warnings,
429
484
  }),
430
485
  };
431
486
  }
432
- // Scoped uninstall removes only this host's marked and marker-less blocks;
433
- // other hosts' blocks and live marker-less tables remain intact. `--all` is
434
- // the explicit every-host sweep for all of this plugin's hook tables.
435
- const { stripped: strippedMarkers, removedBlocks, orphansLeft } = stripManagedBlocks(existing, hostId, removeAllHosts);
436
- // Exact current command bytes also identify this host's table when a host-id
437
- // override disagrees with path derivation or a dev path is outside the strict
438
- // ownership pattern.
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);
439
496
  const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
440
- const { pruned: stripped, count: prunedCount } = pruneOrphanApprovalHooks(strippedMarkers, removeAllHosts ? undefined : hostId, expectedCommand);
441
- const changed = stripped !== existing;
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;
442
505
  if (changed) {
443
- await writeConfigAtomic(configPath, stripped);
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);
444
510
  }
445
511
  if (orphansLeft.length > 0) {
446
512
  warnings.push(`Detected ${orphansLeft.length} orphan marker line(s) at ${orphansLeft
@@ -450,14 +516,6 @@ async function runUninstall(configPath, hookScriptPath, hostId, removeAllHosts,
450
516
  if (prunedCount > 0) {
451
517
  warnings.push(`Pruned ${prunedCount} orphaned kimi-plugin-cc hook block(s) with no managed marker.`);
452
518
  }
453
- const { blocks: remainingBlocks } = parseManagedBlock(stripped, hostId);
454
- const remainingHosts = [
455
- ...new Set(remainingBlocks.map((b) => effectiveHost(b, hostId))),
456
- ];
457
- if (!removeAllHosts && remainingHosts.length > 0) {
458
- warnings.push(`Left ${remainingHosts.length} other host block(s) in place: ${remainingHosts.join(", ")}. ` +
459
- `Use \`/kimi:setup --uninstall --all\` to remove every host's block.`);
460
- }
461
519
  return {
462
520
  action: "uninstall",
463
521
  summary: changed
@@ -469,14 +527,12 @@ async function runUninstall(configPath, hookScriptPath, hostId, removeAllHosts,
469
527
  blockRemoved: changed,
470
528
  probe: "skipped",
471
529
  warnings,
472
- reviewGateEnabled,
473
530
  nextStep: changed
474
- ? "Run /kimi:setup again to reinstall the hook, or leave the plugin uninstalled."
475
- : "Run /kimi:setup to install the hook.",
531
+ ? "Run setup again to reinstall the hook, or leave the plugin uninstalled."
532
+ : "Run setup to install the hook.",
476
533
  details: buildDetails({
477
534
  configPath,
478
535
  hookScriptPath,
479
- reviewGateEnabled,
480
536
  probe: { ok: true, reason: changed ? `removed ${removedBlocks} block(s)` : "no-op (no markers)" },
481
537
  warnings,
482
538
  }),
@@ -494,39 +550,28 @@ async function readConfigSafe(configPath) {
494
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 } });
495
551
  }
496
552
  }
497
- async function writeConfigAtomic(configPath, contents) {
498
- // Write a unique sibling temp file and atomically rename it. O_EXCL prevents
499
- // concurrent operations from sharing an intermediate path.
500
- //
501
- // Pass 0o600 at creation, not in a later chmod: the config can contain
502
- // credentials, so the temp file must never exist with a wider umask-derived
503
- // mode.
504
- await mkdir(path.dirname(configPath), { recursive: true });
553
+ async function writeFileAtomic(targetPath, contents, mode) {
554
+ await mkdir(path.dirname(targetPath), { recursive: true });
505
555
  const suffix = randomBytes(8).toString("hex");
506
- const tmpPath = `${configPath}.kimi-plugin-cc.${process.pid}.${suffix}.tmp`;
556
+ const tmpPath = `${targetPath}.kimi-plugin-cc.${process.pid}.${suffix}.tmp`;
507
557
  const openFlags = fsConstants.O_WRONLY |
508
558
  fsConstants.O_CREAT |
509
559
  fsConstants.O_EXCL |
510
560
  (fsConstants.O_NOFOLLOW ?? 0);
511
561
  try {
512
- const handle = await open(tmpPath, openFlags, 0o600);
562
+ const handle = await open(tmpPath, openFlags, mode);
513
563
  try {
514
564
  if (process.platform !== "win32") {
515
- // Windows file modes are emulated; skip the chmod to avoid
516
- // platform-specific noise. The threat model excludes Windows.
517
- // Belt-and-suspenders alongside the create-time mode above,
518
- // matching createPrivateLockFile's pattern.
519
- await handle.chmod(0o600);
565
+ await handle.chmod(mode);
520
566
  }
521
567
  await handle.writeFile(contents, "utf8");
522
568
  }
523
569
  finally {
524
570
  await handle.close();
525
571
  }
526
- await rename(tmpPath, configPath);
572
+ await rename(tmpPath, targetPath);
527
573
  }
528
574
  catch (err) {
529
- // Best-effort cleanup so stale tmp files don't accumulate.
530
575
  try {
531
576
  await unlink(tmpPath);
532
577
  }
@@ -536,11 +581,15 @@ async function writeConfigAtomic(configPath, contents) {
536
581
  throw err;
537
582
  }
538
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
+ }
539
588
  async function assertKimiHookSetValid(contents, configPath, stage, env) {
540
589
  const validation = await validateKimiHookSetForEnvironment(contents, env);
541
590
  if (validation.valid)
542
591
  return;
543
- 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, {
544
593
  details: {
545
594
  configPath,
546
595
  hookEntry: validation.entry,
@@ -631,44 +680,28 @@ function removeOrphanMarkers(contents) {
631
680
  ? { contents, count: 0 }
632
681
  : { contents: removeLines(contents, remove), count: remove.size };
633
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);
694
+ }
634
695
  /**
635
- * Remove managed blocks owned by `currentHost`, or every host with `removeAll`.
636
- * Ownership comes from the marker suffix or a legacy command's derived host.
637
- * Orphan markers are removed individually so surrounding user content survives.
696
+ * Remove all managed blocks and orphan markers while preserving surrounding content.
638
697
  */
639
- function stripManagedBlocks(contents, currentHost, removeAll) {
698
+ function stripManagedBlocks(contents) {
640
699
  const lines = splitPreservingEnding(contents);
641
700
  const { blocks, orphans } = pairBlocks(lines);
642
- // Suffixed blocks belong only to the matching host. Complete legacy blocks
643
- // use their command-derived host; an unattributable non-canonical command is
644
- // ambiguous and only --all removes it. Orphan marker lines have no command
645
- // and can be swept individually by a scoped uninstall.
646
- const shouldRemove = (markerHost, commandPath, isOrphanMarker) => {
647
- if (removeAll)
648
- return true;
649
- if (markerHost !== null)
650
- return markerHost === currentHost;
651
- if (isOrphanMarker)
652
- return true;
653
- const derived = commandPath !== null ? hostIdFromHookCommand(commandPath) : null;
654
- if (derived === null)
655
- return false;
656
- return derived === currentHost;
657
- };
658
- const orphansLeft = orphans
659
- .filter((orphan) => shouldRemove(orphan.hostId, null, true))
660
- .map((orphan) => orphan.line);
701
+ const orphansLeft = orphans.map((orphan) => orphan.line);
661
702
  const remove = new Set(orphansLeft);
662
703
  let removedBlocks = 0;
663
704
  for (const block of blocks) {
664
- // Attribute by the LAST command line in the body, even one after a line
665
- // that makes the block invalid (unlike the validator's commandPath).
666
- let blockCommand = null;
667
- for (const line of lines.slice(block.beginLine + 1, block.endLine)) {
668
- blockCommand = decodeManagedCommandLine(line.trim()) ?? blockCommand;
669
- }
670
- if (!shouldRemove(block.hostId, blockCommand, false))
671
- continue;
672
705
  removedBlocks += 1;
673
706
  for (let i = block.beginLine; i <= block.endLine; i += 1)
674
707
  remove.add(i);
@@ -679,20 +712,12 @@ function removeLines(contents, remove) {
679
712
  return contents.split(/(?<=\n)/).filter((_, index) => !remove.has(index)).join("");
680
713
  }
681
714
  /**
682
- * Remove orphaned, marker-less `[[hooks]]` tables that are unambiguously this
683
- * plugin's approval hook (see `findUnmanagedApprovalHookBlocks`). Returns the
684
- * cleaned text, the count removed, and the decoded commands of the removed
685
- * tables (so install can distinguish "re-adorning this host's live hook after
686
- * a kimi-code comment strip" from "sweeping stale cruft"). A no-op (returns
687
- * the input unchanged) when there is nothing to prune, so callers can compare
688
- * identity cheaply.
689
- *
690
- * `ownedBy` restricts the prune to tables whose command path derives to that
691
- * host — REQUIRED for scoped install/uninstall so one host never disarms the
692
- * 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.
693
718
  */
694
- function pruneOrphanApprovalHooks(contents, ownedBy, alsoMatchCommand) {
695
- const ranges = findUnmanagedApprovalHookBlocks(contents, ownedBy, alsoMatchCommand);
719
+ function pruneOrphanApprovalHooks(contents, alsoMatchCommand) {
720
+ const ranges = findUnmanagedApprovalHookBlocks(contents, alsoMatchCommand);
696
721
  if (ranges.length === 0)
697
722
  return { pruned: contents, count: 0, commands: [] };
698
723
  const remove = new Set();
@@ -709,15 +734,11 @@ function pruneOrphanApprovalHooks(contents, ownedBy, alsoMatchCommand) {
709
734
  };
710
735
  }
711
736
  // ----- Block content -----------------------------------------------------
712
- function buildManagedBlock(shellCommand, lineEnding = "\n", hostId = "") {
737
+ function buildManagedBlock(shellCommand, lineEnding = "\n") {
713
738
  const commandLine = `command = ${tomlBasicString(shellCommand)}`;
714
- const suffix = hostId.length > 0 ? `:${hostId}` : "";
715
739
  return [
716
- `${BEGIN_MARKER_PREFIX}${suffix} (v${KIMI_PLUGIN_CC_VERSION}) ===`,
717
- `# DO NOT EDIT — managed by /kimi:setup. Run /kimi:setup --uninstall to remove.`,
718
- `# Host: ${hostId.length > 0 ? hostId : "(legacy)"} — each host owns a separate block in this shared`,
719
- `# ~/.kimi-code/config.toml. Scoped setup/uninstall preserves other hosts;`,
720
- `# /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.`,
721
742
  `# Purpose:`,
722
743
  `# kimi-code's \`kimi -p\` mode hard-codes permission='auto' and`,
723
744
  `# auto-approves every tool call. This hook enforces each managed command's`,
@@ -734,7 +755,7 @@ function buildManagedBlock(shellCommand, lineEnding = "\n", hostId = "") {
734
755
  `event = "PreToolUse"`,
735
756
  commandLine,
736
757
  `timeout = ${DEFAULT_HOOK_TIMEOUT_S}`,
737
- `# === END kimi-plugin-cc-managed${suffix} ===`,
758
+ `# === END kimi-plugin-cc-managed ===`,
738
759
  ].join(lineEnding);
739
760
  }
740
761
  /**
@@ -957,8 +978,8 @@ async function runInstallKimi(json, context) {
957
978
  `Jobs: ${jobsLine}`,
958
979
  ],
959
980
  nextStep: jobsUseIt
960
- ? "Run /kimi:setup --check to confirm the hook and the selected binary."
961
- : "Unset KIMI_PLUGIN_CC_KIMI_BIN to use the plugin-owned binary, then run /kimi:setup --check.",
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.",
962
983
  report: {
963
984
  ok: true,
964
985
  json,
@@ -1003,7 +1024,6 @@ function installKimiResult(args) {
1003
1024
  probe: args.failed ? "failed" : "skipped",
1004
1025
  probeError: args.probeError,
1005
1026
  warnings: [],
1006
- reviewGateEnabled: false,
1007
1027
  nextStep: args.nextStep,
1008
1028
  details: args.details,
1009
1029
  kimiInstall: args.report,
@@ -1275,13 +1295,11 @@ async function collectKimiVersionWarnings(env, warnings) {
1275
1295
  env,
1276
1296
  });
1277
1297
  if (probe.kind === "failed") {
1278
- // Don't warn about probe failure here — if kimi is genuinely
1279
- // missing/broken, the hook probe path will catch it with a much
1280
- // 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.`);
1281
1299
  return;
1282
1300
  }
1283
- if (!probe.inTestedRange && !isNativeV2CertifiedVersion(probe.version)) {
1284
- 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));
1285
1303
  return;
1286
1304
  }
1287
1305
  if (kimiReleaseHas(probe.version, "bounded-swarm")) {
@@ -1296,7 +1314,7 @@ async function collectKimiVersionWarnings(env, warnings) {
1296
1314
  * Non-blocking notice for kimi-code's own enabled plugins from
1297
1315
  * ~/.kimi-code/plugins/installed.json. Their tools can register on every
1298
1316
  * session, but read-only commands deny everything outside READ_ONLY_TOOLS
1299
- * (Read, Grep, Glob, ReadMediaFile, TaskList, TaskOutput), which can waste model
1317
+ * (Read, Grep, Glob, ReadMediaFile, TaskList, TaskOutput, WaitFor), which can waste model
1300
1318
  * turns. Missing, unreadable, or malformed manifests produce no notice; setup
1301
1319
  * never blocks on or mutates the plugin list.
1302
1320
  */
@@ -1332,10 +1350,10 @@ async function collectInstalledKimiPluginsNotice(env, warnings) {
1332
1350
  warnings.push([
1333
1351
  `NOTE: ${enabledIds.length} kimi-code plugin(s) installed and enabled: ${enabledIds.join(", ")}.`,
1334
1352
  " kimi-code registers their tools (including MCP) on every session. Under kimi-plugin-cc's",
1335
- " read-only commands (/kimi:task, /kimi:review and the review gate) the",
1336
- " 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",
1337
1355
  " are blocked — safe, but they can waste model turns. This is expected; no action needed.",
1338
- " (/kimi:task --write 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",
1339
1357
  " kimi-code plugins you don't need for delegated work in your kimi-code config.",
1340
1358
  ].join("\n"));
1341
1359
  }
@@ -1403,11 +1421,9 @@ function buildDetails(args) {
1403
1421
  const details = [
1404
1422
  `Companion runtime: Node ${process.version}`,
1405
1423
  `Plugin version: ${KIMI_PLUGIN_CC_VERSION}`,
1406
- ...(args.hostId ? [`Host id: ${args.hostId}`] : []),
1407
1424
  ...(args.kimiBinary ? [`Kimi binary: ${args.kimiBinary}`] : []),
1408
1425
  `Config file: ${args.configPath}`,
1409
1426
  `Hook script: ${args.hookScriptPath}`,
1410
- `Review gate: ${args.reviewGateEnabled ? "enabled" : "disabled"}`,
1411
1427
  `Probe: ${args.probe.ok ? "ok" : "failed"} — ${args.probe.reason}`,
1412
1428
  ];
1413
1429
  if (args.warnings.length > 0) {
@@ -1428,7 +1444,6 @@ export function renderSetupResult(result) {
1428
1444
  `Block written: ${result.blockWritten ? "yes" : "no"}`,
1429
1445
  `Block removed: ${result.blockRemoved ? "yes" : "no"}`,
1430
1446
  `Probe: ${result.probe}${result.probeError ? ` (${result.probeError})` : ""}`,
1431
- `Review gate: ${result.reviewGateEnabled ? "enabled" : "disabled"}`,
1432
1447
  "",
1433
1448
  "Details:",
1434
1449
  ...result.details.map((detail) => `- ${detail}`),