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
@@ -2,7 +2,7 @@ import { RuntimeError } from "../errors.js";
2
2
  import { resolveRepoIdentity } from "../git.js";
3
3
  import { sweepStaleJobs } from "../jobs.js";
4
4
  import { reconcileHistoricalJobProvenance } from "../kimi-engine.js";
5
- import { parseHookEscapes, renderBudgetSource, withJobStore } from "../job-store.js";
5
+ import { parseHookEscapes, parseJobWarnings, renderBudgetSource, withJobStore } from "../job-store.js";
6
6
  import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
7
7
  import { parseJobLookupArgs } from "../parsing.js";
8
8
  export async function runStatus(argv, context) {
@@ -22,6 +22,6 @@ export async function runStatus(argv, context) {
22
22
  throw new RuntimeError("JOB_NOT_FOUND", "No matching job was found for status.", "status.lookup");
23
23
  }
24
24
  const job = await reconcileHistoricalJobProvenance(store, found);
25
- return `${JSON.stringify({ ...job, swarm_recovery: store.getSwarmRecovery(job.job_id)?.record ?? null, thinking_effort_requested: job.thinking_effort ?? null, hook_escapes: parseHookEscapes(job.hook_escapes), budget_source: renderBudgetSource(job) }, null, 2)}\n`;
25
+ return `${JSON.stringify({ ...job, swarm_recovery: store.getSwarmRecovery(job.job_id)?.record ?? null, thinking_effort_requested: job.thinking_effort ?? null, hook_escapes: parseHookEscapes(job.hook_escapes), budget_source: renderBudgetSource(job), ...(job.warnings ? { warnings: parseJobWarnings(job.warnings) } : {}) }, null, 2)}\n`;
26
26
  });
27
27
  }
@@ -17,31 +17,32 @@ import { KIMI_SWARM_DEFAULT_BUDGET_MS } from "../kimi-timeouts.js";
17
17
  import { writeInvocationLogHeader } from "../logging.js";
18
18
  import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
19
19
  import { parseSwarmArgs } from "../parsing.js";
20
+ import { parseJobReadScope, resolveReadScope, serializeReadScope } from "../read-scope.js";
20
21
  import { readArtifact, renderManagedJobOutput, writeArtifact } from "../render.js";
21
- import { hookRefusalDetails, hookRefusalRetryProtocol, maybeWarnHookMissing, verifyHookInstalled, } from "../hooks/install.js";
22
+ import { hookGateRefusal, verifyHookInstalled } from "../hooks/install.js";
22
23
  import { assertCliResultSuccess, reassembleProseFromRecords, warnIfSessionIdMissing, warnHookEscapes } from "./cli-helpers.js";
23
24
  import { buildKimiSessionTitle, syncKimiSessionTitle } from "../session-title.js";
24
25
  import { usesBoundedSwarmPolicy } from "../swarm-policy.js";
25
26
  // /kimi:swarm — parallel fan-out, read-only by default and runtime-foreground-only.
26
27
  // A finite wall-clock budget bounds the whole run. --cap is a SOFT total-count
27
- // prompt hint. Exact native-v2 2.6.2/2.6.3/2.7.2 bounds admitted waves and prevents native
28
+ // prompt hint. A bounded-swarm release (kimi-releases.ts) bounds admitted waves and prevents native
28
29
  // child timeouts from returning a continuing coordinator before children stop.
29
30
  // Concurrency 1 uses a direct worker without native fan-out. Older versions keep
30
31
  // their normal-launch setting and inherited recovery limitation. Read/write
31
32
  // modes reuse review/rescue lineage, and the
32
33
  // mandatory PreToolUse hook enforces read-only policy or trusted-worktree write
33
34
  // confinement on the coordinator and every subagent. Write mode requires
34
- // kimi-code 0.18.0+. Exact 2.3.2, 2.3.3, 2.4.0, 2.4.1, 2.5.0, 2.5.1, 2.5.2,
35
- // and certified 2.5.3 activate a same-job session through a bounded loopback
36
- // web lifecycle, then resume it through the normal print path. 2.6.2/2.6.3 parallel
37
- // waves, 2.7.2 JSON-authenticated waves, and candidate-only 2.6.0 use that lifecycle too. The per-operation certification
35
+ // kimi-code 0.18.0+. A web-preactivation release activates a same-job session
36
+ // through a bounded loopback web lifecycle, then resumes it through the normal
37
+ // print path; bounded-swarm parallel waves, web-json-ready authenticated waves
38
+ // and candidate-only 2.6.0 use that lifecycle too. The per-operation certification
38
39
  // table controls whether each exact version is reachable in production.
39
40
  const SWARM_SUMMARY_MAX = 120;
40
41
  const SWARM_AGENT_PROFILE = "<swarm>";
41
42
  const SWARM_WRITE_AGENT_PROFILE = "<swarm-write>";
42
43
  /**
43
44
  * Default concurrency setting when the user passes no `--max-concurrency`.
44
- * Exact native-v2 2.6.2/2.6.3/2.7.2 also enforces this as the admitted wave size. The plugin exports
45
+ * A bounded-swarm release also enforces this as the admitted wave size. The plugin exports
45
46
  * KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY; older read-only swarms ignore it and
46
47
  * retain only the wall-clock hard bound. Rate-limit recovery can exceed it on
47
48
  * older reviewed sources; their setting is not an unconditional peak guarantee.
@@ -57,7 +58,7 @@ export function resolveSwarmMaxConcurrency(requested) {
57
58
  return requested ?? SWARM_DEFAULT_MAX_CONCURRENCY;
58
59
  }
59
60
  /**
60
- * Default concurrency for WRITE mode — 1 vs read's 4. Exact native-v2 2.6.2/2.6.3/2.7.2
61
+ * Default concurrency for WRITE mode — 1 vs read's 4. A bounded-swarm release
61
62
  * runs one direct worker; older versions serialize normal child launches but
62
63
  * retain the rate-limit recovery overrun. Disjoint-target partitioning remains
63
64
  * prompt-only when parallel workers are explicitly requested.
@@ -209,12 +210,14 @@ export async function runSwarm(argv, context) {
209
210
  if (!objective) {
210
211
  throw new RuntimeError("INVALID_ARGS", "/kimi:swarm requires an objective. Usage: /kimi:swarm [--write] [--budget 30m] [--cap N] [--max-concurrency N] [-m model] <objective>", "swarm.parse");
211
212
  }
212
- return parsed.write
213
- ? runWriteSwarm(parsed, objective, context)
214
- : runReadSwarm(parsed, objective, context);
213
+ if (parsed.write)
214
+ return runWriteSwarm(parsed, objective, context);
215
+ const readScope = parsed.readRoots === undefined && parsed.network === undefined ? undefined
216
+ : await resolveReadScope(parsed.readRoots, parsed.network, "swarm.parse");
217
+ return runReadSwarm(parsed, objective, context, readScope);
215
218
  }
216
219
  /** Read-only swarm (default). */
217
- async function runReadSwarm(parsed, objective, context) {
220
+ async function runReadSwarm(parsed, objective, context, readScope) {
218
221
  const paths = resolvePluginPaths(context.env);
219
222
  await ensurePluginPaths(paths);
220
223
  const repoIdentity = await resolveRepoIdentity(context.cwd);
@@ -225,49 +228,19 @@ async function runReadSwarm(parsed, objective, context) {
225
228
  operationKind: "swarm",
226
229
  cwd: context.cwd,
227
230
  env: context.env,
231
+ stderr: context.stderr,
228
232
  });
229
233
  const maxConcurrency = resolveSwarmMaxConcurrency(parsed.maxConcurrency);
230
234
  const prompt = buildSwarmPrompt(objective, parsed.cap, usesBoundedSwarmPolicy(executionPlan) ? maxConcurrency : undefined);
231
235
  const jobId = allocateJobId(context);
232
236
  const logPath = path.join(paths.logsDir, `swarm-${jobId}.jsonl`);
233
- const job = store.createJob({
234
- job_id: jobId,
235
- repo_id: repoIdentity.repoId,
236
- // Reuse the read-only review lineage; the hook label below ("swarm") is
237
- // what actually drives the allowlist.
238
- command_type: "review",
239
- cwd: context.cwd,
240
- model: parsed.model ?? null,
241
- thinking: null,
242
- thinking_effort: parsed.thinkingEffort ?? null,
243
- background: false,
244
- budget_ms: parsed.budgetMs ?? KIMI_SWARM_DEFAULT_BUDGET_MS,
245
- budget_source: parsed.budgetMs !== undefined ? "explicit" : "default",
246
- pid: process.pid,
247
- kimi_pid: null,
248
- status: "running",
249
- kimi_session_id: null,
250
- ...persistedExecutionPlanFields(executionPlan),
251
- agent_profile: SWARM_AGENT_PROFILE,
252
- prompt_digest: digestPrompt(prompt),
253
- summary: `[swarm] ${shorten(objective, SWARM_SUMMARY_MAX)}`,
254
- phase: "starting",
255
- final_output_path: null,
256
- stream_log_path: logPath,
257
- error: null,
237
+ // Reuse the read-only review lineage; the hook label ("swarm") is what
238
+ // actually drives the allowlist.
239
+ const job = await createSwarmJob(store, paths, {
240
+ jobId, repoId: repoIdentity.repoId, commandType: "review", label: "swarm",
241
+ agentProfile: SWARM_AGENT_PROFILE, failureSummary: "Swarm failed.",
242
+ parsed, objective, prompt, executionPlan, logPath, cwd: context.cwd, readScope,
258
243
  });
259
- try {
260
- await writeInvocationLogHeader(logPath, {
261
- commandType: "swarm",
262
- kimiSessionId: "(pending)",
263
- cwd: context.cwd,
264
- });
265
- }
266
- catch (error) {
267
- const classified = new RuntimeError("SWARM_LOG_HEADER_FAILED", `Failed to write swarm invocation log header: ${error.message ?? String(error)}`, "swarm.log-header", error instanceof Error ? { cause: error } : undefined);
268
- await markJobFailed(store, paths, job, classified, "Swarm failed.", { phase: "failed" });
269
- throw classified;
270
- }
271
244
  const completed = await executeSwarmJob(job.job_id, prompt, objective, job.budget_ms, maxConcurrency, context, undefined, await realpath(context.cwd));
272
245
  if (!completed.final_output_path) {
273
246
  throw new RuntimeError("SWARM_RESULT_MISSING", "Swarm finished without a rendered result.", "swarm.result");
@@ -329,50 +302,18 @@ async function runWriteSwarm(parsed, objective, context) {
329
302
  operationKind: "swarm-write",
330
303
  cwd: worktreePath,
331
304
  env: context.env,
305
+ stderr: context.stderr,
332
306
  });
333
307
  const prompt = buildSwarmWritePrompt(objective, parsed.cap, usesBoundedSwarmPolicy(executionPlan) ? maxConcurrency : undefined);
334
- const job = store.createJob({
335
- job_id: jobId,
336
- repo_id: repoIdentity.repoId,
337
- // Reuse the rescue (write-capable) lineage, like pursue; the hook label
338
- // below ("swarm-write") drives the allowlist. cwd stays the USER's real
339
- // cwd for lineage — the kimi spawn cwd is the worktree (threaded via the
340
- // writeMode arg to executeSwarmJob).
341
- command_type: "rescue",
342
- cwd: context.cwd,
343
- model: parsed.model ?? null,
344
- thinking: null,
345
- thinking_effort: parsed.thinkingEffort ?? null,
346
- background: false,
347
- budget_ms: parsed.budgetMs ?? KIMI_SWARM_DEFAULT_BUDGET_MS,
348
- budget_source: parsed.budgetMs !== undefined ? "explicit" : "default",
349
- pid: process.pid,
350
- kimi_pid: null,
351
- status: "running",
352
- kimi_session_id: null,
353
- ...persistedExecutionPlanFields(executionPlan),
354
- agent_profile: SWARM_WRITE_AGENT_PROFILE,
355
- prompt_digest: digestPrompt(prompt),
356
- summary: `[swarm-write] ${shorten(objective, SWARM_SUMMARY_MAX)}`,
357
- phase: "starting",
358
- final_output_path: null,
359
- stream_log_path: logPath,
360
- error: null,
308
+ // Reuse the rescue (write-capable) lineage, like pursue; the hook label
309
+ // ("swarm-write") drives the allowlist. cwd stays the USER's real cwd for
310
+ // lineage — the kimi spawn cwd is the worktree (threaded via the writeMode
311
+ // arg to executeSwarmJob).
312
+ const job = await createSwarmJob(store, paths, {
313
+ jobId, repoId: repoIdentity.repoId, commandType: "rescue", label: "swarm-write",
314
+ agentProfile: SWARM_WRITE_AGENT_PROFILE, failureSummary: "Swarm (write) failed.",
315
+ parsed, objective, prompt, executionPlan, logPath, cwd: context.cwd,
361
316
  });
362
- try {
363
- await writeInvocationLogHeader(logPath, {
364
- commandType: "swarm-write",
365
- kimiSessionId: "(pending)",
366
- cwd: context.cwd,
367
- });
368
- }
369
- catch (error) {
370
- const classified = new RuntimeError("SWARM_LOG_HEADER_FAILED", `Failed to write swarm-write invocation log header: ${error.message ?? String(error)}`, "swarm.log-header", error instanceof Error ? { cause: error } : undefined);
371
- await markJobFailed(store, paths, job, classified, "Swarm (write) failed.", {
372
- phase: "failed",
373
- });
374
- throw classified;
375
- }
376
317
  const completed = await executeSwarmJob(job.job_id, prompt, objective, job.budget_ms, maxConcurrency, context, {
377
318
  spawnCwd: worktreePath,
378
319
  workspaceRoot: worktreePath,
@@ -403,6 +344,51 @@ async function runWriteSwarm(parsed, objective, context) {
403
344
  store.close();
404
345
  }
405
346
  }
347
+ /**
348
+ * Create the running job row and write its invocation log header. A header
349
+ * failure marks the job failed and rethrows.
350
+ */
351
+ async function createSwarmJob(store, paths, spec) {
352
+ const { parsed } = spec;
353
+ const job = store.createJob({
354
+ job_id: spec.jobId,
355
+ repo_id: spec.repoId,
356
+ command_type: spec.commandType,
357
+ cwd: spec.cwd,
358
+ model: parsed.model ?? null,
359
+ thinking: null,
360
+ thinking_effort: parsed.thinkingEffort ?? null,
361
+ read_scope: serializeReadScope(spec.readScope),
362
+ background: false,
363
+ budget_ms: parsed.budgetMs ?? KIMI_SWARM_DEFAULT_BUDGET_MS,
364
+ budget_source: parsed.budgetMs !== undefined ? "explicit" : "default",
365
+ pid: process.pid,
366
+ kimi_pid: null,
367
+ status: "running",
368
+ kimi_session_id: null,
369
+ ...persistedExecutionPlanFields(spec.executionPlan),
370
+ agent_profile: spec.agentProfile,
371
+ prompt_digest: digestPrompt(spec.prompt),
372
+ summary: `[${spec.label}] ${shorten(spec.objective, SWARM_SUMMARY_MAX)}`,
373
+ phase: "starting",
374
+ final_output_path: null,
375
+ stream_log_path: spec.logPath,
376
+ error: null,
377
+ });
378
+ try {
379
+ await writeInvocationLogHeader(spec.logPath, {
380
+ commandType: spec.label,
381
+ kimiSessionId: "(pending)",
382
+ cwd: spec.cwd,
383
+ });
384
+ }
385
+ catch (error) {
386
+ const classified = new RuntimeError("SWARM_LOG_HEADER_FAILED", `Failed to write ${spec.label} invocation log header: ${error.message ?? String(error)}`, "swarm.log-header", error instanceof Error ? { cause: error } : undefined);
387
+ await markJobFailed(store, paths, job, classified, spec.failureSummary, { phase: "failed" });
388
+ throw classified;
389
+ }
390
+ return job;
391
+ }
406
392
  /** Refuse --write outside a git repo (git worktree add has nothing to fork). */
407
393
  function assertWriteSwarmPreconditions(repoIdentity) {
408
394
  if (!repoIdentity.isGitRepo) {
@@ -429,9 +415,6 @@ async function capturePatchArtifact(paths, jobId, worktreePath, stderr, onFailur
429
415
  }
430
416
  /** Render the patch-handoff header prepended to a write-swarm report. */
431
417
  function renderWriteSwarmHeader(captured) {
432
- if (captured === null) {
433
- return "**Patch:** capture FAILED — no patch was written; inspect the run logs.";
434
- }
435
418
  if (captured.empty) {
436
419
  return "**Patch:** the swarm made NO changes (empty patch).";
437
420
  }
@@ -468,14 +451,7 @@ writeMode, executionCwd) {
468
451
  if (context.env.KIMI_PLUGIN_CC_SKIP_HOOK_CHECK !== "1") {
469
452
  const installStatus = await verifyHookInstalled(context.env);
470
453
  if (!installStatus.installed) {
471
- maybeWarnHookMissing(installStatus, "swarm", context.stderr);
472
- const classified = new RuntimeError("SWARM_HOOK_NOT_INSTALLED", [
473
- "/kimi:swarm refuses to run without the kimi-plugin-cc PreToolUse hook.",
474
- "The hook enforces each worker's tool permissions, write confinement, and delegation limits.",
475
- `Hook check failed: ${installStatus.reason ?? "unknown"}.`,
476
- "Repair by running Claude Code /kimi:setup or Codex $kimi-setup, then retry.",
477
- hookRefusalRetryProtocol(context.env),
478
- ].join(" "), "swarm.hook-check", { details: hookRefusalDetails(installStatus) });
454
+ const classified = hookGateRefusal("swarm", installStatus, context.env, context.stderr);
479
455
  try {
480
456
  return await markJobFailed(store, paths, job, classified, "Swarm failed.", { phase: "failed" });
481
457
  }
@@ -520,10 +496,11 @@ writeMode, executionCwd) {
520
496
  const executionPlan = executionPlanFromPersisted(job);
521
497
  const boundedSwarm = usesBoundedSwarmPolicy(executionPlan);
522
498
  const singleWorker = boundedSwarm && maxConcurrency === 1;
523
- const needsPreactivation = !singleWorker && requiresSwarmPreactivation(executionPlan.kimiVersion);
499
+ const preactivationVersion = requiresSwarmPreactivation(executionPlan.kimiVersion);
500
+ const needsPreactivation = !singleWorker && preactivationVersion;
524
501
  // A direct worker still needs durable print ownership and patch recovery.
525
502
  // Its record has no activated session and never requires web cleanup.
526
- if (requiresSwarmPreactivation(executionPlan.kimiVersion)) {
503
+ if (preactivationVersion) {
527
504
  const owner = await probeProcessIdentity(process.pid);
528
505
  recovery = { schema: 1, jobId: job.job_id, ownerPid: process.pid, owner: owner.identity ?? null,
529
506
  kimiHome: resolveKimiHome(context.env, writeMode?.spawnCwd ?? job.cwd),
@@ -531,17 +508,23 @@ writeMode, executionCwd) {
531
508
  launches: [], session: null, sessionDirty: false, complete: false, patchPath: null };
532
509
  store.saveSwarmRecovery(job.job_id, recovery);
533
510
  }
534
- activationOptions = {
511
+ // Shared by the web lifecycle and the print spawn; prefixArgs stay per call.
512
+ const spawnOptions = {
535
513
  cwd: executionCwd ?? writeMode?.spawnCwd ?? job.cwd,
536
514
  env: context.env,
537
515
  command: executionPlan.command,
538
- prefixArgs: executionPlan.prefixArgs,
539
516
  executionPlan,
540
517
  commandLabel,
541
518
  model: job.model ?? undefined,
542
519
  thinkingEffort: job.thinking_effort ?? undefined,
520
+ // Read-only swarm only: write mode rejects scope flags at parse time.
521
+ readScope: writeMode ? undefined : parseJobReadScope(job.read_scope),
543
522
  swarmMaxConcurrency: maxConcurrency,
544
523
  trustedWorkspaceRoot: executionCwd ?? writeMode?.workspaceRoot,
524
+ };
525
+ activationOptions = {
526
+ ...spawnOptions,
527
+ prefixArgs: executionPlan.prefixArgs,
545
528
  expectedVersion: executionPlan.kimiVersion ?? undefined,
546
529
  onRecoveryEvent: recovery ? (event) => recordRecoveryEvent(store, recovery, event) : undefined,
547
530
  };
@@ -613,17 +596,9 @@ writeMode, executionCwd) {
613
596
  if (recovery)
614
597
  recordRecoveryEvent(store, recovery, { kind: "print-spawn" });
615
598
  const result = await runCliPromptWithBudget({
616
- cwd: activationOptions.cwd,
617
- env: context.env,
618
- command: executionPlan.command,
599
+ ...spawnOptions,
619
600
  prefixArgs: [...executionPlan.prefixArgs],
620
- executionPlan,
621
601
  prompt,
622
- commandLabel,
623
- swarmMaxConcurrency: maxConcurrency,
624
- trustedWorkspaceRoot: executionCwd ?? writeMode?.workspaceRoot,
625
- model: job.model ?? undefined,
626
- thinkingEffort: job.thinking_effort ?? undefined,
627
602
  resumeSessionId: preactivated?.sessionId,
628
603
  logPath: job.stream_log_path,
629
604
  onSpawn: async (pid) => {
@@ -644,7 +619,8 @@ writeMode, executionCwd) {
644
619
  if (recovery)
645
620
  recordRecoveryEvent(store, recovery, { kind: "print-exit" });
646
621
  store.updateRunningJob(job.job_id, observedExecutionFields(result));
647
- finalText = reassembleProseFromRecords(result.records);
622
+ const prose = reassembleProseFromRecords(result.records);
623
+ finalText = prose;
648
624
  let resultError;
649
625
  if (handlers.cancelling) {
650
626
  resultError = new RuntimeError("SWARM_CANCELLED", "Swarm cancelled by user request.", "swarm.runtime");
@@ -682,12 +658,10 @@ writeMode, executionCwd) {
682
658
  env: context.env,
683
659
  cwd: job.cwd,
684
660
  sessionId: result.sessionId ?? job.kimi_session_id,
685
- title: buildKimiSessionTitle(writeMode ? "swarm-write" : "swarm", objective),
661
+ title: buildKimiSessionTitle(commandLabel, objective),
686
662
  stderr: context.stderr,
687
663
  });
688
664
  warnIfSessionIdMissing(result, "swarm", job.job_id, context.stderr);
689
- const prose = reassembleProseFromRecords(result.records);
690
- finalText = prose;
691
665
  if (writeMode) {
692
666
  const captured = await capturePatchArtifact(paths, job.job_id, writeMode.workspaceRoot, context.stderr, writeMode.onPatchCaptureFailure);
693
667
  if (captured === null) {
@@ -716,7 +690,7 @@ writeMode, executionCwd) {
716
690
  if (recovery)
717
691
  finishRecoveryRecord(store, recovery);
718
692
  return (store.markCompleted(job.job_id, {
719
- summary: `[${writeMode ? "swarm-write" : "swarm"}] ${shorten(objective, SWARM_SUMMARY_MAX)}`,
693
+ summary: `[${commandLabel}] ${shorten(objective, SWARM_SUMMARY_MAX)}`,
720
694
  phase: "done",
721
695
  final_output_path: artifactPath,
722
696
  error: null,
@@ -12,8 +12,7 @@ export async function runWorker(argv, context) {
12
12
  throw new RuntimeError("MISSING_RESCUE_PROMPT", "Background rescue prompt is missing.", "worker");
13
13
  }
14
14
  const prompt = Buffer.from(encodedPrompt, "base64").toString("utf8");
15
- const reusedSession = context.env.KIMI_PLUGIN_CC_RESCUE_REUSED_SESSION === "1";
16
- await executeRescueJob(jobId, prompt, context, { workerPid: process.pid, reusedSession });
15
+ await executeRescueJob(jobId, prompt, context, { workerPid: process.pid });
17
16
  return;
18
17
  }
19
18
  const encodedPrompt = context.env.KIMI_PLUGIN_CC_ASK_PROMPT_B64;
@@ -13,7 +13,9 @@ import { resolveKimiHome } from "./kimi-home.js";
13
13
  import { runModelCommand } from "./model-command.js";
14
14
  import { runMcpChild } from "./mcp/supervised-child.js";
15
15
  import { runMcpServer } from "./mcp/server.js";
16
- async function main(argv) {
16
+ import { routeSurfaceAliases } from "./surface-routing.js";
17
+ async function main(rawArgv) {
18
+ const argv = routeSurfaceAliases(rawArgv);
17
19
  const help = companionHelp(argv);
18
20
  if (help !== undefined) {
19
21
  process.stdout.write(`${help}\n`);
@@ -89,23 +89,24 @@ function commandArguments(rawInput) {
89
89
  const trimmed = rawInput.trim();
90
90
  return trimmed.length === 0 ? [] : trimmed.split(/\s+/);
91
91
  }
92
+ export const DSH_SETUP_HINT = "[--check|--uninstall|--models [--json]|--install-kimi [--json]]";
93
+ /** Setup arguments DSH forwards; `--uninstall --all` and combined modes stay unavailable here. */
94
+ export function dshSetupArguments(rawInput) {
95
+ const args = commandArguments(rawInput);
96
+ const valid = args.length === 0
97
+ || (args.length === 1 && ["--check", "--uninstall", "--models", "--install-kimi"].includes(args[0]))
98
+ || (args.length === 2 && ["--models", "--install-kimi"].includes(args[0]) && args[1] === "--json");
99
+ return valid ? args : undefined;
100
+ }
92
101
  function commandText(result) {
93
102
  return [result.stdout.trimEnd(), result.stderr.trimEnd()]
94
103
  .filter((text) => text.length > 0)
95
104
  .join("\n");
96
105
  }
97
106
  export function apply(ctx, config) {
98
- const resolved = resolveConfig(config);
99
107
  const spec = {
100
108
  companionPath: COMPANION_PATH,
101
- dataRoot: resolved.dataRoot,
102
- env: resolved.env,
103
- disposeGraceMs: resolved.disposeGraceMs,
104
- maxOutputBytes: resolved.maxOutputBytes,
105
- model: resolved.model,
106
- thinkingEffort: resolved.thinkingEffort,
107
- budget: resolved.budget,
108
- reviewBase: resolved.reviewBase,
109
+ ...resolveConfig(config),
109
110
  spawn: (spawnSpec) => ctx.subprocess.spawn(spawnSpec),
110
111
  };
111
112
  for (const operation of DSH_COMPANION_OPERATIONS) {
@@ -141,16 +142,13 @@ export function apply(ctx, config) {
141
142
  commandCtx.commands.register({
142
143
  definitionId: CommandDefinitionId("kimi-plugin-cc/dsh/setup"),
143
144
  name: "kimi-setup",
144
- description: "Install, check, or remove the DSH-owned Kimi PreToolUse hook; list configured models",
145
- input: { hint: "[--check|--uninstall|--models [--json]]" },
145
+ description: "Install, check, or remove the DSH-owned Kimi PreToolUse hook; list configured models; install a certified Kimi Code CLI on request",
146
+ input: { hint: DSH_SETUP_HINT },
146
147
  recordInput: false,
147
148
  handler: (invocation) => {
148
- const args = commandArguments(invocation.rawInput);
149
- const valid = args.length === 0
150
- || (args.length === 1 && ["--check", "--uninstall", "--models"].includes(args[0]))
151
- || (args.length === 2 && args[0] === "--models" && args[1] === "--json");
152
- if (!valid) {
153
- return { kind: "error", text: "Usage: /kimi-setup [--check|--uninstall|--models [--json]]" };
149
+ const args = dshSetupArguments(invocation.rawInput);
150
+ if (args === undefined) {
151
+ return { kind: "error", text: `Usage: /kimi-setup ${DSH_SETUP_HINT}` };
154
152
  }
155
153
  return execute(invocation, ["setup", ...args]);
156
154
  },
@@ -110,7 +110,7 @@ function truncateDiff(diffText) {
110
110
  }
111
111
  return `${diffText.slice(0, MAX_DIFF_CHARS)}\n\n[diff truncated by companion after ${MAX_DIFF_CHARS} characters]`;
112
112
  }
113
- function sha256(value) {
113
+ export function sha256(value) {
114
114
  return createHash("sha256").update(value).digest("hex");
115
115
  }
116
116
  // ---------------------------------------------------------------------
@@ -204,14 +204,6 @@ export async function removeWorktree(repoRoot, worktreePath) {
204
204
  });
205
205
  }
206
206
  }
207
- /**
208
- * Prune stale worktree admin entries (entries whose on-disk dir is gone). Cheap;
209
- * run at the start of every write-swarm. Does NOT remove on-disk worktrees whose
210
- * dirs still exist — the caller sweeps those by path. Never throws.
211
- */
212
- export async function pruneWorktrees(repoRoot) {
213
- await runGitAllowFailure(["worktree", "prune"], repoRoot);
214
- }
215
207
  /**
216
208
  * True if the working tree at `cwd` has uncommitted changes (tracked or
217
209
  * untracked). write-swarm bases its worktree on HEAD, so a dirty tree means the
@@ -25,9 +25,9 @@ export function companionHelp(argv) {
25
25
  case "swarm": return usage("task swarm", "[options] [--] <objective>", SWARM_SUPPORTED_FLAGS, "Parallel task; default budget 30m. Runtime foreground-only; --write produces a patch.");
26
26
  default: return `Usage: companion.sh task <kind> [arguments]. Task kinds: ${TASK_KINDS}. Use task <kind> --help for usage.`;
27
27
  }
28
- case "ask": return usage(command, "[options] [--] [prompt]", ASK_SUPPORTED_FLAGS, "Read-only question; default budget 30m. Backgrounding does not extend the budget.");
29
- case "review": return usage(command, "[options] [--] [focus]", REVIEW_SUPPORTED_FLAGS, "Read-only review; default budget 30m. Foreground-only (no --background/--wait).");
30
- case "setup": return usage(command, "[options]", SETUP_SUPPORTED_FLAGS, "Install, check, or remove this host's managed hook, or list configured models.");
28
+ case "ask": return usage(command, "[options] [--] [prompt]", ASK_SUPPORTED_FLAGS, "Read-only question; default budget 30m. Backgrounding does not extend the budget. A leading --write runs the write-capable task rescue instead.");
29
+ case "review": return usage(command, "[options] [--] [focus]", REVIEW_SUPPORTED_FLAGS, "Read-only review; default budget 30m. Foreground-only (no --background/--wait). A leading --challenge runs task challenge instead.");
30
+ case "setup": return usage(command, "[options]", SETUP_SUPPORTED_FLAGS, "Install, check, or remove this host's managed hook, list configured models, or install the highest certified Kimi Code CLI for the plugin's own use (--install-kimi).");
31
31
  case "status":
32
32
  case "result":
33
33
  case "cancel":
@@ -26,10 +26,13 @@
26
26
  // shell-quoted absolute tokens — the resolved Node binary and hook script — so
27
27
  // `/bin/sh -c` does not depend on its working directory or PATH.
28
28
  import { decideHookOutcome } from "./approval-policy.js";
29
+ import { HOOK_DECISION_DEADLINE_MS, HOOK_TEST_DELAY_ENV } from "./hook-timing.js";
30
+ import { NETWORK_ENV, READ_ROOTS_ENV } from "../read-scope.js";
29
31
  import { evaluateRescueHookRequest } from "../rescue-approval.js";
30
32
  import { SWARM_POLICY_ENV, SWARM_WAVE_SIZE_ENV } from "../swarm-policy.js";
31
33
  const STDIN_TIMEOUT_MS = 5_000;
32
34
  async function main() {
35
+ armDecisionDeadline();
33
36
  const stdinText = await readStdinWithTimeout(STDIN_TIMEOUT_MS);
34
37
  let input;
35
38
  try {
@@ -43,6 +46,7 @@ async function main() {
43
46
  failClosed(`stdin was not a JSON object: ${formatErr(err)}`);
44
47
  return;
45
48
  }
49
+ await testOnlyDelay(process.env[HOOK_TEST_DELAY_ENV]);
46
50
  const decision = await decideHookOutcome(input, {
47
51
  commandLabel: process.env.KIMI_PLUGIN_CC_CMD,
48
52
  operationKind: process.env.KIMI_PLUGIN_CC_OPERATION,
@@ -52,6 +56,9 @@ async function main() {
52
56
  // Trusted root for rescue/pursue/swarm-write. Set by the plugin spawn; the
53
57
  // model inside kimi cannot forge it and hook payload cwd is not trusted.
54
58
  trustedWorkspaceRoot: process.env.KIMI_PLUGIN_CC_WORKSPACE_ROOT,
59
+ // Per-call read scope, set or deleted by the plugin on every spawn.
60
+ readRoots: process.env[READ_ROOTS_ENV],
61
+ network: process.env[NETWORK_ENV],
55
62
  });
56
63
  if (decision.decision === "deny") {
57
64
  // stderr.trim() in runner.ts:118 becomes the model-visible reason.
@@ -61,6 +68,40 @@ async function main() {
61
68
  }
62
69
  process.exit(0);
63
70
  }
71
+ /**
72
+ * A timed-out hook is ALLOW upstream, so a labelled call that has not decided
73
+ * within HOOK_DECISION_DEADLINE_MS (below the installed timeout) denies. The
74
+ * timer is unref'd so it never keeps a decided process alive; a stall with
75
+ * nothing pending would then drain the loop and exit 0, so `beforeExit`
76
+ * denies too. Every decision path exits explicitly before either fires.
77
+ * Unlabelled calls are out-of-plugin use and keep their exit-0 behaviour.
78
+ */
79
+ function armDecisionDeadline() {
80
+ const label = process.env.KIMI_PLUGIN_CC_CMD;
81
+ if (label === undefined || label.length === 0)
82
+ return;
83
+ const reason = `kimi-plugin-cc safety hook: no decision within ${HOOK_DECISION_DEADLINE_MS / 1000}s; ` +
84
+ "the tool call is denied because a hook that times out would be read as allow.";
85
+ setTimeout(() => {
86
+ process.stderr.write(`${reason}\n`);
87
+ process.exit(2);
88
+ }, HOOK_DECISION_DEADLINE_MS).unref();
89
+ process.once("beforeExit", () => {
90
+ process.stderr.write(`${reason}\n`);
91
+ process.exit(2);
92
+ });
93
+ }
94
+ async function testOnlyDelay(value) {
95
+ if (value === undefined || value.length === 0)
96
+ return;
97
+ if (value === "hang") {
98
+ await new Promise(() => { });
99
+ return;
100
+ }
101
+ const ms = Number(value);
102
+ if (Number.isSafeInteger(ms) && ms > 0)
103
+ await new Promise((resolve) => setTimeout(resolve, ms));
104
+ }
64
105
  function failClosed(reason) {
65
106
  process.stderr.write(`kimi-plugin-cc safety hook misconfigured: ${reason}\n`);
66
107
  process.exit(2);