kimi-plugin-cc 3.0.0 → 3.1.1

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