kimi-plugin-cc 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +3 -14
  3. package/README.md +428 -572
  4. package/assets/logo.svg +6 -0
  5. package/cordis.patch.yml +18 -0
  6. package/dist/background-spawn.js +4 -2
  7. package/dist/cli-client.js +105 -66
  8. package/dist/commands/ask.js +27 -12
  9. package/dist/commands/cancel.js +4 -13
  10. package/dist/commands/cli-helpers.js +1 -1
  11. package/dist/commands/pursue.js +3 -2
  12. package/dist/commands/registry.js +7 -26
  13. package/dist/commands/repair-sessions.js +7 -4
  14. package/dist/commands/replay.js +4 -3
  15. package/dist/commands/rescue.js +17 -5
  16. package/dist/commands/review.js +18 -5
  17. package/dist/commands/setup.js +283 -265
  18. package/dist/commands/swarm.js +20 -7
  19. package/dist/companion.js +142 -18
  20. package/dist/help.js +11 -7
  21. package/dist/hook-escape.js +7 -16
  22. package/dist/hooks/approval-hook.js +1762 -124
  23. package/dist/hooks/approval-policy.js +15 -10
  24. package/dist/hooks/config-safety.js +15 -24
  25. package/dist/hooks/hook-timing.js +1 -1
  26. package/dist/hooks/install-paths.js +224 -112
  27. package/dist/hooks/install.js +64 -169
  28. package/dist/hooks/managed-block.js +52 -101
  29. package/dist/job-store.js +117 -49
  30. package/dist/jobs.js +53 -1
  31. package/dist/kimi-engine.js +68 -92
  32. package/dist/kimi-errors.js +1 -1
  33. package/dist/kimi-journal.js +3 -2
  34. package/dist/kimi-releases.js +28 -49
  35. package/dist/kimi-timeouts.js +1 -15
  36. package/dist/kimi-version-probe.js +24 -72
  37. package/dist/logging.js +12 -7
  38. package/dist/mcp/binding.js +13 -4
  39. package/dist/mcp/job-control.js +386 -89
  40. package/dist/mcp/launcher.js +1 -1
  41. package/dist/mcp/operations.js +387 -193
  42. package/dist/mcp/protocol.js +116 -27
  43. package/dist/mcp/skills.js +130 -0
  44. package/dist/mcp/stdio.js +15 -2
  45. package/dist/native-v2-preflight.js +127 -35
  46. package/dist/parsing.js +45 -11
  47. package/dist/paths.js +20 -10
  48. package/dist/plugin-data.js +28 -83
  49. package/dist/read-scope.js +2 -2
  50. package/dist/render.js +13 -38
  51. package/dist/session-references.js +216 -0
  52. package/dist/session-title.js +1 -1
  53. package/dist/surface-routing.js +92 -5
  54. package/dist/swarm-activation.js +26 -137
  55. package/dist/version.js +1 -1
  56. package/docs/migration.md +46 -227
  57. package/docs/models.md +24 -66
  58. package/docs/safety.md +195 -400
  59. package/docs/session-visibility.md +24 -14
  60. package/docs/swarm-recovery.md +26 -20
  61. package/dsh/index.json +54 -0
  62. package/mcp_config.json +10 -0
  63. package/package.json +23 -82
  64. package/plugin.json +19 -0
  65. package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
  66. package/plugins/kimi-codex/.mcp.json +2 -3
  67. package/plugins/kimi-codex/dist/background-spawn.js +4 -2
  68. package/plugins/kimi-codex/dist/cli-client.js +105 -66
  69. package/plugins/kimi-codex/dist/commands/ask.js +27 -12
  70. package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
  71. package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
  72. package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
  73. package/plugins/kimi-codex/dist/commands/registry.js +7 -26
  74. package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
  75. package/plugins/kimi-codex/dist/commands/replay.js +4 -3
  76. package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
  77. package/plugins/kimi-codex/dist/commands/review.js +18 -5
  78. package/plugins/kimi-codex/dist/commands/setup.js +283 -265
  79. package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
  80. package/plugins/kimi-codex/dist/companion.js +142 -18
  81. package/plugins/kimi-codex/dist/help.js +11 -7
  82. package/plugins/kimi-codex/dist/hook-escape.js +7 -16
  83. package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
  84. package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
  85. package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
  86. package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
  87. package/plugins/kimi-codex/dist/hooks/install-paths.js +224 -112
  88. package/plugins/kimi-codex/dist/hooks/install.js +64 -169
  89. package/plugins/kimi-codex/dist/hooks/managed-block.js +52 -101
  90. package/plugins/kimi-codex/dist/job-store.js +117 -49
  91. package/plugins/kimi-codex/dist/jobs.js +53 -1
  92. package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
  93. package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
  94. package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
  95. package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
  96. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
  97. package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
  98. package/plugins/kimi-codex/dist/logging.js +12 -7
  99. package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
  100. package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
  101. package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
  102. package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
  103. package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
  104. package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
  105. package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
  106. package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
  107. package/plugins/kimi-codex/dist/parsing.js +45 -11
  108. package/plugins/kimi-codex/dist/paths.js +20 -10
  109. package/plugins/kimi-codex/dist/plugin-data.js +28 -83
  110. package/plugins/kimi-codex/dist/read-scope.js +2 -2
  111. package/plugins/kimi-codex/dist/render.js +13 -38
  112. package/plugins/kimi-codex/dist/session-references.js +216 -0
  113. package/plugins/kimi-codex/dist/session-title.js +1 -1
  114. package/plugins/kimi-codex/dist/surface-routing.js +92 -5
  115. package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
  116. package/plugins/kimi-codex/dist/version.js +1 -1
  117. package/plugins/kimi-codex/scripts/companion.sh +4 -15
  118. package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
  119. package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
  120. package/scripts/companion.sh +4 -15
  121. package/skills/kimi/SKILL.md +77 -0
  122. package/skills/kimi/agents/openai.yaml +6 -0
  123. package/CHANGELOG.md +0 -1402
  124. package/agents/kimi-pursue.md +0 -93
  125. package/agents/kimi-review.md +0 -86
  126. package/agents/kimi-swarm.md +0 -88
  127. package/agents/kimi-task.md +0 -93
  128. package/commands/README.md +0 -14
  129. package/commands/cancel.md +0 -17
  130. package/commands/pursue.md +0 -41
  131. package/commands/replay.md +0 -13
  132. package/commands/result.md +0 -13
  133. package/commands/review.md +0 -40
  134. package/commands/setup.md +0 -25
  135. package/commands/status.md +0 -13
  136. package/commands/swarm.md +0 -45
  137. package/commands/task.md +0 -40
  138. package/dist/commands/review-gate.js +0 -391
  139. package/dist/config.js +0 -22
  140. package/dist/dsh/companion.js +0 -177
  141. package/dist/dsh/index.js +0 -167
  142. package/dist/hooks/review-gate-stop.js +0 -19
  143. package/dist/schemas/review-gate-output.js +0 -41
  144. package/docs/registry-releases.md +0 -228
  145. package/docs/upstream-2.4.1-certification.md +0 -54
  146. package/docs/upstream-2.5.0-certification.md +0 -52
  147. package/docs/upstream-2.5.1-certification.md +0 -47
  148. package/docs/upstream-2.5.2-certification.md +0 -40
  149. package/docs/upstream-2.5.3-certification.md +0 -73
  150. package/docs/upstream-2.6.0-certification.md +0 -65
  151. package/docs/upstream-2.6.2-certification.md +0 -144
  152. package/docs/upstream-2.6.3-certification.md +0 -100
  153. package/docs/upstream-2.7.2-certification.md +0 -113
  154. package/docs/upstream-2.7.3-certification.md +0 -95
  155. package/docs/windows-validation.md +0 -39
  156. package/hooks/README.md +0 -9
  157. package/hooks/hooks.json +0 -16
  158. package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
  159. package/plugins/kimi-codex/dist/config.js +0 -22
  160. package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
  161. package/plugins/kimi-codex/dist/dsh/index.js +0 -167
  162. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
  163. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
  165. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
  166. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
  167. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
  168. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
  169. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
  170. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
  171. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
  172. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
  173. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
  174. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
  175. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
  176. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
  177. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
  178. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
  179. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
  180. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
  181. package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
  182. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
  183. package/plugins/kimi-dsh/LICENSE +0 -201
  184. package/plugins/kimi-dsh/README.md +0 -84
  185. package/plugins/kimi-dsh/cordis.patch.yml +0 -45
  186. package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
  187. package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
  188. package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
  189. package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
  190. package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
  191. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
  192. package/plugins/kimi-dsh/dist/commands/models.js +0 -139
  193. package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
  194. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
  195. package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
  196. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
  197. package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
  198. package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
  199. package/plugins/kimi-dsh/dist/commands/result.js +0 -72
  200. package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
  201. package/plugins/kimi-dsh/dist/commands/review.js +0 -217
  202. package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
  203. package/plugins/kimi-dsh/dist/commands/status.js +0 -27
  204. package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
  205. package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
  206. package/plugins/kimi-dsh/dist/companion.js +0 -99
  207. package/plugins/kimi-dsh/dist/config.js +0 -22
  208. package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
  209. package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
  210. package/plugins/kimi-dsh/dist/errors.js +0 -40
  211. package/plugins/kimi-dsh/dist/git.js +0 -216
  212. package/plugins/kimi-dsh/dist/help.js +0 -43
  213. package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
  214. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
  215. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
  216. package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
  217. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
  218. package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
  219. package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
  220. package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
  221. package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
  222. package/plugins/kimi-dsh/dist/job-id.js +0 -12
  223. package/plugins/kimi-dsh/dist/job-store.js +0 -631
  224. package/plugins/kimi-dsh/dist/jobs.js +0 -212
  225. package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
  226. package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
  227. package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
  228. package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
  229. package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
  230. package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
  231. package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
  232. package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
  233. package/plugins/kimi-dsh/dist/logging.js +0 -22
  234. package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
  235. package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
  236. package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
  237. package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
  238. package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
  239. package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
  240. package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
  241. package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
  242. package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
  243. package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
  244. package/plugins/kimi-dsh/dist/model-command.js +0 -34
  245. package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
  246. package/plugins/kimi-dsh/dist/package.json +0 -1
  247. package/plugins/kimi-dsh/dist/parsing.js +0 -554
  248. package/plugins/kimi-dsh/dist/paths.js +0 -35
  249. package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
  250. package/plugins/kimi-dsh/dist/process-tree.js +0 -597
  251. package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
  252. package/plugins/kimi-dsh/dist/read-scope.js +0 -435
  253. package/plugins/kimi-dsh/dist/render.js +0 -214
  254. package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
  255. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
  256. package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
  257. package/plugins/kimi-dsh/dist/session-title.js +0 -313
  258. package/plugins/kimi-dsh/dist/stream-json.js +0 -344
  259. package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
  260. package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
  261. package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
  262. package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
  263. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
  264. package/plugins/kimi-dsh/dist/types.js +0 -1
  265. package/plugins/kimi-dsh/dist/util.js +0 -28
  266. package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
  267. package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
  268. package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
  269. package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
  270. package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
  271. package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
  272. package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
  273. package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
  274. package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
  275. package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
  276. package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
  277. package/plugins/kimi-dsh/dist/version.js +0 -7
  278. package/plugins/kimi-dsh/package.json +0 -78
  279. package/plugins/kimi-dsh/scripts/companion.sh +0 -37
  280. package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
  281. package/scripts/review-gate-hook.sh +0 -32
@@ -1,641 +0,0 @@
1
- import { createHash, randomBytes } from "node:crypto";
2
- import { constants as fsConstants } from "node:fs";
3
- import { link, lstat, mkdir, open, rename, unlink } from "node:fs/promises";
4
- import path from "node:path";
5
- import { RuntimeError } from "../errors.js";
6
- import { selectKimiBinary } from "../kimi-command.js";
7
- import { kimiReleaseHas } from "../kimi-releases.js";
8
- import { probeKimiVersion } from "../kimi-version-probe.js";
9
- import { sleep, tomlErrorLocation } from "../util.js";
10
- import { extractValue } from "../vendor/smol-toml/extract.js";
11
- import { parse as parseToml } from "../vendor/smol-toml/parse.js";
12
- import { parseKey } from "../vendor/smol-toml/struct.js";
13
- import { skipVoid } from "../vendor/smol-toml/util.js";
14
- const LOCK_SUFFIX = ".kimi-plugin-cc.lock";
15
- const DEFAULT_LOCK_WAIT_MS = 10_000;
16
- const DEFAULT_LOCK_STALE_MS = 2_000;
17
- const DEFAULT_LOCK_RETRY_MS = 25;
18
- export const KIMI_CONFIG_LOCK_METADATA_MAX_BYTES = 4_096;
19
- const HOOK_FIELDS = new Set(["event", "matcher", "command", "timeout"]);
20
- // These events exist throughout the supported 0.x range. The remaining events
21
- // are additive and require a local version probe before they can be blessed.
22
- const BASE_HOOK_EVENTS = new Set([
23
- "PreToolUse",
24
- "PostToolUse",
25
- "PostToolUseFailure",
26
- "UserPromptSubmit",
27
- "Stop",
28
- "StopFailure",
29
- "SessionStart",
30
- "SessionEnd",
31
- "SubagentStart",
32
- "SubagentStop",
33
- "PreCompact",
34
- "PostCompact",
35
- "Notification",
36
- ]);
37
- const VERSION_SENSITIVE_HOOK_EVENTS = new Map([
38
- ["PermissionRequest", 8],
39
- ["PermissionResult", 8],
40
- ["Interrupt", 14],
41
- ]);
42
- export function kimiConfigLockPath(configPath) {
43
- return `${configPath}${LOCK_SUFFIX}`;
44
- }
45
- /**
46
- * Serialize setup read-modify-write operations with a private sibling lock.
47
- * A crashed owner is recoverable after `staleMs`; a live owner is never
48
- * stolen, even when old, and wait time is bounded.
49
- */
50
- export async function withKimiConfigLock(configPath, operation, options = {}) {
51
- const lockPath = kimiConfigLockPath(configPath);
52
- const waitMs = options.waitMs ?? DEFAULT_LOCK_WAIT_MS;
53
- const staleMs = options.staleMs ?? DEFAULT_LOCK_STALE_MS;
54
- const retryMs = options.retryMs ?? DEFAULT_LOCK_RETRY_MS;
55
- const owner = {
56
- pid: process.pid,
57
- token: randomBytes(16).toString("hex"),
58
- createdAt: new Date().toISOString(),
59
- };
60
- await mkdir(path.dirname(configPath), { recursive: true, mode: 0o700 });
61
- const deadline = Date.now() + waitMs;
62
- let lastOwner = null;
63
- let acquired = null;
64
- for (;;) {
65
- try {
66
- acquired = await createPrivateLockFile(lockPath, owner);
67
- break;
68
- }
69
- catch (error) {
70
- if (error.code !== "EEXIST") {
71
- if (error instanceof RuntimeError)
72
- throw error;
73
- throw new RuntimeError("SETUP_CONFIG_LOCK_FAILED", `Failed to acquire setup lock ${lockPath}: ${error.message}`, "setup.config-lock", error instanceof Error
74
- ? { cause: error, details: { configPath, lockPath } }
75
- : { details: { configPath, lockPath } });
76
- }
77
- }
78
- const snapshot = await readLockSnapshot(lockPath);
79
- lastOwner = snapshot?.owner ?? null;
80
- if (snapshot !== null && isStaleLock(snapshot, staleMs)) {
81
- await options.testHooks?.beforeStaleRecovery?.(lockPath, {
82
- identity: snapshot.identity,
83
- ownerToken: snapshot.owner?.token ?? null,
84
- });
85
- const recovered = await tryRecoverStaleLock(lockPath, snapshot, staleMs);
86
- if (recovered)
87
- continue;
88
- }
89
- if (Date.now() >= deadline) {
90
- const ownerDetail = lastOwner === null
91
- ? "owner metadata is unavailable"
92
- : `owner pid ${lastOwner.pid}, created ${lastOwner.createdAt}`;
93
- throw new RuntimeError("SETUP_CONFIG_LOCK_TIMEOUT", `Timed out after ${waitMs}ms waiting for setup lock ${lockPath} (${ownerDetail}). Another setup may still be running; retry after it finishes or remove the lock only if that process is gone.`, "setup.config-lock", { details: { configPath, lockPath, waitMs, owner: lastOwner } });
94
- }
95
- await sleep(Math.min(retryMs, Math.max(1, deadline - Date.now())));
96
- }
97
- try {
98
- await options.testHooks?.afterPublish?.(lockPath);
99
- await assertOwnedLock(lockPath, acquired, owner.token);
100
- return await operation();
101
- }
102
- finally {
103
- await releaseOwnedLock(lockPath, acquired, owner.token);
104
- }
105
- }
106
- /**
107
- * Publish complete owner metadata atomically. `open(lockPath, "wx")` is not
108
- * sufficient: it exposes a zero-byte inode while metadata is being written,
109
- * which a stale-lock observer can misclassify and remove. A private candidate
110
- * is written and synced first; hard-link creation is the atomic create-if-absent
111
- * operation that makes those complete bytes visible at the public lock path.
112
- */
113
- async function createPrivateLockFile(lockPath, owner) {
114
- const candidatePath = `${lockPath}.candidate.${owner.pid}.${owner.token}`;
115
- const handle = await open(candidatePath, fsConstants.O_WRONLY |
116
- fsConstants.O_CREAT |
117
- fsConstants.O_EXCL |
118
- (fsConstants.O_NOFOLLOW ?? 0), 0o600);
119
- let candidateIdentity = "";
120
- try {
121
- if (process.platform !== "win32")
122
- await handle.chmod(0o600);
123
- await handle.writeFile(`${JSON.stringify(owner)}\n`, "utf8");
124
- await handle.sync();
125
- const stats = await handle.stat({ bigint: true });
126
- candidateIdentity = lockIdentity(stats.dev, stats.ino);
127
- }
128
- finally {
129
- await handle.close().catch(() => undefined);
130
- }
131
- try {
132
- await link(candidatePath, lockPath);
133
- const published = await readLockSnapshot(lockPath);
134
- if (published === null ||
135
- published.identity !== candidateIdentity ||
136
- published.owner?.token !== owner.token) {
137
- throw lockOwnershipLost(lockPath, owner.token, published);
138
- }
139
- return published;
140
- }
141
- finally {
142
- await unlink(candidatePath).catch(() => undefined);
143
- }
144
- }
145
- async function readLockSnapshot(lockPath) {
146
- let before;
147
- try {
148
- before = await lstat(lockPath, { bigint: true });
149
- }
150
- catch (error) {
151
- if (error.code === "ENOENT")
152
- return null;
153
- throw error;
154
- }
155
- if (!before.isFile())
156
- throw unsafeLockPath(lockPath, describeFileType(before));
157
- let handle;
158
- try {
159
- handle = await open(lockPath, fsConstants.O_RDONLY |
160
- (fsConstants.O_NOFOLLOW ?? 0) |
161
- (fsConstants.O_NONBLOCK ?? 0));
162
- }
163
- catch (error) {
164
- if (error.code === "ENOENT")
165
- return null;
166
- if (error.code === "ELOOP") {
167
- throw unsafeLockPath(lockPath, "symbolic link");
168
- }
169
- throw error;
170
- }
171
- try {
172
- const stats = await handle.stat({ bigint: true });
173
- if (!stats.isFile())
174
- throw unsafeLockPath(lockPath, describeFileType(stats));
175
- // Always cap the actual read, even if size changes after fstat(). O_NONBLOCK
176
- // above prevents a raced FIFO/device replacement from hanging setup.
177
- const buffer = Buffer.alloc(KIMI_CONFIG_LOCK_METADATA_MAX_BYTES + 1);
178
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
179
- const metadataTruncated = stats.size > BigInt(KIMI_CONFIG_LOCK_METADATA_MAX_BYTES) ||
180
- bytesRead > KIMI_CONFIG_LOCK_METADATA_MAX_BYTES;
181
- const raw = metadataTruncated
182
- ? ""
183
- : buffer.subarray(0, bytesRead).toString("utf8");
184
- return {
185
- identity: lockIdentity(stats.dev, stats.ino),
186
- owner: parseLockOwner(raw),
187
- ageMs: Math.max(0, Date.now() - Number(stats.mtimeMs)),
188
- metadataTruncated,
189
- };
190
- }
191
- finally {
192
- await handle.close();
193
- }
194
- }
195
- function lockIdentity(device, inode) {
196
- return `${device.toString()}:${inode.toString()}`;
197
- }
198
- function describeFileType(stats) {
199
- if (stats.isSymbolicLink())
200
- return "symbolic link";
201
- if (stats.isDirectory())
202
- return "directory";
203
- if (stats.isFIFO())
204
- return "FIFO";
205
- if (stats.isCharacterDevice())
206
- return "character device";
207
- if (stats.isBlockDevice())
208
- return "block device";
209
- if (stats.isSocket())
210
- return "socket";
211
- return "non-regular file";
212
- }
213
- function unsafeLockPath(lockPath, type) {
214
- return new RuntimeError("SETUP_CONFIG_LOCK_UNSAFE", `Refusing setup lock ${lockPath}: the path is a ${type}, not a regular private lock file. Remove it manually after verifying its origin; setup will not follow or read it.`, "setup.config-lock", { details: { lockPath, type } });
215
- }
216
- function parseLockOwner(raw) {
217
- try {
218
- const value = JSON.parse(raw);
219
- if (!Number.isInteger(value.pid) ||
220
- (value.pid ?? 0) <= 0 ||
221
- typeof value.token !== "string" ||
222
- !/^[a-f0-9]{32}$/.test(value.token) ||
223
- typeof value.createdAt !== "string") {
224
- return null;
225
- }
226
- return { pid: value.pid, token: value.token, createdAt: value.createdAt };
227
- }
228
- catch {
229
- return null;
230
- }
231
- }
232
- function isStaleLock(snapshot, staleMs) {
233
- if (snapshot.ageMs < staleMs)
234
- return false;
235
- return snapshot.owner === null || !isProcessAlive(snapshot.owner.pid);
236
- }
237
- function isProcessAlive(pid) {
238
- try {
239
- process.kill(pid, 0);
240
- return true;
241
- }
242
- catch (error) {
243
- return error.code !== "ESRCH";
244
- }
245
- }
246
- async function tryRecoverStaleLock(lockPath, observed, staleMs) {
247
- const identityHash = createHash("sha256").update(observed.identity).digest("hex").slice(0, 16);
248
- const recoveryPath = `${lockPath}.recover.${identityHash}`;
249
- const recoveryOwner = {
250
- pid: process.pid,
251
- token: randomBytes(16).toString("hex"),
252
- createdAt: new Date().toISOString(),
253
- };
254
- let recoverySnapshot;
255
- try {
256
- recoverySnapshot = await createPrivateLockFile(recoveryPath, recoveryOwner);
257
- }
258
- catch (error) {
259
- if (error.code !== "EEXIST")
260
- throw error;
261
- const existingRecovery = await readLockSnapshot(recoveryPath);
262
- if (existingRecovery !== null && isStaleLock(existingRecovery, staleMs)) {
263
- // One bounded, non-recursive claim. A crashed recovery lease is renamed
264
- // to a unique quarantine path, verified there, and removed only when its
265
- // inode and owner token still match the snapshot we observed.
266
- await removeStaleRecoveryLease(recoveryPath, existingRecovery);
267
- }
268
- return false;
269
- }
270
- let recovered = false;
271
- try {
272
- await assertOwnedLock(recoveryPath, recoverySnapshot, recoveryOwner.token);
273
- const current = await readLockSnapshot(lockPath);
274
- if (current !== null && sameObservedLock(current, observed) && isStaleLock(current, staleMs)) {
275
- // The per-identity recovery lock above ensures only one observer of this
276
- // inode can claim it. Rename is the atomic removal from the public path;
277
- // verification happens on the claimed inode before its unique name is
278
- // unlinked, eliminating the old check(path) -> unlink(path) ABA window.
279
- const quarantinePath = `${lockPath}.stale.${identityHash}.${recoveryOwner.token}`;
280
- try {
281
- await rename(lockPath, quarantinePath);
282
- }
283
- catch (error) {
284
- if (error.code === "ENOENT")
285
- return false;
286
- throw error;
287
- }
288
- const claimed = await readLockSnapshot(quarantinePath);
289
- if (!sameObservedLock(claimed, observed)) {
290
- throw new RuntimeError("SETUP_CONFIG_LOCK_RECOVERY_RACE", `Setup lock ${lockPath} changed identity while stale recovery claimed it; the claimed file was preserved at ${quarantinePath} instead of being deleted.`, "setup.config-lock", { details: { lockPath, quarantinePath, observed: observed.identity, claimed: claimed?.identity } });
291
- }
292
- await unlink(quarantinePath);
293
- recovered = true;
294
- }
295
- }
296
- finally {
297
- await releaseOwnedLock(recoveryPath, recoverySnapshot, recoveryOwner.token);
298
- }
299
- return recovered;
300
- }
301
- async function removeStaleRecoveryLease(recoveryPath, observed) {
302
- const quarantinePath = `${recoveryPath}.stale.${process.pid}.${randomBytes(16).toString("hex")}`;
303
- try {
304
- await rename(recoveryPath, quarantinePath);
305
- }
306
- catch (error) {
307
- if (error.code === "ENOENT")
308
- return;
309
- throw error;
310
- }
311
- const claimed = await readLockSnapshot(quarantinePath);
312
- if (!sameObservedLock(claimed, observed)) {
313
- throw new RuntimeError("SETUP_CONFIG_LOCK_RECOVERY_RACE", `Recovery lease ${recoveryPath} changed identity while being claimed; the claimed file was preserved at ${quarantinePath} instead of being deleted.`, "setup.config-lock", {
314
- details: {
315
- recoveryPath,
316
- quarantinePath,
317
- observed: observed.identity,
318
- claimed: claimed?.identity,
319
- },
320
- });
321
- }
322
- await unlink(quarantinePath);
323
- }
324
- function sameObservedLock(current, observed) {
325
- return current !== null &&
326
- current.identity === observed.identity &&
327
- current.owner?.token === observed.owner?.token;
328
- }
329
- async function assertOwnedLock(lockPath, acquired, token) {
330
- const current = await readLockSnapshot(lockPath);
331
- if (current === null ||
332
- current.identity !== acquired.identity ||
333
- current.owner?.token !== token) {
334
- throw lockOwnershipLost(lockPath, token, current);
335
- }
336
- }
337
- function lockOwnershipLost(lockPath, expectedToken, current) {
338
- return new RuntimeError("SETUP_CONFIG_LOCK_OWNERSHIP_LOST", `Setup lock ${lockPath} changed before the protected operation began; refusing to enter the config transaction.`, "setup.config-lock", {
339
- details: {
340
- lockPath,
341
- expectedToken,
342
- currentIdentity: current?.identity,
343
- currentToken: current?.owner?.token,
344
- },
345
- });
346
- }
347
- async function releaseOwnedLock(lockPath, acquired, token) {
348
- const current = await readLockSnapshot(lockPath);
349
- if (current === null ||
350
- current.identity !== acquired.identity ||
351
- current.owner?.token !== token)
352
- return;
353
- const releasePath = `${lockPath}.release.${token}`;
354
- try {
355
- await rename(lockPath, releasePath);
356
- }
357
- catch (error) {
358
- if (error.code === "ENOENT")
359
- return;
360
- throw error;
361
- }
362
- const claimed = await readLockSnapshot(releasePath);
363
- if (claimed === null ||
364
- claimed.identity !== acquired.identity ||
365
- claimed.owner?.token !== token) {
366
- throw new RuntimeError("SETUP_CONFIG_LOCK_RELEASE_RACE", `Setup lock ${lockPath} changed identity during release; the claimed file was preserved at ${releasePath}.`, "setup.config-lock", { details: { lockPath, releasePath, expectedIdentity: acquired.identity, claimedIdentity: claimed?.identity } });
367
- }
368
- await unlink(releasePath);
369
- }
370
- /**
371
- * Convert a validated top-level inline `hooks = [...]` assignment to canonical
372
- * `[[hooks]]` tables so setup can append its own array-table entry without
373
- * redefining the TOML key. Bytes outside that one assignment are untouched;
374
- * formatting and comments inside the assignment are intentionally normalized.
375
- */
376
- export function normalizeTopLevelInlineHooks(contents, lineEnding) {
377
- let config;
378
- try {
379
- config = parseToml(contents);
380
- }
381
- catch {
382
- return { contents, found: false, converted: false, entryCount: 0 };
383
- }
384
- const assignment = findTopLevelHooksAssignment(contents);
385
- if (assignment === null) {
386
- return { contents, found: false, converted: false, entryCount: 0 };
387
- }
388
- const hooks = config["hooks"];
389
- if (!Array.isArray(hooks)) {
390
- return { contents, found: true, converted: false, entryCount: 0 };
391
- }
392
- const rendered = [];
393
- for (const entry of hooks) {
394
- if (!isPlainRecord(entry)) {
395
- return { contents, found: true, converted: false, entryCount: hooks.length };
396
- }
397
- const table = renderCanonicalHookTable(entry, lineEnding);
398
- if (table === null) {
399
- return { contents, found: true, converted: false, entryCount: hooks.length };
400
- }
401
- rendered.push(table);
402
- }
403
- const replacementBody = rendered.join(`${lineEnding}${lineEnding}`);
404
- const replacement = replacementBody.length > 0 && assignment.hadLineEnding
405
- ? `${replacementBody}${lineEnding}`
406
- : replacementBody;
407
- return {
408
- contents: `${contents.slice(0, assignment.start)}${replacement}${contents.slice(assignment.end)}`,
409
- found: true,
410
- converted: true,
411
- entryCount: hooks.length,
412
- };
413
- }
414
- // Same defaults as smol-toml 1.9.1 parse(); this walker only locates assignments.
415
- // tests/runtime/toml-walker-context.test.ts asserts these against the vendored parse().
416
- export function assignmentParseContext(s) {
417
- return { s, p: s.charCodeAt(0) === 0xfeff ? 1 : 0, d: 1_000, bi: false, ld: true, uk: 0 };
418
- }
419
- function findTopLevelHooksAssignment(contents) {
420
- const ctx = assignmentParseContext(contents);
421
- skipVoid(ctx);
422
- while (ctx.p < contents.length) {
423
- // A root-level direct assignment cannot resume after entering a table.
424
- if (contents[ctx.p] === "[")
425
- return null;
426
- const declarationStart = ctx.p;
427
- const key = parseKey(ctx);
428
- skipVoid(ctx, true, true);
429
- extractValue(ctx, undefined);
430
- const valueEnd = ctx.p;
431
- if (key.length === 1 && key[0] === "hooks") {
432
- const lineStart = contents.lastIndexOf("\n", declarationStart - 1) + 1;
433
- const start = /^[\t ]*$/.test(contents.slice(lineStart, declarationStart))
434
- ? lineStart
435
- : declarationStart;
436
- let end = valueEnd;
437
- while (end < contents.length && contents[end] !== "\n" && contents[end] !== "\r")
438
- end += 1;
439
- let hadLineEnding = false;
440
- if (contents[end] === "\r" && contents[end + 1] === "\n") {
441
- end += 2;
442
- hadLineEnding = true;
443
- }
444
- else if (contents[end] === "\r" || contents[end] === "\n") {
445
- end += 1;
446
- hadLineEnding = true;
447
- }
448
- return { start, end, hadLineEnding };
449
- }
450
- skipVoid(ctx);
451
- }
452
- return null;
453
- }
454
- function renderCanonicalHookTable(entry, lineEnding) {
455
- const lines = ["[[hooks]]"];
456
- for (const field of ["event", "matcher", "command", "timeout"]) {
457
- if (!Object.hasOwn(entry, field))
458
- continue;
459
- const value = entry[field];
460
- if (field === "timeout") {
461
- if (typeof value !== "number" || !Number.isInteger(value))
462
- return null;
463
- lines.push(`${field} = ${value}`);
464
- }
465
- else {
466
- if (typeof value !== "string")
467
- return null;
468
- lines.push(`${field} = ${JSON.stringify(value)}`);
469
- }
470
- }
471
- if (Object.keys(entry).some((field) => !HOOK_FIELDS.has(field)))
472
- return null;
473
- return lines.join(lineEnding);
474
- }
475
- /**
476
- * Validate the complete configured hook array against kimi-code's strict
477
- * HookDef schema. Upstream salvages a bad `hooks[n]` issue by dropping the
478
- * entire `hooks` section, so one foreign invalid entry disables our otherwise
479
- * canonical PreToolUse block too.
480
- */
481
- export function validateKimiHookSet(contents, version) {
482
- const inspection = inspectKimiHookSet(contents);
483
- if (!inspection.validation.valid)
484
- return inspection.validation;
485
- return validateVersionSensitiveEvents(inspection.versionSensitiveEvents, version);
486
- }
487
- /**
488
- * Probe `kimi --version` only when the config uses an additive hook event.
489
- * A job's execution plan passes its own exact probe as `knownVersion`, so the
490
- * hook set is judged against the release the job runs and nothing is spawned.
491
- */
492
- export async function validateKimiHookSetForEnvironment(contents, env, knownVersion) {
493
- const inspection = inspectKimiHookSet(contents);
494
- if (!inspection.validation.valid || inspection.versionSensitiveEvents.length === 0) {
495
- return inspection.validation;
496
- }
497
- const probe = knownVersion ?? await probeKimiVersion({
498
- kimiBin: selectKimiBinary(env).command,
499
- env,
500
- });
501
- const first = inspection.versionSensitiveEvents[0];
502
- if (probe.kind === "failed") {
503
- return invalidHookSet(`cannot verify version-sensitive event ${JSON.stringify(first.event)} because kimi-code version detection failed (${probe.reason})`, first.entry, first.line);
504
- }
505
- return validateVersionSensitiveEvents(inspection.versionSensitiveEvents, probe);
506
- }
507
- function inspectKimiHookSet(contents) {
508
- let config;
509
- try {
510
- config = parseToml(contents);
511
- }
512
- catch (error) {
513
- const line = tomlErrorLine(error);
514
- return {
515
- validation: invalidHookSet(`TOML parse failed: ${tomlErrorLocation(error)}`, 0, line, "parse"),
516
- versionSensitiveEvents: [],
517
- };
518
- }
519
- const versionSensitiveEvents = [];
520
- const hooks = config["hooks"];
521
- if (hooks === undefined)
522
- return { validation: { valid: true }, versionSensitiveEvents };
523
- if (!Array.isArray(hooks)) {
524
- return {
525
- validation: invalidHookSet("top-level `hooks` must be an array of hook entries", 0, 1),
526
- versionSensitiveEvents,
527
- };
528
- }
529
- const entryLines = findHookEntryLines(contents);
530
- for (let offset = 0; offset < hooks.length; offset += 1) {
531
- const entry = hooks[offset];
532
- const index = offset + 1;
533
- const line = entryLines[offset] ?? 1;
534
- if (!isPlainRecord(entry)) {
535
- return {
536
- validation: invalidHookSet("hook entry must be a TOML table", index, line),
537
- versionSensitiveEvents,
538
- };
539
- }
540
- const result = validateHookEntry(entry, index, line, versionSensitiveEvents);
541
- if (!result.valid)
542
- return { validation: result, versionSensitiveEvents };
543
- }
544
- return { validation: { valid: true }, versionSensitiveEvents };
545
- }
546
- function validateHookEntry(entry, index, line, versionSensitiveEvents) {
547
- for (const field of Object.keys(entry)) {
548
- if (!HOOK_FIELDS.has(field)) {
549
- return invalidHookSet(`unknown field ${JSON.stringify(field)} (allowed: event, matcher, command, timeout)`, index, line);
550
- }
551
- }
552
- const event = entry["event"];
553
- if (event === undefined)
554
- return invalidHookSet("missing required field `event`", index, line);
555
- if (typeof event !== "string")
556
- return invalidHookSet("`event` must be a string", index, line);
557
- const minimumMinor = VERSION_SENSITIVE_HOOK_EVENTS.get(event);
558
- if (!BASE_HOOK_EVENTS.has(event) && minimumMinor === undefined) {
559
- return invalidHookSet(`unsupported hook event ${JSON.stringify(event)}`, index, line);
560
- }
561
- if (minimumMinor !== undefined) {
562
- versionSensitiveEvents.push({
563
- event,
564
- minimumMinor,
565
- entry: index,
566
- line,
567
- });
568
- }
569
- const command = entry["command"];
570
- if (command === undefined)
571
- return invalidHookSet("missing required field `command`", index, line);
572
- if (typeof command !== "string" || command.length === 0) {
573
- return invalidHookSet("`command` must be a non-empty string", index, line);
574
- }
575
- const matcher = entry["matcher"];
576
- if (matcher !== undefined && typeof matcher !== "string") {
577
- return invalidHookSet("`matcher` must be a string when present", index, line);
578
- }
579
- const timeout = entry["timeout"];
580
- if (timeout !== undefined &&
581
- (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 1 || timeout > 600)) {
582
- return invalidHookSet("`timeout` must be an integer from 1 through 600", index, line);
583
- }
584
- return { valid: true };
585
- }
586
- function validateVersionSensitiveEvents(events, version) {
587
- if (events.length === 0)
588
- return { valid: true };
589
- const first = events[0];
590
- if (version === undefined) {
591
- return invalidHookSet(`version-sensitive event ${JSON.stringify(first.event)} requires a verified kimi-code version`, first.entry, first.line);
592
- }
593
- // The additive events and HookDefSchema are unchanged at every release whose
594
- // row in kimi-releases.ts carries "hook-schema" (each row names the reviewed
595
- // commit). Schema acceptance does not certify operations.
596
- // Require the full version string AND matching components; no inferred 2.x compatibility.
597
- if (version.major === 2 &&
598
- version.version === `${version.major}.${version.minor}.${version.patch}` &&
599
- kimiReleaseHas(version.version, "hook-schema")) {
600
- return { valid: true };
601
- }
602
- if (version.major !== 0) {
603
- return invalidHookSet(`version-sensitive event ${JSON.stringify(first.event)} has no verified schema contract for kimi-code ${version.major}.${version.minor}`, first.entry, first.line);
604
- }
605
- for (const event of events) {
606
- if (version.minor < event.minimumMinor) {
607
- return invalidHookSet(`event ${JSON.stringify(event.event)} requires kimi-code >= 0.${event.minimumMinor}, but the installed version is 0.${version.minor}`, event.entry, event.line);
608
- }
609
- }
610
- return { valid: true };
611
- }
612
- function invalidHookSet(reason, entry, line, failureKind = "schema") {
613
- const location = entry > 0 ? `hooks[${entry - 1}] at line ${line}` : `hooks configuration at line ${line}`;
614
- const consequence = failureKind === "parse"
615
- ? "kimi-code cannot parse this config, so no configured PreToolUse hook will load."
616
- : "kimi-code drops the entire hooks array when any entry fails its strict schema, so no configured PreToolUse hook will run.";
617
- return {
618
- valid: false,
619
- reason: `${location} is invalid: ${reason}. ${consequence}`,
620
- entry,
621
- line,
622
- };
623
- }
624
- function tomlErrorLine(error) {
625
- if (typeof error !== "object" || error === null)
626
- return 1;
627
- const line = error.line;
628
- return typeof line === "number" && Number.isInteger(line) && line > 0 ? line : 1;
629
- }
630
- function findHookEntryLines(contents) {
631
- const lines = [];
632
- const header = /^\s*\[\[\s*(?:hooks|"hooks"|'hooks')\s*\]\]\s*(?:#.*)?$/;
633
- for (const [offset, line] of contents.split(/\r?\n/).entries()) {
634
- if (header.test(line))
635
- lines.push(offset + 1);
636
- }
637
- return lines;
638
- }
639
- function isPlainRecord(value) {
640
- return typeof value === "object" && value !== null && !Array.isArray(value);
641
- }
@@ -1,48 +0,0 @@
1
- // Timing shared by the installed managed block and the hook entry script.
2
- //
3
- // kimi-code reads a hook that times out as ALLOW, so the hook must decide (or
4
- // deny) before kimi-code's timeout expires. The installed timeout, the shortest
5
- // timeout an entry may have and still count as enforcing, and the decision
6
- // deadline all derive from HOOK_TIMEOUT_S so they cannot drift.
7
- /** `timeout` (seconds) written into every managed PreToolUse block. */
8
- export const HOOK_TIMEOUT_S = 15;
9
- /**
10
- * Fail-closed deadline for a labelled call, counted from hook start and
11
- * covering stdin read plus policy evaluation. The margin absorbs Node startup
12
- * and module load, which kimi-code's timeout counts but this timer does not.
13
- */
14
- export const HOOK_DECISION_DEADLINE_MS = HOOK_TIMEOUT_S * 1000 - 5_000;
15
- /**
16
- * kimi-code's timeout (seconds) for a [[hooks]] entry with no `timeout` key:
17
- * `DEFAULT_HOOK_TIMEOUT_SECONDS` in agent-core-v2 `externalHooks/internal/
18
- * matchHooks.ts`, 30 in every certified source through 2.7.3. Each compat
19
- * audit re-verifies it.
20
- */
21
- export const UPSTREAM_DEFAULT_HOOK_TIMEOUT_S = 30;
22
- /**
23
- * The timeout kimi-code applies to an entry's raw `timeout` value: the
24
- * upstream default when absent, the integer itself within upstream's 1-600
25
- * schema, otherwise `null` (not provably enforcing).
26
- */
27
- export function effectiveHookTimeoutS(value) {
28
- if (value === undefined)
29
- return UPSTREAM_DEFAULT_HOOK_TIMEOUT_S;
30
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 600)
31
- return null;
32
- return value;
33
- }
34
- /**
35
- * True when kimi-code waits at least `HOOK_TIMEOUT_S` for the hook, so the
36
- * fail-closed deadline below fires before upstream's timeout-as-allow.
37
- */
38
- export function hookTimeoutEnforces(value) {
39
- const effective = effectiveHookTimeoutS(value);
40
- return effective !== null && effective >= HOOK_TIMEOUT_S;
41
- }
42
- /**
43
- * Test-only delay before the policy decision (milliseconds, or `hang` for a
44
- * promise that never settles). It can only push a decision into the
45
- * fail-closed deadline, and buildKimiCliEnvironment deletes it on every spawn,
46
- * so it never reaches a job's hook.
47
- */
48
- export const HOOK_TEST_DELAY_ENV = "KIMI_PLUGIN_CC_HOOK_TEST_DELAY_MS";