kimi-plugin-cc 2.5.9 → 2.6.3
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 +130 -41
- 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 +7 -4
- 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 +13 -8
- package/dist/swarm-policy.js +73 -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 +42 -17
- package/docs/swarm-recovery.md +4 -2
- package/docs/upstream-2.6.2-certification.md +93 -3
- package/docs/upstream-2.6.3-certification.md +88 -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 +130 -41
- 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 +7 -4
- 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 +13 -8
- package/plugins/kimi-codex/dist/swarm-policy.js +73 -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 +130 -41
- 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 +7 -4
- 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 +13 -8
- package/plugins/kimi-dsh/dist/swarm-policy.js +73 -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
|
@@ -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
|
|
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
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
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
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
374
|
-
const processGroupId = Number
|
|
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.
|
|
380
|
-
!Number.
|
|
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,9 +9,11 @@ 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
|
-
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"];
|
|
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", "2.6.3"];
|
|
15
17
|
const READY_TIMEOUT_MS = 10_000;
|
|
16
18
|
const REST_TIMEOUT_MS = 5_000;
|
|
17
19
|
// Exact 2.4.0 can take longer than 5s to drain session/workspace lifecycle work.
|
|
@@ -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
|
}
|
|
@@ -338,7 +343,7 @@ async function resolveProfileModel(web, options, failureCode) {
|
|
|
338
343
|
}
|
|
339
344
|
async function createSession(web, options, expectedVersion, failureCode) {
|
|
340
345
|
const request = { metadata: { cwd: options.cwd } };
|
|
341
|
-
if (["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(expectedVersion)) {
|
|
346
|
+
if (["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion)) {
|
|
342
347
|
request.environment_id = "local";
|
|
343
348
|
request.environment_cwd = options.cwd;
|
|
344
349
|
}
|
|
@@ -349,7 +354,7 @@ async function createSession(web, options, expectedVersion, failureCode) {
|
|
|
349
354
|
return { sessionId: data.id, workspaceId: data.workspace_id };
|
|
350
355
|
}
|
|
351
356
|
async function verifyLocalEnvironment(web, identity, expectedCwd, expectedVersion, signal, failureCode) {
|
|
352
|
-
if (!["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(expectedVersion))
|
|
357
|
+
if (!["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion))
|
|
353
358
|
return;
|
|
354
359
|
const data = await restData(web, "GET", `/api/v1/sessions/${encodeURIComponent(identity.sessionId)}/environment`, undefined, signal, failureCode);
|
|
355
360
|
if (!isRecord(data)) {
|
|
@@ -369,10 +374,10 @@ async function postSwarmProfile(web, identity, active, model, signal, failureCod
|
|
|
369
374
|
await restData(web, "POST", `/api/v1/sessions/${encodeURIComponent(identity.sessionId)}/profile`, { agent_config: agentConfig }, signal, failureCode);
|
|
370
375
|
}
|
|
371
376
|
async function verifySwarmStatus(web, identity, active, model, expectedVersion, signal, failureCode) {
|
|
372
|
-
const data = ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(expectedVersion)
|
|
377
|
+
const data = ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion)
|
|
373
378
|
? await readWebSocketAgentState(web, identity.sessionId, expectedVersion, signal, failureCode)
|
|
374
379
|
: await restData(web, "GET", `/api/v1/sessions/${encodeURIComponent(identity.sessionId)}/status`, undefined, signal, failureCode);
|
|
375
|
-
const source = ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(expectedVersion) ? "agent state" : "/status";
|
|
380
|
+
const source = ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion) ? "agent state" : "/status";
|
|
376
381
|
if (!isRecord(data)) {
|
|
377
382
|
throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} returned an invalid payload.`);
|
|
378
383
|
}
|
|
@@ -382,10 +387,10 @@ async function verifySwarmStatus(web, identity, active, model, expectedVersion,
|
|
|
382
387
|
if (data.plan_mode !== false) {
|
|
383
388
|
throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} did not confirm plan mode is off.`);
|
|
384
389
|
}
|
|
385
|
-
if (["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(expectedVersion) && data.tower_mode !== false) {
|
|
390
|
+
if (["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion) && data.tower_mode !== false) {
|
|
386
391
|
throw failure(failureCode, "swarm-activation.status", "Kimi web agent state did not confirm tower mode is off.");
|
|
387
392
|
}
|
|
388
|
-
const permission = ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2"].includes(expectedVersion) ? data.permission_mode : data.permission;
|
|
393
|
+
const permission = ["2.5.0", "2.5.1", "2.5.2", "2.5.3", "2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion) ? data.permission_mode : data.permission;
|
|
389
394
|
if (permission !== "auto") {
|
|
390
395
|
throw failure(failureCode, "swarm-activation.status", `Kimi web ${source} did not confirm auto permission mode.`);
|
|
391
396
|
}
|
|
@@ -401,7 +406,7 @@ async function readWebSocketAgentState(web, sessionId, expectedVersion, signal,
|
|
|
401
406
|
return await new Promise((resolve, reject) => {
|
|
402
407
|
let socket;
|
|
403
408
|
const bearerProtocol = `kimi-code.bearer.${web.token}`;
|
|
404
|
-
const legacyControl = !["2.6.0", "2.6.2"].includes(expectedVersion);
|
|
409
|
+
const legacyControl = !["2.6.0", "2.6.2", "2.6.3"].includes(expectedVersion);
|
|
405
410
|
const helloId = `swarm-activation-hello-${randomUUID()}`;
|
|
406
411
|
const subscribeId = `swarm-activation-subscribe-${randomUUID()}`;
|
|
407
412
|
try {
|
|
@@ -0,0 +1,73 @@
|
|
|
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" &&
|
|
10
|
+
(plan.kimiVersion === "2.6.2" || plan.kimiVersion === "2.6.3") &&
|
|
11
|
+
(plan.operationKind === "swarm" || plan.operationKind === "swarm-write");
|
|
12
|
+
}
|
|
13
|
+
function plainObject(value) {
|
|
14
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) &&
|
|
15
|
+
(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
16
|
+
}
|
|
17
|
+
function nonemptyString(value) {
|
|
18
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
19
|
+
}
|
|
20
|
+
const SWARM_INPUT_KEYS = new Set([
|
|
21
|
+
"description", "subagent_type", "prompt_template", "items", "fork", "resume_agent_ids", "model",
|
|
22
|
+
]);
|
|
23
|
+
/** Stateless admission; repeated host hooks cannot consume or refund slots. */
|
|
24
|
+
export function evaluateSwarmWaveInput(input, policy, waveSize) {
|
|
25
|
+
const deny = (reason) => ({
|
|
26
|
+
decision: "deny",
|
|
27
|
+
reason: `kimi-plugin-cc safety hook: AgentSwarm denied: ${reason}`,
|
|
28
|
+
});
|
|
29
|
+
if (policy !== BOUNDED_SWARM_POLICY)
|
|
30
|
+
return deny("missing or unrecognized swarm policy.");
|
|
31
|
+
const width = typeof waveSize === "string" && /^[1-9][0-9]*$/.test(waveSize)
|
|
32
|
+
? Number(waveSize) : NaN;
|
|
33
|
+
if (!Number.isSafeInteger(width) || width < 1)
|
|
34
|
+
return deny("missing or invalid trusted wave size.");
|
|
35
|
+
if (width === 1) {
|
|
36
|
+
return deny("concurrency 1 uses one worker directly; complete the task yourself without delegation.");
|
|
37
|
+
}
|
|
38
|
+
if (!plainObject(input))
|
|
39
|
+
return deny("arguments must be an object.");
|
|
40
|
+
if (Reflect.ownKeys(input).some((key) => typeof key !== "string" || !SWARM_INPUT_KEYS.has(key))) {
|
|
41
|
+
return deny("unrecognized arguments.");
|
|
42
|
+
}
|
|
43
|
+
if (!nonemptyString(input.description))
|
|
44
|
+
return deny("description must be a nonempty string.");
|
|
45
|
+
for (const key of ["subagent_type", "prompt_template"]) {
|
|
46
|
+
if (input[key] !== undefined && !nonemptyString(input[key]))
|
|
47
|
+
return deny(`${key} must be a nonempty string.`);
|
|
48
|
+
}
|
|
49
|
+
if (input.model !== undefined && typeof input.model !== "string")
|
|
50
|
+
return deny("model must be a string.");
|
|
51
|
+
if (input.fork !== undefined && input.fork !== false)
|
|
52
|
+
return deny("forked subagents are not supported.");
|
|
53
|
+
if (input.items !== undefined && (!Array.isArray(input.items) || !input.items.every(nonemptyString))) {
|
|
54
|
+
return deny("items must be an array of nonempty strings.");
|
|
55
|
+
}
|
|
56
|
+
if (input.resume_agent_ids !== undefined && (!plainObject(input.resume_agent_ids) ||
|
|
57
|
+
Reflect.ownKeys(input.resume_agent_ids).some((key) => typeof key !== "string" ||
|
|
58
|
+
!nonemptyString(key) || !nonemptyString(input.resume_agent_ids[key])))) {
|
|
59
|
+
return deny("resume_agent_ids must map nonempty agent IDs to nonempty prompts.");
|
|
60
|
+
}
|
|
61
|
+
const fresh = Array.isArray(input.items) ? input.items.length : 0;
|
|
62
|
+
const resumed = plainObject(input.resume_agent_ids) ? Object.keys(input.resume_agent_ids).length : 0;
|
|
63
|
+
const total = fresh + resumed;
|
|
64
|
+
if (total === 0)
|
|
65
|
+
return deny("a wave must contain at least one new or resumed entry.");
|
|
66
|
+
if (total > width) {
|
|
67
|
+
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.`);
|
|
68
|
+
}
|
|
69
|
+
if (fresh === 1 && resumed === 0) {
|
|
70
|
+
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.");
|
|
71
|
+
}
|
|
72
|
+
return { decision: "allow" };
|
|
73
|
+
}
|
|
@@ -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
|
|
54
|
-
*
|
|
55
|
-
*
|
|
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 =
|
|
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()) {
|