kimi-plugin-cc 2.7.2 → 3.0.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 (224) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +3 -5
  3. package/CHANGELOG.md +78 -1
  4. package/README.md +505 -448
  5. package/agents/kimi-pursue.md +6 -6
  6. package/agents/kimi-review.md +22 -22
  7. package/agents/kimi-swarm.md +25 -23
  8. package/agents/{kimi-ask.md → kimi-task.md} +34 -30
  9. package/commands/README.md +4 -6
  10. package/commands/pursue.md +1 -1
  11. package/commands/review.md +8 -3
  12. package/commands/setup.md +4 -2
  13. package/commands/swarm.md +6 -5
  14. package/commands/{rescue.md → task.md} +13 -11
  15. package/dist/background-spawn.js +10 -17
  16. package/dist/cli-client.js +65 -46
  17. package/dist/commands/ask.js +22 -89
  18. package/dist/commands/cancel.js +7 -46
  19. package/dist/commands/cli-helpers.js +102 -1
  20. package/dist/commands/models.js +2 -3
  21. package/dist/commands/pursue.js +5 -19
  22. package/dist/commands/repair-sessions.js +118 -12
  23. package/dist/commands/rescue.js +12 -82
  24. package/dist/commands/result.js +7 -1
  25. package/dist/commands/review-gate.js +1 -0
  26. package/dist/commands/review.js +12 -15
  27. package/dist/commands/setup.js +606 -270
  28. package/dist/commands/status.js +2 -2
  29. package/dist/commands/swarm.js +93 -119
  30. package/dist/commands/worker.js +1 -2
  31. package/dist/companion.js +3 -1
  32. package/dist/dsh/index.js +15 -17
  33. package/dist/git.js +1 -9
  34. package/dist/help.js +3 -3
  35. package/dist/hooks/approval-hook.js +41 -0
  36. package/dist/hooks/approval-policy.js +72 -10
  37. package/dist/hooks/config-safety.js +19 -42
  38. package/dist/hooks/hook-timing.js +48 -0
  39. package/dist/hooks/install.js +206 -11
  40. package/dist/hooks/managed-block.js +78 -33
  41. package/dist/job-store.js +100 -128
  42. package/dist/jobs.js +14 -19
  43. package/dist/kimi-command.js +74 -1
  44. package/dist/kimi-engine.js +170 -74
  45. package/dist/kimi-errors.js +14 -69
  46. package/dist/kimi-home.js +6 -0
  47. package/dist/kimi-journal.js +41 -0
  48. package/dist/kimi-releases.js +144 -0
  49. package/dist/kimi-timeouts.js +1 -1
  50. package/dist/kimi-version-probe.js +12 -48
  51. package/dist/mcp/job-control.js +4 -6
  52. package/dist/mcp/launcher.js +12 -6
  53. package/dist/mcp/operations.js +50 -18
  54. package/dist/mcp/protocol.js +16 -14
  55. package/dist/mcp/stdio.js +3 -2
  56. package/dist/model-command.js +5 -3
  57. package/dist/native-v2-preflight.js +139 -68
  58. package/dist/parsing.js +171 -237
  59. package/dist/paths.js +8 -0
  60. package/dist/process-tree.js +35 -24
  61. package/dist/read-scope.js +435 -0
  62. package/dist/render.js +46 -9
  63. package/dist/rescue-approval.js +461 -84
  64. package/dist/schemas/review-gate-output.js +3 -5
  65. package/dist/session-title.js +25 -5
  66. package/dist/stream-json.js +1 -3
  67. package/dist/surface-routing.js +21 -0
  68. package/dist/swarm-activation.js +74 -77
  69. package/dist/swarm-policy.js +2 -1
  70. package/dist/swarm-recovery.js +2 -1
  71. package/dist/util.js +28 -0
  72. package/dist/version.js +1 -1
  73. package/docs/migration.md +27 -6
  74. package/docs/models.md +2 -2
  75. package/docs/registry-releases.md +3 -1
  76. package/docs/safety.md +131 -81
  77. package/docs/session-visibility.md +5 -3
  78. package/docs/swarm-recovery.md +4 -4
  79. package/docs/upstream-2.7.2-certification.md +16 -2
  80. package/docs/upstream-2.7.3-certification.md +95 -0
  81. package/package.json +2 -1
  82. package/plugins/kimi-codex/.codex-plugin/plugin.json +3 -3
  83. package/plugins/kimi-codex/.mcp.json +1 -0
  84. package/plugins/kimi-codex/dist/background-spawn.js +10 -17
  85. package/plugins/kimi-codex/dist/cli-client.js +65 -46
  86. package/plugins/kimi-codex/dist/commands/ask.js +22 -89
  87. package/plugins/kimi-codex/dist/commands/cancel.js +7 -46
  88. package/plugins/kimi-codex/dist/commands/cli-helpers.js +102 -1
  89. package/plugins/kimi-codex/dist/commands/models.js +2 -3
  90. package/plugins/kimi-codex/dist/commands/pursue.js +5 -19
  91. package/plugins/kimi-codex/dist/commands/repair-sessions.js +118 -12
  92. package/plugins/kimi-codex/dist/commands/rescue.js +12 -82
  93. package/plugins/kimi-codex/dist/commands/result.js +7 -1
  94. package/plugins/kimi-codex/dist/commands/review-gate.js +1 -0
  95. package/plugins/kimi-codex/dist/commands/review.js +12 -15
  96. package/plugins/kimi-codex/dist/commands/setup.js +606 -270
  97. package/plugins/kimi-codex/dist/commands/status.js +2 -2
  98. package/plugins/kimi-codex/dist/commands/swarm.js +93 -119
  99. package/plugins/kimi-codex/dist/commands/worker.js +1 -2
  100. package/plugins/kimi-codex/dist/companion.js +3 -1
  101. package/plugins/kimi-codex/dist/dsh/index.js +15 -17
  102. package/plugins/kimi-codex/dist/git.js +1 -9
  103. package/plugins/kimi-codex/dist/help.js +3 -3
  104. package/plugins/kimi-codex/dist/hooks/approval-hook.js +41 -0
  105. package/plugins/kimi-codex/dist/hooks/approval-policy.js +72 -10
  106. package/plugins/kimi-codex/dist/hooks/config-safety.js +19 -42
  107. package/plugins/kimi-codex/dist/hooks/hook-timing.js +48 -0
  108. package/plugins/kimi-codex/dist/hooks/install.js +206 -11
  109. package/plugins/kimi-codex/dist/hooks/managed-block.js +78 -33
  110. package/plugins/kimi-codex/dist/job-store.js +100 -128
  111. package/plugins/kimi-codex/dist/jobs.js +14 -19
  112. package/plugins/kimi-codex/dist/kimi-command.js +74 -1
  113. package/plugins/kimi-codex/dist/kimi-engine.js +170 -74
  114. package/plugins/kimi-codex/dist/kimi-errors.js +14 -69
  115. package/plugins/kimi-codex/dist/kimi-home.js +6 -0
  116. package/plugins/kimi-codex/dist/kimi-journal.js +41 -0
  117. package/plugins/kimi-codex/dist/kimi-releases.js +144 -0
  118. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -1
  119. package/plugins/kimi-codex/dist/kimi-version-probe.js +12 -48
  120. package/plugins/kimi-codex/dist/mcp/job-control.js +4 -6
  121. package/plugins/kimi-codex/dist/mcp/launcher.js +12 -6
  122. package/plugins/kimi-codex/dist/mcp/operations.js +50 -18
  123. package/plugins/kimi-codex/dist/mcp/protocol.js +16 -14
  124. package/plugins/kimi-codex/dist/mcp/stdio.js +3 -2
  125. package/plugins/kimi-codex/dist/model-command.js +5 -3
  126. package/plugins/kimi-codex/dist/native-v2-preflight.js +139 -68
  127. package/plugins/kimi-codex/dist/parsing.js +171 -237
  128. package/plugins/kimi-codex/dist/paths.js +8 -0
  129. package/plugins/kimi-codex/dist/process-tree.js +35 -24
  130. package/plugins/kimi-codex/dist/read-scope.js +435 -0
  131. package/plugins/kimi-codex/dist/render.js +46 -9
  132. package/plugins/kimi-codex/dist/rescue-approval.js +461 -84
  133. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +3 -5
  134. package/plugins/kimi-codex/dist/session-title.js +25 -5
  135. package/plugins/kimi-codex/dist/stream-json.js +1 -3
  136. package/plugins/kimi-codex/dist/surface-routing.js +21 -0
  137. package/plugins/kimi-codex/dist/swarm-activation.js +74 -77
  138. package/plugins/kimi-codex/dist/swarm-policy.js +2 -1
  139. package/plugins/kimi-codex/dist/swarm-recovery.js +2 -1
  140. package/plugins/kimi-codex/dist/util.js +28 -0
  141. package/plugins/kimi-codex/dist/version.js +1 -1
  142. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +1 -1
  143. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +8 -7
  144. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +1 -1
  145. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +2 -1
  146. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +8 -6
  147. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +1 -1
  148. package/plugins/kimi-codex/skills/{kimi-ask → kimi-task}/SKILL.md +11 -9
  149. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +6 -0
  150. package/plugins/kimi-dsh/README.md +3 -2
  151. package/plugins/kimi-dsh/dist/background-spawn.js +10 -17
  152. package/plugins/kimi-dsh/dist/cli-client.js +65 -46
  153. package/plugins/kimi-dsh/dist/commands/ask.js +22 -89
  154. package/plugins/kimi-dsh/dist/commands/cancel.js +7 -46
  155. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +102 -1
  156. package/plugins/kimi-dsh/dist/commands/models.js +2 -3
  157. package/plugins/kimi-dsh/dist/commands/pursue.js +5 -19
  158. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +118 -12
  159. package/plugins/kimi-dsh/dist/commands/rescue.js +12 -82
  160. package/plugins/kimi-dsh/dist/commands/result.js +7 -1
  161. package/plugins/kimi-dsh/dist/commands/review-gate.js +1 -0
  162. package/plugins/kimi-dsh/dist/commands/review.js +12 -15
  163. package/plugins/kimi-dsh/dist/commands/setup.js +606 -270
  164. package/plugins/kimi-dsh/dist/commands/status.js +2 -2
  165. package/plugins/kimi-dsh/dist/commands/swarm.js +93 -119
  166. package/plugins/kimi-dsh/dist/commands/worker.js +1 -2
  167. package/plugins/kimi-dsh/dist/companion.js +3 -1
  168. package/plugins/kimi-dsh/dist/dsh/index.js +15 -17
  169. package/plugins/kimi-dsh/dist/git.js +1 -9
  170. package/plugins/kimi-dsh/dist/help.js +3 -3
  171. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +41 -0
  172. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +72 -10
  173. package/plugins/kimi-dsh/dist/hooks/config-safety.js +19 -42
  174. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +48 -0
  175. package/plugins/kimi-dsh/dist/hooks/install.js +206 -11
  176. package/plugins/kimi-dsh/dist/hooks/managed-block.js +78 -33
  177. package/plugins/kimi-dsh/dist/job-store.js +100 -128
  178. package/plugins/kimi-dsh/dist/jobs.js +14 -19
  179. package/plugins/kimi-dsh/dist/kimi-command.js +74 -1
  180. package/plugins/kimi-dsh/dist/kimi-engine.js +170 -74
  181. package/plugins/kimi-dsh/dist/kimi-errors.js +14 -69
  182. package/plugins/kimi-dsh/dist/kimi-home.js +6 -0
  183. package/plugins/kimi-dsh/dist/kimi-journal.js +41 -0
  184. package/plugins/kimi-dsh/dist/kimi-releases.js +144 -0
  185. package/plugins/kimi-dsh/dist/kimi-timeouts.js +1 -1
  186. package/plugins/kimi-dsh/dist/kimi-version-probe.js +12 -48
  187. package/plugins/kimi-dsh/dist/mcp/job-control.js +4 -6
  188. package/plugins/kimi-dsh/dist/mcp/launcher.js +12 -6
  189. package/plugins/kimi-dsh/dist/mcp/operations.js +50 -18
  190. package/plugins/kimi-dsh/dist/mcp/protocol.js +16 -14
  191. package/plugins/kimi-dsh/dist/mcp/stdio.js +3 -2
  192. package/plugins/kimi-dsh/dist/model-command.js +5 -3
  193. package/plugins/kimi-dsh/dist/native-v2-preflight.js +139 -68
  194. package/plugins/kimi-dsh/dist/parsing.js +171 -237
  195. package/plugins/kimi-dsh/dist/paths.js +8 -0
  196. package/plugins/kimi-dsh/dist/process-tree.js +35 -24
  197. package/plugins/kimi-dsh/dist/read-scope.js +435 -0
  198. package/plugins/kimi-dsh/dist/render.js +46 -9
  199. package/plugins/kimi-dsh/dist/rescue-approval.js +461 -84
  200. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +3 -5
  201. package/plugins/kimi-dsh/dist/session-title.js +25 -5
  202. package/plugins/kimi-dsh/dist/stream-json.js +1 -3
  203. package/plugins/kimi-dsh/dist/surface-routing.js +21 -0
  204. package/plugins/kimi-dsh/dist/swarm-activation.js +74 -77
  205. package/plugins/kimi-dsh/dist/swarm-policy.js +2 -1
  206. package/plugins/kimi-dsh/dist/swarm-recovery.js +2 -1
  207. package/plugins/kimi-dsh/dist/util.js +28 -0
  208. package/plugins/kimi-dsh/dist/version.js +1 -1
  209. package/plugins/kimi-dsh/package.json +1 -1
  210. package/agents/kimi-challenge.md +0 -86
  211. package/agents/kimi-rescue.md +0 -92
  212. package/agents/kimi-swarm-write.md +0 -96
  213. package/commands/ask.md +0 -38
  214. package/commands/challenge.md +0 -35
  215. package/dist/commands/not-implemented.js +0 -4
  216. package/plugins/kimi-codex/dist/commands/not-implemented.js +0 -4
  217. package/plugins/kimi-codex/skills/kimi-ask/agents/openai.yaml +0 -6
  218. package/plugins/kimi-codex/skills/kimi-challenge/SKILL.md +0 -34
  219. package/plugins/kimi-codex/skills/kimi-challenge/agents/openai.yaml +0 -6
  220. package/plugins/kimi-codex/skills/kimi-rescue/SKILL.md +0 -34
  221. package/plugins/kimi-codex/skills/kimi-rescue/agents/openai.yaml +0 -6
  222. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +0 -36
  223. package/plugins/kimi-codex/skills/kimi-swarm-write/agents/openai.yaml +0 -6
  224. package/plugins/kimi-dsh/dist/commands/not-implemented.js +0 -4
@@ -23,8 +23,11 @@
23
23
  // - `event = "PreToolUse"` is required.
24
24
  // - Exactly one `[[hooks]]` table appears inside the markers.
25
25
  // - The decoded command must equal the canonical expected command byte-for-byte.
26
+ // - Every PreToolUse entry with that command needs an effective timeout of at
27
+ // least HOOK_TIMEOUT_S (checked on the whole-file parse).
26
28
  import { parse as parseToml } from "../vendor/smol-toml/parse.js";
27
29
  import { classifyHookCommandDrift, describeHookCommandDrift, hostIdFromHookCommand, isOurApprovalHookCommand, } from "./install-paths.js";
30
+ import { HOOK_TIMEOUT_S, hookTimeoutEnforces } from "./hook-timing.js";
28
31
  const MARKER_TAG = "kimi-plugin-cc-managed";
29
32
  /**
30
33
  * Plain install removes unpaired marker comments for every host and leaves each
@@ -147,7 +150,7 @@ function findMarkers(lines) {
147
150
  * both sides rather than being guessed into a block. Callers decide which
148
151
  * orphans fail closed (see `parseManagedBlock`).
149
152
  */
150
- function pairBlocks(lines) {
153
+ export function pairBlocks(lines) {
151
154
  const markers = findMarkers(lines);
152
155
  const blocks = [];
153
156
  const orphans = [];
@@ -214,13 +217,12 @@ function validateBlockBody(rawBody) {
214
217
  foundEvent = true;
215
218
  continue;
216
219
  }
217
- const basic = COMMAND_LINE_RE.exec(line);
218
- const literal = COMMAND_LITERAL_LINE_RE.exec(line);
219
- if (basic !== null || literal !== null) {
220
- // Decode TOML basic-string escapes before comparing with the canonical JS
221
- // string; literal strings have no escapes. Otherwise shell quoting and
222
- // TOML escaping can make an equivalent command compare unequal.
223
- commandPath = basic !== null ? decodeTomlBasicString(basic[1]) : literal[1];
220
+ // Decode TOML basic-string escapes before comparing with the canonical JS
221
+ // string; literal strings have no escapes. Otherwise shell quoting and
222
+ // TOML escaping can make an equivalent command compare unequal.
223
+ const decoded = decodeManagedCommandLine(line);
224
+ if (decoded !== null) {
225
+ commandPath = decoded;
224
226
  continue;
225
227
  }
226
228
  // Other TOML lines are ignored only by this local grammar. Whole-file schema
@@ -353,9 +355,9 @@ export function decodeManagedCommandLine(trimmedLine) {
353
355
  * True if a parsed `hooks[]` array contains a clean enforcing entry for
354
356
  * `expectedCommand`: `event="PreToolUse"`, byte-exact `command`, NO `matcher`
355
357
  * (any spelling the parser normalized to the `matcher` key can disable/narrow
356
- * the hook), and no keys beyond {event,command,timeout} (a stray key is fatal to
357
- * kimi-code's strict schema). Each host's hook path is distinct, so the command
358
- * uniquely identifies this host's entry.
358
+ * the hook), no keys beyond {event,command,timeout} (a stray key is fatal to
359
+ * kimi-code's strict schema), and a timeout kimi-code waits out. Each host's
360
+ * hook path is distinct, so the command uniquely identifies this host's entry.
359
361
  */
360
362
  function countCleanEntries(hooks, expectedCommand) {
361
363
  if (!Array.isArray(hooks))
@@ -374,12 +376,62 @@ function countCleanEntries(hooks, expectedCommand) {
374
376
  continue;
375
377
  if (!Object.keys(rec).every((k) => allowedKeys.has(k)))
376
378
  continue;
379
+ if (!hookTimeoutEnforces(rec.timeout))
380
+ continue;
377
381
  count += 1;
378
382
  }
379
383
  return count;
380
384
  }
381
- function hooksArrayHasCleanEntry(hooks, expectedCommand) {
382
- return countCleanEntries(hooks, expectedCommand) > 0;
385
+ /** Clean entries in the whole file's parsed `hooks[]`; 0 when it does not parse. */
386
+ export function countCleanEntriesInFile(contents, expectedCommand) {
387
+ let parsed;
388
+ try {
389
+ parsed = parseToml(contents);
390
+ }
391
+ catch {
392
+ return 0;
393
+ }
394
+ if (parsed === null || typeof parsed !== "object")
395
+ return 0;
396
+ return countCleanEntries(parsed.hooks, expectedCommand);
397
+ }
398
+ /**
399
+ * The first PreToolUse entry with this exact command whose timeout kimi-code
400
+ * would not wait out, in whole-file parse order (a `timeout` after the END
401
+ * marker binds to the same table). kimi-code runs only the first entry per
402
+ * command, after matcher filtering, so a short copy anywhere can be the one
403
+ * that runs and its timeout is read as allow. `null` when every copy enforces
404
+ * or the file does not parse; parse failures already fail closed elsewhere.
405
+ */
406
+ export function findShortHookTimeout(contents, expectedCommand) {
407
+ let parsed;
408
+ try {
409
+ parsed = parseToml(contents);
410
+ }
411
+ catch {
412
+ return null;
413
+ }
414
+ const hooks = parsed?.hooks;
415
+ if (!Array.isArray(hooks))
416
+ return null;
417
+ for (const entry of hooks) {
418
+ if (entry === null || typeof entry !== "object")
419
+ continue;
420
+ const rec = entry;
421
+ if (rec.event !== "PreToolUse" || rec.command !== expectedCommand)
422
+ continue;
423
+ if (!hookTimeoutEnforces(rec.timeout))
424
+ return { timeout: rec.timeout };
425
+ }
426
+ return null;
427
+ }
428
+ /** `timeout = <value>` as written, for diagnoses. */
429
+ export function describeHookTimeout(timeout) {
430
+ const shown = typeof timeout === "number" || typeof timeout === "bigint" ? String(timeout) : JSON.stringify(timeout);
431
+ return `timeout = ${shown}`;
432
+ }
433
+ export function hookTimeoutReason(timeout) {
434
+ return `this host's hook entry has ${describeHookTimeout(timeout)}; kimi-code reads a hook that runs past its timeout as allow, so the entry needs a timeout of at least ${HOOK_TIMEOUT_S} seconds. Run /kimi:setup to rewrite it; setup leaves the config unchanged and names any copy it cannot rewrite.`;
383
435
  }
384
436
  /**
385
437
  * Parser-based fallback used only in the absent state. Parse the WHOLE file
@@ -393,18 +445,9 @@ function hooksArrayHasCleanEntry(hooks, expectedCommand) {
393
445
  * errors fail closed. Callers run whole-file schema validation first.
394
446
  */
395
447
  export function hasCleanEnforcingHookEntry(contents, expectedCommand) {
396
- let parsed;
397
- try {
398
- parsed = parseToml(contents);
399
- }
400
- catch {
401
- return false;
402
- }
403
- if (parsed === null || typeof parsed !== "object")
404
- return false;
405
448
  const lines = contents.split("\n").map((line) => line.replace(/\r$/, ""));
406
449
  const managedWithCommand = pairBlocks(lines).blocks.filter((block) => block.commandPath === expectedCommand).length;
407
- return countCleanEntries(parsed.hooks, expectedCommand) > managedWithCommand;
450
+ return countCleanEntriesInFile(contents, expectedCommand) > managedWithCommand;
408
451
  }
409
452
  /**
410
453
  * Whole-file parser check for the FOUND (marked-block present) path. The line
@@ -417,20 +460,20 @@ export function hasCleanEnforcingHookEntry(contents, expectedCommand) {
417
460
  * and rejects it. Fail-closed on any parse error.
418
461
  */
419
462
  function foundHookEntryIsClean(contents, expectedCommand) {
420
- let parsed;
421
- try {
422
- parsed = parseToml(contents);
423
- }
424
- catch {
425
- return false;
426
- }
427
- if (parsed === null || typeof parsed !== "object")
428
- return false;
429
- return hooksArrayHasCleanEntry(parsed.hooks, expectedCommand);
463
+ return countCleanEntriesInFile(contents, expectedCommand) > 0;
430
464
  }
431
465
  export function evaluateInstalled(contents, expectedCommand, opts) {
432
466
  const { state } = parseManagedBlock(contents, opts.hostId);
467
+ const shortTimeout = findShortHookTimeout(contents, expectedCommand);
468
+ const timeoutRefusal = () => ({
469
+ installed: false,
470
+ reason: hookTimeoutReason(shortTimeout.timeout),
471
+ state,
472
+ timeoutTooShort: true,
473
+ });
433
474
  if (state.kind === "absent") {
475
+ if (shortTimeout !== null)
476
+ return timeoutRefusal();
434
477
  // kimi-code config rewrites drop comments but leave hook tables intact. In
435
478
  // the absent state only, accept a marker-less table that is exactly this
436
479
  // host's clean enforcing hook: markers are not the security boundary, the
@@ -493,6 +536,8 @@ export function evaluateInstalled(contents, expectedCommand, opts) {
493
536
  drift: classifyHookCommandDrift(state.commandPath, expectedCommand),
494
537
  };
495
538
  }
539
+ if (shortTimeout !== null)
540
+ return timeoutRefusal();
496
541
  if (!foundHookEntryIsClean(contents, expectedCommand)) {
497
542
  return {
498
543
  installed: false,
@@ -27,7 +27,7 @@ export class JobStore {
27
27
  throw translateSqliteError(error);
28
28
  }
29
29
  this.db = db;
30
- // Every `this.db.exec` / `tableHasColumn` below can throw on a
30
+ // Every `this.db.exec` / `existingColumns` below can throw on a
31
31
  // corrupt DB, full disk, mid-migration failure, etc. Catch
32
32
  // internally, close the adapter, and rethrow the translated error
33
33
  // so the SQLite handle never leaks past a failed migration.
@@ -67,35 +67,10 @@ export class JobStore {
67
67
  error TEXT
68
68
  );
69
69
  `);
70
- if (!tableHasColumn(this.db, "phase")) {
71
- this.db.exec(`ALTER TABLE jobs ADD COLUMN phase TEXT;`);
72
- }
73
- if (!tableHasColumn(this.db, "budget_ms")) {
74
- this.db.exec(`ALTER TABLE jobs ADD COLUMN budget_ms INTEGER;`);
75
- }
76
- for (const column of ["kimi_session_id_source", "budget_source", "thinking_effort", "hook_escapes"]) {
77
- if (!tableHasColumn(this.db, column)) {
78
- this.db.exec("ALTER TABLE jobs ADD COLUMN " + column + " TEXT;");
79
- }
80
- }
81
- // Additive provenance migration. Existing rows deliberately remain NULL:
82
- // v1.9.5 plus kimi-code 0.33/0.34 could have routed to native v2 before the
83
- // legacy pin landed, so a blanket historical v1 backfill would invent fact.
84
- const provenanceColumns = [
85
- "operation_kind",
86
- "intended_engine",
87
- "observed_engine",
88
- "kimi_version",
89
- "system_version",
90
- "kimi_command",
91
- "kimi_prefix_args",
92
- "plan_certification",
93
- "resumed_from_job_id",
94
- "safety_profile",
95
- ];
96
- for (const column of provenanceColumns) {
97
- if (!tableHasColumn(this.db, column)) {
98
- this.db.exec(`ALTER TABLE jobs ADD COLUMN ${column} TEXT;`);
70
+ for (const [column, type] of ADDED_JOB_COLUMNS) {
71
+ // Re-read per column: another process may be migrating the same store.
72
+ if (!existingColumns(this.db, "jobs").has(column)) {
73
+ this.db.exec(`ALTER TABLE jobs ADD COLUMN ${column} ${type};`);
99
74
  }
100
75
  }
101
76
  this.db.exec(`
@@ -171,7 +146,7 @@ export class JobStore {
171
146
  -- 0.1.6 migration: rename adversarial_review to challenge
172
147
  UPDATE jobs SET command_type = 'challenge' WHERE command_type = 'adversarial_review';
173
148
  `);
174
- if (!mcpTableHasColumn(this.db, "kimi_identity")) {
149
+ if (!existingColumns(this.db, "mcp_tasks").has("kimi_identity")) {
175
150
  this.db.exec("ALTER TABLE mcp_tasks ADD COLUMN kimi_identity TEXT;");
176
151
  }
177
152
  }
@@ -205,22 +180,7 @@ export class JobStore {
205
180
  createJob(input) {
206
181
  const now = new Date().toISOString();
207
182
  try {
208
- this.db.run(`
209
- INSERT INTO jobs (
210
- job_id, repo_id, command_type, created_at, updated_at, cwd, model, thinking, thinking_effort,
211
- background, pid, kimi_pid, status, kimi_session_id, kimi_session_id_source, budget_source,
212
- operation_kind, intended_engine, observed_engine, kimi_version, system_version,
213
- kimi_command, kimi_prefix_args, plan_certification, resumed_from_job_id, safety_profile,
214
- agent_profile, prompt_digest, summary, phase, budget_ms, final_output_path, stream_log_path, error
215
- )
216
- VALUES (
217
- @job_id, @repo_id, @command_type, @created_at, @updated_at, @cwd, @model, @thinking, @thinking_effort,
218
- @background, @pid, @kimi_pid, @status, @kimi_session_id, @kimi_session_id_source, @budget_source,
219
- @operation_kind, @intended_engine, @observed_engine, @kimi_version, @system_version,
220
- @kimi_command, @kimi_prefix_args, @plan_certification, @resumed_from_job_id, @safety_profile,
221
- @agent_profile, @prompt_digest, @summary, @phase, @budget_ms, @final_output_path, @stream_log_path, @error
222
- )
223
- `, {
183
+ this.db.run(INSERT_JOB_SQL, {
224
184
  ...serializeRecord(input),
225
185
  created_at: now,
226
186
  updated_at: now,
@@ -247,6 +207,10 @@ export class JobStore {
247
207
  hasSessionId(sessionId, exceptJobId = "") {
248
208
  return Boolean(this.db.get("SELECT 1 FROM jobs WHERE kimi_session_id = ? AND job_id != ? LIMIT 1", sessionId, exceptJobId));
249
209
  }
210
+ /** Every job recorded for a Kimi session, across repos and states, oldest first. */
211
+ listJobsBySessionId(sessionId) {
212
+ return this.db.all("SELECT * FROM jobs WHERE kimi_session_id = ? ORDER BY created_at", sessionId).map(hydrateRow);
213
+ }
250
214
  findLatestJob(options) {
251
215
  const conditions = ["repo_id = @repo_id"];
252
216
  const params = {
@@ -270,27 +234,21 @@ export class JobStore {
270
234
  return rows.map(hydrateRow);
271
235
  }
272
236
  findRescueJobBySession(repoId, sessionId) {
273
- const row = this.db.get(`
274
- SELECT *
275
- FROM jobs
276
- WHERE repo_id = ?
277
- AND command_type = 'rescue'
278
- AND kimi_session_id = ?
279
- ORDER BY updated_at DESC
280
- LIMIT 1
281
- `, repoId, sessionId);
282
- return row ? hydrateRow(row) : null;
237
+ return this.findJobBySession("rescue", repoId, sessionId);
283
238
  }
284
239
  findAskJobBySession(repoId, sessionId) {
240
+ return this.findJobBySession("ask", repoId, sessionId);
241
+ }
242
+ findJobBySession(commandType, repoId, sessionId) {
285
243
  const row = this.db.get(`
286
244
  SELECT *
287
245
  FROM jobs
288
246
  WHERE repo_id = ?
289
- AND command_type = 'ask'
247
+ AND command_type = ?
290
248
  AND kimi_session_id = ?
291
249
  ORDER BY updated_at DESC
292
250
  LIMIT 1
293
- `, repoId, sessionId);
251
+ `, repoId, commandType, sessionId);
294
252
  return row ? hydrateRow(row) : null;
295
253
  }
296
254
  createMcpTask(input) {
@@ -327,8 +285,25 @@ export class JobStore {
327
285
  this.db.run(`UPDATE mcp_tasks SET ${updates.join(", ")} WHERE task_id = @task_id`, params);
328
286
  return this.getMcpTask(taskId);
329
287
  }
288
+ /** Terminal states are permanent: every update is guarded by status = 'running'. */
330
289
  updateRunningJob(jobId, patch) {
331
- return this.updateWhere(jobId, patch, "status = 'running'");
290
+ const updates = ["updated_at = @updated_at"];
291
+ const params = {
292
+ job_id: jobId,
293
+ updated_at: new Date().toISOString(),
294
+ };
295
+ for (const [key, value] of Object.entries(serializePatch(patch))) {
296
+ if (value === undefined || !UPDATABLE_JOB_COLUMNS.has(key))
297
+ continue;
298
+ updates.push(`${key} = @${key}`);
299
+ params[key] = value;
300
+ }
301
+ this.db.run(`
302
+ UPDATE jobs
303
+ SET ${updates.join(", ")}
304
+ WHERE job_id = @job_id AND status = 'running'
305
+ `, params);
306
+ return this.getJob(jobId);
332
307
  }
333
308
  /** Recheck uniqueness atomically: another worker can claim an ID during the
334
309
  * asynchronous directory scan. Ordinary announced/resumed IDs may be shared. */
@@ -366,73 +341,73 @@ export class JobStore {
366
341
  return this.getJob(jobId);
367
342
  }
368
343
  markCompleted(jobId, patch) {
369
- return this.updateWhere(jobId, { ...patch, status: "completed", pid: null, kimi_pid: null }, "status = 'running'");
344
+ return this.updateRunningJob(jobId, { ...patch, status: "completed", pid: null, kimi_pid: null });
370
345
  }
371
346
  markFailed(jobId, patch) {
372
- return this.updateWhere(jobId, { ...patch, status: "failed", pid: null, kimi_pid: null }, "status = 'running'");
347
+ return this.updateRunningJob(jobId, { ...patch, status: "failed", pid: null, kimi_pid: null });
373
348
  }
374
349
  markCancelled(jobId, patch) {
375
- return this.updateWhere(jobId, { ...patch, status: "cancelled", pid: null, kimi_pid: null }, "status = 'running'");
376
- }
377
- static JOBS_COLUMNS = new Set([
378
- "status", "summary", "phase", "budget_ms", "budget_source", "kimi_session_id_source", "pid", "kimi_pid",
379
- "final_output_path", "stream_log_path", "kimi_session_id",
380
- "error", "command_type", "prompt_digest", "repo_id",
381
- "cwd", "model", "thinking", "thinking_effort", "hook_escapes", "background", "agent_profile",
382
- "operation_kind", "intended_engine", "observed_engine", "kimi_version",
383
- "system_version", "kimi_command", "kimi_prefix_args", "plan_certification",
384
- "resumed_from_job_id", "safety_profile",
385
- ]);
386
- updateWhere(jobId, patch, whereClause) {
387
- const updates = ["updated_at = @updated_at"];
388
- const params = {
389
- job_id: jobId,
390
- updated_at: new Date().toISOString(),
391
- };
392
- for (const [key, value] of Object.entries(serializePatch(patch))) {
393
- if (key === "job_id" || key === "created_at" || key === "updated_at" || value === undefined) {
394
- continue;
395
- }
396
- if (!JobStore.JOBS_COLUMNS.has(key))
397
- continue;
398
- updates.push(`${key} = @${key}`);
399
- params[key] = value;
400
- }
401
- const statement = `
402
- UPDATE jobs
403
- SET ${updates.join(", ")}
404
- WHERE job_id = @job_id${whereClause ? ` AND ${whereClause}` : ""}
405
- `;
406
- this.db.run(statement, params);
407
- return this.getJob(jobId);
350
+ return this.updateRunningJob(jobId, { ...patch, status: "cancelled", pid: null, kimi_pid: null });
408
351
  }
409
352
  }
353
+ /** Columns added after the first schema, in the order older stores receive them. */
354
+ const ADDED_JOB_COLUMNS = [
355
+ ["phase", "TEXT"],
356
+ ["budget_ms", "INTEGER"],
357
+ ["kimi_session_id_source", "TEXT"],
358
+ ["budget_source", "TEXT"],
359
+ ["thinking_effort", "TEXT"],
360
+ ["hook_escapes", "TEXT"],
361
+ // Additive provenance migration. Existing rows deliberately remain NULL:
362
+ // v1.9.5 plus kimi-code 0.33/0.34 could have routed to native v2 before the
363
+ // legacy pin landed, so a blanket historical v1 backfill would invent fact.
364
+ ["operation_kind", "TEXT"],
365
+ ["intended_engine", "TEXT"],
366
+ ["observed_engine", "TEXT"],
367
+ ["kimi_version", "TEXT"],
368
+ ["system_version", "TEXT"],
369
+ ["kimi_command", "TEXT"],
370
+ ["kimi_prefix_args", "TEXT"],
371
+ ["plan_certification", "TEXT"],
372
+ ["resumed_from_job_id", "TEXT"],
373
+ ["safety_profile", "TEXT"],
374
+ ["warnings", "TEXT"],
375
+ ["read_scope", "TEXT"],
376
+ ];
377
+ /** Columns createJob writes, in INSERT order. hook_escapes is written only by updates. */
378
+ const INSERT_JOB_COLUMNS = [
379
+ "job_id", "repo_id", "command_type", "created_at", "updated_at", "cwd", "model", "thinking", "thinking_effort",
380
+ "background", "pid", "kimi_pid", "status", "kimi_session_id", "kimi_session_id_source", "budget_source",
381
+ "operation_kind", "intended_engine", "observed_engine", "kimi_version", "system_version",
382
+ "kimi_command", "kimi_prefix_args", "plan_certification", "resumed_from_job_id", "safety_profile", "warnings",
383
+ "read_scope", "agent_profile", "prompt_digest", "summary", "phase", "budget_ms", "final_output_path", "stream_log_path", "error",
384
+ ];
385
+ const INSERT_JOB_SQL = `INSERT INTO jobs (${INSERT_JOB_COLUMNS.join(", ")}) VALUES (${INSERT_JOB_COLUMNS.map((column) => `@${column}`).join(", ")})`;
386
+ /** Columns an update may set; identity and timestamps are store-owned. */
387
+ const UPDATABLE_JOB_COLUMNS = new Set([
388
+ ...INSERT_JOB_COLUMNS.filter((column) => column !== "job_id" && column !== "created_at" && column !== "updated_at"),
389
+ "hook_escapes",
390
+ ]);
410
391
  function hydrateRow(row) {
392
+ // A warning-free row keeps its historical shape, so every JSON surface that
393
+ // spreads a JobRecord stays byte-identical.
394
+ const { warnings, read_scope, ...rest } = row;
411
395
  return {
412
- ...row,
396
+ ...rest,
397
+ ...(warnings !== null && warnings !== undefined ? { warnings } : {}),
398
+ ...(read_scope !== null && read_scope !== undefined ? { read_scope } : {}),
413
399
  thinking: row.thinking === null ? null : Boolean(row.thinking),
414
400
  background: Boolean(row.background),
415
401
  error: row.error ? JSON.parse(row.error) : null,
416
402
  };
417
403
  }
404
+ // Spreads the whole input so node:sqlite still rejects keys that are not INSERT parameters.
418
405
  function serializeRecord(record) {
406
+ const row = { ...record };
407
+ for (const column of INSERT_JOB_COLUMNS)
408
+ row[column] ??= null;
419
409
  return {
420
- ...record,
421
- thinking_effort: record.thinking_effort ?? null,
422
- phase: record.phase ?? null,
423
- budget_ms: record.budget_ms ?? null,
424
- budget_source: record.budget_source ?? null,
425
- kimi_session_id_source: record.kimi_session_id_source ?? null,
426
- operation_kind: record.operation_kind ?? null,
427
- intended_engine: record.intended_engine ?? null,
428
- observed_engine: record.observed_engine ?? null,
429
- kimi_version: record.kimi_version ?? null,
430
- system_version: record.system_version ?? null,
431
- kimi_command: record.kimi_command ?? null,
432
- kimi_prefix_args: record.kimi_prefix_args ?? null,
433
- plan_certification: record.plan_certification ?? null,
434
- resumed_from_job_id: record.resumed_from_job_id ?? null,
435
- safety_profile: record.safety_profile ?? null,
410
+ ...row,
436
411
  thinking: record.thinking === null ? null : Number(record.thinking),
437
412
  background: Number(record.background),
438
413
  error: record.error ? JSON.stringify(record.error) : null,
@@ -589,12 +564,8 @@ function rewriteNamedParamsForBun(statement) {
589
564
  function rewriteNamedBindingsForBun(bindings) {
590
565
  return Object.fromEntries(Object.entries(bindings).map(([key, value]) => [`$${key}`, value]));
591
566
  }
592
- function tableHasColumn(db, columnName) {
593
- const columns = db.all(`PRAGMA table_info(jobs)`);
594
- return columns.some((column) => column.name === columnName);
595
- }
596
- function mcpTableHasColumn(db, columnName) {
597
- return db.all("PRAGMA table_info(mcp_tasks)").some((column) => column.name === columnName);
567
+ function existingColumns(db, table) {
568
+ return new Set(db.all(`PRAGMA table_info(${table})`).map((column) => column.name));
598
569
  }
599
570
  function isSqliteConstraintError(error) {
600
571
  const message = formatError(error).toLowerCase();
@@ -630,24 +601,25 @@ export async function withJobStore(paths, fn) {
630
601
  store?.close();
631
602
  }
632
603
  }
633
- /** Synchronous companion to `withJobStore` for callers that don't await inside. */
634
- export function withJobStoreSync(paths, fn) {
635
- let store;
604
+ /** Parsed `hook_escapes` column for JSON envelopes: [] when NULL or unreadable. */
605
+ export function parseHookEscapes(raw) {
606
+ if (!raw)
607
+ return [];
636
608
  try {
637
- store = new JobStore(paths);
638
- return fn(store);
609
+ const parsed = JSON.parse(raw);
610
+ return Array.isArray(parsed) ? parsed : [];
639
611
  }
640
- finally {
641
- store?.close();
612
+ catch {
613
+ return [];
642
614
  }
643
615
  }
644
- /** Parsed `hook_escapes` column for JSON envelopes: [] when NULL or unreadable. */
645
- export function parseHookEscapes(raw) {
616
+ /** Parsed `warnings` column: [] when NULL or unreadable. */
617
+ export function parseJobWarnings(raw) {
646
618
  if (!raw)
647
619
  return [];
648
620
  try {
649
621
  const parsed = JSON.parse(raw);
650
- return Array.isArray(parsed) ? parsed : [];
622
+ return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : [];
651
623
  }
652
624
  catch {
653
625
  return [];
@@ -1,9 +1,7 @@
1
- import { createHash } from "node:crypto";
2
1
  import { RuntimeError } from "./errors.js";
3
- import { formatBudgetDuration, renderTerminalJobArtifact, writeArtifact } from "./render.js";
4
- export function digestPrompt(prompt) {
5
- return createHash("sha256").update(prompt).digest("hex");
6
- }
2
+ import { capitalize, formatBudgetDuration, renderTerminalJobArtifact, writeArtifact } from "./render.js";
3
+ import { sleep } from "./util.js";
4
+ export { sha256 as digestPrompt } from "./git.js";
7
5
  export function normalizeJobError(error) {
8
6
  if (error instanceof RuntimeError) {
9
7
  const normalized = {
@@ -34,13 +32,12 @@ export async function markJobFailed(store, paths, job, error, summary = "Job fai
34
32
  if (current.status !== "running")
35
33
  return current;
36
34
  if (options?.partialOutput) {
37
- const label = job.command_type[0].toUpperCase() + job.command_type.slice(1);
38
- summary = `${label} timed out after ${formatBudgetDuration(options.partialOutput.budgetMs)}; partial output captured (${options.partialOutput.text.trim().length} chars).`;
35
+ summary = `${capitalize(job.command_type)} timed out after ${formatBudgetDuration(options.partialOutput.budgetMs)}; partial output captured (${options.partialOutput.text.trim().length} chars).`;
39
36
  }
40
37
  const normalized = normalizeJobError(error);
41
38
  const phase = options?.phase;
42
39
  const artifactJob = {
43
- ...(store.getJob(job.job_id) ?? job),
40
+ ...current,
44
41
  status: "failed",
45
42
  summary,
46
43
  error: normalized,
@@ -102,7 +99,7 @@ export async function sweepStaleJobs(store, paths) {
102
99
  ? `Background worker pid ${job.pid} is no longer running.`
103
100
  : `Kimi pid ${job.kimi_pid} is no longer running while background worker pid ${job.pid} is still recorded.`, "jobs.sweep"), companionMissing
104
101
  ? "Background worker disappeared before reporting a terminal state."
105
- : "Kimi process disappeared before reporting a terminal state.", job.command_type === "ask" || job.command_type === "rescue" ? { phase: "failed" } : undefined);
102
+ : "Kimi process disappeared before reporting a terminal state.", lineagePhase(job, "failed"));
106
103
  continue;
107
104
  }
108
105
  if (!companionMissing && !kimiMissing) {
@@ -117,10 +114,14 @@ export async function sweepStaleJobs(store, paths) {
117
114
  continue;
118
115
  }
119
116
  terminateRecordedProcesses(job);
120
- await markJobFailed(store, paths, job, new RuntimeError("FOREGROUND_PROCESS_DISAPPEARED", describeMissingForegroundProcess(job, companionMissing, kimiMissing), "jobs.sweep"), "Foreground Kimi job disappeared before reporting a terminal state.", job.command_type === "ask" || job.command_type === "rescue" ? { phase: "failed" } : undefined);
117
+ await markJobFailed(store, paths, job, new RuntimeError("FOREGROUND_PROCESS_DISAPPEARED", describeMissingForegroundProcess(job, companionMissing, kimiMissing), "jobs.sweep"), "Foreground Kimi job disappeared before reporting a terminal state.", lineagePhase(job, "failed"));
121
118
  }
122
119
  }
123
120
  export const STALE_SWEEP_GRACE_MS = 15_000;
121
+ /** Ask and rescue rows track a phase; the other lineages leave it untouched. */
122
+ export function lineagePhase(job, phase) {
123
+ return job.command_type === "ask" || job.command_type === "rescue" ? { phase } : undefined;
124
+ }
124
125
  function isStaleEnoughToSweep(job) {
125
126
  const updatedAt = Date.parse(job.updated_at);
126
127
  return Number.isFinite(updatedAt) && Date.now() - updatedAt >= STALE_SWEEP_GRACE_MS;
@@ -158,7 +159,7 @@ function terminateRecordedProcesses(job) {
158
159
  timer.unref();
159
160
  }
160
161
  }
161
- function killPid(pid, signal) {
162
+ export function killPid(pid, signal) {
162
163
  try {
163
164
  process.kill(pid, signal);
164
165
  }
@@ -171,7 +172,7 @@ function killPid(pid, signal) {
171
172
  }
172
173
  }
173
174
  }
174
- function isPidAlive(pid) {
175
+ export function isPidAlive(pid) {
175
176
  try {
176
177
  process.kill(pid, 0);
177
178
  return true;
@@ -185,8 +186,7 @@ function isPidAlive(pid) {
185
186
  // pid in v0.2.2+; under normal usage we should always have permission
186
187
  // to signal our own descendants. Returning true here lets stale jobs
187
188
  // hide forever (the sweeper relies on isPidAlive=false to flip them to
188
- // failed). signalJobProcesses and killPid already swallow EPERM
189
- // consistently — this brings the read path in line with the write path.
189
+ // failed). killPid swallows EPERM the same way.
190
190
  if (code === "ESRCH" || code === "EPERM") {
191
191
  return false;
192
192
  }
@@ -210,8 +210,3 @@ export async function waitForTerminalJob(storeFactory, jobId, timeoutMs = 60_000
210
210
  }
211
211
  throw new RuntimeError("JOB_WAIT_TIMEOUT", `Timed out after ${timeoutMs}ms while waiting for job ${jobId} to finish. The worker may still be running; use /kimi:status ${jobId} to check progress or /kimi:result ${jobId} once it completes.`, "jobs.wait");
212
212
  }
213
- function sleep(ms) {
214
- return new Promise((resolve) => {
215
- setTimeout(resolve, ms);
216
- });
217
- }