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
@@ -1,1078 +0,0 @@
1
- // Subprocess client for `kimi -p --output-format stream-json`.
2
- //
3
- // Per-job env (`KIMI_PLUGIN_CC_CMD`) is set on this spawn so the
4
- // PreToolUse hook can branch per command (review vs rescue vs ask). It is
5
- // passed via the spawn `env` option, not exported to a shell, so concurrent
6
- // jobs never share an env block.
7
- import { spawn } from "node:child_process";
8
- import { appendFile, mkdir } from "node:fs/promises";
9
- import path from "node:path";
10
- import { assertPromptFitsCommandLine } from "./prompt-size.js";
11
- import { createHookEscapeMonitor } from "./hook-escape.js";
12
- import { RuntimeError, formatError } from "./errors.js";
13
- import { assertNoUnsafeExperimentalSelector, assertExecutionPlanMatchesSpawn, } from "./kimi-engine.js";
14
- import { assertPrefixArgsSafe } from "./kimi-command.js";
15
- import { resolveKimiHome } from "./kimi-home.js";
16
- import { assertNativeV2Preflight } from "./native-v2-preflight.js";
17
- import { parseVersionLine } from "./kimi-version-probe.js";
18
- import { BOUNDED_SWARM_POLICY, SWARM_CHILD_TIMEOUT_MS, SWARM_POLICY_ENV, SWARM_WAVE_SIZE_ENV, usesBoundedSwarmPolicy, } from "./swarm-policy.js";
19
- import { StreamJsonParser, extractSessionIdFromStderr, } from "./stream-json.js";
20
- import { collectDescendantIdentities, collectDescendantIdentitiesForRoots, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
21
- /** Bytes of stderr retained for diagnostics on completion. Rolling buffer. */
22
- const STDERR_TAIL_BYTES = 8192;
23
- /** Hard cap on awaiting diagnostics log drain before resolving the result. */
24
- const LOG_DRAIN_TIMEOUT_MS = 250;
25
- /** Default 1500 ms delay between SIGTERM and SIGKILL after an abort. */
26
- const DEFAULT_ESCALATION_MS = 1_500;
27
- /** Maximum time spent confirming POSIX tree exit after SIGKILL dispatch. */
28
- const POST_KILL_QUIESCENCE_MS = 500;
29
- /** Hard bound for the one-shot descendant identity snapshot. */
30
- const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000;
31
- /** Hard bound for each batched identity revalidation pass. */
32
- const IDENTITY_REVALIDATION_TIMEOUT_MS = 250;
33
- /** Keep ownership evidence before a native Bash shell can exit ahead of its children. */
34
- const BOUNDED_DESCENDANT_POLL_MS = 100;
35
- const DESCENDANT_SNAPSHOT_TIMEOUT = Symbol("descendant-snapshot-timeout");
36
- function spawnErrorDetails(error) {
37
- const cause = error;
38
- return {
39
- spawn_code: cause?.code,
40
- spawn_errno: cause?.errno,
41
- spawn_message: formatError(error),
42
- };
43
- }
44
- export async function runCliPrompt(opts) {
45
- // Pre-aborted signal: refuse to spawn at all.
46
- if (opts.signal?.aborted === true) {
47
- throw new RuntimeError("CLI_ABORTED", "kimi subprocess request cancelled before spawn", "cli-client.pre-spawn", { details: { command: opts.command } });
48
- }
49
- assertExecutionPlanMatchesSpawn(opts.executionPlan, opts.command, opts.prefixArgs ?? [], opts.env);
50
- if ((opts.commandLabel === "rescue" || opts.commandLabel === "swarm-write") &&
51
- !opts.trustedWorkspaceRoot) {
52
- throw new RuntimeError("CLI_TRUSTED_WORKSPACE_ROOT_MISSING", `Refusing ${opts.commandLabel}: write-capable plugin launches require a plugin-owned trusted workspace root.`, "cli-client.pre-spawn", { details: { command_label: opts.commandLabel } });
53
- }
54
- // The master experimental flag enables v2-only features (tower, subagent
55
- // fork) outside the certified no-plan profile. Refuse it at the final
56
- // boundary too, in case the environment changed after plan creation.
57
- assertNoUnsafeExperimentalSelector(opts.env, "cli-client.pre-spawn");
58
- // Validate the ACTUAL prefix argv used for this spawn — not only the
59
- // env-resolved value — so a forged/corrupt persisted plan cannot smuggle a
60
- // reserved kimi flag (e.g. `-r <session>`, which would resume a session the
61
- // v2 preflight never scanned for plan taint).
62
- assertPrefixArgsSafe(opts.prefixArgs ?? []);
63
- if (opts.executionPlan.intendedEngine === "native-v2") {
64
- // Re-run the cheap no-plan preconditions at the final boundary: the
65
- // operator's config.toml and the resume journal are mutable between plan
66
- // creation (possibly in another process) and this spawn.
67
- await assertNativeV2Preflight({
68
- kimiHome: resolveKimiHome(opts.env, opts.cwd),
69
- env: opts.env,
70
- resumeSessionId: opts.resumeSessionId,
71
- expectedExecutionRoot: opts.trustedWorkspaceRoot ?? opts.cwd,
72
- stage: "cli-client.spawn",
73
- });
74
- }
75
- const args = buildArgs(opts);
76
- assertPromptFitsCommandLine(opts.command, args);
77
- const env = buildKimiCliEnvironment(opts);
78
- const boundedSwarm = usesBoundedSwarmPolicy(opts.executionPlan);
79
- if (opts.logPath !== undefined) {
80
- await mkdir(path.dirname(opts.logPath), { recursive: true }).catch(() => {
81
- // Best-effort; if mkdir fails the appendFile below will error and be
82
- // swallowed by the log chain (diagnostics are non-blocking).
83
- });
84
- }
85
- let child;
86
- let spawnedAt;
87
- try {
88
- spawnedAt = Date.now();
89
- child = spawn(opts.command, args, {
90
- cwd: opts.cwd,
91
- env,
92
- stdio: "pipe",
93
- // POSIX gets a fresh process group so cancellation reaches kimi's
94
- // descendants; Windows has no negative-pid process-group signaling.
95
- detached: process.platform !== "win32",
96
- });
97
- }
98
- catch (err) {
99
- throw new RuntimeError("CLI_SPAWN_FAILED", `Failed to spawn kimi: ${formatError(err)}`, "cli-client.spawn", err instanceof Error
100
- ? { cause: err, details: { command: opts.command, args, ...spawnErrorDetails(err) } }
101
- : { details: { command: opts.command, args, ...spawnErrorDetails(err) } });
102
- }
103
- // Pre-attach an 'error' listener immediately. Bun (and Node) can emit
104
- // 'error' asynchronously between spawn returning and our Promise body
105
- // attaching the real listener — without a handler in place, EventEmitter
106
- // crashes the process. Capture into an array (not a single slot) so two
107
- // back-to-back errors don't lose the first; we replay the first one when
108
- // the real handler installs. The replacement is atomic across two
109
- // synchronous statements (flag-flip + .on attach), so no async work can
110
- // interleave between them.
111
- const earlyErrors = [];
112
- let earlyErrorHandled = false;
113
- child.on("error", function earlyErrorListener(err) {
114
- if (earlyErrorHandled)
115
- return;
116
- earlyErrors.push(err);
117
- });
118
- const parser = new StreamJsonParser();
119
- const records = [];
120
- const malformed = [];
121
- // Rolling stderr tail — keep only the trailing STDERR_TAIL_BYTES so a
122
- // long-running kimi process emitting megabytes of stderr (tool.updated
123
- // output/status, thinking deltas) doesn't grow our RSS unboundedly.
124
- let stderrTail = "";
125
- let announcedSessionId;
126
- let announcedGoalSummary;
127
- let announcedCliError;
128
- let announcedSystemVersion;
129
- const hookMonitor = createHookEscapeMonitor({ commandLabel: opts.commandLabel,
130
- operationKind: opts.executionPlan.operationKind, trustedWorkspaceRoot: opts.trustedWorkspaceRoot, cwd: opts.cwd,
131
- swarmPolicy: env[SWARM_POLICY_ENV], swarmWaveSize: env[SWARM_WAVE_SIZE_ENV] });
132
- const hookEscapes = [];
133
- const noteHookEscape = (escape) => {
134
- hookEscapes.push(escape);
135
- appendLogLine({ event: "hook_escape", ...escape, command_label: opts.commandLabel,
136
- operation_kind: opts.executionPlan.operationKind });
137
- };
138
- let engineMismatchDetected = false;
139
- let handleEngineMismatch;
140
- const plannedEngine = opts.executionPlan.intendedEngine;
141
- const plannedVersion = opts.executionPlan.kimiVersion === null
142
- ? null
143
- : (parseVersionLine(opts.executionPlan.kimiVersion)?.raw ?? opts.executionPlan.kimiVersion);
144
- let logChain = Promise.resolve();
145
- const appendLogLine = (payload) => {
146
- if (opts.logPath === undefined)
147
- return;
148
- const line = `${JSON.stringify({ ts: new Date().toISOString(), ...payload })}\n`;
149
- logChain = logChain.then(() => appendFile(opts.logPath, line, "utf8").catch(() => {
150
- // Diagnostics best-effort; never crash on log failure.
151
- }));
152
- };
153
- appendLogLine({
154
- event: "spawn",
155
- command: opts.command,
156
- args,
157
- cwd: opts.cwd,
158
- command_label: opts.commandLabel ?? null,
159
- operation_kind: opts.executionPlan.operationKind,
160
- intended_engine: opts.executionPlan.intendedEngine,
161
- kimi_version: opts.executionPlan.kimiVersion,
162
- plan_certification: opts.executionPlan.certification,
163
- safety_profile: opts.executionPlan.safetyProfile,
164
- swarm_max_concurrency: opts.swarmMaxConcurrency ?? null,
165
- legacy_v1_forced: env.KIMI_CODE_LEGACY_FLAG === KIMI_LEGACY_FORCED_VALUE,
166
- });
167
- const invokeOnRecord = (record) => {
168
- if (opts.onRecord === undefined)
169
- return;
170
- try {
171
- opts.onRecord(record);
172
- }
173
- catch {
174
- // Caller-supplied callback must never destabilize the parse loop.
175
- }
176
- };
177
- // A native-v2 plan must see agent-core-v2's pre-tool system.version marker
178
- // before any consumer-facing output; a legacy plan must never see it.
179
- const requireMarkerBeforeOutput = (what) => {
180
- if (plannedEngine !== "native-v2" || announcedSystemVersion !== undefined)
181
- return false;
182
- handleEngineMismatch?.({
183
- observedEngine: null,
184
- systemVersion: undefined,
185
- reason: `${what} arrived before the native-v2 system.version marker; the engine that started cannot be established.`,
186
- });
187
- return true;
188
- };
189
- const consumeOutcomes = (outcomes) => {
190
- for (const outcome of outcomes) {
191
- if (engineMismatchDetected)
192
- return;
193
- if (outcome.cliError !== undefined) {
194
- if (requireMarkerBeforeOutput("a CLI error record"))
195
- return;
196
- announcedCliError ??= outcome.cliError;
197
- appendLogLine({ event: "cli_error", ...outcome.cliError });
198
- continue;
199
- }
200
- if (outcome.unknownRecord !== undefined) {
201
- // Unknown roles are diagnostic-only and excluded from consumer records;
202
- // native-v2 still refuses any output before its marker.
203
- if (requireMarkerBeforeOutput(`an unknown-role (${outcome.unknownRecord.role}) record`)) {
204
- return;
205
- }
206
- appendLogLine({
207
- event: "unknown_record",
208
- role: outcome.unknownRecord.role,
209
- });
210
- continue;
211
- }
212
- if (outcome.goalSummary !== undefined) {
213
- if (requireMarkerBeforeOutput("goal.summary"))
214
- return;
215
- // Out-of-band metadata; first-announce-wins, excluded from consumer records.
216
- if (announcedGoalSummary === undefined) {
217
- announcedGoalSummary = outcome.goalSummary;
218
- appendLogLine({
219
- event: "goal_summary",
220
- goal_id: outcome.goalSummary.goalId,
221
- status: outcome.goalSummary.status,
222
- turns_used: outcome.goalSummary.turnsUsed,
223
- tokens_used: outcome.goalSummary.tokensUsed,
224
- wall_clock_ms: outcome.goalSummary.wallClockMs,
225
- });
226
- }
227
- continue;
228
- }
229
- if (outcome.record !== undefined) {
230
- // Meta records are out-of-band wrapper metadata, never consumer-facing
231
- // assistant/tool records. Capture session.resume_hint (first-announce
232
- // wins, mirroring the stderr capture below for kimi 0.1.x), and skip
233
- // every recognized meta type, including 0.23.5's turn.step.retrying and
234
- // agent-core-v2's system.version. This keeps records[] and onRecord
235
- // stable while preserving the resume hint as the primary session-id
236
- // source under kimi 0.2.0+.
237
- if (outcome.record.role === "meta") {
238
- // Contract: on a native-v2 plan the system.version marker is the
239
- // FIRST stream-json line. Any other meta (e.g. session.resume_hint)
240
- // arriving before it violates the ordering and means the started
241
- // engine cannot be established — refuse before pinning a session id.
242
- if (outcome.record.type !== "system.version" &&
243
- requireMarkerBeforeOutput(`a ${outcome.record.type} record`)) {
244
- return;
245
- }
246
- if (outcome.record.type === "session.resume_hint" &&
247
- announcedSessionId === undefined) {
248
- announcedSessionId = outcome.record.sessionId;
249
- appendLogLine({
250
- event: "session_announce",
251
- source: "stream-json.meta",
252
- session_id: outcome.record.sessionId,
253
- });
254
- }
255
- else if (outcome.record.type === "system.version" &&
256
- announcedSystemVersion === undefined) {
257
- announcedSystemVersion = outcome.record.version;
258
- appendLogLine({
259
- event: "system_version",
260
- source: "stream-json.meta",
261
- version: outcome.record.version,
262
- });
263
- if (plannedEngine !== "native-v2") {
264
- handleEngineMismatch?.({
265
- observedEngine: "native-v2",
266
- systemVersion: outcome.record.version,
267
- reason: `the pre-tool system.version marker proves native-v2 ${outcome.record.version} started.`,
268
- });
269
- return;
270
- }
271
- // The marker's `version` is a structured field, not a CLI banner:
272
- // require a single well-formed semver token. A multi-line or
273
- // otherwise decorated value must not be normalized into a certified
274
- // one by taking its first line.
275
- const observedVersion = parseExactVersionToken(outcome.record.version);
276
- if (observedVersion === undefined) {
277
- handleEngineMismatch?.({
278
- observedEngine: "native-v2",
279
- systemVersion: outcome.record.version,
280
- reason: `the system.version marker carries a malformed version value ${JSON.stringify(outcome.record.version)}; the started engine's version cannot be established.`,
281
- });
282
- return;
283
- }
284
- if (plannedVersion !== null && observedVersion !== plannedVersion) {
285
- handleEngineMismatch?.({
286
- observedEngine: "native-v2",
287
- systemVersion: outcome.record.version,
288
- reason: `the system.version marker reports ${outcome.record.version}, but the plan certified ${plannedVersion}.`,
289
- });
290
- return;
291
- }
292
- }
293
- continue;
294
- }
295
- if (requireMarkerBeforeOutput(`a ${outcome.record.role} record`))
296
- return;
297
- const escape = hookMonitor.observe(outcome.record);
298
- if (escape)
299
- noteHookEscape(escape);
300
- records.push(outcome.record);
301
- appendLogLine({ event: "record", record: outcome.record });
302
- invokeOnRecord(outcome.record);
303
- }
304
- else if (outcome.malformedLine !== undefined) {
305
- // Diagnostics-only in general, but on a native-v2 plan a line that is
306
- // not the marker arriving first still violates marker-first: the
307
- // engine that produced it cannot be established.
308
- if (requireMarkerBeforeOutput("a malformed stream-json line"))
309
- return;
310
- const entry = {
311
- line: truncateChars(outcome.malformedLine, 200),
312
- reason: outcome.malformedReason ?? "unknown",
313
- };
314
- malformed.push(entry);
315
- appendLogLine({ event: "malformed", ...entry });
316
- }
317
- }
318
- };
319
- const errorDetails = () => ({
320
- command: opts.command,
321
- args,
322
- command_label: opts.commandLabel ?? null,
323
- });
324
- return await new Promise(async (resolve, reject) => {
325
- let aborted = false;
326
- let cancellationTeardown;
327
- let processCleanupUnverified = false;
328
- let settlementStarted = false;
329
- const settle = (kind, payload) => {
330
- if (settlementStarted)
331
- return;
332
- if (boundedSwarm)
333
- beginTeardown();
334
- // Denied calls still without a result (a cancel/budget race, an abnormal
335
- // exit, or a turn that ended without the denial the hook owes) are reported
336
- // alongside the real outcome, never instead of it.
337
- for (const escape of hookMonitor.settle())
338
- noteHookEscape(escape);
339
- if (kind === "resolve" && hookEscapes.length > 0)
340
- payload = { ...payload, hookEscapes: [...hookEscapes] };
341
- settlementStarted = true;
342
- opts.signal?.removeEventListener("abort", onAbort);
343
- // Abort teardown can outlive the direct child's close event while a
344
- // detached descendant is still being enumerated or escalated. Never
345
- // expose a result/error until that one owned teardown path completes.
346
- void (cancellationTeardown ?? Promise.resolve({ ok: true })).then((teardown) => {
347
- if (!teardown.ok) {
348
- const details = {
349
- ...errorDetails(),
350
- ...(boundedSwarm || processCleanupUnverified ? { process_cleanup_unverified: true } : {}),
351
- ...(boundedSwarm && kind === "resolve" ? {
352
- process_exit_code: payload.exitCode,
353
- process_signal: payload.signal,
354
- } : {}),
355
- };
356
- appendLogLine({
357
- event: "cancellation_teardown_error",
358
- message: formatError(teardown.error),
359
- });
360
- reject(new RuntimeError(boundedSwarm ? "CLI_PROCESS_SETTLEMENT_FAILED" : "CLI_CANCELLATION_TEARDOWN_FAILED", `kimi ${boundedSwarm ? "process settlement" : "cancellation teardown"} failed: ${formatError(teardown.error)}`, boundedSwarm ? "cli-client.settlement" : "cli-client.cancellation", teardown.error instanceof Error
361
- ? { cause: teardown.error, details }
362
- : { details }));
363
- return;
364
- }
365
- if (kind === "resolve")
366
- resolve({ ...payload, settledAt: Date.now() });
367
- else
368
- reject(payload);
369
- });
370
- };
371
- const escalationMs = opts.escalationMs ?? DEFAULT_ESCALATION_MS;
372
- const identityReader = opts.processIdentityReader;
373
- let processExited = false;
374
- child.once("exit", () => {
375
- processExited = true;
376
- // A descendant may still hold stdout open. Start cleanup on exit rather
377
- // than waiting for close, which cannot arrive until that tail is gone.
378
- if (boundedSwarm)
379
- beginTeardown();
380
- });
381
- const captureProcessIdentities = async (collect, excludedPid, onFailure) => {
382
- let snapshot;
383
- try {
384
- const collected = await raceWithValueTimeout(collect(), DESCENDANT_SNAPSHOT_TIMEOUT_MS, DESCENDANT_SNAPSHOT_TIMEOUT);
385
- if (collected === DESCENDANT_SNAPSHOT_TIMEOUT) {
386
- appendLogLine({
387
- event: "descendant_collection_timeout",
388
- timeout_ms: DESCENDANT_SNAPSHOT_TIMEOUT_MS,
389
- });
390
- onFailure?.(new Error("descendant ownership snapshot timed out"));
391
- return [];
392
- }
393
- snapshot = collected;
394
- }
395
- catch (err) {
396
- appendLogLine({
397
- event: "descendant_collection_error",
398
- message: formatError(err),
399
- });
400
- onFailure?.(err);
401
- return [];
402
- }
403
- const identities = [];
404
- const seen = new Set();
405
- for (const identity of snapshot) {
406
- const key = `${identity.pid}:${identity.startToken}:${identity.processGroupId}`;
407
- if (Number.isInteger(identity.pid) &&
408
- identity.pid > 0 &&
409
- identity.pid !== excludedPid &&
410
- Number.isInteger(identity.processGroupId) &&
411
- identity.processGroupId > 0 &&
412
- identity.startToken.length > 0 &&
413
- !seen.has(key)) {
414
- seen.add(key);
415
- identities.push({ ...identity });
416
- }
417
- }
418
- return identities;
419
- };
420
- const captureDescendantIdentities = (childPid, expectedRoot, onFailure) => captureProcessIdentities(() => (opts.descendantIdentityCollector ?? collectDescendantIdentities)(childPid, expectedRoot), childPid, onFailure);
421
- const trySignalPid = (pid, signal) => {
422
- try {
423
- process.kill(pid, signal);
424
- }
425
- catch (err) {
426
- const ignored = isErrnoException(err, "ESRCH") || isErrnoException(err, "EPERM");
427
- void ignored;
428
- }
429
- };
430
- const signalCapturedTree = async (childPid, identities, signal) => {
431
- // The live ChildProcess anchors its detached group. Signal the group
432
- // before the direct child can exit and make that numeric PGID stale.
433
- if (!processExited) {
434
- trySignalPid(-childPid, signal);
435
- try {
436
- child.kill(signal);
437
- }
438
- catch {
439
- // Best-effort direct-child signaling; ChildProcess owns this pid.
440
- }
441
- }
442
- // One bounded pass replaces up to 512 sequential ps calls. A pid whose
443
- // start token or PGID changed belongs to another process and is skipped.
444
- const pidValidation = await revalidateProcessIdentities(identities, {
445
- identityReader,
446
- timeoutMs: IDENTITY_REVALIDATION_TIMEOUT_MS,
447
- });
448
- for (const current of pidValidation.identities) {
449
- trySignalPid(current.pid, signal);
450
- }
451
- // Revalidate again immediately before signaling non-root groups. Never
452
- // send to an unanchored numeric PGID left over from collection.
453
- const groupValidation = await revalidateProcessIdentities(identities, {
454
- identityReader,
455
- timeoutMs: IDENTITY_REVALIDATION_TIMEOUT_MS,
456
- });
457
- const activeGroupIds = new Set(groupValidation.identities.map((identity) => identity.processGroupId));
458
- activeGroupIds.delete(childPid);
459
- for (const processGroupId of activeGroupIds) {
460
- trySignalPid(-processGroupId, signal);
461
- }
462
- };
463
- const trackedIdentities = new Map();
464
- const identityKey = (identity) => `${identity.pid}:${identity.startToken}`;
465
- let trackerTimer;
466
- let trackerPass;
467
- let publishedIdentities = "";
468
- let spawnRecorded = opts.onSpawn === undefined;
469
- let observationError;
470
- let checkpointError;
471
- let lastPassComplete = false;
472
- let lastPassCheckpointed = false;
473
- const retainIdentities = (identities) => {
474
- for (const identity of identities) {
475
- // A changed PGID is not a new ownership grant. Keep the first identity
476
- // so revalidation refuses to signal a process that moved groups.
477
- if (!trackedIdentities.has(identityKey(identity))) {
478
- trackedIdentities.set(identityKey(identity), identity);
479
- }
480
- }
481
- };
482
- const refreshTrackedIdentities = () => {
483
- if (trackerPass)
484
- return trackerPass;
485
- trackerPass = (async () => {
486
- lastPassComplete = false;
487
- lastPassCheckpointed = false;
488
- let passError;
489
- const noteFailure = (error) => { passError ??= error; };
490
- const childPid = child.pid;
491
- if (childPid === undefined || process.platform === "win32")
492
- return;
493
- const reachable = !processExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
494
- retainIdentities(reachable);
495
- const reachableKeys = new Set(reachable.map(identityKey));
496
- const validation = await revalidateProcessIdentities([...trackedIdentities.values()], {
497
- identityReader, timeoutMs: IDENTITY_REVALIDATION_TIMEOUT_MS,
498
- });
499
- if (!validation.complete) {
500
- noteFailure(new Error("descendant ownership could not be revalidated"));
501
- }
502
- // Once a shell exits its surviving children are no longer under the
503
- // print root. Reuse their pinned identities as anchors, never bare PIDs.
504
- // Dead anchors provide no discovery evidence. Incomplete validation
505
- // retains earlier identities without multiplying full-table probes.
506
- const orphanedAnchors = validation.complete
507
- ? validation.identities.filter((identity) => !reachableKeys.has(identityKey(identity)))
508
- : [];
509
- const additional = orphanedAnchors.length === 0 ? [] : await captureProcessIdentities(() => (opts.descendantIdentityBatchCollector ?? collectDescendantIdentitiesForRoots)(orphanedAnchors), childPid, noteFailure);
510
- retainIdentities(additional);
511
- if (passError === undefined) {
512
- const liveKeys = new Set([
513
- ...validation.identities, ...(validation.groupChanged ?? []), ...additional,
514
- ].map(identityKey));
515
- for (const key of trackedIdentities.keys()) {
516
- if (!liveKeys.has(key))
517
- trackedIdentities.delete(key);
518
- }
519
- }
520
- // Observation failures describe this pass. A later complete pass can
521
- // recover; incomplete passes retain every earlier ownership identity.
522
- observationError = passError;
523
- lastPassComplete = passError === undefined;
524
- const current = [...trackedIdentities.values()];
525
- const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete]);
526
- // Recovery stores the print root first. Capture starts immediately,
527
- // but descendant publication waits for that durable root checkpoint.
528
- if (spawnRecorded) {
529
- if (signature === publishedIdentities && checkpointError === undefined) {
530
- lastPassCheckpointed = true;
531
- }
532
- else {
533
- try {
534
- await opts.onProcessIdentities?.(current, lastPassComplete);
535
- publishedIdentities = signature;
536
- checkpointError = undefined;
537
- lastPassCheckpointed = true;
538
- }
539
- catch (error) {
540
- checkpointError = error;
541
- }
542
- }
543
- }
544
- })().catch((error) => {
545
- observationError = error;
546
- lastPassComplete = false;
547
- }).finally(() => {
548
- trackerPass = undefined;
549
- });
550
- return trackerPass;
551
- };
552
- const waitForTrackedExit = async (timeoutMs) => {
553
- const deadline = Date.now() + Math.max(0, timeoutMs);
554
- while (true) {
555
- await refreshTrackedIdentities();
556
- if (processExited && trackedIdentities.size === 0 && lastPassComplete && lastPassCheckpointed)
557
- return true;
558
- if (Date.now() >= deadline)
559
- return false;
560
- await new Promise((resolve) => setTimeout(resolve, Math.min(BOUNDED_DESCENDANT_POLL_MS, deadline - Date.now())));
561
- }
562
- };
563
- const teardownBoundedTree = async () => {
564
- const childPid = child.pid;
565
- try {
566
- await opts.cancellationTeardownHook?.();
567
- if (childPid === undefined)
568
- return;
569
- await refreshTrackedIdentities();
570
- await signalCapturedTree(childPid, [...trackedIdentities.values()], "SIGTERM");
571
- let quiescent = await waitForTrackedExit(escalationMs);
572
- if (!quiescent && Number.isFinite(escalationMs)) {
573
- await signalCapturedTree(childPid, [...trackedIdentities.values()], "SIGKILL");
574
- quiescent = await waitForTrackedExit(POST_KILL_QUIESCENCE_MS);
575
- }
576
- if (!quiescent)
577
- throw checkpointError ?? observationError ?? new Error("owned descendants did not reach verified quiescence");
578
- }
579
- finally {
580
- if (trackerTimer)
581
- clearInterval(trackerTimer);
582
- await trackerPass;
583
- }
584
- };
585
- const teardownChildTree = async () => {
586
- if (boundedSwarm && process.platform !== "win32")
587
- return teardownBoundedTree();
588
- await opts.cancellationTeardownHook?.();
589
- const childPid = child.pid;
590
- if (childPid === undefined || processExited)
591
- return;
592
- const finiteEscalation = Number.isFinite(escalationMs);
593
- if (process.platform === "win32") {
594
- // Preserve the documented win32 behavior: only the direct child is
595
- // managed; descendant enumeration/reaping remains unsupported.
596
- try {
597
- child.kill("SIGTERM");
598
- }
599
- catch {
600
- // Best-effort.
601
- }
602
- const exited = await waitForProcessTreeExit([], escalationMs, {
603
- isRootAlive: () => !processExited,
604
- });
605
- if (!exited && finiteEscalation) {
606
- try {
607
- child.kill("SIGKILL");
608
- }
609
- catch {
610
- // Best-effort.
611
- }
612
- }
613
- return;
614
- }
615
- let snapshotFailure;
616
- const identities = await captureDescendantIdentities(childPid, undefined, (error) => {
617
- snapshotFailure ??= { error };
618
- processCleanupUnverified = true;
619
- });
620
- await signalCapturedTree(childPid, identities, "SIGTERM");
621
- // The grace interval starts only after SIGTERM has reached every
622
- // revalidated target. Slow process enumeration never consumes the grace.
623
- const exited = await waitForProcessTreeExit(identities, escalationMs, {
624
- identityReader,
625
- isRootAlive: () => !processExited,
626
- });
627
- if (!exited && finiteEscalation) {
628
- await signalCapturedTree(childPid, identities, "SIGKILL");
629
- const quiescent = await waitForProcessTreeExit(identities, POST_KILL_QUIESCENCE_MS, {
630
- identityReader,
631
- isRootAlive: () => !processExited,
632
- });
633
- if (!quiescent) {
634
- appendLogLine({
635
- event: "post_kill_quiescence_timeout",
636
- timeout_ms: POST_KILL_QUIESCENCE_MS,
637
- descendant_count: identities.length,
638
- });
639
- }
640
- }
641
- // An unreadable snapshot is not evidence of an empty descendant tree.
642
- // Finish the owned-root cleanup before exposing the original failure.
643
- if (snapshotFailure !== undefined)
644
- throw snapshotFailure.error;
645
- };
646
- const beginTeardown = () => {
647
- // Assign the shared promise before invoking callbacks that can abort.
648
- cancellationTeardown ??= Promise.resolve().then(teardownChildTree).then(() => ({ ok: true }), (error) => ({ ok: false, error }));
649
- void cancellationTeardown.then((outcome) => {
650
- if (outcome.ok)
651
- return;
652
- // Failure cannot strand the live owned root or wait forever for a
653
- // descendant that still holds its pipes. Surface uncertainty instead.
654
- const childPid = child.pid;
655
- if (childPid !== undefined && !processExited) {
656
- if (process.platform !== "win32")
657
- trySignalPid(-childPid, "SIGKILL");
658
- try {
659
- child.kill("SIGKILL");
660
- }
661
- catch { /* Best effort. */ }
662
- }
663
- if (boundedSwarm || processCleanupUnverified) {
664
- // An unverified tail may still hold inherited pipes. Release our
665
- // handles so reporting failure does not wait on that tail.
666
- for (const stream of [child.stdin, child.stdout, child.stderr]) {
667
- try {
668
- stream.destroy();
669
- }
670
- catch { /* Preserve the settlement error. */ }
671
- }
672
- try {
673
- child.unref();
674
- }
675
- catch { /* Preserve the settlement error. */ }
676
- }
677
- settle("reject", new RuntimeError(boundedSwarm ? "CLI_PROCESS_SETTLEMENT_FAILED" : "CLI_CANCELLATION_TEARDOWN_FAILED", "kimi owned process teardown failed", boundedSwarm ? "cli-client.settlement" : "cli-client.cancellation"));
678
- });
679
- };
680
- const stopForPolicyFailure = (error) => {
681
- engineMismatchDetected = true; // Stops all further consumer output.
682
- beginTeardown();
683
- settle("reject", error);
684
- };
685
- let engineMismatchError;
686
- handleEngineMismatch = (mismatch) => {
687
- if (engineMismatchError !== undefined)
688
- return;
689
- engineMismatchDetected = true;
690
- engineMismatchError = new RuntimeError("CLI_ENGINE_PROVENANCE_MISMATCH", `Refusing kimi output: execution plan required ${plannedEngine}, but ${mismatch.reason}`, "cli-client.engine-provenance", {
691
- details: {
692
- operation_kind: opts.executionPlan.operationKind,
693
- intended_engine: plannedEngine,
694
- observed_engine: mismatch.observedEngine,
695
- planned_kimi_version: opts.executionPlan.kimiVersion,
696
- system_version: mismatch.systemVersion ?? null,
697
- },
698
- });
699
- appendLogLine({
700
- event: "engine_provenance_mismatch",
701
- intended_engine: plannedEngine,
702
- observed_engine: mismatch.observedEngine,
703
- system_version: mismatch.systemVersion ?? null,
704
- reason: mismatch.reason,
705
- });
706
- stopForPolicyFailure(engineMismatchError);
707
- };
708
- const onAbort = () => {
709
- if (aborted)
710
- return;
711
- aborted = true;
712
- beginTeardown();
713
- };
714
- if (boundedSwarm && process.platform !== "win32" && child.pid !== undefined) {
715
- void refreshTrackedIdentities();
716
- trackerTimer = setInterval(() => { void refreshTrackedIdentities(); }, BOUNDED_DESCENDANT_POLL_MS);
717
- trackerTimer.unref();
718
- }
719
- opts.signal?.addEventListener("abort", onAbort, { once: true });
720
- // Abort may occur during any pre-spawn await, and addEventListener does not
721
- // replay an already-aborted signal. Re-check after attaching the listener so
722
- // the spawned child cannot escape cancellation teardown.
723
- if (opts.signal?.aborted === true) {
724
- onAbort();
725
- }
726
- if (child.pid !== undefined && opts.onSpawn) {
727
- try {
728
- await opts.onSpawn(child.pid);
729
- spawnRecorded = true;
730
- }
731
- catch (error) {
732
- const spawnError = new RuntimeError("CLI_SPAWN_CALLBACK_FAILED", `Failed to record the spawned kimi process: ${formatError(error)}`, "cli-client.spawn", error instanceof Error ? { cause: error, details: errorDetails() } : { details: errorDetails() });
733
- if (boundedSwarm)
734
- checkpointError = spawnError;
735
- onAbort();
736
- settle("reject", spawnError);
737
- return;
738
- }
739
- }
740
- earlyErrorHandled = true;
741
- child.on("error", (err) => {
742
- appendLogLine({ event: "process_error", message: formatError(err) });
743
- settle("reject", new RuntimeError("CLI_PROCESS_ERROR", `kimi subprocess error: ${formatError(err)}`, "cli-client.process", err instanceof Error
744
- ? { cause: err, details: { ...errorDetails(), ...spawnErrorDetails(err) } }
745
- : { details: { ...errorDetails(), ...spawnErrorDetails(err) } }));
746
- });
747
- if (earlyErrors.length > 0) {
748
- const captured = earlyErrors[0];
749
- queueMicrotask(() => {
750
- appendLogLine({
751
- event: "process_error",
752
- message: formatError(captured),
753
- early: true,
754
- additional_count: earlyErrors.length - 1,
755
- });
756
- settle("reject", new RuntimeError("CLI_PROCESS_ERROR", `kimi subprocess error: ${formatError(captured)}`, "cli-client.process", { cause: captured, details: { ...errorDetails(), ...spawnErrorDetails(captured) } }));
757
- });
758
- }
759
- child.on("close", async (exitCode, signal) => {
760
- consumeOutcomes(parser.flush());
761
- if (!engineMismatchDetected &&
762
- exitCode === 0 &&
763
- !aborted &&
764
- requireMarkerBeforeOutput("a clean exit")) {
765
- return;
766
- }
767
- // The stderr resume-hint channel is the kimi 0.1.x fallback and exists
768
- // only for legacy-v1 plans; a native-v2 plan pins a session id from the
769
- // stdout meta record alone (after the marker), so stderr can never pin
770
- // an id ahead of, or different from, the provenance-checked stream.
771
- const sessionId = announcedSessionId ??
772
- (plannedEngine === "legacy-v1" ? extractSessionIdFromStderr(stderrTail) : undefined);
773
- appendLogLine({
774
- event: "exit",
775
- exit_code: exitCode,
776
- signal,
777
- session_id: sessionId,
778
- malformed_count: malformed.length,
779
- record_count: records.length,
780
- aborted,
781
- });
782
- // Cap the log drain wait so a wedged disk can't block result delivery.
783
- // The result itself is in memory; diagnostics are best-effort.
784
- await raceWithTimeout(logChain, LOG_DRAIN_TIMEOUT_MS);
785
- settle("resolve", {
786
- spawnedAt,
787
- settledAt: 0,
788
- sessionId,
789
- goalSummary: announcedGoalSummary,
790
- cliError: announcedCliError,
791
- systemVersion: announcedSystemVersion,
792
- observedEngine: announcedSystemVersion !== undefined
793
- ? "native-v2"
794
- : plannedEngine === "legacy-v1" &&
795
- (exitCode === 0 ||
796
- records.length > 0 ||
797
- sessionId !== undefined ||
798
- announcedGoalSummary !== undefined)
799
- ? "legacy-v1"
800
- : null,
801
- records,
802
- malformed,
803
- stderrTail,
804
- exitCode: exitCode ?? -1,
805
- signal,
806
- aborted,
807
- });
808
- });
809
- // Stdin: kimi -p reads from argv, not stdin. End it immediately so the
810
- // child never blocks. Stream method calls on a failed-spawn child can
811
- // throw synchronously — guard so the 'error' event still wins.
812
- try {
813
- child.stdout.setEncoding("utf8");
814
- child.stderr.setEncoding("utf8");
815
- child.stdout.on("data", (chunk) => {
816
- consumeOutcomes(parser.push(chunk));
817
- });
818
- child.stderr.on("data", (chunk) => {
819
- // First-announce-wins across both channels: once a session id is
820
- // pinned (from the stdout meta record or an earlier stderr line),
821
- // never let a later stderr line overwrite it. The stderr channel is
822
- // the 0.1.x fallback and is consulted ONLY for legacy-v1 plans — on a
823
- // native-v2 plan a stderr line could otherwise pin a session id before
824
- // (or different from) the provenance-checked stdout stream.
825
- if (plannedEngine === "legacy-v1" && announcedSessionId === undefined) {
826
- const nextSessionId = extractSessionIdFromStderr(stderrTail + chunk);
827
- if (nextSessionId !== undefined) {
828
- announcedSessionId = nextSessionId;
829
- }
830
- }
831
- stderrTail = appendToTail(stderrTail, chunk, STDERR_TAIL_BYTES);
832
- });
833
- child.stdin.end();
834
- }
835
- catch (err) {
836
- settle("reject", new RuntimeError("CLI_PROCESS_ERROR", `kimi subprocess stream setup failed: ${formatError(err)}`, "cli-client.streams", err instanceof Error
837
- ? { cause: err, details: { ...errorDetails(), ...spawnErrorDetails(err) } }
838
- : { details: { ...errorDetails(), ...spawnErrorDetails(err) } }));
839
- }
840
- });
841
- }
842
- /**
843
- * Helper for callers that require a session id (replay-capable commands).
844
- * Throws CLI_NO_SESSION_ID if the result lacks one, embedding the command
845
- * label and exit code in details so the failure is actionable in logs.
846
- *
847
- * Use this AT the call site rather than baking the requirement into
848
- * runCliPrompt — some callers (setup probes, smoke tests) are fine with
849
- * an undefined sessionId.
850
- */
851
- export function requireSessionId(result, context) {
852
- if (result.sessionId !== undefined && result.sessionId.length > 0) {
853
- return result.sessionId;
854
- }
855
- throw new RuntimeError("CLI_NO_SESSION_ID", "kimi subprocess completed without announcing a session id; replay and resume will be unavailable", "cli-client.session-id", {
856
- details: {
857
- command_label: context.commandLabel ?? null,
858
- exit_code: result.exitCode,
859
- signal: result.signal,
860
- aborted: result.aborted,
861
- stderr_tail_len: result.stderrTail.length,
862
- },
863
- });
864
- }
865
- /** Settled timeout data; stream records are deliberately non-serializable.
866
- * Without a partial result (teardown rejection), aborted means abort was issued,
867
- * not that the process was observed aborting. */
868
- export class ResponseTimeoutError extends RuntimeError {
869
- constructor(budgetMs, stage, commandLabel, partialResult, cause) {
870
- super("RESPONSE_TIMEOUT", `${stage} timed out after ${budgetMs}ms.`, stage, {
871
- ...(cause instanceof Error ? { cause } : {}),
872
- details: {
873
- budget_ms: budgetMs,
874
- command_label: commandLabel ?? null,
875
- record_count: partialResult?.records.length ?? 0,
876
- partial_output_chars: partialResult?.records.reduce((count, record) => count + (record.role === "assistant" && typeof record.content === "string" ? record.content.length : 0), 0) ?? 0,
877
- aborted: partialResult?.aborted ?? true,
878
- ...(partialResult ? { settled_post_abort: true } : {}),
879
- ...(partialResult?.hookEscapes?.length ? { hook_escapes: partialResult.hookEscapes } : {}),
880
- },
881
- });
882
- this.name = "ResponseTimeoutError";
883
- // Never serialize stream records into job error details or error envelopes.
884
- Object.defineProperty(this, "partialResult", { value: partialResult, enumerable: false });
885
- }
886
- }
887
- /**
888
- * Run `kimi -p` under a budget that also tells the subprocess to die
889
- * when the budget expires.
890
- *
891
- * Why this exists separately from `withTimeout`:
892
- *
893
- * The generic `withTimeout` (runtime/kimi-timeouts.ts) only rejects
894
- * the outer Promise — it has no handle on the kimi child process.
895
- *
896
- * Behavior:
897
- *
898
- * - Owns an internal AbortController. If the caller passes
899
- * `opts.signal`, both signals are linked — abort on either side
900
- * aborts the internal controller.
901
- * - When the budget expires, abort the internal controller, await the
902
- * subprocess/tree teardown, then reject with
903
- * `RuntimeError("RESPONSE_TIMEOUT", …)` matching the legacy
904
- * `withTimeout` code shape.
905
- * - A clean non-aborted exit-0 result wins same-tick budget expiry.
906
- * Otherwise a settled result on timeout is carried as partial output.
907
- */
908
- export async function runCliPromptWithBudget(opts, budgetMs, stage) {
909
- const controller = new AbortController();
910
- if (opts.signal?.aborted === true) {
911
- controller.abort();
912
- }
913
- const onParentAbort = () => controller.abort();
914
- opts.signal?.addEventListener("abort", onParentAbort, { once: true });
915
- let timeoutFired = false;
916
- let timer;
917
- timer = setTimeout(() => {
918
- timeoutFired = true;
919
- controller.abort();
920
- }, budgetMs);
921
- timer.unref();
922
- const timeoutError = (partialResult, cause) => new ResponseTimeoutError(budgetMs, stage, opts.commandLabel, partialResult, cause);
923
- try {
924
- let result;
925
- try {
926
- // Deliberately do not race this promise against an early timeout
927
- // rejection. The timer aborts it, and runCliPrompt owns the complete
928
- // child/descendant teardown before it can settle.
929
- result = await runCliPrompt({ ...opts, signal: controller.signal });
930
- }
931
- catch (error) {
932
- if (timeoutFired)
933
- throw timeoutError(undefined, error);
934
- throw error;
935
- }
936
- if (timeoutFired && (result.aborted || result.exitCode !== 0)) {
937
- // A clean, non-aborted result won the settle/timeout boundary and is success.
938
- // Budget aborts normally resolve with records, after owned teardown settles.
939
- throw timeoutError(result);
940
- }
941
- return result;
942
- }
943
- finally {
944
- if (timer !== undefined)
945
- clearTimeout(timer);
946
- opts.signal?.removeEventListener("abort", onParentAbort);
947
- }
948
- }
949
- /**
950
- * Parse a structured version FIELD (the system.version marker), not a CLI
951
- * banner: the whole value must be one semver token (optional leading `v`,
952
- * optional pre-release/build suffix) with no surrounding whitespace or extra
953
- * lines. Returns the normalized `raw` form, or undefined when malformed.
954
- */
955
- function parseExactVersionToken(value) {
956
- if (/\s/.test(value) || value.length === 0)
957
- return undefined;
958
- return parseVersionLine(value)?.raw;
959
- }
960
- const KIMI_LEGACY_ENV = "KIMI_CODE_LEGACY_FLAG";
961
- const KIMI_LEGACY_FORCED_VALUE = "1";
962
- function buildArgs(opts) {
963
- const args = [...(opts.prefixArgs ?? [])];
964
- args.push("--output-format", "stream-json");
965
- const smokeCandidate = opts.executionPlan.certification === "test-bypass" && opts.env.KIMI_PLUGIN_CC_SMOKE === "1"
966
- ? opts.env.KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE
967
- : undefined;
968
- if (opts.resumeSessionId === undefined &&
969
- ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3", "2.7.2", "2.7.3"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
970
- args.push("--environment", "local");
971
- }
972
- if (opts.resumeSessionId !== undefined) {
973
- args.push("-r", opts.resumeSessionId);
974
- }
975
- if (opts.model !== undefined) {
976
- args.push("-m", opts.model);
977
- }
978
- if (opts.skillsDirs !== undefined) {
979
- for (const dir of opts.skillsDirs) {
980
- args.push("--skills-dir", dir);
981
- }
982
- }
983
- // -p accepts the prompt as the option value. We pass it as a separate argv
984
- // entry so prompts with leading dashes or whitespace are not interpreted as
985
- // additional flags.
986
- args.push("-p", opts.prompt);
987
- return args;
988
- }
989
- export function buildKimiCliEnvironment(opts) {
990
- const env = { ...opts.env };
991
- // A previous host/job cannot opt another operation into a swarm policy or
992
- // choose its bound. Only this immutable execution plan grants the policy.
993
- delete env[SWARM_POLICY_ENV];
994
- delete env[SWARM_WAVE_SIZE_ENV];
995
- if (usesBoundedSwarmPolicy(opts.executionPlan)) {
996
- if (opts.commandLabel !== opts.executionPlan.operationKind ||
997
- !Number.isSafeInteger(opts.swarmMaxConcurrency) || (opts.swarmMaxConcurrency ?? 0) < 1) {
998
- throw new RuntimeError("SWARM_POLICY_INVALID", "Bounded swarm requires its exact operation label and a positive safe-integer concurrency limit.", "cli-client.environment");
999
- }
1000
- env[SWARM_POLICY_ENV] = BOUNDED_SWARM_POLICY;
1001
- env[SWARM_WAVE_SIZE_ENV] = String(opts.swarmMaxConcurrency);
1002
- env.KIMI_CODE_SWARM_TIMEOUT_MS = String(SWARM_CHILD_TIMEOUT_MS);
1003
- }
1004
- if (opts.thinkingEffort !== undefined)
1005
- env.KIMI_MODEL_THINKING_EFFORT = opts.thinkingEffort;
1006
- // Ambient workspace trust starts project MCP stdio servers outside PreToolUse.
1007
- delete env.KIMI_CODE_TRUST_WORKSPACE;
1008
- // Legacy-v1 plans use this flag on releases whose unflagged -p default can
1009
- // route to native-v2. Always overwrite ambient false values; older releases
1010
- // ignore it. The engine choice stays plugin-owned, while certified native-v2
1011
- // plans use the no-plan construction rather than a legacy pin.
1012
- if (opts.executionPlan.intendedEngine === "legacy-v1") {
1013
- env[KIMI_LEGACY_ENV] = KIMI_LEGACY_FORCED_VALUE;
1014
- }
1015
- // Suppress passive update checks on the `-p` path. Manually staged native
1016
- // swaps remain an upstream exception, so the exact probe and first-line
1017
- // version marker must still prove the spawned artifact's identity.
1018
- env.KIMI_CODE_NO_AUTO_UPDATE = "1";
1019
- // Plugin-owned web lifecycles must not inherit ambient idle-session reclamation.
1020
- env.KIMI_CODE_SESSION_IDLE_RECLAIM_MS = "0";
1021
- // Rescue and pursue share the write label. Only the immutable execution
1022
- // plan can grant pursue's narrow goal-metadata access; never trust ambient
1023
- // state inherited from another plugin job.
1024
- env.KIMI_PLUGIN_CC_OPERATION = opts.executionPlan.operationKind;
1025
- env.KIMI_CODE_HOME = resolveKimiHome(opts.env, opts.cwd);
1026
- if (opts.commandLabel !== undefined) {
1027
- env.KIMI_PLUGIN_CC_CMD = opts.commandLabel;
1028
- }
1029
- if (opts.swarmMaxConcurrency !== undefined) {
1030
- env.KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY = String(opts.swarmMaxConcurrency);
1031
- }
1032
- if (opts.trustedWorkspaceRoot !== undefined) {
1033
- // Trusted allowlist root for write-capable PreToolUse cases. Forge-proof
1034
- // (env on the spawned process; the model cannot alter it). See field doc.
1035
- env.KIMI_PLUGIN_CC_WORKSPACE_ROOT = opts.trustedWorkspaceRoot;
1036
- }
1037
- return env;
1038
- }
1039
- function appendToTail(tail, chunk, maxBytes) {
1040
- const combined = tail + chunk;
1041
- if (combined.length <= maxBytes)
1042
- return combined;
1043
- return combined.slice(combined.length - maxBytes);
1044
- }
1045
- function truncateChars(value, maxChars) {
1046
- return value.length <= maxChars ? value : value.slice(0, maxChars);
1047
- }
1048
- function isErrnoException(err, code) {
1049
- return typeof err === "object" && err !== null && "code" in err && err.code === code;
1050
- }
1051
- function raceWithTimeout(promise, timeoutMs) {
1052
- let timer;
1053
- const timeoutPromise = new Promise((resolve) => {
1054
- timer = setTimeout(resolve, timeoutMs);
1055
- });
1056
- return Promise.race([
1057
- promise.then(() => { }, () => { }),
1058
- timeoutPromise,
1059
- ]).finally(() => {
1060
- if (timer !== undefined)
1061
- clearTimeout(timer);
1062
- });
1063
- }
1064
- async function raceWithValueTimeout(promise, timeoutMs, timeoutValue) {
1065
- let timer;
1066
- try {
1067
- return await Promise.race([
1068
- promise,
1069
- new Promise((resolve) => {
1070
- timer = setTimeout(() => resolve(timeoutValue), Math.max(0, timeoutMs));
1071
- }),
1072
- ]);
1073
- }
1074
- finally {
1075
- if (timer !== undefined)
1076
- clearTimeout(timer);
1077
- }
1078
- }