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,41 +0,0 @@
1
- import { RuntimeError } from "../errors.js";
2
- import { isRecord } from "../util.js";
3
- const ALLOWED_DECISIONS = new Set(["ALLOW", "BLOCK"]);
4
- const ALLOWED_SEVERITIES = new Set(["low", "medium", "high"]);
5
- const ALLOWED_CONFIDENCE = new Set(["low", "medium", "high"]);
6
- export function parseReviewGateOutput(text) {
7
- let parsed;
8
- try {
9
- parsed = JSON.parse(text);
10
- }
11
- catch (error) {
12
- throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", `Review gate output is not valid JSON: ${error.message}`, "review_gate.parse", { cause: error });
13
- }
14
- if (!isRecord(parsed)) {
15
- throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", "Review gate output must be a JSON object.", "review_gate.parse");
16
- }
17
- const { decision, confidence, summary, issues } = parsed;
18
- if (!ALLOWED_DECISIONS.has(String(decision)) ||
19
- !ALLOWED_CONFIDENCE.has(String(confidence)) ||
20
- typeof summary !== "string" ||
21
- !Array.isArray(issues)) {
22
- throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", "Review gate output must contain decision, confidence, summary, and issues.", "review_gate.parse");
23
- }
24
- return {
25
- decision: decision,
26
- confidence: confidence,
27
- summary,
28
- issues: issues.map((issue, index) => normalizeIssue(issue, index)),
29
- };
30
- }
31
- function normalizeIssue(issue, index) {
32
- if (!isRecord(issue)) {
33
- throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", `Review gate issue ${index + 1} must be an object.`, "review_gate.parse");
34
- }
35
- if (typeof issue.title !== "string" ||
36
- typeof issue.body !== "string" ||
37
- !ALLOWED_SEVERITIES.has(String(issue.severity))) {
38
- throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", `Review gate issue ${index + 1} is missing a required field.`, "review_gate.parse");
39
- }
40
- return issue;
41
- }
@@ -1,202 +0,0 @@
1
- import { constants } from "node:fs";
2
- import { lstat, open, opendir, realpath } from "node:fs/promises";
3
- import path from "node:path";
4
- import { digestPrompt } from "./jobs.js";
5
- // Total entries visited across both enumeration levels. The cap guards against
6
- // a pathological tree rather than budgeting normal store size. opendir streams,
7
- // so entries are not buffered. Dot-entries (`.index-dirty`, `.index-cache`) are
8
- // upstream index state, never workspaces, and are skipped without being counted.
9
- // Directories whose mtime predates the spawn cannot have been created by this
10
- // run and are skipped before any read, so the byte budget scales with concurrent
11
- // activity, not with store size.
12
- const DIR_ENUM_CAP = 65_536;
13
- const STATE_MAX_BYTES = 1024 * 1024;
14
- const JOURNAL_PREFIX_BYTES = 4 * 1024 * 1024; // The prompt is argv-bounded (< 1 MiB); the first user message follows a few config records.
15
- const SCAN_MAX_BYTES = 64 * 1024 * 1024;
16
- const MTIME_SLACK_MS = 1000; // Filesystems with coarse mtime granularity.
17
- const SESSION_ID = /^session_[0-9a-f-]{36}$/;
18
- /** Metadata recovery only, never a substitute for resume lineage/plan scans.
19
- * A capped or unreadable enumeration cannot establish uniqueness and refuses;
20
- * skipping symlinked or dot entries is not partial — neither can be a session
21
- * the child created.
22
- *
23
- * A candidate is bound to THIS job by content, not only by time: the first
24
- * user message in the session's main journal must carry a text item whose
25
- * sha256 equals the caller-supplied digest of the exact `-p` argument. Native
26
- * goal print stores the unwrapped objective, so the smoke recovery control
27
- * supplies that digest. Production pursue does not perform store recovery. Time and
28
- * cwd alone would admit a concurrent TUI session, another host's finished job
29
- * (host-local stores cannot see each other's session ids), or a `state.json`
30
- * planted by repository code running under rescue. The digest is not unique
31
- * on its own either (the same prompt can run twice), so the window and the
32
- * exactly-one rule stay in force. */
33
- export async function recoverSessionIdFromStore(options) {
34
- const entryCap = options.entryCap ?? DIR_ENUM_CAP;
35
- let entries = 0;
36
- let bytes = 0;
37
- let digestMismatches = 0;
38
- let missingJournals = 0;
39
- const candidates = [];
40
- const capped = new Error("enumeration_capped");
41
- async function* directories(dir) {
42
- if ((await lstat(dir)).isSymbolicLink())
43
- throw new Error("unreadable");
44
- const handle = await opendir(dir);
45
- for await (const entry of handle) {
46
- if (entry.name.startsWith("."))
47
- continue;
48
- if (++entries > entryCap)
49
- throw capped;
50
- // A symlinked entry is never a session the child created; skipping it
51
- // keeps one stray link from disabling recovery host-wide. Directories
52
- // we descend are still lstat-anchored above.
53
- if (entry.isSymbolicLink())
54
- continue;
55
- if (entry.isDirectory())
56
- yield entry.name;
57
- }
58
- }
59
- // Bounded no-follow read of a regular file. Returns undefined when the file
60
- // is absent; throws "unreadable" for anything that is not a plain file. With
61
- // `prefix`, a larger file yields its first `maxBytes` instead of refusing.
62
- async function readBounded(file, maxBytes, prefix = false) {
63
- let handle;
64
- try {
65
- handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
66
- }
67
- catch (error) {
68
- if (error.code === "ENOENT")
69
- return undefined;
70
- throw error;
71
- }
72
- try {
73
- const stat = await handle.stat();
74
- if (!stat.isFile() || (stat.size > maxBytes && !prefix))
75
- throw new Error("unreadable");
76
- const size = Math.min(stat.size, maxBytes);
77
- bytes += size;
78
- if (bytes > SCAN_MAX_BYTES)
79
- throw capped;
80
- const buffer = Buffer.alloc(size);
81
- let offset = 0;
82
- while (offset < buffer.length) {
83
- const read = await handle.read(buffer, offset, buffer.length - offset, offset);
84
- if (!read.bytesRead)
85
- break;
86
- offset += read.bytesRead;
87
- }
88
- return buffer.subarray(0, offset);
89
- }
90
- finally {
91
- await handle.close();
92
- }
93
- }
94
- try {
95
- if (!Number.isFinite(options.spawnedAt) || !Number.isFinite(options.settledAt) ||
96
- options.settledAt < options.spawnedAt || !/^[0-9a-f]{64}$/.test(options.promptDigest)) {
97
- return { reason: "none" };
98
- }
99
- const cwd = await realpath(options.cwd);
100
- const sessions = path.join(options.kimiHome, "sessions");
101
- // Missing nested dirs mean an incomplete scan; only a missing root is normal.
102
- try {
103
- await lstat(sessions);
104
- }
105
- catch (error) {
106
- if (error.code === "ENOENT")
107
- return { reason: "none" };
108
- throw error;
109
- }
110
- for await (const workspace of directories(sessions)) {
111
- const workspacePath = path.join(sessions, workspace);
112
- for await (const session of directories(workspacePath)) {
113
- if (!SESSION_ID.test(session))
114
- continue;
115
- const sessionPath = path.join(workspacePath, session);
116
- // A directory this run created was modified at or after the spawn.
117
- if ((await lstat(sessionPath)).mtimeMs < options.spawnedAt - MTIME_SLACK_MS)
118
- continue;
119
- const raw = await readBounded(path.join(sessionPath, "state.json"), STATE_MAX_BYTES);
120
- if (!raw)
121
- continue;
122
- let state;
123
- try {
124
- state = JSON.parse(raw.toString("utf8"));
125
- }
126
- catch {
127
- continue;
128
- }
129
- if (!state || typeof state !== "object")
130
- continue;
131
- const value = state;
132
- // The child writes createdAt after the parent stamped spawnedAt on the
133
- // same clock, so causality orders them; no pre-spawn slack is justified.
134
- if (value.version !== 2 || typeof value.cwd !== "string" || !path.isAbsolute(value.cwd) ||
135
- typeof value.id !== "string" || !SESSION_ID.test(value.id) || value.id !== session ||
136
- typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt) ||
137
- value.createdAt < options.spawnedAt || value.createdAt > options.settledAt)
138
- continue;
139
- let stateCwd;
140
- try {
141
- stateCwd = await realpath(value.cwd);
142
- }
143
- catch {
144
- continue;
145
- }
146
- if (stateCwd !== cwd || options.store.hasSessionId(value.id, options.jobId))
147
- continue;
148
- const journal = await readBounded(path.join(sessionPath, "agents", "main", "wire.jsonl"), JOURNAL_PREFIX_BYTES, true);
149
- if (!journal) {
150
- missingJournals += 1;
151
- continue;
152
- }
153
- // A prefix cut mid-record must never be parsed as a complete line.
154
- const text = journal.length === JOURNAL_PREFIX_BYTES
155
- ? journal.subarray(0, journal.lastIndexOf(0x0a) + 1).toString("utf8") : journal.toString("utf8");
156
- if (!firstUserMessageMatches(text, options.promptDigest)) {
157
- digestMismatches += 1;
158
- continue;
159
- }
160
- candidates.push(value.id);
161
- }
162
- }
163
- if (candidates.length === 1)
164
- return { sessionId: candidates[0] };
165
- if (candidates.length > 1)
166
- return { reason: `ambiguous:${candidates.length}` };
167
- if (digestMismatches > 0)
168
- return { reason: `digest_mismatch:${digestMismatches}` };
169
- return { reason: missingJournals > 0 ? `journal_missing:${missingJournals}` : "none" };
170
- }
171
- catch (error) {
172
- return { reason: error === capped ? "enumeration_capped" : "unreadable" };
173
- }
174
- }
175
- /** True when the FIRST user message in a native-v2 main journal carries a
176
- * text item equal to the prompt the job spawned with. Later user turns are
177
- * never consulted: only the opening prompt binds a session to its spawn. */
178
- export function firstUserMessageMatches(journal, promptDigest) {
179
- for (const line of journal.split("\n")) {
180
- if (!line.trim())
181
- continue;
182
- let record;
183
- try {
184
- record = JSON.parse(line);
185
- }
186
- catch {
187
- continue;
188
- }
189
- if (!record || typeof record !== "object")
190
- continue;
191
- const message = record.message;
192
- if (!message || typeof message !== "object" || message.role !== "user")
193
- continue;
194
- const content = message.content;
195
- if (!Array.isArray(content))
196
- return false;
197
- return content.some((item) => item && typeof item === "object" && item.type === "text" &&
198
- typeof item.text === "string" &&
199
- digestPrompt(item.text) === promptDigest);
200
- }
201
- return false;
202
- }
@@ -1,313 +0,0 @@
1
- import { basename, isAbsolute, relative, resolve } from "node:path";
2
- import path from "node:path";
3
- import { constants } from "node:fs";
4
- import { randomUUID } from "node:crypto";
5
- import { lstat, mkdir, open, realpath, rename, rm, writeFile } from "node:fs/promises";
6
- import { resolveKimiHome } from "./kimi-home.js";
7
- export const KIMI_SESSION_TITLE_MAX_LENGTH = 120;
8
- const SESSION_INDEX_MAX_BYTES = 16 * 1024 * 1024;
9
- const SESSION_INDEX_LINE_MAX_BYTES = 1024 * 1024;
10
- const SESSION_STATE_MAX_BYTES = 1024 * 1024;
11
- const DISPLAY_NAMES = {
12
- ask: "Ask",
13
- review: "Review",
14
- challenge: "Challenge",
15
- rescue: "Rescue",
16
- pursue: "Pursue",
17
- swarm: "Swarm",
18
- "swarm-write": "Swarm Write",
19
- };
20
- export function buildKimiSessionTitle(command, summary) {
21
- const prefix = `Kimi ${DISPLAY_NAMES[command] ?? "Session"}`;
22
- const normalized = promptMetadataText(summary ?? "") ?? "";
23
- return shortenForTitle(normalized ? `${prefix}: ${normalized}` : prefix, KIMI_SESSION_TITLE_MAX_LENGTH);
24
- }
25
- export function normalizeTitleFragment(text) {
26
- return text
27
- .replace(/[\u0000-\u001f\u007f]/g, " ")
28
- .replace(/\s+/g, " ")
29
- .trim();
30
- }
31
- /** Mirrors kimi-code 2.0.0 promptMetadataTextFromText: redact BEFORE truncating. */
32
- export function promptMetadataText(text) {
33
- const sanitized = sanitizePromptMetadata(text);
34
- return sanitized ? sanitized.slice(0, 4000) : undefined;
35
- }
36
- function sanitizePromptMetadata(text) {
37
- return text
38
- .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi, "[redacted]")
39
- .replace(/\b(authorization)\s*:\s*bearer\s+\S+/gi, "$1: Bearer [redacted]")
40
- .replace(/\b(api[_-]?key|token|secret|password|passwd|pwd)\b\s*[:=]\s*(?:"[^"]*"|'[^']*'|\S+)/gi, "$1=[redacted]")
41
- .replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
42
- .replace(/\b[A-Za-z0-9][A-Za-z0-9+/=_-]{39,}\b/g, "[redacted]")
43
- .replace(/\p{Cc}+/gu, " ")
44
- .replace(/\s+/g, " ")
45
- .trim();
46
- }
47
- const OWN_PROMPT_MIN_PREFIX = 40;
48
- /**
49
- * Earlier plugin releases stored the submitted prompt redacted, whitespace-
50
- * collapsed and capped, so compare normalized forms. A prefix relation counts
51
- * only when the shorter side is long enough that short native text never does.
52
- */
53
- function isOwnPrompt(existing, ownPrompts) {
54
- const current = normalizeTitleFragment(existing);
55
- if (!current)
56
- return false;
57
- return ownPrompts.some((prompt) => [normalizeTitleFragment(prompt), sanitizePromptMetadata(prompt)].some((own) => own.length > 0 && (current === own ||
58
- (Math.min(own.length, current.length) >= OWN_PROMPT_MIN_PREFIX && (own.startsWith(current) || current.startsWith(own))))));
59
- }
60
- export function shortenForTitle(text, maxLength) {
61
- const normalized = normalizeTitleFragment(text);
62
- if (normalized.length <= maxLength) {
63
- return normalized;
64
- }
65
- return `${normalized.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
66
- }
67
- export async function syncKimiSessionTitle(options) {
68
- const sessionId = options.sessionId?.trim();
69
- if (!sessionId) {
70
- return "missing-session-id";
71
- }
72
- if (sessionId === "." || sessionId === ".." || /[/\\\p{Cc}]/u.test(sessionId)) {
73
- warn(options.stderr, `session metadata sync skipped for ${formatSessionIdForLog(sessionId)}: unsafe session id`);
74
- return "unsafe-entry";
75
- }
76
- const kimiHome = resolveKimiHome(options.env, options.cwd);
77
- const sessionsRoot = path.join(kimiHome, "sessions");
78
- const indexPath = path.join(kimiHome, "session_index.jsonl");
79
- const indexRead = await readUtf8FileCapped(indexPath, SESSION_INDEX_MAX_BYTES);
80
- if (!indexRead.ok) {
81
- if (indexRead.reason === "too-large") {
82
- warn(options.stderr, `session title sync skipped: session_index.jsonl is too large`);
83
- }
84
- return "missing-index";
85
- }
86
- const entry = findSessionIndexEntry(indexRead.text, sessionId, options.stderr);
87
- if (!entry) {
88
- return "missing-entry";
89
- }
90
- const safeSessionId = formatSessionIdForLog(sessionId);
91
- const sessionDir = resolve(entry.sessionDir);
92
- if (!isAbsolute(entry.sessionDir) ||
93
- !isPathInside(sessionsRoot, sessionDir) ||
94
- basename(sessionDir) !== sessionId) {
95
- warn(options.stderr, `session title sync skipped for ${safeSessionId}: unsafe session index entry`);
96
- return "unsafe-entry";
97
- }
98
- if (!(await isSafeSessionsRoot(sessionsRoot))) {
99
- warn(options.stderr, `session title sync skipped for ${safeSessionId}: unsafe sessions root`);
100
- return "unsafe-entry";
101
- }
102
- if (!(await isRealPathInside(sessionsRoot, sessionDir))) {
103
- warn(options.stderr, `session title sync skipped for ${safeSessionId}: unsafe session index target`);
104
- return "unsafe-entry";
105
- }
106
- const statePath = path.join(sessionDir, "state.json");
107
- const stateFileMode = await readSafeStateFileMode(statePath, options.stderr, sessionId);
108
- if (stateFileMode === null) {
109
- return "unsafe-entry";
110
- }
111
- let parsed;
112
- const stateRead = await readUtf8FileCapped(statePath, SESSION_STATE_MAX_BYTES);
113
- if (!stateRead.ok) {
114
- const reason = stateRead.reason === "too-large" ? "oversized state.json" : "missing or invalid state.json";
115
- warn(options.stderr, `session title sync skipped for ${safeSessionId}: ${reason}`);
116
- return "missing-state";
117
- }
118
- try {
119
- parsed = JSON.parse(stateRead.text);
120
- }
121
- catch {
122
- warn(options.stderr, `session title sync skipped for ${safeSessionId}: missing or invalid state.json`);
123
- return "missing-state";
124
- }
125
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
126
- warn(options.stderr, `session title sync skipped for ${safeSessionId}: invalid state.json shape`);
127
- return "invalid-state";
128
- }
129
- const state = parsed;
130
- const nativeV2 = state.version === 2;
131
- if (options.requireNativeV2 && !nativeV2)
132
- return "unsupported-state";
133
- if (nativeV2 && typeof state.id === "string" && state.id !== sessionId)
134
- return "invalid-state";
135
- // Custom-title normalization also recognizes titleKind and the older customTitle.
136
- const customTitle = state.isCustomTitle === true || state.titleKind === "custom" ||
137
- (typeof state.customTitle === "string" && state.customTitle.trim().length > 0);
138
- const generatedTitle = state.titleKind === "generated";
139
- const next = { ...state };
140
- const preview = options.promptText === undefined ? undefined : promptMetadataText(options.promptText);
141
- const blankPreview = typeof state.lastPrompt !== "string" || !state.lastPrompt.trim();
142
- if (nativeV2 && preview && (blankPreview || !options.ownPrompts || isOwnPrompt(state.lastPrompt, options.ownPrompts))) {
143
- next.lastPrompt = preview;
144
- }
145
- const replacedPreview = !blankPreview && next.lastPrompt !== state.lastPrompt;
146
- if (!options.preserveTitle && !customTitle && !generatedTitle) {
147
- next.title = promptMetadataText(options.title)?.slice(0, KIMI_SESSION_TITLE_MAX_LENGTH) ?? "Kimi Session";
148
- // Native UI generation must remain eligible; a deterministic fallback is not
149
- // a human rename. Legacy engines retain their existing custom-title behavior.
150
- next.isCustomTitle = !nativeV2;
151
- if (nativeV2)
152
- next.titleKind = "replaceable";
153
- }
154
- const changed = JSON.stringify(next) !== JSON.stringify(state);
155
- if (options.dryRun)
156
- return !changed ? "unchanged" : replacedPreview ? "would-replace-preview" : "would-update";
157
- try {
158
- if (changed && !(await writeStateFileAtomic(statePath, `${JSON.stringify(next, null, 2)}\n`, stateFileMode, stateRead.text))) {
159
- warn(options.stderr, "session metadata sync skipped: state changed concurrently; retry after the session is idle");
160
- return "state-changed";
161
- }
162
- }
163
- catch {
164
- warn(options.stderr, `session metadata sync skipped for ${safeSessionId}: failed to write state.json`);
165
- return "write-failed";
166
- }
167
- if (nativeV2) {
168
- try {
169
- // Also re-mark unchanged metadata, so a previous invalidation failure is
170
- // repairable without rewriting the state or changing a manual title.
171
- await markSessionIndexDirty(sessionsRoot, sessionId);
172
- }
173
- catch {
174
- warn(options.stderr, `session metadata saved for ${safeSessionId}, but index notification failed; retry repair-sessions --apply when idle`);
175
- return "index-failed";
176
- }
177
- }
178
- if (changed)
179
- return replacedPreview ? "preview-replaced" : "updated";
180
- return customTitle && !options.preserveTitle ? "custom-title" : "unchanged";
181
- }
182
- function findSessionIndexEntry(indexText, sessionId, stderr) {
183
- for (const line of indexText.split(/\r?\n/)) {
184
- const trimmed = line.trim();
185
- if (!trimmed)
186
- continue;
187
- if (Buffer.byteLength(trimmed, "utf8") > SESSION_INDEX_LINE_MAX_BYTES) {
188
- warn(stderr, `session title sync skipped oversized session index line`);
189
- continue;
190
- }
191
- let parsed;
192
- try {
193
- parsed = JSON.parse(trimmed);
194
- }
195
- catch {
196
- warn(stderr, `session title sync skipped malformed session index line`);
197
- continue;
198
- }
199
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
200
- continue;
201
- }
202
- const entry = parsed;
203
- if (entry.sessionId === sessionId &&
204
- typeof entry.sessionDir === "string") {
205
- return {
206
- sessionId,
207
- sessionDir: entry.sessionDir,
208
- };
209
- }
210
- }
211
- return null;
212
- }
213
- function isPathInside(parent, child) {
214
- const rel = relative(resolve(parent), resolve(child));
215
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
216
- }
217
- async function isSafeSessionsRoot(sessionsRoot) {
218
- try {
219
- const stats = await lstat(sessionsRoot);
220
- return stats.isDirectory() && !stats.isSymbolicLink();
221
- }
222
- catch {
223
- return false;
224
- }
225
- }
226
- async function isRealPathInside(parent, child) {
227
- try {
228
- let current = parent;
229
- for (const part of relative(parent, child).split(path.sep)) {
230
- current = path.join(current, part);
231
- const info = await lstat(current);
232
- if (!info.isDirectory() || info.isSymbolicLink())
233
- return false;
234
- }
235
- const realParent = await realpath(parent);
236
- const realChild = await realpath(child);
237
- return isPathInside(realParent, realChild);
238
- }
239
- catch {
240
- return false;
241
- }
242
- }
243
- async function readSafeStateFileMode(statePath, stderr, sessionId) {
244
- try {
245
- const stats = await lstat(statePath);
246
- if (stats.isSymbolicLink() || !stats.isFile()) {
247
- warn(stderr, `session title sync skipped for ${formatSessionIdForLog(sessionId)}: unsafe state.json`);
248
- return null;
249
- }
250
- return stats.mode & 0o777;
251
- }
252
- catch {
253
- return 0o600;
254
- }
255
- }
256
- async function writeStateFileAtomic(statePath, contents, mode, expected) {
257
- const tmpPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`;
258
- try {
259
- await writeFile(tmpPath, contents, { encoding: "utf8", mode, flag: "wx" });
260
- const current = await readUtf8FileCapped(statePath, SESSION_STATE_MAX_BYTES);
261
- if (!current.ok || current.text !== expected)
262
- return false;
263
- await rename(tmpPath, statePath);
264
- return true;
265
- }
266
- finally {
267
- await rm(tmpPath, { force: true }).catch(() => { });
268
- }
269
- }
270
- async function markSessionIndexDirty(sessionsRoot, sessionId) {
271
- if (!(await isSafeSessionsRoot(sessionsRoot)))
272
- throw new Error("Unsafe sessions root");
273
- const dir = path.join(sessionsRoot, ".index-dirty");
274
- await mkdir(dir, { mode: 0o700 }).catch((error) => {
275
- if (error.code !== "EEXIST")
276
- throw error;
277
- });
278
- if (!(await isRealPathInside(sessionsRoot, dir)))
279
- throw new Error("Unsafe dirty journal");
280
- // Upstream splits at the LAST dot; the unique suffix must contain no dots.
281
- const file = await open(path.join(dir, `${sessionId}.${Date.now()}-${randomUUID()}`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
282
- await file.close();
283
- }
284
- async function readUtf8FileCapped(filePath, maxBytes) {
285
- let file;
286
- try {
287
- file = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
288
- }
289
- catch {
290
- return { ok: false, reason: "missing" };
291
- }
292
- try {
293
- const stats = await file.stat();
294
- if (!stats.isFile()) {
295
- return { ok: false, reason: "not-file" };
296
- }
297
- if (stats.size > maxBytes) {
298
- return { ok: false, reason: "too-large" };
299
- }
300
- const buffer = Buffer.alloc(stats.size);
301
- const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
302
- return { ok: true, text: buffer.subarray(0, bytesRead).toString("utf8") };
303
- }
304
- finally {
305
- await file.close();
306
- }
307
- }
308
- function formatSessionIdForLog(sessionId) {
309
- return JSON.stringify(normalizeTitleFragment(sessionId));
310
- }
311
- function warn(stderr, message) {
312
- stderr?.write(`[kimi-plugin-cc] ${message}.\n`);
313
- }