kimi-plugin-cc 2.5.8 → 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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +19 -0
- package/README.md +29 -13
- package/agents/kimi-swarm-write.md +6 -4
- package/agents/kimi-swarm.md +5 -4
- package/commands/swarm.md +5 -3
- package/dist/cli-client.js +224 -31
- package/dist/commands/recover-swarm.js +4 -0
- package/dist/commands/setup.js +5 -1
- package/dist/commands/swarm.js +131 -43
- package/dist/hooks/approval-hook.js +3 -0
- package/dist/hooks/approval-policy.js +34 -12
- package/dist/hooks/config-safety.js +5 -4
- package/dist/kimi-engine.js +5 -3
- package/dist/kimi-timeouts.js +4 -4
- package/dist/mcp/operations.js +1 -1
- package/dist/process-tree.js +150 -43
- package/dist/swarm-activation.js +14 -9
- package/dist/swarm-policy.js +72 -0
- package/dist/swarm-recovery.js +41 -10
- package/dist/swarm-tool-policy.js +146 -0
- package/dist/version.js +1 -1
- package/docs/migration.md +13 -5
- package/docs/registry-releases.md +6 -0
- package/docs/safety.md +41 -16
- package/docs/swarm-recovery.md +4 -2
- package/docs/upstream-2.6.0-certification.md +13 -0
- package/docs/upstream-2.6.2-certification.md +132 -0
- package/package.json +3 -2
- package/plugins/kimi-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/kimi-codex/dist/cli-client.js +224 -31
- package/plugins/kimi-codex/dist/commands/recover-swarm.js +4 -0
- package/plugins/kimi-codex/dist/commands/setup.js +5 -1
- package/plugins/kimi-codex/dist/commands/swarm.js +131 -43
- package/plugins/kimi-codex/dist/hooks/approval-hook.js +3 -0
- package/plugins/kimi-codex/dist/hooks/approval-policy.js +34 -12
- package/plugins/kimi-codex/dist/hooks/config-safety.js +5 -4
- package/plugins/kimi-codex/dist/kimi-engine.js +5 -3
- package/plugins/kimi-codex/dist/kimi-timeouts.js +4 -4
- package/plugins/kimi-codex/dist/mcp/operations.js +1 -1
- package/plugins/kimi-codex/dist/process-tree.js +150 -43
- package/plugins/kimi-codex/dist/swarm-activation.js +14 -9
- package/plugins/kimi-codex/dist/swarm-policy.js +72 -0
- package/plugins/kimi-codex/dist/swarm-recovery.js +41 -10
- package/plugins/kimi-codex/dist/swarm-tool-policy.js +146 -0
- package/plugins/kimi-codex/dist/version.js +1 -1
- package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +2 -0
- package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +2 -0
- package/plugins/kimi-dsh/dist/cli-client.js +224 -31
- package/plugins/kimi-dsh/dist/commands/recover-swarm.js +4 -0
- package/plugins/kimi-dsh/dist/commands/setup.js +5 -1
- package/plugins/kimi-dsh/dist/commands/swarm.js +131 -43
- package/plugins/kimi-dsh/dist/hooks/approval-hook.js +3 -0
- package/plugins/kimi-dsh/dist/hooks/approval-policy.js +34 -12
- package/plugins/kimi-dsh/dist/hooks/config-safety.js +5 -4
- package/plugins/kimi-dsh/dist/kimi-engine.js +5 -3
- package/plugins/kimi-dsh/dist/kimi-timeouts.js +4 -4
- package/plugins/kimi-dsh/dist/mcp/operations.js +1 -1
- package/plugins/kimi-dsh/dist/process-tree.js +150 -43
- package/plugins/kimi-dsh/dist/swarm-activation.js +14 -9
- package/plugins/kimi-dsh/dist/swarm-policy.js +72 -0
- package/plugins/kimi-dsh/dist/swarm-recovery.js +41 -10
- package/plugins/kimi-dsh/dist/swarm-tool-policy.js +146 -0
- package/plugins/kimi-dsh/dist/version.js +1 -1
- package/plugins/kimi-dsh/package.json +1 -1
|
@@ -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
|
+
}
|
|
@@ -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.
|
|
@@ -15,8 +15,9 @@ import { assertPrefixArgsSafe } from "./kimi-command.js";
|
|
|
15
15
|
import { resolveKimiHome } from "./kimi-home.js";
|
|
16
16
|
import { assertNativeV2Preflight } from "./native-v2-preflight.js";
|
|
17
17
|
import { parseVersionLine } from "./kimi-version-probe.js";
|
|
18
|
+
import { BOUNDED_SWARM_POLICY, SWARM_CHILD_TIMEOUT_MS, SWARM_POLICY_ENV, SWARM_WAVE_SIZE_ENV, usesBoundedSwarmPolicy, } from "./swarm-policy.js";
|
|
18
19
|
import { StreamJsonParser, extractSessionIdFromStderr, } from "./stream-json.js";
|
|
19
|
-
import { collectDescendantIdentities, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
|
|
20
|
+
import { collectDescendantIdentities, collectDescendantIdentitiesForRoots, revalidateProcessIdentities, waitForProcessTreeExit, } from "./process-tree.js";
|
|
20
21
|
/** Bytes of stderr retained for diagnostics on completion. Rolling buffer. */
|
|
21
22
|
const STDERR_TAIL_BYTES = 8192;
|
|
22
23
|
/** Hard cap on awaiting diagnostics log drain before resolving the result. */
|
|
@@ -29,6 +30,8 @@ const POST_KILL_QUIESCENCE_MS = 500;
|
|
|
29
30
|
const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000;
|
|
30
31
|
/** Hard bound for each batched identity revalidation pass. */
|
|
31
32
|
const IDENTITY_REVALIDATION_TIMEOUT_MS = 250;
|
|
33
|
+
/** Keep ownership evidence before a native Bash shell can exit ahead of its children. */
|
|
34
|
+
const BOUNDED_DESCENDANT_POLL_MS = 100;
|
|
32
35
|
const DESCENDANT_SNAPSHOT_TIMEOUT = Symbol("descendant-snapshot-timeout");
|
|
33
36
|
function spawnErrorDetails(error) {
|
|
34
37
|
const cause = error;
|
|
@@ -72,6 +75,7 @@ export async function runCliPrompt(opts) {
|
|
|
72
75
|
const args = buildArgs(opts);
|
|
73
76
|
assertPromptFitsCommandLine(opts.command, args);
|
|
74
77
|
const env = buildKimiCliEnvironment(opts);
|
|
78
|
+
const boundedSwarm = usesBoundedSwarmPolicy(opts.executionPlan);
|
|
75
79
|
if (opts.logPath !== undefined) {
|
|
76
80
|
await mkdir(path.dirname(opts.logPath), { recursive: true }).catch(() => {
|
|
77
81
|
// Best-effort; if mkdir fails the appendFile below will error and be
|
|
@@ -123,7 +127,8 @@ export async function runCliPrompt(opts) {
|
|
|
123
127
|
let announcedCliError;
|
|
124
128
|
let announcedSystemVersion;
|
|
125
129
|
const hookMonitor = createHookEscapeMonitor({ commandLabel: opts.commandLabel,
|
|
126
|
-
operationKind: opts.executionPlan.operationKind, trustedWorkspaceRoot: opts.trustedWorkspaceRoot, cwd: opts.cwd
|
|
130
|
+
operationKind: opts.executionPlan.operationKind, trustedWorkspaceRoot: opts.trustedWorkspaceRoot, cwd: opts.cwd,
|
|
131
|
+
swarmPolicy: env[SWARM_POLICY_ENV], swarmWaveSize: env[SWARM_WAVE_SIZE_ENV] });
|
|
127
132
|
const hookEscapes = [];
|
|
128
133
|
const noteHookEscape = (escape) => {
|
|
129
134
|
hookEscapes.push(escape);
|
|
@@ -319,10 +324,13 @@ export async function runCliPrompt(opts) {
|
|
|
319
324
|
return await new Promise(async (resolve, reject) => {
|
|
320
325
|
let aborted = false;
|
|
321
326
|
let cancellationTeardown;
|
|
327
|
+
let processCleanupUnverified = false;
|
|
322
328
|
let settlementStarted = false;
|
|
323
329
|
const settle = (kind, payload) => {
|
|
324
330
|
if (settlementStarted)
|
|
325
331
|
return;
|
|
332
|
+
if (boundedSwarm)
|
|
333
|
+
beginTeardown();
|
|
326
334
|
// Denied calls still without a result (a cancel/budget race, an abnormal
|
|
327
335
|
// exit, or a turn that ended without the denial the hook owes) are reported
|
|
328
336
|
// alongside the real outcome, never instead of it.
|
|
@@ -337,13 +345,21 @@ export async function runCliPrompt(opts) {
|
|
|
337
345
|
// expose a result/error until that one owned teardown path completes.
|
|
338
346
|
void (cancellationTeardown ?? Promise.resolve({ ok: true })).then((teardown) => {
|
|
339
347
|
if (!teardown.ok) {
|
|
348
|
+
const details = {
|
|
349
|
+
...errorDetails(),
|
|
350
|
+
...(boundedSwarm || processCleanupUnverified ? { process_cleanup_unverified: true } : {}),
|
|
351
|
+
...(boundedSwarm && kind === "resolve" ? {
|
|
352
|
+
process_exit_code: payload.exitCode,
|
|
353
|
+
process_signal: payload.signal,
|
|
354
|
+
} : {}),
|
|
355
|
+
};
|
|
340
356
|
appendLogLine({
|
|
341
357
|
event: "cancellation_teardown_error",
|
|
342
358
|
message: formatError(teardown.error),
|
|
343
359
|
});
|
|
344
|
-
reject(new RuntimeError("CLI_CANCELLATION_TEARDOWN_FAILED", `kimi cancellation teardown failed: ${formatError(teardown.error)}`, "cli-client.cancellation", teardown.error instanceof Error
|
|
345
|
-
? { cause: teardown.error, details
|
|
346
|
-
: { details
|
|
360
|
+
reject(new RuntimeError(boundedSwarm ? "CLI_PROCESS_SETTLEMENT_FAILED" : "CLI_CANCELLATION_TEARDOWN_FAILED", `kimi ${boundedSwarm ? "process settlement" : "cancellation teardown"} failed: ${formatError(teardown.error)}`, boundedSwarm ? "cli-client.settlement" : "cli-client.cancellation", teardown.error instanceof Error
|
|
361
|
+
? { cause: teardown.error, details }
|
|
362
|
+
: { details }));
|
|
347
363
|
return;
|
|
348
364
|
}
|
|
349
365
|
if (kind === "resolve")
|
|
@@ -357,16 +373,21 @@ export async function runCliPrompt(opts) {
|
|
|
357
373
|
let processExited = false;
|
|
358
374
|
child.once("exit", () => {
|
|
359
375
|
processExited = true;
|
|
376
|
+
// A descendant may still hold stdout open. Start cleanup on exit rather
|
|
377
|
+
// than waiting for close, which cannot arrive until that tail is gone.
|
|
378
|
+
if (boundedSwarm)
|
|
379
|
+
beginTeardown();
|
|
360
380
|
});
|
|
361
|
-
const
|
|
381
|
+
const captureProcessIdentities = async (collect, excludedPid, onFailure) => {
|
|
362
382
|
let snapshot;
|
|
363
383
|
try {
|
|
364
|
-
const collected = await raceWithValueTimeout((
|
|
384
|
+
const collected = await raceWithValueTimeout(collect(), DESCENDANT_SNAPSHOT_TIMEOUT_MS, DESCENDANT_SNAPSHOT_TIMEOUT);
|
|
365
385
|
if (collected === DESCENDANT_SNAPSHOT_TIMEOUT) {
|
|
366
386
|
appendLogLine({
|
|
367
387
|
event: "descendant_collection_timeout",
|
|
368
388
|
timeout_ms: DESCENDANT_SNAPSHOT_TIMEOUT_MS,
|
|
369
389
|
});
|
|
390
|
+
onFailure?.(new Error("descendant ownership snapshot timed out"));
|
|
370
391
|
return [];
|
|
371
392
|
}
|
|
372
393
|
snapshot = collected;
|
|
@@ -376,6 +397,7 @@ export async function runCliPrompt(opts) {
|
|
|
376
397
|
event: "descendant_collection_error",
|
|
377
398
|
message: formatError(err),
|
|
378
399
|
});
|
|
400
|
+
onFailure?.(err);
|
|
379
401
|
return [];
|
|
380
402
|
}
|
|
381
403
|
const identities = [];
|
|
@@ -384,7 +406,7 @@ export async function runCliPrompt(opts) {
|
|
|
384
406
|
const key = `${identity.pid}:${identity.startToken}:${identity.processGroupId}`;
|
|
385
407
|
if (Number.isInteger(identity.pid) &&
|
|
386
408
|
identity.pid > 0 &&
|
|
387
|
-
identity.pid !==
|
|
409
|
+
identity.pid !== excludedPid &&
|
|
388
410
|
Number.isInteger(identity.processGroupId) &&
|
|
389
411
|
identity.processGroupId > 0 &&
|
|
390
412
|
identity.startToken.length > 0 &&
|
|
@@ -395,6 +417,7 @@ export async function runCliPrompt(opts) {
|
|
|
395
417
|
}
|
|
396
418
|
return identities;
|
|
397
419
|
};
|
|
420
|
+
const captureDescendantIdentities = (childPid, expectedRoot, onFailure) => captureProcessIdentities(() => (opts.descendantIdentityCollector ?? collectDescendantIdentities)(childPid, expectedRoot), childPid, onFailure);
|
|
398
421
|
const trySignalPid = (pid, signal) => {
|
|
399
422
|
try {
|
|
400
423
|
process.kill(pid, signal);
|
|
@@ -437,7 +460,131 @@ export async function runCliPrompt(opts) {
|
|
|
437
460
|
trySignalPid(-processGroupId, signal);
|
|
438
461
|
}
|
|
439
462
|
};
|
|
463
|
+
const trackedIdentities = new Map();
|
|
464
|
+
const identityKey = (identity) => `${identity.pid}:${identity.startToken}`;
|
|
465
|
+
let trackerTimer;
|
|
466
|
+
let trackerPass;
|
|
467
|
+
let publishedIdentities = "";
|
|
468
|
+
let spawnRecorded = opts.onSpawn === undefined;
|
|
469
|
+
let observationError;
|
|
470
|
+
let checkpointError;
|
|
471
|
+
let lastPassComplete = false;
|
|
472
|
+
let lastPassCheckpointed = false;
|
|
473
|
+
const retainIdentities = (identities) => {
|
|
474
|
+
for (const identity of identities) {
|
|
475
|
+
// A changed PGID is not a new ownership grant. Keep the first identity
|
|
476
|
+
// so revalidation refuses to signal a process that moved groups.
|
|
477
|
+
if (!trackedIdentities.has(identityKey(identity))) {
|
|
478
|
+
trackedIdentities.set(identityKey(identity), identity);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
const refreshTrackedIdentities = () => {
|
|
483
|
+
if (trackerPass)
|
|
484
|
+
return trackerPass;
|
|
485
|
+
trackerPass = (async () => {
|
|
486
|
+
lastPassComplete = false;
|
|
487
|
+
lastPassCheckpointed = false;
|
|
488
|
+
let passError;
|
|
489
|
+
const noteFailure = (error) => { passError ??= error; };
|
|
490
|
+
const childPid = child.pid;
|
|
491
|
+
if (childPid === undefined || process.platform === "win32")
|
|
492
|
+
return;
|
|
493
|
+
const reachable = !processExited ? await captureDescendantIdentities(childPid, undefined, noteFailure) : [];
|
|
494
|
+
retainIdentities(reachable);
|
|
495
|
+
const reachableKeys = new Set(reachable.map(identityKey));
|
|
496
|
+
const validation = await revalidateProcessIdentities([...trackedIdentities.values()], {
|
|
497
|
+
identityReader, timeoutMs: IDENTITY_REVALIDATION_TIMEOUT_MS,
|
|
498
|
+
});
|
|
499
|
+
if (!validation.complete) {
|
|
500
|
+
noteFailure(new Error("descendant ownership could not be revalidated"));
|
|
501
|
+
}
|
|
502
|
+
// Once a shell exits its surviving children are no longer under the
|
|
503
|
+
// print root. Reuse their pinned identities as anchors, never bare PIDs.
|
|
504
|
+
// Dead anchors provide no discovery evidence. Incomplete validation
|
|
505
|
+
// retains earlier identities without multiplying full-table probes.
|
|
506
|
+
const orphanedAnchors = validation.complete
|
|
507
|
+
? validation.identities.filter((identity) => !reachableKeys.has(identityKey(identity)))
|
|
508
|
+
: [];
|
|
509
|
+
const additional = orphanedAnchors.length === 0 ? [] : await captureProcessIdentities(() => (opts.descendantIdentityBatchCollector ?? collectDescendantIdentitiesForRoots)(orphanedAnchors), childPid, noteFailure);
|
|
510
|
+
retainIdentities(additional);
|
|
511
|
+
if (passError === undefined) {
|
|
512
|
+
const liveKeys = new Set([
|
|
513
|
+
...validation.identities, ...(validation.groupChanged ?? []), ...additional,
|
|
514
|
+
].map(identityKey));
|
|
515
|
+
for (const key of trackedIdentities.keys()) {
|
|
516
|
+
if (!liveKeys.has(key))
|
|
517
|
+
trackedIdentities.delete(key);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
// Observation failures describe this pass. A later complete pass can
|
|
521
|
+
// recover; incomplete passes retain every earlier ownership identity.
|
|
522
|
+
observationError = passError;
|
|
523
|
+
lastPassComplete = passError === undefined;
|
|
524
|
+
const current = [...trackedIdentities.values()];
|
|
525
|
+
const signature = JSON.stringify([current.map((identity) => [identity.pid, identity.startToken, identity.processGroupId]), lastPassComplete]);
|
|
526
|
+
// Recovery stores the print root first. Capture starts immediately,
|
|
527
|
+
// but descendant publication waits for that durable root checkpoint.
|
|
528
|
+
if (spawnRecorded) {
|
|
529
|
+
if (signature === publishedIdentities && checkpointError === undefined) {
|
|
530
|
+
lastPassCheckpointed = true;
|
|
531
|
+
}
|
|
532
|
+
else {
|
|
533
|
+
try {
|
|
534
|
+
await opts.onProcessIdentities?.(current, lastPassComplete);
|
|
535
|
+
publishedIdentities = signature;
|
|
536
|
+
checkpointError = undefined;
|
|
537
|
+
lastPassCheckpointed = true;
|
|
538
|
+
}
|
|
539
|
+
catch (error) {
|
|
540
|
+
checkpointError = error;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
})().catch((error) => {
|
|
545
|
+
observationError = error;
|
|
546
|
+
lastPassComplete = false;
|
|
547
|
+
}).finally(() => {
|
|
548
|
+
trackerPass = undefined;
|
|
549
|
+
});
|
|
550
|
+
return trackerPass;
|
|
551
|
+
};
|
|
552
|
+
const waitForTrackedExit = async (timeoutMs) => {
|
|
553
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
554
|
+
while (true) {
|
|
555
|
+
await refreshTrackedIdentities();
|
|
556
|
+
if (processExited && trackedIdentities.size === 0 && lastPassComplete && lastPassCheckpointed)
|
|
557
|
+
return true;
|
|
558
|
+
if (Date.now() >= deadline)
|
|
559
|
+
return false;
|
|
560
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(BOUNDED_DESCENDANT_POLL_MS, deadline - Date.now())));
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
const teardownBoundedTree = async () => {
|
|
564
|
+
const childPid = child.pid;
|
|
565
|
+
try {
|
|
566
|
+
await opts.cancellationTeardownHook?.();
|
|
567
|
+
if (childPid === undefined)
|
|
568
|
+
return;
|
|
569
|
+
await refreshTrackedIdentities();
|
|
570
|
+
await signalCapturedTree(childPid, [...trackedIdentities.values()], "SIGTERM");
|
|
571
|
+
let quiescent = await waitForTrackedExit(escalationMs);
|
|
572
|
+
if (!quiescent && Number.isFinite(escalationMs)) {
|
|
573
|
+
await signalCapturedTree(childPid, [...trackedIdentities.values()], "SIGKILL");
|
|
574
|
+
quiescent = await waitForTrackedExit(POST_KILL_QUIESCENCE_MS);
|
|
575
|
+
}
|
|
576
|
+
if (!quiescent)
|
|
577
|
+
throw checkpointError ?? observationError ?? new Error("owned descendants did not reach verified quiescence");
|
|
578
|
+
}
|
|
579
|
+
finally {
|
|
580
|
+
if (trackerTimer)
|
|
581
|
+
clearInterval(trackerTimer);
|
|
582
|
+
await trackerPass;
|
|
583
|
+
}
|
|
584
|
+
};
|
|
440
585
|
const teardownChildTree = async () => {
|
|
586
|
+
if (boundedSwarm && process.platform !== "win32")
|
|
587
|
+
return teardownBoundedTree();
|
|
441
588
|
await opts.cancellationTeardownHook?.();
|
|
442
589
|
const childPid = child.pid;
|
|
443
590
|
if (childPid === undefined || processExited)
|
|
@@ -465,7 +612,11 @@ export async function runCliPrompt(opts) {
|
|
|
465
612
|
}
|
|
466
613
|
return;
|
|
467
614
|
}
|
|
468
|
-
|
|
615
|
+
let snapshotFailure;
|
|
616
|
+
const identities = await captureDescendantIdentities(childPid, undefined, (error) => {
|
|
617
|
+
snapshotFailure ??= { error };
|
|
618
|
+
processCleanupUnverified = true;
|
|
619
|
+
});
|
|
469
620
|
await signalCapturedTree(childPid, identities, "SIGTERM");
|
|
470
621
|
// The grace interval starts only after SIGTERM has reached every
|
|
471
622
|
// revalidated target. Slow process enumeration never consumes the grace.
|
|
@@ -487,10 +638,48 @@ export async function runCliPrompt(opts) {
|
|
|
487
638
|
});
|
|
488
639
|
}
|
|
489
640
|
}
|
|
641
|
+
// An unreadable snapshot is not evidence of an empty descendant tree.
|
|
642
|
+
// Finish the owned-root cleanup before exposing the original failure.
|
|
643
|
+
if (snapshotFailure !== undefined)
|
|
644
|
+
throw snapshotFailure.error;
|
|
645
|
+
};
|
|
646
|
+
const beginTeardown = () => {
|
|
647
|
+
// Assign the shared promise before invoking callbacks that can abort.
|
|
648
|
+
cancellationTeardown ??= Promise.resolve().then(teardownChildTree).then(() => ({ ok: true }), (error) => ({ ok: false, error }));
|
|
649
|
+
void cancellationTeardown.then((outcome) => {
|
|
650
|
+
if (outcome.ok)
|
|
651
|
+
return;
|
|
652
|
+
// Failure cannot strand the live owned root or wait forever for a
|
|
653
|
+
// descendant that still holds its pipes. Surface uncertainty instead.
|
|
654
|
+
const childPid = child.pid;
|
|
655
|
+
if (childPid !== undefined && !processExited) {
|
|
656
|
+
if (process.platform !== "win32")
|
|
657
|
+
trySignalPid(-childPid, "SIGKILL");
|
|
658
|
+
try {
|
|
659
|
+
child.kill("SIGKILL");
|
|
660
|
+
}
|
|
661
|
+
catch { /* Best effort. */ }
|
|
662
|
+
}
|
|
663
|
+
if (boundedSwarm || processCleanupUnverified) {
|
|
664
|
+
// An unverified tail may still hold inherited pipes. Release our
|
|
665
|
+
// handles so reporting failure does not wait on that tail.
|
|
666
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) {
|
|
667
|
+
try {
|
|
668
|
+
stream.destroy();
|
|
669
|
+
}
|
|
670
|
+
catch { /* Preserve the settlement error. */ }
|
|
671
|
+
}
|
|
672
|
+
try {
|
|
673
|
+
child.unref();
|
|
674
|
+
}
|
|
675
|
+
catch { /* Preserve the settlement error. */ }
|
|
676
|
+
}
|
|
677
|
+
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
|
+
});
|
|
490
679
|
};
|
|
491
680
|
const stopForPolicyFailure = (error) => {
|
|
492
681
|
engineMismatchDetected = true; // Stops all further consumer output.
|
|
493
|
-
|
|
682
|
+
beginTeardown();
|
|
494
683
|
settle("reject", error);
|
|
495
684
|
};
|
|
496
685
|
let engineMismatchError;
|
|
@@ -520,26 +709,13 @@ export async function runCliPrompt(opts) {
|
|
|
520
709
|
if (aborted)
|
|
521
710
|
return;
|
|
522
711
|
aborted = true;
|
|
523
|
-
|
|
524
|
-
void cancellationTeardown.then((outcome) => {
|
|
525
|
-
if (outcome.ok)
|
|
526
|
-
return;
|
|
527
|
-
// A bug in teardown must neither strand the outer promise nor leave the
|
|
528
|
-
// owned root running. The controlled child anchors this emergency kill.
|
|
529
|
-
const childPid = child.pid;
|
|
530
|
-
if (childPid !== undefined && !processExited) {
|
|
531
|
-
if (process.platform !== "win32")
|
|
532
|
-
trySignalPid(-childPid, "SIGKILL");
|
|
533
|
-
try {
|
|
534
|
-
child.kill("SIGKILL");
|
|
535
|
-
}
|
|
536
|
-
catch {
|
|
537
|
-
// Best-effort; settlement still surfaces the teardown failure.
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
settle("reject", new RuntimeError("CLI_CANCELLATION_TEARDOWN_FAILED", "kimi cancellation teardown failed", "cli-client.cancellation"));
|
|
541
|
-
});
|
|
712
|
+
beginTeardown();
|
|
542
713
|
};
|
|
714
|
+
if (boundedSwarm && process.platform !== "win32" && child.pid !== undefined) {
|
|
715
|
+
void refreshTrackedIdentities();
|
|
716
|
+
trackerTimer = setInterval(() => { void refreshTrackedIdentities(); }, BOUNDED_DESCENDANT_POLL_MS);
|
|
717
|
+
trackerTimer.unref();
|
|
718
|
+
}
|
|
543
719
|
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
544
720
|
// Abort may occur during any pre-spawn await, and addEventListener does not
|
|
545
721
|
// replay an already-aborted signal. Re-check after attaching the listener so
|
|
@@ -550,10 +726,14 @@ export async function runCliPrompt(opts) {
|
|
|
550
726
|
if (child.pid !== undefined && opts.onSpawn) {
|
|
551
727
|
try {
|
|
552
728
|
await opts.onSpawn(child.pid);
|
|
729
|
+
spawnRecorded = true;
|
|
553
730
|
}
|
|
554
731
|
catch (error) {
|
|
732
|
+
const spawnError = new RuntimeError("CLI_SPAWN_CALLBACK_FAILED", `Failed to record the spawned kimi process: ${formatError(error)}`, "cli-client.spawn", error instanceof Error ? { cause: error, details: errorDetails() } : { details: errorDetails() });
|
|
733
|
+
if (boundedSwarm)
|
|
734
|
+
checkpointError = spawnError;
|
|
555
735
|
onAbort();
|
|
556
|
-
settle("reject",
|
|
736
|
+
settle("reject", spawnError);
|
|
557
737
|
return;
|
|
558
738
|
}
|
|
559
739
|
}
|
|
@@ -786,7 +966,7 @@ function buildArgs(opts) {
|
|
|
786
966
|
? opts.env.KIMI_PLUGIN_CC_SMOKE_V2_CANDIDATE
|
|
787
967
|
: undefined;
|
|
788
968
|
if (opts.resumeSessionId === undefined &&
|
|
789
|
-
["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
|
|
969
|
+
["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(opts.executionPlan.kimiVersion ?? smokeCandidate ?? "")) {
|
|
790
970
|
args.push("--environment", "local");
|
|
791
971
|
}
|
|
792
972
|
if (opts.resumeSessionId !== undefined) {
|
|
@@ -808,6 +988,19 @@ function buildArgs(opts) {
|
|
|
808
988
|
}
|
|
809
989
|
export function buildKimiCliEnvironment(opts) {
|
|
810
990
|
const env = { ...opts.env };
|
|
991
|
+
// A previous host/job cannot opt another operation into a swarm policy or
|
|
992
|
+
// choose its bound. Only this immutable execution plan grants the policy.
|
|
993
|
+
delete env[SWARM_POLICY_ENV];
|
|
994
|
+
delete env[SWARM_WAVE_SIZE_ENV];
|
|
995
|
+
if (usesBoundedSwarmPolicy(opts.executionPlan)) {
|
|
996
|
+
if (opts.commandLabel !== opts.executionPlan.operationKind ||
|
|
997
|
+
!Number.isSafeInteger(opts.swarmMaxConcurrency) || (opts.swarmMaxConcurrency ?? 0) < 1) {
|
|
998
|
+
throw new RuntimeError("SWARM_POLICY_INVALID", "Bounded swarm requires its exact operation label and a positive safe-integer concurrency limit.", "cli-client.environment");
|
|
999
|
+
}
|
|
1000
|
+
env[SWARM_POLICY_ENV] = BOUNDED_SWARM_POLICY;
|
|
1001
|
+
env[SWARM_WAVE_SIZE_ENV] = String(opts.swarmMaxConcurrency);
|
|
1002
|
+
env.KIMI_CODE_SWARM_TIMEOUT_MS = String(SWARM_CHILD_TIMEOUT_MS);
|
|
1003
|
+
}
|
|
811
1004
|
if (opts.thinkingEffort !== undefined)
|
|
812
1005
|
env.KIMI_MODEL_THINKING_EFFORT = opts.thinkingEffort;
|
|
813
1006
|
// Ambient workspace trust starts project MCP stdio servers outside PreToolUse.
|
|
@@ -106,6 +106,10 @@ export async function runRecoverSwarm(argv, context) {
|
|
|
106
106
|
const recoveryExecutionCwd = await realpath(record.cwd);
|
|
107
107
|
await deactivateSwarmSession({ cwd: recoveryExecutionCwd, env: context.env, command: current.command,
|
|
108
108
|
prefixArgs: current.prefixArgs, executionPlan: current, commandLabel: expectedRoot ? "swarm-write" : "swarm",
|
|
109
|
+
// Recovery only deactivates the stopped session; it never starts a model
|
|
110
|
+
// turn. Use the strictest admission policy rather than reconstructing a
|
|
111
|
+
// prior wave limit that recovery records do not need to retain.
|
|
112
|
+
swarmMaxConcurrency: 1,
|
|
109
113
|
trustedWorkspaceRoot: expectedRoot ?? undefined, ...record.session, signal,
|
|
110
114
|
onRecoveryEvent: (event) => recordRecoveryEvent(store, record, event) });
|
|
111
115
|
}
|
|
@@ -977,8 +977,12 @@ async function collectKimiVersionWarnings(env, warnings) {
|
|
|
977
977
|
warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION, NATIVE_V2_ANY_OPERATION_VERSIONS));
|
|
978
978
|
return;
|
|
979
979
|
}
|
|
980
|
+
if (probe.version === "2.6.2") {
|
|
981
|
+
warnings.push("NOTE: kimi-code 2.6.2 is certified for all operations. Swarm uses bounded waves with concurrency 2 or more, and one direct worker at concurrency 1. The finite job budget stops the whole run.");
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
980
984
|
if (NATIVE_V2_NON_SWARM_VERSIONS.includes(probe.version)) {
|
|
981
|
-
warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn
|
|
985
|
+
warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn on this exact release. Select exact kimi-code 2.6.2 for this plugin's certified bounded waves and single-worker path.`);
|
|
982
986
|
}
|
|
983
987
|
}
|
|
984
988
|
/**
|