kimi-plugin-cc 2.5.9 → 2.6.2

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 (62) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +9 -0
  4. package/README.md +29 -13
  5. package/agents/kimi-swarm-write.md +6 -4
  6. package/agents/kimi-swarm.md +5 -4
  7. package/commands/swarm.md +5 -3
  8. package/dist/cli-client.js +223 -30
  9. package/dist/commands/recover-swarm.js +4 -0
  10. package/dist/commands/setup.js +5 -1
  11. package/dist/commands/swarm.js +130 -41
  12. package/dist/hooks/approval-hook.js +3 -0
  13. package/dist/hooks/approval-policy.js +34 -12
  14. package/dist/kimi-engine.js +6 -4
  15. package/dist/kimi-timeouts.js +4 -4
  16. package/dist/mcp/operations.js +1 -1
  17. package/dist/process-tree.js +150 -43
  18. package/dist/swarm-activation.js +5 -0
  19. package/dist/swarm-policy.js +72 -0
  20. package/dist/swarm-recovery.js +41 -10
  21. package/dist/swarm-tool-policy.js +146 -0
  22. package/dist/version.js +1 -1
  23. package/docs/migration.md +13 -5
  24. package/docs/registry-releases.md +4 -0
  25. package/docs/safety.md +40 -15
  26. package/docs/swarm-recovery.md +4 -2
  27. package/docs/upstream-2.6.2-certification.md +80 -2
  28. package/package.json +2 -2
  29. package/plugins/kimi-codex/.codex-plugin/plugin.json +1 -1
  30. package/plugins/kimi-codex/dist/cli-client.js +223 -30
  31. package/plugins/kimi-codex/dist/commands/recover-swarm.js +4 -0
  32. package/plugins/kimi-codex/dist/commands/setup.js +5 -1
  33. package/plugins/kimi-codex/dist/commands/swarm.js +130 -41
  34. package/plugins/kimi-codex/dist/hooks/approval-hook.js +3 -0
  35. package/plugins/kimi-codex/dist/hooks/approval-policy.js +34 -12
  36. package/plugins/kimi-codex/dist/kimi-engine.js +6 -4
  37. package/plugins/kimi-codex/dist/kimi-timeouts.js +4 -4
  38. package/plugins/kimi-codex/dist/mcp/operations.js +1 -1
  39. package/plugins/kimi-codex/dist/process-tree.js +150 -43
  40. package/plugins/kimi-codex/dist/swarm-activation.js +5 -0
  41. package/plugins/kimi-codex/dist/swarm-policy.js +72 -0
  42. package/plugins/kimi-codex/dist/swarm-recovery.js +41 -10
  43. package/plugins/kimi-codex/dist/swarm-tool-policy.js +146 -0
  44. package/plugins/kimi-codex/dist/version.js +1 -1
  45. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +2 -0
  46. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +2 -0
  47. package/plugins/kimi-dsh/dist/cli-client.js +223 -30
  48. package/plugins/kimi-dsh/dist/commands/recover-swarm.js +4 -0
  49. package/plugins/kimi-dsh/dist/commands/setup.js +5 -1
  50. package/plugins/kimi-dsh/dist/commands/swarm.js +130 -41
  51. package/plugins/kimi-dsh/dist/hooks/approval-hook.js +3 -0
  52. package/plugins/kimi-dsh/dist/hooks/approval-policy.js +34 -12
  53. package/plugins/kimi-dsh/dist/kimi-engine.js +6 -4
  54. package/plugins/kimi-dsh/dist/kimi-timeouts.js +4 -4
  55. package/plugins/kimi-dsh/dist/mcp/operations.js +1 -1
  56. package/plugins/kimi-dsh/dist/process-tree.js +150 -43
  57. package/plugins/kimi-dsh/dist/swarm-activation.js +5 -0
  58. package/plugins/kimi-dsh/dist/swarm-policy.js +72 -0
  59. package/plugins/kimi-dsh/dist/swarm-recovery.js +41 -10
  60. package/plugins/kimi-dsh/dist/swarm-tool-policy.js +146 -0
  61. package/plugins/kimi-dsh/dist/version.js +1 -1
  62. package/plugins/kimi-dsh/package.json +1 -1
@@ -12,12 +12,23 @@ const PROBE_TIMEOUT = Symbol("process-probe-timeout");
12
12
  * Capture descendant ancestry and reusable identities in the same bounded
13
13
  * process-table snapshot. There is no PID-only handoff: on Linux, PPID, PGID,
14
14
  * state, and start time come from one /proc/<pid>/stat read per row; other
15
- * POSIX systems use one ps invocation for the whole table.
15
+ * POSIX systems use one ps invocation for the whole table. Retained anchors
16
+ * supply expectedRoot so a reused PID cannot introduce unrelated descendants.
16
17
  */
17
- export async function collectDescendantIdentities(rootPid) {
18
+ export async function collectDescendantIdentities(rootPid, expectedRoot) {
18
19
  if (!Number.isInteger(rootPid) || rootPid <= 0 || process.platform === "win32")
19
20
  return [];
20
- const snapshot = await raceValueWithTimeout(collectVerifiedDescendantIdentities(rootPid), PROCESS_SNAPSHOT_TIMEOUT_MS);
21
+ const snapshot = await raceValueWithTimeout(collectVerifiedDescendantIdentities(rootPid, expectedRoot), PROCESS_SNAPSHOT_TIMEOUT_MS);
22
+ if (snapshot === PROBE_TIMEOUT) {
23
+ throw new Error(`process snapshot exceeded ${PROCESS_SNAPSHOT_TIMEOUT_MS}ms`);
24
+ }
25
+ return snapshot;
26
+ }
27
+ /** Collect owned roots and descendants with one shared table and targeted verification. */
28
+ export async function collectDescendantIdentitiesForRoots(expectedRoots) {
29
+ if (expectedRoots.length === 0 || process.platform === "win32")
30
+ return [];
31
+ const snapshot = await raceValueWithTimeout(collectVerifiedDescendantIdentitiesForRoots(expectedRoots), PROCESS_SNAPSHOT_TIMEOUT_MS);
21
32
  if (snapshot === PROBE_TIMEOUT) {
22
33
  throw new Error(`process snapshot exceeded ${PROCESS_SNAPSHOT_TIMEOUT_MS}ms`);
23
34
  }
@@ -142,19 +153,37 @@ export async function waitForProcessTreeExit(identities, timeoutMs, options = {}
142
153
  await sleep(Math.min(PROCESS_EXIT_POLL_MS, afterProbeRemainingMs));
143
154
  }
144
155
  }
145
- async function collectVerifiedDescendantIdentities(rootPid) {
156
+ async function collectVerifiedDescendantIdentities(rootPid, expectedRoot) {
157
+ if (expectedRoot !== undefined && expectedRoot.pid !== rootPid) {
158
+ return [];
159
+ }
146
160
  const initialRows = await collectProcessSnapshotRows();
147
161
  if (initialRows === undefined)
148
162
  throw new Error("process snapshot unavailable");
149
- const candidateRows = descendantRowsFromSnapshot(rootPid, initialRows);
150
163
  const initialRoot = initialRows.find((row) => row.pid === rootPid);
151
- if (initialRoot === undefined || candidateRows.length === 0)
164
+ if (initialRoot === undefined)
165
+ return [];
166
+ assertSignalableSnapshotRows([initialRoot]);
167
+ if (expectedRoot !== undefined &&
168
+ (initialRoot.startToken !== expectedRoot.startToken ||
169
+ initialRoot.processGroupId !== expectedRoot.processGroupId)) {
170
+ return [];
171
+ }
172
+ const candidateRows = descendantRowsFromSnapshot(rootPid, initialRows);
173
+ assertSignalableSnapshotRows(candidateRows);
174
+ if (candidateRows.length === 0)
152
175
  return [];
153
176
  // A second, targeted snapshot closes the cross-row /proc race: each child
154
177
  // must retain its PID and start token. Reparenting and PGID changes are not exit.
155
178
  const expectedRows = [initialRoot, ...candidateRows];
156
179
  const expectedByPid = new Map(expectedRows.map((row) => [row.pid, row]));
157
180
  const verificationRows = await readCurrentSnapshotRows(expectedRows);
181
+ const verifiedRoot = verificationRows.find((row) => row.pid === rootPid);
182
+ if (expectedRoot !== undefined && verifiedRoot !== undefined &&
183
+ (verifiedRoot.startToken !== expectedRoot.startToken ||
184
+ verifiedRoot.processGroupId !== expectedRoot.processGroupId)) {
185
+ return [];
186
+ }
158
187
  const stableRows = verificationRows.filter((current) => {
159
188
  const expected = expectedByPid.get(current.pid);
160
189
  return (expected !== undefined &&
@@ -163,20 +192,69 @@ async function collectVerifiedDescendantIdentities(rootPid) {
163
192
  });
164
193
  return stableRows.map(toProcessIdentity);
165
194
  }
166
- function descendantRowsFromSnapshot(rootPid, rows) {
167
- const root = rows.find((row) => row.pid === rootPid);
168
- if (root === undefined || isQuiescentState(root.state))
195
+ async function collectVerifiedDescendantIdentitiesForRoots(expectedRoots) {
196
+ const roots = expectedRoots.filter((root) => Number.isInteger(root.pid) && root.pid > 0);
197
+ if (roots.length === 0)
169
198
  return [];
170
- const childrenByParent = new Map();
171
- for (const row of rows) {
172
- if (row.pid <= 0 || row.parentPid <= 0 || row.pid === row.parentPid)
199
+ if (new Set(roots.map((root) => root.pid)).size > MAX_DESCENDANT_PIDS) {
200
+ throw new Error(`process descendant snapshot exceeded ${MAX_DESCENDANT_PIDS} identities`);
201
+ }
202
+ const initialRows = await collectProcessSnapshotRows();
203
+ if (initialRows === undefined)
204
+ throw new Error("process snapshot unavailable");
205
+ const initialByPid = new Map(initialRows.map((row) => [row.pid, row]));
206
+ const childrenByParent = indexChildrenByParent(initialRows);
207
+ const candidatesByRoot = new Map();
208
+ const expectedByPid = new Map();
209
+ for (const expected of roots) {
210
+ const root = initialByPid.get(expected.pid);
211
+ if (root !== undefined)
212
+ assertSignalableSnapshotRows([root]);
213
+ if (root === undefined || isQuiescentState(root.state) ||
214
+ root.startToken !== expected.startToken || root.processGroupId !== expected.processGroupId)
173
215
  continue;
174
- const children = childrenByParent.get(row.parentPid);
175
- if (children === undefined)
176
- childrenByParent.set(row.parentPid, [row]);
177
- else
178
- children.push(row);
216
+ if (candidatesByRoot.has(root.pid))
217
+ continue;
218
+ const candidates = [root, ...descendantRowsFromSnapshot(root.pid, initialRows, childrenByParent)];
219
+ assertSignalableSnapshotRows(candidates);
220
+ candidatesByRoot.set(root.pid, candidates);
221
+ for (const row of candidates) {
222
+ expectedByPid.set(row.pid, row);
223
+ if (expectedByPid.size > MAX_DESCENDANT_PIDS) {
224
+ throw new Error(`process descendant snapshot exceeded ${MAX_DESCENDANT_PIDS} identities`);
225
+ }
226
+ }
227
+ }
228
+ if (expectedByPid.size === 0)
229
+ return [];
230
+ const verificationRows = await readCurrentSnapshotRows([...expectedByPid.values()]);
231
+ const verifiedByPid = new Map(verificationRows.map((row) => [row.pid, row]));
232
+ const ownedPids = new Set();
233
+ for (const [rootPid, candidates] of candidatesByRoot) {
234
+ const expected = expectedByPid.get(rootPid);
235
+ const current = verifiedByPid.get(rootPid);
236
+ if (current !== undefined &&
237
+ (current.startToken !== expected.startToken || current.processGroupId !== expected.processGroupId))
238
+ continue;
239
+ for (const candidate of candidates)
240
+ ownedPids.add(candidate.pid);
179
241
  }
242
+ return verificationRows.filter((current) => {
243
+ const expected = expectedByPid.get(current.pid);
244
+ return ownedPids.has(current.pid) && expected !== undefined &&
245
+ current.startToken === expected.startToken && !isQuiescentState(current.state);
246
+ }).map(toProcessIdentity);
247
+ }
248
+ function assertSignalableSnapshotRows(rows) {
249
+ if (rows.some((row) => row.processGroupId <= 0)) {
250
+ throw new Error("process snapshot contains a nonsignalable owned process");
251
+ }
252
+ }
253
+ function descendantRowsFromSnapshot(rootPid, rows, indexedChildren) {
254
+ const root = rows.find((row) => row.pid === rootPid);
255
+ if (root === undefined || isQuiescentState(root.state))
256
+ return [];
257
+ const childrenByParent = indexedChildren ?? indexChildrenByParent(rows);
180
258
  const descendants = [];
181
259
  const seen = new Set([rootPid]);
182
260
  let frontier = [rootPid];
@@ -197,6 +275,19 @@ function descendantRowsFromSnapshot(rootPid, rows) {
197
275
  }
198
276
  return descendants;
199
277
  }
278
+ function indexChildrenByParent(rows) {
279
+ const childrenByParent = new Map();
280
+ for (const row of rows) {
281
+ if (row.pid <= 0 || row.parentPid <= 0 || row.pid === row.parentPid)
282
+ continue;
283
+ const children = childrenByParent.get(row.parentPid);
284
+ if (children === undefined)
285
+ childrenByParent.set(row.parentPid, [row]);
286
+ else
287
+ children.push(row);
288
+ }
289
+ return childrenByParent;
290
+ }
200
291
  async function readCurrentSnapshotRows(expectedRows) {
201
292
  const procPids = [];
202
293
  const psPids = [];
@@ -212,7 +303,7 @@ async function readCurrentSnapshotRows(expectedRows) {
212
303
  Promise.all(procPids.map((pid) => readProcRow(pid))),
213
304
  collectProcessSnapshotRowsFromPs(psPids),
214
305
  ]);
215
- if (procOutcomes.some((outcome) => outcome.status === "error") || (psPids.length > 0 && psRows === undefined)) {
306
+ if (procOutcomes.some((outcome) => outcome.status === "error" || outcome.status === "kernel" || outcome.status === "nonsignalable") || (psPids.length > 0 && psRows === undefined)) {
216
307
  throw new Error("process identity verification failed");
217
308
  }
218
309
  return [
@@ -221,12 +312,11 @@ async function readCurrentSnapshotRows(expectedRows) {
221
312
  ];
222
313
  }
223
314
  async function collectProcessSnapshotRows() {
224
- if (process.platform === "linux") {
225
- const procRows = await collectProcessSnapshotRowsFromProc();
226
- if (procRows !== undefined)
227
- return procRows;
228
- }
229
- return collectProcessSnapshotRowsFromPs();
315
+ // Linux probes use start ticks. Switching a failed table read to ps would
316
+ // give the same process a different identity, so genuine proc errors fail closed.
317
+ return process.platform === "linux"
318
+ ? collectProcessSnapshotRowsFromProc()
319
+ : collectProcessSnapshotRowsFromPs();
230
320
  }
231
321
  async function collectProcessSnapshotRowsFromProc() {
232
322
  let entries;
@@ -243,7 +333,9 @@ async function collectProcessSnapshotRowsFromProc() {
243
333
  .map((entry) => readProcRow(Number.parseInt(entry, 10))));
244
334
  if (outcomes.some((outcome) => outcome.status === "error"))
245
335
  return undefined;
246
- return outcomes.flatMap((outcome) => outcome.status === "found" ? [outcome.row] : []);
336
+ // Retain valid hidden/released groups for ancestry. Only a requested subtree
337
+ // that depends on such a row must fail; unrelated rows cannot disable capture.
338
+ return outcomes.flatMap((outcome) => outcome.status === "found" || outcome.status === "nonsignalable" ? [outcome.row] : []);
247
339
  }
248
340
  async function collectProcessSnapshotRowsFromPs(pids) {
249
341
  const uniquePids = pids === undefined ? undefined : uniqueValidPids(pids);
@@ -261,7 +353,9 @@ async function collectProcessSnapshotRowsFromPs(pids) {
261
353
  });
262
354
  stdout = result.stdout;
263
355
  }
264
- catch {
356
+ catch (err) {
357
+ if (uniquePids !== undefined && isExitCode(err, 1))
358
+ return [];
265
359
  return undefined;
266
360
  }
267
361
  return parsePsSnapshotRows(stdout);
@@ -294,7 +388,7 @@ async function readProcessIdentityBatchFromProc(pids) {
294
388
  if (outcome.status === "found") {
295
389
  identities.set(outcome.row.pid, toProcessIdentity(outcome.row));
296
390
  }
297
- else if (outcome.status === "error") {
391
+ else if (outcome.status === "error" || outcome.status === "kernel" || outcome.status === "nonsignalable") {
298
392
  complete = false;
299
393
  }
300
394
  }
@@ -367,29 +461,42 @@ async function readProcRow(pid) {
367
461
  const openParen = stat.indexOf("(");
368
462
  if (openParen < 1 || closeParen < openParen)
369
463
  return { status: "error" };
370
- const parsedPid = Number.parseInt(stat.slice(0, openParen).trim(), 10);
464
+ const rawPid = stat.slice(0, openParen).trim();
465
+ const parsedPid = Number(rawPid);
371
466
  const fields = stat.slice(closeParen + 1).trim().split(/\s+/);
372
467
  const state = fields[0];
373
- const parentPid = Number.parseInt(fields[1] ?? "", 10);
374
- const processGroupId = Number.parseInt(fields[2] ?? "", 10);
468
+ const parentPid = Number(fields[1]);
469
+ const processGroupId = Number(fields[2]);
375
470
  const startTimeTicks = fields[19];
376
- if (parsedPid !== pid ||
377
- state === undefined ||
378
- startTimeTicks === undefined ||
379
- !Number.isInteger(parentPid) ||
380
- !Number.isInteger(processGroupId) ||
381
- processGroupId <= 0) {
471
+ if (!/^\d+$/.test(rawPid) || !Number.isSafeInteger(parsedPid) || parsedPid !== pid ||
472
+ state === undefined || !/^[a-z]$/i.test(state) ||
473
+ startTimeTicks === undefined || !/^\d+$/.test(startTimeTicks) ||
474
+ !/^\d+$/.test(fields[1] ?? "") || !Number.isSafeInteger(parentPid) ||
475
+ !/^(?:\d+|-1)$/.test(fields[2] ?? "") || !Number.isSafeInteger(processGroupId)) {
382
476
  return { status: "error" };
383
477
  }
478
+ const row = {
479
+ pid,
480
+ parentPid,
481
+ processGroupId,
482
+ startToken: `proc:${startTimeTicks}`,
483
+ state,
484
+ };
485
+ if (processGroupId <= 0) {
486
+ // /proc stat field 9 carries PF_KTHREAD (Linux include/linux/sched.h).
487
+ // Only proven kernel threads are outside the user-process ancestry;
488
+ // a namespace-hidden user PGID of zero must remain an incomplete probe.
489
+ const rawFlags = fields[6];
490
+ const flags = rawFlags === undefined || !/^\d+$/.test(rawFlags) ? NaN : Number(rawFlags);
491
+ if (!Number.isSafeInteger(flags) || flags < 0 || flags > 0xffff_ffff)
492
+ return { status: "error" };
493
+ if (fields[2] === "0" && (flags & 0x0020_0000) !== 0)
494
+ return { status: "kernel" };
495
+ return { status: "nonsignalable", row };
496
+ }
384
497
  return {
385
498
  status: "found",
386
- row: {
387
- pid,
388
- parentPid,
389
- processGroupId,
390
- startToken: `proc:${startTimeTicks}`,
391
- state,
392
- },
499
+ row,
393
500
  };
394
501
  }
395
502
  function parsePsSnapshotRows(stdout) {
@@ -9,6 +9,8 @@ import { assertPrefixArgsSafe } from "./kimi-command.js";
9
9
  import { assertExecutionPlanMatchesSpawn, assertNoUnsafeExperimentalSelector, } from "./kimi-engine.js";
10
10
  import { resolveKimiHome } from "./kimi-home.js";
11
11
  import { assertNativeV2Preflight } from "./native-v2-preflight.js";
12
+ import { usesBoundedSwarmPolicy } from "./swarm-policy.js";
13
+ import { installBoundedSwarmToolPolicy } from "./swarm-tool-policy.js";
12
14
  import { collectDescendantIdentities, collectProcessGroupsIdentities, probeProcessIdentity, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
13
15
  // These exact 2.6.x activation entries support candidate integration; production scope is per operation.
14
16
  const PREACTIVATION_VERSIONS = ["2.3.2", "2.3.3", "2.4.0", "2.4.1", "2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"];
@@ -51,6 +53,9 @@ export async function preactivateSwarmSession(options) {
51
53
  await verifySwarmStatus(web, identity, true, model, prepared.expectedVersion, options.signal, failureCode);
52
54
  await shutdownWeb(web, options.signal, failureCode);
53
55
  await requireSwarmJournal(prepared.kimiHome, identity, "enter", options.signal, failureCode);
56
+ if (usesBoundedSwarmPolicy(options.executionPlan) && options.swarmMaxConcurrency > 1) {
57
+ await installBoundedSwarmToolPolicy(prepared.kimiHome, identity, options.signal);
58
+ }
54
59
  throwIfAborted(options.signal, failureCode, "swarm-activation.complete");
55
60
  return identity;
56
61
  }
@@ -0,0 +1,72 @@
1
+ export const SWARM_POLICY_ENV = "KIMI_PLUGIN_CC_SWARM_POLICY";
2
+ export const SWARM_WAVE_SIZE_ENV = "KIMI_PLUGIN_CC_SWARM_WAVE_SIZE";
3
+ export const BOUNDED_SWARM_POLICY = "bounded-waves/1";
4
+ // Native retry timeouts can return a wave before its child work settles. This
5
+ // valid upstream timer exceeds the plugin's finite <=24h job deadline, so only
6
+ // terminal whole-job cancellation can interrupt a wave. Environment 0 is ignored.
7
+ export const SWARM_CHILD_TIMEOUT_MS = 2_147_483_647;
8
+ export function usesBoundedSwarmPolicy(plan) {
9
+ return plan.intendedEngine === "native-v2" && plan.kimiVersion === "2.6.2" &&
10
+ (plan.operationKind === "swarm" || plan.operationKind === "swarm-write");
11
+ }
12
+ function plainObject(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value) &&
14
+ (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
15
+ }
16
+ function nonemptyString(value) {
17
+ return typeof value === "string" && value.trim().length > 0;
18
+ }
19
+ const SWARM_INPUT_KEYS = new Set([
20
+ "description", "subagent_type", "prompt_template", "items", "fork", "resume_agent_ids", "model",
21
+ ]);
22
+ /** Stateless admission; repeated host hooks cannot consume or refund slots. */
23
+ export function evaluateSwarmWaveInput(input, policy, waveSize) {
24
+ const deny = (reason) => ({
25
+ decision: "deny",
26
+ reason: `kimi-plugin-cc safety hook: AgentSwarm denied: ${reason}`,
27
+ });
28
+ if (policy !== BOUNDED_SWARM_POLICY)
29
+ return deny("missing or unrecognized swarm policy.");
30
+ const width = typeof waveSize === "string" && /^[1-9][0-9]*$/.test(waveSize)
31
+ ? Number(waveSize) : NaN;
32
+ if (!Number.isSafeInteger(width) || width < 1)
33
+ return deny("missing or invalid trusted wave size.");
34
+ if (width === 1) {
35
+ return deny("concurrency 1 uses one worker directly; complete the task yourself without delegation.");
36
+ }
37
+ if (!plainObject(input))
38
+ return deny("arguments must be an object.");
39
+ if (Reflect.ownKeys(input).some((key) => typeof key !== "string" || !SWARM_INPUT_KEYS.has(key))) {
40
+ return deny("unrecognized arguments.");
41
+ }
42
+ if (!nonemptyString(input.description))
43
+ return deny("description must be a nonempty string.");
44
+ for (const key of ["subagent_type", "prompt_template"]) {
45
+ if (input[key] !== undefined && !nonemptyString(input[key]))
46
+ return deny(`${key} must be a nonempty string.`);
47
+ }
48
+ if (input.model !== undefined && typeof input.model !== "string")
49
+ return deny("model must be a string.");
50
+ if (input.fork !== undefined && input.fork !== false)
51
+ return deny("forked subagents are not supported.");
52
+ if (input.items !== undefined && (!Array.isArray(input.items) || !input.items.every(nonemptyString))) {
53
+ return deny("items must be an array of nonempty strings.");
54
+ }
55
+ if (input.resume_agent_ids !== undefined && (!plainObject(input.resume_agent_ids) ||
56
+ Reflect.ownKeys(input.resume_agent_ids).some((key) => typeof key !== "string" ||
57
+ !nonemptyString(key) || !nonemptyString(input.resume_agent_ids[key])))) {
58
+ return deny("resume_agent_ids must map nonempty agent IDs to nonempty prompts.");
59
+ }
60
+ const fresh = Array.isArray(input.items) ? input.items.length : 0;
61
+ const resumed = plainObject(input.resume_agent_ids) ? Object.keys(input.resume_agent_ids).length : 0;
62
+ const total = fresh + resumed;
63
+ if (total === 0)
64
+ return deny("a wave must contain at least one new or resumed entry.");
65
+ if (total > width) {
66
+ return deny(`wave has ${total} new and resumed entries, exceeding the limit ${width}; split the work into sequential waves of at most ${width} entries and wait for each wave to finish.`);
67
+ }
68
+ if (fresh === 1 && resumed === 0) {
69
+ return deny("fresh-only waves require at least two entries; regroup targets into disjoint entries within the wave limit, or resume an existing child for the remaining work.");
70
+ }
71
+ return { decision: "allow" };
72
+ }
@@ -22,6 +22,21 @@ export function recordRecoveryEvent(store, record, event) {
22
22
  launch.quiescent = true;
23
23
  launch.pending = false;
24
24
  }
25
+ else if (event.kind === "print-processes-snapshot") {
26
+ const root = launch.identities[0];
27
+ if (!root)
28
+ throw recoveryError("The print root identity was not durably recorded before its process snapshot.");
29
+ // The root remains the recovery anchor after exit. Complete bounded
30
+ // snapshots replace historical descendants; an incomplete observation
31
+ // cannot discard an identity whose exit has not been proven.
32
+ const previous = new Map(launch.identities.map((identity) => [processIdentityKey(identity), identity]));
33
+ const current = event.identities.map((identity) => previous.get(processIdentityKey(identity)) ?? identity);
34
+ const all = event.complete ? [root, ...current] : [...launch.identities, ...current];
35
+ launch.identities = [...new Map(all.map((identity) => [processIdentityKey(identity), identity])).values()];
36
+ launch.pending = false;
37
+ launch.uncertain = !event.complete;
38
+ launch.boundedSnapshot = true;
39
+ }
25
40
  else if ("identities" in event) {
26
41
  const all = [...launch.identities, ...event.identities];
27
42
  launch.identities = [...new Map(all.map((identity) => [`${identity.pid}:${identity.startToken}:${identity.processGroupId}`, identity])).values()];
@@ -31,6 +46,10 @@ export function recordRecoveryEvent(store, record, event) {
31
46
  }
32
47
  store.saveSwarmRecovery(record.jobId, record);
33
48
  }
49
+ function processIdentityKey(identity) {
50
+ // A changed process group is not a new ownership grant for the same process.
51
+ return `${identity.pid}:${identity.startToken}`;
52
+ }
34
53
  export function finishRecoveryRecord(store, record) {
35
54
  record.complete = !record.sessionDirty && record.launches.every((entry) => entry.quiescent)
36
55
  && (record.workspaceRoot === null || record.patchPath !== null);
@@ -50,10 +69,9 @@ export async function assertRecoveryOwnerGone(record) {
50
69
  }
51
70
  }
52
71
  /**
53
- * Linux may fall back from /proc to ps for a whole-group snapshot while targeted
54
- * identity reads still use /proc. Those start tokens are different namespaces,
55
- * not different processes. Prove both representations current around the known
56
- * identity read; never accept a member based on PID/PGID equality alone.
72
+ * Older Linux records may retain ps start tokens while current snapshots use
73
+ * /proc start ticks. Prove both representations current around the known identity
74
+ * read; never accept a member based on PID/PGID equality alone.
57
75
  */
58
76
  export async function validateRecoveryGroupMembers(known, members, validate = revalidateProcessIdentities) {
59
77
  const membership = await validate(members);
@@ -73,6 +91,24 @@ export async function validateRecoveryGroupMembers(known, members, validate = re
73
91
  }
74
92
  return ownership.identities;
75
93
  }
94
+ export async function inspectRecoveryLaunchProcesses(launch, validate = revalidateProcessIdentities, collect = collectProcessGroupsIdentities) {
95
+ let known = launch.identities;
96
+ if (launch.kind === "print" && launch.boundedSnapshot === true) {
97
+ const live = await validate(known);
98
+ if (!live.complete || live.groupChanged?.length) {
99
+ throw recoveryError("Process ownership or group membership is uncertain.");
100
+ }
101
+ // The saved root remains first for ancestry recovery, but an exited root
102
+ // grants no ownership of its numeric group after that group is reused.
103
+ known = live.identities;
104
+ if (known.length === 0)
105
+ return [];
106
+ }
107
+ const members = await collect(known.map((identity) => identity.processGroupId));
108
+ if (members === undefined)
109
+ throw recoveryError("Process group membership is unreadable.");
110
+ return validateRecoveryGroupMembers(known, members, validate);
111
+ }
76
112
  /** Never signal an unproven group, PID replacement, or changed-PGID process. */
77
113
  export async function recoverLaunch(launch, persist, signal) {
78
114
  if (launch.quiescent)
@@ -96,12 +132,7 @@ export async function recoverLaunch(launch, persist, signal) {
96
132
  launch.identities = [...new Map([...launch.identities, ...descendants].map((id) => [`${id.pid}:${id.startToken}:${id.processGroupId}`, id])).values()];
97
133
  persist();
98
134
  }
99
- const inspect = async () => {
100
- const members = await collectProcessGroupsIdentities(launch.identities.map((id) => id.processGroupId));
101
- if (members === undefined)
102
- throw recoveryError("Process group membership is unreadable.");
103
- return validateRecoveryGroupMembers(launch.identities, members);
104
- };
135
+ const inspect = () => inspectRecoveryLaunchProcesses(launch);
105
136
  for (const [killSignal, waitMs] of [["SIGTERM", 1500], ["SIGKILL", 500]]) {
106
137
  signal?.throwIfAborted();
107
138
  for (const identity of await inspect()) {
@@ -0,0 +1,146 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { link, lstat, mkdir, open, realpath, unlink } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { RuntimeError } from "./errors.js";
6
+ const POLICY_CONTENT = `${JSON.stringify({ disabledTools: ["TaskStop"] })}\n`;
7
+ const POLICY_MAX_BYTES = 4096;
8
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,255}$/;
9
+ /**
10
+ * Called only for our fresh, stopped, journal-proven session before its first
11
+ * print turn. TaskStop is already denied by the managed hook; disabling it in
12
+ * native policy also makes Bash's allowBackground false for every child,
13
+ * including its automatic foreground-timeout detachment path.
14
+ */
15
+ export async function installBoundedSwarmToolPolicy(kimiHome, identity, signal) {
16
+ const directories = [];
17
+ let candidatePath;
18
+ let candidateIdentity;
19
+ try {
20
+ checkSignal(signal);
21
+ if (!SAFE_ID.test(identity.sessionId) || !SAFE_ID.test(identity.workspaceId)) {
22
+ throw policyFailure("invalid-session-identity");
23
+ }
24
+ const canonicalHome = await realpath(kimiHome);
25
+ let current = canonicalHome;
26
+ for (const segment of [undefined, "sessions", identity.workspaceId, identity.sessionId]) {
27
+ if (segment !== undefined)
28
+ current = path.join(current, segment);
29
+ directories.push(await directoryIdentity(current));
30
+ checkSignal(signal);
31
+ }
32
+ const policyDir = path.join(current, "tool-policy");
33
+ await assertDirectoriesUnchanged(directories);
34
+ await mkdir(policyDir, { mode: 0o700 }).catch((error) => {
35
+ if (error.code !== "EEXIST")
36
+ throw error;
37
+ });
38
+ directories.push(await directoryIdentity(policyDir));
39
+ const statePath = path.join(policyDir, "state.json");
40
+ // No merge or replacement: this is a fresh-session construction, not an
41
+ // operator-policy editor. link() below closes this absence-check race.
42
+ const existing = await lstat(statePath).catch((error) => {
43
+ if (error.code === "ENOENT")
44
+ return undefined;
45
+ throw error;
46
+ });
47
+ if (existing !== undefined)
48
+ throw policyFailure("policy-already-exists");
49
+ checkSignal(signal);
50
+ await assertDirectoriesUnchanged(directories);
51
+ candidatePath = path.join(policyDir, `.state.${process.pid}.${randomUUID()}.tmp`);
52
+ const candidate = await open(candidatePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
53
+ try {
54
+ const stats = await candidate.stat({ bigint: true });
55
+ candidateIdentity = { dev: stats.dev, ino: stats.ino };
56
+ if (!stats.isFile())
57
+ throw policyFailure("candidate-not-regular");
58
+ if (process.platform !== "win32")
59
+ await candidate.chmod(0o600);
60
+ await candidate.writeFile(POLICY_CONTENT, "utf8");
61
+ await candidate.sync();
62
+ }
63
+ finally {
64
+ await candidate.close();
65
+ }
66
+ checkSignal(signal);
67
+ await assertDirectoriesUnchanged(directories);
68
+ // A hard link publishes the complete synced inode atomically and refuses
69
+ // an existing destination, unlike rename(), which could replace policy.
70
+ await link(candidatePath, statePath);
71
+ await verifyPublishedPolicy(statePath, candidateIdentity);
72
+ await assertDirectoriesUnchanged(directories);
73
+ checkSignal(signal);
74
+ }
75
+ catch (error) {
76
+ if (signal?.aborted)
77
+ throw policyFailure("cancelled", true);
78
+ if (error instanceof RuntimeError)
79
+ throw error;
80
+ throw policyFailure("policy-installation-failed");
81
+ }
82
+ finally {
83
+ // Never unlink a replacement or follow a replaced ancestor while cleaning
84
+ // up our private candidate. An uncertain path remains as failure evidence.
85
+ if (candidatePath !== undefined && candidateIdentity !== undefined) {
86
+ try {
87
+ await assertDirectoriesUnchanged(directories);
88
+ const stats = await lstat(candidatePath, { bigint: true });
89
+ if (stats.isFile() && sameIdentity(stats, candidateIdentity))
90
+ await unlink(candidatePath);
91
+ }
92
+ catch { /* Preserve uncertain paths. */ }
93
+ }
94
+ }
95
+ }
96
+ async function directoryIdentity(directory) {
97
+ const stats = await lstat(directory, { bigint: true });
98
+ if (!stats.isDirectory() || stats.isSymbolicLink() || await realpath(directory) !== directory) {
99
+ throw policyFailure("unsafe-session-directory");
100
+ }
101
+ return { path: directory, dev: stats.dev, ino: stats.ino };
102
+ }
103
+ async function assertDirectoriesUnchanged(directories) {
104
+ for (const directory of directories) {
105
+ const current = await directoryIdentity(directory.path);
106
+ if (!sameIdentity(current, directory))
107
+ throw policyFailure("session-directory-changed");
108
+ }
109
+ }
110
+ async function verifyPublishedPolicy(statePath, expected) {
111
+ const file = await open(statePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
112
+ try {
113
+ const before = await file.stat({ bigint: true });
114
+ if (!before.isFile() || before.size > BigInt(POLICY_MAX_BYTES) || !sameIdentity(before, expected)) {
115
+ throw policyFailure("published-policy-invalid");
116
+ }
117
+ const bytes = Buffer.alloc(Number(before.size));
118
+ let offset = 0;
119
+ while (offset < bytes.length) {
120
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
121
+ if (bytesRead === 0)
122
+ break;
123
+ offset += bytesRead;
124
+ }
125
+ const after = await file.stat({ bigint: true });
126
+ const named = await lstat(statePath, { bigint: true });
127
+ if (offset !== bytes.length || bytes.toString("utf8") !== POLICY_CONTENT ||
128
+ before.size !== after.size || !sameIdentity(after, expected) ||
129
+ !named.isFile() || !sameIdentity(named, expected)) {
130
+ throw policyFailure("published-policy-changed");
131
+ }
132
+ }
133
+ finally {
134
+ await file.close();
135
+ }
136
+ }
137
+ function sameIdentity(a, b) {
138
+ return a.dev === b.dev && a.ino === b.ino;
139
+ }
140
+ function checkSignal(signal) {
141
+ if (signal?.aborted)
142
+ throw policyFailure("cancelled", true);
143
+ }
144
+ function policyFailure(reason, cancelled = false) {
145
+ return new RuntimeError("SWARM_ACTIVATION_FAILED", "The fresh swarm session could not install its native tool restriction; refusing the model turn.", "swarm-activation.tool-policy", { details: { reason, ...(cancelled ? { cancelled: true } : {}) } });
146
+ }
@@ -4,4 +4,4 @@
4
4
  // and AGENTS.md on every release. A future improvement would read this from
5
5
  // package.json at build time, but that adds a build-step dependency we
6
6
  // don't want yet.
7
- export const KIMI_PLUGIN_CC_VERSION = "2.5.9";
7
+ export const KIMI_PLUGIN_CC_VERSION = "2.6.2";
@@ -29,5 +29,7 @@ Pass through: `[--budget <30m|1h>] [--cap <N>] [--max-concurrency <N>] [-m <mode
29
29
  - For subscription auth, guide native Kimi `/login`; for API keys or other providers, guide native `/provider` and have the user enter secrets there. Only an explicit saved-default request calls for native `/model`. Re-list after setup; use `setup --check` for hook readiness. Swarm `-m` selects the coordinator; `[secondary_model]` can select different child models.
30
30
  - Require many independent review targets plus explicit fan-out intent.
31
31
  - Pass finite budget and concurrency bounds; default to foreground unless the user explicitly asks to detach.
32
+ - On exact Kimi Code 2.6.2, concurrency 1 runs one direct worker; larger values use bounded sequential waves. Older certified versions retain their normal-launch limit and recovery limitation.
33
+ - The bound counts simultaneous Kimi child-agent turns, not OS subprocesses. Fresh-only waves need at least two entries; group odd target counts into disjoint worker assignments.
32
34
  - If the companion reports SWARM_HOOK_NOT_INSTALLED, tell the user to run Claude Code /kimi:setup or Codex $kimi-setup, then retry.
33
35
  - Return the consolidated companion report verbatim.
@@ -29,6 +29,8 @@ Pass through: `[--budget <30m|1h>] [--cap <N>] [--max-concurrency <N>] [-m <mode
29
29
  - For subscription auth, guide native Kimi `/login`; for API keys or other providers, guide native `/provider` and have the user enter secrets there. Only an explicit saved-default request calls for native `/model`. Re-list after setup; use `setup --check` for hook readiness. Swarm `-m` selects the coordinator; `[secondary_model]` can select different child models.
30
30
  - Require both many disjoint write targets and explicit parallel fan-out intent.
31
31
  - Keep `--max-concurrency` conservative, normally 1, unless the user explicitly asks to widen it.
32
+ - On exact Kimi Code 2.6.2, the default concurrency 1 runs a single worker in the throwaway worktree. Explicit concurrency 2 or higher uses bounded waves; every mode returns a patch for review.
33
+ - Parallel Kimi workers cannot background shell commands; native foreground Bash has a 60-second default and 300-second maximum timeout. Choose concurrency 1 for longer tests. Owned process cleanup must finish before patch capture; failed verification retains the worktree instead.
32
34
  - The runtime rejects `--background`, but detaching your own shell call is expected: a fan-out routinely outlives a foreground timeout, and the run is patch-only and worktree-confined. Keep `--budget` and `--max-concurrency` finite. To stop a run, use `companion.sh cancel` with NO id — it targets the latest running job for the repo, and no UUID crosses you or the user (a detached run prints nothing at launch; the id first arrives with the final report). Prefer that over an interrupt: an interrupt gives the companion only ~1.35s before SIGKILL, less than its teardown plus `git diff --binary` patch capture, so interrupting can lose the patch.
33
35
  - If the companion reports SWARM_HOOK_NOT_INSTALLED, tell the user to run Claude Code /kimi:setup or Codex $kimi-setup, then retry.
34
36
  - Return the patch path and companion output verbatim; do not apply the patch unless the user separately asks.