kimi-plugin-cc 2.7.3 → 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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +3 -5
  3. package/CHANGELOG.md +69 -0
  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 +3 -2
  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 -43
  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 -75
  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 +72 -75
  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 +24 -3
  74. package/docs/models.md +2 -2
  75. package/docs/registry-releases.md +1 -1
  76. package/docs/safety.md +120 -70
  77. package/docs/session-visibility.md +5 -3
  78. package/docs/swarm-recovery.md +1 -1
  79. package/docs/upstream-2.7.3-certification.md +14 -2
  80. package/package.json +1 -1
  81. package/plugins/kimi-codex/.codex-plugin/plugin.json +3 -3
  82. package/plugins/kimi-codex/.mcp.json +1 -0
  83. package/plugins/kimi-codex/dist/background-spawn.js +10 -17
  84. package/plugins/kimi-codex/dist/cli-client.js +65 -46
  85. package/plugins/kimi-codex/dist/commands/ask.js +22 -89
  86. package/plugins/kimi-codex/dist/commands/cancel.js +7 -46
  87. package/plugins/kimi-codex/dist/commands/cli-helpers.js +102 -1
  88. package/plugins/kimi-codex/dist/commands/models.js +2 -3
  89. package/plugins/kimi-codex/dist/commands/pursue.js +5 -19
  90. package/plugins/kimi-codex/dist/commands/repair-sessions.js +118 -12
  91. package/plugins/kimi-codex/dist/commands/rescue.js +12 -82
  92. package/plugins/kimi-codex/dist/commands/result.js +7 -1
  93. package/plugins/kimi-codex/dist/commands/review-gate.js +1 -0
  94. package/plugins/kimi-codex/dist/commands/review.js +12 -15
  95. package/plugins/kimi-codex/dist/commands/setup.js +606 -270
  96. package/plugins/kimi-codex/dist/commands/status.js +2 -2
  97. package/plugins/kimi-codex/dist/commands/swarm.js +93 -119
  98. package/plugins/kimi-codex/dist/commands/worker.js +1 -2
  99. package/plugins/kimi-codex/dist/companion.js +3 -1
  100. package/plugins/kimi-codex/dist/dsh/index.js +15 -17
  101. package/plugins/kimi-codex/dist/git.js +1 -9
  102. package/plugins/kimi-codex/dist/help.js +3 -3
  103. package/plugins/kimi-codex/dist/hooks/approval-hook.js +41 -0
  104. package/plugins/kimi-codex/dist/hooks/approval-policy.js +72 -10
  105. package/plugins/kimi-codex/dist/hooks/config-safety.js +19 -43
  106. package/plugins/kimi-codex/dist/hooks/hook-timing.js +48 -0
  107. package/plugins/kimi-codex/dist/hooks/install.js +206 -11
  108. package/plugins/kimi-codex/dist/hooks/managed-block.js +78 -33
  109. package/plugins/kimi-codex/dist/job-store.js +100 -128
  110. package/plugins/kimi-codex/dist/jobs.js +14 -19
  111. package/plugins/kimi-codex/dist/kimi-command.js +74 -1
  112. package/plugins/kimi-codex/dist/kimi-engine.js +170 -75
  113. package/plugins/kimi-codex/dist/kimi-errors.js +14 -69
  114. package/plugins/kimi-codex/dist/kimi-home.js +6 -0
  115. package/plugins/kimi-codex/dist/kimi-journal.js +41 -0
  116. package/plugins/kimi-codex/dist/kimi-releases.js +144 -0
  117. package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -1
  118. package/plugins/kimi-codex/dist/kimi-version-probe.js +12 -48
  119. package/plugins/kimi-codex/dist/mcp/job-control.js +4 -6
  120. package/plugins/kimi-codex/dist/mcp/launcher.js +12 -6
  121. package/plugins/kimi-codex/dist/mcp/operations.js +50 -18
  122. package/plugins/kimi-codex/dist/mcp/protocol.js +16 -14
  123. package/plugins/kimi-codex/dist/mcp/stdio.js +3 -2
  124. package/plugins/kimi-codex/dist/model-command.js +5 -3
  125. package/plugins/kimi-codex/dist/native-v2-preflight.js +139 -68
  126. package/plugins/kimi-codex/dist/parsing.js +171 -237
  127. package/plugins/kimi-codex/dist/paths.js +8 -0
  128. package/plugins/kimi-codex/dist/process-tree.js +35 -24
  129. package/plugins/kimi-codex/dist/read-scope.js +435 -0
  130. package/plugins/kimi-codex/dist/render.js +46 -9
  131. package/plugins/kimi-codex/dist/rescue-approval.js +461 -84
  132. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +3 -5
  133. package/plugins/kimi-codex/dist/session-title.js +25 -5
  134. package/plugins/kimi-codex/dist/stream-json.js +1 -3
  135. package/plugins/kimi-codex/dist/surface-routing.js +21 -0
  136. package/plugins/kimi-codex/dist/swarm-activation.js +72 -75
  137. package/plugins/kimi-codex/dist/swarm-policy.js +2 -1
  138. package/plugins/kimi-codex/dist/swarm-recovery.js +2 -1
  139. package/plugins/kimi-codex/dist/util.js +28 -0
  140. package/plugins/kimi-codex/dist/version.js +1 -1
  141. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +1 -1
  142. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +8 -7
  143. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +1 -1
  144. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +2 -1
  145. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +8 -6
  146. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +1 -1
  147. package/plugins/kimi-codex/skills/{kimi-ask → kimi-task}/SKILL.md +11 -9
  148. package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +6 -0
  149. package/plugins/kimi-dsh/README.md +3 -2
  150. package/plugins/kimi-dsh/dist/background-spawn.js +10 -17
  151. package/plugins/kimi-dsh/dist/cli-client.js +65 -46
  152. package/plugins/kimi-dsh/dist/commands/ask.js +22 -89
  153. package/plugins/kimi-dsh/dist/commands/cancel.js +7 -46
  154. package/plugins/kimi-dsh/dist/commands/cli-helpers.js +102 -1
  155. package/plugins/kimi-dsh/dist/commands/models.js +2 -3
  156. package/plugins/kimi-dsh/dist/commands/pursue.js +5 -19
  157. package/plugins/kimi-dsh/dist/commands/repair-sessions.js +118 -12
  158. package/plugins/kimi-dsh/dist/commands/rescue.js +12 -82
  159. package/plugins/kimi-dsh/dist/commands/result.js +7 -1
  160. package/plugins/kimi-dsh/dist/commands/review-gate.js +1 -0
  161. package/plugins/kimi-dsh/dist/commands/review.js +12 -15
  162. package/plugins/kimi-dsh/dist/commands/setup.js +606 -270
  163. package/plugins/kimi-dsh/dist/commands/status.js +2 -2
  164. package/plugins/kimi-dsh/dist/commands/swarm.js +93 -119
  165. package/plugins/kimi-dsh/dist/commands/worker.js +1 -2
  166. package/plugins/kimi-dsh/dist/companion.js +3 -1
  167. package/plugins/kimi-dsh/dist/dsh/index.js +15 -17
  168. package/plugins/kimi-dsh/dist/git.js +1 -9
  169. package/plugins/kimi-dsh/dist/help.js +3 -3
  170. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +41 -0
  171. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +72 -10
  172. package/plugins/kimi-dsh/dist/hooks/config-safety.js +19 -43
  173. package/plugins/kimi-dsh/dist/hooks/hook-timing.js +48 -0
  174. package/plugins/kimi-dsh/dist/hooks/install.js +206 -11
  175. package/plugins/kimi-dsh/dist/hooks/managed-block.js +78 -33
  176. package/plugins/kimi-dsh/dist/job-store.js +100 -128
  177. package/plugins/kimi-dsh/dist/jobs.js +14 -19
  178. package/plugins/kimi-dsh/dist/kimi-command.js +74 -1
  179. package/plugins/kimi-dsh/dist/kimi-engine.js +170 -75
  180. package/plugins/kimi-dsh/dist/kimi-errors.js +14 -69
  181. package/plugins/kimi-dsh/dist/kimi-home.js +6 -0
  182. package/plugins/kimi-dsh/dist/kimi-journal.js +41 -0
  183. package/plugins/kimi-dsh/dist/kimi-releases.js +144 -0
  184. package/plugins/kimi-dsh/dist/kimi-timeouts.js +1 -1
  185. package/plugins/kimi-dsh/dist/kimi-version-probe.js +12 -48
  186. package/plugins/kimi-dsh/dist/mcp/job-control.js +4 -6
  187. package/plugins/kimi-dsh/dist/mcp/launcher.js +12 -6
  188. package/plugins/kimi-dsh/dist/mcp/operations.js +50 -18
  189. package/plugins/kimi-dsh/dist/mcp/protocol.js +16 -14
  190. package/plugins/kimi-dsh/dist/mcp/stdio.js +3 -2
  191. package/plugins/kimi-dsh/dist/model-command.js +5 -3
  192. package/plugins/kimi-dsh/dist/native-v2-preflight.js +139 -68
  193. package/plugins/kimi-dsh/dist/parsing.js +171 -237
  194. package/plugins/kimi-dsh/dist/paths.js +8 -0
  195. package/plugins/kimi-dsh/dist/process-tree.js +35 -24
  196. package/plugins/kimi-dsh/dist/read-scope.js +435 -0
  197. package/plugins/kimi-dsh/dist/render.js +46 -9
  198. package/plugins/kimi-dsh/dist/rescue-approval.js +461 -84
  199. package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +3 -5
  200. package/plugins/kimi-dsh/dist/session-title.js +25 -5
  201. package/plugins/kimi-dsh/dist/stream-json.js +1 -3
  202. package/plugins/kimi-dsh/dist/surface-routing.js +21 -0
  203. package/plugins/kimi-dsh/dist/swarm-activation.js +72 -75
  204. package/plugins/kimi-dsh/dist/swarm-policy.js +2 -1
  205. package/plugins/kimi-dsh/dist/swarm-recovery.js +2 -1
  206. package/plugins/kimi-dsh/dist/util.js +28 -0
  207. package/plugins/kimi-dsh/dist/version.js +1 -1
  208. package/plugins/kimi-dsh/package.json +1 -1
  209. package/agents/kimi-challenge.md +0 -86
  210. package/agents/kimi-rescue.md +0 -92
  211. package/agents/kimi-swarm-write.md +0 -96
  212. package/commands/ask.md +0 -38
  213. package/commands/challenge.md +0 -35
  214. package/dist/commands/not-implemented.js +0 -4
  215. package/plugins/kimi-codex/dist/commands/not-implemented.js +0 -4
  216. package/plugins/kimi-codex/skills/kimi-ask/agents/openai.yaml +0 -6
  217. package/plugins/kimi-codex/skills/kimi-challenge/SKILL.md +0 -34
  218. package/plugins/kimi-codex/skills/kimi-challenge/agents/openai.yaml +0 -6
  219. package/plugins/kimi-codex/skills/kimi-rescue/SKILL.md +0 -34
  220. package/plugins/kimi-codex/skills/kimi-rescue/agents/openai.yaml +0 -6
  221. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +0 -36
  222. package/plugins/kimi-codex/skills/kimi-swarm-write/agents/openai.yaml +0 -6
  223. package/plugins/kimi-dsh/dist/commands/not-implemented.js +0 -4
@@ -7,6 +7,7 @@ import { preferStableNodePath } from "./hooks/install-paths.js";
7
7
  import { markJobFailed, waitForTerminalJob } from "./jobs.js";
8
8
  import { JobStore } from "./job-store.js";
9
9
  import { readArtifact } from "./render.js";
10
+ import { sleep } from "./util.js";
10
11
  // Resolves to runtime/companion.ts in dev (via tsx) and dist/companion.js in production (compiled
11
12
  // with tsc to the same relative layout). The extension is derived from the running module so the
12
13
  // child-process spawn in startBackgroundJob targets the right entrypoint in both modes.
@@ -15,6 +16,8 @@ const companionEntrypoint = fileURLToPath(new URL(isCompiledRuntime ? "./compani
15
16
  const companionProjectRoot = path.resolve(path.dirname(companionEntrypoint), "..");
16
17
  const FAILURE_PERSIST_RETRY_DELAYS_MS = [100, 200, 400];
17
18
  export async function startBackgroundJob(job, prompt, context, paths, options) {
19
+ const stem = options.workerKind.toUpperCase();
20
+ const spawnStage = `${options.workerKind}.worker.spawn`;
18
21
  // Background spawn and hook verification must resolve the same stable Node
19
22
  // path: the worker re-verifies the byte-exact hook command from its own
20
23
  // runtime path, so a different spelling than setup pinned fails closed. For
@@ -32,7 +35,7 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
32
35
  // Only fast-path the `fs.access` check for absolute/relative paths. A bare
33
36
  // name like "node" is resolved by spawn() via PATH; the spawn `error` listener
34
37
  // will still surface ENOENT on nextTick for that path, classified as
35
- // spawnFailedErrorCode via the listener below.
38
+ // <KIND>_WORKER_SPAWN_FAILED via the listener below.
36
39
  if (nodeBinary.includes("/") || nodeBinary.includes("\\")) {
37
40
  try {
38
41
  await access(nodeBinary, fsConstants.X_OK);
@@ -40,7 +43,7 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
40
43
  catch (accessError) {
41
44
  const code = accessError.code;
42
45
  if (code === "ENOENT" || code === "EACCES" || code === "EPERM") {
43
- const classified = new RuntimeError(options.nodeBinInvalidErrorCode, `Configured Node binary is not executable: ${nodeBinary}. Set KIMI_PLUGIN_CC_NODE_BIN to a valid Node >=22.5 executable and retry.`, options.spawnStage, accessError instanceof Error ? { cause: accessError } : undefined);
46
+ const classified = new RuntimeError(`${stem}_NODE_BIN_INVALID`, `Configured Node binary is not executable: ${nodeBinary}. Set KIMI_PLUGIN_CC_NODE_BIN to a valid Node >=22.5 executable and retry.`, spawnStage, accessError instanceof Error ? { cause: accessError } : undefined);
44
47
  await persistBackgroundFailure(paths, job.job_id, classified, options.failedSummary, "node-bin-invalid");
45
48
  throw classified;
46
49
  }
@@ -59,9 +62,7 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
59
62
  env: {
60
63
  ...context.env,
61
64
  KIMI_PLUGIN_CC_WORKSPACE_CWD: context.cwd,
62
- [options.promptEnvVar]: b64,
63
- [options.reusedSessionEnvVar]: options.reusedSession ? "1" : "0",
64
- ...(options.extraEnv ?? {}),
65
+ [`KIMI_PLUGIN_CC_${stem}_PROMPT_B64`]: b64,
65
66
  // A worker must reopen the exact store its parent selected, regardless of cwd.
66
67
  KIMI_PLUGIN_CC_DATA: path.resolve(paths.claudePluginData),
67
68
  },
@@ -78,7 +79,7 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
78
79
  };
79
80
  child.once("error", (spawnError) => {
80
81
  spawnReportedFailure = true;
81
- settle(new RuntimeError(options.spawnFailedErrorCode, `Background ${options.workerKind} worker failed to spawn: ${spawnError.message}`, options.spawnStage, { cause: spawnError }));
82
+ settle(new RuntimeError(`${stem}_WORKER_SPAWN_FAILED`, `Background ${options.workerKind} worker failed to spawn: ${spawnError.message}`, spawnStage, { cause: spawnError }));
82
83
  });
83
84
  // Give the event loop one tick to deliver a synchronous spawn error
84
85
  // (ENOENT fires on process.nextTick). If nothing fires by then, the
@@ -94,13 +95,13 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
94
95
  }
95
96
  // The worker exited non-zero before any state update. If the job is
96
97
  // still in its spawn phase, the worker never reached executeJob.
97
- const classified = new RuntimeError(options.earlyExitErrorCode, `Background ${options.workerKind} worker exited with code ${exitCode}${signal ? ` (signal ${signal})` : ""} before reporting a result.`, options.spawnStage);
98
+ const classified = new RuntimeError(`${stem}_WORKER_EXITED_EARLY`, `Background ${options.workerKind} worker exited with code ${exitCode}${signal ? ` (signal ${signal})` : ""} before reporting a result.`, spawnStage);
98
99
  void markEarlyExit(paths, job.job_id, classified, options.failedSummary);
99
100
  });
100
101
  child.unref();
101
102
  const spawnError = await spawnErrorPromise;
102
103
  if (spawnError) {
103
- await markSpawnFailure(paths, job.job_id, spawnError, options.failedSummary);
104
+ await persistBackgroundFailure(paths, job.job_id, spawnError, options.failedSummary, "spawn-failed");
104
105
  throw spawnError;
105
106
  }
106
107
  const store = new JobStore(paths);
@@ -116,7 +117,7 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
116
117
  if (options.wait) {
117
118
  const completed = await waitForTerminalJob(() => new JobStore(paths), job.job_id);
118
119
  if (!completed.final_output_path) {
119
- throw new RuntimeError(options.missingResultErrorCode, describeMissingResult(completed, options.workerKind), options.waitStage);
120
+ throw new RuntimeError(`${stem}_RESULT_MISSING`, describeMissingResult(completed, options.workerKind), `${options.workerKind}.wait`);
120
121
  }
121
122
  return readArtifact(completed.final_output_path);
122
123
  }
@@ -125,9 +126,6 @@ export async function startBackgroundJob(job, prompt, context, paths, options) {
125
126
  command_type: job.command_type,
126
127
  }, null, 2)}\n`;
127
128
  }
128
- async function markSpawnFailure(paths, jobId, classified, failedSummary) {
129
- await persistBackgroundFailure(paths, jobId, classified, failedSummary, "spawn-failed");
130
- }
131
129
  async function markEarlyExit(paths, jobId, classified, failedSummary) {
132
130
  await persistBackgroundFailure(paths, jobId, classified, failedSummary, "early-exit", (current) => {
133
131
  // Only mark failure if the worker exited before advancing past the spawn phase.
@@ -186,11 +184,6 @@ async function appendStuckJobTelemetry(paths, entry) {
186
184
  process.stderr.write(`[kimi-plugin-cc] failed to append stuck job telemetry at ${stuckPath}: ${formatError(appendError)}\n`);
187
185
  }
188
186
  }
189
- function sleep(ms) {
190
- return new Promise((resolve) => {
191
- setTimeout(resolve, ms);
192
- });
193
- }
194
187
  /**
195
188
  * Builds a descriptive message for the rare edge case where `waitForTerminalJob`
196
189
  * returns a terminal job whose `final_output_path` is null (e.g. `markJobFailed`'s
@@ -11,13 +11,18 @@ import { assertPromptFitsCommandLine } from "./prompt-size.js";
11
11
  import { createHookEscapeMonitor } from "./hook-escape.js";
12
12
  import { RuntimeError, formatError } from "./errors.js";
13
13
  import { assertNoUnsafeExperimentalSelector, assertExecutionPlanMatchesSpawn, } from "./kimi-engine.js";
14
+ import { HOOK_TEST_DELAY_ENV } from "./hooks/hook-timing.js";
14
15
  import { assertPrefixArgsSafe } from "./kimi-command.js";
16
+ import { backslashWorkspacePath } from "./rescue-approval.js";
15
17
  import { resolveKimiHome } from "./kimi-home.js";
18
+ import { kimiReleaseHas } from "./kimi-releases.js";
16
19
  import { assertNativeV2Preflight } from "./native-v2-preflight.js";
17
20
  import { parseVersionLine } from "./kimi-version-probe.js";
21
+ import { assertScopeSupported, NETWORK_ENV, READ_ROOTS_ENV, READ_SCOPE_LABELS, readScopeEnvironment, SCOPE_FLAGS_WRITE_MESSAGE, } from "./read-scope.js";
22
+ import { sleep } from "./util.js";
18
23
  import { BOUNDED_SWARM_POLICY, SWARM_CHILD_TIMEOUT_MS, SWARM_POLICY_ENV, SWARM_WAVE_SIZE_ENV, usesBoundedSwarmPolicy, } from "./swarm-policy.js";
19
24
  import { StreamJsonParser, extractSessionIdFromStderr, } from "./stream-json.js";
20
- import { collectDescendantIdentities, collectDescendantIdentitiesForRoots, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
25
+ import { collectDescendantIdentities, collectDescendantIdentitiesForRoots, raceValueWithTimeout, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
21
26
  /** Bytes of stderr retained for diagnostics on completion. Rolling buffer. */
22
27
  const STDERR_TAIL_BYTES = 8192;
23
28
  /** Hard cap on awaiting diagnostics log drain before resolving the result. */
@@ -51,10 +56,13 @@ export async function runCliPrompt(opts) {
51
56
  !opts.trustedWorkspaceRoot) {
52
57
  throw new RuntimeError("CLI_TRUSTED_WORKSPACE_ROOT_MISSING", `Refusing ${opts.commandLabel}: write-capable plugin launches require a plugin-owned trusted workspace root.`, "cli-client.pre-spawn", { details: { command_label: opts.commandLabel } });
53
58
  }
59
+ if (opts.commandLabel === "rescue" || opts.commandLabel === "swarm-write") {
60
+ assertWorkspaceSpellable(opts.commandLabel, [opts.cwd, opts.trustedWorkspaceRoot], "cli-client.pre-spawn");
61
+ }
54
62
  // The master experimental flag enables v2-only features (tower, subagent
55
- // fork) outside the certified no-plan profile. Refuse it at the final
56
- // boundary too, in case the environment changed after plan creation.
57
- assertNoUnsafeExperimentalSelector(opts.env, "cli-client.pre-spawn");
63
+ // fork) outside the certified no-plan profile. Legacy-v1 and uncertified
64
+ // plans refuse it at the final boundary too; native-v2 children never get it.
65
+ assertNoUnsafeExperimentalSelector(opts.env, "cli-client.pre-spawn", opts.executionPlan);
58
66
  // Validate the ACTUAL prefix argv used for this spawn — not only the
59
67
  // env-resolved value — so a forged/corrupt persisted plan cannot smuggle a
60
68
  // reserved kimi flag (e.g. `-r <session>`, which would resume a session the
@@ -70,6 +78,7 @@ export async function runCliPrompt(opts) {
70
78
  resumeSessionId: opts.resumeSessionId,
71
79
  expectedExecutionRoot: opts.trustedWorkspaceRoot ?? opts.cwd,
72
80
  stage: "cli-client.spawn",
81
+ release: opts.executionPlan,
73
82
  });
74
83
  }
75
84
  const args = buildArgs(opts);
@@ -128,7 +137,8 @@ export async function runCliPrompt(opts) {
128
137
  let announcedSystemVersion;
129
138
  const hookMonitor = createHookEscapeMonitor({ commandLabel: opts.commandLabel,
130
139
  operationKind: opts.executionPlan.operationKind, trustedWorkspaceRoot: opts.trustedWorkspaceRoot, cwd: opts.cwd,
131
- swarmPolicy: env[SWARM_POLICY_ENV], swarmWaveSize: env[SWARM_WAVE_SIZE_ENV] });
140
+ swarmPolicy: env[SWARM_POLICY_ENV], swarmWaveSize: env[SWARM_WAVE_SIZE_ENV],
141
+ readRoots: env[READ_ROOTS_ENV], network: env[NETWORK_ENV] });
132
142
  const hookEscapes = [];
133
143
  const noteHookEscape = (escape) => {
134
144
  hookEscapes.push(escape);
@@ -381,7 +391,7 @@ export async function runCliPrompt(opts) {
381
391
  const captureProcessIdentities = async (collect, excludedPid, onFailure) => {
382
392
  let snapshot;
383
393
  try {
384
- const collected = await raceWithValueTimeout(collect(), DESCENDANT_SNAPSHOT_TIMEOUT_MS, DESCENDANT_SNAPSHOT_TIMEOUT);
394
+ const collected = await raceValueWithTimeout(collect(), DESCENDANT_SNAPSHOT_TIMEOUT_MS, DESCENDANT_SNAPSHOT_TIMEOUT);
385
395
  if (collected === DESCENDANT_SNAPSHOT_TIMEOUT) {
386
396
  appendLogLine({
387
397
  event: "descendant_collection_timeout",
@@ -422,9 +432,8 @@ export async function runCliPrompt(opts) {
422
432
  try {
423
433
  process.kill(pid, signal);
424
434
  }
425
- catch (err) {
426
- const ignored = isErrnoException(err, "ESRCH") || isErrnoException(err, "EPERM");
427
- void ignored;
435
+ catch {
436
+ // ESRCH/EPERM and every other failure: best-effort signaling.
428
437
  }
429
438
  };
430
439
  const signalCapturedTree = async (childPid, identities, signal) => {
@@ -557,7 +566,7 @@ export async function runCliPrompt(opts) {
557
566
  return true;
558
567
  if (Date.now() >= deadline)
559
568
  return false;
560
- await new Promise((resolve) => setTimeout(resolve, Math.min(BOUNDED_DESCENDANT_POLL_MS, deadline - Date.now())));
569
+ await sleep(Math.min(BOUNDED_DESCENDANT_POLL_MS, deadline - Date.now()));
561
570
  }
562
571
  };
563
572
  const teardownBoundedTree = async () => {
@@ -677,17 +686,11 @@ export async function runCliPrompt(opts) {
677
686
  settle("reject", new RuntimeError(boundedSwarm ? "CLI_PROCESS_SETTLEMENT_FAILED" : "CLI_CANCELLATION_TEARDOWN_FAILED", "kimi owned process teardown failed", boundedSwarm ? "cli-client.settlement" : "cli-client.cancellation"));
678
687
  });
679
688
  };
680
- const stopForPolicyFailure = (error) => {
681
- engineMismatchDetected = true; // Stops all further consumer output.
682
- beginTeardown();
683
- settle("reject", error);
684
- };
685
- let engineMismatchError;
686
689
  handleEngineMismatch = (mismatch) => {
687
- if (engineMismatchError !== undefined)
690
+ if (engineMismatchDetected)
688
691
  return;
689
- engineMismatchDetected = true;
690
- engineMismatchError = new RuntimeError("CLI_ENGINE_PROVENANCE_MISMATCH", `Refusing kimi output: execution plan required ${plannedEngine}, but ${mismatch.reason}`, "cli-client.engine-provenance", {
692
+ engineMismatchDetected = true; // Stops all further consumer output.
693
+ const engineMismatchError = new RuntimeError("CLI_ENGINE_PROVENANCE_MISMATCH", `Refusing kimi output: execution plan required ${plannedEngine}, but ${mismatch.reason}`, "cli-client.engine-provenance", {
691
694
  details: {
692
695
  operation_kind: opts.executionPlan.operationKind,
693
696
  intended_engine: plannedEngine,
@@ -703,7 +706,8 @@ export async function runCliPrompt(opts) {
703
706
  system_version: mismatch.systemVersion ?? null,
704
707
  reason: mismatch.reason,
705
708
  });
706
- stopForPolicyFailure(engineMismatchError);
709
+ beginTeardown();
710
+ settle("reject", engineMismatchError);
707
711
  };
708
712
  const onAbort = () => {
709
713
  if (aborted)
@@ -737,12 +741,14 @@ export async function runCliPrompt(opts) {
737
741
  return;
738
742
  }
739
743
  }
744
+ const processError = (prefix, stage, err) => {
745
+ const details = { ...errorDetails(), ...spawnErrorDetails(err) };
746
+ return new RuntimeError("CLI_PROCESS_ERROR", `${prefix}: ${formatError(err)}`, stage, err instanceof Error ? { cause: err, details } : { details });
747
+ };
740
748
  earlyErrorHandled = true;
741
749
  child.on("error", (err) => {
742
750
  appendLogLine({ event: "process_error", message: formatError(err) });
743
- settle("reject", new RuntimeError("CLI_PROCESS_ERROR", `kimi subprocess error: ${formatError(err)}`, "cli-client.process", err instanceof Error
744
- ? { cause: err, details: { ...errorDetails(), ...spawnErrorDetails(err) } }
745
- : { details: { ...errorDetails(), ...spawnErrorDetails(err) } }));
751
+ settle("reject", processError("kimi subprocess error", "cli-client.process", err));
746
752
  });
747
753
  if (earlyErrors.length > 0) {
748
754
  const captured = earlyErrors[0];
@@ -753,7 +759,7 @@ export async function runCliPrompt(opts) {
753
759
  early: true,
754
760
  additional_count: earlyErrors.length - 1,
755
761
  });
756
- settle("reject", new RuntimeError("CLI_PROCESS_ERROR", `kimi subprocess error: ${formatError(captured)}`, "cli-client.process", { cause: captured, details: { ...errorDetails(), ...spawnErrorDetails(captured) } }));
762
+ settle("reject", processError("kimi subprocess error", "cli-client.process", captured));
757
763
  });
758
764
  }
759
765
  child.on("close", async (exitCode, signal) => {
@@ -833,9 +839,7 @@ export async function runCliPrompt(opts) {
833
839
  child.stdin.end();
834
840
  }
835
841
  catch (err) {
836
- settle("reject", new RuntimeError("CLI_PROCESS_ERROR", `kimi subprocess stream setup failed: ${formatError(err)}`, "cli-client.streams", err instanceof Error
837
- ? { cause: err, details: { ...errorDetails(), ...spawnErrorDetails(err) } }
838
- : { details: { ...errorDetails(), ...spawnErrorDetails(err) } }));
842
+ settle("reject", processError("kimi subprocess stream setup failed", "cli-client.streams", err));
839
843
  }
840
844
  });
841
845
  }
@@ -848,6 +852,17 @@ export async function runCliPrompt(opts) {
848
852
  * runCliPrompt — some callers (setup probes, smoke tests) are fine with
849
853
  * an undefined sessionId.
850
854
  */
855
+ /**
856
+ * Write confinement compares Node paths with kimi-code's `pathe` paths; a
857
+ * literal backslash in the run directory or trusted root is a separator to
858
+ * pathe only, so the two would name different directories.
859
+ */
860
+ export function assertWorkspaceSpellable(commandLabel, paths, stage) {
861
+ const slashed = backslashWorkspacePath(paths);
862
+ if (slashed === undefined)
863
+ return;
864
+ throw new RuntimeError("CLI_TRUSTED_WORKSPACE_ROOT_INVALID", `Refusing ${commandLabel}: write confinement cannot use ${slashed}: it contains a backslash, which kimi-code reads as a path separator. Run from a directory whose path has no backslash.`, stage, { details: { command_label: commandLabel, path: slashed } });
865
+ }
851
866
  export function requireSessionId(result, context) {
852
867
  if (result.sessionId !== undefined && result.sessionId.length > 0) {
853
868
  return result.sessionId;
@@ -966,7 +981,7 @@ function buildArgs(opts) {
966
981
  ? opts.env.KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE
967
982
  : undefined;
968
983
  if (opts.resumeSessionId === undefined &&
969
- ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3", "2.7.2", "2.7.3"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
984
+ kimiReleaseHas(opts.executionPlan.kimiVersion ?? smokeCandidate, "local-environment")) {
970
985
  args.push("--environment", "local");
971
986
  }
972
987
  if (opts.resumeSessionId !== undefined) {
@@ -1018,6 +1033,15 @@ export function buildKimiCliEnvironment(opts) {
1018
1033
  env.KIMI_CODE_NO_AUTO_UPDATE = "1";
1019
1034
  // Plugin-owned web lifecycles must not inherit ambient idle-session reclamation.
1020
1035
  env.KIMI_CODE_SESSION_IDLE_RECLAIM_MS = "0";
1036
+ // Tower and subagent fork are uncertified. A per-flag env value outranks
1037
+ // [experimental] config and the master flag upstream (0.42.0-2.7.3), and
1038
+ // "0" parses as false there, so these force both off for print and web.
1039
+ env.KIMI_CODE_EXPERIMENTAL_TOWER = "0";
1040
+ env.KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK = "0";
1041
+ // The master flag is read only from the child's own environment, so a
1042
+ // native-v2 child simply never receives it.
1043
+ if (opts.executionPlan.intendedEngine === "native-v2")
1044
+ delete env.KIMI_CODE_EXPERIMENTAL_FLAG;
1021
1045
  // Rescue and pursue share the write label. Only the immutable execution
1022
1046
  // plan can grant pursue's narrow goal-metadata access; never trust ambient
1023
1047
  // state inherited from another plugin job.
@@ -1034,6 +1058,19 @@ export function buildKimiCliEnvironment(opts) {
1034
1058
  // (env on the spawned process; the model cannot alter it). See field doc.
1035
1059
  env.KIMI_PLUGIN_CC_WORKSPACE_ROOT = opts.trustedWorkspaceRoot;
1036
1060
  }
1061
+ // Test-only hook delay: never reaches a job's hook.
1062
+ delete env[HOOK_TEST_DELAY_ENV];
1063
+ // Scope comes only from this call: an ambient value must never widen it.
1064
+ delete env[READ_ROOTS_ENV];
1065
+ delete env[NETWORK_ENV];
1066
+ const scopeEnv = readScopeEnvironment(opts.readScope, opts.cwd);
1067
+ if (Object.keys(scopeEnv).length > 0) {
1068
+ if (opts.commandLabel === undefined || !READ_SCOPE_LABELS.has(opts.commandLabel)) {
1069
+ throw new RuntimeError("READ_SCOPE_INVALID", SCOPE_FLAGS_WRITE_MESSAGE, "cli-client.environment");
1070
+ }
1071
+ assertScopeSupported(opts.readScope, opts.executionPlan.certification, "READ_SCOPE_INVALID", "cli-client.environment");
1072
+ Object.assign(env, scopeEnv);
1073
+ }
1037
1074
  return env;
1038
1075
  }
1039
1076
  function appendToTail(tail, chunk, maxBytes) {
@@ -1045,9 +1082,6 @@ function appendToTail(tail, chunk, maxBytes) {
1045
1082
  function truncateChars(value, maxChars) {
1046
1083
  return value.length <= maxChars ? value : value.slice(0, maxChars);
1047
1084
  }
1048
- function isErrnoException(err, code) {
1049
- return typeof err === "object" && err !== null && "code" in err && err.code === code;
1050
- }
1051
1085
  function raceWithTimeout(promise, timeoutMs) {
1052
1086
  let timer;
1053
1087
  const timeoutPromise = new Promise((resolve) => {
@@ -1061,18 +1095,3 @@ function raceWithTimeout(promise, timeoutMs) {
1061
1095
  clearTimeout(timer);
1062
1096
  });
1063
1097
  }
1064
- async function raceWithValueTimeout(promise, timeoutMs, timeoutValue) {
1065
- let timer;
1066
- try {
1067
- return await Promise.race([
1068
- promise,
1069
- new Promise((resolve) => {
1070
- timer = setTimeout(() => resolve(timeoutValue), Math.max(0, timeoutMs));
1071
- }),
1072
- ]);
1073
- }
1074
- finally {
1075
- if (timer !== undefined)
1076
- clearTimeout(timer);
1077
- }
1078
- }
@@ -3,7 +3,7 @@ import { allocateJobId } from "../job-id.js";
3
3
  import path from "node:path";
4
4
  import { createCliCancellationHandlers } from "../cli-cancellation.js";
5
5
  import { runCliPromptWithBudget } from "../cli-client.js";
6
- import { assertPersistedResumeLineage, executionPlanFromPersisted, observedExecutionFields, persistedExecutionPlanFields, prepareKimiExecutionPlan, reconcileHistoricalJobProvenance, } from "../kimi-engine.js";
6
+ import { assertPersistedResumeLineage, executionPlanFromPersisted, observedExecutionFields, persistedExecutionPlanFields, prepareKimiExecutionPlan, } from "../kimi-engine.js";
7
7
  import { getManagedCommandConfig } from "./registry.js";
8
8
  import { RuntimeError } from "../errors.js";
9
9
  import { resolveRepoIdentity } from "../git.js";
@@ -13,12 +13,13 @@ import { KIMI_ASK_PROMPT_TIMEOUT_MS } from "../kimi-timeouts.js";
13
13
  import { writeInvocationLogHeader } from "../logging.js";
14
14
  import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
15
15
  import { parseAskArgs } from "../parsing.js";
16
+ import { assertScopeSupported, effectiveReadRoots, parseJobReadScope, resolveReadScope, serializeReadScope } from "../read-scope.js";
16
17
  import { readArtifact, renderManagedJobOutput, writeArtifact } from "../render.js";
17
18
  import { classifyManagedCommandFailure } from "../kimi-errors.js";
18
19
  import { startBackgroundJob } from "../background-spawn.js";
19
- import { hookRefusalDetails, hookRefusalRetryProtocol, maybeWarnHookMissing, verifyHookInstalled, } from "../hooks/install.js";
20
- import { warnInheritedBudget, captureTimeoutPartialOutput, assertCliResultSuccess, reassembleProseFromRecords, warnIfSessionIdMissing, warnHookEscapes } from "./cli-helpers.js";
20
+ import { warnInheritedBudget, captureTimeoutPartialOutput, assertCliResultSuccess, reassembleProseFromRecords, warnIfSessionIdMissing, warnHookEscapes, resolveResumeSession, assertNetworkResumeConfined, resumeBudget, hookRefusal } from "./cli-helpers.js";
21
21
  import { buildKimiSessionTitle, syncKimiSessionTitle } from "../session-title.js";
22
+ import { shorten } from "../util.js";
22
23
  const ASK_SUMMARY_MAX = 120;
23
24
  const ASK_AGENT_PROFILE_PLACEHOLDER = "<cli-client>";
24
25
  const ASK_PROMPT_CONTRACT = [
@@ -45,6 +46,9 @@ export async function runAsk(argv, context) {
45
46
  const parsed = parseAskArgs(argv);
46
47
  if (parsed.help)
47
48
  return companionHelp(["ask", ...argv]);
49
+ // Scope always comes from this invocation, never from a resumed job.
50
+ const readScope = parsed.readRoots === undefined && parsed.network === undefined ? undefined
51
+ : await resolveReadScope(parsed.readRoots, parsed.network, "ask.parse");
48
52
  if (context.env.KIMI_PLUGIN_CC_SKIP_HOOK_CHECK !== "1") {
49
53
  await requireAskHookInstalled(context);
50
54
  }
@@ -56,16 +60,21 @@ export async function runAsk(argv, context) {
56
60
  try {
57
61
  await sweepStaleJobs(store, paths);
58
62
  const jobId = allocateJobId(context);
59
- const sessionResolution = await resolveAskSession(store, repoIdentity.repoId, parsed.fresh, parsed.resume, parsed.resumeTarget);
63
+ const sessionResolution = await resolveResumeSession(store, "ask", repoIdentity.repoId, parsed);
64
+ if (readScope?.network === true) {
65
+ assertNetworkResumeConfined(store, "ask", sessionResolution, effectiveReadRoots(readScope, context.cwd));
66
+ }
60
67
  const askPrompt = buildAskPrompt(parsed.prompt, sessionResolution.reusedSession);
61
68
  const executionPlan = await prepareKimiExecutionPlan({
62
69
  operationKind: "ask",
63
70
  cwd: context.cwd,
64
71
  env: context.env,
72
+ stderr: context.stderr,
65
73
  resumedFromJobId: sessionResolution.resumedFromJobId,
66
74
  resumeSessionId: sessionResolution.kimiSessionId ?? undefined,
67
75
  resumeSource: sessionResolution.sourceJob,
68
76
  });
77
+ assertScopeSupported(readScope, executionPlan.certification, "INVALID_ARGS", "ask.parse");
69
78
  const logPath = path.join(paths.logsDir, `ask-${jobId}.jsonl`);
70
79
  const job = store.createJob({
71
80
  job_id: jobId,
@@ -75,10 +84,9 @@ export async function runAsk(argv, context) {
75
84
  model: parsed.model ?? null,
76
85
  thinking: null,
77
86
  thinking_effort: parsed.thinkingEffort ?? null,
87
+ read_scope: serializeReadScope(readScope),
78
88
  background: parsed.background,
79
- budget_ms: parsed.budgetMs ?? (sessionResolution.sourceJob?.operation_kind === "ask" ? sessionResolution.sourceJob.budget_ms : null) ?? null,
80
- budget_source: parsed.budgetMs !== undefined ? "explicit"
81
- : sessionResolution.sourceJob?.operation_kind === "ask" && sessionResolution.sourceJob.budget_ms !== null ? "inherited" : "default",
89
+ ...resumeBudget("ask", parsed.budgetMs, sessionResolution.sourceJob),
82
90
  pid: parsed.background ? null : process.pid,
83
91
  kimi_pid: null,
84
92
  status: "running",
@@ -110,16 +118,7 @@ export async function runAsk(argv, context) {
110
118
  return startBackgroundJob(job, askPrompt, context, paths, {
111
119
  workerKind: "ask",
112
120
  wait: parsed.wait,
113
- promptEnvVar: "KIMI_PLUGIN_CC_ASK_PROMPT_B64",
114
- reusedSessionEnvVar: "KIMI_PLUGIN_CC_ASK_REUSED_SESSION",
115
- reusedSession: sessionResolution.reusedSession,
116
121
  failedSummary: askConfig.cancellation.failedSummary,
117
- missingResultErrorCode: "ASK_RESULT_MISSING",
118
- spawnFailedErrorCode: "ASK_WORKER_SPAWN_FAILED",
119
- earlyExitErrorCode: "ASK_WORKER_EXITED_EARLY",
120
- nodeBinInvalidErrorCode: "ASK_NODE_BIN_INVALID",
121
- waitStage: "ask.wait",
122
- spawnStage: "ask.worker.spawn",
123
122
  });
124
123
  }
125
124
  const completed = await executeAskJob(job.job_id, askPrompt, context);
@@ -152,6 +151,7 @@ export async function executeAskJob(jobId, prompt, context, options) {
152
151
  }
153
152
  handlers = createCliCancellationHandlers();
154
153
  const executionPlan = executionPlanFromPersisted(job);
154
+ const readScope = parseJobReadScope(job.read_scope);
155
155
  store.updateRunningJob(job.job_id, { phase: "turn-running" });
156
156
  // Re-validate resume lineage from the store before spawning: a detached
157
157
  // worker (or a forged queued row) reloads the persisted plan and would
@@ -173,6 +173,7 @@ export async function executeAskJob(jobId, prompt, context, options) {
173
173
  commandLabel: "ask",
174
174
  model: job.model ?? undefined,
175
175
  thinkingEffort: job.thinking_effort ?? undefined,
176
+ readScope,
176
177
  resumeSessionId: job.kimi_session_id ?? undefined,
177
178
  logPath: job.stream_log_path,
178
179
  onSpawn: (pid) => { store.updateRunningJob(job.job_id, { kimi_pid: pid }); },
@@ -194,7 +195,7 @@ export async function executeAskJob(jobId, prompt, context, options) {
194
195
  store.updateRunningJob(job.job_id, { kimi_session_id_source: "announced", kimi_session_id: result.sessionId });
195
196
  }
196
197
  await syncKimiSessionTitle({
197
- promptText: prompt,
198
+ promptText: askPromptSubject(prompt),
198
199
  env: context.env,
199
200
  cwd: job.cwd,
200
201
  sessionId: result.sessionId ?? job.kimi_session_id,
@@ -248,70 +249,9 @@ async function requireAskHookInstalled(context) {
248
249
  if (context.env.KIMI_PLUGIN_CC_SKIP_HOOK_CHECK === "1") {
249
250
  return;
250
251
  }
251
- const installStatus = await verifyHookInstalled(context.env);
252
- if (installStatus.installed) {
253
- return;
254
- }
255
- maybeWarnHookMissing(installStatus, "ask", context.stderr);
256
- throw new RuntimeError("ASK_HOOK_NOT_INSTALLED", [
257
- "ask refuses to run without the canonical kimi-plugin-cc PreToolUse hook.",
258
- `Hook check failed: ${installStatus.reason ?? "unknown"}.`,
259
- "Run /kimi:setup or $kimi-setup to install or repair this host's managed block.",
260
- "Set KIMI_PLUGIN_CC_SKIP_HOOK_CHECK=1 only if you intentionally accept un-enforced execution.",
261
- hookRefusalRetryProtocol(context.env),
262
- ].join(" "), "ask.hook-check", { details: hookRefusalDetails(installStatus) });
263
- }
264
- async function resolveAskSession(store, repoId, fresh, resume, resumeTarget) {
265
- if (fresh) {
266
- return { kimiSessionId: null, reusedSession: false, resumedFromJobId: null, sourceJob: null };
267
- }
268
- if (resumeTarget) {
269
- const byJob = store.getJob(resumeTarget);
270
- const scoped = byJob?.repo_id === repoId && byJob.command_type === "ask" ? byJob : null;
271
- const exact = scoped ?? store.findAskJobBySession(repoId, resumeTarget);
272
- if (!exact) {
273
- throw new RuntimeError("ASK_RESUME_NOT_FOUND", `No ask job or session matched ${resumeTarget}.`, "ask.resume");
274
- }
275
- // Order matters: surface ASK_ALREADY_RUNNING before complaining that
276
- // the session id is missing. In v1.0 a running ask row carries
277
- // kimi_session_id=NULL (kimi-code assigns the id post-call), so the
278
- // legacy "no session id → not found" check would mask the more
279
- // accurate "already running" error.
280
- const source = await reconcileHistoricalJobProvenance(store, exact);
281
- ensureAskSessionIsNotRunning(source);
282
- if (!source.kimi_session_id) {
283
- throw new RuntimeError("ASK_RESUME_NOT_FOUND", `No ask job or session matched ${resumeTarget}.`, "ask.resume");
284
- }
285
- return {
286
- kimiSessionId: source.kimi_session_id,
287
- reusedSession: true,
288
- resumedFromJobId: source.job_id,
289
- sourceJob: source,
290
- };
291
- }
292
- if (resume) {
293
- const latest = store.findLatestJob({ repoId, commandType: "ask" });
294
- if (!latest) {
295
- throw new RuntimeError("ASK_RESUME_NOT_FOUND", "No prior ask session exists for this repository.", "ask.resume");
296
- }
297
- const source = await reconcileHistoricalJobProvenance(store, latest);
298
- ensureAskSessionIsNotRunning(source);
299
- if (!source.kimi_session_id) {
300
- throw new RuntimeError("ASK_RESUME_NOT_FOUND", "No prior ask session exists for this repository.", "ask.resume");
301
- }
302
- return {
303
- kimiSessionId: source.kimi_session_id,
304
- reusedSession: true,
305
- resumedFromJobId: source.job_id,
306
- sourceJob: source,
307
- };
308
- }
309
- return { kimiSessionId: null, reusedSession: false, resumedFromJobId: null, sourceJob: null };
310
- }
311
- function ensureAskSessionIsNotRunning(job) {
312
- if (job.status === "running") {
313
- throw new RuntimeError("ASK_ALREADY_RUNNING", `Ask session ${job.kimi_session_id ?? "<unknown>"} is already active under job ${job.job_id}.`, "ask.resume");
314
- }
252
+ const refusal = await hookRefusal(context, "ask");
253
+ if (refusal)
254
+ throw refusal;
315
255
  }
316
256
  function buildAskPrompt(question, reusedSession) {
317
257
  if (question?.trim()) {
@@ -322,15 +262,8 @@ function buildAskPrompt(question, reusedSession) {
322
262
  }
323
263
  throw new RuntimeError("INVALID_ARGS", "ask requires a question after the flags.", "ask.parse");
324
264
  }
325
- function askPromptSubject(prompt) {
265
+ export function askPromptSubject(prompt) {
326
266
  if (prompt.startsWith(ASK_PROMPT_PREFIX))
327
267
  return prompt.slice(ASK_PROMPT_PREFIX.length);
328
268
  return prompt === ASK_RESUME_PROMPT ? ASK_CONTINUE_TASK : prompt;
329
269
  }
330
- function shorten(text, max) {
331
- const normalized = text.replace(/\s+/g, " ").trim();
332
- if (normalized.length <= max) {
333
- return normalized;
334
- }
335
- return `${normalized.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
336
- }
@@ -1,12 +1,12 @@
1
- import process from "node:process";
2
1
  import { RuntimeError } from "../errors.js";
3
2
  import { resolveRepoIdentity } from "../git.js";
4
- import { markJobCancelled, sweepStaleJobs } from "../jobs.js";
3
+ import { isPidAlive, killPid, lineagePhase, markJobCancelled, sweepStaleJobs } from "../jobs.js";
5
4
  import { JobStore, withJobStore } from "../job-store.js";
6
5
  import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
7
6
  import { parseJobLookupArgs } from "../parsing.js";
8
7
  import { revalidateProcessIdentities } from "../process-tree.js";
9
8
  import { getManagedCommandConfig } from "./registry.js";
9
+ import { sleep } from "../util.js";
10
10
  export async function runCancel(argv, context) {
11
11
  const parsed = parseJobLookupArgs(argv);
12
12
  const paths = resolvePluginPaths(context.env);
@@ -103,7 +103,7 @@ export async function runCancel(argv, context) {
103
103
  await withJobStore(paths, async (forcedStore) => {
104
104
  const current = forcedStore.getJob(job.job_id);
105
105
  if (current?.status === "running") {
106
- await markJobCancelled(forcedStore, paths, current, "Job was force-cancelled after recorded process termination.", undefined, current.command_type === "ask" || current.command_type === "rescue" ? { phase: "cancelled" } : undefined);
106
+ await markJobCancelled(forcedStore, paths, current, "Job was force-cancelled after recorded process termination.", undefined, lineagePhase(current, "cancelled"));
107
107
  }
108
108
  });
109
109
  return `${JSON.stringify({
@@ -149,25 +149,8 @@ function signalJobProcesses(job, signal, include = { companion: true, kimi: true
149
149
  pids.add(job.pid);
150
150
  if (include.kimi && job.kimi_pid !== null)
151
151
  pids.add(job.kimi_pid);
152
- for (const pid of pids) {
153
- try {
154
- process.kill(pid, signal);
155
- }
156
- catch (error) {
157
- const code = error.code;
158
- // ESRCH: process already gone. EPERM: pid was likely reused by an
159
- // unrelated process we don't own — silently skip rather than surface a
160
- // confusing "operation not permitted" to the user.
161
- if (code !== "ESRCH" && code !== "EPERM") {
162
- throw error;
163
- }
164
- }
165
- }
166
- }
167
- function sleep(ms) {
168
- return new Promise((resolve) => {
169
- setTimeout(resolve, ms);
170
- });
152
+ for (const pid of pids)
153
+ killPid(pid, signal);
171
154
  }
172
155
  async function waitForCancellation(paths, jobId) {
173
156
  const deadline = Date.now() + 4_000;
@@ -185,32 +168,10 @@ async function waitForCancellation(paths, jobId) {
185
168
  finally {
186
169
  store.close();
187
170
  }
188
- await new Promise((resolve) => {
189
- setTimeout(resolve, 200);
190
- });
171
+ await sleep(200);
191
172
  }
192
173
  return null;
193
174
  }
194
175
  function hasLiveRecordedProcess(job) {
195
- const pids = new Set();
196
- if (job.pid !== null)
197
- pids.add(job.pid);
198
- if (job.kimi_pid !== null)
199
- pids.add(job.kimi_pid);
200
- for (const pid of pids) {
201
- try {
202
- process.kill(pid, 0);
203
- return true;
204
- }
205
- catch (error) {
206
- const code = error.code;
207
- // ESRCH: definitively dead. EPERM: pid likely reused by an
208
- // unrelated process — treat as dead for our purposes (consistent
209
- // with isPidAlive in jobs.ts and signalJobProcesses above).
210
- if (code !== "ESRCH" && code !== "EPERM") {
211
- return true;
212
- }
213
- }
214
- }
215
- return false;
176
+ return (job.pid !== null && isPidAlive(job.pid)) || (job.kimi_pid !== null && job.kimi_pid !== job.pid && isPidAlive(job.kimi_pid));
216
177
  }