kimi-plugin-cc 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +3 -14
- package/README.md +428 -572
- package/assets/logo.svg +6 -0
- package/cordis.patch.yml +18 -0
- package/dist/background-spawn.js +4 -2
- package/dist/cli-client.js +105 -66
- package/dist/commands/ask.js +27 -12
- package/dist/commands/cancel.js +4 -13
- package/dist/commands/cli-helpers.js +1 -1
- package/dist/commands/pursue.js +3 -2
- package/dist/commands/registry.js +7 -26
- package/dist/commands/repair-sessions.js +7 -4
- package/dist/commands/replay.js +4 -3
- package/dist/commands/rescue.js +17 -5
- package/dist/commands/review.js +18 -5
- package/dist/commands/setup.js +277 -262
- package/dist/commands/swarm.js +20 -7
- package/dist/companion.js +142 -18
- package/dist/help.js +11 -7
- package/dist/hook-escape.js +7 -16
- package/dist/hooks/approval-hook.js +1762 -124
- package/dist/hooks/approval-policy.js +15 -10
- package/dist/hooks/config-safety.js +15 -24
- package/dist/hooks/hook-timing.js +1 -1
- package/dist/hooks/install-paths.js +179 -107
- package/dist/hooks/install.js +44 -166
- package/dist/hooks/managed-block.js +44 -95
- package/dist/job-store.js +117 -49
- package/dist/jobs.js +53 -1
- package/dist/kimi-engine.js +68 -92
- package/dist/kimi-errors.js +1 -1
- package/dist/kimi-journal.js +3 -2
- package/dist/kimi-releases.js +28 -49
- package/dist/kimi-timeouts.js +1 -15
- package/dist/kimi-version-probe.js +24 -72
- package/dist/logging.js +12 -7
- package/dist/mcp/binding.js +13 -4
- package/dist/mcp/job-control.js +386 -89
- package/dist/mcp/launcher.js +1 -1
- package/dist/mcp/operations.js +387 -193
- package/dist/mcp/protocol.js +116 -27
- package/dist/mcp/skills.js +130 -0
- package/dist/mcp/stdio.js +15 -2
- package/dist/native-v2-preflight.js +127 -35
- package/dist/parsing.js +45 -11
- package/dist/paths.js +20 -10
- package/dist/plugin-data.js +28 -83
- package/dist/read-scope.js +2 -2
- package/dist/render.js +13 -38
- package/dist/session-references.js +216 -0
- package/dist/session-title.js +1 -1
- package/dist/surface-routing.js +92 -5
- package/dist/swarm-activation.js +26 -137
- package/dist/version.js +1 -1
- package/docs/migration.md +45 -227
- package/docs/models.md +24 -66
- package/docs/safety.md +195 -400
- package/docs/session-visibility.md +24 -14
- package/docs/swarm-recovery.md +26 -20
- package/dsh/index.json +54 -0
- package/mcp_config.json +10 -0
- package/package.json +23 -82
- package/plugin.json +19 -0
- package/plugins/kimi-codex/.codex-plugin/plugin.json +7 -7
- package/plugins/kimi-codex/.mcp.json +2 -3
- package/plugins/kimi-codex/dist/background-spawn.js +4 -2
- package/plugins/kimi-codex/dist/cli-client.js +105 -66
- package/plugins/kimi-codex/dist/commands/ask.js +27 -12
- package/plugins/kimi-codex/dist/commands/cancel.js +4 -13
- package/plugins/kimi-codex/dist/commands/cli-helpers.js +1 -1
- package/plugins/kimi-codex/dist/commands/pursue.js +3 -2
- package/plugins/kimi-codex/dist/commands/registry.js +7 -26
- package/plugins/kimi-codex/dist/commands/repair-sessions.js +7 -4
- package/plugins/kimi-codex/dist/commands/replay.js +4 -3
- package/plugins/kimi-codex/dist/commands/rescue.js +17 -5
- package/plugins/kimi-codex/dist/commands/review.js +18 -5
- package/plugins/kimi-codex/dist/commands/setup.js +277 -262
- package/plugins/kimi-codex/dist/commands/swarm.js +20 -7
- package/plugins/kimi-codex/dist/companion.js +142 -18
- package/plugins/kimi-codex/dist/help.js +11 -7
- package/plugins/kimi-codex/dist/hook-escape.js +7 -16
- package/plugins/kimi-codex/dist/hooks/approval-hook.js +1762 -124
- package/plugins/kimi-codex/dist/hooks/approval-policy.js +15 -10
- package/plugins/kimi-codex/dist/hooks/config-safety.js +15 -24
- package/plugins/kimi-codex/dist/hooks/hook-timing.js +1 -1
- package/plugins/kimi-codex/dist/hooks/install-paths.js +179 -107
- package/plugins/kimi-codex/dist/hooks/install.js +44 -166
- package/plugins/kimi-codex/dist/hooks/managed-block.js +44 -95
- package/plugins/kimi-codex/dist/job-store.js +117 -49
- package/plugins/kimi-codex/dist/jobs.js +53 -1
- package/plugins/kimi-codex/dist/kimi-engine.js +68 -92
- package/plugins/kimi-codex/dist/kimi-errors.js +1 -1
- package/plugins/kimi-codex/dist/kimi-journal.js +3 -2
- package/plugins/kimi-codex/dist/kimi-releases.js +28 -49
- package/plugins/kimi-codex/dist/kimi-timeouts.js +1 -15
- package/plugins/kimi-codex/dist/kimi-version-probe.js +24 -72
- package/plugins/kimi-codex/dist/logging.js +12 -7
- package/plugins/kimi-codex/dist/mcp/binding.js +13 -4
- package/plugins/kimi-codex/dist/mcp/job-control.js +386 -89
- package/plugins/kimi-codex/dist/mcp/launcher.js +1 -1
- package/plugins/kimi-codex/dist/mcp/operations.js +387 -193
- package/plugins/kimi-codex/dist/mcp/protocol.js +116 -27
- package/plugins/kimi-codex/dist/mcp/skills.js +130 -0
- package/plugins/kimi-codex/dist/mcp/stdio.js +15 -2
- package/plugins/kimi-codex/dist/native-v2-preflight.js +127 -35
- package/plugins/kimi-codex/dist/parsing.js +45 -11
- package/plugins/kimi-codex/dist/paths.js +20 -10
- package/plugins/kimi-codex/dist/plugin-data.js +28 -83
- package/plugins/kimi-codex/dist/read-scope.js +2 -2
- package/plugins/kimi-codex/dist/render.js +13 -38
- package/plugins/kimi-codex/dist/session-references.js +216 -0
- package/plugins/kimi-codex/dist/session-title.js +1 -1
- package/plugins/kimi-codex/dist/surface-routing.js +92 -5
- package/plugins/kimi-codex/dist/swarm-activation.js +26 -137
- package/plugins/kimi-codex/dist/version.js +1 -1
- package/plugins/kimi-codex/scripts/companion.sh +4 -15
- package/plugins/kimi-codex/skills/kimi/SKILL.md +77 -0
- package/plugins/kimi-codex/skills/kimi/agents/openai.yaml +6 -0
- package/scripts/companion.sh +4 -15
- package/skills/kimi/SKILL.md +77 -0
- package/skills/kimi/agents/openai.yaml +6 -0
- package/CHANGELOG.md +0 -1402
- package/agents/kimi-pursue.md +0 -93
- package/agents/kimi-review.md +0 -86
- package/agents/kimi-swarm.md +0 -88
- package/agents/kimi-task.md +0 -93
- package/commands/README.md +0 -14
- package/commands/cancel.md +0 -17
- package/commands/pursue.md +0 -41
- package/commands/replay.md +0 -13
- package/commands/result.md +0 -13
- package/commands/review.md +0 -40
- package/commands/setup.md +0 -25
- package/commands/status.md +0 -13
- package/commands/swarm.md +0 -45
- package/commands/task.md +0 -40
- package/dist/commands/review-gate.js +0 -391
- package/dist/config.js +0 -22
- package/dist/dsh/companion.js +0 -177
- package/dist/dsh/index.js +0 -167
- package/dist/hooks/review-gate-stop.js +0 -19
- package/dist/schemas/review-gate-output.js +0 -41
- package/docs/registry-releases.md +0 -228
- package/docs/upstream-2.4.1-certification.md +0 -54
- package/docs/upstream-2.5.0-certification.md +0 -52
- package/docs/upstream-2.5.1-certification.md +0 -47
- package/docs/upstream-2.5.2-certification.md +0 -40
- package/docs/upstream-2.5.3-certification.md +0 -73
- package/docs/upstream-2.6.0-certification.md +0 -65
- package/docs/upstream-2.6.2-certification.md +0 -144
- package/docs/upstream-2.6.3-certification.md +0 -100
- package/docs/upstream-2.7.2-certification.md +0 -113
- package/docs/upstream-2.7.3-certification.md +0 -95
- package/docs/windows-validation.md +0 -39
- package/hooks/README.md +0 -9
- package/hooks/hooks.json +0 -16
- package/plugins/kimi-codex/dist/commands/review-gate.js +0 -391
- package/plugins/kimi-codex/dist/config.js +0 -22
- package/plugins/kimi-codex/dist/dsh/companion.js +0 -177
- package/plugins/kimi-codex/dist/dsh/index.js +0 -167
- package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +0 -19
- package/plugins/kimi-codex/dist/schemas/review-gate-output.js +0 -41
- package/plugins/kimi-codex/scripts/review-gate-hook.sh +0 -32
- package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +0 -25
- package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +0 -32
- package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +0 -25
- package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-result/SKILL.md +0 -25
- package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-review/SKILL.md +0 -35
- package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +0 -35
- package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-status/SKILL.md +0 -25
- package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +0 -37
- package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +0 -6
- package/plugins/kimi-codex/skills/kimi-task/SKILL.md +0 -37
- package/plugins/kimi-codex/skills/kimi-task/agents/openai.yaml +0 -6
- package/plugins/kimi-dsh/LICENSE +0 -201
- package/plugins/kimi-dsh/README.md +0 -84
- package/plugins/kimi-dsh/cordis.patch.yml +0 -45
- package/plugins/kimi-dsh/dist/background-spawn.js +0 -209
- package/plugins/kimi-dsh/dist/cli-cancellation.js +0 -43
- package/plugins/kimi-dsh/dist/cli-client.js +0 -1097
- package/plugins/kimi-dsh/dist/commands/ask.js +0 -269
- package/plugins/kimi-dsh/dist/commands/cancel.js +0 -177
- package/plugins/kimi-dsh/dist/commands/cli-helpers.js +0 -302
- package/plugins/kimi-dsh/dist/commands/models.js +0 -139
- package/plugins/kimi-dsh/dist/commands/pursue.js +0 -293
- package/plugins/kimi-dsh/dist/commands/recover-swarm.js +0 -140
- package/plugins/kimi-dsh/dist/commands/registry.js +0 -74
- package/plugins/kimi-dsh/dist/commands/repair-sessions.js +0 -266
- package/plugins/kimi-dsh/dist/commands/replay.js +0 -124
- package/plugins/kimi-dsh/dist/commands/rescue.js +0 -277
- package/plugins/kimi-dsh/dist/commands/result.js +0 -72
- package/plugins/kimi-dsh/dist/commands/review-gate.js +0 -391
- package/plugins/kimi-dsh/dist/commands/review.js +0 -217
- package/plugins/kimi-dsh/dist/commands/setup.js +0 -1465
- package/plugins/kimi-dsh/dist/commands/status.js +0 -27
- package/plugins/kimi-dsh/dist/commands/swarm.js +0 -823
- package/plugins/kimi-dsh/dist/commands/worker.js +0 -24
- package/plugins/kimi-dsh/dist/companion.js +0 -99
- package/plugins/kimi-dsh/dist/config.js +0 -22
- package/plugins/kimi-dsh/dist/dsh/companion.js +0 -177
- package/plugins/kimi-dsh/dist/dsh/index.js +0 -167
- package/plugins/kimi-dsh/dist/errors.js +0 -40
- package/plugins/kimi-dsh/dist/git.js +0 -216
- package/plugins/kimi-dsh/dist/help.js +0 -43
- package/plugins/kimi-dsh/dist/hook-escape.js +0 -71
- package/plugins/kimi-dsh/dist/hooks/approval-hook.js +0 -145
- package/plugins/kimi-dsh/dist/hooks/approval-policy.js +0 -295
- package/plugins/kimi-dsh/dist/hooks/config-safety.js +0 -641
- package/plugins/kimi-dsh/dist/hooks/hook-timing.js +0 -48
- package/plugins/kimi-dsh/dist/hooks/install-paths.js +0 -428
- package/plugins/kimi-dsh/dist/hooks/install.js +0 -405
- package/plugins/kimi-dsh/dist/hooks/managed-block.js +0 -729
- package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +0 -19
- package/plugins/kimi-dsh/dist/job-id.js +0 -12
- package/plugins/kimi-dsh/dist/job-store.js +0 -631
- package/plugins/kimi-dsh/dist/jobs.js +0 -212
- package/plugins/kimi-dsh/dist/kimi-command.js +0 -144
- package/plugins/kimi-dsh/dist/kimi-engine.js +0 -770
- package/plugins/kimi-dsh/dist/kimi-errors.js +0 -205
- package/plugins/kimi-dsh/dist/kimi-home.js +0 -15
- package/plugins/kimi-dsh/dist/kimi-journal.js +0 -41
- package/plugins/kimi-dsh/dist/kimi-releases.js +0 -144
- package/plugins/kimi-dsh/dist/kimi-timeouts.js +0 -52
- package/plugins/kimi-dsh/dist/kimi-version-probe.js +0 -198
- package/plugins/kimi-dsh/dist/logging.js +0 -22
- package/plugins/kimi-dsh/dist/mcp/binding.js +0 -58
- package/plugins/kimi-dsh/dist/mcp/job-control.js +0 -343
- package/plugins/kimi-dsh/dist/mcp/launcher.js +0 -263
- package/plugins/kimi-dsh/dist/mcp/operations.js +0 -333
- package/plugins/kimi-dsh/dist/mcp/protocol.js +0 -277
- package/plugins/kimi-dsh/dist/mcp/server.js +0 -8
- package/plugins/kimi-dsh/dist/mcp/stdio.js +0 -79
- package/plugins/kimi-dsh/dist/mcp/supervised-child.js +0 -15
- package/plugins/kimi-dsh/dist/mcp/tool-result.js +0 -7
- package/plugins/kimi-dsh/dist/mcp/workspace.js +0 -34
- package/plugins/kimi-dsh/dist/model-command.js +0 -34
- package/plugins/kimi-dsh/dist/native-v2-preflight.js +0 -596
- package/plugins/kimi-dsh/dist/package.json +0 -1
- package/plugins/kimi-dsh/dist/parsing.js +0 -554
- package/plugins/kimi-dsh/dist/paths.js +0 -35
- package/plugins/kimi-dsh/dist/plugin-data.js +0 -98
- package/plugins/kimi-dsh/dist/process-tree.js +0 -597
- package/plugins/kimi-dsh/dist/prompt-size.js +0 -18
- package/plugins/kimi-dsh/dist/read-scope.js +0 -435
- package/plugins/kimi-dsh/dist/render.js +0 -214
- package/plugins/kimi-dsh/dist/rescue-approval.js +0 -1242
- package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +0 -41
- package/plugins/kimi-dsh/dist/session-recovery.js +0 -202
- package/plugins/kimi-dsh/dist/session-title.js +0 -313
- package/plugins/kimi-dsh/dist/stream-json.js +0 -344
- package/plugins/kimi-dsh/dist/surface-routing.js +0 -21
- package/plugins/kimi-dsh/dist/swarm-activation.js +0 -1194
- package/plugins/kimi-dsh/dist/swarm-policy.js +0 -74
- package/plugins/kimi-dsh/dist/swarm-recovery.js +0 -166
- package/plugins/kimi-dsh/dist/swarm-tool-policy.js +0 -146
- package/plugins/kimi-dsh/dist/types.js +0 -1
- package/plugins/kimi-dsh/dist/util.js +0 -28
- package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +0 -24
- package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +0 -1
- package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +0 -229
- package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +0 -24
- package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +0 -156
- package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +0 -67
- package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +0 -293
- package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +0 -164
- package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +0 -151
- package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +0 -156
- package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +0 -57
- package/plugins/kimi-dsh/dist/version.js +0 -7
- package/plugins/kimi-dsh/package.json +0 -78
- package/plugins/kimi-dsh/scripts/companion.sh +0 -37
- package/plugins/kimi-dsh/scripts/review-gate-hook.sh +0 -32
- package/scripts/review-gate-hook.sh +0 -32
|
@@ -1,823 +0,0 @@
|
|
|
1
|
-
import { resolveKimiHome } from "../kimi-home.js";
|
|
2
|
-
import { probeProcessIdentity } from "../process-tree.js";
|
|
3
|
-
import { recordRecoveryEvent, finishRecoveryRecord } from "../swarm-recovery.js";
|
|
4
|
-
import { allocateJobId } from "../job-id.js";
|
|
5
|
-
import { mkdir, realpath, writeFile } from "node:fs/promises";
|
|
6
|
-
import path from "node:path";
|
|
7
|
-
import { createCliCancellationHandlers } from "../cli-cancellation.js";
|
|
8
|
-
import { ResponseTimeoutError, runCliPromptWithBudget } from "../cli-client.js";
|
|
9
|
-
import { deactivateSwarmSession, preactivateSwarmSession, requiresSwarmPreactivation, } from "../swarm-activation.js";
|
|
10
|
-
import { executionPlanFromPersisted, observedExecutionFields, persistedExecutionPlanFields, prepareKimiExecutionPlan, } from "../kimi-engine.js";
|
|
11
|
-
import { RuntimeError } from "../errors.js";
|
|
12
|
-
import { captureWorktreePatch, createEphemeralWorktree, hasBornHead, isWorkingTreeDirty, removeWorktree, resolveRepoIdentity, } from "../git.js";
|
|
13
|
-
import { digestPrompt, markJobCancelled, markJobFailed, sweepStaleJobs } from "../jobs.js";
|
|
14
|
-
import { JobStore } from "../job-store.js";
|
|
15
|
-
import { classifyManagedCommandFailure } from "../kimi-errors.js";
|
|
16
|
-
import { KIMI_SWARM_DEFAULT_BUDGET_MS } from "../kimi-timeouts.js";
|
|
17
|
-
import { writeInvocationLogHeader } from "../logging.js";
|
|
18
|
-
import { ensurePluginPaths, resolvePluginPaths } from "../paths.js";
|
|
19
|
-
import { parseSwarmArgs } from "../parsing.js";
|
|
20
|
-
import { parseJobReadScope, resolveReadScope, serializeReadScope } from "../read-scope.js";
|
|
21
|
-
import { readArtifact, renderManagedJobOutput, writeArtifact } from "../render.js";
|
|
22
|
-
import { hookGateRefusal, verifyHookInstalled } from "../hooks/install.js";
|
|
23
|
-
import { assertCliResultSuccess, reassembleProseFromRecords, warnIfSessionIdMissing, warnHookEscapes } from "./cli-helpers.js";
|
|
24
|
-
import { buildKimiSessionTitle, syncKimiSessionTitle } from "../session-title.js";
|
|
25
|
-
import { usesBoundedSwarmPolicy } from "../swarm-policy.js";
|
|
26
|
-
// /kimi:swarm — parallel fan-out, read-only by default and runtime-foreground-only.
|
|
27
|
-
// A finite wall-clock budget bounds the whole run. --cap is a SOFT total-count
|
|
28
|
-
// prompt hint. A bounded-swarm release (kimi-releases.ts) bounds admitted waves and prevents native
|
|
29
|
-
// child timeouts from returning a continuing coordinator before children stop.
|
|
30
|
-
// Concurrency 1 uses a direct worker without native fan-out. Older versions keep
|
|
31
|
-
// their normal-launch setting and inherited recovery limitation. Read/write
|
|
32
|
-
// modes reuse review/rescue lineage, and the
|
|
33
|
-
// mandatory PreToolUse hook enforces read-only policy or trusted-worktree write
|
|
34
|
-
// confinement on the coordinator and every subagent. Write mode requires
|
|
35
|
-
// kimi-code 0.18.0+. A web-preactivation release activates a same-job session
|
|
36
|
-
// through a bounded loopback web lifecycle, then resumes it through the normal
|
|
37
|
-
// print path; bounded-swarm parallel waves, web-json-ready authenticated waves
|
|
38
|
-
// and candidate-only 2.6.0 use that lifecycle too. The per-operation certification
|
|
39
|
-
// table controls whether each exact version is reachable in production.
|
|
40
|
-
const SWARM_SUMMARY_MAX = 120;
|
|
41
|
-
const SWARM_AGENT_PROFILE = "<swarm>";
|
|
42
|
-
const SWARM_WRITE_AGENT_PROFILE = "<swarm-write>";
|
|
43
|
-
/**
|
|
44
|
-
* Default concurrency setting when the user passes no `--max-concurrency`.
|
|
45
|
-
* A bounded-swarm release also enforces this as the admitted wave size. The plugin exports
|
|
46
|
-
* KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY; older read-only swarms ignore it and
|
|
47
|
-
* retain only the wall-clock hard bound. Rate-limit recovery can exceed it on
|
|
48
|
-
* older reviewed sources; their setting is not an unconditional peak guarantee.
|
|
49
|
-
*/
|
|
50
|
-
export const SWARM_DEFAULT_MAX_CONCURRENCY = 4;
|
|
51
|
-
/**
|
|
52
|
-
* Resolve the requested normal-launch concurrency: an explicit
|
|
53
|
-
* `--max-concurrency` wins; otherwise use SWARM_DEFAULT_MAX_CONCURRENCY so the
|
|
54
|
-
* setting is never unset. Pure + exported for unit testing (the parser leaves
|
|
55
|
-
* the value undefined; swarm.ts owns the default, mirroring `budgetMs`).
|
|
56
|
-
*/
|
|
57
|
-
export function resolveSwarmMaxConcurrency(requested) {
|
|
58
|
-
return requested ?? SWARM_DEFAULT_MAX_CONCURRENCY;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Default concurrency for WRITE mode — 1 vs read's 4. A bounded-swarm release
|
|
62
|
-
* runs one direct worker; older versions serialize normal child launches but
|
|
63
|
-
* retain the rate-limit recovery overrun. Disjoint-target partitioning remains
|
|
64
|
-
* prompt-only when parallel workers are explicitly requested.
|
|
65
|
-
* Override with an explicit `--max-concurrency N`.
|
|
66
|
-
*/
|
|
67
|
-
export const SWARM_WRITE_DEFAULT_MAX_CONCURRENCY = 1;
|
|
68
|
-
/** Resolve the write-mode normal-launch concurrency: explicit wins, else default 1. */
|
|
69
|
-
export function resolveSwarmWriteMaxConcurrency(requested) {
|
|
70
|
-
return requested ?? SWARM_WRITE_DEFAULT_MAX_CONCURRENCY;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Build the swarm coordination prompt. States the READ-ONLY review GOAL and the
|
|
74
|
-
* desired report shape, then trusts the model to fan the work out with its own
|
|
75
|
-
* subagent capability — we deliberately do NOT prescribe the AgentSwarm tool call,
|
|
76
|
-
* subagent_type, or prompt_template/items mechanics. Over-prescribing those made
|
|
77
|
-
* the kimi-code 0.26.0 (k3) coordinator emit a non-sole-tool-call response that
|
|
78
|
-
* failed to launch (0 records, hang to budget); a goal-only prompt lets it launch.
|
|
79
|
-
* Read-only is NOT enforced by this prose — the PreToolUse hook (swarm label) at
|
|
80
|
-
* policy index 0 denies every write/edit/shell for the coordinator AND every
|
|
81
|
-
* subagent, so slimming this text does not move the safety boundary. The optional
|
|
82
|
-
* `cap` is a SOFT total subagent-count hint. `waveSize` is supplied only for
|
|
83
|
-
* the exact bounded policy: 1 runs directly; larger values guide the model to
|
|
84
|
-
* satisfy the separately enforced admission rule. Older versions keep their
|
|
85
|
-
* existing prompt and normal-launch concurrency semantics.
|
|
86
|
-
*/
|
|
87
|
-
export function buildSwarmPrompt(objective, cap, waveSize) {
|
|
88
|
-
const trimmed = objective.trim();
|
|
89
|
-
if (waveSize === 1) {
|
|
90
|
-
return [
|
|
91
|
-
"Review the following read-only as the single worker: inspect and report; do not modify anything.",
|
|
92
|
-
"",
|
|
93
|
-
`Objective: ${trimmed}`,
|
|
94
|
-
"",
|
|
95
|
-
"Complete every target yourself, one at a time. Do not delegate: Agent and AgentSwarm are denied.",
|
|
96
|
-
"Use the allowed read-only tools, primarily Read/Grep/Glob and ReadMediaFile where relevant;",
|
|
97
|
-
"shell/Bash and every write/edit tool are denied.",
|
|
98
|
-
"",
|
|
99
|
-
"Return a single markdown report: deduplicate findings, preserve coverage across every target,",
|
|
100
|
-
"and explicitly mention targets with no findings. Include a short verdict line, a brief summary,",
|
|
101
|
-
"then findings as `file:line — issue — severity`. No JSON wrapper or outer code fences.",
|
|
102
|
-
].join("\n");
|
|
103
|
-
}
|
|
104
|
-
const capClause = cap !== undefined
|
|
105
|
-
? `Use at most ${cap} subagents in total across the whole run (soft cap); split or group targets to stay within it.`
|
|
106
|
-
: undefined;
|
|
107
|
-
return [
|
|
108
|
-
"Review the following read-only: inspect and report; do not modify anything.",
|
|
109
|
-
"",
|
|
110
|
-
`Objective: ${trimmed}`,
|
|
111
|
-
"",
|
|
112
|
-
"Use the allowed read-only tools, primarily Read/Grep/Glob and ReadMediaFile where relevant;",
|
|
113
|
-
"shell/Bash and every write/edit tool are denied. Launch the parallel fan-out as your FIRST action;",
|
|
114
|
-
"do NOT run preliminary shell commands to size or list files first (the subagents inspect the",
|
|
115
|
-
"workspace directly with the allowed read-only tools).",
|
|
116
|
-
"Fan the work out across the relevant targets in parallel using your own subagent capability,",
|
|
117
|
-
"as you judge best — split or group the work however fits the objective.",
|
|
118
|
-
...boundedWaveInstructions(waveSize),
|
|
119
|
-
...(capClause ? [capClause] : []),
|
|
120
|
-
"",
|
|
121
|
-
"Consolidate into a single markdown report: deduplicate findings, preserve coverage across",
|
|
122
|
-
"every target, and explicitly mention targets with no findings rather than dropping them.",
|
|
123
|
-
"Include a short verdict line, a brief summary, then findings as `file:line — issue — severity`.",
|
|
124
|
-
"Return plain markdown — no JSON wrapper, no outer code fences.",
|
|
125
|
-
].join("\n");
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Build the WRITE-mode coordination prompt. Unlike the read-only prompt, this
|
|
129
|
-
* sets subagent_type="coder" (write-capable) and instructs DISJOINT target
|
|
130
|
-
* assignments with NO git and NO nested swarm. The coordinator and all
|
|
131
|
-
* subagents run in an ephemeral throwaway worktree; the PreToolUse hook
|
|
132
|
-
* (swarm-write label) confines writes there and the plugin captures a patch the
|
|
133
|
-
* user reviews. The `cap` is the same SOFT total-count hint as read mode.
|
|
134
|
-
*/
|
|
135
|
-
export function buildSwarmWritePrompt(objective, cap, waveSize) {
|
|
136
|
-
const trimmed = objective.trim();
|
|
137
|
-
if (waveSize === 1) {
|
|
138
|
-
return [
|
|
139
|
-
"Perform the following CODE-EDITING task as the single worker.",
|
|
140
|
-
"",
|
|
141
|
-
`Objective: ${trimmed}`,
|
|
142
|
-
"",
|
|
143
|
-
"You are running inside a throwaway git worktree dedicated to this task.",
|
|
144
|
-
"Complete every target yourself, one at a time. Do not delegate: Agent and AgentSwarm are denied.",
|
|
145
|
-
"Your changes will be captured as a patch for the human to review and apply.",
|
|
146
|
-
"",
|
|
147
|
-
"Safety rules enforced by the PreToolUse hook:",
|
|
148
|
-
"- Writes are confined to this worktree; an out-of-worktree write is denied.",
|
|
149
|
-
"- Git mutation is denied: do not add, commit, checkout, or change repository state.",
|
|
150
|
-
"",
|
|
151
|
-
"Report what changed and why, with a short verdict and a section for each target listing edited files.",
|
|
152
|
-
"Do not paste full diffs; the patch is captured separately. Return plain markdown,",
|
|
153
|
-
"without a JSON wrapper or outer code fences.",
|
|
154
|
-
].join("\n");
|
|
155
|
-
}
|
|
156
|
-
const capClause = cap !== undefined
|
|
157
|
-
? `Launch at most ${cap} subagents in total across the whole run (soft cap — split or group targets to stay within it).`
|
|
158
|
-
: waveSize === undefined
|
|
159
|
-
? "Launch one subagent per distinct target; group related targets if there are many."
|
|
160
|
-
: "Assign disjoint targets or target groups to subagents; group related targets when needed.";
|
|
161
|
-
return [
|
|
162
|
-
"Coordinate a parallel CODE-EDITING task using the AgentSwarm tool.",
|
|
163
|
-
"",
|
|
164
|
-
`Objective: ${trimmed}`,
|
|
165
|
-
"",
|
|
166
|
-
"You are running inside a throwaway git worktree dedicated to this task — edit freely;",
|
|
167
|
-
"your changes will be captured as a patch for the human to review and apply. Use the",
|
|
168
|
-
'AgentSwarm tool to fan the work out across subagents. Set subagent_type to "coder" (the',
|
|
169
|
-
...(waveSize === undefined
|
|
170
|
-
? [
|
|
171
|
-
"write-capable profile). Give each subagent ONE target via prompt_template + items: a single",
|
|
172
|
-
"file or module per subagent.",
|
|
173
|
-
]
|
|
174
|
-
: [
|
|
175
|
-
"write-capable profile). Give each subagent a DISJOINT target or target group via prompt_template + items.",
|
|
176
|
-
"Each file must belong to only one subagent's assignment.",
|
|
177
|
-
]),
|
|
178
|
-
...boundedWaveInstructions(waveSize),
|
|
179
|
-
capClause,
|
|
180
|
-
"",
|
|
181
|
-
"Safety rules enforced by the PreToolUse hook (violations are denied):",
|
|
182
|
-
"- Writes are confined to this worktree; an out-of-worktree write is denied.",
|
|
183
|
-
"- Do NOT run any git command that mutates state (no add/commit/checkout/etc.) — git mutation",
|
|
184
|
-
" is denied. The human owns all git operations.",
|
|
185
|
-
"",
|
|
186
|
-
"Coordination rules (prompt-only; the hook does NOT enforce them):",
|
|
187
|
-
"- Keep every assigned target DISJOINT: no overlap between subagents (two subagents editing",
|
|
188
|
-
" the same file will corrupt the result).",
|
|
189
|
-
"- Subagents must NOT call AgentSwarm (no nested fan-out). One flat generation only.",
|
|
190
|
-
"- Report exactly what you changed and why.",
|
|
191
|
-
"",
|
|
192
|
-
"After the subagents return, consolidate into a single markdown report: a short verdict line,",
|
|
193
|
-
"a summary of what changed across all targets, then one section per target listing the edited",
|
|
194
|
-
"files. Do NOT paste full diffs (the patch is captured separately). Return plain markdown —",
|
|
195
|
-
"no JSON wrapper, no outer code fences.",
|
|
196
|
-
].join("\n");
|
|
197
|
-
}
|
|
198
|
-
function boundedWaveInstructions(waveSize) {
|
|
199
|
-
return waveSize === undefined ? [] : [
|
|
200
|
-
`Each AgentSwarm call must contain at most ${waveSize} entries in total, counting both new items and resumed agents.`,
|
|
201
|
-
"A wave with no resumed agents must contain at least two new entries; a single resumed agent is allowed.",
|
|
202
|
-
"For odd target counts, group multiple targets into disjoint worker entries so the final wave is not a lone fresh entry.",
|
|
203
|
-
"Split larger work into sequential waves and wait for each wave to finish before starting the next.",
|
|
204
|
-
"Oversized calls and forks are denied; if a call is denied, group or split its targets into smaller waves.",
|
|
205
|
-
];
|
|
206
|
-
}
|
|
207
|
-
export async function runSwarm(argv, context) {
|
|
208
|
-
const parsed = parseSwarmArgs(argv);
|
|
209
|
-
const objective = parsed.objective?.trim();
|
|
210
|
-
if (!objective) {
|
|
211
|
-
throw new RuntimeError("INVALID_ARGS", "/kimi:swarm requires an objective. Usage: /kimi:swarm [--write] [--budget 30m] [--cap N] [--max-concurrency N] [-m model] <objective>", "swarm.parse");
|
|
212
|
-
}
|
|
213
|
-
if (parsed.write)
|
|
214
|
-
return runWriteSwarm(parsed, objective, context);
|
|
215
|
-
const readScope = parsed.readRoots === undefined && parsed.network === undefined ? undefined
|
|
216
|
-
: await resolveReadScope(parsed.readRoots, parsed.network, "swarm.parse");
|
|
217
|
-
return runReadSwarm(parsed, objective, context, readScope);
|
|
218
|
-
}
|
|
219
|
-
/** Read-only swarm (default). */
|
|
220
|
-
async function runReadSwarm(parsed, objective, context, readScope) {
|
|
221
|
-
const paths = resolvePluginPaths(context.env);
|
|
222
|
-
await ensurePluginPaths(paths);
|
|
223
|
-
const repoIdentity = await resolveRepoIdentity(context.cwd);
|
|
224
|
-
const store = new JobStore(paths);
|
|
225
|
-
try {
|
|
226
|
-
await sweepStaleJobs(store, paths);
|
|
227
|
-
const executionPlan = await prepareKimiExecutionPlan({
|
|
228
|
-
operationKind: "swarm",
|
|
229
|
-
cwd: context.cwd,
|
|
230
|
-
env: context.env,
|
|
231
|
-
stderr: context.stderr,
|
|
232
|
-
});
|
|
233
|
-
const maxConcurrency = resolveSwarmMaxConcurrency(parsed.maxConcurrency);
|
|
234
|
-
const prompt = buildSwarmPrompt(objective, parsed.cap, usesBoundedSwarmPolicy(executionPlan) ? maxConcurrency : undefined);
|
|
235
|
-
const jobId = allocateJobId(context);
|
|
236
|
-
const logPath = path.join(paths.logsDir, `swarm-${jobId}.jsonl`);
|
|
237
|
-
// Reuse the read-only review lineage; the hook label ("swarm") is what
|
|
238
|
-
// actually drives the allowlist.
|
|
239
|
-
const job = await createSwarmJob(store, paths, {
|
|
240
|
-
jobId, repoId: repoIdentity.repoId, commandType: "review", label: "swarm",
|
|
241
|
-
agentProfile: SWARM_AGENT_PROFILE, failureSummary: "Swarm failed.",
|
|
242
|
-
parsed, objective, prompt, executionPlan, logPath, cwd: context.cwd, readScope,
|
|
243
|
-
});
|
|
244
|
-
const completed = await executeSwarmJob(job.job_id, prompt, objective, job.budget_ms, maxConcurrency, context, undefined, await realpath(context.cwd));
|
|
245
|
-
if (!completed.final_output_path) {
|
|
246
|
-
throw new RuntimeError("SWARM_RESULT_MISSING", "Swarm finished without a rendered result.", "swarm.result");
|
|
247
|
-
}
|
|
248
|
-
return readArtifact(completed.final_output_path);
|
|
249
|
-
}
|
|
250
|
-
finally {
|
|
251
|
-
store.close();
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* WRITE-capable swarm (--write, v1.4). Spawns the coordinator in an ephemeral
|
|
256
|
-
* throwaway worktree off HEAD; `coder` subagents edit there; writes are confined
|
|
257
|
-
* by the swarm-write hook label; the result is captured as a patch the main
|
|
258
|
-
* thread reviews + applies. The worktree is removed after successful patch
|
|
259
|
-
* capture; capture failure retains it and reports its path for recovery.
|
|
260
|
-
* Reuses the rescue (write-capable) job lineage.
|
|
261
|
-
*/
|
|
262
|
-
async function runWriteSwarm(parsed, objective, context) {
|
|
263
|
-
const paths = resolvePluginPaths(context.env);
|
|
264
|
-
await ensurePluginPaths(paths);
|
|
265
|
-
const repoIdentity = await resolveRepoIdentity(context.cwd);
|
|
266
|
-
const store = new JobStore(paths);
|
|
267
|
-
try {
|
|
268
|
-
await sweepStaleJobs(store, paths);
|
|
269
|
-
// Write mode needs a real git repo and a born HEAD before any job state is
|
|
270
|
-
// created. Its execution plan is certified below from the actual throwaway
|
|
271
|
-
// worktree cwd, not from the user's tree.
|
|
272
|
-
assertWriteSwarmPreconditions(repoIdentity);
|
|
273
|
-
if (!(await hasBornHead(context.cwd))) {
|
|
274
|
-
throw new RuntimeError("WRITE_SWARM_NO_HEAD", "/kimi:swarm --write needs a git repository with at least one commit (HEAD). This repo has an unborn HEAD; make an initial commit first.", "swarm.precondition");
|
|
275
|
-
}
|
|
276
|
-
// Abandoned trees are recovery evidence, never age-based garbage.
|
|
277
|
-
if (await isWorkingTreeDirty(context.cwd)) {
|
|
278
|
-
context.stderr.write("[kimi-plugin-cc] /kimi:swarm --write bases its worktree on HEAD — your uncommitted changes are NOT visible to the swarm. Commit or stash them first if the swarm needs them.\n");
|
|
279
|
-
}
|
|
280
|
-
const maxConcurrency = resolveSwarmWriteMaxConcurrency(parsed.maxConcurrency);
|
|
281
|
-
const jobId = allocateJobId(context);
|
|
282
|
-
const logPath = path.join(paths.logsDir, `swarm-write-${jobId}.jsonl`);
|
|
283
|
-
// Namespace worktrees per repo so the cross-repo sweep below only ever
|
|
284
|
-
// touches THIS repo's subtree (the worktreesDir is a single global dir shared
|
|
285
|
-
// across every repo the user runs --write in).
|
|
286
|
-
const worktreePath = path.join(paths.worktreesDir, repoIdentity.repoId, `swarm-write-${jobId}`);
|
|
287
|
-
await mkdir(path.dirname(worktreePath), { recursive: true });
|
|
288
|
-
try {
|
|
289
|
-
await createEphemeralWorktree(repoIdentity.repoRoot, "HEAD", worktreePath);
|
|
290
|
-
}
|
|
291
|
-
catch (error) {
|
|
292
|
-
throw (error instanceof RuntimeError
|
|
293
|
-
? error
|
|
294
|
-
: new RuntimeError("GIT_WORKTREE_ADD_FAILED", String(error), "swarm.worktree"));
|
|
295
|
-
}
|
|
296
|
-
let preserveWorktree = false;
|
|
297
|
-
try {
|
|
298
|
-
// Prefix args can contain relative wrapper/script paths. Probe from the
|
|
299
|
-
// exact spawn cwd so the certified command tuple and its effective target
|
|
300
|
-
// cannot diverge merely because --write runs in a separate worktree.
|
|
301
|
-
const executionPlan = await prepareKimiExecutionPlan({
|
|
302
|
-
operationKind: "swarm-write",
|
|
303
|
-
cwd: worktreePath,
|
|
304
|
-
env: context.env,
|
|
305
|
-
stderr: context.stderr,
|
|
306
|
-
});
|
|
307
|
-
const prompt = buildSwarmWritePrompt(objective, parsed.cap, usesBoundedSwarmPolicy(executionPlan) ? maxConcurrency : undefined);
|
|
308
|
-
// Reuse the rescue (write-capable) lineage, like pursue; the hook label
|
|
309
|
-
// ("swarm-write") drives the allowlist. cwd stays the USER's real cwd for
|
|
310
|
-
// lineage — the kimi spawn cwd is the worktree (threaded via the writeMode
|
|
311
|
-
// arg to executeSwarmJob).
|
|
312
|
-
const job = await createSwarmJob(store, paths, {
|
|
313
|
-
jobId, repoId: repoIdentity.repoId, commandType: "rescue", label: "swarm-write",
|
|
314
|
-
agentProfile: SWARM_WRITE_AGENT_PROFILE, failureSummary: "Swarm (write) failed.",
|
|
315
|
-
parsed, objective, prompt, executionPlan, logPath, cwd: context.cwd,
|
|
316
|
-
});
|
|
317
|
-
const completed = await executeSwarmJob(job.job_id, prompt, objective, job.budget_ms, maxConcurrency, context, {
|
|
318
|
-
spawnCwd: worktreePath,
|
|
319
|
-
workspaceRoot: worktreePath,
|
|
320
|
-
onPatchCaptureFailure: () => {
|
|
321
|
-
preserveWorktree = true;
|
|
322
|
-
},
|
|
323
|
-
}, await realpath(worktreePath));
|
|
324
|
-
if (preserveWorktree && completed.error) {
|
|
325
|
-
throw new RuntimeError(completed.error.code, completed.error.message, completed.error.stage, {
|
|
326
|
-
details: completed.error.details,
|
|
327
|
-
});
|
|
328
|
-
}
|
|
329
|
-
if (!completed.final_output_path) {
|
|
330
|
-
throw new RuntimeError("SWARM_RESULT_MISSING", "Swarm (write) finished without a rendered result.", "swarm.result");
|
|
331
|
-
}
|
|
332
|
-
return readArtifact(completed.final_output_path);
|
|
333
|
-
}
|
|
334
|
-
finally {
|
|
335
|
-
if (preserveWorktree) {
|
|
336
|
-
context.stderr.write(`[kimi-plugin-cc] swarm-write patch capture or session cleanup failed; worktree retained at ${worktreePath}.\n`);
|
|
337
|
-
}
|
|
338
|
-
else {
|
|
339
|
-
await removeWorktree(repoIdentity.repoRoot, worktreePath);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
finally {
|
|
344
|
-
store.close();
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Create the running job row and write its invocation log header. A header
|
|
349
|
-
* failure marks the job failed and rethrows.
|
|
350
|
-
*/
|
|
351
|
-
async function createSwarmJob(store, paths, spec) {
|
|
352
|
-
const { parsed } = spec;
|
|
353
|
-
const job = store.createJob({
|
|
354
|
-
job_id: spec.jobId,
|
|
355
|
-
repo_id: spec.repoId,
|
|
356
|
-
command_type: spec.commandType,
|
|
357
|
-
cwd: spec.cwd,
|
|
358
|
-
model: parsed.model ?? null,
|
|
359
|
-
thinking: null,
|
|
360
|
-
thinking_effort: parsed.thinkingEffort ?? null,
|
|
361
|
-
read_scope: serializeReadScope(spec.readScope),
|
|
362
|
-
background: false,
|
|
363
|
-
budget_ms: parsed.budgetMs ?? KIMI_SWARM_DEFAULT_BUDGET_MS,
|
|
364
|
-
budget_source: parsed.budgetMs !== undefined ? "explicit" : "default",
|
|
365
|
-
pid: process.pid,
|
|
366
|
-
kimi_pid: null,
|
|
367
|
-
status: "running",
|
|
368
|
-
kimi_session_id: null,
|
|
369
|
-
...persistedExecutionPlanFields(spec.executionPlan),
|
|
370
|
-
agent_profile: spec.agentProfile,
|
|
371
|
-
prompt_digest: digestPrompt(spec.prompt),
|
|
372
|
-
summary: `[${spec.label}] ${shorten(spec.objective, SWARM_SUMMARY_MAX)}`,
|
|
373
|
-
phase: "starting",
|
|
374
|
-
final_output_path: null,
|
|
375
|
-
stream_log_path: spec.logPath,
|
|
376
|
-
error: null,
|
|
377
|
-
});
|
|
378
|
-
try {
|
|
379
|
-
await writeInvocationLogHeader(spec.logPath, {
|
|
380
|
-
commandType: spec.label,
|
|
381
|
-
kimiSessionId: "(pending)",
|
|
382
|
-
cwd: spec.cwd,
|
|
383
|
-
});
|
|
384
|
-
}
|
|
385
|
-
catch (error) {
|
|
386
|
-
const classified = new RuntimeError("SWARM_LOG_HEADER_FAILED", `Failed to write ${spec.label} invocation log header: ${error.message ?? String(error)}`, "swarm.log-header", error instanceof Error ? { cause: error } : undefined);
|
|
387
|
-
await markJobFailed(store, paths, job, classified, spec.failureSummary, { phase: "failed" });
|
|
388
|
-
throw classified;
|
|
389
|
-
}
|
|
390
|
-
return job;
|
|
391
|
-
}
|
|
392
|
-
/** Refuse --write outside a git repo (git worktree add has nothing to fork). */
|
|
393
|
-
function assertWriteSwarmPreconditions(repoIdentity) {
|
|
394
|
-
if (!repoIdentity.isGitRepo) {
|
|
395
|
-
throw new RuntimeError("WRITE_SWARM_NOT_A_REPO", "/kimi:swarm --write requires a git repository (it works in a throwaway worktree off HEAD). The current directory is not inside a git repo.", "swarm.precondition");
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
/**
|
|
399
|
-
* Capture the worktree change set as a `.patch` artifact (write mode). Returns
|
|
400
|
-
* the artifact path + size, or null on capture failure. Called on EVERY terminal
|
|
401
|
-
* path so partial work survives a cancel/budget-expiry.
|
|
402
|
-
*/
|
|
403
|
-
async function capturePatchArtifact(paths, jobId, worktreePath, stderr, onFailure) {
|
|
404
|
-
try {
|
|
405
|
-
const patch = await captureWorktreePatch(worktreePath);
|
|
406
|
-
const patchPath = path.join(paths.artifactsDir, `swarm-write-${jobId}.patch`);
|
|
407
|
-
await writeFile(patchPath, patch, "utf8");
|
|
408
|
-
return { path: patchPath, bytes: Buffer.byteLength(patch, "utf8"), empty: patch.trim().length === 0 };
|
|
409
|
-
}
|
|
410
|
-
catch (error) {
|
|
411
|
-
onFailure?.();
|
|
412
|
-
stderr.write(`[kimi-plugin-cc] swarm-write patch capture failed for job ${jobId}: ${error.message ?? String(error)}\n`);
|
|
413
|
-
return null;
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
/** Render the patch-handoff header prepended to a write-swarm report. */
|
|
417
|
-
function renderWriteSwarmHeader(captured) {
|
|
418
|
-
if (captured.empty) {
|
|
419
|
-
return "**Patch:** the swarm made NO changes (empty patch).";
|
|
420
|
-
}
|
|
421
|
-
return [
|
|
422
|
-
`**Patch written to:** \`${captured.path}\` (${captured.bytes} bytes).`,
|
|
423
|
-
`Review it, then apply from the repo root with: \`git apply --3way ${captured.path}\` ` +
|
|
424
|
-
"(the worktree was based on HEAD, so `--3way` reconciles against your current tree; " +
|
|
425
|
-
"plain `git apply` works only if your tree hasn't moved since).",
|
|
426
|
-
"The plugin did NOT apply or commit anything — you own the merge.",
|
|
427
|
-
].join("\n");
|
|
428
|
-
}
|
|
429
|
-
async function executeSwarmJob(jobId, prompt, objective, budgetMs, maxConcurrency, context,
|
|
430
|
-
/**
|
|
431
|
-
* Write mode (v1.4): when set, the kimi spawn cwd is the throwaway worktree
|
|
432
|
-
* (`spawnCwd`), the hook label is "swarm-write", and `workspaceRoot` (the same
|
|
433
|
-
* worktree) is exported as the trusted allowlist root + used to capture the
|
|
434
|
-
* patch. Undefined ⇒ read-only swarm (label "swarm", spawn cwd = job.cwd).
|
|
435
|
-
* Real command paths supply the canonical execution cwd for activation/resume,
|
|
436
|
-
* trusted-root checks, read-mode preflight, and the print spawn. Virtual test
|
|
437
|
-
* doubles may omit the canonical path and retain their original spawn spelling.
|
|
438
|
-
*/
|
|
439
|
-
writeMode, executionCwd) {
|
|
440
|
-
const paths = resolvePluginPaths(context.env);
|
|
441
|
-
await ensurePluginPaths(paths);
|
|
442
|
-
const store = new JobStore(paths);
|
|
443
|
-
const job = store.getJob(jobId);
|
|
444
|
-
if (!job) {
|
|
445
|
-
store.close();
|
|
446
|
-
throw new RuntimeError("JOB_NOT_FOUND", `Swarm job ${jobId} was not found.`, "swarm.worker");
|
|
447
|
-
}
|
|
448
|
-
// Both modes require the PreToolUse hook, including a direct single worker:
|
|
449
|
-
// read mode enforces read-only policy; write mode confines writes to its
|
|
450
|
-
// worktree. Fail closed before spawning.
|
|
451
|
-
if (context.env.KIMI_PLUGIN_CC_SKIP_HOOK_CHECK !== "1") {
|
|
452
|
-
const installStatus = await verifyHookInstalled(context.env);
|
|
453
|
-
if (!installStatus.installed) {
|
|
454
|
-
const classified = hookGateRefusal("swarm", installStatus, context.env, context.stderr);
|
|
455
|
-
try {
|
|
456
|
-
return await markJobFailed(store, paths, job, classified, "Swarm failed.", { phase: "failed" });
|
|
457
|
-
}
|
|
458
|
-
finally {
|
|
459
|
-
store.close();
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
const handlers = createCliCancellationHandlers();
|
|
464
|
-
const budgetDeadline = Date.now() + budgetMs;
|
|
465
|
-
let activationOptions;
|
|
466
|
-
let preactivated;
|
|
467
|
-
let deactivationRequired = false;
|
|
468
|
-
let cleanupAttempted = false;
|
|
469
|
-
let cleanupFailure;
|
|
470
|
-
let finalText;
|
|
471
|
-
let recovery;
|
|
472
|
-
const commandLabel = writeMode ? "swarm-write" : "swarm";
|
|
473
|
-
const recoveryCleanupTimeoutMs = 2_000;
|
|
474
|
-
const cleanupSignal = (timeoutMs) => AbortSignal.any([
|
|
475
|
-
handlers.signal,
|
|
476
|
-
AbortSignal.timeout(Math.max(1, timeoutMs)),
|
|
477
|
-
]);
|
|
478
|
-
const attemptDeactivation = async (identity, fallbackStage, timeoutMs = Math.max(1, budgetDeadline - Date.now())) => {
|
|
479
|
-
cleanupAttempted = true;
|
|
480
|
-
try {
|
|
481
|
-
await deactivateSwarmSession({
|
|
482
|
-
...activationOptions,
|
|
483
|
-
...identity,
|
|
484
|
-
signal: cleanupSignal(timeoutMs),
|
|
485
|
-
});
|
|
486
|
-
deactivationRequired = false;
|
|
487
|
-
return undefined;
|
|
488
|
-
}
|
|
489
|
-
catch (error) {
|
|
490
|
-
return error instanceof RuntimeError
|
|
491
|
-
? error
|
|
492
|
-
: new RuntimeError("SWARM_SESSION_CLEANUP_FAILED", "Swarm session cleanup failed without a safe diagnostic payload.", fallbackStage);
|
|
493
|
-
}
|
|
494
|
-
};
|
|
495
|
-
try {
|
|
496
|
-
const executionPlan = executionPlanFromPersisted(job);
|
|
497
|
-
const boundedSwarm = usesBoundedSwarmPolicy(executionPlan);
|
|
498
|
-
const singleWorker = boundedSwarm && maxConcurrency === 1;
|
|
499
|
-
const preactivationVersion = requiresSwarmPreactivation(executionPlan.kimiVersion);
|
|
500
|
-
const needsPreactivation = !singleWorker && preactivationVersion;
|
|
501
|
-
// A direct worker still needs durable print ownership and patch recovery.
|
|
502
|
-
// Its record has no activated session and never requires web cleanup.
|
|
503
|
-
if (preactivationVersion) {
|
|
504
|
-
const owner = await probeProcessIdentity(process.pid);
|
|
505
|
-
recovery = { schema: 1, jobId: job.job_id, ownerPid: process.pid, owner: owner.identity ?? null,
|
|
506
|
-
kimiHome: resolveKimiHome(context.env, writeMode?.spawnCwd ?? job.cwd),
|
|
507
|
-
cwd: writeMode?.spawnCwd ?? job.cwd, workspaceRoot: writeMode?.workspaceRoot ?? null,
|
|
508
|
-
launches: [], session: null, sessionDirty: false, complete: false, patchPath: null };
|
|
509
|
-
store.saveSwarmRecovery(job.job_id, recovery);
|
|
510
|
-
}
|
|
511
|
-
// Shared by the web lifecycle and the print spawn; prefixArgs stay per call.
|
|
512
|
-
const spawnOptions = {
|
|
513
|
-
cwd: executionCwd ?? writeMode?.spawnCwd ?? job.cwd,
|
|
514
|
-
env: context.env,
|
|
515
|
-
command: executionPlan.command,
|
|
516
|
-
executionPlan,
|
|
517
|
-
commandLabel,
|
|
518
|
-
model: job.model ?? undefined,
|
|
519
|
-
thinkingEffort: job.thinking_effort ?? undefined,
|
|
520
|
-
// Read-only swarm only: write mode rejects scope flags at parse time.
|
|
521
|
-
readScope: writeMode ? undefined : parseJobReadScope(job.read_scope),
|
|
522
|
-
swarmMaxConcurrency: maxConcurrency,
|
|
523
|
-
trustedWorkspaceRoot: executionCwd ?? writeMode?.workspaceRoot,
|
|
524
|
-
};
|
|
525
|
-
activationOptions = {
|
|
526
|
-
...spawnOptions,
|
|
527
|
-
prefixArgs: executionPlan.prefixArgs,
|
|
528
|
-
expectedVersion: executionPlan.kimiVersion ?? undefined,
|
|
529
|
-
onRecoveryEvent: recovery ? (event) => recordRecoveryEvent(store, recovery, event) : undefined,
|
|
530
|
-
};
|
|
531
|
-
if (needsPreactivation) {
|
|
532
|
-
store.updateRunningJob(job.job_id, { phase: "turn-running" });
|
|
533
|
-
const activationController = new AbortController();
|
|
534
|
-
const onParentAbort = () => activationController.abort();
|
|
535
|
-
let activationTimedOut = false;
|
|
536
|
-
handlers.signal.addEventListener("abort", onParentAbort, { once: true });
|
|
537
|
-
if (handlers.signal.aborted)
|
|
538
|
-
onParentAbort();
|
|
539
|
-
const activationTimer = setTimeout(() => {
|
|
540
|
-
activationTimedOut = true;
|
|
541
|
-
activationController.abort();
|
|
542
|
-
}, Math.max(1, budgetDeadline - Date.now()));
|
|
543
|
-
activationTimer.unref();
|
|
544
|
-
try {
|
|
545
|
-
preactivated = await preactivateSwarmSession({
|
|
546
|
-
...activationOptions,
|
|
547
|
-
signal: activationController.signal,
|
|
548
|
-
});
|
|
549
|
-
deactivationRequired = true;
|
|
550
|
-
store.updateRunningJob(job.job_id, {
|
|
551
|
-
kimi_session_id: preactivated.sessionId,
|
|
552
|
-
kimi_session_id_source: "preactivated",
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
catch (error) {
|
|
556
|
-
const activationDidTimeOut = activationTimedOut;
|
|
557
|
-
clearTimeout(activationTimer);
|
|
558
|
-
handlers.signal.removeEventListener("abort", onParentAbort);
|
|
559
|
-
const details = error instanceof RuntimeError ? error.details : {};
|
|
560
|
-
const sessionId = typeof details.session_id === "string" ? details.session_id : undefined;
|
|
561
|
-
const workspaceId = typeof details.workspace_id === "string" ? details.workspace_id : undefined;
|
|
562
|
-
const hasSessionIdentity = sessionId !== undefined && workspaceId !== undefined;
|
|
563
|
-
if (error instanceof RuntimeError &&
|
|
564
|
-
error.code === "SWARM_SESSION_CLEANUP_FAILED" &&
|
|
565
|
-
details.process_cleanup_unverified === true) {
|
|
566
|
-
cleanupFailure = error;
|
|
567
|
-
}
|
|
568
|
-
if (hasSessionIdentity) {
|
|
569
|
-
store.updateRunningJob(job.job_id, {
|
|
570
|
-
kimi_session_id: sessionId,
|
|
571
|
-
kimi_session_id_source: "preactivated",
|
|
572
|
-
});
|
|
573
|
-
}
|
|
574
|
-
if (hasSessionIdentity && !handlers.cancelling) {
|
|
575
|
-
const sessionCleanupFailure = await attemptDeactivation({ sessionId, workspaceId }, "swarm.activation-cleanup", recoveryCleanupTimeoutMs);
|
|
576
|
-
if (sessionCleanupFailure)
|
|
577
|
-
cleanupFailure = sessionCleanupFailure;
|
|
578
|
-
}
|
|
579
|
-
else if (hasSessionIdentity && cleanupFailure === undefined) {
|
|
580
|
-
cleanupFailure = new RuntimeError("SWARM_SESSION_CLEANUP_FAILED", "Swarm session cleanup was not completed after activation was cancelled.", "swarm.activation-cleanup", { details: { cancelled: true, cleanup_unverified: true } });
|
|
581
|
-
}
|
|
582
|
-
if (activationDidTimeOut && !handlers.cancelling) {
|
|
583
|
-
throw new ResponseTimeoutError(budgetMs, "swarm.activation", commandLabel, undefined, error);
|
|
584
|
-
}
|
|
585
|
-
throw error;
|
|
586
|
-
}
|
|
587
|
-
finally {
|
|
588
|
-
clearTimeout(activationTimer);
|
|
589
|
-
handlers.signal.removeEventListener("abort", onParentAbort);
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
const promptBudgetMs = budgetDeadline - Date.now();
|
|
593
|
-
if (promptBudgetMs <= 0)
|
|
594
|
-
throw new ResponseTimeoutError(budgetMs, "swarm.prompt", commandLabel);
|
|
595
|
-
store.updateRunningJob(job.job_id, { phase: "turn-running" });
|
|
596
|
-
if (recovery)
|
|
597
|
-
recordRecoveryEvent(store, recovery, { kind: "print-spawn" });
|
|
598
|
-
const result = await runCliPromptWithBudget({
|
|
599
|
-
...spawnOptions,
|
|
600
|
-
prefixArgs: [...executionPlan.prefixArgs],
|
|
601
|
-
prompt,
|
|
602
|
-
resumeSessionId: preactivated?.sessionId,
|
|
603
|
-
logPath: job.stream_log_path,
|
|
604
|
-
onSpawn: async (pid) => {
|
|
605
|
-
store.updateRunningJob(job.job_id, { kimi_pid: pid });
|
|
606
|
-
if (recovery) {
|
|
607
|
-
const probe = await probeProcessIdentity(pid);
|
|
608
|
-
recordRecoveryEvent(store, recovery, { kind: "print-processes", identities: probe.identity ? [probe.identity] : [], complete: probe.complete });
|
|
609
|
-
}
|
|
610
|
-
},
|
|
611
|
-
onProcessIdentities: recovery
|
|
612
|
-
? (identities, complete) => recordRecoveryEvent(store, recovery, {
|
|
613
|
-
kind: boundedSwarm ? "print-processes-snapshot" : "print-processes",
|
|
614
|
-
identities: [...identities], complete,
|
|
615
|
-
})
|
|
616
|
-
: undefined,
|
|
617
|
-
signal: handlers.signal,
|
|
618
|
-
}, promptBudgetMs, "swarm.prompt");
|
|
619
|
-
if (recovery)
|
|
620
|
-
recordRecoveryEvent(store, recovery, { kind: "print-exit" });
|
|
621
|
-
store.updateRunningJob(job.job_id, observedExecutionFields(result));
|
|
622
|
-
const prose = reassembleProseFromRecords(result.records);
|
|
623
|
-
finalText = prose;
|
|
624
|
-
let resultError;
|
|
625
|
-
if (handlers.cancelling) {
|
|
626
|
-
resultError = new RuntimeError("SWARM_CANCELLED", "Swarm cancelled by user request.", "swarm.runtime");
|
|
627
|
-
}
|
|
628
|
-
else {
|
|
629
|
-
try {
|
|
630
|
-
assertCliResultSuccess(result, "swarm.runtime");
|
|
631
|
-
if (preactivated && result.sessionId !== preactivated.sessionId) {
|
|
632
|
-
throw new RuntimeError("SWARM_SESSION_MISMATCH", "The resumed print session differs from the preactivated swarm session.", "swarm.session-provenance", { details: { expected_session_id: preactivated.sessionId, actual_session_id: result.sessionId ?? null } });
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
catch (error) {
|
|
636
|
-
resultError = error;
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
warnHookEscapes(result, "swarm", context.stderr);
|
|
640
|
-
if (preactivated) {
|
|
641
|
-
cleanupFailure = await attemptDeactivation(preactivated, "swarm.cleanup");
|
|
642
|
-
}
|
|
643
|
-
if (resultError !== undefined)
|
|
644
|
-
throw resultError;
|
|
645
|
-
if (handlers.cancelling) {
|
|
646
|
-
throw new RuntimeError("SWARM_CANCELLED", "Swarm cancelled by user request.", "swarm.runtime");
|
|
647
|
-
}
|
|
648
|
-
if (cleanupFailure)
|
|
649
|
-
throw cleanupFailure;
|
|
650
|
-
if (!preactivated &&
|
|
651
|
-
result.sessionId !== undefined &&
|
|
652
|
-
result.sessionId.length > 0 &&
|
|
653
|
-
result.sessionId !== job.kimi_session_id) {
|
|
654
|
-
store.updateRunningJob(job.job_id, { kimi_session_id_source: "announced", kimi_session_id: result.sessionId });
|
|
655
|
-
}
|
|
656
|
-
await syncKimiSessionTitle({
|
|
657
|
-
promptText: objective,
|
|
658
|
-
env: context.env,
|
|
659
|
-
cwd: job.cwd,
|
|
660
|
-
sessionId: result.sessionId ?? job.kimi_session_id,
|
|
661
|
-
title: buildKimiSessionTitle(commandLabel, objective),
|
|
662
|
-
stderr: context.stderr,
|
|
663
|
-
});
|
|
664
|
-
warnIfSessionIdMissing(result, "swarm", job.job_id, context.stderr);
|
|
665
|
-
if (writeMode) {
|
|
666
|
-
const captured = await capturePatchArtifact(paths, job.job_id, writeMode.workspaceRoot, context.stderr, writeMode.onPatchCaptureFailure);
|
|
667
|
-
if (captured === null) {
|
|
668
|
-
throw new RuntimeError("SWARM_PATCH_CAPTURE_FAILED", `Swarm patch capture failed; worktree retained at ${writeMode.workspaceRoot}.`, "swarm.patch-capture", { details: { worktreePath: writeMode.workspaceRoot } });
|
|
669
|
-
}
|
|
670
|
-
if (recovery)
|
|
671
|
-
recovery.patchPath = captured.path;
|
|
672
|
-
finalText = `${renderWriteSwarmHeader(captured)}\n\n---\n\n${prose}`.trimEnd();
|
|
673
|
-
}
|
|
674
|
-
const rendered = renderManagedJobOutput(job, finalText);
|
|
675
|
-
let artifactPath;
|
|
676
|
-
try {
|
|
677
|
-
artifactPath = await writeArtifact(paths, job, rendered.rendered);
|
|
678
|
-
}
|
|
679
|
-
catch (writeError) {
|
|
680
|
-
context.stderr.write(`[kimi-plugin-cc] swarm artifact write failed for job ${job.job_id}; raw output preserved in error details.\n`);
|
|
681
|
-
const classified = new RuntimeError("SWARM_ARTIFACT_WRITE_FAILED", `Failed to write swarm artifact: ${writeError.message ?? String(writeError)}`, "swarm.artifact", {
|
|
682
|
-
...(writeError instanceof Error ? { cause: writeError } : {}),
|
|
683
|
-
details: { rawOutput: finalText },
|
|
684
|
-
});
|
|
685
|
-
return await markJobFailed(store, paths, job, classified, "Swarm failed.", { phase: "failed" });
|
|
686
|
-
}
|
|
687
|
-
if (handlers.cancelling) {
|
|
688
|
-
throw new RuntimeError("SWARM_CANCELLED", "Swarm cancelled after artifact write.", "swarm.runtime");
|
|
689
|
-
}
|
|
690
|
-
if (recovery)
|
|
691
|
-
finishRecoveryRecord(store, recovery);
|
|
692
|
-
return (store.markCompleted(job.job_id, {
|
|
693
|
-
summary: `[${commandLabel}] ${shorten(objective, SWARM_SUMMARY_MAX)}`,
|
|
694
|
-
phase: "done",
|
|
695
|
-
final_output_path: artifactPath,
|
|
696
|
-
error: null,
|
|
697
|
-
}) ?? job);
|
|
698
|
-
}
|
|
699
|
-
catch (error) {
|
|
700
|
-
if (preactivated && deactivationRequired && activationOptions) {
|
|
701
|
-
if (handlers.cancelling) {
|
|
702
|
-
cleanupFailure = new RuntimeError("SWARM_SESSION_CLEANUP_FAILED", "Swarm session cleanup was not completed after cancellation.", "swarm.cleanup", { details: { cancelled: true, cleanup_unverified: true } });
|
|
703
|
-
}
|
|
704
|
-
else if (!cleanupAttempted) {
|
|
705
|
-
cleanupFailure = await attemptDeactivation(preactivated, "swarm.cleanup", recoveryCleanupTimeoutMs);
|
|
706
|
-
}
|
|
707
|
-
else if (error instanceof RuntimeError && error.code === "SWARM_SESSION_CLEANUP_FAILED") {
|
|
708
|
-
cleanupFailure ??= error;
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
if (cleanupFailure) {
|
|
712
|
-
writeMode?.onPatchCaptureFailure?.();
|
|
713
|
-
context.stderr.write(`[kimi-plugin-cc] swarm session cleanup also failed: ${cleanupFailure.message}\n`);
|
|
714
|
-
}
|
|
715
|
-
const processCleanupUnverified = hasUnverifiedProcessCleanup(error) || hasUnverifiedProcessCleanup(cleanupFailure);
|
|
716
|
-
const patchCaptureSkipped = writeMode !== undefined && processCleanupUnverified;
|
|
717
|
-
if (patchCaptureSkipped) {
|
|
718
|
-
writeMode.onPatchCaptureFailure?.();
|
|
719
|
-
context.stderr.write(`[kimi-plugin-cc] swarm-write process cleanup is unverified; no patch was captured. Worktree retained at ${writeMode.workspaceRoot}.\n`);
|
|
720
|
-
}
|
|
721
|
-
let captureFailed = writeMode !== undefined && error instanceof RuntimeError && error.code === "SWARM_PATCH_CAPTURE_FAILED";
|
|
722
|
-
if (writeMode && !patchCaptureSkipped && !(error instanceof RuntimeError && error.code === "SWARM_PATCH_CAPTURE_FAILED")) {
|
|
723
|
-
const captured = await capturePatchArtifact(paths, job.job_id, writeMode.workspaceRoot, context.stderr, writeMode.onPatchCaptureFailure);
|
|
724
|
-
captureFailed = captured === null;
|
|
725
|
-
if (recovery && captured)
|
|
726
|
-
recovery.patchPath = captured.path;
|
|
727
|
-
if (captured && !captured.empty) {
|
|
728
|
-
context.stderr.write(`[kimi-plugin-cc] swarm-write run ended early; partial patch captured at ${captured.path}.\n`);
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
const recoveryDetails = {
|
|
732
|
-
...(error instanceof RuntimeError && typeof error.details.exit_code === "number"
|
|
733
|
-
? { exit_code: error.details.exit_code }
|
|
734
|
-
: {}),
|
|
735
|
-
...((captureFailed || cleanupFailure || patchCaptureSkipped) && writeMode ? { worktreePath: writeMode.workspaceRoot } : {}),
|
|
736
|
-
...(processCleanupUnverified ? { process_cleanup_unverified: true } : {}),
|
|
737
|
-
...(patchCaptureSkipped ? { patch_capture_skipped: true } : {}),
|
|
738
|
-
...(cleanupFailure
|
|
739
|
-
? {
|
|
740
|
-
cleanup_error: {
|
|
741
|
-
code: cleanupFailure.code,
|
|
742
|
-
stage: cleanupFailure.stage,
|
|
743
|
-
cancelled: handlers.cancelling,
|
|
744
|
-
unverified: true,
|
|
745
|
-
},
|
|
746
|
-
...(finalText !== undefined ? { rawOutput: finalText } : {}),
|
|
747
|
-
}
|
|
748
|
-
: {}),
|
|
749
|
-
};
|
|
750
|
-
if (handlers.cancelling) {
|
|
751
|
-
const cancellationCause = classifyManagedCommandFailure(error, writeMode ? "rescue" : "review", job.job_id, {
|
|
752
|
-
preserveStage: true,
|
|
753
|
-
});
|
|
754
|
-
const cancelledError = new RuntimeError("SWARM_CANCELLED", patchCaptureSkipped && writeMode
|
|
755
|
-
? `Swarm cancelled; process cleanup is unverified. No patch was captured; worktree retained at ${writeMode.workspaceRoot}.`
|
|
756
|
-
: captureFailed && writeMode
|
|
757
|
-
? `Swarm cancelled; patch capture failed and worktree retained at ${writeMode.workspaceRoot}.`
|
|
758
|
-
: "Swarm cancelled by user request.", "swarm.runtime", {
|
|
759
|
-
...(error instanceof Error ? { cause: error } : {}),
|
|
760
|
-
details: {
|
|
761
|
-
...(cancellationCause instanceof RuntimeError ? cancellationCause.details : {}),
|
|
762
|
-
...recoveryDetails,
|
|
763
|
-
},
|
|
764
|
-
});
|
|
765
|
-
return await markJobCancelled(store, paths, job, "Swarm cancelled by user request.", cancelledError, {
|
|
766
|
-
phase: "cancelled",
|
|
767
|
-
});
|
|
768
|
-
}
|
|
769
|
-
if (error === cleanupFailure && budgetDeadline <= Date.now() && !(error instanceof ResponseTimeoutError)) {
|
|
770
|
-
error = new ResponseTimeoutError(budgetMs, "swarm.cleanup", commandLabel, undefined, cleanupFailure);
|
|
771
|
-
}
|
|
772
|
-
const classified = classifyManagedCommandFailure(error, writeMode ? "rescue" : "review", job.job_id, {
|
|
773
|
-
preserveStage: true,
|
|
774
|
-
});
|
|
775
|
-
const withRecovery = captureFailed || cleanupFailure || processCleanupUnverified
|
|
776
|
-
? classified instanceof RuntimeError
|
|
777
|
-
? new RuntimeError(classified.code, classified.message, classified.stage, {
|
|
778
|
-
cause: classified,
|
|
779
|
-
details: { ...classified.details, ...recoveryDetails },
|
|
780
|
-
})
|
|
781
|
-
: new RuntimeError(cleanupFailure?.code ?? (processCleanupUnverified ? "CLI_PROCESS_SETTLEMENT_FAILED" : "SWARM_PATCH_CAPTURE_FAILED"), classified.message, cleanupFailure?.stage ?? (processCleanupUnverified ? "cli-client.settlement" : "swarm.patch-capture"), { cause: classified, details: recoveryDetails })
|
|
782
|
-
: classified;
|
|
783
|
-
return await markJobFailed(store, paths, job, withRecovery, "Swarm failed.", { phase: "failed" });
|
|
784
|
-
}
|
|
785
|
-
finally {
|
|
786
|
-
handlers.dispose();
|
|
787
|
-
try {
|
|
788
|
-
if (recovery)
|
|
789
|
-
finishRecoveryRecord(store, recovery);
|
|
790
|
-
if (recovery && !recovery.complete) {
|
|
791
|
-
writeMode?.onPatchCaptureFailure?.();
|
|
792
|
-
context.stderr.write(`[kimi-plugin-cc] recovery record retained: companion.sh recover-swarm ${job.job_id} (preview).\n`);
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
catch (error) {
|
|
796
|
-
// A failed final journal commit cannot authorize removal of recovery evidence.
|
|
797
|
-
writeMode?.onPatchCaptureFailure?.();
|
|
798
|
-
throw error;
|
|
799
|
-
}
|
|
800
|
-
finally {
|
|
801
|
-
store.close();
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
function hasUnverifiedProcessCleanup(error) {
|
|
806
|
-
// Budget expiry wraps teardown failures. Preserve the unsafe-settlement
|
|
807
|
-
// signal through that cause chain before considering any patch capture.
|
|
808
|
-
const seen = new Set();
|
|
809
|
-
while (error instanceof Error && !seen.has(error)) {
|
|
810
|
-
seen.add(error);
|
|
811
|
-
if (error instanceof RuntimeError && (error.code === "CLI_PROCESS_SETTLEMENT_FAILED" || error.details.process_cleanup_unverified === true))
|
|
812
|
-
return true;
|
|
813
|
-
error = error.cause;
|
|
814
|
-
}
|
|
815
|
-
return false;
|
|
816
|
-
}
|
|
817
|
-
function shorten(text, max) {
|
|
818
|
-
const normalized = text.replace(/\s+/g, " ").trim();
|
|
819
|
-
if (normalized.length <= max) {
|
|
820
|
-
return normalized;
|
|
821
|
-
}
|
|
822
|
-
return `${normalized.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
|
|
823
|
-
}
|