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,1194 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import { constants as fsConstants } from "node:fs";
4
- import { open } from "node:fs/promises";
5
- import path from "node:path";
6
- import { assertWorkspaceSpellable, buildKimiCliEnvironment, } from "./cli-client.js";
7
- import { RuntimeError } from "./errors.js";
8
- import { assertPrefixArgsSafe } from "./kimi-command.js";
9
- import { assertExecutionPlanMatchesSpawn, assertNoUnsafeExperimentalSelector, } from "./kimi-engine.js";
10
- import { resolveKimiHome } from "./kimi-home.js";
11
- import { kimiJournalRecords, UNPARSEABLE_JOURNAL_LINE } from "./kimi-journal.js";
12
- import { kimiReleaseHas, kimiVersionsWith } from "./kimi-releases.js";
13
- import { assertNativeV2Preflight } from "./native-v2-preflight.js";
14
- import { usesBoundedSwarmPolicy } from "./swarm-policy.js";
15
- import { installBoundedSwarmToolPolicy } from "./swarm-tool-policy.js";
16
- import { sleep } from "./util.js";
17
- import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, retryIncompleteCapture, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
18
- // These exact activation entries support candidate integration; production scope is per operation.
19
- const PREACTIVATION_VERSIONS = kimiVersionsWith("web-preactivation");
20
- const JSON_READY_VERSIONS = kimiVersionsWith("web-json-ready");
21
- const KIMI_AGENT_PROTOCOL_VERSION = "1.0.0";
22
- const READY_TIMEOUT_MS = 10_000;
23
- const REST_TIMEOUT_MS = 5_000;
24
- // Exact 2.4.0 can take longer than 5s to drain session/workspace lifecycle work.
25
- const SHUTDOWN_TIMEOUT_MS = 15_000;
26
- const JOURNAL_TIMEOUT_MS = 2_000;
27
- const JOURNAL_POLL_MS = 50;
28
- const READY_LINE_MAX_CHARS = 65_536;
29
- const REST_RESPONSE_MAX_BYTES = 1024 * 1024;
30
- const WEBSOCKET_MAX_FRAMES = 64;
31
- const WEBSOCKET_RESPONSE_MAX_CHARS = 1024 * 1024;
32
- const JOURNAL_MAX_BYTES = 64 * 1024 * 1024;
33
- const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 2_000;
34
- const DESCENDANT_TRACK_INTERVAL_MS = 50;
35
- const IDENTITY_REVALIDATION_TIMEOUT_MS = 250;
36
- const ESCALATION_MS = 1_500;
37
- const POST_KILL_QUIESCENCE_MS = 500;
38
- const ENV_MODEL_ALIAS = "__kimi_env_model__";
39
- export function requiresSwarmPreactivation(version) {
40
- return version !== null && PREACTIVATION_VERSIONS.includes(version);
41
- }
42
- export async function preactivateSwarmSession(options) {
43
- const failureCode = "SWARM_ACTIVATION_FAILED";
44
- let web;
45
- let identity;
46
- let profileMutationAttempted = false;
47
- try {
48
- const prepared = await prepareWebSpawn(options, failureCode);
49
- throwIfAborted(options.signal, failureCode, "swarm-activation.pre-spawn");
50
- web = await startWebChild(options, prepared.env, prepared.expectedVersion, failureCode);
51
- await verifyMeta(web, prepared.expectedVersion, options.signal, failureCode);
52
- const model = await resolveProfileModel(web, options, failureCode);
53
- identity = await createSession(web, options, prepared.expectedVersion, failureCode);
54
- await verifyLocalEnvironment(web, identity, options.cwd, prepared.expectedVersion, options.signal, failureCode);
55
- options.onRecoveryEvent?.({ kind: "session", ...identity });
56
- profileMutationAttempted = true;
57
- await setSwarmMode(web, prepared, identity, true, model, options.signal, failureCode);
58
- if (usesBoundedSwarmPolicy(options.executionPlan) && options.swarmMaxConcurrency > 1) {
59
- await installBoundedSwarmToolPolicy(prepared.kimiHome, identity, options.signal);
60
- }
61
- throwIfAborted(options.signal, failureCode, "swarm-activation.complete");
62
- return identity;
63
- }
64
- catch (error) {
65
- const primary = asSafeFailure(error, failureCode, "swarm-activation");
66
- if (web !== undefined && !(await teardownOwnedChild(web))) {
67
- const cleanupError = failure("SWARM_SESSION_CLEANUP_FAILED", "swarm-activation.process-cleanup", "The Kimi web process tree did not become quiescent after activation failed.");
68
- throw failure("SWARM_SESSION_CLEANUP_FAILED", "swarm-activation.process-cleanup", "Swarm preactivation failed and its web process tree could not be verified quiescent.", {
69
- activation_error: errorReference(primary),
70
- cleanup_error: errorReference(cleanupError),
71
- process_cleanup_unverified: true,
72
- cancelled: primary.details.cancelled === true,
73
- ...(profileMutationAttempted && identity !== undefined
74
- ? { session_id: identity.sessionId, workspace_id: identity.workspaceId }
75
- : {}),
76
- });
77
- }
78
- if (profileMutationAttempted && identity !== undefined) {
79
- throw new RuntimeError(primary.code, primary.message, primary.stage, {
80
- details: {
81
- ...primary.details,
82
- cleanup_unverified: true,
83
- session_id: identity.sessionId,
84
- workspace_id: identity.workspaceId,
85
- },
86
- });
87
- }
88
- throw primary;
89
- }
90
- }
91
- export async function deactivateSwarmSession(options) {
92
- const failureCode = "SWARM_SESSION_CLEANUP_FAILED";
93
- let web;
94
- try {
95
- // Cleanup must still run when activation left no journal or the print run tainted it;
96
- // the print spawn owns resume plan-taint refusal.
97
- const prepared = await prepareWebSpawn(options, failureCode);
98
- throwIfAborted(options.signal, failureCode, "swarm-deactivation.pre-spawn");
99
- web = await startWebChild(options, prepared.env, prepared.expectedVersion, failureCode);
100
- await verifyMeta(web, prepared.expectedVersion, options.signal, failureCode);
101
- await verifyLocalEnvironment(web, options, options.cwd, prepared.expectedVersion, options.signal, failureCode);
102
- await setSwarmMode(web, prepared, options, false, undefined, options.signal, failureCode);
103
- options.onRecoveryEvent?.({ kind: "disabled" });
104
- throwIfAborted(options.signal, failureCode, "swarm-deactivation.complete");
105
- }
106
- catch (error) {
107
- const primary = asSafeFailure(error, failureCode, "swarm-deactivation");
108
- if (web !== undefined && !(await teardownOwnedChild(web))) {
109
- throw failure("SWARM_SESSION_CLEANUP_FAILED", "swarm-deactivation.process-cleanup", `Swarm deactivation failed and the Kimi web process tree did not become quiescent (${web.cleanupSummary ?? "summary unavailable"}).`, { cleanup_error: errorReference(primary) });
110
- }
111
- throw primary;
112
- }
113
- }
114
- /** Set swarm mode, prove the resulting state, stop the web child, then require the journal record. */
115
- async function setSwarmMode(web, prepared, identity, active, model, signal, failureCode) {
116
- await postSwarmProfile(web, identity, active, model, signal, failureCode);
117
- await verifySwarmStatus(web, identity, active, model, prepared.expectedVersion, signal, failureCode);
118
- await shutdownWeb(web, signal, failureCode);
119
- await requireSwarmJournal(prepared.kimiHome, identity, active ? "enter" : "exit", signal, failureCode);
120
- }
121
- async function prepareWebSpawn(options, failureCode) {
122
- throwIfAborted(options.signal, failureCode, "swarm-activation.pre-spawn");
123
- const prefixArgs = options.prefixArgs ?? [];
124
- assertExecutionPlanMatchesSpawn(options.executionPlan, options.command, prefixArgs, options.env);
125
- if (options.commandLabel === "swarm-write" && !options.trustedWorkspaceRoot) {
126
- throw new RuntimeError("CLI_TRUSTED_WORKSPACE_ROOT_MISSING", "Refusing swarm-write: write-capable plugin launches require a plugin-owned trusted workspace root.", "swarm-activation.pre-spawn", { details: { command_label: options.commandLabel } });
127
- }
128
- if (options.commandLabel === "swarm-write") {
129
- assertWorkspaceSpellable(options.commandLabel, [options.cwd, options.trustedWorkspaceRoot], "swarm-activation.pre-spawn");
130
- }
131
- assertNoUnsafeExperimentalSelector(options.env, "swarm-activation.pre-spawn", options.executionPlan);
132
- assertPrefixArgsSafe(prefixArgs);
133
- if (options.expectedVersion !== undefined &&
134
- options.executionPlan.kimiVersion !== null &&
135
- options.expectedVersion !== options.executionPlan.kimiVersion) {
136
- throw failure(failureCode, "swarm-activation.version", "expectedVersion must match the execution plan version when that version is known.");
137
- }
138
- const expectedVersion = options.expectedVersion ?? options.executionPlan.kimiVersion;
139
- if (expectedVersion === null || !requiresSwarmPreactivation(expectedVersion)) {
140
- throw failure(failureCode, "swarm-activation.version", `Swarm web preactivation requires exact kimi-code ${PREACTIVATION_VERSIONS.join(" or ")}.`);
141
- }
142
- const kimiHome = resolveKimiHome(options.env, options.cwd);
143
- if (options.executionPlan.intendedEngine === "native-v2") {
144
- await assertNativeV2Preflight({
145
- kimiHome,
146
- env: options.env,
147
- expectedExecutionRoot: options.cwd,
148
- stage: "swarm-activation.pre-spawn",
149
- release: options.executionPlan,
150
- });
151
- }
152
- throwIfAborted(options.signal, failureCode, "swarm-activation.pre-spawn");
153
- return {
154
- expectedVersion,
155
- env: buildKimiCliEnvironment(options),
156
- kimiHome,
157
- };
158
- }
159
- async function startWebChild(options, env, expectedVersion, failureCode) {
160
- const args = [
161
- ...(options.prefixArgs ?? []),
162
- "web",
163
- JSON_READY_VERSIONS.includes(expectedVersion) ? "--json" : "--no-open",
164
- "--host",
165
- "127.0.0.1",
166
- "--port",
167
- "0",
168
- "--log-level",
169
- "error",
170
- ];
171
- let child;
172
- options.onRecoveryEvent?.({ kind: "web-spawn" });
173
- try {
174
- child = spawn(options.command, args, {
175
- cwd: options.cwd,
176
- env,
177
- stdio: "pipe",
178
- detached: process.platform !== "win32",
179
- });
180
- }
181
- catch {
182
- options.onRecoveryEvent?.({ kind: "web-exit" });
183
- throw failure(failureCode, "swarm-activation.spawn", "Failed to spawn the Kimi web lifecycle process.");
184
- }
185
- let exited = false;
186
- let processError = false;
187
- let settleClose;
188
- const closePromise = new Promise((resolve) => {
189
- settleClose = resolve;
190
- });
191
- child.once("exit", () => {
192
- exited = true;
193
- });
194
- child.once("close", (exitCode, signal) => {
195
- exited = true;
196
- settleClose({ exitCode, signal });
197
- });
198
- child.on("error", () => {
199
- processError = true;
200
- });
201
- child.stdout.on("data", () => undefined);
202
- child.stderr.on("data", () => undefined);
203
- child.stdout.setEncoding("utf8");
204
- child.stderr.setEncoding("utf8");
205
- try {
206
- child.stdin.end();
207
- }
208
- catch {
209
- }
210
- const owned = {
211
- child,
212
- closePromise,
213
- descendants: [],
214
- onRecoveryEvent: options.onRecoveryEvent,
215
- trackingStopped: false,
216
- lastSnapshotComplete: false,
217
- snapshotIncomplete: false,
218
- get exited() {
219
- return exited;
220
- },
221
- get processError() {
222
- return processError;
223
- },
224
- };
225
- startDescendantTracking(owned);
226
- try {
227
- const ready = await waitForReadyLine(owned, expectedVersion, options.signal, failureCode);
228
- await refreshOwnedDescendants(owned);
229
- if (owned.recoveryFailed)
230
- throw failure(failureCode, "swarm-activation.recovery", "Cannot persist web ownership; refusing session mutation.");
231
- return Object.assign(owned, ready);
232
- }
233
- catch (error) {
234
- const primary = asSafeFailure(error, failureCode, "swarm-activation.ready");
235
- if (!(await teardownOwnedChild(owned))) {
236
- throw failure("SWARM_SESSION_CLEANUP_FAILED", "swarm-activation.ready-cleanup", "The Kimi web process tree did not become quiescent after startup failed.", { activation_error: errorReference(primary), process_cleanup_unverified: true });
237
- }
238
- throw primary;
239
- }
240
- }
241
- async function waitForReadyLine(owned, expectedVersion, signal, failureCode) {
242
- throwIfAborted(signal, failureCode, "swarm-activation.ready");
243
- const ready = JSON_READY_VERSIONS.includes(expectedVersion)
244
- ? {
245
- skip: (line) => line.trim().length === 0,
246
- parse: parseJsonReadyLine,
247
- invalid: "The Kimi web JSON ready line did not confirm the authenticated KAP loopback contract.",
248
- }
249
- : {
250
- skip: (line) => !line.startsWith("Kimi server: "),
251
- parse: parseReadyLine,
252
- invalid: "The Kimi web ready line was not an authenticated loopback URL in the expected format.",
253
- };
254
- return await new Promise((resolve, reject) => {
255
- let buffered = "";
256
- let settled = false;
257
- const timer = setTimeout(() => {
258
- settle(failure(failureCode, "swarm-activation.ready", "Timed out waiting for the Kimi web ready line.", { timeout_ms: READY_TIMEOUT_MS }));
259
- }, READY_TIMEOUT_MS);
260
- const cleanup = () => {
261
- clearTimeout(timer);
262
- signal?.removeEventListener("abort", onAbort);
263
- owned.child.stdout.off("data", onStdout);
264
- owned.child.off("error", onError);
265
- owned.child.off("close", onClose);
266
- };
267
- const settle = (result) => {
268
- if (settled)
269
- return;
270
- settled = true;
271
- cleanup();
272
- if (result instanceof RuntimeError)
273
- reject(result);
274
- else
275
- resolve(result);
276
- };
277
- const onAbort = () => {
278
- settle(cancelledFailure(failureCode, "swarm-activation.ready"));
279
- };
280
- const onError = () => {
281
- settle(failure(failureCode, "swarm-activation.process", "The Kimi web process failed before becoming ready."));
282
- };
283
- const onClose = () => {
284
- settle(failure(failureCode, "swarm-activation.process", "The Kimi web process exited before becoming ready."));
285
- };
286
- const onStdout = (chunk) => {
287
- buffered += chunk;
288
- if (buffered.length > READY_LINE_MAX_CHARS) {
289
- settle(failure(failureCode, "swarm-activation.ready", "The Kimi web ready line exceeded the bounded parser limit."));
290
- return;
291
- }
292
- while (buffered.includes("\n")) {
293
- const newline = buffered.indexOf("\n");
294
- const line = buffered.slice(0, newline).replace(/\r$/, "");
295
- buffered = buffered.slice(newline + 1);
296
- if (ready.skip(line))
297
- continue;
298
- try {
299
- settle(ready.parse(line));
300
- }
301
- catch {
302
- settle(failure(failureCode, "swarm-activation.ready", ready.invalid));
303
- }
304
- return;
305
- }
306
- };
307
- signal?.addEventListener("abort", onAbort, { once: true });
308
- owned.child.stdout.on("data", onStdout);
309
- owned.child.on("error", onError);
310
- owned.child.on("close", onClose);
311
- if (signal?.aborted === true)
312
- onAbort();
313
- });
314
- }
315
- function parseReadyLine(line) {
316
- const candidate = line.slice("Kimi server: ".length);
317
- const parsed = new URL(candidate);
318
- if (!isLoopbackRootUrl(parsed))
319
- throw new Error("invalid ready URL");
320
- if (!parsed.hash.startsWith("#token=") || parsed.hash.length === "#token=".length) {
321
- throw new Error("invalid ready token");
322
- }
323
- return {
324
- origin: parsed.origin,
325
- token: parsed.hash.slice("#token=".length),
326
- };
327
- }
328
- /** An http://127.0.0.1:<port>/ URL with no query or credentials; callers check the hash. */
329
- function isLoopbackRootUrl(url) {
330
- return (url.protocol === "http:" &&
331
- url.hostname === "127.0.0.1" &&
332
- url.port.length > 0 &&
333
- url.pathname === "/" &&
334
- url.search.length === 0 &&
335
- url.username.length === 0 &&
336
- url.password.length === 0);
337
- }
338
- function parseJsonReadyLine(line) {
339
- const data = JSON.parse(line);
340
- if (!isRecord(data) ||
341
- typeof data.origin !== "string" ||
342
- typeof data.ws_url !== "string" ||
343
- typeof data.token !== "string" ||
344
- data.token.trim().length === 0 ||
345
- data.kimi_agent_protocol_version !== KIMI_AGENT_PROTOCOL_VERSION) {
346
- throw new Error("invalid JSON ready payload");
347
- }
348
- const origin = new URL(data.origin);
349
- if (!isLoopbackRootUrl(origin) ||
350
- origin.hash.length > 0 ||
351
- (data.origin !== origin.origin && data.origin !== `${origin.origin}/`)) {
352
- throw new Error("invalid JSON ready origin");
353
- }
354
- const websocket = new URL(data.ws_url);
355
- if (websocket.protocol !== "ws:" ||
356
- websocket.host !== origin.host ||
357
- websocket.pathname !== "/api/v1/ws" ||
358
- websocket.search.length > 0 ||
359
- websocket.hash.length > 0 ||
360
- websocket.username.length > 0 ||
361
- websocket.password.length > 0 ||
362
- data.ws_url !== websocket.href) {
363
- throw new Error("invalid JSON ready WebSocket URL");
364
- }
365
- return { origin: origin.origin, token: data.token };
366
- }
367
- async function verifyMeta(web, expectedVersion, signal, failureCode) {
368
- const data = await restData(web, "GET", "/api/v1/meta", undefined, signal, failureCode);
369
- if (!isRecord(data)) {
370
- throw failure(failureCode, "swarm-activation.meta", "Kimi web /meta returned an invalid payload.");
371
- }
372
- if (JSON_READY_VERSIONS.includes(expectedVersion)) {
373
- if (data.kimi_agent_protocol_version !== KIMI_AGENT_PROTOCOL_VERSION ||
374
- !isRecord(data.capabilities) ||
375
- data.capabilities.websocket !== true ||
376
- "backend" in data) {
377
- throw failure(failureCode, "swarm-activation.meta", "Kimi web /meta did not confirm the KAP 1.0.0 WebSocket contract without a legacy backend.");
378
- }
379
- }
380
- else if (data.backend !== "v2") {
381
- throw failure(failureCode, "swarm-activation.meta", "Kimi web /meta did not confirm the v2 backend.");
382
- }
383
- if (data.dangerous_bypass_auth !== false) {
384
- throw failure(failureCode, "swarm-activation.meta", "Refusing a Kimi web server with authentication bypass enabled.");
385
- }
386
- if (data.server_version !== expectedVersion) {
387
- throw failure(failureCode, "swarm-activation.meta", "Kimi web /meta server_version did not exactly match the execution plan.");
388
- }
389
- }
390
- async function resolveProfileModel(web, options, failureCode) {
391
- if (options.model !== undefined) {
392
- if (options.model.length === 0) {
393
- throw failure(failureCode, "swarm-activation.model", "The explicit swarm model alias is empty.");
394
- }
395
- return options.model;
396
- }
397
- if (options.env.KIMI_MODEL_NAME?.trim())
398
- return ENV_MODEL_ALIAS;
399
- const data = await restData(web, "GET", "/api/v1/config", undefined, options.signal, failureCode);
400
- if (!isRecord(data) || typeof data.default_model !== "string" || data.default_model.trim().length === 0) {
401
- throw failure(failureCode, "swarm-activation.model", "Kimi web /config did not provide a usable default_model.");
402
- }
403
- return data.default_model;
404
- }
405
- async function createSession(web, options, expectedVersion, failureCode) {
406
- const request = { metadata: { cwd: options.cwd } };
407
- if (kimiReleaseHas(expectedVersion, "local-environment")) {
408
- request.environment_id = "local";
409
- request.environment_cwd = options.cwd;
410
- }
411
- const data = await restData(web, "POST", "/api/v1/sessions", request, options.signal, failureCode);
412
- if (!isRecord(data) || !validPathId(data.id) || !validPathId(data.workspace_id)) {
413
- throw failure(failureCode, "swarm-activation.create-session", "Kimi web returned an invalid session identity.");
414
- }
415
- return { sessionId: data.id, workspaceId: data.workspace_id };
416
- }
417
- async function verifyLocalEnvironment(web, identity, expectedCwd, expectedVersion, signal, failureCode) {
418
- if (!kimiReleaseHas(expectedVersion, "local-environment"))
419
- return;
420
- const data = await restData(web, "GET", `/api/v1/sessions/${encodeURIComponent(identity.sessionId)}/environment`, undefined, signal, failureCode);
421
- if (!isRecord(data)) {
422
- throw failure(failureCode, "swarm-activation.environment", "Kimi web /environment returned an invalid payload.");
423
- }
424
- if (data.workspace_id !== identity.workspaceId || data.environment_id !== "local" || data.cwd !== expectedCwd) {
425
- throw failure(failureCode, "swarm-activation.environment", "Kimi web /environment did not confirm the expected local workspace binding.");
426
- }
427
- }
428
- async function postSwarmProfile(web, identity, active, model, signal, failureCode) {
429
- const agentConfig = {
430
- swarm_mode: active,
431
- permission_mode: "auto",
432
- };
433
- if (active)
434
- agentConfig.model = model;
435
- await restData(web, "POST", `/api/v1/sessions/${encodeURIComponent(identity.sessionId)}/profile`, { agent_config: agentConfig }, signal, failureCode);
436
- }
437
- async function verifySwarmStatus(web, identity, active, model, expectedVersion, signal, failureCode) {
438
- const agentState = kimiReleaseHas(expectedVersion, "agent-state");
439
- const data = agentState
440
- ? await readWebSocketAgentState(web, identity.sessionId, expectedVersion, signal, failureCode)
441
- : await restData(web, "GET", `/api/v1/sessions/${encodeURIComponent(identity.sessionId)}/status`, undefined, signal, failureCode);
442
- const source = agentState ? "agent state" : "/status";
443
- if (!isRecord(data)) {
444
- throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} returned an invalid payload.`);
445
- }
446
- if (data.swarm_mode !== active) {
447
- throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} did not confirm swarm_mode=${active}.`, { expected_swarm_mode: active });
448
- }
449
- if (data.plan_mode !== false) {
450
- throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} did not confirm plan mode is off.`);
451
- }
452
- if (agentState && data.tower_mode !== false) {
453
- throw failure(failureCode, "swarm-activation.status", "Kimi web agent state did not confirm tower mode is off.");
454
- }
455
- const permission = agentState ? data.permission_mode : data.permission;
456
- if (permission !== "auto") {
457
- throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} did not confirm auto permission mode.`);
458
- }
459
- if (active && data.model !== model) {
460
- throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} did not confirm the selected model alias.`);
461
- }
462
- }
463
- async function readWebSocketAgentState(web, sessionId, expectedVersion, signal, failureCode) {
464
- throwIfAborted(signal, failureCode, "swarm-activation.status");
465
- await refreshOwnedDescendants(web);
466
- throwIfAborted(signal, failureCode, "swarm-activation.status");
467
- try {
468
- return await new Promise((resolve, reject) => {
469
- let socket;
470
- const bearerProtocol = `kimi-code.bearer.${web.token}`;
471
- const legacyControl = !kimiReleaseHas(expectedVersion, "modern-ws-control");
472
- const helloId = `swarm-activation-hello-${randomUUID()}`;
473
- const subscribeId = `swarm-activation-subscribe-${randomUUID()}`;
474
- try {
475
- const url = new URL(web.origin);
476
- url.protocol = "ws:";
477
- url.pathname = "/api/v1/ws";
478
- socket = new WebSocket(url, bearerProtocol);
479
- }
480
- catch {
481
- reject(failure(failureCode, "swarm-activation.status", "Could not open the authenticated Kimi web agent-state channel."));
482
- return;
483
- }
484
- let settled = false;
485
- let serverHello = false;
486
- let clientHelloAcknowledged = false;
487
- let subscribeSent = false;
488
- let subscriptionAcknowledged = false;
489
- let closeRequested = false;
490
- let closeTimer;
491
- let latestState;
492
- let frames = 0;
493
- let receivedChars = 0;
494
- const timer = setTimeout(() => {
495
- settle(failure(failureCode, "swarm-activation.status", "Kimi web agent-state verification timed out.", { timeout_ms: REST_TIMEOUT_MS }));
496
- }, REST_TIMEOUT_MS);
497
- const cleanup = () => {
498
- clearTimeout(timer);
499
- if (closeTimer !== undefined)
500
- clearTimeout(closeTimer);
501
- signal?.removeEventListener("abort", onAbort);
502
- socket.removeEventListener("open", onOpen);
503
- socket.removeEventListener("message", onMessage);
504
- socket.removeEventListener("error", onError);
505
- socket.removeEventListener("close", onClose);
506
- try {
507
- socket.close();
508
- }
509
- catch {
510
- }
511
- };
512
- const settle = (result) => {
513
- if (settled)
514
- return;
515
- settled = true;
516
- cleanup();
517
- if (result instanceof RuntimeError)
518
- reject(result);
519
- else
520
- resolve(result);
521
- };
522
- const rejectState = (message) => {
523
- settle(failure(failureCode, "swarm-activation.status", message));
524
- };
525
- const send = (frame) => {
526
- try {
527
- socket.send(JSON.stringify(frame));
528
- return true;
529
- }
530
- catch {
531
- rejectState("Could not send a Kimi web agent-state control frame.");
532
- return false;
533
- }
534
- };
535
- const handshakeComplete = () => !legacyControl || (serverHello && clientHelloAcknowledged);
536
- const closeForValidation = () => {
537
- closeRequested = true;
538
- try {
539
- socket.close();
540
- }
541
- catch {
542
- rejectState("Could not close the Kimi web agent-state channel for final validation.");
543
- }
544
- };
545
- const completeIfReady = () => {
546
- if (!handshakeComplete() || !subscriptionAcknowledged || latestState === undefined || closeRequested)
547
- return;
548
- if (legacyControl) {
549
- closeForValidation();
550
- return;
551
- }
552
- closeTimer ??= setTimeout(() => {
553
- closeTimer = undefined;
554
- closeForValidation();
555
- }, 0);
556
- };
557
- const onOpen = () => {
558
- if (socket.protocol !== bearerProtocol) {
559
- rejectState("Kimi web did not authenticate the agent-state channel with the expected subprotocol.");
560
- return;
561
- }
562
- if (legacyControl) {
563
- send({
564
- type: "client_hello",
565
- id: helloId,
566
- payload: { client_id: "kimi-plugin-cc-swarm-activation" },
567
- });
568
- return;
569
- }
570
- subscribeSent = send({
571
- type: "subscribe",
572
- request_id: subscribeId,
573
- session_id: sessionId,
574
- agent_ids: ["main"],
575
- });
576
- };
577
- const onMessage = (event) => {
578
- if (settled)
579
- return;
580
- if (typeof event.data !== "string") {
581
- rejectState("Kimi web agent-state channel returned a non-text frame.");
582
- return;
583
- }
584
- frames += 1;
585
- receivedChars += event.data.length;
586
- if (frames > WEBSOCKET_MAX_FRAMES || receivedChars > WEBSOCKET_RESPONSE_MAX_CHARS) {
587
- rejectState("Kimi web agent-state channel exceeded the bounded response limit.");
588
- return;
589
- }
590
- let frame;
591
- try {
592
- frame = JSON.parse(event.data);
593
- }
594
- catch {
595
- rejectState("Kimi web agent-state channel returned malformed JSON.");
596
- return;
597
- }
598
- if (!isRecord(frame) || typeof frame.type !== "string") {
599
- rejectState("Kimi web agent-state channel returned an invalid frame.");
600
- return;
601
- }
602
- if (legacyControl && frame.type === "server_hello") {
603
- if (serverHello || !isRecord(frame.payload) ||
604
- frame.payload.protocol_version !== 2 ||
605
- typeof frame.payload.ws_connection_id !== "string" ||
606
- !isRecord(frame.payload.capabilities) ||
607
- frame.payload.capabilities.event_batching !== false ||
608
- frame.payload.capabilities.compression !== false) {
609
- rejectState("Kimi web agent-state channel did not provide the expected protocol-v2 hello.");
610
- return;
611
- }
612
- serverHello = true;
613
- return;
614
- }
615
- if (legacyControl && !serverHello) {
616
- rejectState("Kimi web agent-state channel sent data before its protocol hello.");
617
- return;
618
- }
619
- if (legacyControl && frame.type === "ack") {
620
- if (typeof frame.id !== "string" || typeof frame.code !== "number" || !isRecord(frame.payload)) {
621
- rejectState("Kimi web agent-state channel returned an invalid acknowledgement.");
622
- return;
623
- }
624
- if (frame.id === helloId) {
625
- if (clientHelloAcknowledged || frame.code !== 0) {
626
- rejectState("Kimi web agent-state channel rejected the client hello.");
627
- return;
628
- }
629
- clientHelloAcknowledged = true;
630
- subscribeSent = send({
631
- type: "subscribe_v2",
632
- id: subscribeId,
633
- payload: { session_id: sessionId, transcript: { main: "block" } },
634
- });
635
- return;
636
- }
637
- if (frame.id === subscribeId) {
638
- if (subscriptionAcknowledged || !subscribeSent || frame.code !== 0 ||
639
- !Array.isArray(frame.payload.accepted) ||
640
- frame.payload.accepted.length !== 1 ||
641
- frame.payload.accepted[0] !== sessionId ||
642
- !Array.isArray(frame.payload.not_found) ||
643
- frame.payload.not_found.length !== 0) {
644
- rejectState("Kimi web agent-state channel did not accept the exact main-session subscription.");
645
- return;
646
- }
647
- subscriptionAcknowledged = true;
648
- completeIfReady();
649
- return;
650
- }
651
- rejectState("Kimi web agent-state channel returned an unexpected acknowledgement.");
652
- return;
653
- }
654
- if (!legacyControl && frame.type === "response") {
655
- if (typeof frame.request_id !== "string" || !Number.isInteger(frame.code)) {
656
- rejectState("Kimi web agent-state channel returned an invalid subscription response.");
657
- return;
658
- }
659
- if (frame.request_id !== subscribeId) {
660
- rejectState("Kimi web agent-state channel returned an unexpected subscription response.");
661
- return;
662
- }
663
- if (subscriptionAcknowledged || !subscribeSent || frame.code !== 0) {
664
- rejectState("Kimi web agent-state channel did not accept the exact main-session subscription.");
665
- return;
666
- }
667
- subscriptionAcknowledged = true;
668
- completeIfReady();
669
- return;
670
- }
671
- if (frame.type === "agent") {
672
- if (!subscribeSent || (!legacyControl && !subscriptionAcknowledged) ||
673
- !isAgentStateFrame(frame, sessionId)) {
674
- rejectState("Kimi web agent-state channel returned invalid or misbound main-agent state.");
675
- return;
676
- }
677
- latestState = frame;
678
- completeIfReady();
679
- return;
680
- }
681
- if (frame.type === "ping") {
682
- if (legacyControl && isRecord(frame.payload) && typeof frame.payload.nonce === "string") {
683
- send({ type: "pong", payload: { nonce: frame.payload.nonce } });
684
- }
685
- else if (!legacyControl) {
686
- send({ type: "pong" });
687
- }
688
- }
689
- };
690
- const onAbort = () => {
691
- settle(cancelledFailure(failureCode, "swarm-activation.status"));
692
- };
693
- const onError = () => {
694
- rejectState("Kimi web agent-state channel failed before valid state was received.");
695
- };
696
- const onClose = () => {
697
- if (closeRequested &&
698
- handshakeComplete() &&
699
- subscriptionAcknowledged &&
700
- latestState !== undefined) {
701
- settle(latestState);
702
- return;
703
- }
704
- rejectState("Kimi web agent-state channel closed before valid state was received.");
705
- };
706
- signal?.addEventListener("abort", onAbort, { once: true });
707
- socket.addEventListener("open", onOpen);
708
- socket.addEventListener("message", onMessage);
709
- socket.addEventListener("error", onError);
710
- socket.addEventListener("close", onClose);
711
- if (signal?.aborted === true)
712
- onAbort();
713
- });
714
- }
715
- finally {
716
- await refreshOwnedDescendants(web);
717
- }
718
- }
719
- function isAgentStateFrame(frame, sessionId) {
720
- return frame.session_id === sessionId &&
721
- frame.agent_id === "main" &&
722
- typeof frame.event_created_at === "string" &&
723
- Number.isFinite(Date.parse(frame.event_created_at)) &&
724
- (frame.status === "idle" || frame.status === "running") &&
725
- (frame.model === undefined || typeof frame.model === "string") &&
726
- (frame.thinking === undefined || typeof frame.thinking === "string") &&
727
- (frame.permission_mode === undefined ||
728
- frame.permission_mode === "manual" ||
729
- frame.permission_mode === "yolo" ||
730
- frame.permission_mode === "auto") &&
731
- typeof frame.plan_mode === "boolean" &&
732
- typeof frame.swarm_mode === "boolean" &&
733
- typeof frame.tower_mode === "boolean";
734
- }
735
- async function shutdownWeb(web, signal, failureCode) {
736
- await restData(web, "POST", "/api/v1/shutdown", undefined, signal, failureCode);
737
- const settlement = await waitForChildClose(web, signal, failureCode);
738
- if (!(await teardownOwnedChild(web))) {
739
- throw failure(failureCode, "swarm-activation.shutdown", "The Kimi web process tree did not become quiescent after shutdown.", { exit_code: settlement.exitCode, signal: settlement.signal, cleanup_summary: web.cleanupSummary ?? null });
740
- }
741
- if (web.processError || settlement.exitCode !== 0) {
742
- throw failure(failureCode, "swarm-activation.shutdown", "The Kimi web process did not exit cleanly after shutdown.", { exit_code: settlement.exitCode, signal: settlement.signal });
743
- }
744
- }
745
- async function waitForChildClose(web, signal, failureCode) {
746
- let timer;
747
- let onAbort;
748
- try {
749
- return await Promise.race([
750
- web.closePromise,
751
- new Promise((_resolve, reject) => {
752
- timer = setTimeout(() => {
753
- reject(failure(failureCode, "swarm-activation.shutdown", "Timed out waiting for the Kimi web process to shut down.", { timeout_ms: SHUTDOWN_TIMEOUT_MS }));
754
- }, SHUTDOWN_TIMEOUT_MS);
755
- onAbort = () => reject(cancelledFailure(failureCode, "swarm-activation.shutdown"));
756
- signal?.addEventListener("abort", onAbort, { once: true });
757
- if (signal?.aborted === true)
758
- onAbort();
759
- }),
760
- ]);
761
- }
762
- finally {
763
- if (timer !== undefined)
764
- clearTimeout(timer);
765
- if (onAbort !== undefined)
766
- signal?.removeEventListener("abort", onAbort);
767
- }
768
- }
769
- async function restData(web, method, route, body, signal, failureCode) {
770
- throwIfAborted(signal, failureCode, "swarm-activation.rest");
771
- await refreshOwnedDescendants(web);
772
- throwIfAborted(signal, failureCode, "swarm-activation.rest");
773
- const controller = new AbortController();
774
- let timedOut = false;
775
- const onAbort = () => controller.abort();
776
- const timer = setTimeout(() => {
777
- timedOut = true;
778
- controller.abort();
779
- }, REST_TIMEOUT_MS);
780
- signal?.addEventListener("abort", onAbort, { once: true });
781
- if (signal?.aborted === true)
782
- onAbort();
783
- try {
784
- const headers = { accept: "application/json", authorization: `Bearer ${web.token}` };
785
- if (body !== undefined)
786
- headers["content-type"] = "application/json";
787
- const response = await fetch(`${web.origin}${route}`, {
788
- method,
789
- headers,
790
- body: body === undefined ? undefined : JSON.stringify(body),
791
- redirect: "error",
792
- signal: controller.signal,
793
- });
794
- await refreshOwnedDescendants(web);
795
- if (!response.ok) {
796
- await response.body?.cancel().catch(() => undefined);
797
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST returned an unsuccessful HTTP status.", { route, http_status: response.status });
798
- }
799
- const text = await readBoundedResponse(response, failureCode, route);
800
- let envelope;
801
- try {
802
- envelope = JSON.parse(text);
803
- }
804
- catch {
805
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST returned malformed JSON.", { route });
806
- }
807
- if (!isRecord(envelope) || !("data" in envelope)) {
808
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST returned an invalid response envelope.", { route });
809
- }
810
- if (envelope.code !== 0) {
811
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST returned an unsuccessful business response.", {
812
- route,
813
- business_code: typeof envelope.code === "number" ? envelope.code : null,
814
- });
815
- }
816
- return envelope.data;
817
- }
818
- catch (error) {
819
- if (signal?.aborted === true)
820
- throw cancelledFailure(failureCode, "swarm-activation.rest");
821
- if (timedOut) {
822
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST timed out.", { route, timeout_ms: REST_TIMEOUT_MS });
823
- }
824
- if (error instanceof RuntimeError)
825
- throw error;
826
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST failed before a valid response was received.", { route });
827
- }
828
- finally {
829
- clearTimeout(timer);
830
- signal?.removeEventListener("abort", onAbort);
831
- }
832
- }
833
- async function readBoundedResponse(response, failureCode, route) {
834
- if (response.body === null) {
835
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST returned an empty response.", { route });
836
- }
837
- const reader = response.body.getReader();
838
- const chunks = [];
839
- let size = 0;
840
- while (true) {
841
- const { done, value } = await reader.read();
842
- if (done)
843
- break;
844
- if (value === undefined)
845
- continue;
846
- size += value.byteLength;
847
- if (size > REST_RESPONSE_MAX_BYTES) {
848
- await reader.cancel().catch(() => undefined);
849
- throw failure(failureCode, "swarm-activation.rest", "Kimi web REST response exceeded the bounded size limit.", { route, max_bytes: REST_RESPONSE_MAX_BYTES });
850
- }
851
- chunks.push(value);
852
- }
853
- const combined = new Uint8Array(size);
854
- let offset = 0;
855
- for (const chunk of chunks) {
856
- combined.set(chunk, offset);
857
- offset += chunk.byteLength;
858
- }
859
- return new TextDecoder().decode(combined);
860
- }
861
- async function requireSwarmJournal(kimiHome, identity, expected, signal, failureCode) {
862
- const stage = expected === "enter" ? "swarm-activation.journal" : "swarm-deactivation.journal";
863
- const journalPath = path.join(kimiHome, "sessions", identity.workspaceId, identity.sessionId, "agents", "main", "wire.jsonl");
864
- const deadline = Date.now() + JOURNAL_TIMEOUT_MS;
865
- let observed = "missing";
866
- while (true) {
867
- throwIfAborted(signal, failureCode, stage);
868
- observed = await readSwarmJournalState(journalPath);
869
- if (observed === expected)
870
- return;
871
- const remaining = deadline - Date.now();
872
- if (remaining <= 0) {
873
- throw failure(failureCode, stage, `The main-agent journal did not confirm swarm_mode.${expected === "enter" ? "enter with manual trigger" : "exit"}.`, { journal_state: observed, timeout_ms: JOURNAL_TIMEOUT_MS });
874
- }
875
- await delay(Math.min(JOURNAL_POLL_MS, remaining), signal, failureCode, stage);
876
- }
877
- }
878
- async function readSwarmJournalState(journalPath) {
879
- let handle;
880
- try {
881
- handle = await open(journalPath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0));
882
- }
883
- catch (error) {
884
- const code = error.code;
885
- return code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable";
886
- }
887
- try {
888
- const stats = await handle.stat({ bigint: true });
889
- if (!stats.isFile() || stats.size > BigInt(JOURNAL_MAX_BYTES))
890
- return "unreadable";
891
- const size = Number(stats.size);
892
- const buffer = Buffer.alloc(size);
893
- let offset = 0;
894
- while (offset < size) {
895
- const { bytesRead } = await handle.read(buffer, offset, size - offset, offset);
896
- if (bytesRead === 0)
897
- break;
898
- offset += bytesRead;
899
- }
900
- // Framed as kimi-code replays it. Replay stops at the first corrupt
901
- // terminated line, so no later record may confirm a state: fail closed.
902
- // An unparseable unterminated tail is truncation, which replay drops.
903
- let state = "missing";
904
- for await (const { line, parsed: record, terminated } of kimiJournalRecords([buffer.subarray(0, offset)])) {
905
- if (record === UNPARSEABLE_JOURNAL_LINE) {
906
- if (terminated || line.includes("swarm_mode."))
907
- return "unreadable";
908
- continue;
909
- }
910
- if (!isRecord(record))
911
- continue;
912
- if (record.type === "swarm_mode.enter") {
913
- state = record.trigger === "manual" ? "enter" : "other";
914
- }
915
- else if (record.type === "swarm_mode.exit") {
916
- state = "exit";
917
- }
918
- }
919
- return state;
920
- }
921
- catch {
922
- return "unreadable";
923
- }
924
- finally {
925
- await handle.close().catch(() => undefined);
926
- }
927
- }
928
- function startDescendantTracking(owned) {
929
- if (process.platform === "win32")
930
- return;
931
- owned.trackerPromise = (async () => {
932
- while (!owned.trackingStopped && !owned.exited) {
933
- await refreshOwnedDescendants(owned);
934
- if (owned.trackingStopped || owned.exited)
935
- break;
936
- await sleep(DESCENDANT_TRACK_INTERVAL_MS);
937
- }
938
- })();
939
- }
940
- async function stopDescendantTracking(owned) {
941
- owned.trackingStopped = true;
942
- await owned.trackerPromise;
943
- await owned.refreshPromise;
944
- }
945
- async function refreshOwnedDescendants(owned) {
946
- if (process.platform === "win32" || owned.exited)
947
- return;
948
- if (owned.refreshPromise !== undefined)
949
- return await owned.refreshPromise;
950
- const childPid = owned.child.pid;
951
- if (childPid === undefined) {
952
- owned.lastSnapshotComplete = true;
953
- return;
954
- }
955
- owned.refreshPromise = (async () => {
956
- const snapshot = await retryIncompleteCapture(() => captureDescendantIdentities(childPid));
957
- const previousRoot = owned.rootIdentity;
958
- if (snapshot.root !== undefined) {
959
- if (previousRoot === undefined) {
960
- owned.rootIdentity = snapshot.root;
961
- }
962
- else if (previousRoot.startToken !== snapshot.root.startToken) {
963
- owned.snapshotIncomplete = true;
964
- owned.lastSnapshotComplete = false;
965
- return;
966
- }
967
- }
968
- const seen = new Set(owned.descendants.map(identityKey));
969
- for (const identity of snapshot.identities) {
970
- const key = identityKey(identity);
971
- if (seen.has(key))
972
- continue;
973
- seen.add(key);
974
- owned.descendants.push(identity);
975
- }
976
- if (snapshot.complete && (snapshot.root !== undefined || previousRoot !== undefined)) {
977
- if (!owned.snapshotIncomplete)
978
- owned.lastSnapshotComplete = true;
979
- }
980
- else {
981
- owned.snapshotIncomplete = true;
982
- owned.lastSnapshotComplete = false;
983
- }
984
- try {
985
- owned.onRecoveryEvent?.({ kind: "web-processes", identities: [...(owned.rootIdentity ? [owned.rootIdentity] : []), ...owned.descendants], complete: owned.lastSnapshotComplete });
986
- }
987
- catch {
988
- owned.recoveryFailed = true;
989
- }
990
- })().finally(() => {
991
- owned.refreshPromise = undefined;
992
- });
993
- return await owned.refreshPromise;
994
- }
995
- async function teardownOwnedChild(owned) {
996
- const quiescent = await teardownOwnedChildInner(owned);
997
- if (quiescent && !owned.recoveryFailed) {
998
- owned.onRecoveryEvent?.({ kind: "web-exit" });
999
- return true;
1000
- }
1001
- return false;
1002
- }
1003
- async function teardownOwnedChildInner(owned) {
1004
- await stopDescendantTracking(owned);
1005
- const childPid = owned.child.pid;
1006
- if (childPid === undefined)
1007
- return true;
1008
- try {
1009
- if (process.platform === "win32") {
1010
- if (!owned.exited) {
1011
- try {
1012
- owned.child.kill("SIGTERM");
1013
- }
1014
- catch {
1015
- }
1016
- }
1017
- const exited = await waitForProcessTreeExit([], ESCALATION_MS, {
1018
- isRootAlive: () => !owned.exited,
1019
- });
1020
- if (!exited) {
1021
- try {
1022
- owned.child.kill("SIGKILL");
1023
- }
1024
- catch {
1025
- }
1026
- return await waitForProcessTreeExit([], POST_KILL_QUIESCENCE_MS, {
1027
- isRootAlive: () => !owned.exited,
1028
- });
1029
- }
1030
- return true;
1031
- }
1032
- if (!owned.exited)
1033
- await refreshOwnedDescendants(owned);
1034
- const identities = owned.descendants;
1035
- await signalCapturedTree(owned, childPid, identities, "SIGTERM");
1036
- const exited = await waitForProcessTreeExit(identities, ESCALATION_MS, {
1037
- isRootAlive: () => !owned.exited,
1038
- });
1039
- let quiescent = exited && await processGroupsQuiescent(owned, childPid);
1040
- let killWaitExited;
1041
- if (!quiescent) {
1042
- await signalCapturedTree(owned, childPid, identities, "SIGKILL");
1043
- killWaitExited = await waitForProcessTreeExit(identities, POST_KILL_QUIESCENCE_MS, {
1044
- isRootAlive: () => !owned.exited,
1045
- });
1046
- quiescent = killWaitExited && await processGroupsQuiescent(owned, childPid);
1047
- }
1048
- owned.cleanupSummary = [
1049
- `root_exited=${owned.exited}`,
1050
- `first_wait_exited=${exited}`,
1051
- `kill_wait_exited=${killWaitExited ?? "not-run"}`,
1052
- `groups_quiescent=${quiescent}`,
1053
- `last_snapshot_complete=${owned.lastSnapshotComplete}`,
1054
- `descendants=${identities.length}`,
1055
- ].join(", ");
1056
- return quiescent && owned.lastSnapshotComplete;
1057
- }
1058
- catch {
1059
- if (!owned.exited) {
1060
- if (process.platform !== "win32")
1061
- trySignalPid(-childPid, "SIGKILL");
1062
- try {
1063
- owned.child.kill("SIGKILL");
1064
- }
1065
- catch {
1066
- }
1067
- }
1068
- return false;
1069
- }
1070
- }
1071
- async function processGroupsQuiescent(owned, childPid) {
1072
- const groupIds = new Set([childPid]);
1073
- for (const identity of owned.descendants)
1074
- groupIds.add(identity.processGroupId);
1075
- const scan = await retryIncompleteCapture(async () => {
1076
- const members = await collectProcessGroupsIdentities([...groupIds]);
1077
- return { members, complete: members !== undefined };
1078
- });
1079
- return scan.members !== undefined && scan.members.every((identity) => /^[ZX]/i.test(identity.state.trim()));
1080
- }
1081
- async function captureDescendantIdentities(childPid) {
1082
- let timer;
1083
- try {
1084
- const snapshot = await Promise.race([
1085
- Promise.all([
1086
- collectDescendantIdentities(childPid),
1087
- probeProcessIdentity(childPid),
1088
- ]),
1089
- new Promise((resolve) => {
1090
- timer = setTimeout(() => resolve(null), DESCENDANT_SNAPSHOT_TIMEOUT_MS);
1091
- }),
1092
- ]);
1093
- if (snapshot === null)
1094
- return { identities: [], complete: false, timedOut: true };
1095
- const [collected, rootProbe] = snapshot;
1096
- const identities = [];
1097
- const seen = new Set();
1098
- for (const identity of collected) {
1099
- const key = identityKey(identity);
1100
- if (Number.isInteger(identity.pid) &&
1101
- identity.pid > 0 &&
1102
- identity.pid !== childPid &&
1103
- Number.isInteger(identity.processGroupId) &&
1104
- identity.processGroupId > 0 &&
1105
- identity.startToken.length > 0 &&
1106
- !seen.has(key)) {
1107
- seen.add(key);
1108
- identities.push({ ...identity });
1109
- }
1110
- }
1111
- return { identities, complete: rootProbe.complete, root: rootProbe.identity };
1112
- }
1113
- catch {
1114
- return { identities: [], complete: false };
1115
- }
1116
- finally {
1117
- if (timer !== undefined)
1118
- clearTimeout(timer);
1119
- }
1120
- }
1121
- function identityKey(identity) {
1122
- return `${identity.pid}:${identity.startToken}:${identity.processGroupId}`;
1123
- }
1124
- async function signalCapturedTree(owned, childPid, identities, signal) {
1125
- if (!owned.exited) {
1126
- trySignalPid(-childPid, signal);
1127
- try {
1128
- owned.child.kill(signal);
1129
- }
1130
- catch {
1131
- }
1132
- }
1133
- const pidValidation = await revalidateProcessIdentities(identities, {
1134
- timeoutMs: IDENTITY_REVALIDATION_TIMEOUT_MS,
1135
- });
1136
- for (const identity of pidValidation.identities)
1137
- trySignalPid(identity.pid, signal);
1138
- const activeGroupIds = new Set(pidValidation.identities.map((identity) => identity.processGroupId));
1139
- if (!owned.exited)
1140
- activeGroupIds.delete(childPid);
1141
- for (const processGroupId of activeGroupIds)
1142
- trySignalPid(-processGroupId, signal);
1143
- }
1144
- function trySignalPid(pid, signal) {
1145
- try {
1146
- process.kill(pid, signal);
1147
- }
1148
- catch {
1149
- }
1150
- }
1151
- function throwIfAborted(signal, code, stage) {
1152
- if (signal?.aborted === true)
1153
- throw cancelledFailure(code, stage);
1154
- }
1155
- function cancelledFailure(code, stage) {
1156
- return failure(code, stage, "Swarm web lifecycle cancelled by the caller.", { cancelled: true });
1157
- }
1158
- function failure(code, stage, message, details = {}) {
1159
- return new RuntimeError(code, message, stage, { details });
1160
- }
1161
- function asSafeFailure(error, code, stage) {
1162
- if (error instanceof RuntimeError)
1163
- return error;
1164
- return failure(code, stage, "The swarm web lifecycle failed without a safe diagnostic payload.");
1165
- }
1166
- function errorReference(error) {
1167
- return {
1168
- code: error.code,
1169
- stage: error.stage,
1170
- cancelled: error.details.cancelled === true,
1171
- };
1172
- }
1173
- function validPathId(value) {
1174
- return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,255}$/.test(value);
1175
- }
1176
- function isRecord(value) {
1177
- return typeof value === "object" && value !== null && !Array.isArray(value);
1178
- }
1179
- async function delay(ms, signal, code, stage) {
1180
- throwIfAborted(signal, code, stage);
1181
- await new Promise((resolve, reject) => {
1182
- const timer = setTimeout(() => {
1183
- signal?.removeEventListener("abort", onAbort);
1184
- resolve();
1185
- }, ms);
1186
- const onAbort = () => {
1187
- clearTimeout(timer);
1188
- reject(cancelledFailure(code, stage));
1189
- };
1190
- signal?.addEventListener("abort", onAbort, { once: true });
1191
- if (signal?.aborted === true)
1192
- onAbort();
1193
- });
1194
- }