kimi-plugin-cc 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -14
  3. package/README.md +428 -572
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +4 -2
  7. package/dist/cli-client.js +105 -66
  8. package/dist/commands/ask.js +27 -12
  9. package/dist/commands/cancel.js +4 -13
  10. package/dist/commands/cli-helpers.js +1 -1
  11. package/dist/commands/pursue.js +3 -2
  12. package/dist/commands/registry.js +7 -26
  13. package/dist/commands/repair-sessions.js +7 -4
  14. package/dist/commands/replay.js +4 -3
  15. package/dist/commands/rescue.js +17 -5
  16. package/dist/commands/review.js +18 -5
  17. package/dist/commands/setup.js +277 -262
  18. package/dist/commands/swarm.js +20 -7
  19. package/dist/companion.js +142 -18
  20. package/dist/help.js +11 -7
  21. package/dist/hook-escape.js +7 -16
  22. package/dist/hooks/approval-hook.js +1762 -124
  23. package/dist/hooks/approval-policy.js +15 -10
  24. package/dist/hooks/config-safety.js +15 -24
  25. package/dist/hooks/hook-timing.js +1 -1
  26. package/dist/hooks/install-paths.js +179 -107
  27. package/dist/hooks/install.js +44 -166
  28. package/dist/hooks/managed-block.js +44 -95
  29. package/dist/job-store.js +117 -49
  30. package/dist/jobs.js +53 -1
  31. package/dist/kimi-engine.js +68 -92
  32. package/dist/kimi-errors.js +1 -1
  33. package/dist/kimi-journal.js +3 -2
  34. package/dist/kimi-releases.js +28 -49
  35. package/dist/kimi-timeouts.js +1 -15
  36. package/dist/kimi-version-probe.js +24 -72
  37. package/dist/logging.js +12 -7
  38. package/dist/mcp/binding.js +13 -4
  39. package/dist/mcp/job-control.js +386 -89
  40. package/dist/mcp/launcher.js +1 -1
  41. package/dist/mcp/operations.js +387 -193
  42. package/dist/mcp/protocol.js +116 -27
  43. package/dist/mcp/skills.js +130 -0
  44. package/dist/mcp/stdio.js +15 -2
  45. package/dist/native-v2-preflight.js +127 -35
  46. package/dist/parsing.js +45 -11
  47. package/dist/paths.js +20 -10
  48. package/dist/plugin-data.js +28 -83
  49. package/dist/read-scope.js +2 -2
  50. package/dist/render.js +13 -38
  51. package/dist/session-references.js +216 -0
  52. package/dist/session-title.js +1 -1
  53. package/dist/surface-routing.js +92 -5
  54. package/dist/swarm-activation.js +26 -137
  55. package/dist/version.js +1 -1
  56. package/docs/migration.md +45 -227
  57. package/docs/models.md +24 -66
  58. package/docs/safety.md +195 -400
  59. package/docs/session-visibility.md +24 -14
  60. package/docs/swarm-recovery.md +26 -20
  61. package/dsh/index.json +54 -0
  62. package/mcp_config.json +10 -0
  63. package/package.json +23 -82
  64. package/plugin.json +19 -0
  65. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  66. package/plugins/kimi-codex/.mcp.json +2 -3
  67. package/plugins/kimi-codex/dist/background-spawn.js +4 -2
  68. package/plugins/kimi-codex/dist/cli-client.js +105 -66
  69. package/plugins/kimi-codex/dist/commands/ask.js +27 -12
  70. package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
  71. package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
  72. package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
  73. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  74. package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
  75. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  76. package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
  77. package/plugins/kimi-codex/dist/commands/review.js +18 -5
  78. package/plugins/kimi-codex/dist/commands/setup.js +277 -262
  79. package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
  80. package/plugins/kimi-codex/dist/companion.js +142 -18
  81. package/plugins/kimi-codex/dist/help.js +11 -7
  82. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  83. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
  84. package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
  85. package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
  86. package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
  87. package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
  88. package/plugins/kimi-codex/dist/hooks/install.js +44 -166
  89. package/plugins/kimi-codex/dist/hooks/managed-block.js +44 -95
  90. package/plugins/kimi-codex/dist/job-store.js +117 -49
  91. package/plugins/kimi-codex/dist/jobs.js +53 -1
  92. package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
  93. package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
  94. package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
  95. package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
  96. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
  97. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
  98. package/plugins/kimi-codex/dist/logging.js +12 -7
  99. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  100. package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
  101. package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
  102. package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
  103. package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
  104. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  105. package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
  106. package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
  107. package/plugins/kimi-codex/dist/parsing.js +45 -11
  108. package/plugins/kimi-codex/dist/paths.js +20 -10
  109. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  110. package/plugins/kimi-codex/dist/read-scope.js +2 -2
  111. package/plugins/kimi-codex/dist/render.js +13 -38
  112. package/plugins/kimi-codex/dist/session-references.js +216 -0
  113. package/plugins/kimi-codex/dist/session-title.js +1 -1
  114. package/plugins/kimi-codex/dist/surface-routing.js +92 -5
  115. package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
  116. package/plugins/kimi-codex/dist/version.js +1 -1
  117. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  118. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  119. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  120. package/scripts/companion.sh +4 -15
  121. package/skills/kimi/SKILL.md +77 -0
  122. package/skills/kimi/agents/openai.yaml +6 -0
  123. package/CHANGELOG.md +0 -1402
  124. package/agents/kimi-pursue.md +0 -93
  125. package/agents/kimi-review.md +0 -86
  126. package/agents/kimi-swarm.md +0 -88
  127. package/agents/kimi-task.md +0 -93
  128. package/commands/README.md +0 -14
  129. package/commands/cancel.md +0 -17
  130. package/commands/pursue.md +0 -41
  131. package/commands/replay.md +0 -13
  132. package/commands/result.md +0 -13
  133. package/commands/review.md +0 -40
  134. package/commands/setup.md +0 -25
  135. package/commands/status.md +0 -13
  136. package/commands/swarm.md +0 -45
  137. package/commands/task.md +0 -40
  138. package/dist/commands/review-gate.js +0 -391
  139. package/dist/config.js +0 -22
  140. package/dist/dsh/companion.js +0 -177
  141. package/dist/dsh/index.js +0 -167
  142. package/dist/hooks/review-gate-stop.js +0 -19
  143. package/dist/schemas/review-gate-output.js +0 -41
  144. package/docs/registry-releases.md +0 -228
  145. package/docs/upstream-2.4.1-certification.md +0 -54
  146. package/docs/upstream-2.5.0-certification.md +0 -52
  147. package/docs/upstream-2.5.1-certification.md +0 -47
  148. package/docs/upstream-2.5.2-certification.md +0 -40
  149. package/docs/upstream-2.5.3-certification.md +0 -73
  150. package/docs/upstream-2.6.0-certification.md +0 -65
  151. package/docs/upstream-2.6.2-certification.md +0 -144
  152. package/docs/upstream-2.6.3-certification.md +0 -100
  153. package/docs/upstream-2.7.2-certification.md +0 -113
  154. package/docs/upstream-2.7.3-certification.md +0 -95
  155. package/docs/windows-validation.md +0 -39
  156. package/hooks/README.md +0 -9
  157. package/hooks/hooks.json +0 -16
  158. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
  159. package/plugins/kimi-codex/dist/config.js +0 -22
  160. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  161. package/plugins/kimi-codex/dist/dsh/index.js +0 -167
  162. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  163. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  165. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  166. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  167. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  168. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  169. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  170. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  171. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  172. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  173. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
  174. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  175. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
  176. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  177. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  178. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  179. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
  180. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  181. package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
  182. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
  183. package/plugins/kimi-dsh/LICENSE +0 -201
  184. package/plugins/kimi-dsh/README.md +0 -84
  185. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  186. package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
  187. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  188. package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
  189. package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
  190. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
  191. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
  192. package/plugins/kimi-dsh/dist/commands/models.js +0 -139
  193. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
  194. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  195. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  196. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
  197. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  198. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
  199. package/plugins/kimi-dsh/dist/commands/result.js +0 -72
  200. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
  201. package/plugins/kimi-dsh/dist/commands/review.js +0 -217
  202. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
  203. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  204. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
  205. package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
  206. package/plugins/kimi-dsh/dist/companion.js +0 -99
  207. package/plugins/kimi-dsh/dist/config.js +0 -22
  208. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  209. package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
  210. package/plugins/kimi-dsh/dist/errors.js +0 -40
  211. package/plugins/kimi-dsh/dist/git.js +0 -216
  212. package/plugins/kimi-dsh/dist/help.js +0 -43
  213. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  214. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
  215. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
  216. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
  217. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
  218. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  219. package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
  220. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
  221. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  222. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  223. package/plugins/kimi-dsh/dist/job-store.js +0 -631
  224. package/plugins/kimi-dsh/dist/jobs.js +0 -212
  225. package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
  226. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
  227. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
  228. package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
  229. package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
  230. package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
  231. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  232. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
  233. package/plugins/kimi-dsh/dist/logging.js +0 -22
  234. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  235. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
  236. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
  237. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
  238. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
  239. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  240. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
  241. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  242. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  243. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  244. package/plugins/kimi-dsh/dist/model-command.js +0 -34
  245. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
  246. package/plugins/kimi-dsh/dist/package.json +0 -1
  247. package/plugins/kimi-dsh/dist/parsing.js +0 -554
  248. package/plugins/kimi-dsh/dist/paths.js +0 -35
  249. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  250. package/plugins/kimi-dsh/dist/process-tree.js +0 -597
  251. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  252. package/plugins/kimi-dsh/dist/read-scope.js +0 -435
  253. package/plugins/kimi-dsh/dist/render.js +0 -214
  254. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
  255. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
  256. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  257. package/plugins/kimi-dsh/dist/session-title.js +0 -313
  258. package/plugins/kimi-dsh/dist/stream-json.js +0 -344
  259. package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
  260. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
  261. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
  262. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
  263. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  264. package/plugins/kimi-dsh/dist/types.js +0 -1
  265. package/plugins/kimi-dsh/dist/util.js +0 -28
  266. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  267. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  268. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  269. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  270. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  271. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  272. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  273. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  274. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  275. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  276. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  277. package/plugins/kimi-dsh/dist/version.js +0 -7
  278. package/plugins/kimi-dsh/package.json +0 -78
  279. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  280. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  281. package/scripts/review-gate-hook.sh +0 -32
@@ -1,266 +0,0 @@
1
- import { REPAIR_SESSIONS_SUPPORTED_FLAGS } from "../parsing.js";
2
- import { constants } from "node:fs";
3
- import { lstat, open } from "node:fs/promises";
4
- import { createRequire } from "node:module";
5
- import path from "node:path";
6
- import { RuntimeError } from "../errors.js";
7
- import { resolveRepoIdentity } from "../git.js";
8
- import { digestPrompt } from "../jobs.js";
9
- import { resolvePluginPaths } from "../paths.js";
10
- import { syncKimiSessionTitle } from "../session-title.js";
11
- import { askPromptSubject } from "./ask.js";
12
- import { buildGoalPrompt } from "./pursue.js";
13
- import { stripRescuePromptPrefix } from "./rescue.js";
14
- import { buildSwarmPrompt, buildSwarmWritePrompt } from "./swarm.js";
15
- // Repair is deliberately finite and local. Stream logs may be very large, but
16
- // the spawn record follows the invocation header: read only a bounded prefix.
17
- const MAX_JOBS = 1000;
18
- const MAX_SPAWN_BYTES = 2 * 1024 * 1024;
19
- export async function runRepairSessions(argv, context) {
20
- const seen = new Set();
21
- for (const arg of argv) {
22
- if ((arg !== "--apply" && arg !== "--all") || seen.has(arg)) {
23
- throw new RuntimeError("INVALID_ARGS", `Usage: repair-sessions. Supported flags: ${REPAIR_SESSIONS_SUPPORTED_FLAGS}.`, "repair-sessions.args");
24
- }
25
- seen.add(arg);
26
- }
27
- const apply = seen.has("--apply");
28
- const all = seen.has("--all");
29
- const paths = resolvePluginPaths(context.env);
30
- const repoId = all ? undefined : (await resolveRepoIdentity(context.cwd)).repoId;
31
- const jobs = await readRepairJobs(paths.stateDbPath, repoId);
32
- // Newest job first per session: it supplies the preview, while every
33
- // verified prompt of the session counts as the plugin's own.
34
- const sessions = new Map();
35
- for (const job of jobs) {
36
- const sessionJobs = sessions.get(job.kimi_session_id);
37
- if (sessionJobs)
38
- sessionJobs.push(job);
39
- else
40
- sessions.set(job.kimi_session_id, [job]);
41
- }
42
- const results = [];
43
- for (const [sessionId, [job, ...earlier]] of sessions) {
44
- const prompt = await readVerifiedPrompt(job, paths.logsDir, paths.worktreesDir);
45
- let status = "unavailable-verified-prompt";
46
- if (prompt !== undefined) {
47
- const raw = rawTaskTextFromSubmittedPrompt(job.operation_kind, prompt);
48
- const own = [prompt];
49
- if (raw !== undefined) {
50
- for (const other of earlier) {
51
- const otherPrompt = await readVerifiedPrompt(other, paths.logsDir, paths.worktreesDir);
52
- if (otherPrompt !== undefined)
53
- own.push(otherPrompt);
54
- }
55
- }
56
- status = await syncKimiSessionTitle({
57
- env: context.env,
58
- cwd: job.cwd,
59
- sessionId,
60
- title: "",
61
- // Without an exact raw-text derivation, only a missing preview is
62
- // filled, with the verified prompt itself.
63
- promptText: raw ?? prompt,
64
- ownPrompts: raw === undefined ? [] : own,
65
- dryRun: !apply,
66
- preserveTitle: true,
67
- requireNativeV2: true,
68
- stderr: context.stderr,
69
- });
70
- }
71
- results.push({ job_id: job.job_id, session_id: sessionId, status });
72
- }
73
- const counts = {};
74
- for (const { status } of results)
75
- counts[status] = (counts[status] ?? 0) + 1;
76
- return `${JSON.stringify({ mode: apply ? "apply" : "dry-run", scope: all ? "host" : "repository", sessions: results.length, counts, results }, null, 2)}\n`;
77
- }
78
- async function readRepairJobs(filename, repoId) {
79
- try {
80
- const stats = await lstat(filename);
81
- if (!stats.isFile() || stats.isSymbolicLink()) {
82
- throw new RuntimeError("SESSION_REPAIR_UNSAFE_STORE", "Repair requires a regular, non-symlink job database.", "repair-sessions.store");
83
- }
84
- }
85
- catch (error) {
86
- if (error.code === "ENOENT")
87
- return [];
88
- throw error;
89
- }
90
- const require = createRequire(import.meta.url);
91
- // Bind constructors before `new`: compiler emission must not turn the
92
- // module-loader call into the constructor (new require(...).Database).
93
- const db = (() => {
94
- if (typeof Bun !== "undefined") {
95
- const { Database } = require("bun:sqlite");
96
- return new Database(filename, { readonly: true });
97
- }
98
- const { DatabaseSync } = require("node:sqlite");
99
- return new DatabaseSync(filename, { readOnly: true });
100
- })();
101
- try {
102
- // Never construct JobStore here: it performs migrations and stale-row
103
- // reconciliation. Both preview and apply keep plugin job data read-only.
104
- const columns = db.prepare("PRAGMA table_info(jobs)").all();
105
- const names = new Set(columns.map((column) => column.name));
106
- const required = ["job_id", "repo_id", "command_type", "operation_kind", "status", "kimi_session_id", "cwd", "kimi_version", "intended_engine", "observed_engine", "stream_log_path", "prompt_digest", "updated_at"];
107
- if (required.some((name) => !names.has(name)))
108
- return [];
109
- const rows = db.prepare(`
110
- SELECT j.job_id, j.repo_id, j.operation_kind, j.kimi_session_id, j.cwd, j.kimi_version, j.stream_log_path, j.prompt_digest
111
- FROM jobs j
112
- WHERE j.status = 'completed' AND j.intended_engine = 'native-v2' AND j.observed_engine = 'native-v2'
113
- AND j.command_type != 'review_gate'
114
- AND j.operation_kind IN ('ask', 'review', 'challenge', 'rescue', 'pursue', 'swarm', 'swarm-write')
115
- AND j.kimi_session_id IS NOT NULL AND length(trim(j.kimi_session_id)) > 0
116
- AND j.kimi_version IS NOT NULL
117
- ${repoId === undefined ? "" : "AND j.repo_id = ?"}
118
- AND NOT EXISTS (SELECT 1 FROM jobs active WHERE active.kimi_session_id = j.kimi_session_id AND active.status = 'running')
119
- ORDER BY j.updated_at DESC, j.job_id DESC LIMIT ${MAX_JOBS + 1}
120
- `).all(...(repoId === undefined ? [] : [repoId]));
121
- if (rows.length > MAX_JOBS) {
122
- throw new RuntimeError("SESSION_REPAIR_LIMIT", `More than ${MAX_JOBS} eligible jobs; narrow the repair to one repository.`, "repair-sessions.store");
123
- }
124
- return rows;
125
- }
126
- finally {
127
- db.close();
128
- }
129
- }
130
- async function readVerifiedPrompt(job, logsDir, worktreesDir) {
131
- // All plugin stream logs are direct children. Refuse nested/escaped paths,
132
- // symlinks and special files; opening nonblocking avoids FIFO hangs.
133
- if (!path.isAbsolute(job.stream_log_path) || path.dirname(job.stream_log_path) !== logsDir)
134
- return undefined;
135
- try {
136
- const root = await lstat(logsDir);
137
- if (!root.isDirectory() || root.isSymbolicLink())
138
- return undefined;
139
- const file = await open(job.stream_log_path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
140
- try {
141
- const stats = await file.stat();
142
- if (!stats.isFile())
143
- return undefined;
144
- const buffer = Buffer.alloc(MAX_SPAWN_BYTES + 1);
145
- const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
146
- const prefix = buffer.subarray(0, bytesRead).toString("utf8");
147
- const lines = prefix.split("\n");
148
- // A prefix cut mid-record must never be treated as a complete JSON line.
149
- if (bytesRead > MAX_SPAWN_BYTES)
150
- lines.pop();
151
- for (const line of lines.slice(0, 32)) {
152
- if (!line.trim())
153
- continue;
154
- const record = JSON.parse(line);
155
- if (record.event !== "spawn") {
156
- if (record.direction === "meta")
157
- continue;
158
- return undefined;
159
- }
160
- const expectedCwd = job.operation_kind === "swarm-write"
161
- ? path.join(worktreesDir, job.repo_id, `swarm-write-${job.job_id}`)
162
- : job.cwd;
163
- if (record.intended_engine !== "native-v2" || record.kimi_version !== job.kimi_version ||
164
- record.operation_kind !== job.operation_kind || record.cwd !== expectedCwd)
165
- return undefined;
166
- if (!Array.isArray(record.args) || record.args.length < 2)
167
- return undefined;
168
- const args = record.args;
169
- const prompt = args[args.length - 1];
170
- if (args[args.length - 2] !== "-p" || typeof prompt !== "string" || !prompt.trim())
171
- return undefined;
172
- return digestPrompt(prompt) === job.prompt_digest ? prompt : undefined;
173
- }
174
- return undefined;
175
- }
176
- finally {
177
- await file.close();
178
- }
179
- }
180
- catch {
181
- return undefined;
182
- }
183
- }
184
- const TASK_SLOT = "\u0000kimi-plugin-cc-task\u0000";
185
- /**
186
- * Recover the raw task text a live run previews from its verified submitted
187
- * prompt. Derivations are exact or absent: prompts from other plugin releases,
188
- * ambiguous parameter choices and unknown operations return undefined.
189
- */
190
- export function rawTaskTextFromSubmittedPrompt(operationKind, prompt) {
191
- switch (operationKind) {
192
- case "ask":
193
- return strippedOrUndefined(prompt, askPromptSubject(prompt));
194
- case "rescue":
195
- return strippedOrUndefined(prompt, stripRescuePromptPrefix(prompt));
196
- case "pursue":
197
- return uniqueInversion(prompt, [undefined, ...numbersAfter(prompt, /at most (\d+) turns/g)]
198
- .map((turns) => (task) => buildGoalPrompt(task, turns)));
199
- case "swarm":
200
- case "swarm-write": {
201
- const build = operationKind === "swarm" ? buildSwarmPrompt : buildSwarmWritePrompt;
202
- const caps = [undefined, ...numbersAfter(prompt, /at most (\d+) subagents/g)];
203
- const waves = [undefined, 1, ...numbersAfter(prompt, /at most (\d+) entries/g)];
204
- return uniqueInversion(prompt, caps.flatMap((cap) => waves.map((wave) => (task) => build(task, cap, wave))));
205
- }
206
- case "review":
207
- case "challenge":
208
- return reviewTaskText(prompt);
209
- default:
210
- return undefined;
211
- }
212
- }
213
- function strippedOrUndefined(prompt, stripped) {
214
- return stripped !== prompt && stripped.trim() ? stripped : undefined;
215
- }
216
- function numbersAfter(prompt, pattern) {
217
- return [...new Set([...prompt.matchAll(pattern)].map((match) => Number(match[1])))];
218
- }
219
- /**
220
- * Split each candidate template around the task slot and require an exact
221
- * rebuild. The template explaining the most prompt text wins (without --turns
222
- * the turn guidance would otherwise read as objective); a tie is ambiguous.
223
- */
224
- function uniqueInversion(prompt, builders) {
225
- let found = new Set();
226
- let bestTemplate = -1;
227
- for (const build of builders) {
228
- try {
229
- const template = build(TASK_SLOT);
230
- const at = template.indexOf(TASK_SLOT);
231
- if (at < 0)
232
- continue;
233
- const head = template.slice(0, at);
234
- const tail = template.slice(at + TASK_SLOT.length);
235
- if (prompt.length < head.length + tail.length || !prompt.startsWith(head) || !prompt.endsWith(tail))
236
- continue;
237
- const task = prompt.slice(head.length, prompt.length - tail.length);
238
- if (!task.trim() || build(task) !== prompt || head.length + tail.length < bestTemplate)
239
- continue;
240
- if (head.length + tail.length > bestTemplate)
241
- found = new Set();
242
- bestTemplate = head.length + tail.length;
243
- found.add(task);
244
- }
245
- catch {
246
- continue;
247
- }
248
- }
249
- return found.size === 1 ? [...found][0] : undefined;
250
- }
251
- // Mirrors the review/challenge preview built at the review.ts sync call; the
252
- // review command tests pin the two against real submitted prompts.
253
- const REVIEW_PROMPT_START = "Perform a read-only code review of the supplied repository changes.\n";
254
- const REVIEW_TARGET_LINES = /\n\nTarget: (current working tree changes|branch diff against [^\n]+)\nScope: (?:branch diff only; all working-tree changes are out of scope|current working tree, including tracked and untracked changes)\nRepository root: /;
255
- const REVIEW_FOCUS_LINE = "\nReview focus: ";
256
- function reviewTaskText(prompt) {
257
- if (!prompt.startsWith(REVIEW_PROMPT_START))
258
- return undefined;
259
- const target = REVIEW_TARGET_LINES.exec(prompt);
260
- if (!target)
261
- return undefined;
262
- const header = prompt.slice(0, target.index);
263
- const focusAt = header.indexOf(REVIEW_FOCUS_LINE);
264
- const focus = focusAt < 0 ? undefined : header.slice(focusAt + REVIEW_FOCUS_LINE.length);
265
- return `Review target: ${target[1]}${focus ? `. Focus: ${focus}` : ""}`;
266
- }
@@ -1,124 +0,0 @@
1
- import { REPLAY_SUPPORTED_FLAGS } from "../parsing.js";
2
- import { access, stat, readFile } from "node:fs/promises";
3
- import { constants as fsConstants } from "node:fs";
4
- import { RuntimeError } from "../errors.js";
5
- import { resolveRepoIdentity } from "../git.js";
6
- import { withJobStore } from "../job-store.js";
7
- import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
8
- import { renderManagedJobOutput } from "../render.js";
9
- import { sweepStaleJobs } from "../jobs.js";
10
- const MAX_REPLAY_LOG_BYTES = 32 * 1024 * 1024;
11
- export async function runReplay(argv, context) {
12
- const [jobId, ...rest] = argv;
13
- if (!jobId || jobId.startsWith("-") || rest.length > 0) {
14
- throw new RuntimeError("INVALID_ARGS", `replay expects exactly one job id: replay <job-id>. Supported flags: ${REPLAY_SUPPORTED_FLAGS}.`, "replay.parse");
15
- }
16
- const paths = resolvePluginPaths(context.env);
17
- await ensurePluginPaths(paths);
18
- const repoIdentity = await resolveRepoIdentity(context.cwd);
19
- return withJobStore(paths, async (store) => {
20
- await sweepStaleJobs(store, paths);
21
- const job = store.getJob(jobId);
22
- if (!job || job.repo_id !== repoIdentity.repoId) {
23
- throw new RuntimeError("JOB_NOT_FOUND", `No job matched ${jobId} for replay.`, "replay.lookup");
24
- }
25
- const replayed = await replayJob(job);
26
- return `${replayed.rendered}${replayed.rendered.endsWith("\n") ? "" : "\n"}`;
27
- });
28
- }
29
- export async function replayJob(job) {
30
- if (!job.stream_log_path) {
31
- throw new RuntimeError("REPLAY_LOG_MISSING", `Job ${job.job_id} does not have a stored stream log path to replay.`, "replay.lookup");
32
- }
33
- try {
34
- await access(job.stream_log_path, fsConstants.R_OK);
35
- }
36
- catch {
37
- throw new RuntimeError("REPLAY_LOG_MISSING", `Job ${job.job_id} cannot be replayed because ${job.stream_log_path} is missing.`, "replay.lookup");
38
- }
39
- const stats = await stat(job.stream_log_path);
40
- if (stats.size > MAX_REPLAY_LOG_BYTES) {
41
- throw new RuntimeError("REPLAY_LOG_TOO_LARGE", `Job ${job.job_id} stream log is ${stats.size} bytes, which exceeds the ${MAX_REPLAY_LOG_BYTES}-byte replay ceiling.`, "replay.lookup");
42
- }
43
- const finalText = await replayFinalText(job.stream_log_path);
44
- const rendered = renderManagedJobOutput(job, finalText);
45
- return {
46
- rendered: rendered.rendered,
47
- output: rendered.output,
48
- summary: rendered.summary,
49
- };
50
- }
51
- async function replayFinalText(logPath) {
52
- const contents = await readFile(logPath, "utf8");
53
- const rawLines = contents.split("\n");
54
- let sawSpawn = false;
55
- let sawExit = false;
56
- let sawV1Event = false;
57
- let sawV04Direction = false;
58
- let assistantContent = "";
59
- for (let lineNumber = 0; lineNumber < rawLines.length; lineNumber += 1) {
60
- const line = rawLines[lineNumber].trim();
61
- if (!line)
62
- continue;
63
- let entry;
64
- try {
65
- entry = JSON.parse(line);
66
- }
67
- catch (error) {
68
- // A truncated trailing line is the expected shape when a worker
69
- // was SIGKILL'd mid-write. Drop it silently so replay still works
70
- // on the consistent prefix.
71
- if (lineNumber === rawLines.length - 1)
72
- continue;
73
- throw new RuntimeError("REPLAY_LOG_INVALID", `Stream log ${logPath}:${lineNumber + 1} is malformed JSON: ${error.message}`, "replay.log", { cause: error });
74
- }
75
- if (typeof entry.event === "string")
76
- sawV1Event = true;
77
- if (Object.prototype.hasOwnProperty.call(entry, "direction"))
78
- sawV04Direction = true;
79
- const event = typeof entry.event === "string" ? entry.event : "";
80
- switch (event) {
81
- case "spawn":
82
- sawSpawn = true;
83
- break;
84
- case "record": {
85
- const record = entry.record;
86
- if (typeof record !== "object" || record === null || Array.isArray(record)) {
87
- throw new RuntimeError("REPLAY_LOG_INVALID", `Stream log ${logPath}:${lineNumber + 1} record entry is not an object.`, "replay.log");
88
- }
89
- const role = record.role;
90
- const content = record.content;
91
- if (role === "assistant" && typeof content === "string") {
92
- assistantContent += content;
93
- }
94
- // Non-string content (null/undefined/object) silently skipped —
95
- // these are diagnostic-only records we don't render.
96
- break;
97
- }
98
- case "exit":
99
- sawExit = true;
100
- break;
101
- case "process_error": {
102
- const detail = typeof entry.message === "string" ? entry.message : "<unknown>";
103
- throw new RuntimeError("REPLAY_LOG_PROCESS_ERROR", `Stream log ${logPath} captured a subprocess error and cannot be replayed: ${detail}`, "replay.log", { details: { logPath, line: lineNumber + 1 } });
104
- }
105
- default:
106
- // Unknown / malformed-line / future events are diagnostics — skip.
107
- break;
108
- }
109
- }
110
- if (!sawSpawn) {
111
- // Differentiate "this is a v0.4 wire log" from "this is a v1.0 log
112
- // that died before reaching the spawn event". v0.4 logs had a
113
- // `direction` field on every entry (out/in/meta/stderr); v1.0 logs
114
- // use `event` instead.
115
- if (sawV04Direction && !sawV1Event) {
116
- throw new RuntimeError("REPLAY_LOG_UNREADABLE", `Stream log ${logPath} is a v0.4 wire log (no \`event\` key). v0.4 wire logs are not supported by the v1.0 replay command.`, "replay.log", { details: { logPath } });
117
- }
118
- throw new RuntimeError("REPLAY_LOG_NO_SPAWN", `Stream log ${logPath} contains no spawn event — the worker likely failed before launching kimi (e.g., synchronous spawn failure, early cancellation). No assistant content to replay.`, "replay.log", { details: { logPath } });
119
- }
120
- if (!sawExit && assistantContent.length === 0) {
121
- throw new RuntimeError("REPLAY_LOG_INVALID", `Stream log ${logPath} did not capture any assistant content before truncation.`, "replay.log", { details: { logPath } });
122
- }
123
- return assistantContent;
124
- }
@@ -1,277 +0,0 @@
1
- import { companionHelp } from "../help.js";
2
- import { allocateJobId } from "../job-id.js";
3
- import path from "node:path";
4
- import { createCliCancellationHandlers } from "../cli-cancellation.js";
5
- import { runCliPromptWithBudget } from "../cli-client.js";
6
- import { assertPersistedResumeLineage, executionPlanFromPersisted, observedExecutionFields, persistedExecutionPlanFields, prepareKimiExecutionPlan, reconcileHistoricalJobProvenance, } from "../kimi-engine.js";
7
- import { getManagedCommandConfig } from "./registry.js";
8
- import { RuntimeError } from "../errors.js";
9
- import { resolveRepoIdentity } from "../git.js";
10
- import { digestPrompt, markJobCancelled, markJobFailed, sweepStaleJobs } from "../jobs.js";
11
- import { JobStore } from "../job-store.js";
12
- import { classifyManagedCommandFailure } from "../kimi-errors.js";
13
- import { KIMI_RESCUE_PROMPT_TIMEOUT_MS } from "../kimi-timeouts.js";
14
- import { writeInvocationLogHeader } from "../logging.js";
15
- import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
16
- import { parseRescueArgs } from "../parsing.js";
17
- import { readArtifact, renderManagedJobOutput, writeArtifact } from "../render.js";
18
- import { startBackgroundJob } from "../background-spawn.js";
19
- import { warnInheritedBudget, captureTimeoutPartialOutput, assertCliResultSuccess, reassembleProseFromRecords, warnIfSessionIdMissing, warnHookEscapes, resolveResumeSession, resumeBudget, hookRefusal } from "./cli-helpers.js";
20
- import { buildKimiSessionTitle, syncKimiSessionTitle } from "../session-title.js";
21
- import { shorten } from "../util.js";
22
- // "Continue working on the bug" verbs that auto-attach to the latest
23
- // rescue session. Documented UX trap: a prompt matching this pattern
24
- // will resume the most recent rescue session regardless of whether
25
- // that session was about the same bug. Users should pass an explicit
26
- // `--resume <job-id>` or `--fresh` when the topic switches.
27
- const AUTO_RESUME_PATTERN = /\b(continue|resume|keep going|keep working|apply the top fix|dig deeper)\b/i;
28
- const RESCUE_SUMMARY_MAX = 120;
29
- const RESCUE_AGENT_PROFILE_PLACEHOLDER = "<cli-client>";
30
- const RESCUE_CONTINUE_TASK = "Continue the previous rescue task using the latest repository state.";
31
- const RESCUE_PROMPT_PREFIX = [
32
- "Follow repository instructions and inspect the current state before editing.",
33
- "Implement the smallest complete change that satisfies the task instead of stopping at a plan.",
34
- "Do not mutate git state.",
35
- "Run proportionate relevant checks, and never claim unrun checks passed.",
36
- "Do not narrate progress.",
37
- "Finish with a self-contained report of changed files, verification commands and results, and unfinished work or blockers.",
38
- "",
39
- "Rescue task:",
40
- "",
41
- ].join("\n");
42
- export async function runRescue(argv, context) {
43
- const parsed = parseRescueArgs(argv);
44
- if (parsed.help)
45
- return companionHelp(["task", "rescue", ...argv]);
46
- const paths = resolvePluginPaths(context.env);
47
- await ensurePluginPaths(paths);
48
- const repoIdentity = await resolveRepoIdentity(context.cwd);
49
- const rescueConfig = getManagedCommandConfig("rescue");
50
- const store = new JobStore(paths);
51
- try {
52
- await sweepStaleJobs(store, paths);
53
- const sessionResolution = await resolveRescueSession(store, repoIdentity.repoId, parsed);
54
- const prompt = buildRescuePrompt(parsed.prompt, sessionResolution.reusedSession);
55
- const executionPlan = await prepareKimiExecutionPlan({
56
- operationKind: "rescue",
57
- cwd: context.cwd,
58
- env: context.env,
59
- stderr: context.stderr,
60
- resumedFromJobId: sessionResolution.resumedFromJobId,
61
- resumeSessionId: sessionResolution.kimiSessionId ?? undefined,
62
- resumeSource: sessionResolution.sourceJob,
63
- });
64
- const jobId = allocateJobId(context);
65
- const logPath = path.join(paths.logsDir, `rescue-${jobId}.jsonl`);
66
- const job = store.createJob({
67
- job_id: jobId,
68
- repo_id: repoIdentity.repoId,
69
- command_type: "rescue",
70
- cwd: context.cwd,
71
- model: parsed.model ?? null,
72
- thinking: null,
73
- thinking_effort: parsed.thinkingEffort ?? null,
74
- background: parsed.background,
75
- ...resumeBudget("rescue", parsed.budgetMs, sessionResolution.sourceJob),
76
- pid: parsed.background ? null : process.pid,
77
- kimi_pid: null,
78
- status: "running",
79
- kimi_session_id: sessionResolution.kimiSessionId,
80
- kimi_session_id_source: sessionResolution.sourceJob?.kimi_session_id_source ?? null,
81
- ...persistedExecutionPlanFields(executionPlan),
82
- agent_profile: RESCUE_AGENT_PROFILE_PLACEHOLDER,
83
- prompt_digest: digestPrompt(prompt),
84
- summary: shorten(stripRescuePromptPrefix(prompt), RESCUE_SUMMARY_MAX),
85
- phase: parsed.background ? "queued" : "starting",
86
- final_output_path: null,
87
- stream_log_path: logPath,
88
- error: null,
89
- });
90
- try {
91
- await writeInvocationLogHeader(logPath, {
92
- commandType: "rescue",
93
- kimiSessionId: sessionResolution.kimiSessionId ?? "(pending)",
94
- cwd: context.cwd,
95
- });
96
- }
97
- catch (error) {
98
- const classified = new RuntimeError("RESCUE_LOG_HEADER_FAILED", `Failed to write rescue invocation log header: ${error.message ?? String(error)}`, "rescue.log-header", error instanceof Error ? { cause: error } : undefined);
99
- await markJobFailed(store, paths, job, classified, rescueConfig.cancellation.failedSummary, { phase: "failed" });
100
- throw classified;
101
- }
102
- warnInheritedBudget(job, context.stderr);
103
- if (parsed.background) {
104
- return startBackgroundJob(job, prompt, context, paths, {
105
- workerKind: "rescue",
106
- wait: parsed.wait,
107
- failedSummary: rescueConfig.cancellation.failedSummary,
108
- });
109
- }
110
- const completed = await executeRescueJob(job.job_id, prompt, context);
111
- if (!completed.final_output_path) {
112
- throw new RuntimeError("RESCUE_RESULT_MISSING", "Rescue finished without a rendered result.", "rescue.result");
113
- }
114
- return readArtifact(completed.final_output_path);
115
- }
116
- finally {
117
- store.close();
118
- }
119
- }
120
- export async function executeRescueJob(jobId, prompt, context, options) {
121
- const paths = resolvePluginPaths(context.env);
122
- await ensurePluginPaths(paths);
123
- const store = new JobStore(paths);
124
- const job = store.getJob(jobId);
125
- if (!job) {
126
- store.close();
127
- throw new RuntimeError("JOB_NOT_FOUND", `Rescue job ${jobId} was not found.`, "rescue.worker");
128
- }
129
- const rescueConfig = getManagedCommandConfig("rescue");
130
- const cancel = rescueConfig.cancellation;
131
- // Rescue writes directly to the workspace. Without the PreToolUse hook,
132
- // kimi-code's `-p` mode auto-approves every Bash/Write/Edit, including
133
- // destructive ones. Refuse before the worker can spawn Kimi.
134
- //
135
- // The hook check happens BEFORE `createCliCancellationHandlers()` so
136
- // an early return doesn't leak SIGTERM/SIGINT listeners. Tests /
137
- // setup probes / intentional bypass: KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1.
138
- if (context.env.KIMI_PLUGIN_CC_SKIP_HOOK_CHECK !== "1") {
139
- const classified = await hookRefusal(context, "rescue");
140
- if (classified) {
141
- try {
142
- return await markJobFailed(store, paths, job, classified, cancel.failedSummary, { phase: "failed" });
143
- }
144
- finally {
145
- store.close();
146
- }
147
- }
148
- }
149
- const handlers = createCliCancellationHandlers();
150
- try {
151
- const executionPlan = executionPlanFromPersisted(job);
152
- // Re-validate resume lineage from the store before spawning: a detached
153
- // worker (or a forged queued row) reloads the persisted plan and would
154
- // otherwise hand kimi_session_id to the spawn without the dispatch-time
155
- // lineage check. Fresh sessions (no resumedFromJobId) are exempt.
156
- if (job.kimi_session_id !== null) {
157
- await assertPersistedResumeLineage(store, executionPlan, job.kimi_session_id, "rescue");
158
- }
159
- if (options?.workerPid) {
160
- store.updateRunningJob(job.job_id, { pid: options.workerPid, phase: "worker-running" });
161
- }
162
- store.updateRunningJob(job.job_id, { phase: "turn-running" });
163
- const result = await runCliPromptWithBudget({
164
- cwd: job.cwd,
165
- env: context.env,
166
- command: executionPlan.command,
167
- prefixArgs: [...executionPlan.prefixArgs],
168
- executionPlan,
169
- prompt,
170
- commandLabel: "rescue",
171
- trustedWorkspaceRoot: job.cwd,
172
- model: job.model ?? undefined,
173
- thinkingEffort: job.thinking_effort ?? undefined,
174
- resumeSessionId: job.kimi_session_id ?? undefined,
175
- logPath: job.stream_log_path,
176
- onSpawn: (pid) => { store.updateRunningJob(job.job_id, { kimi_pid: pid }); },
177
- signal: handlers.signal,
178
- }, job.budget_ms ?? KIMI_RESCUE_PROMPT_TIMEOUT_MS, "rescue.prompt");
179
- store.updateRunningJob(job.job_id, observedExecutionFields(result));
180
- if (handlers.cancelling) {
181
- throw new RuntimeError(cancel.errorCodes.cancelled, cancel.cancelMessages.afterPrompt, "rescue.runtime");
182
- }
183
- assertCliResultSuccess(result, "rescue.runtime");
184
- warnHookEscapes(result, "rescue", context.stderr);
185
- if (result.sessionId !== undefined &&
186
- result.sessionId.length > 0) {
187
- // Never persist an empty ID because NULL represents a missing session ID.
188
- store.updateRunningJob(job.job_id, { kimi_session_id_source: "announced", kimi_session_id: result.sessionId });
189
- }
190
- await syncKimiSessionTitle({
191
- promptText: stripRescuePromptPrefix(prompt),
192
- env: context.env,
193
- cwd: job.cwd,
194
- sessionId: result.sessionId ?? job.kimi_session_id,
195
- title: buildKimiSessionTitle("rescue", stripRescuePromptPrefix(prompt)),
196
- stderr: context.stderr,
197
- });
198
- if (job.kimi_session_id === null) {
199
- warnIfSessionIdMissing(result, "rescue", job.job_id, context.stderr);
200
- }
201
- const finalText = reassembleProseFromRecords(result.records);
202
- const rendered = renderManagedJobOutput(job, finalText);
203
- let artifactPath;
204
- try {
205
- if (context.env.KIMI_PLUGIN_CC_TEST_FAIL_WRITE_ARTIFACT === "1") {
206
- throw new Error("Simulated artifact write failure (test seam).");
207
- }
208
- artifactPath = await writeArtifact(paths, job, rendered.rendered);
209
- }
210
- catch (writeError) {
211
- // LLM-caller discipline: writing the raw model output to stderr
212
- // for a wrapper LLM-caller would corrupt its prose stream. Keep
213
- // the raw text in the RuntimeError details — surfaces via
214
- // /kimi:status / /kimi:result --json — and emit only a short
215
- // human-facing line on stderr.
216
- context.stderr.write(`[kimi-plugin-cc] rescue artifact write failed for job ${job.job_id}; raw output preserved in error details.\n`);
217
- const classified = new RuntimeError("RESCUE_ARTIFACT_WRITE_FAILED", `Failed to write rescue artifact: ${writeError.message ?? String(writeError)}`, "rescue.artifact", {
218
- ...(writeError instanceof Error ? { cause: writeError } : {}),
219
- details: { rawOutput: finalText },
220
- });
221
- return await markJobFailed(store, paths, job, classified, cancel.failedSummary, { phase: "failed" });
222
- }
223
- if (handlers.cancelling) {
224
- throw new RuntimeError(cancel.errorCodes.cancelled, cancel.cancelMessages.afterArtifact, "rescue.runtime");
225
- }
226
- return (store.markCompleted(job.job_id, {
227
- summary: rendered.summary,
228
- phase: "done",
229
- final_output_path: artifactPath,
230
- error: null,
231
- }) ?? job);
232
- }
233
- catch (error) {
234
- const classified = classifyManagedCommandFailure(error, "rescue", job.job_id, {
235
- preserveStage: true,
236
- background: job.background,
237
- budgetMs: job.budget_ms ?? KIMI_RESCUE_PROMPT_TIMEOUT_MS,
238
- });
239
- const partialOutput = await captureTimeoutPartialOutput(classified, store, job, context.env, handlers.signal);
240
- if (handlers.cancelling) {
241
- const cancelledError = new RuntimeError(cancel.errorCodes.cancelled, cancel.cancelMessages.default, "rescue.runtime", error instanceof Error ? { cause: error } : undefined);
242
- return await markJobCancelled(store, paths, job, cancel.cancelledSummary, cancelledError, { phase: "cancelled" });
243
- }
244
- return await markJobFailed(store, paths, job, classified, cancel.failedSummary, { phase: "failed", partialOutput });
245
- }
246
- finally {
247
- handlers.dispose();
248
- store.close();
249
- }
250
- }
251
- function buildRescuePrompt(prompt, reusedSession) {
252
- if (prompt?.trim()) {
253
- return RESCUE_PROMPT_PREFIX + prompt.trim();
254
- }
255
- if (reusedSession) {
256
- return RESCUE_PROMPT_PREFIX + RESCUE_CONTINUE_TASK;
257
- }
258
- throw new RuntimeError("INVALID_ARGS", "rescue requires a task description.", "rescue.parse");
259
- }
260
- export function stripRescuePromptPrefix(prompt) {
261
- return prompt.startsWith(RESCUE_PROMPT_PREFIX) ? prompt.slice(RESCUE_PROMPT_PREFIX.length) : prompt;
262
- }
263
- async function resolveRescueSession(store, repoId, parsed) {
264
- if (!parsed.fresh && !parsed.resumeTarget && !parsed.resume && parsed.prompt && AUTO_RESUME_PATTERN.test(parsed.prompt)) {
265
- const latest = store.findLatestJob({ repoId, commandType: "rescue" });
266
- if (latest?.kimi_session_id && latest.status !== "running") {
267
- const source = await reconcileHistoricalJobProvenance(store, latest);
268
- return {
269
- kimiSessionId: source.kimi_session_id,
270
- reusedSession: true,
271
- resumedFromJobId: source.job_id,
272
- sourceJob: source,
273
- };
274
- }
275
- }
276
- return resolveResumeSession(store, "rescue", repoId, parsed);
277
- }