kimi-plugin-cc 3.0.0 → 3.1.1
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 +283 -265
- 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 +224 -112
- package/dist/hooks/install.js +64 -169
- package/dist/hooks/managed-block.js +52 -101
- 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 +46 -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 +283 -265
- 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 +224 -112
- package/plugins/kimi-codex/dist/hooks/install.js +64 -169
- package/plugins/kimi-codex/dist/hooks/managed-block.js +52 -101
- 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,1465 +0,0 @@
|
|
|
1
|
-
import { SETUP_SUPPORTED_FLAGS } from "../parsing.js";
|
|
2
|
-
// Managed-block installer for the load-bearing kimi-code PreToolUse hook.
|
|
3
|
-
// Without it, `kimi -p` auto-approves tool calls, including from read-only
|
|
4
|
-
// commands.
|
|
5
|
-
//
|
|
6
|
-
// Setup writes or refreshes a host-scoped BEGIN/END block containing the
|
|
7
|
-
// canonical `'<absolute-node>' '<absolute-hook-script>'` command from
|
|
8
|
-
// resolveNodeBinary/buildHookShellCommand. Both tokens are shell-quoted and the
|
|
9
|
-
// absolute Node path avoids PATH dependence under sanitized launches. Setup
|
|
10
|
-
// probes the hook directly with the Node binary parsed back from that command
|
|
11
|
-
// and through `/bin/sh -c` using the exact installed command bytes. It also warns about broad permission
|
|
12
|
-
// denies, repairs orphan marker comments, and refuses remaining
|
|
13
|
-
// duplicate, orphaned, or malformed managed blocks.
|
|
14
|
-
//
|
|
15
|
-
// Subcommands: install (default), --check, --uninstall [--all],
|
|
16
|
-
// --enable-review-gate/--disable-review-gate, and the explicit, network-using
|
|
17
|
-
// --install-kimi [--json], which installs the highest certified kimi-code into
|
|
18
|
-
// plugin data. Nothing else in setup or any job installs or downloads.
|
|
19
|
-
//
|
|
20
|
-
// Managed-block splicing is line-based and preserves user bytes outside owned
|
|
21
|
-
// edits; whole-file validation and inline-hook normalization use the TOML parser.
|
|
22
|
-
import { spawn } from "node:child_process";
|
|
23
|
-
import { access, mkdir, lstat, mkdtemp, open, readdir, readFile, readlink, realpath, rename, rm, symlink, unlink, writeFile, } from "node:fs/promises";
|
|
24
|
-
import { constants as fsConstants, existsSync } from "node:fs";
|
|
25
|
-
import { randomBytes } from "node:crypto";
|
|
26
|
-
import path from "node:path";
|
|
27
|
-
import { readPluginConfig, writePluginConfig } from "../config.js";
|
|
28
|
-
import { RuntimeError } from "../errors.js";
|
|
29
|
-
import { HOOK_TIMEOUT_S } from "../hooks/hook-timing.js";
|
|
30
|
-
import { olderHostHookWarnings } from "../hooks/install.js";
|
|
31
|
-
import { normalizeTopLevelInlineHooks, validateKimiHookSetForEnvironment, withKimiConfigLock, } from "../hooks/config-safety.js";
|
|
32
|
-
import { buildHookShellCommand, hostIdFromHookCommand, parseHookShellCommand, resolveHookScriptPath, resolveHostId, resolveNodeBinary, } from "../hooks/install-paths.js";
|
|
33
|
-
import { decodeManagedCommandLine, describeHookTimeout, effectiveHost, evaluateInstalled, findShortHookTimeout, findUnmanagedApprovalHookBlocks, ORPHAN_MARKER_REMEDY, pairBlocks, parseManagedBlock, } from "../hooks/managed-block.js";
|
|
34
|
-
import { formatVersionOutOfRangeWarning, probeKimiVersion, } from "../kimi-version-probe.js";
|
|
35
|
-
import { inspectPluginOwnedKimi, selectKimiBinary } from "../kimi-command.js";
|
|
36
|
-
import { isNativeV2CertifiedVersion, NATIVE_V2_ANY_OPERATION_VERSIONS, NATIVE_V2_CERTIFIED_VERSIONS, NATIVE_V2_NON_SWARM_VERSIONS, } from "../kimi-engine.js";
|
|
37
|
-
import { resolveKimiCodeConfigPath, resolveKimiHome } from "../kimi-home.js";
|
|
38
|
-
import { formatVersionChoice, kimiReleaseHas, kimiVersionsWith } from "../kimi-releases.js";
|
|
39
|
-
import { ensurePluginPaths, resolveKimiBinDir, resolvePluginPaths } from "../paths.js";
|
|
40
|
-
import { KIMI_PLUGIN_CC_VERSION } from "../version.js";
|
|
41
|
-
import { parse as parseToml } from "../vendor/smol-toml/parse.js";
|
|
42
|
-
const BEGIN_MARKER_PREFIX = "# === BEGIN kimi-plugin-cc-managed";
|
|
43
|
-
const DEFAULT_HOOK_TIMEOUT_S = HOOK_TIMEOUT_S;
|
|
44
|
-
// Probe timing. The direct script probe is local and fast; allow 5s for
|
|
45
|
-
// node startup on cold CI runners. The shell probe adds /bin/sh fork
|
|
46
|
-
// overhead but should still complete well within the same budget.
|
|
47
|
-
const PROBE_TIMEOUT_MS = 5_000;
|
|
48
|
-
// Reject the specific control characters, double quotes, and backslashes matched
|
|
49
|
-
// below, including newlines and tabs; this is not a general shell-metacharacter
|
|
50
|
-
// filter. Normal install paths do not contain them, so a match indicates an
|
|
51
|
-
// unsafe override or an unusual layout that needs an explicit path change.
|
|
52
|
-
const PATH_FORBIDDEN_RE = /[\x00-\x1f"\\\n\r\t]/;
|
|
53
|
-
export async function runSetup(argv, context) {
|
|
54
|
-
const parsed = parseArgs(argv);
|
|
55
|
-
if (parsed.mode === "install-kimi") {
|
|
56
|
-
return await runInstallKimi(parsed.json, context);
|
|
57
|
-
}
|
|
58
|
-
const paths = resolvePluginPaths(context.env);
|
|
59
|
-
await ensurePluginPaths(paths);
|
|
60
|
-
// Reconcile the review-gate flag first — it's independent of the
|
|
61
|
-
// kimi-code hook and we want the answer reflected in the result even
|
|
62
|
-
// if the rest of setup fails.
|
|
63
|
-
const existingConfig = await readPluginConfig(paths);
|
|
64
|
-
const reviewGateEnabled = parsed.enableReviewGate
|
|
65
|
-
? true
|
|
66
|
-
: parsed.disableReviewGate
|
|
67
|
-
? false
|
|
68
|
-
: existingConfig.reviewGateEnabled;
|
|
69
|
-
if (reviewGateEnabled !== existingConfig.reviewGateEnabled) {
|
|
70
|
-
await writePluginConfig(paths, { reviewGateEnabled });
|
|
71
|
-
}
|
|
72
|
-
const configPath = resolveKimiCodeConfigPath(context.env);
|
|
73
|
-
const hookScriptPath = resolveHookScriptPath(context.env);
|
|
74
|
-
assertHookPathTomlSafe(hookScriptPath);
|
|
75
|
-
// Host id scopes each managed block so Claude Code and Codex can share one
|
|
76
|
-
// ~/.kimi-code/config.toml without clobbering each other.
|
|
77
|
-
const hostId = resolveHostId(context.env, hookScriptPath);
|
|
78
|
-
const warnings = [];
|
|
79
|
-
switch (parsed.mode) {
|
|
80
|
-
case "uninstall":
|
|
81
|
-
return await runUninstall(configPath, hookScriptPath, hostId, parsed.removeAllHosts, reviewGateEnabled, warnings, context);
|
|
82
|
-
case "check":
|
|
83
|
-
return await runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context);
|
|
84
|
-
case "install":
|
|
85
|
-
return await runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
function parseArgs(argv) {
|
|
89
|
-
let mode = "install";
|
|
90
|
-
let enableReviewGate = false;
|
|
91
|
-
let disableReviewGate = false;
|
|
92
|
-
let removeAllHosts = false;
|
|
93
|
-
let installKimi = false;
|
|
94
|
-
let json = false;
|
|
95
|
-
for (const token of argv) {
|
|
96
|
-
switch (token) {
|
|
97
|
-
case "--install-kimi":
|
|
98
|
-
installKimi = true;
|
|
99
|
-
break;
|
|
100
|
-
case "--json":
|
|
101
|
-
json = true;
|
|
102
|
-
break;
|
|
103
|
-
case "--check":
|
|
104
|
-
if (mode === "uninstall") {
|
|
105
|
-
throw new RuntimeError("INVALID_ARGS", "setup accepts at most one of --check, --uninstall.", "setup.parse");
|
|
106
|
-
}
|
|
107
|
-
mode = "check";
|
|
108
|
-
break;
|
|
109
|
-
case "--uninstall":
|
|
110
|
-
if (mode === "check") {
|
|
111
|
-
throw new RuntimeError("INVALID_ARGS", "setup accepts at most one of --check, --uninstall.", "setup.parse");
|
|
112
|
-
}
|
|
113
|
-
mode = "uninstall";
|
|
114
|
-
break;
|
|
115
|
-
case "--all":
|
|
116
|
-
removeAllHosts = true;
|
|
117
|
-
break;
|
|
118
|
-
case "--enable-review-gate":
|
|
119
|
-
enableReviewGate = true;
|
|
120
|
-
break;
|
|
121
|
-
case "--disable-review-gate":
|
|
122
|
-
disableReviewGate = true;
|
|
123
|
-
break;
|
|
124
|
-
default:
|
|
125
|
-
throw new RuntimeError("INVALID_ARGS", `Unknown setup flag ${token}. Supported flags: ${SETUP_SUPPORTED_FLAGS}.`, "setup.parse");
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
if (enableReviewGate && disableReviewGate) {
|
|
129
|
-
throw new RuntimeError("INVALID_ARGS", "setup accepts either --enable-review-gate or --disable-review-gate, not both.", "setup.parse");
|
|
130
|
-
}
|
|
131
|
-
if (removeAllHosts && mode !== "uninstall") {
|
|
132
|
-
throw new RuntimeError("INVALID_ARGS", "--all is only valid with --uninstall (it removes EVERY host's managed block).", "setup.parse");
|
|
133
|
-
}
|
|
134
|
-
if (installKimi) {
|
|
135
|
-
if (argv.some((token) => token !== "--install-kimi" && token !== "--json")) {
|
|
136
|
-
throw new RuntimeError("INVALID_ARGS", "--install-kimi does not combine with other setup flags except --json.", "setup.parse");
|
|
137
|
-
}
|
|
138
|
-
return { mode: "install-kimi", json, enableReviewGate, disableReviewGate, removeAllHosts };
|
|
139
|
-
}
|
|
140
|
-
if (json) {
|
|
141
|
-
throw new RuntimeError("INVALID_ARGS", "--json is only valid with --install-kimi or --models.", "setup.parse");
|
|
142
|
-
}
|
|
143
|
-
return { mode, json, enableReviewGate, disableReviewGate, removeAllHosts };
|
|
144
|
-
}
|
|
145
|
-
async function runInstall(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context) {
|
|
146
|
-
await assertHookScriptExists(hookScriptPath);
|
|
147
|
-
const mutation = await withKimiConfigLock(configPath, async () => {
|
|
148
|
-
const original = await readConfigSafe(configPath);
|
|
149
|
-
const lineEnding = detectLineEnding(original);
|
|
150
|
-
try {
|
|
151
|
-
parseToml(original);
|
|
152
|
-
}
|
|
153
|
-
catch {
|
|
154
|
-
await assertKimiHookSetValid(original, configPath, "setup.install", context.env);
|
|
155
|
-
}
|
|
156
|
-
const repaired = removeOrphanMarkers(original);
|
|
157
|
-
if (repaired.count > 0) {
|
|
158
|
-
warnings.push(`Removed ${repaired.count} orphaned managed marker comment(s); surrounding config was preserved.`);
|
|
159
|
-
}
|
|
160
|
-
const inlineHooks = normalizeTopLevelInlineHooks(repaired.contents, lineEnding);
|
|
161
|
-
if (inlineHooks.found) {
|
|
162
|
-
// Validate before normalizing so an invalid inline entry is reported
|
|
163
|
-
// against the user's original bytes and the config remains untouched.
|
|
164
|
-
await assertKimiHookSetValid(original, configPath, "setup.install", context.env);
|
|
165
|
-
if (!inlineHooks.converted) {
|
|
166
|
-
throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `Could not safely convert the top-level inline hooks assignment in ${configPath}; the existing config was left unchanged.`, "setup.install", { details: { configPath } });
|
|
167
|
-
}
|
|
168
|
-
warnings.push(`Converted the top-level inline hooks array (${inlineHooks.entryCount} entr${inlineHooks.entryCount === 1 ? "y" : "ies"}) to canonical [[hooks]] tables before installing. Surrounding config bytes were preserved; formatting and comments inside that hooks assignment were normalized.`);
|
|
169
|
-
}
|
|
170
|
-
// Prune only this host's orphaned marker-less entries before computing
|
|
171
|
-
// splice line numbers. Another host's marker-less table may be its live hook
|
|
172
|
-
// after a config rewrite strips comments, so it must remain untouched.
|
|
173
|
-
const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
|
|
174
|
-
const shortBefore = findShortHookTimeout(inlineHooks.contents, expectedCommand);
|
|
175
|
-
const { pruned, count: prunedCount, commands: prunedCommands } = pruneOrphanApprovalHooks(inlineHooks.contents, hostId, expectedCommand);
|
|
176
|
-
const existing = pruned;
|
|
177
|
-
if (prunedCount > 0) {
|
|
178
|
-
const readorned = prunedCommands.includes(expectedCommand);
|
|
179
|
-
warnings.push(readorned
|
|
180
|
-
? shortBefore === null
|
|
181
|
-
? `Re-adorned this host's managed-block markers: kimi-code rewrites its config on login/settings changes and strips all comments (markers included), leaving the hook enforcing but unmarked. Replaced the bare hook table with a freshly marked block (${prunedCount} table(s) refreshed). Enforcement was never interrupted.`
|
|
182
|
-
: `Re-adorned this host's managed-block markers: replaced the bare hook table with a freshly marked block (${prunedCount} table(s) refreshed).`
|
|
183
|
-
: `Pruned ${prunedCount} stale marker-less kimi-plugin-cc hook block(s) left by this host's earlier installs. This is a cleanup — your active hook is unaffected.`);
|
|
184
|
-
}
|
|
185
|
-
const { state, blocks } = parseManagedBlock(existing, hostId);
|
|
186
|
-
if (state.kind === "orphan") {
|
|
187
|
-
throw new RuntimeError("SETUP_ORPHAN_MARKERS", [
|
|
188
|
-
`kimi-code config at ${configPath} contains an orphaned ${state.detail} marker.`,
|
|
189
|
-
"Inspect the managed marker comments and re-run setup.",
|
|
190
|
-
].join(" "), "setup.install", { details: { configPath, orphan: state.detail } });
|
|
191
|
-
}
|
|
192
|
-
if (state.kind === "duplicate") {
|
|
193
|
-
throw new RuntimeError("SETUP_DUPLICATE_BLOCKS", [
|
|
194
|
-
`kimi-code config at ${configPath} contains ${state.beginLines.length} kimi-plugin-cc managed blocks for host ${hostId} (lines ${state.beginLines
|
|
195
|
-
.map((line) => line + 1)
|
|
196
|
-
.join(", ")}).`,
|
|
197
|
-
"This usually means two /kimi:setup runs raced. Run `/kimi:setup --uninstall` to clear them, then `/kimi:setup` again.",
|
|
198
|
-
].join(" "), "setup.install", { details: { configPath, beginLines: state.beginLines } });
|
|
199
|
-
}
|
|
200
|
-
// Non-blocking note: other hosts (e.g. Codex) manage their own block in the
|
|
201
|
-
// same shared config — surface so an operator understands the coexistence.
|
|
202
|
-
const otherHosts = [
|
|
203
|
-
...new Set(blocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
|
|
204
|
-
];
|
|
205
|
-
if (otherHosts.length > 0) {
|
|
206
|
-
warnings.push(`Other host(s) also manage a block in this shared config: ${otherHosts.join(", ")}. ` +
|
|
207
|
-
`They are left untouched — each host owns its own PreToolUse block.`);
|
|
208
|
-
}
|
|
209
|
-
const block = buildManagedBlock(expectedCommand, lineEnding, hostId);
|
|
210
|
-
const next = state.kind === "found"
|
|
211
|
-
? spliceBlock(existing, state.beginLine, state.endLine, block, lineEnding)
|
|
212
|
-
: insertBlockNearManagedBlocks(existing, blocks, block, lineEnding);
|
|
213
|
-
await assertKimiHookSetValid(next, configPath, "setup.install", context.env);
|
|
214
|
-
// Setup rewrites only its own block and prunable tables. Any other copy of
|
|
215
|
-
// this command (e.g. one with a matcher) can be the entry kimi-code runs.
|
|
216
|
-
const shortAfter = findShortHookTimeout(next, expectedCommand);
|
|
217
|
-
if (shortAfter !== null) {
|
|
218
|
-
throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `kimi-code config at ${configPath} has another [[hooks]] entry with this host's hook command and ${describeHookTimeout(shortAfter.timeout)}; kimi-code runs only one entry per command and reads a hook that runs past its timeout as allow. Remove that entry before rerunning /kimi:setup; the existing config was left unchanged.`, "setup.install", { details: { configPath, timeout: describeHookTimeout(shortAfter.timeout) } });
|
|
219
|
-
}
|
|
220
|
-
if (shortBefore !== null) {
|
|
221
|
-
warnings.push(`Rewrote this host's hook entry from ${describeHookTimeout(shortBefore.timeout)} to timeout = ${HOOK_TIMEOUT_S}: kimi-code reads a hook that runs past its timeout as allow, so the earlier entry did not reliably enforce.`);
|
|
222
|
-
}
|
|
223
|
-
const blockWritten = next !== original;
|
|
224
|
-
if (blockWritten)
|
|
225
|
-
await writeConfigAtomic(configPath, next);
|
|
226
|
-
return { blockWritten, next, expectedCommand };
|
|
227
|
-
});
|
|
228
|
-
const { blockWritten, next, expectedCommand } = mutation;
|
|
229
|
-
warnings.push(...await olderHostHookWarnings(next, hostId, expectedCommand));
|
|
230
|
-
collectPermissionRuleWarnings(next, warnings);
|
|
231
|
-
const kimiBinary = describeKimiBinary(context.env, warnings);
|
|
232
|
-
await collectKimiVersionWarnings(context.env, warnings);
|
|
233
|
-
await collectInstalledKimiPluginsNotice(context.env, warnings);
|
|
234
|
-
const probe = await probeHook(hookScriptPath, expectedCommand, context.env);
|
|
235
|
-
const summary = probe.ok
|
|
236
|
-
? blockWritten
|
|
237
|
-
? `Installed kimi-plugin-cc PreToolUse hook in ${configPath}.`
|
|
238
|
-
: `kimi-plugin-cc PreToolUse hook already up to date in ${configPath}.`
|
|
239
|
-
: `Wrote managed block to ${configPath} but the hook script probe failed.`;
|
|
240
|
-
return {
|
|
241
|
-
action: "install",
|
|
242
|
-
summary,
|
|
243
|
-
configPath,
|
|
244
|
-
hookScriptPath,
|
|
245
|
-
blockWritten,
|
|
246
|
-
blockRemoved: false,
|
|
247
|
-
probe: probe.ok ? "ok" : "failed",
|
|
248
|
-
probeError: probe.ok ? undefined : probe.reason,
|
|
249
|
-
warnings,
|
|
250
|
-
reviewGateEnabled,
|
|
251
|
-
nextStep: probe.ok
|
|
252
|
-
? "Run /kimi:task, /kimi:review, /kimi:pursue or /kimi:swarm. Codex users can invoke the matching $kimi-* skills."
|
|
253
|
-
: "Re-run /kimi:setup after installing kimi-code and Node. If the probe keeps failing, run /kimi:setup --uninstall and inspect ~/.kimi-code/config.toml manually.",
|
|
254
|
-
details: buildDetails({
|
|
255
|
-
configPath,
|
|
256
|
-
hookScriptPath,
|
|
257
|
-
reviewGateEnabled,
|
|
258
|
-
probe,
|
|
259
|
-
warnings,
|
|
260
|
-
hostId,
|
|
261
|
-
kimiBinary,
|
|
262
|
-
}),
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
async function runCheck(configPath, hookScriptPath, hostId, reviewGateEnabled, warnings, context) {
|
|
266
|
-
const failedCheck = (result) => ({
|
|
267
|
-
action: "check",
|
|
268
|
-
summary: result.summary,
|
|
269
|
-
configPath,
|
|
270
|
-
hookScriptPath,
|
|
271
|
-
blockWritten: false,
|
|
272
|
-
blockRemoved: false,
|
|
273
|
-
probe: "failed",
|
|
274
|
-
probeError: result.reason,
|
|
275
|
-
warnings,
|
|
276
|
-
reviewGateEnabled,
|
|
277
|
-
nextStep: result.nextStep,
|
|
278
|
-
details: buildDetails({
|
|
279
|
-
configPath,
|
|
280
|
-
hookScriptPath,
|
|
281
|
-
reviewGateEnabled,
|
|
282
|
-
probe: { ok: false, reason: result.detailReason ?? result.reason },
|
|
283
|
-
warnings,
|
|
284
|
-
hostId: result.hostId,
|
|
285
|
-
kimiBinary,
|
|
286
|
-
}),
|
|
287
|
-
});
|
|
288
|
-
// Reported on every check path, including early failures.
|
|
289
|
-
const kimiBinary = describeKimiBinary(context.env, warnings);
|
|
290
|
-
const existing = await readConfigSafe(configPath);
|
|
291
|
-
const hookSet = await validateKimiHookSetForEnvironment(existing, context.env);
|
|
292
|
-
if (!hookSet.valid) {
|
|
293
|
-
return failedCheck({
|
|
294
|
-
summary: `kimi-code hook configuration is invalid; the configured hooks array will not load.`,
|
|
295
|
-
reason: hookSet.reason ?? "configured hooks failed validation",
|
|
296
|
-
nextStep: "Repair or remove the invalid [[hooks]] entry named above, then run /kimi:setup --check again. No model call is required.",
|
|
297
|
-
hostId,
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
|
|
301
|
-
// nodeExists refines mismatch prose into drift classification; hostId checks
|
|
302
|
-
// only this host's block in the shared config.
|
|
303
|
-
const installedCheck = evaluateInstalled(existing, expectedCommand, {
|
|
304
|
-
hostId,
|
|
305
|
-
nodeExists: (binPath) => existsSync(binPath),
|
|
306
|
-
});
|
|
307
|
-
// Non-blocking coexistence + cruft notices.
|
|
308
|
-
const { blocks: allBlocks, foreignOrphans } = parseManagedBlock(existing, hostId);
|
|
309
|
-
for (const orphan of foreignOrphans) {
|
|
310
|
-
warnings.push(`Host "${orphan.hostId}" has an orphaned ${orphan.detail} managed marker at line ${orphan.line + 1}; that host's commands refuse until it is repaired. ${ORPHAN_MARKER_REMEDY}`);
|
|
311
|
-
}
|
|
312
|
-
const otherHosts = [
|
|
313
|
-
...new Set(allBlocks.map((b) => effectiveHost(b, hostId)).filter((h) => h !== hostId)),
|
|
314
|
-
];
|
|
315
|
-
if (otherHosts.length > 0) {
|
|
316
|
-
warnings.push(`Other host(s) also manage a block in this shared config: ${otherHosts.join(", ")} (coexisting, untouched).`);
|
|
317
|
-
}
|
|
318
|
-
warnings.push(...await olderHostHookWarnings(existing, hostId, expectedCommand));
|
|
319
|
-
// Config rewrites can strip markers while leaving each host's table enforcing.
|
|
320
|
-
// Our exact-command table is live; our stale table is prunable; another host's
|
|
321
|
-
// table is reported but left strictly alone.
|
|
322
|
-
const bareTables = findUnmanagedApprovalHookBlocks(existing);
|
|
323
|
-
const ownStale = bareTables.filter((t) => hostIdFromHookCommand(t.command) === hostId && t.command !== expectedCommand);
|
|
324
|
-
const foreignHosts = [
|
|
325
|
-
...new Set(bareTables
|
|
326
|
-
// Exact current command bytes identify this host even when a host-id
|
|
327
|
-
// override disagrees with the path-derived host.
|
|
328
|
-
.filter((t) => t.command !== expectedCommand)
|
|
329
|
-
.map((t) => hostIdFromHookCommand(t.command))
|
|
330
|
-
.filter((h) => h !== null && h !== hostId)),
|
|
331
|
-
];
|
|
332
|
-
if (ownStale.length > 0) {
|
|
333
|
-
warnings.push(`Found ${ownStale.length} stale marker-less kimi-plugin-cc hook block(s) from this host's earlier installs. ` +
|
|
334
|
-
`Run /kimi:setup to refresh, or /kimi:setup --uninstall --all to clear everything.`);
|
|
335
|
-
}
|
|
336
|
-
for (const host of foreignHosts) {
|
|
337
|
-
warnings.push(`Host "${host}" has a marker-less kimi-plugin-cc hook block (kimi-code config rewrites strip comments). ` +
|
|
338
|
-
`It still enforces and is left untouched; run that host's setup to re-adorn its markers.`);
|
|
339
|
-
}
|
|
340
|
-
if (installedCheck.installed && installedCheck.note !== undefined) {
|
|
341
|
-
warnings.push(`Note: ${installedCheck.note}`);
|
|
342
|
-
}
|
|
343
|
-
if (!installedCheck.installed) {
|
|
344
|
-
return failedCheck({
|
|
345
|
-
summary: installedCheck.timeoutTooShort === true
|
|
346
|
-
? `kimi-plugin-cc PreToolUse hook in ${configPath} does not enforce: ${installedCheck.reason}`
|
|
347
|
-
: installedCheck.state.kind === "absent"
|
|
348
|
-
? `kimi-plugin-cc managed block is NOT installed in ${configPath}.`
|
|
349
|
-
: `kimi-plugin-cc managed block is present but invalid: ${installedCheck.reason}.`,
|
|
350
|
-
reason: installedCheck.reason ?? "managed block missing or invalid",
|
|
351
|
-
detailReason: installedCheck.reason ?? "block missing/invalid",
|
|
352
|
-
nextStep: installedCheck.timeoutTooShort === true
|
|
353
|
-
? "Run /kimi:setup (without --check) to rewrite the hook timeout."
|
|
354
|
-
: installedCheck.state.kind === "absent"
|
|
355
|
-
? "Run /kimi:setup (without --check) to install the managed block."
|
|
356
|
-
: installedCheck.state.kind === "orphan"
|
|
357
|
-
? ORPHAN_MARKER_REMEDY
|
|
358
|
-
: "Run /kimi:setup --uninstall, then /kimi:setup to repair.",
|
|
359
|
-
});
|
|
360
|
-
}
|
|
361
|
-
collectPermissionRuleWarnings(existing, warnings);
|
|
362
|
-
await collectKimiVersionWarnings(context.env, warnings);
|
|
363
|
-
await collectInstalledKimiPluginsNotice(context.env, warnings);
|
|
364
|
-
// Block is structurally valid AND points at the resolved hook
|
|
365
|
-
// script — now confirm the script itself still loads and behaves.
|
|
366
|
-
try {
|
|
367
|
-
await assertHookScriptExists(hookScriptPath);
|
|
368
|
-
}
|
|
369
|
-
catch (err) {
|
|
370
|
-
return failedCheck({
|
|
371
|
-
summary: `Managed block references ${hookScriptPath} but that path is unreadable.`,
|
|
372
|
-
reason: err instanceof Error ? err.message : String(err),
|
|
373
|
-
nextStep: "Reinstall the plugin so dist/hooks/approval-hook.js is present, or run /kimi:setup to refresh the managed block.",
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
const probe = await probeHook(hookScriptPath, expectedCommand, context.env);
|
|
377
|
-
return {
|
|
378
|
-
action: "check",
|
|
379
|
-
summary: probe.ok
|
|
380
|
-
? `kimi-plugin-cc PreToolUse hook is installed and probe passed.`
|
|
381
|
-
: `Managed block is installed but probe failed (${probe.reason}).`,
|
|
382
|
-
configPath,
|
|
383
|
-
hookScriptPath,
|
|
384
|
-
blockWritten: false,
|
|
385
|
-
blockRemoved: false,
|
|
386
|
-
probe: probe.ok ? "ok" : "failed",
|
|
387
|
-
probeError: probe.ok ? undefined : probe.reason,
|
|
388
|
-
warnings,
|
|
389
|
-
reviewGateEnabled,
|
|
390
|
-
nextStep: !probe.ok
|
|
391
|
-
? "Run /kimi:setup to repair the managed block, or /kimi:setup --uninstall if you want to remove the integration."
|
|
392
|
-
: installedCheck.via === "bare-table"
|
|
393
|
-
// Enforcement remains active through the marker-less table, but recommend
|
|
394
|
-
// re-adorning rather than claiming no action is needed.
|
|
395
|
-
? "Enforcement is active. Run /kimi:setup to re-adorn this host's managed-block markers — kimi-code stripped them on its last config write (comments are not preserved). Your hook keeps working meanwhile."
|
|
396
|
-
: "No action needed.",
|
|
397
|
-
details: buildDetails({
|
|
398
|
-
configPath,
|
|
399
|
-
hookScriptPath,
|
|
400
|
-
reviewGateEnabled,
|
|
401
|
-
probe,
|
|
402
|
-
warnings,
|
|
403
|
-
hostId,
|
|
404
|
-
kimiBinary,
|
|
405
|
-
}),
|
|
406
|
-
};
|
|
407
|
-
}
|
|
408
|
-
async function runUninstall(configPath, hookScriptPath, hostId, removeAllHosts, reviewGateEnabled, warnings, context) {
|
|
409
|
-
return await withKimiConfigLock(configPath, async () => {
|
|
410
|
-
const existing = await readConfigSafe(configPath);
|
|
411
|
-
if (existing.length === 0) {
|
|
412
|
-
return {
|
|
413
|
-
action: "uninstall",
|
|
414
|
-
summary: `Nothing to remove — ${configPath} does not exist or is empty.`,
|
|
415
|
-
configPath,
|
|
416
|
-
hookScriptPath,
|
|
417
|
-
blockWritten: false,
|
|
418
|
-
blockRemoved: false,
|
|
419
|
-
probe: "skipped",
|
|
420
|
-
warnings,
|
|
421
|
-
reviewGateEnabled,
|
|
422
|
-
nextStep: "Run /kimi:setup to install the managed block again.",
|
|
423
|
-
details: buildDetails({
|
|
424
|
-
configPath,
|
|
425
|
-
hookScriptPath,
|
|
426
|
-
reviewGateEnabled,
|
|
427
|
-
probe: { ok: true, reason: "no-op (config absent)" },
|
|
428
|
-
warnings,
|
|
429
|
-
}),
|
|
430
|
-
};
|
|
431
|
-
}
|
|
432
|
-
// Scoped uninstall removes only this host's marked and marker-less blocks;
|
|
433
|
-
// other hosts' blocks and live marker-less tables remain intact. `--all` is
|
|
434
|
-
// the explicit every-host sweep for all of this plugin's hook tables.
|
|
435
|
-
const { stripped: strippedMarkers, removedBlocks, orphansLeft } = stripManagedBlocks(existing, hostId, removeAllHosts);
|
|
436
|
-
// Exact current command bytes also identify this host's table when a host-id
|
|
437
|
-
// override disagrees with path derivation or a dev path is outside the strict
|
|
438
|
-
// ownership pattern.
|
|
439
|
-
const expectedCommand = buildHookShellCommand(hookScriptPath, context.env);
|
|
440
|
-
const { pruned: stripped, count: prunedCount } = pruneOrphanApprovalHooks(strippedMarkers, removeAllHosts ? undefined : hostId, expectedCommand);
|
|
441
|
-
const changed = stripped !== existing;
|
|
442
|
-
if (changed) {
|
|
443
|
-
await writeConfigAtomic(configPath, stripped);
|
|
444
|
-
}
|
|
445
|
-
if (orphansLeft.length > 0) {
|
|
446
|
-
warnings.push(`Detected ${orphansLeft.length} orphan marker line(s) at ${orphansLeft
|
|
447
|
-
.map((line) => `line ${line + 1}`)
|
|
448
|
-
.join(", ")}. Removed the marker line(s) but preserved surrounding user content — verify the config visually.`);
|
|
449
|
-
}
|
|
450
|
-
if (prunedCount > 0) {
|
|
451
|
-
warnings.push(`Pruned ${prunedCount} orphaned kimi-plugin-cc hook block(s) with no managed marker.`);
|
|
452
|
-
}
|
|
453
|
-
const { blocks: remainingBlocks } = parseManagedBlock(stripped, hostId);
|
|
454
|
-
const remainingHosts = [
|
|
455
|
-
...new Set(remainingBlocks.map((b) => effectiveHost(b, hostId))),
|
|
456
|
-
];
|
|
457
|
-
if (!removeAllHosts && remainingHosts.length > 0) {
|
|
458
|
-
warnings.push(`Left ${remainingHosts.length} other host block(s) in place: ${remainingHosts.join(", ")}. ` +
|
|
459
|
-
`Use \`/kimi:setup --uninstall --all\` to remove every host's block.`);
|
|
460
|
-
}
|
|
461
|
-
return {
|
|
462
|
-
action: "uninstall",
|
|
463
|
-
summary: changed
|
|
464
|
-
? `Removed ${removedBlocks} managed block(s)${prunedCount > 0 ? ` + ${prunedCount} orphan hook block(s)` : ""} from ${configPath}.`
|
|
465
|
-
: `No kimi-plugin-cc managed block to remove from ${configPath}.`,
|
|
466
|
-
configPath,
|
|
467
|
-
hookScriptPath,
|
|
468
|
-
blockWritten: false,
|
|
469
|
-
blockRemoved: changed,
|
|
470
|
-
probe: "skipped",
|
|
471
|
-
warnings,
|
|
472
|
-
reviewGateEnabled,
|
|
473
|
-
nextStep: changed
|
|
474
|
-
? "Run /kimi:setup again to reinstall the hook, or leave the plugin uninstalled."
|
|
475
|
-
: "Run /kimi:setup to install the hook.",
|
|
476
|
-
details: buildDetails({
|
|
477
|
-
configPath,
|
|
478
|
-
hookScriptPath,
|
|
479
|
-
reviewGateEnabled,
|
|
480
|
-
probe: { ok: true, reason: changed ? `removed ${removedBlocks} block(s)` : "no-op (no markers)" },
|
|
481
|
-
warnings,
|
|
482
|
-
}),
|
|
483
|
-
};
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
// ----- Config IO ---------------------------------------------------------
|
|
487
|
-
async function readConfigSafe(configPath) {
|
|
488
|
-
try {
|
|
489
|
-
return await readFile(configPath, "utf8");
|
|
490
|
-
}
|
|
491
|
-
catch (err) {
|
|
492
|
-
if (err.code === "ENOENT")
|
|
493
|
-
return "";
|
|
494
|
-
throw new RuntimeError("SETUP_CONFIG_READ_FAILED", `Failed to read kimi-code config at ${configPath}: ${err.message}`, "setup.read-config", err instanceof Error ? { cause: err, details: { configPath } } : { details: { configPath } });
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
async function writeConfigAtomic(configPath, contents) {
|
|
498
|
-
// Write a unique sibling temp file and atomically rename it. O_EXCL prevents
|
|
499
|
-
// concurrent operations from sharing an intermediate path.
|
|
500
|
-
//
|
|
501
|
-
// Pass 0o600 at creation, not in a later chmod: the config can contain
|
|
502
|
-
// credentials, so the temp file must never exist with a wider umask-derived
|
|
503
|
-
// mode.
|
|
504
|
-
await mkdir(path.dirname(configPath), { recursive: true });
|
|
505
|
-
const suffix = randomBytes(8).toString("hex");
|
|
506
|
-
const tmpPath = `${configPath}.kimi-plugin-cc.${process.pid}.${suffix}.tmp`;
|
|
507
|
-
const openFlags = fsConstants.O_WRONLY |
|
|
508
|
-
fsConstants.O_CREAT |
|
|
509
|
-
fsConstants.O_EXCL |
|
|
510
|
-
(fsConstants.O_NOFOLLOW ?? 0);
|
|
511
|
-
try {
|
|
512
|
-
const handle = await open(tmpPath, openFlags, 0o600);
|
|
513
|
-
try {
|
|
514
|
-
if (process.platform !== "win32") {
|
|
515
|
-
// Windows file modes are emulated; skip the chmod to avoid
|
|
516
|
-
// platform-specific noise. The threat model excludes Windows.
|
|
517
|
-
// Belt-and-suspenders alongside the create-time mode above,
|
|
518
|
-
// matching createPrivateLockFile's pattern.
|
|
519
|
-
await handle.chmod(0o600);
|
|
520
|
-
}
|
|
521
|
-
await handle.writeFile(contents, "utf8");
|
|
522
|
-
}
|
|
523
|
-
finally {
|
|
524
|
-
await handle.close();
|
|
525
|
-
}
|
|
526
|
-
await rename(tmpPath, configPath);
|
|
527
|
-
}
|
|
528
|
-
catch (err) {
|
|
529
|
-
// Best-effort cleanup so stale tmp files don't accumulate.
|
|
530
|
-
try {
|
|
531
|
-
await unlink(tmpPath);
|
|
532
|
-
}
|
|
533
|
-
catch {
|
|
534
|
-
// ignore
|
|
535
|
-
}
|
|
536
|
-
throw err;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
async function assertKimiHookSetValid(contents, configPath, stage, env) {
|
|
540
|
-
const validation = await validateKimiHookSetForEnvironment(contents, env);
|
|
541
|
-
if (validation.valid)
|
|
542
|
-
return;
|
|
543
|
-
throw new RuntimeError("SETUP_INVALID_HOOKS_CONFIG", `${validation.reason ?? "Configured hooks failed validation"} Repair or remove that [[hooks]] entry before rerunning /kimi:setup; the existing config was left unchanged.`, stage, {
|
|
544
|
-
details: {
|
|
545
|
-
configPath,
|
|
546
|
-
hookEntry: validation.entry,
|
|
547
|
-
line: validation.line,
|
|
548
|
-
},
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
// ----- Line endings -----------------------------------------------------
|
|
552
|
-
function detectLineEnding(contents) {
|
|
553
|
-
// Heuristic: if the file contains any `\r\n`, treat it as CRLF.
|
|
554
|
-
// Otherwise use LF (also covers the empty-file case where we're
|
|
555
|
-
// writing fresh content). This keeps the file's line-ending shape
|
|
556
|
-
// stable across install/uninstall on Windows users' configs.
|
|
557
|
-
return contents.includes("\r\n") ? "\r\n" : "\n";
|
|
558
|
-
}
|
|
559
|
-
function spliceBlock(contents, beginLine, endLine, replacement, lineEnding) {
|
|
560
|
-
const lines = contents.split(/(?<=\n)/);
|
|
561
|
-
const before = lines.slice(0, beginLine).join("");
|
|
562
|
-
const after = lines.slice(endLine + 1).join("");
|
|
563
|
-
const beforeWithSep = before.endsWith("\n") || before.length === 0 ? before : `${before}${lineEnding}`;
|
|
564
|
-
const replacementWithEnding = replacement.endsWith(lineEnding) ? replacement : `${replacement}${lineEnding}`;
|
|
565
|
-
return `${beforeWithSep}${replacementWithEnding}${after}`;
|
|
566
|
-
}
|
|
567
|
-
// Keep every host's block in one contiguous run. Magpie's table rewrite drops
|
|
568
|
-
// comments that follow a table it owns (yetone/magpie#5614): a block appended
|
|
569
|
-
// after such a table loses its BEGIN marker and header, leaving an orphan END.
|
|
570
|
-
// Insert after the last managed END only when nothing but blanks/comments
|
|
571
|
-
// precedes the next header AND the real parser proves the result equals the
|
|
572
|
-
// appended form apart from hook order, so no field can rebind and no value can
|
|
573
|
-
// be split; otherwise append.
|
|
574
|
-
function insertBlockNearManagedBlocks(contents, blocks, block, lineEnding) {
|
|
575
|
-
if (blocks.length === 0)
|
|
576
|
-
return appendBlock(contents, block, lineEnding);
|
|
577
|
-
const anchor = Math.max(...blocks.map((b) => b.endLine));
|
|
578
|
-
const lines = splitPreservingEnding(contents);
|
|
579
|
-
for (let i = anchor + 1; i < lines.length; i += 1) {
|
|
580
|
-
const trimmed = lines[i].trim();
|
|
581
|
-
if (trimmed.startsWith("["))
|
|
582
|
-
break;
|
|
583
|
-
if (trimmed.length > 0 && !trimmed.startsWith("#"))
|
|
584
|
-
return appendBlock(contents, block, lineEnding);
|
|
585
|
-
}
|
|
586
|
-
const rawLines = contents.split(/(?<=\n)/);
|
|
587
|
-
const head = rawLines.slice(0, anchor + 1).join("");
|
|
588
|
-
const tail = rawLines.slice(anchor + 1).join("");
|
|
589
|
-
const appended = appendBlock(contents, block, lineEnding);
|
|
590
|
-
if (tail.length === 0)
|
|
591
|
-
return appended;
|
|
592
|
-
const headWithEnding = head.endsWith("\n") ? head : `${head}${lineEnding}`;
|
|
593
|
-
const body = block.endsWith(lineEnding) ? block : `${block}${lineEnding}`;
|
|
594
|
-
const tailSeparator = /^\r?\n/.test(tail) ? "" : lineEnding;
|
|
595
|
-
const inserted = `${headWithEnding}${lineEnding}${body}${tailSeparator}${tail}`;
|
|
596
|
-
return sameTomlIgnoringHookOrder(inserted, appended) ? inserted : appended;
|
|
597
|
-
}
|
|
598
|
-
function sameTomlIgnoringHookOrder(a, b) {
|
|
599
|
-
const canonical = (text) => {
|
|
600
|
-
const parsed = parseToml(text);
|
|
601
|
-
const hooks = Array.isArray(parsed.hooks)
|
|
602
|
-
? parsed.hooks.map((entry) => JSON.stringify(entry)).sort()
|
|
603
|
-
: parsed.hooks;
|
|
604
|
-
return JSON.stringify({ ...parsed, hooks });
|
|
605
|
-
};
|
|
606
|
-
try {
|
|
607
|
-
return canonical(a) === canonical(b);
|
|
608
|
-
}
|
|
609
|
-
catch {
|
|
610
|
-
return false;
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
function appendBlock(contents, block, lineEnding) {
|
|
614
|
-
const base = contents.length === 0 || contents.endsWith(lineEnding) ? contents : `${contents}${lineEnding}`;
|
|
615
|
-
const separator = base.length === 0 ? "" : lineEnding;
|
|
616
|
-
const body = block.endsWith(lineEnding) ? block : `${block}${lineEnding}`;
|
|
617
|
-
return `${base}${separator}${body}`;
|
|
618
|
-
}
|
|
619
|
-
function splitPreservingEnding(contents) {
|
|
620
|
-
// We canonicalize to '\n' for the split, then strip any '\r' that
|
|
621
|
-
// came from CRLF. Rejoining is the caller's responsibility (they
|
|
622
|
-
// pass the desired line ending).
|
|
623
|
-
return contents.split("\n").map((line) => line.replace(/\r$/, ""));
|
|
624
|
-
}
|
|
625
|
-
// A partial upstream hooks-array rewrite can leave one marker comment behind.
|
|
626
|
-
// Remove only unpaired marker comments, never the intervening content. The
|
|
627
|
-
// normal full-file validation still gates writes.
|
|
628
|
-
function removeOrphanMarkers(contents) {
|
|
629
|
-
const remove = new Set(pairBlocks(splitPreservingEnding(contents)).orphans.map((marker) => marker.line));
|
|
630
|
-
return remove.size === 0
|
|
631
|
-
? { contents, count: 0 }
|
|
632
|
-
: { contents: removeLines(contents, remove), count: remove.size };
|
|
633
|
-
}
|
|
634
|
-
/**
|
|
635
|
-
* Remove managed blocks owned by `currentHost`, or every host with `removeAll`.
|
|
636
|
-
* Ownership comes from the marker suffix or a legacy command's derived host.
|
|
637
|
-
* Orphan markers are removed individually so surrounding user content survives.
|
|
638
|
-
*/
|
|
639
|
-
function stripManagedBlocks(contents, currentHost, removeAll) {
|
|
640
|
-
const lines = splitPreservingEnding(contents);
|
|
641
|
-
const { blocks, orphans } = pairBlocks(lines);
|
|
642
|
-
// Suffixed blocks belong only to the matching host. Complete legacy blocks
|
|
643
|
-
// use their command-derived host; an unattributable non-canonical command is
|
|
644
|
-
// ambiguous and only --all removes it. Orphan marker lines have no command
|
|
645
|
-
// and can be swept individually by a scoped uninstall.
|
|
646
|
-
const shouldRemove = (markerHost, commandPath, isOrphanMarker) => {
|
|
647
|
-
if (removeAll)
|
|
648
|
-
return true;
|
|
649
|
-
if (markerHost !== null)
|
|
650
|
-
return markerHost === currentHost;
|
|
651
|
-
if (isOrphanMarker)
|
|
652
|
-
return true;
|
|
653
|
-
const derived = commandPath !== null ? hostIdFromHookCommand(commandPath) : null;
|
|
654
|
-
if (derived === null)
|
|
655
|
-
return false;
|
|
656
|
-
return derived === currentHost;
|
|
657
|
-
};
|
|
658
|
-
const orphansLeft = orphans
|
|
659
|
-
.filter((orphan) => shouldRemove(orphan.hostId, null, true))
|
|
660
|
-
.map((orphan) => orphan.line);
|
|
661
|
-
const remove = new Set(orphansLeft);
|
|
662
|
-
let removedBlocks = 0;
|
|
663
|
-
for (const block of blocks) {
|
|
664
|
-
// Attribute by the LAST command line in the body, even one after a line
|
|
665
|
-
// that makes the block invalid (unlike the validator's commandPath).
|
|
666
|
-
let blockCommand = null;
|
|
667
|
-
for (const line of lines.slice(block.beginLine + 1, block.endLine)) {
|
|
668
|
-
blockCommand = decodeManagedCommandLine(line.trim()) ?? blockCommand;
|
|
669
|
-
}
|
|
670
|
-
if (!shouldRemove(block.hostId, blockCommand, false))
|
|
671
|
-
continue;
|
|
672
|
-
removedBlocks += 1;
|
|
673
|
-
for (let i = block.beginLine; i <= block.endLine; i += 1)
|
|
674
|
-
remove.add(i);
|
|
675
|
-
}
|
|
676
|
-
return { stripped: removeLines(contents, remove), removedBlocks, orphansLeft };
|
|
677
|
-
}
|
|
678
|
-
function removeLines(contents, remove) {
|
|
679
|
-
return contents.split(/(?<=\n)/).filter((_, index) => !remove.has(index)).join("");
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
* Remove orphaned, marker-less `[[hooks]]` tables that are unambiguously this
|
|
683
|
-
* plugin's approval hook (see `findUnmanagedApprovalHookBlocks`). Returns the
|
|
684
|
-
* cleaned text, the count removed, and the decoded commands of the removed
|
|
685
|
-
* tables (so install can distinguish "re-adorning this host's live hook after
|
|
686
|
-
* a kimi-code comment strip" from "sweeping stale cruft"). A no-op (returns
|
|
687
|
-
* the input unchanged) when there is nothing to prune, so callers can compare
|
|
688
|
-
* identity cheaply.
|
|
689
|
-
*
|
|
690
|
-
* `ownedBy` restricts the prune to tables whose command path derives to that
|
|
691
|
-
* host — REQUIRED for scoped install/uninstall so one host never disarms the
|
|
692
|
-
* other's live (marker-stripped) hook. Omit only for `--uninstall --all`.
|
|
693
|
-
*/
|
|
694
|
-
function pruneOrphanApprovalHooks(contents, ownedBy, alsoMatchCommand) {
|
|
695
|
-
const ranges = findUnmanagedApprovalHookBlocks(contents, ownedBy, alsoMatchCommand);
|
|
696
|
-
if (ranges.length === 0)
|
|
697
|
-
return { pruned: contents, count: 0, commands: [] };
|
|
698
|
-
const remove = new Set();
|
|
699
|
-
for (const { start, end } of ranges) {
|
|
700
|
-
for (let i = start; i < end; i += 1)
|
|
701
|
-
remove.add(i);
|
|
702
|
-
}
|
|
703
|
-
const lines = contents.split(/(?<=\n)/);
|
|
704
|
-
const kept = lines.filter((_, idx) => !remove.has(idx));
|
|
705
|
-
return {
|
|
706
|
-
pruned: kept.join(""),
|
|
707
|
-
count: ranges.length,
|
|
708
|
-
commands: ranges.map((range) => range.command),
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
// ----- Block content -----------------------------------------------------
|
|
712
|
-
function buildManagedBlock(shellCommand, lineEnding = "\n", hostId = "") {
|
|
713
|
-
const commandLine = `command = ${tomlBasicString(shellCommand)}`;
|
|
714
|
-
const suffix = hostId.length > 0 ? `:${hostId}` : "";
|
|
715
|
-
return [
|
|
716
|
-
`${BEGIN_MARKER_PREFIX}${suffix} (v${KIMI_PLUGIN_CC_VERSION}) ===`,
|
|
717
|
-
`# DO NOT EDIT — managed by /kimi:setup. Run /kimi:setup --uninstall to remove.`,
|
|
718
|
-
`# Host: ${hostId.length > 0 ? hostId : "(legacy)"} — each host owns a separate block in this shared`,
|
|
719
|
-
`# ~/.kimi-code/config.toml. Scoped setup/uninstall preserves other hosts;`,
|
|
720
|
-
`# /kimi:setup --uninstall --all removes every host's block.`,
|
|
721
|
-
`# Purpose:`,
|
|
722
|
-
`# kimi-code's \`kimi -p\` mode hard-codes permission='auto' and`,
|
|
723
|
-
`# auto-approves every tool call. This hook enforces each managed command's`,
|
|
724
|
-
`# read-only or workspace-bound approval policy. Without this block,`,
|
|
725
|
-
`# the plugin's safety contract collapses.`,
|
|
726
|
-
`# Matcher field is intentionally OMITTED — kimi-code compiles the`,
|
|
727
|
-
`# matcher with \`new RegExp(...)\`. An empty/missing matcher means`,
|
|
728
|
-
`# "fire for every tool". The string "*" would throw and silently`,
|
|
729
|
-
`# disable the hook. Do not "fix" this.`,
|
|
730
|
-
`# The Node binary path is absolute so kimi-code's \`/bin/sh -c\``,
|
|
731
|
-
`# hook spawn doesn't need \`node\` on its PATH (GUI launches,`,
|
|
732
|
-
`# LaunchAgents, etc.).`,
|
|
733
|
-
`[[hooks]]`,
|
|
734
|
-
`event = "PreToolUse"`,
|
|
735
|
-
commandLine,
|
|
736
|
-
`timeout = ${DEFAULT_HOOK_TIMEOUT_S}`,
|
|
737
|
-
`# === END kimi-plugin-cc-managed${suffix} ===`,
|
|
738
|
-
].join(lineEnding);
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* Encode a TOML basic string, including quotes, backslashes, and control
|
|
742
|
-
* escapes. Raw shell output must not be interpolated directly: TOML reserves
|
|
743
|
-
* `\'`, and a compliant parser rejects that escape.
|
|
744
|
-
*/
|
|
745
|
-
function tomlBasicString(value) {
|
|
746
|
-
const escaped = value
|
|
747
|
-
.replaceAll("\\", "\\\\")
|
|
748
|
-
.replaceAll("\"", "\\\"")
|
|
749
|
-
.replaceAll("\b", "\\b")
|
|
750
|
-
.replaceAll("\t", "\\t")
|
|
751
|
-
.replaceAll("\n", "\\n")
|
|
752
|
-
.replaceAll("\f", "\\f")
|
|
753
|
-
.replaceAll("\r", "\\r");
|
|
754
|
-
return `"${escaped}"`;
|
|
755
|
-
}
|
|
756
|
-
function assertHookPathTomlSafe(hookScriptPath) {
|
|
757
|
-
if (!PATH_FORBIDDEN_RE.test(hookScriptPath))
|
|
758
|
-
return;
|
|
759
|
-
throw new RuntimeError("SETUP_HOOK_PATH_UNSAFE", [
|
|
760
|
-
`Hook script path ${JSON.stringify(hookScriptPath)} contains characters`,
|
|
761
|
-
`(control chars, quotes, backslashes, or newlines) that cannot be safely`,
|
|
762
|
-
`written into kimi-code's TOML config. Set KIMI_PLUGIN_CC_HOOK_SCRIPT`,
|
|
763
|
-
`to an unambiguous absolute path or reinstall the plugin to a location`,
|
|
764
|
-
`without these characters.`,
|
|
765
|
-
].join(" "), "setup.hook-path", { details: { hookScriptPath } });
|
|
766
|
-
}
|
|
767
|
-
// ----- Path resolution ---------------------------------------------------
|
|
768
|
-
async function assertHookScriptExists(hookScriptPath) {
|
|
769
|
-
try {
|
|
770
|
-
await access(hookScriptPath, fsConstants.R_OK);
|
|
771
|
-
}
|
|
772
|
-
catch (err) {
|
|
773
|
-
throw new RuntimeError("SETUP_HOOK_SCRIPT_MISSING", `Hook script ${hookScriptPath} is missing or unreadable. Reinstall the plugin so dist/hooks/approval-hook.js is present.`, "setup.hook-script", err instanceof Error ? { cause: err, details: { hookScriptPath } } : { details: { hookScriptPath } });
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
/**
|
|
777
|
-
* Two-layer probe; both layers require exit 2 and a non-empty denial reason.
|
|
778
|
-
*
|
|
779
|
-
* 1. Directly spawn the hook with the absolute Node path parsed back from
|
|
780
|
-
* `command`, catching missing/broken scripts and incorrect hook exit
|
|
781
|
-
* behavior without relying on PATH.
|
|
782
|
-
* 2. Execute `command`, the exact canonical bytes from buildHookShellCommand,
|
|
783
|
-
* through `/bin/sh -c`: two shell-quoted absolute tokens for Node and the
|
|
784
|
-
* script.
|
|
785
|
-
* This catches pinned-interpreter execution and quoting failures. It does
|
|
786
|
-
* NOT test PATH discovery or compatibility of some other `node` on PATH.
|
|
787
|
-
*
|
|
788
|
-
* The shell layer is skipped where `/bin/sh` is unsupported; the runtime
|
|
789
|
-
* otherwise assumes POSIX.
|
|
790
|
-
*/
|
|
791
|
-
async function probeHook(hookScriptPath, command, env) {
|
|
792
|
-
const directResult = await probeHookDirect(hookScriptPath, command, env);
|
|
793
|
-
if (!directResult.ok)
|
|
794
|
-
return directResult;
|
|
795
|
-
const shellResult = await probeHookViaShell(command, env);
|
|
796
|
-
if (!shellResult.ok)
|
|
797
|
-
return shellResult;
|
|
798
|
-
return {
|
|
799
|
-
ok: true,
|
|
800
|
-
reason: `${directResult.reason}; shell probe also ok`,
|
|
801
|
-
};
|
|
802
|
-
}
|
|
803
|
-
async function probeHookDirect(hookScriptPath, command, env) {
|
|
804
|
-
// Parsed back from the command, never re-resolved; the fallback is unreachable.
|
|
805
|
-
const nodeBin = parseHookShellCommand(command)?.nodeBin ?? resolveNodeBinary(env);
|
|
806
|
-
return await spawnProbe(nodeBin, [hookScriptPath], env, `direct probe via ${nodeBin}`);
|
|
807
|
-
}
|
|
808
|
-
async function probeHookViaShell(shellCommand, env) {
|
|
809
|
-
if (process.platform === "win32") {
|
|
810
|
-
// The hook runner shells out via `/bin/sh -c` per agent-core; on
|
|
811
|
-
// Windows the entire kimi-code launcher is unsupported. Skip the
|
|
812
|
-
// shell probe so we don't false-fail on a platform we don't run on.
|
|
813
|
-
return { ok: true, reason: "shell probe skipped (Windows)" };
|
|
814
|
-
}
|
|
815
|
-
// The exact command string the managed block wrote into kimi-code's config,
|
|
816
|
-
// so probe and runtime cannot drift.
|
|
817
|
-
return await spawnProbe("/bin/sh", ["-c", shellCommand], env, `shell probe via /bin/sh -c`);
|
|
818
|
-
}
|
|
819
|
-
function spawnProbe(command, args, env, label) {
|
|
820
|
-
const payload = JSON.stringify({
|
|
821
|
-
hook_event_name: "PreToolUse",
|
|
822
|
-
session_id: "kimi-plugin-cc-setup-probe",
|
|
823
|
-
cwd: process.cwd(),
|
|
824
|
-
tool_name: "Bash",
|
|
825
|
-
tool_input: { command: "echo probe" },
|
|
826
|
-
tool_call_id: "probe-1",
|
|
827
|
-
});
|
|
828
|
-
return new Promise((resolve) => {
|
|
829
|
-
let child;
|
|
830
|
-
try {
|
|
831
|
-
child = spawn(command, args, {
|
|
832
|
-
env: {
|
|
833
|
-
...env,
|
|
834
|
-
KIMI_PLUGIN_CC_CMD: "review",
|
|
835
|
-
KIMI_PLUGIN_CC_SKIP_HOOK_CHECK: "1",
|
|
836
|
-
},
|
|
837
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
838
|
-
});
|
|
839
|
-
}
|
|
840
|
-
catch (err) {
|
|
841
|
-
resolve({ ok: false, reason: `${label}: spawn failed: ${err.message}` });
|
|
842
|
-
return;
|
|
843
|
-
}
|
|
844
|
-
let stdout = "";
|
|
845
|
-
let stderr = "";
|
|
846
|
-
child.stdout?.setEncoding("utf8");
|
|
847
|
-
child.stderr?.setEncoding("utf8");
|
|
848
|
-
child.stdout?.on("data", (chunk) => {
|
|
849
|
-
stdout += chunk;
|
|
850
|
-
});
|
|
851
|
-
child.stderr?.on("data", (chunk) => {
|
|
852
|
-
stderr += chunk;
|
|
853
|
-
});
|
|
854
|
-
const timer = setTimeout(() => {
|
|
855
|
-
try {
|
|
856
|
-
child.kill("SIGKILL");
|
|
857
|
-
}
|
|
858
|
-
catch {
|
|
859
|
-
}
|
|
860
|
-
resolve({
|
|
861
|
-
ok: false,
|
|
862
|
-
reason: `${label}: timed out after ${PROBE_TIMEOUT_MS}ms (no exit). stderr: ${truncate(stderr, 200)}`,
|
|
863
|
-
});
|
|
864
|
-
}, PROBE_TIMEOUT_MS);
|
|
865
|
-
timer.unref();
|
|
866
|
-
child.on("error", (err) => {
|
|
867
|
-
clearTimeout(timer);
|
|
868
|
-
resolve({ ok: false, reason: `${label}: process error: ${err.message}` });
|
|
869
|
-
});
|
|
870
|
-
child.on("close", (code) => {
|
|
871
|
-
clearTimeout(timer);
|
|
872
|
-
const stderrTrimmed = stderr.trim();
|
|
873
|
-
if (code === 2 && stderrTrimmed.length > 0) {
|
|
874
|
-
resolve({ ok: true, reason: `${label}: deny reason captured (${stderrTrimmed.slice(0, 80)}…)` });
|
|
875
|
-
}
|
|
876
|
-
else {
|
|
877
|
-
resolve({
|
|
878
|
-
ok: false,
|
|
879
|
-
reason: `${label}: expected exit 2 with deny reason, got exit ${code ?? "<null>"}. stdout=${truncate(stdout, 120)} stderr=${truncate(stderrTrimmed, 200)}`,
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
});
|
|
883
|
-
try {
|
|
884
|
-
child.stdin?.write(payload);
|
|
885
|
-
child.stdin?.end();
|
|
886
|
-
}
|
|
887
|
-
catch (err) {
|
|
888
|
-
clearTimeout(timer);
|
|
889
|
-
resolve({ ok: false, reason: `${label}: failed to write probe stdin: ${err.message}` });
|
|
890
|
-
}
|
|
891
|
-
});
|
|
892
|
-
}
|
|
893
|
-
function truncate(value, max) {
|
|
894
|
-
if (value.length <= max)
|
|
895
|
-
return value;
|
|
896
|
-
return `${value.slice(0, max)}…`;
|
|
897
|
-
}
|
|
898
|
-
// ----- Plugin-owned kimi-code (--install-kimi) ---------------------------
|
|
899
|
-
const KIMI_PACKAGE = "@moonshot-ai/kimi-code";
|
|
900
|
-
const KIMI_INSTALL_TIMEOUT_MS = 300_000;
|
|
901
|
-
const KIMI_INSTALL_KILL_GRACE_MS = 2_000;
|
|
902
|
-
// First start of a fresh install loads a large bundle; allow more than the
|
|
903
|
-
// 5s job-time probe.
|
|
904
|
-
const KIMI_INSTALL_PROBE_TIMEOUT_MS = 30_000;
|
|
905
|
-
const STDERR_TAIL_BYTES = 2_000;
|
|
906
|
-
const STAGING_PREFIX = ".staging-";
|
|
907
|
-
// A staging directory younger than this may belong to a concurrent install
|
|
908
|
-
// still inside its npm timeout and probe window, so it is not stale yet.
|
|
909
|
-
const STALE_STAGING_AGE_MS = 2 * (KIMI_INSTALL_TIMEOUT_MS + KIMI_INSTALL_PROBE_TIMEOUT_MS);
|
|
910
|
-
/** Numeric, not lexical: "2.10.0" is above "2.9.0". */
|
|
911
|
-
export function highestCertifiedKimiVersion(versions = NATIVE_V2_CERTIFIED_VERSIONS) {
|
|
912
|
-
const parse = (v) => v.split(".").map(Number);
|
|
913
|
-
const sorted = [...versions].sort((a, b) => {
|
|
914
|
-
const [x, y] = [parse(a), parse(b)];
|
|
915
|
-
for (let i = 0; i < 3; i += 1) {
|
|
916
|
-
if (x[i] !== y[i])
|
|
917
|
-
return (x[i] ?? 0) - (y[i] ?? 0);
|
|
918
|
-
}
|
|
919
|
-
return 0;
|
|
920
|
-
});
|
|
921
|
-
const highest = sorted[sorted.length - 1];
|
|
922
|
-
if (highest === undefined || !/^\d+\.\d+\.\d+$/.test(highest)) {
|
|
923
|
-
throw new RuntimeError("KIMI_INSTALL_FAILED", "No exact certified kimi-code version is available to install.", "setup.install-kimi");
|
|
924
|
-
}
|
|
925
|
-
return highest;
|
|
926
|
-
}
|
|
927
|
-
function compareExactVersions(a, b) {
|
|
928
|
-
const [x, y] = [a.split(".").map(Number), b.split(".").map(Number)];
|
|
929
|
-
for (let i = 0; i < 3; i += 1) {
|
|
930
|
-
if (x[i] !== y[i])
|
|
931
|
-
return (x[i] ?? 0) - (y[i] ?? 0);
|
|
932
|
-
}
|
|
933
|
-
return 0;
|
|
934
|
-
}
|
|
935
|
-
async function runInstallKimi(json, context) {
|
|
936
|
-
let version = "";
|
|
937
|
-
try {
|
|
938
|
-
version = highestCertifiedKimiVersion();
|
|
939
|
-
const outcome = await installPluginOwnedKimi(version, context.env);
|
|
940
|
-
const selection = selectKimiBinary(context.env);
|
|
941
|
-
const jobsUseIt = selection.source === "plugin-owned" && selection.command === outcome.binary;
|
|
942
|
-
const summary = outcome.downloaded
|
|
943
|
-
? `Installed kimi-code ${version} for kimi-plugin-cc.`
|
|
944
|
-
: `kimi-code ${version} is already installed for kimi-plugin-cc; nothing was downloaded.`;
|
|
945
|
-
const jobsLine = jobsUseIt
|
|
946
|
-
? "Jobs will now use this binary."
|
|
947
|
-
: selection.source === "override"
|
|
948
|
-
? `KIMI_PLUGIN_CC_KIMI_BIN is set, so jobs keep using ${selection.command} until it is unset.`
|
|
949
|
-
: `Jobs do not use this binary yet: ${selection.pluginOwned.reason ?? "selection did not pick it"}.`;
|
|
950
|
-
return installKimiResult({
|
|
951
|
-
summary,
|
|
952
|
-
failed: false,
|
|
953
|
-
details: [
|
|
954
|
-
`Version: ${version}`,
|
|
955
|
-
`Binary: ${outcome.binary}`,
|
|
956
|
-
`Current link: ${outcome.current} -> ${path.join(version, "node_modules", ".bin", "kimi")}`,
|
|
957
|
-
`Jobs: ${jobsLine}`,
|
|
958
|
-
],
|
|
959
|
-
nextStep: jobsUseIt
|
|
960
|
-
? "Run /kimi:setup --check to confirm the hook and the selected binary."
|
|
961
|
-
: "Unset KIMI_PLUGIN_CC_KIMI_BIN to use the plugin-owned binary, then run /kimi:setup --check.",
|
|
962
|
-
report: {
|
|
963
|
-
ok: true,
|
|
964
|
-
json,
|
|
965
|
-
version,
|
|
966
|
-
downloaded: outcome.downloaded,
|
|
967
|
-
binary: outcome.binary,
|
|
968
|
-
current: outcome.current,
|
|
969
|
-
selectedBinary: selection.command,
|
|
970
|
-
selectedSource: selection.source,
|
|
971
|
-
},
|
|
972
|
-
});
|
|
973
|
-
}
|
|
974
|
-
catch (error) {
|
|
975
|
-
const runtimeError = error instanceof RuntimeError
|
|
976
|
-
? error
|
|
977
|
-
: new RuntimeError("KIMI_INSTALL_FAILED", error instanceof Error ? error.message : String(error), "setup.install-kimi");
|
|
978
|
-
return installKimiResult({
|
|
979
|
-
summary: `Failed to install kimi-code${version ? ` ${version}` : ""} for kimi-plugin-cc; the selected binary is unchanged.`,
|
|
980
|
-
failed: true,
|
|
981
|
-
probeError: `[${runtimeError.code}] ${runtimeError.message}`,
|
|
982
|
-
details: [`Error: [${runtimeError.code}] ${runtimeError.message}`],
|
|
983
|
-
nextStep: "Fix the cause above and re-run setup --install-kimi. Jobs keep using the previously selected binary.",
|
|
984
|
-
report: {
|
|
985
|
-
ok: false,
|
|
986
|
-
json,
|
|
987
|
-
version,
|
|
988
|
-
downloaded: false,
|
|
989
|
-
error: { code: runtimeError.code, message: runtimeError.message, details: runtimeError.details },
|
|
990
|
-
},
|
|
991
|
-
});
|
|
992
|
-
}
|
|
993
|
-
}
|
|
994
|
-
function installKimiResult(args) {
|
|
995
|
-
return {
|
|
996
|
-
action: "install-kimi",
|
|
997
|
-
summary: args.summary,
|
|
998
|
-
configPath: "",
|
|
999
|
-
hookScriptPath: "",
|
|
1000
|
-
blockWritten: false,
|
|
1001
|
-
blockRemoved: false,
|
|
1002
|
-
// "failed" makes the companion exit 1; the hook itself is not probed here.
|
|
1003
|
-
probe: args.failed ? "failed" : "skipped",
|
|
1004
|
-
probeError: args.probeError,
|
|
1005
|
-
warnings: [],
|
|
1006
|
-
reviewGateEnabled: false,
|
|
1007
|
-
nextStep: args.nextStep,
|
|
1008
|
-
details: args.details,
|
|
1009
|
-
kimiInstall: args.report,
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
/**
|
|
1013
|
-
* Install exactly `version` into `<data root>/kimi-plugin-cc/kimi-bin/<version>/` and point
|
|
1014
|
-
* `current` at it. A verified existing install is reused without network
|
|
1015
|
-
* access. Downloads stage in a sibling directory that is verified with the
|
|
1016
|
-
* exact-version probe before it is renamed into place; any failure removes
|
|
1017
|
-
* the staging directory and leaves `current` untouched.
|
|
1018
|
-
*/
|
|
1019
|
-
async function installPluginOwnedKimi(version, env) {
|
|
1020
|
-
if (process.platform === "win32") {
|
|
1021
|
-
throw new RuntimeError("KIMI_INSTALL_UNSUPPORTED_PLATFORM", "setup --install-kimi is not supported on Windows. Install kimi-code yourself and set KIMI_PLUGIN_CC_KIMI_BIN to its path.", "setup.install-kimi");
|
|
1022
|
-
}
|
|
1023
|
-
const binDir = resolveKimiBinDir(env);
|
|
1024
|
-
await mkdir(binDir, { recursive: true });
|
|
1025
|
-
await removeStaleStaging(binDir);
|
|
1026
|
-
const versionDir = path.join(binDir, version);
|
|
1027
|
-
const binRelative = path.join(version, "node_modules", ".bin", "kimi");
|
|
1028
|
-
const binPath = path.join(binDir, binRelative);
|
|
1029
|
-
const currentPath = path.join(binDir, "current");
|
|
1030
|
-
const existing = await verifyKimiBinary(binPath, binDir, version, version, env);
|
|
1031
|
-
if (existing.ok) {
|
|
1032
|
-
await pointCurrentAt(binDir, binRelative, currentPath, env);
|
|
1033
|
-
return { version, downloaded: false, binary: await realpath(binPath), current: currentPath };
|
|
1034
|
-
}
|
|
1035
|
-
const staging = await mkdtemp(path.join(binDir, `${STAGING_PREFIX}${version}-`));
|
|
1036
|
-
let trash;
|
|
1037
|
-
try {
|
|
1038
|
-
await writeFile(path.join(staging, "package.json"), `${JSON.stringify({ name: "kimi-plugin-cc-kimi-bin", private: true })}\n`, "utf8");
|
|
1039
|
-
await runNpmInstall(staging, version, env);
|
|
1040
|
-
const staged = await verifyKimiBinary(path.join(staging, "node_modules", ".bin", "kimi"), binDir, path.basename(staging), version, env);
|
|
1041
|
-
if (!staged.ok) {
|
|
1042
|
-
throw new RuntimeError("KIMI_INSTALL_VERIFY_FAILED", `The installed kimi-code did not verify as exactly ${version}: ${staged.reason}.`, "setup.install-kimi", { details: { expected_version: version } });
|
|
1043
|
-
}
|
|
1044
|
-
if (await pathExists(versionDir)) {
|
|
1045
|
-
// A present but unverifiable version directory is set aside, not reused.
|
|
1046
|
-
trash = path.join(binDir, `.trash-${version}-${randomBytes(4).toString("hex")}`);
|
|
1047
|
-
await rename(versionDir, trash);
|
|
1048
|
-
}
|
|
1049
|
-
try {
|
|
1050
|
-
await rename(staging, versionDir);
|
|
1051
|
-
}
|
|
1052
|
-
catch (error) {
|
|
1053
|
-
if (trash) {
|
|
1054
|
-
await rename(trash, versionDir).catch(() => undefined);
|
|
1055
|
-
trash = undefined;
|
|
1056
|
-
}
|
|
1057
|
-
throw error;
|
|
1058
|
-
}
|
|
1059
|
-
await pointCurrentAt(binDir, binRelative, currentPath, env);
|
|
1060
|
-
return { version, downloaded: true, binary: await realpath(binPath), current: currentPath };
|
|
1061
|
-
}
|
|
1062
|
-
finally {
|
|
1063
|
-
await rm(staging, { recursive: true, force: true });
|
|
1064
|
-
if (trash)
|
|
1065
|
-
await rm(trash, { recursive: true, force: true });
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
/** Remove staging directories an interrupted install left directly in kimi-bin/. */
|
|
1069
|
-
async function removeStaleStaging(binDir, now = Date.now()) {
|
|
1070
|
-
let entries;
|
|
1071
|
-
try {
|
|
1072
|
-
entries = await readdir(binDir);
|
|
1073
|
-
}
|
|
1074
|
-
catch {
|
|
1075
|
-
return;
|
|
1076
|
-
}
|
|
1077
|
-
for (const name of entries) {
|
|
1078
|
-
if (!name.startsWith(STAGING_PREFIX))
|
|
1079
|
-
continue;
|
|
1080
|
-
const entry = path.join(binDir, name);
|
|
1081
|
-
try {
|
|
1082
|
-
const info = await lstat(entry);
|
|
1083
|
-
if (!info.isDirectory() || now - info.mtimeMs < STALE_STAGING_AGE_MS)
|
|
1084
|
-
continue;
|
|
1085
|
-
await rm(entry, { recursive: true, force: true });
|
|
1086
|
-
}
|
|
1087
|
-
catch {
|
|
1088
|
-
// Best effort: a leftover never affects binary resolution.
|
|
1089
|
-
}
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
/**
|
|
1093
|
-
* Containment comes before execution: `binary` must resolve to an executable
|
|
1094
|
-
* regular file physically inside `<realpath(binDir)>/<dirName>/`, and only
|
|
1095
|
-
* that resolved path is probed. Anchoring at the real kimi-bin plus the
|
|
1096
|
-
* expected name rejects a version or staging directory that is itself a link.
|
|
1097
|
-
*/
|
|
1098
|
-
async function verifyKimiBinary(binary, binDir, dirName, version, env) {
|
|
1099
|
-
let resolved;
|
|
1100
|
-
let root;
|
|
1101
|
-
try {
|
|
1102
|
-
resolved = await realpath(binary);
|
|
1103
|
-
root = path.join(await realpath(binDir), dirName);
|
|
1104
|
-
}
|
|
1105
|
-
catch {
|
|
1106
|
-
return { ok: false, reason: `${binary} is missing` };
|
|
1107
|
-
}
|
|
1108
|
-
if (!resolved.startsWith(`${root}${path.sep}`)) {
|
|
1109
|
-
return { ok: false, reason: `${binary} resolves to ${resolved}, outside ${root}${path.sep}` };
|
|
1110
|
-
}
|
|
1111
|
-
try {
|
|
1112
|
-
const info = await lstat(resolved);
|
|
1113
|
-
if (!info.isFile())
|
|
1114
|
-
return { ok: false, reason: `${resolved} is not a regular file` };
|
|
1115
|
-
await access(resolved, fsConstants.X_OK);
|
|
1116
|
-
}
|
|
1117
|
-
catch {
|
|
1118
|
-
return { ok: false, reason: `${resolved} is not executable` };
|
|
1119
|
-
}
|
|
1120
|
-
const probe = await probeKimiVersion({ kimiBin: resolved, env, timeoutMs: KIMI_INSTALL_PROBE_TIMEOUT_MS });
|
|
1121
|
-
if (probe.kind !== "ok")
|
|
1122
|
-
return { ok: false, reason: probe.reason };
|
|
1123
|
-
const observed = probe.version.replace(/^v/, "");
|
|
1124
|
-
return observed === version ? { ok: true } : { ok: false, reason: `\`--version\` reported ${probe.version}` };
|
|
1125
|
-
}
|
|
1126
|
-
/**
|
|
1127
|
-
* Atomically replace `current` (POSIX rename over the old link), then confirm
|
|
1128
|
-
* binary resolution accepts the new link; otherwise restore the old one.
|
|
1129
|
-
*/
|
|
1130
|
-
async function pointCurrentAt(binDir, binRelative, currentPath, env) {
|
|
1131
|
-
let previous;
|
|
1132
|
-
try {
|
|
1133
|
-
previous = await readlink(currentPath);
|
|
1134
|
-
}
|
|
1135
|
-
catch {
|
|
1136
|
-
previous = undefined;
|
|
1137
|
-
}
|
|
1138
|
-
if (previous === binRelative && inspectPluginOwnedKimi(env).status === "active")
|
|
1139
|
-
return;
|
|
1140
|
-
const swap = async (target) => {
|
|
1141
|
-
const temp = path.join(binDir, `.current-${randomBytes(4).toString("hex")}`);
|
|
1142
|
-
await symlink(target, temp);
|
|
1143
|
-
try {
|
|
1144
|
-
await rename(temp, currentPath);
|
|
1145
|
-
}
|
|
1146
|
-
catch (error) {
|
|
1147
|
-
await rm(temp, { force: true });
|
|
1148
|
-
throw error;
|
|
1149
|
-
}
|
|
1150
|
-
};
|
|
1151
|
-
await swap(binRelative);
|
|
1152
|
-
const state = inspectPluginOwnedKimi(env);
|
|
1153
|
-
if (state.status !== "active") {
|
|
1154
|
-
if (previous !== undefined)
|
|
1155
|
-
await swap(previous);
|
|
1156
|
-
else
|
|
1157
|
-
await rm(currentPath, { force: true });
|
|
1158
|
-
throw new RuntimeError("KIMI_INSTALL_VERIFY_FAILED", `The new ${currentPath} link was not accepted by binary resolution: ${state.reason ?? state.status}. The previous link was restored.`, "setup.install-kimi");
|
|
1159
|
-
}
|
|
1160
|
-
}
|
|
1161
|
-
async function runNpmInstall(prefix, version, env) {
|
|
1162
|
-
// Never a global install, whatever the caller's npm environment says.
|
|
1163
|
-
const npmEnv = { ...env };
|
|
1164
|
-
for (const key of Object.keys(npmEnv)) {
|
|
1165
|
-
if (/^npm_config_(global|location|prefix)$/i.test(key))
|
|
1166
|
-
delete npmEnv[key];
|
|
1167
|
-
}
|
|
1168
|
-
const args = [
|
|
1169
|
-
"install",
|
|
1170
|
-
"--prefix", prefix,
|
|
1171
|
-
"--no-global",
|
|
1172
|
-
// kimi-code's postinstall only acts on global installs and no runtime
|
|
1173
|
-
// dependency declares an install script.
|
|
1174
|
-
"--ignore-scripts",
|
|
1175
|
-
"--no-audit",
|
|
1176
|
-
"--no-fund",
|
|
1177
|
-
"--no-update-notifier",
|
|
1178
|
-
"--save-exact",
|
|
1179
|
-
`${KIMI_PACKAGE}@${version}`,
|
|
1180
|
-
];
|
|
1181
|
-
await new Promise((resolve, reject) => {
|
|
1182
|
-
let child;
|
|
1183
|
-
try {
|
|
1184
|
-
child = spawn("npm", args, { cwd: prefix, env: npmEnv, stdio: ["ignore", "ignore", "pipe"], detached: true });
|
|
1185
|
-
}
|
|
1186
|
-
catch (error) {
|
|
1187
|
-
reject(npmFailure(`could not start npm: ${error.message}`, version));
|
|
1188
|
-
return;
|
|
1189
|
-
}
|
|
1190
|
-
let stderr = "";
|
|
1191
|
-
child.stderr.setEncoding("utf8");
|
|
1192
|
-
child.stderr.on("data", (chunk) => {
|
|
1193
|
-
stderr = (stderr + chunk).slice(-STDERR_TAIL_BYTES);
|
|
1194
|
-
});
|
|
1195
|
-
let timedOut = false;
|
|
1196
|
-
const killGroup = (signal) => {
|
|
1197
|
-
try {
|
|
1198
|
-
if (child.pid !== undefined)
|
|
1199
|
-
process.kill(-child.pid, signal);
|
|
1200
|
-
}
|
|
1201
|
-
catch {
|
|
1202
|
-
}
|
|
1203
|
-
};
|
|
1204
|
-
const timer = setTimeout(() => {
|
|
1205
|
-
timedOut = true;
|
|
1206
|
-
killGroup("SIGTERM");
|
|
1207
|
-
setTimeout(() => killGroup("SIGKILL"), KIMI_INSTALL_KILL_GRACE_MS).unref();
|
|
1208
|
-
}, KIMI_INSTALL_TIMEOUT_MS);
|
|
1209
|
-
child.on("error", (error) => {
|
|
1210
|
-
clearTimeout(timer);
|
|
1211
|
-
reject(npmFailure(`could not start npm: ${error.message}`, version));
|
|
1212
|
-
});
|
|
1213
|
-
child.on("close", (code, signal) => {
|
|
1214
|
-
clearTimeout(timer);
|
|
1215
|
-
if (timedOut) {
|
|
1216
|
-
reject(npmFailure(`npm install timed out after ${KIMI_INSTALL_TIMEOUT_MS / 1000}s`, version, stderr));
|
|
1217
|
-
}
|
|
1218
|
-
else if (code !== 0) {
|
|
1219
|
-
reject(npmFailure(`npm install exited ${code ?? signal}`, version, stderr));
|
|
1220
|
-
}
|
|
1221
|
-
else {
|
|
1222
|
-
resolve();
|
|
1223
|
-
}
|
|
1224
|
-
});
|
|
1225
|
-
});
|
|
1226
|
-
}
|
|
1227
|
-
function npmFailure(reason, version, stderr = "") {
|
|
1228
|
-
return new RuntimeError("KIMI_INSTALL_FAILED", `Could not install ${KIMI_PACKAGE}@${version}: ${reason}.`, "setup.install-kimi", { details: { package: `${KIMI_PACKAGE}@${version}`, ...(stderr.trim() ? { npm_stderr_tail: stderr.trim() } : {}) } });
|
|
1229
|
-
}
|
|
1230
|
-
async function pathExists(target) {
|
|
1231
|
-
try {
|
|
1232
|
-
await access(target);
|
|
1233
|
-
return true;
|
|
1234
|
-
}
|
|
1235
|
-
catch {
|
|
1236
|
-
return false;
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
/** Which binary jobs will use and why, plus a note when the plugin-owned one is stale or unusable. */
|
|
1240
|
-
function describeKimiBinary(env, warnings) {
|
|
1241
|
-
const selection = selectKimiBinary(env);
|
|
1242
|
-
const owned = selection.pluginOwned;
|
|
1243
|
-
const highest = highestCertifiedKimiVersion();
|
|
1244
|
-
if (owned.status === "active" && owned.version && compareExactVersions(owned.version, highest) < 0) {
|
|
1245
|
-
warnings.push(`NOTE: the plugin-owned kimi-code ${owned.version} is behind the highest certified version ${highest}. Run setup --install-kimi to install ${highest}.`);
|
|
1246
|
-
}
|
|
1247
|
-
if (owned.status === "rejected") {
|
|
1248
|
-
warnings.push(`The plugin-owned kimi-code install is not used: ${owned.reason}. Run setup --install-kimi to repair it.`);
|
|
1249
|
-
}
|
|
1250
|
-
switch (selection.source) {
|
|
1251
|
-
case "override":
|
|
1252
|
-
return `${selection.command} (KIMI_PLUGIN_CC_KIMI_BIN override)`;
|
|
1253
|
-
case "plugin-owned":
|
|
1254
|
-
return `${selection.command} (plugin-owned kimi-code ${owned.version} from setup --install-kimi)`;
|
|
1255
|
-
case "path":
|
|
1256
|
-
return owned.status === "absent"
|
|
1257
|
-
? `kimi on PATH (no plugin-owned install; setup --install-kimi installs ${highest})`
|
|
1258
|
-
: `kimi on PATH (plugin-owned install ${owned.status}${owned.reason ? `: ${owned.reason}` : ""})`;
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
// ----- Permission rules scan --------------------------------------------
|
|
1262
|
-
/**
|
|
1263
|
-
* Warn only when the installed kimi is demonstrably outside the certified
|
|
1264
|
-
* range. Probe failure records nothing here because the hook probe reports the
|
|
1265
|
-
* more direct problem; setup may finish, but model spawn still refuses an
|
|
1266
|
-
* uncertified binary. KIMI_PLUGIN_CC_SKIP_VERSION_PROBE is a test/CI bypass,
|
|
1267
|
-
* not a production compatibility override.
|
|
1268
|
-
*/
|
|
1269
|
-
async function collectKimiVersionWarnings(env, warnings) {
|
|
1270
|
-
if (env.KIMI_PLUGIN_CC_SKIP_VERSION_PROBE === "1")
|
|
1271
|
-
return;
|
|
1272
|
-
// The same binary jobs select (override, plugin-owned, then PATH).
|
|
1273
|
-
const probe = await probeKimiVersion({
|
|
1274
|
-
kimiBin: selectKimiBinary(env).command,
|
|
1275
|
-
env,
|
|
1276
|
-
});
|
|
1277
|
-
if (probe.kind === "failed") {
|
|
1278
|
-
// Don't warn about probe failure here — if kimi is genuinely
|
|
1279
|
-
// missing/broken, the hook probe path will catch it with a much
|
|
1280
|
-
// clearer message. Avoid double-noise.
|
|
1281
|
-
return;
|
|
1282
|
-
}
|
|
1283
|
-
if (!probe.inTestedRange && !isNativeV2CertifiedVersion(probe.version)) {
|
|
1284
|
-
warnings.push(formatVersionOutOfRangeWarning(probe, KIMI_PLUGIN_CC_VERSION, NATIVE_V2_ANY_OPERATION_VERSIONS));
|
|
1285
|
-
return;
|
|
1286
|
-
}
|
|
1287
|
-
if (kimiReleaseHas(probe.version, "bounded-swarm")) {
|
|
1288
|
-
warnings.push(`NOTE: kimi-code ${probe.version} is certified for all operations. Swarm uses bounded waves with concurrency 2 or more, and one direct worker at concurrency 1. The finite job budget stops the whole run.`);
|
|
1289
|
-
return;
|
|
1290
|
-
}
|
|
1291
|
-
if (NATIVE_V2_NON_SWARM_VERSIONS.includes(probe.version)) {
|
|
1292
|
-
warnings.push(`NOTE: kimi-code ${probe.version} is certified for review, challenge, ask, rescue, review gate, and pursue only. Read-only swarm and write swarm refuse before model spawn on this exact release. Select exact kimi-code ${formatVersionChoice(kimiVersionsWith("bounded-swarm"))} for this plugin's certified bounded waves and single-worker path.`);
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
/**
|
|
1296
|
-
* Non-blocking notice for kimi-code's own enabled plugins from
|
|
1297
|
-
* ~/.kimi-code/plugins/installed.json. Their tools can register on every
|
|
1298
|
-
* session, but read-only commands deny everything outside READ_ONLY_TOOLS
|
|
1299
|
-
* (Read, Grep, Glob, ReadMediaFile, TaskList, TaskOutput), which can waste model
|
|
1300
|
-
* turns. Missing, unreadable, or malformed manifests produce no notice; setup
|
|
1301
|
-
* never blocks on or mutates the plugin list.
|
|
1302
|
-
*/
|
|
1303
|
-
async function collectInstalledKimiPluginsNotice(env, warnings) {
|
|
1304
|
-
const home = resolveKimiHome(env);
|
|
1305
|
-
const installedPath = path.join(home, "plugins", "installed.json");
|
|
1306
|
-
let raw;
|
|
1307
|
-
try {
|
|
1308
|
-
raw = await readFile(installedPath, "utf8");
|
|
1309
|
-
}
|
|
1310
|
-
catch {
|
|
1311
|
-
return; // ENOENT / unreadable — kimi-code's plugin system isn't in use here.
|
|
1312
|
-
}
|
|
1313
|
-
let enabledIds;
|
|
1314
|
-
try {
|
|
1315
|
-
const parsed = JSON.parse(raw);
|
|
1316
|
-
if (parsed === null || typeof parsed !== "object" || !Array.isArray(parsed.plugins)) {
|
|
1317
|
-
return;
|
|
1318
|
-
}
|
|
1319
|
-
enabledIds = parsed.plugins
|
|
1320
|
-
.filter((entry) => entry !== null && typeof entry === "object")
|
|
1321
|
-
// `enabled !== false` so an explicitly-disabled plugin is hidden while an
|
|
1322
|
-
// enabled or format-ambiguous one is surfaced (it can still register tools).
|
|
1323
|
-
.filter((entry) => entry.enabled !== false)
|
|
1324
|
-
.map((entry) => (typeof entry.id === "string" ? entry.id : ""))
|
|
1325
|
-
.filter((id) => id.length > 0);
|
|
1326
|
-
}
|
|
1327
|
-
catch {
|
|
1328
|
-
return; // Malformed JSON — don't guess.
|
|
1329
|
-
}
|
|
1330
|
-
if (enabledIds.length === 0)
|
|
1331
|
-
return;
|
|
1332
|
-
warnings.push([
|
|
1333
|
-
`NOTE: ${enabledIds.length} kimi-code plugin(s) installed and enabled: ${enabledIds.join(", ")}.`,
|
|
1334
|
-
" kimi-code registers their tools (including MCP) on every session. Under kimi-plugin-cc's",
|
|
1335
|
-
" read-only commands (/kimi:task, /kimi:review and the review gate) the",
|
|
1336
|
-
" PreToolUse hook denies any tool outside Read/Grep/Glob, so calls to these plugins' tools",
|
|
1337
|
-
" are blocked — safe, but they can waste model turns. This is expected; no action needed.",
|
|
1338
|
-
" (/kimi:task --write and /kimi:swarm apply their own allowlists.) To avoid the turn-waste, disable",
|
|
1339
|
-
" kimi-code plugins you don't need for delegated work in your kimi-code config.",
|
|
1340
|
-
].join("\n"));
|
|
1341
|
-
}
|
|
1342
|
-
/**
|
|
1343
|
-
* Best-effort line scan for permission rules that deny common read tools. This
|
|
1344
|
-
* is not a TOML parse: it recognizes basic and literal quoted strings but misses
|
|
1345
|
-
* inline-table and multiline forms.
|
|
1346
|
-
*/
|
|
1347
|
-
function collectPermissionRuleWarnings(contents, warnings) {
|
|
1348
|
-
const lines = contents.split("\n").map((line) => line.replace(/\r$/, ""));
|
|
1349
|
-
let inRule = false;
|
|
1350
|
-
let ruleStartLine = -1;
|
|
1351
|
-
let ruleDecision = "";
|
|
1352
|
-
let rulePattern = "";
|
|
1353
|
-
const flushRule = () => {
|
|
1354
|
-
if (!inRule)
|
|
1355
|
-
return;
|
|
1356
|
-
if (ruleDecision === "deny" && rulePattern.length > 0) {
|
|
1357
|
-
if (rulePattern === "*" ||
|
|
1358
|
-
/^\s*Read\b/.test(rulePattern) ||
|
|
1359
|
-
/^\s*Grep\b/.test(rulePattern) ||
|
|
1360
|
-
/^\s*Glob\b/.test(rulePattern)) {
|
|
1361
|
-
warnings.push(`permission.rules at line ${ruleStartLine + 1}: deny pattern "${rulePattern}" may block read-only commands; consider scoping the deny narrower.`);
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
inRule = false;
|
|
1365
|
-
ruleStartLine = -1;
|
|
1366
|
-
ruleDecision = "";
|
|
1367
|
-
rulePattern = "";
|
|
1368
|
-
};
|
|
1369
|
-
// Accept either double-quoted basic strings or single-quoted literal
|
|
1370
|
-
// strings for `decision` and `pattern`.
|
|
1371
|
-
const decisionRE = /^\s*decision\s*=\s*(?:"([^"]*)"|'([^']*)')/;
|
|
1372
|
-
const patternRE = /^\s*pattern\s*=\s*(?:"([^"]*)"|'([^']*)')/;
|
|
1373
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
1374
|
-
const line = lines[i];
|
|
1375
|
-
const trimmed = line.trim();
|
|
1376
|
-
if (trimmed === "[[permission.rules]]") {
|
|
1377
|
-
flushRule();
|
|
1378
|
-
inRule = true;
|
|
1379
|
-
ruleStartLine = i;
|
|
1380
|
-
continue;
|
|
1381
|
-
}
|
|
1382
|
-
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
1383
|
-
flushRule();
|
|
1384
|
-
continue;
|
|
1385
|
-
}
|
|
1386
|
-
if (!inRule)
|
|
1387
|
-
continue;
|
|
1388
|
-
const decisionMatch = decisionRE.exec(line);
|
|
1389
|
-
if (decisionMatch) {
|
|
1390
|
-
ruleDecision = decisionMatch[1] ?? decisionMatch[2] ?? "";
|
|
1391
|
-
continue;
|
|
1392
|
-
}
|
|
1393
|
-
const patternMatch = patternRE.exec(line);
|
|
1394
|
-
if (patternMatch) {
|
|
1395
|
-
rulePattern = patternMatch[1] ?? patternMatch[2] ?? "";
|
|
1396
|
-
continue;
|
|
1397
|
-
}
|
|
1398
|
-
}
|
|
1399
|
-
flushRule();
|
|
1400
|
-
}
|
|
1401
|
-
// ----- Detail rendering --------------------------------------------------
|
|
1402
|
-
function buildDetails(args) {
|
|
1403
|
-
const details = [
|
|
1404
|
-
`Companion runtime: Node ${process.version}`,
|
|
1405
|
-
`Plugin version: ${KIMI_PLUGIN_CC_VERSION}`,
|
|
1406
|
-
...(args.hostId ? [`Host id: ${args.hostId}`] : []),
|
|
1407
|
-
...(args.kimiBinary ? [`Kimi binary: ${args.kimiBinary}`] : []),
|
|
1408
|
-
`Config file: ${args.configPath}`,
|
|
1409
|
-
`Hook script: ${args.hookScriptPath}`,
|
|
1410
|
-
`Review gate: ${args.reviewGateEnabled ? "enabled" : "disabled"}`,
|
|
1411
|
-
`Probe: ${args.probe.ok ? "ok" : "failed"} — ${args.probe.reason}`,
|
|
1412
|
-
];
|
|
1413
|
-
if (args.warnings.length > 0) {
|
|
1414
|
-
details.push("Warnings:");
|
|
1415
|
-
for (const warning of args.warnings) {
|
|
1416
|
-
details.push(` - ${warning}`);
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
return details;
|
|
1420
|
-
}
|
|
1421
|
-
export function renderSetupResult(result) {
|
|
1422
|
-
if (result.kimiInstall)
|
|
1423
|
-
return renderInstallKimiResult(result, result.kimiInstall);
|
|
1424
|
-
return [
|
|
1425
|
-
result.summary,
|
|
1426
|
-
"",
|
|
1427
|
-
`Action: ${result.action}`,
|
|
1428
|
-
`Block written: ${result.blockWritten ? "yes" : "no"}`,
|
|
1429
|
-
`Block removed: ${result.blockRemoved ? "yes" : "no"}`,
|
|
1430
|
-
`Probe: ${result.probe}${result.probeError ? ` (${result.probeError})` : ""}`,
|
|
1431
|
-
`Review gate: ${result.reviewGateEnabled ? "enabled" : "disabled"}`,
|
|
1432
|
-
"",
|
|
1433
|
-
"Details:",
|
|
1434
|
-
...result.details.map((detail) => `- ${detail}`),
|
|
1435
|
-
"",
|
|
1436
|
-
`Next step: ${result.nextStep}`,
|
|
1437
|
-
"Models: run setup --models to list configured aliases and provider setup guidance without making a model call.",
|
|
1438
|
-
].join("\n");
|
|
1439
|
-
}
|
|
1440
|
-
function renderInstallKimiResult(result, report) {
|
|
1441
|
-
if (report.json) {
|
|
1442
|
-
return JSON.stringify({
|
|
1443
|
-
action: "install-kimi",
|
|
1444
|
-
ok: report.ok,
|
|
1445
|
-
version: report.version,
|
|
1446
|
-
downloaded: report.downloaded,
|
|
1447
|
-
binary: report.binary ?? null,
|
|
1448
|
-
current: report.current ?? null,
|
|
1449
|
-
selected_binary: report.selectedBinary ?? null,
|
|
1450
|
-
selected_source: report.selectedSource ?? null,
|
|
1451
|
-
error: report.error ?? null,
|
|
1452
|
-
next_step: result.nextStep,
|
|
1453
|
-
}, null, 2);
|
|
1454
|
-
}
|
|
1455
|
-
return [
|
|
1456
|
-
result.summary,
|
|
1457
|
-
"",
|
|
1458
|
-
`Action: ${result.action}`,
|
|
1459
|
-
"",
|
|
1460
|
-
"Details:",
|
|
1461
|
-
...result.details.map((detail) => `- ${detail}`),
|
|
1462
|
-
"",
|
|
1463
|
-
`Next step: ${result.nextStep}`,
|
|
1464
|
-
].join("\n");
|
|
1465
|
-
}
|