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,145 +1,1783 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
2
|
+
|
|
3
|
+
// runtime/read-scope.ts
|
|
4
|
+
import { lstat, realpath, stat } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
var READ_ROOTS_ENV = "KIMI_PLUGIN_CC_READ_ROOTS";
|
|
7
|
+
var NETWORK_ENV = "KIMI_PLUGIN_CC_NETWORK";
|
|
8
|
+
var READ_SCOPE_LABELS = new Set(["ask", "review", "challenge", "swarm"]);
|
|
9
|
+
var SCOPE_FLAGS_WRITE_MESSAGE = "--read-root and --network apply only to read-only operations (ask, review, challenge, read-only swarm). " + "Write-capable operations can read through allowlisted shell commands, so read confinement could not be honoured there.";
|
|
10
|
+
var FAIL_CLOSED = Object.freeze({ confined: true, roots: Object.freeze([]), network: false });
|
|
11
|
+
function parseScopeEnvironment(rawRoots, rawNetwork) {
|
|
12
|
+
if (rawRoots === undefined && rawNetwork === undefined)
|
|
13
|
+
return { confined: false, network: false };
|
|
14
|
+
if (rawRoots === undefined)
|
|
15
|
+
return FAIL_CLOSED;
|
|
16
|
+
if (rawNetwork !== undefined && rawNetwork !== "1")
|
|
17
|
+
return FAIL_CLOSED;
|
|
18
|
+
let parsed;
|
|
19
|
+
try {
|
|
20
|
+
parsed = JSON.parse(rawRoots);
|
|
21
|
+
} catch {
|
|
22
|
+
return FAIL_CLOSED;
|
|
23
|
+
}
|
|
24
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
25
|
+
return FAIL_CLOSED;
|
|
26
|
+
for (const entry of parsed) {
|
|
27
|
+
if (typeof entry !== "string" || entry.includes("\x00") || entry.includes("\\") || !path.isAbsolute(entry) || path.resolve(entry) !== entry) {
|
|
28
|
+
return FAIL_CLOSED;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return Object.freeze({ confined: true, roots: Object.freeze([...parsed]), network: rawNetwork === "1" });
|
|
32
|
+
}
|
|
33
|
+
var SCOPED_READ_KEYS = {
|
|
34
|
+
Read: new Set(["path", "line_offset", "column_offset", "n_lines", "max_chars"]),
|
|
35
|
+
ReadMediaFile: new Set(["path", "region", "full_resolution"]),
|
|
36
|
+
Glob: new Set(["pattern", "path", "head_limit", "offset", "include_ignored", "include_dirs"]),
|
|
37
|
+
Grep: new Set([
|
|
38
|
+
"pattern",
|
|
39
|
+
"path",
|
|
40
|
+
"glob",
|
|
41
|
+
"type",
|
|
42
|
+
"output_mode",
|
|
43
|
+
"-i",
|
|
44
|
+
"-n",
|
|
45
|
+
"-A",
|
|
46
|
+
"-B",
|
|
47
|
+
"-C",
|
|
48
|
+
"head_limit",
|
|
49
|
+
"offset",
|
|
50
|
+
"multiline",
|
|
51
|
+
"include_ignored"
|
|
52
|
+
])
|
|
53
|
+
};
|
|
54
|
+
var SCOPED_READ_TOOLS = new Set(Object.keys(SCOPED_READ_KEYS));
|
|
55
|
+
|
|
56
|
+
class ScopeDenial extends Error {
|
|
57
|
+
}
|
|
58
|
+
async function evaluateScopedRead(toolName, toolInput, roots) {
|
|
59
|
+
const deny = (why) => ({
|
|
60
|
+
decision: "deny",
|
|
61
|
+
reason: `kimi-plugin-cc safety hook: reads are confined to ${roots.length === 0 ? "no readable roots (the scope variables are malformed)" : roots.join(", ")}; tool "${toolName}" denied: ${why}`
|
|
62
|
+
});
|
|
63
|
+
if (roots.length === 0)
|
|
64
|
+
return deny("no path can be read.");
|
|
65
|
+
const allowedKeys = SCOPED_READ_KEYS[toolName];
|
|
66
|
+
if (allowedKeys === undefined)
|
|
67
|
+
return deny("the tool has no confinement rule.");
|
|
68
|
+
if (typeof toolInput !== "object" || toolInput === null || Array.isArray(toolInput)) {
|
|
69
|
+
return deny("its arguments are not an object.");
|
|
70
|
+
}
|
|
71
|
+
const args = toolInput;
|
|
72
|
+
for (const key of Object.keys(args)) {
|
|
73
|
+
if (!allowedKeys.has(key))
|
|
74
|
+
return deny(`argument "${key}" cannot be checked.`);
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const targets = [];
|
|
78
|
+
if (toolName === "Read" || toolName === "ReadMediaFile") {
|
|
79
|
+
targets.push(requirePath(args.path, "path"));
|
|
80
|
+
} else {
|
|
81
|
+
targets.push(args.path === undefined ? roots[0] : requirePath(args.path, "path"));
|
|
82
|
+
const patternKey = toolName === "Glob" ? "pattern" : "glob";
|
|
83
|
+
const pattern = args[patternKey];
|
|
84
|
+
if (toolName === "Glob" || pattern !== undefined) {
|
|
85
|
+
const anchor = patternAnchor(pattern, patternKey);
|
|
86
|
+
if (anchor !== undefined)
|
|
87
|
+
targets.push(anchor);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
for (const target of targets) {
|
|
91
|
+
const absolute = path.isAbsolute(target) ? path.resolve(target) : path.resolve(roots[0], target);
|
|
92
|
+
const real = await realTarget(absolute);
|
|
93
|
+
if (!roots.some((root) => isWithin(root, real))) {
|
|
94
|
+
return deny(`"${target}" resolves outside the read roots.`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} catch (error) {
|
|
98
|
+
return deny(error instanceof ScopeDenial ? error.message : "its target could not be resolved.");
|
|
99
|
+
}
|
|
100
|
+
return { decision: "allow" };
|
|
101
|
+
}
|
|
102
|
+
function requirePath(value, key) {
|
|
103
|
+
if (typeof value !== "string" || value.length === 0 || value.includes("\x00")) {
|
|
104
|
+
throw new ScopeDenial(`argument "${key}" is not a usable path.`);
|
|
105
|
+
}
|
|
106
|
+
if (value.startsWith("~"))
|
|
107
|
+
throw new ScopeDenial(`"${value}" uses home-directory expansion.`);
|
|
108
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value))
|
|
109
|
+
throw new ScopeDenial(`"${value}" is not a filesystem path.`);
|
|
110
|
+
denyAmbiguousSpelling(value, "path");
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
function denyAmbiguousSpelling(value, noun) {
|
|
114
|
+
if (value.includes("\\"))
|
|
115
|
+
throw new ScopeDenial(`${noun} "${value}" contains a backslash.`);
|
|
116
|
+
if (/^[A-Za-z]:/.test(value))
|
|
117
|
+
throw new ScopeDenial(`${noun} "${value}" starts with a drive letter.`);
|
|
118
|
+
}
|
|
119
|
+
function patternAnchor(value, key) {
|
|
120
|
+
if (typeof value !== "string" || value.includes("\x00")) {
|
|
121
|
+
throw new ScopeDenial(`argument "${key}" is not a usable glob.`);
|
|
122
|
+
}
|
|
123
|
+
const body = value.startsWith("!") ? value.slice(1) : value;
|
|
124
|
+
if (body.startsWith("~"))
|
|
125
|
+
throw new ScopeDenial(`glob "${value}" uses home-directory expansion.`);
|
|
126
|
+
denyAmbiguousSpelling(body, "glob");
|
|
127
|
+
const segments = body.split("/");
|
|
128
|
+
if (segments.includes(".."))
|
|
129
|
+
throw new ScopeDenial(`glob "${value}" climbs with "..".`);
|
|
130
|
+
if (!path.isAbsolute(body))
|
|
131
|
+
return;
|
|
132
|
+
const literal = [];
|
|
133
|
+
for (const segment of segments) {
|
|
134
|
+
if (/[*?[\]{}!]/.test(segment))
|
|
135
|
+
break;
|
|
136
|
+
literal.push(segment);
|
|
137
|
+
}
|
|
138
|
+
return literal.join("/") || "/";
|
|
139
|
+
}
|
|
140
|
+
async function realTarget(absolute) {
|
|
141
|
+
try {
|
|
142
|
+
return await realpath(absolute);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
const code = error.code;
|
|
145
|
+
if (code !== "ENOENT" && code !== "ENOTDIR")
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
await lstat(absolute);
|
|
150
|
+
throw new ScopeDenial(`"${absolute}" is a link whose target cannot be resolved.`);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (error instanceof ScopeDenial)
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
let ancestor = path.dirname(absolute);
|
|
156
|
+
while (true) {
|
|
38
157
|
try {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
158
|
+
const real = await realpath(ancestor);
|
|
159
|
+
return path.resolve(real, path.relative(ancestor, absolute));
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const code = error.code;
|
|
162
|
+
if (code !== "ENOENT" && code !== "ENOTDIR")
|
|
163
|
+
throw error;
|
|
164
|
+
const parent = path.dirname(ancestor);
|
|
165
|
+
if (parent === ancestor)
|
|
166
|
+
throw error;
|
|
167
|
+
ancestor = parent;
|
|
44
168
|
}
|
|
45
|
-
|
|
46
|
-
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function isWithin(root, candidate) {
|
|
172
|
+
const relative = path.relative(root, candidate);
|
|
173
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
174
|
+
}
|
|
175
|
+
var NON_GLOBAL_IPV4 = [
|
|
176
|
+
[0, 8],
|
|
177
|
+
[167772160, 8],
|
|
178
|
+
[1681915904, 10],
|
|
179
|
+
[2130706432, 8],
|
|
180
|
+
[2851995648, 16],
|
|
181
|
+
[2886729728, 12],
|
|
182
|
+
[3221225472, 24],
|
|
183
|
+
[3221225984, 24],
|
|
184
|
+
[3227017984, 24],
|
|
185
|
+
[3232235520, 16],
|
|
186
|
+
[3323068416, 15],
|
|
187
|
+
[3325256704, 24],
|
|
188
|
+
[3405803776, 24],
|
|
189
|
+
[3758096384, 4],
|
|
190
|
+
[4026531840, 4]
|
|
191
|
+
];
|
|
192
|
+
function isAllowedFetchUrl(url) {
|
|
193
|
+
if (typeof url !== "string" || !/^https?:\/\//i.test(url))
|
|
194
|
+
return false;
|
|
195
|
+
let parsed;
|
|
196
|
+
try {
|
|
197
|
+
parsed = new URL(url);
|
|
198
|
+
} catch {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
202
|
+
return false;
|
|
203
|
+
if (parsed.username !== "" || parsed.password !== "")
|
|
204
|
+
return false;
|
|
205
|
+
const host = parsed.hostname;
|
|
206
|
+
if (host.startsWith("[")) {
|
|
207
|
+
const hextets = ipv6Hextets(host.slice(1, -1));
|
|
208
|
+
return hextets !== undefined && isGlobalIpv6(hextets);
|
|
209
|
+
}
|
|
210
|
+
const ipv4 = ipv4Value(host);
|
|
211
|
+
if (ipv4 !== undefined) {
|
|
212
|
+
if (rawHost(url) !== host)
|
|
213
|
+
return false;
|
|
214
|
+
return isGlobalIpv4(ipv4);
|
|
215
|
+
}
|
|
216
|
+
const name = host.replace(/\.+$/, "");
|
|
217
|
+
if (name.length === 0 || /^[0-9]+$/.test(name))
|
|
218
|
+
return false;
|
|
219
|
+
return !(name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local") || name.endsWith(".internal"));
|
|
220
|
+
}
|
|
221
|
+
function rawHost(url) {
|
|
222
|
+
const authority = url.replace(/^https?:\/\//i, "").split(/[/\\?#]/, 1)[0];
|
|
223
|
+
const hostPort = authority.slice(authority.lastIndexOf("@") + 1);
|
|
224
|
+
return hostPort.replace(/:[0-9]*$/, "").toLowerCase();
|
|
225
|
+
}
|
|
226
|
+
function ipv4Value(host) {
|
|
227
|
+
const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
228
|
+
if (!match)
|
|
229
|
+
return;
|
|
230
|
+
const octets = match.slice(1).map(Number);
|
|
231
|
+
if (octets.some((octet) => octet > 255))
|
|
232
|
+
return;
|
|
233
|
+
return (octets[0] << 24 >>> 0) + (octets[1] << 16) + (octets[2] << 8) + octets[3];
|
|
234
|
+
}
|
|
235
|
+
function inRange(value, base, bits) {
|
|
236
|
+
const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
|
|
237
|
+
return (value & mask) >>> 0 === base;
|
|
238
|
+
}
|
|
239
|
+
function ipv6Hextets(text) {
|
|
240
|
+
const halves = text.split("::");
|
|
241
|
+
if (halves.length > 2)
|
|
242
|
+
return;
|
|
243
|
+
const parse = (part) => {
|
|
244
|
+
if (part === "")
|
|
245
|
+
return [];
|
|
246
|
+
const out = [];
|
|
247
|
+
for (const piece of part.split(":")) {
|
|
248
|
+
if (piece.includes(".")) {
|
|
249
|
+
const v4 = ipv4Value(piece);
|
|
250
|
+
if (v4 === undefined)
|
|
251
|
+
return;
|
|
252
|
+
out.push(v4 >>> 16, v4 & 65535);
|
|
253
|
+
} else if (/^[0-9a-f]{1,4}$/i.test(piece)) {
|
|
254
|
+
out.push(parseInt(piece, 16));
|
|
255
|
+
} else {
|
|
47
256
|
return;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
};
|
|
261
|
+
const head = parse(halves[0]);
|
|
262
|
+
const tail = halves.length === 2 ? parse(halves[1]) : [];
|
|
263
|
+
if (head === undefined || tail === undefined)
|
|
264
|
+
return;
|
|
265
|
+
const fill = 8 - head.length - tail.length;
|
|
266
|
+
if (halves.length === 2 ? fill < 0 : fill !== 0)
|
|
267
|
+
return;
|
|
268
|
+
return [...head, ...new Array(halves.length === 2 ? fill : 0).fill(0), ...tail];
|
|
269
|
+
}
|
|
270
|
+
function isGlobalIpv4(value) {
|
|
271
|
+
return !NON_GLOBAL_IPV4.some(([base, bits]) => inRange(value, base, bits));
|
|
272
|
+
}
|
|
273
|
+
function isGlobalIpv6(h) {
|
|
274
|
+
if (h[0] === 100 && h[1] === 65435 && h.slice(2, 6).every((part) => part === 0)) {
|
|
275
|
+
return isGlobalIpv4((h[6] << 16 >>> 0) + h[7]);
|
|
276
|
+
}
|
|
277
|
+
if ((h[0] & 57344) !== 8192)
|
|
278
|
+
return false;
|
|
279
|
+
if (h[0] === 8193 && h[1] < 512)
|
|
280
|
+
return false;
|
|
281
|
+
if (h[0] === 8193 && h[1] === 3512)
|
|
282
|
+
return false;
|
|
283
|
+
if (h[0] === 8194)
|
|
284
|
+
return false;
|
|
285
|
+
if (h[0] === 16383 && h[1] < 4096)
|
|
286
|
+
return false;
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// runtime/kimi-releases.ts
|
|
291
|
+
var BASELINE = Object.freeze([
|
|
292
|
+
"hook-schema",
|
|
293
|
+
"web-preactivation",
|
|
294
|
+
"print-cancels-plan",
|
|
295
|
+
"local-environment",
|
|
296
|
+
"agent-state",
|
|
297
|
+
"modern-ws-control",
|
|
298
|
+
"bounded-swarm",
|
|
299
|
+
"web-json-ready"
|
|
300
|
+
]);
|
|
301
|
+
var KIMI_V2_RELEASES = Object.freeze([
|
|
302
|
+
{ version: "2.8.0", commit: "46d9085f", scope: "all", capabilities: BASELINE }
|
|
303
|
+
]);
|
|
304
|
+
var BORROWABLE_CAPABILITIES = new Set([
|
|
305
|
+
"local-environment"
|
|
306
|
+
]);
|
|
307
|
+
|
|
308
|
+
// runtime/swarm-policy.ts
|
|
309
|
+
var SWARM_POLICY_ENV = "KIMI_PLUGIN_CC_SWARM_POLICY";
|
|
310
|
+
var SWARM_WAVE_SIZE_ENV = "KIMI_PLUGIN_CC_SWARM_WAVE_SIZE";
|
|
311
|
+
var BOUNDED_SWARM_POLICY = "bounded-waves/1";
|
|
312
|
+
function plainObject(value) {
|
|
313
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
314
|
+
}
|
|
315
|
+
function nonemptyString(value) {
|
|
316
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
317
|
+
}
|
|
318
|
+
var SWARM_INPUT_KEYS = new Set([
|
|
319
|
+
"description",
|
|
320
|
+
"subagent_type",
|
|
321
|
+
"prompt_template",
|
|
322
|
+
"items",
|
|
323
|
+
"fork",
|
|
324
|
+
"resume_agent_ids",
|
|
325
|
+
"model"
|
|
326
|
+
]);
|
|
327
|
+
function evaluateSwarmWaveInput(input, policy, waveSize) {
|
|
328
|
+
const deny = (reason) => ({
|
|
329
|
+
decision: "deny",
|
|
330
|
+
reason: `kimi-plugin-cc safety hook: AgentSwarm denied: ${reason}`
|
|
331
|
+
});
|
|
332
|
+
if (policy !== BOUNDED_SWARM_POLICY)
|
|
333
|
+
return deny("missing or unrecognized swarm policy.");
|
|
334
|
+
const width = typeof waveSize === "string" && /^[1-9][0-9]*$/.test(waveSize) ? Number(waveSize) : NaN;
|
|
335
|
+
if (!Number.isSafeInteger(width) || width < 1)
|
|
336
|
+
return deny("missing or invalid trusted wave size.");
|
|
337
|
+
if (width === 1) {
|
|
338
|
+
return deny("concurrency 1 uses one worker directly; complete the task yourself without delegation.");
|
|
339
|
+
}
|
|
340
|
+
if (!plainObject(input))
|
|
341
|
+
return deny("arguments must be an object.");
|
|
342
|
+
if (Reflect.ownKeys(input).some((key) => typeof key !== "string" || !SWARM_INPUT_KEYS.has(key))) {
|
|
343
|
+
return deny("unrecognized arguments.");
|
|
344
|
+
}
|
|
345
|
+
if (!nonemptyString(input.description))
|
|
346
|
+
return deny("description must be a nonempty string.");
|
|
347
|
+
for (const key of ["subagent_type", "prompt_template"]) {
|
|
348
|
+
if (input[key] !== undefined && !nonemptyString(input[key]))
|
|
349
|
+
return deny(`${key} must be a nonempty string.`);
|
|
350
|
+
}
|
|
351
|
+
if (input.model !== undefined && typeof input.model !== "string")
|
|
352
|
+
return deny("model must be a string.");
|
|
353
|
+
if (input.fork !== undefined && input.fork !== false)
|
|
354
|
+
return deny("forked subagents are not supported.");
|
|
355
|
+
if (input.items !== undefined && (!Array.isArray(input.items) || !input.items.every(nonemptyString))) {
|
|
356
|
+
return deny("items must be an array of nonempty strings.");
|
|
357
|
+
}
|
|
358
|
+
if (input.resume_agent_ids !== undefined && (!plainObject(input.resume_agent_ids) || Reflect.ownKeys(input.resume_agent_ids).some((key) => typeof key !== "string" || !nonemptyString(key) || !nonemptyString(input.resume_agent_ids[key])))) {
|
|
359
|
+
return deny("resume_agent_ids must map nonempty agent IDs to nonempty prompts.");
|
|
360
|
+
}
|
|
361
|
+
const fresh = Array.isArray(input.items) ? input.items.length : 0;
|
|
362
|
+
const resumed = plainObject(input.resume_agent_ids) ? Object.keys(input.resume_agent_ids).length : 0;
|
|
363
|
+
const total = fresh + resumed;
|
|
364
|
+
if (total === 0)
|
|
365
|
+
return deny("a wave must contain at least one new or resumed entry.");
|
|
366
|
+
if (total > width) {
|
|
367
|
+
return deny(`wave has ${total} new and resumed entries, exceeding the limit ${width}; split the work into sequential waves of at most ${width} entries and wait for each wave to finish.`);
|
|
368
|
+
}
|
|
369
|
+
if (fresh === 1 && resumed === 0) {
|
|
370
|
+
return deny("fresh-only waves require at least two entries; regroup targets into disjoint entries within the wave limit, or resume an existing child for the remaining work.");
|
|
371
|
+
}
|
|
372
|
+
return { decision: "allow" };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// runtime/hooks/approval-policy.ts
|
|
376
|
+
var READ_ONLY_TOOLS = new Set([
|
|
377
|
+
"Read",
|
|
378
|
+
"Grep",
|
|
379
|
+
"Glob",
|
|
380
|
+
"ReadMediaFile",
|
|
381
|
+
"TaskList",
|
|
382
|
+
"TaskOutput",
|
|
383
|
+
"WaitFor"
|
|
384
|
+
]);
|
|
385
|
+
var WEB_TOOLS = new Set(["WebSearch", "FetchURL"]);
|
|
386
|
+
var AGENT_SWARM_TOOL = "AgentSwarm";
|
|
387
|
+
var PLAN_MODE_TOOLS = new Set(["EnterPlanMode", "ExitPlanMode"]);
|
|
388
|
+
var KNOWN_LABELS = new Set([
|
|
389
|
+
"ask",
|
|
390
|
+
"review",
|
|
391
|
+
"challenge",
|
|
392
|
+
"rescue",
|
|
393
|
+
"swarm",
|
|
394
|
+
"swarm-write"
|
|
395
|
+
]);
|
|
396
|
+
async function decideHookOutcome(input, ctx) {
|
|
397
|
+
const result = decideHookOutcomePure(input, ctx);
|
|
398
|
+
if (!("evaluator" in result))
|
|
399
|
+
return result;
|
|
400
|
+
const toolName = typeof input.tool_name === "string" ? input.tool_name : "";
|
|
401
|
+
if (result.evaluator === "read-scope") {
|
|
402
|
+
return await evaluateScopedRead(toolName, input.tool_input, result.roots);
|
|
403
|
+
}
|
|
404
|
+
if (ctx.rescueEvaluator !== undefined) {
|
|
405
|
+
return await ctx.rescueEvaluator(result.workspaceRoot, toolName, input.tool_input);
|
|
406
|
+
}
|
|
407
|
+
if (READ_ONLY_TOOLS.has(toolName))
|
|
408
|
+
return { decision: "allow" };
|
|
409
|
+
return {
|
|
410
|
+
decision: "deny",
|
|
411
|
+
reason: `kimi-plugin-cc safety hook: ${ctx.commandLabel} evaluator not configured; tool "${toolName}" denied as a safety default.`
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function decideHookOutcomePure(input, ctx) {
|
|
415
|
+
const label = typeof ctx.commandLabel === "string" ? ctx.commandLabel : undefined;
|
|
416
|
+
if (label === undefined || label.length === 0) {
|
|
417
|
+
return { decision: "allow" };
|
|
418
|
+
}
|
|
419
|
+
const toolName = typeof input.tool_name === "string" ? input.tool_name : "";
|
|
420
|
+
if ((label === "swarm" || label === "swarm-write") && (ctx.swarmPolicy !== undefined || ctx.swarmWaveSize !== undefined)) {
|
|
421
|
+
if (toolName === AGENT_SWARM_TOOL) {
|
|
422
|
+
return evaluateSwarmWaveInput(input.tool_input, ctx.swarmPolicy, ctx.swarmWaveSize);
|
|
423
|
+
}
|
|
424
|
+
if (toolName === "Agent") {
|
|
425
|
+
return {
|
|
426
|
+
decision: "deny",
|
|
427
|
+
reason: "kimi-plugin-cc safety hook: singular Agent delegation is denied for bounded swarm jobs."
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
const args = input.tool_input;
|
|
431
|
+
if (toolName === "Bash" && typeof args === "object" && args !== null && args.run_in_background === true) {
|
|
432
|
+
return {
|
|
433
|
+
decision: "deny",
|
|
434
|
+
reason: "kimi-plugin-cc safety hook: run commands in the foreground; explicit background commands are disabled for bounded swarm execution."
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (PLAN_MODE_TOOLS.has(toolName)) {
|
|
439
|
+
return {
|
|
440
|
+
decision: "deny",
|
|
441
|
+
reason: `kimi-plugin-cc safety hook: tool "${toolName}" is denied for plugin-managed sessions because agent-core-v2 plan-file writes can bypass later external hooks; native plan mode is never armed in plugin-managed sessions.`
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
if (["GetGoal", "UpdateGoal", "CreateGoal", "SetGoalBudget"].includes(toolName)) {
|
|
445
|
+
if (toolName === "SetGoalBudget" && label === "rescue" && ctx.operationKind === "pursue") {
|
|
446
|
+
return {
|
|
447
|
+
decision: "deny",
|
|
448
|
+
reason: `kimi-plugin-cc safety hook: tool "SetGoalBudget" is denied. The outer plugin wall-clock budget already applies; continue the current goal without retrying SetGoalBudget or changing its budget.`
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
const args = input.tool_input;
|
|
452
|
+
const objectArgs = typeof args === "object" && args !== null && !Array.isArray(args) && (Object.getPrototypeOf(args) === Object.prototype || Object.getPrototypeOf(args) === null);
|
|
453
|
+
const keys = objectArgs ? Reflect.ownKeys(args) : [];
|
|
454
|
+
const validArgs = objectArgs && (toolName === "GetGoal" && keys.length === 0 || toolName === "UpdateGoal" && keys.length === 1 && keys[0] === "status" && (args.status === "complete" || args.status === "blocked"));
|
|
455
|
+
if (label === "rescue" && ctx.operationKind === "pursue" && typeof ctx.trustedWorkspaceRoot === "string" && ctx.trustedWorkspaceRoot.trim().length > 0 && validArgs) {
|
|
456
|
+
return { decision: "allow" };
|
|
457
|
+
}
|
|
458
|
+
return {
|
|
459
|
+
decision: "deny",
|
|
460
|
+
reason: `kimi-plugin-cc safety hook: tool "${toolName}" requires a pursue run with a trusted workspace root and exact terminal goal metadata arguments; goal creation, reactivation, and budget changes are denied.`
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
switch (label) {
|
|
464
|
+
case "ask":
|
|
465
|
+
case "review":
|
|
466
|
+
case "challenge":
|
|
467
|
+
if (READ_ONLY_TOOLS.has(toolName)) {
|
|
468
|
+
return readToolDecision(toolName, scopeOf(ctx));
|
|
469
|
+
}
|
|
470
|
+
if (WEB_TOOLS.has(toolName))
|
|
471
|
+
return webToolDecision(label, toolName, input.tool_input, scopeOf(ctx));
|
|
472
|
+
return {
|
|
473
|
+
decision: "deny",
|
|
474
|
+
reason: denyReadOnlyMessage(label, toolName)
|
|
475
|
+
};
|
|
476
|
+
case "swarm":
|
|
477
|
+
if (toolName === AGENT_SWARM_TOOL)
|
|
478
|
+
return { decision: "allow" };
|
|
479
|
+
if (READ_ONLY_TOOLS.has(toolName))
|
|
480
|
+
return readToolDecision(toolName, scopeOf(ctx));
|
|
481
|
+
if (WEB_TOOLS.has(toolName))
|
|
482
|
+
return webToolDecision(label, toolName, input.tool_input, scopeOf(ctx));
|
|
483
|
+
return {
|
|
484
|
+
decision: "deny",
|
|
485
|
+
reason: denySwarmMessage(toolName, ctx.swarmPolicy === BOUNDED_SWARM_POLICY && ctx.swarmWaveSize === "1")
|
|
486
|
+
};
|
|
487
|
+
case "swarm-write": {
|
|
488
|
+
const slashed = backslashRootDenial(ctx.trustedWorkspaceRoot, toolName);
|
|
489
|
+
if (slashed !== undefined)
|
|
490
|
+
return slashed;
|
|
491
|
+
if (READ_ONLY_TOOLS.has(toolName) || toolName === AGENT_SWARM_TOOL) {
|
|
492
|
+
return { decision: "allow" };
|
|
493
|
+
}
|
|
494
|
+
const workspaceRoot = typeof ctx.trustedWorkspaceRoot === "string" ? ctx.trustedWorkspaceRoot : "";
|
|
495
|
+
if (workspaceRoot.length === 0) {
|
|
496
|
+
return {
|
|
497
|
+
decision: "deny",
|
|
498
|
+
reason: `kimi-plugin-cc safety hook: swarm-write received no trusted workspace root; tool "${toolName}" denied. ` + "This is a plugin misconfiguration — writes are refused rather than risk the user's working tree."
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
return { evaluator: "rescue", workspaceRoot };
|
|
502
|
+
}
|
|
503
|
+
case "rescue": {
|
|
504
|
+
const slashed = backslashRootDenial(ctx.trustedWorkspaceRoot, toolName);
|
|
505
|
+
if (slashed !== undefined)
|
|
506
|
+
return slashed;
|
|
507
|
+
const workspaceRoot = typeof ctx.trustedWorkspaceRoot === "string" ? ctx.trustedWorkspaceRoot : "";
|
|
508
|
+
if (workspaceRoot.length === 0) {
|
|
509
|
+
if (READ_ONLY_TOOLS.has(toolName))
|
|
510
|
+
return { decision: "allow" };
|
|
511
|
+
return {
|
|
512
|
+
decision: "deny",
|
|
513
|
+
reason: `kimi-plugin-cc safety hook: rescue received no trusted workspace root; tool "${toolName}" denied. ` + "This is a plugin misconfiguration — writes are refused rather than trusting hook payload cwd."
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
return { evaluator: "rescue", workspaceRoot };
|
|
517
|
+
}
|
|
518
|
+
default:
|
|
519
|
+
if (KNOWN_LABELS.has(label)) {
|
|
520
|
+
return {
|
|
521
|
+
decision: "deny",
|
|
522
|
+
reason: `kimi-plugin-cc safety hook: command label "${label}" has no policy branch.`
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
if (READ_ONLY_TOOLS.has(toolName)) {
|
|
526
|
+
return readToolDecision(toolName, scopeOf(ctx));
|
|
527
|
+
}
|
|
528
|
+
return {
|
|
529
|
+
decision: "deny",
|
|
530
|
+
reason: `kimi-plugin-cc safety hook: unrecognized command label "${label}"; tool "${toolName}" denied as a safety default.`
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
function backslashRootDenial(root, toolName) {
|
|
535
|
+
if (process.platform === "win32" || typeof root !== "string" || !root.includes("\\"))
|
|
536
|
+
return;
|
|
537
|
+
return {
|
|
538
|
+
decision: "deny",
|
|
539
|
+
reason: `kimi-plugin-cc safety hook: writes cannot be confined to ${root}: it contains a backslash, ` + `which kimi-code reads as a path separator; tool "${toolName}" denied.`
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
function scopeOf(ctx) {
|
|
543
|
+
return parseScopeEnvironment(ctx.readRoots, ctx.network);
|
|
544
|
+
}
|
|
545
|
+
function readToolDecision(toolName, scope) {
|
|
546
|
+
if (scope.confined && SCOPED_READ_TOOLS.has(toolName))
|
|
547
|
+
return { evaluator: "read-scope", roots: scope.roots };
|
|
548
|
+
return { decision: "allow" };
|
|
549
|
+
}
|
|
550
|
+
function webToolDecision(label, toolName, toolInput, scope) {
|
|
551
|
+
if (!scope.network) {
|
|
552
|
+
return {
|
|
553
|
+
decision: "deny",
|
|
554
|
+
reason: `kimi-plugin-cc safety hook: ${label} has no network access; tool "${toolName}" is denied. ` + "The caller can allow WebSearch and FetchURL for one call with --network, which also confines reads to the workspace and any --read-root."
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
if (toolName === "WebSearch")
|
|
558
|
+
return { decision: "allow" };
|
|
559
|
+
const url = typeof toolInput === "object" && toolInput !== null && !Array.isArray(toolInput) ? toolInput.url : undefined;
|
|
560
|
+
if (isAllowedFetchUrl(url))
|
|
561
|
+
return { decision: "allow" };
|
|
562
|
+
return {
|
|
563
|
+
decision: "deny",
|
|
564
|
+
reason: "kimi-plugin-cc safety hook: FetchURL accepts only http:// and https:// URLs without embedded credentials " + "whose host is a public name or a canonical global unicast IP address; localhost, .local and .internal names, " + "numerically encoded hosts, and private, loopback, link-local, documentation, multicast, reserved, 6to4 and Teredo addresses are denied."
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
function denyReadOnlyMessage(label, toolName) {
|
|
568
|
+
const tool = toolName.length > 0 ? toolName : "<unspecified>";
|
|
569
|
+
return [
|
|
570
|
+
`kimi-plugin-cc safety hook: ${label} is read-only.`,
|
|
571
|
+
`Tool "${tool}" is denied — use Read, Grep, or Glob to inspect the workspace instead.`,
|
|
572
|
+
"If you need to mutate state, the user must invoke /kimi:task --write (write-capable) rather than this command."
|
|
573
|
+
].join(" ");
|
|
574
|
+
}
|
|
575
|
+
function denySwarmMessage(toolName, singleWorker) {
|
|
576
|
+
const tool = toolName.length > 0 ? toolName : "<unspecified>";
|
|
577
|
+
if (singleWorker) {
|
|
578
|
+
return [
|
|
579
|
+
"kimi-plugin-cc safety hook: swarm with concurrency 1 is a read-only review.",
|
|
580
|
+
`Tool "${tool}" is denied — use Read, Grep, or Glob to inspect the workspace.`,
|
|
581
|
+
"Complete the review yourself; delegation is denied.",
|
|
582
|
+
"Return your findings in a markdown report."
|
|
583
|
+
].join(" ");
|
|
584
|
+
}
|
|
585
|
+
return [
|
|
586
|
+
"kimi-plugin-cc safety hook: swarm is a read-only parallel review.",
|
|
587
|
+
`Tool "${tool}" is denied — every subagent may use Read, Grep, or Glob to inspect the workspace,`,
|
|
588
|
+
"and the coordinator may use AgentSwarm to fan out, but no write, edit, or shell operations are permitted.",
|
|
589
|
+
"Consolidate the subagents' findings into a markdown report instead."
|
|
590
|
+
].join(" ");
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// runtime/hooks/hook-timing.ts
|
|
594
|
+
var HOOK_TIMEOUT_S = 15;
|
|
595
|
+
var HOOK_DECISION_DEADLINE_MS = HOOK_TIMEOUT_S * 1000 - 5000;
|
|
596
|
+
var HOOK_TEST_DELAY_ENV = "KIMI_PLUGIN_CC_HOOK_TEST_DELAY_MS";
|
|
597
|
+
|
|
598
|
+
// runtime/rescue-approval.ts
|
|
599
|
+
import { access, lstat as lstat2, readdir, realpath as realpath2 } from "node:fs/promises";
|
|
600
|
+
import path2 from "node:path";
|
|
601
|
+
|
|
602
|
+
// runtime/vendor/shell-quote/parse.ts
|
|
603
|
+
var CONTROL = "(?:" + [
|
|
604
|
+
"\\|\\|",
|
|
605
|
+
"\\&\\&",
|
|
606
|
+
";;",
|
|
607
|
+
"\\|\\&",
|
|
608
|
+
"\\<\\(",
|
|
609
|
+
"\\<\\<\\<",
|
|
610
|
+
">>",
|
|
611
|
+
">\\&",
|
|
612
|
+
"<\\&",
|
|
613
|
+
"[&;()|<>]"
|
|
614
|
+
].join("|") + ")";
|
|
615
|
+
var controlRE = new RegExp("^" + CONTROL + "$");
|
|
616
|
+
var META = "|&;()<> \\t";
|
|
617
|
+
var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
|
|
618
|
+
var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
|
|
619
|
+
var hash = /^#$/;
|
|
620
|
+
var SQ = "'";
|
|
621
|
+
var DQ = '"';
|
|
622
|
+
var DS = "$";
|
|
623
|
+
var TOKEN = "";
|
|
624
|
+
var mult = 4294967296;
|
|
625
|
+
for (i = 0;i < 4; i++) {
|
|
626
|
+
TOKEN += (mult * Math.random()).toString(16);
|
|
627
|
+
}
|
|
628
|
+
var i;
|
|
629
|
+
var startsWithToken = new RegExp("^" + TOKEN);
|
|
630
|
+
function matchAll(s, r) {
|
|
631
|
+
var origIndex = r.lastIndex;
|
|
632
|
+
var matches = [];
|
|
633
|
+
var matchObj;
|
|
634
|
+
while (matchObj = r.exec(s)) {
|
|
635
|
+
matches.push(matchObj);
|
|
636
|
+
if (r.lastIndex === matchObj.index) {
|
|
637
|
+
r.lastIndex += 1;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
r.lastIndex = origIndex;
|
|
641
|
+
return matches;
|
|
642
|
+
}
|
|
643
|
+
function getVar(env, pre, key) {
|
|
644
|
+
var r = typeof env === "function" ? env(key) : env[key];
|
|
645
|
+
if (typeof r === "undefined" && key != "") {
|
|
646
|
+
r = "";
|
|
647
|
+
} else if (typeof r === "undefined") {
|
|
648
|
+
r = "$";
|
|
649
|
+
}
|
|
650
|
+
if (typeof r === "object") {
|
|
651
|
+
return pre + TOKEN + JSON.stringify(r) + TOKEN;
|
|
652
|
+
}
|
|
653
|
+
return pre + r;
|
|
654
|
+
}
|
|
655
|
+
function parseInternal(string, env, opts) {
|
|
656
|
+
if (!opts) {
|
|
657
|
+
opts = {};
|
|
658
|
+
}
|
|
659
|
+
var BS = opts.escape || "\\";
|
|
660
|
+
var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
|
|
661
|
+
var chunker = new RegExp([
|
|
662
|
+
"(" + CONTROL + ")",
|
|
663
|
+
"(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
|
|
664
|
+
].join("|"), "g");
|
|
665
|
+
var matches = matchAll(string, chunker);
|
|
666
|
+
if (matches.length === 0) {
|
|
667
|
+
return [];
|
|
668
|
+
}
|
|
669
|
+
if (!env) {
|
|
670
|
+
env = {};
|
|
671
|
+
}
|
|
672
|
+
var commented = false;
|
|
673
|
+
return matches.map(function(match) {
|
|
674
|
+
var s = match[0];
|
|
675
|
+
if (!s || commented) {
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (controlRE.test(s)) {
|
|
679
|
+
return { op: s };
|
|
48
680
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
681
|
+
var quote = false;
|
|
682
|
+
var esc = false;
|
|
683
|
+
var out = "";
|
|
684
|
+
var isGlob = false;
|
|
685
|
+
var i;
|
|
686
|
+
function parseEnvVar() {
|
|
687
|
+
i += 1;
|
|
688
|
+
var varend;
|
|
689
|
+
var varname;
|
|
690
|
+
var char = s.charAt(i);
|
|
691
|
+
if (char === "{") {
|
|
692
|
+
i += 1;
|
|
693
|
+
if (s.charAt(i) === "}") {
|
|
694
|
+
throw new Error("Bad substitution: " + s.slice(i - 2, i + 1));
|
|
695
|
+
}
|
|
696
|
+
varend = s.indexOf("}", i);
|
|
697
|
+
if (varend < 0) {
|
|
698
|
+
throw new Error("Bad substitution: " + s.slice(i));
|
|
699
|
+
}
|
|
700
|
+
varname = s.slice(i, varend);
|
|
701
|
+
i = varend;
|
|
702
|
+
} else if (/[*@#?$!_-]/.test(char)) {
|
|
703
|
+
varname = char;
|
|
704
|
+
i += 1;
|
|
705
|
+
} else {
|
|
706
|
+
var slicedFromI = s.slice(i);
|
|
707
|
+
varend = slicedFromI.match(/[^\w\d_]/);
|
|
708
|
+
if (!varend) {
|
|
709
|
+
varname = slicedFromI;
|
|
710
|
+
i = s.length;
|
|
711
|
+
} else {
|
|
712
|
+
varname = slicedFromI.slice(0, varend.index);
|
|
713
|
+
i += varend.index - 1;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return getVar(env, "", varname);
|
|
717
|
+
}
|
|
718
|
+
for (i = 0;i < s.length; i++) {
|
|
719
|
+
var c = s.charAt(i);
|
|
720
|
+
isGlob = isGlob || !quote && (c === "*" || c === "?");
|
|
721
|
+
if (esc) {
|
|
722
|
+
out += c;
|
|
723
|
+
esc = false;
|
|
724
|
+
} else if (quote) {
|
|
725
|
+
if (c === quote) {
|
|
726
|
+
quote = false;
|
|
727
|
+
} else if (quote == SQ) {
|
|
728
|
+
out += c;
|
|
729
|
+
} else {
|
|
730
|
+
if (c === BS) {
|
|
731
|
+
i += 1;
|
|
732
|
+
c = s.charAt(i);
|
|
733
|
+
if (c === DQ || c === BS || c === DS) {
|
|
734
|
+
out += c;
|
|
735
|
+
} else {
|
|
736
|
+
out += BS + c;
|
|
737
|
+
}
|
|
738
|
+
} else if (c === DS) {
|
|
739
|
+
out += parseEnvVar();
|
|
740
|
+
} else {
|
|
741
|
+
out += c;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
} else if (c === DQ || c === SQ) {
|
|
745
|
+
quote = c;
|
|
746
|
+
} else if (controlRE.test(c)) {
|
|
747
|
+
return { op: s };
|
|
748
|
+
} else if (hash.test(c)) {
|
|
749
|
+
commented = true;
|
|
750
|
+
var commentObj = { comment: string.slice(match.index + i + 1) };
|
|
751
|
+
if (out.length) {
|
|
752
|
+
return [out, commentObj];
|
|
753
|
+
}
|
|
754
|
+
return [commentObj];
|
|
755
|
+
} else if (c === BS) {
|
|
756
|
+
esc = true;
|
|
757
|
+
} else if (c === DS) {
|
|
758
|
+
out += parseEnvVar();
|
|
759
|
+
} else {
|
|
760
|
+
out += c;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (isGlob) {
|
|
764
|
+
return { op: "glob", pattern: out };
|
|
765
|
+
}
|
|
766
|
+
return out;
|
|
767
|
+
}).reduce(function(prev, arg) {
|
|
768
|
+
if (typeof arg === "undefined") {
|
|
769
|
+
return prev;
|
|
770
|
+
}
|
|
771
|
+
[].concat(arg).forEach(function(entry) {
|
|
772
|
+
prev[prev.length] = entry;
|
|
62
773
|
});
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
774
|
+
return prev;
|
|
775
|
+
}, []);
|
|
776
|
+
}
|
|
777
|
+
function parse(s, env, opts) {
|
|
778
|
+
var mapped = parseInternal(s, env, opts);
|
|
779
|
+
if (typeof env !== "function") {
|
|
780
|
+
return mapped;
|
|
781
|
+
}
|
|
782
|
+
return mapped.reduce(function(acc, value) {
|
|
783
|
+
if (typeof value === "object") {
|
|
784
|
+
acc[acc.length] = value;
|
|
785
|
+
return acc;
|
|
786
|
+
}
|
|
787
|
+
var xs = value.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
|
|
788
|
+
if (xs.length === 1) {
|
|
789
|
+
acc[acc.length] = xs[0];
|
|
790
|
+
return acc;
|
|
791
|
+
}
|
|
792
|
+
xs.filter(Boolean).forEach(function(x) {
|
|
793
|
+
acc[acc.length] = startsWithToken.test(x) ? JSON.parse(x.split(TOKEN)[1]) : x;
|
|
794
|
+
});
|
|
795
|
+
return acc;
|
|
796
|
+
}, []);
|
|
797
|
+
}
|
|
798
|
+
// runtime/rescue-approval.ts
|
|
799
|
+
var MUTATING_FLAGS_EXACT = new Set([
|
|
800
|
+
"--fix",
|
|
801
|
+
"--write",
|
|
802
|
+
"-w",
|
|
803
|
+
"--apply",
|
|
804
|
+
"--in-place",
|
|
805
|
+
"-i",
|
|
806
|
+
"--output",
|
|
807
|
+
"--output-file",
|
|
808
|
+
"--output-directory",
|
|
809
|
+
"--output-dir"
|
|
810
|
+
]);
|
|
811
|
+
var MUTATING_FLAG_PREFIXES = [...MUTATING_FLAGS_EXACT].filter((flag) => flag.startsWith("--")).map((flag) => `${flag}=`);
|
|
812
|
+
var EXEC_DELEGATING_FLAGS_EXACT = new Set([
|
|
813
|
+
"--open-files-in-pager",
|
|
814
|
+
"-vettool",
|
|
815
|
+
"--vettool",
|
|
816
|
+
"-toolexec",
|
|
817
|
+
"--toolexec",
|
|
818
|
+
"-exec",
|
|
819
|
+
"-execdir",
|
|
820
|
+
"--pre",
|
|
821
|
+
"--hostname-bin",
|
|
822
|
+
"--compress-program"
|
|
823
|
+
]);
|
|
824
|
+
var EXEC_DELEGATING_FLAG_PREFIXES = [...EXEC_DELEGATING_FLAGS_EXACT].filter((flag) => flag !== "-exec" && flag !== "-execdir").map((flag) => `${flag}=`);
|
|
825
|
+
var PYTEST_REPORT_FLAGS = [
|
|
826
|
+
"--junitxml",
|
|
827
|
+
"--junit-xml",
|
|
828
|
+
"--result-log",
|
|
829
|
+
"--report-log"
|
|
830
|
+
];
|
|
831
|
+
var PIPELINE_PLUMBING = new Set(["head", "tail", "wc", "sort", "uniq"]);
|
|
832
|
+
var GIT_READONLY_SUBCOMMANDS = new Set(["status", "diff", "show", "log", "grep", "blame"]);
|
|
833
|
+
var CARGO_SUBCOMMANDS = new Set(["check", "clippy", "test"]);
|
|
834
|
+
var GO_SUBCOMMANDS = new Set(["build", "vet", "test"]);
|
|
835
|
+
var BANNED_FIND_ACTIONS = new Set([
|
|
836
|
+
"-exec",
|
|
837
|
+
"-execdir",
|
|
838
|
+
"-ok",
|
|
839
|
+
"-okdir",
|
|
840
|
+
"-delete",
|
|
841
|
+
"-fprint",
|
|
842
|
+
"-fprintf",
|
|
843
|
+
"-fprint0",
|
|
844
|
+
"-fls"
|
|
845
|
+
]);
|
|
846
|
+
var GO_WRITE_FLAGS = new Set([
|
|
847
|
+
"-coverprofile",
|
|
848
|
+
"-cpuprofile",
|
|
849
|
+
"-memprofile",
|
|
850
|
+
"-blockprofile",
|
|
851
|
+
"-mutexprofile",
|
|
852
|
+
"-trace",
|
|
853
|
+
"-outputdir"
|
|
854
|
+
]);
|
|
855
|
+
var CARGO_WRITE_FLAGS = new Set(["--target-dir", "--out-dir"]);
|
|
856
|
+
var TSC_WRITE_FLAGS_LC = new Set([
|
|
857
|
+
"--generatecpuprofile",
|
|
858
|
+
"--generatetrace",
|
|
859
|
+
"--tsbuildinfofile",
|
|
860
|
+
"--outfile",
|
|
861
|
+
"--outdir",
|
|
862
|
+
"--out",
|
|
863
|
+
"--declarationdir"
|
|
864
|
+
]);
|
|
865
|
+
var RUFF_WRITE_FLAGS = new Set(["--add-noqa", "--fix-only", "--cache-dir", "--output-file", "--config"]);
|
|
866
|
+
var ESLINT_WRITE_FLAGS = new Set(["--cache-location", "--output-file"]);
|
|
867
|
+
var ESLINT_CODELOAD_FLAGS = new Set(["--parser", "--rulesdir", "--resolve-plugins-relative-to"]);
|
|
868
|
+
var MYPY_WRITE_FLAGS_ABBREV = [
|
|
869
|
+
"--junit-xml",
|
|
870
|
+
"--cache-dir",
|
|
871
|
+
"--install-types",
|
|
872
|
+
"--config-file",
|
|
873
|
+
"--any-exprs-report",
|
|
874
|
+
"--cobertura-xml-report",
|
|
875
|
+
"--html-report",
|
|
876
|
+
"--linecount-report",
|
|
877
|
+
"--linecoverage-report",
|
|
878
|
+
"--lineprecision-report",
|
|
879
|
+
"--memory-xml-report",
|
|
880
|
+
"--txt-report",
|
|
881
|
+
"--xml-report",
|
|
882
|
+
"--xslt-html-report",
|
|
883
|
+
"--xslt-txt-report"
|
|
884
|
+
];
|
|
885
|
+
function hasFlagFromSet(args, flags) {
|
|
886
|
+
return args.some((arg) => flags.has(flagName(arg)));
|
|
887
|
+
}
|
|
888
|
+
function flagName(arg) {
|
|
889
|
+
const eq = arg.indexOf("=");
|
|
890
|
+
return eq === -1 ? arg : arg.slice(0, eq);
|
|
891
|
+
}
|
|
892
|
+
function matchesAbbreviatedFlag(args, flags) {
|
|
893
|
+
return args.some((arg) => {
|
|
894
|
+
const name = flagName(arg);
|
|
895
|
+
if (name.length < 3)
|
|
896
|
+
return false;
|
|
897
|
+
return flags.some((flag) => flag.startsWith(name) || name.startsWith(flag));
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
async function evaluateRescueHookRequest(workspaceRoot, toolName, toolInput) {
|
|
901
|
+
if (READ_ONLY_TOOLS.has(toolName)) {
|
|
902
|
+
return { decision: "allow" };
|
|
903
|
+
}
|
|
904
|
+
const posix = process.platform !== "win32";
|
|
905
|
+
if (posix && workspaceRoot.includes("\\")) {
|
|
906
|
+
return { decision: "deny", reason: backslashRootReason(workspaceRoot, toolName) };
|
|
907
|
+
}
|
|
908
|
+
let root;
|
|
909
|
+
try {
|
|
910
|
+
root = await realpath2(workspaceRoot);
|
|
911
|
+
} catch (err) {
|
|
912
|
+
return {
|
|
913
|
+
decision: "deny",
|
|
914
|
+
reason: `rescue cannot resolve workspace root: ${err.message}`
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
if (posix && root.includes("\\")) {
|
|
918
|
+
return { decision: "deny", reason: backslashRootReason(root, toolName) };
|
|
919
|
+
}
|
|
920
|
+
if (toolName === "Bash") {
|
|
921
|
+
const command = extractBashCommand(toolInput);
|
|
922
|
+
if (command === null) {
|
|
923
|
+
return {
|
|
924
|
+
decision: "deny",
|
|
925
|
+
reason: "rescue cannot evaluate Bash input with no command field"
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
const cwd = isObject(toolInput) ? toolInput.cwd : undefined;
|
|
929
|
+
if (cwd !== undefined) {
|
|
930
|
+
if (typeof cwd !== "string" || cwd.length === 0) {
|
|
931
|
+
return { decision: "deny", reason: "rescue requires Bash cwd to be a non-empty string" };
|
|
932
|
+
}
|
|
933
|
+
if (hasAmbiguousPathSpelling(cwd))
|
|
934
|
+
return ambiguousPathDenial(cwd, root);
|
|
935
|
+
try {
|
|
936
|
+
const outcome = await checkApprovedDirectory(root, cwd);
|
|
937
|
+
if (outcome === "symlink") {
|
|
938
|
+
return { decision: "deny", reason: `rescue rejects Bash cwd symlinks: ${cwd}` };
|
|
939
|
+
}
|
|
940
|
+
if (outcome === "missing") {
|
|
941
|
+
return { decision: "deny", reason: `rescue rejects Bash cwd that is missing or not a directory: ${cwd}` };
|
|
942
|
+
}
|
|
943
|
+
if (outcome === "reject") {
|
|
944
|
+
return { decision: "deny", reason: `rescue rejects Bash cwd outside the workspace or inside .git: ${cwd}` };
|
|
945
|
+
}
|
|
946
|
+
} catch (err) {
|
|
947
|
+
return { decision: "deny", reason: `rescue cannot inspect Bash cwd ${cwd}: ${err.message}` };
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
const result = await validateWorkspaceShellCommand(command, root);
|
|
951
|
+
return result.response === "approve" ? { decision: "allow" } : { decision: "deny", reason: result.feedback ?? "rescue rejected the shell command" };
|
|
952
|
+
}
|
|
953
|
+
if (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
|
|
954
|
+
for (const key of ["path", "file_path"]) {
|
|
955
|
+
const candidate = isObject(toolInput) ? toolInput[key] : undefined;
|
|
956
|
+
if (typeof candidate === "string" && hasAmbiguousPathSpelling(candidate)) {
|
|
957
|
+
return ambiguousPathDenial(candidate, root);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
const filePath = extractFilePath(toolInput);
|
|
961
|
+
if (filePath === null) {
|
|
962
|
+
return {
|
|
963
|
+
decision: "deny",
|
|
964
|
+
reason: `rescue cannot evaluate ${toolName} input with no path field`
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
try {
|
|
968
|
+
return pathDecision(await checkApprovedPath(root, filePath), filePath);
|
|
969
|
+
} catch (err) {
|
|
970
|
+
return {
|
|
971
|
+
decision: "deny",
|
|
972
|
+
reason: `rescue cannot inspect ${filePath} (outside the workspace, inside .git or unreadable): ${err.message}`
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return {
|
|
977
|
+
decision: "deny",
|
|
978
|
+
reason: `rescue does not allow tool "${toolName}" — only Bash, Write, Edit, MultiEdit (with allowlist checks) and read-only tools are permitted.`
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
function backslashRootReason(root, toolName) {
|
|
982
|
+
return `kimi-plugin-cc safety hook: writes cannot be confined to ${root}: it contains a backslash, ` + `which kimi-code reads as a path separator; tool "${toolName}" denied.`;
|
|
983
|
+
}
|
|
984
|
+
function hasAmbiguousPathSpelling(candidate) {
|
|
985
|
+
return candidate.includes("\\") || candidate.includes("\x00") || candidate.startsWith("~") || /^[A-Za-z]:/.test(candidate) || /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(candidate);
|
|
986
|
+
}
|
|
987
|
+
function ambiguousPathDenial(candidate, root) {
|
|
988
|
+
return {
|
|
989
|
+
decision: "deny",
|
|
990
|
+
reason: `rescue rejects the path ${JSON.stringify(candidate)}: a backslash, leading ~, drive letter, NUL or URL ` + `scheme can resolve differently in kimi-code; use a plain POSIX path under ${root}`
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
function pathDecision(outcome, filePath) {
|
|
994
|
+
if (outcome === "allow")
|
|
995
|
+
return { decision: "allow" };
|
|
996
|
+
if (outcome === "hardlink")
|
|
997
|
+
return { decision: "deny", reason: `${HARD_LINK_REASON}: ${filePath}` };
|
|
998
|
+
if (outcome === "symlink") {
|
|
999
|
+
return {
|
|
1000
|
+
decision: "deny",
|
|
1001
|
+
reason: `rescue does not overwrite symlinks: ${filePath}`
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
return {
|
|
1005
|
+
decision: "deny",
|
|
1006
|
+
reason: `rescue rejects file edits outside the workspace or inside .git: ${filePath}`
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
function extractBashCommand(toolInput) {
|
|
1010
|
+
if (!isObject(toolInput))
|
|
1011
|
+
return null;
|
|
1012
|
+
const command = toolInput.command;
|
|
1013
|
+
return typeof command === "string" && command.length > 0 ? command : null;
|
|
1014
|
+
}
|
|
1015
|
+
function extractFilePath(toolInput) {
|
|
1016
|
+
if (!isObject(toolInput))
|
|
1017
|
+
return null;
|
|
1018
|
+
const candidate = toolInput.path ?? toolInput.file_path;
|
|
1019
|
+
return typeof candidate === "string" && candidate.length > 0 ? candidate : null;
|
|
1020
|
+
}
|
|
1021
|
+
function isObject(value) {
|
|
1022
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1023
|
+
}
|
|
1024
|
+
async function checkApprovedPath(workspaceRoot, rawTargetPath) {
|
|
1025
|
+
const absoluteTarget = path2.isAbsolute(rawTargetPath) ? path2.resolve(rawTargetPath) : path2.resolve(workspaceRoot, rawTargetPath);
|
|
1026
|
+
const targetStats = await statIfExists(absoluteTarget);
|
|
1027
|
+
if (targetStats?.isSymbolicLink()) {
|
|
1028
|
+
return "symlink";
|
|
1029
|
+
}
|
|
1030
|
+
let candidatePath;
|
|
1031
|
+
if (targetStats !== null) {
|
|
1032
|
+
candidatePath = await realpath2(absoluteTarget);
|
|
1033
|
+
} else {
|
|
1034
|
+
const nearestExistingAncestor = await findNearestExistingAncestor(path2.dirname(absoluteTarget));
|
|
1035
|
+
const ancestorRealPath = await realpath2(nearestExistingAncestor);
|
|
1036
|
+
candidatePath = path2.resolve(ancestorRealPath, path2.relative(nearestExistingAncestor, absoluteTarget));
|
|
1037
|
+
}
|
|
1038
|
+
if (!isWithinWorkspaceOutsideAnyGit(workspaceRoot, candidatePath))
|
|
1039
|
+
return "reject";
|
|
1040
|
+
return isHardLinkedFile(targetStats) ? "hardlink" : "allow";
|
|
1041
|
+
}
|
|
1042
|
+
function isHardLinkedFile(stats) {
|
|
1043
|
+
return stats !== null && stats.isFile() && stats.nlink > 1;
|
|
1044
|
+
}
|
|
1045
|
+
var HARD_LINK_REASON = "rescue does not write through hard links";
|
|
1046
|
+
async function checkApprovedDirectory(workspaceRoot, rawCwd) {
|
|
1047
|
+
const candidate = path2.resolve(workspaceRoot, rawCwd);
|
|
1048
|
+
const stats = await statIfExists(candidate);
|
|
1049
|
+
if (stats?.isSymbolicLink())
|
|
1050
|
+
return "symlink";
|
|
1051
|
+
if (!stats?.isDirectory())
|
|
1052
|
+
return "missing";
|
|
1053
|
+
const resolved = await realpath2(candidate);
|
|
1054
|
+
return isWithinWorkspaceOutsideAnyGit(workspaceRoot, resolved) ? "allow" : "reject";
|
|
1055
|
+
}
|
|
1056
|
+
async function statIfExists(targetPath) {
|
|
1057
|
+
try {
|
|
1058
|
+
return await lstat2(targetPath);
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
if (error.code === "ENOENT") {
|
|
1061
|
+
return null;
|
|
1062
|
+
}
|
|
1063
|
+
throw error;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
async function findNearestExistingAncestor(targetDirectory) {
|
|
1067
|
+
let candidate = targetDirectory;
|
|
1068
|
+
while (true) {
|
|
1069
|
+
try {
|
|
1070
|
+
await access(candidate);
|
|
1071
|
+
return candidate;
|
|
1072
|
+
} catch {
|
|
1073
|
+
const parent = path2.dirname(candidate);
|
|
1074
|
+
if (parent === candidate) {
|
|
1075
|
+
return candidate;
|
|
1076
|
+
}
|
|
1077
|
+
candidate = parent;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
async function validateWorkspaceShellCommand(command, workspaceRoot) {
|
|
1082
|
+
const parsed = parseShellPipeline(command);
|
|
1083
|
+
if ("response" in parsed)
|
|
1084
|
+
return parsed;
|
|
1085
|
+
if (parsed.stages.filter((stage) => FILE_OPERATION_FLAGS.has(stage[0])).length > 1) {
|
|
1086
|
+
return rejectShell(`Rescue allows only one rm, mv, cp or mkdir per command: ${command}`);
|
|
1087
|
+
}
|
|
1088
|
+
for (let index = 0;index < parsed.stages.length; index += 1) {
|
|
1089
|
+
const stage = parsed.stages[index];
|
|
1090
|
+
const allowed = FILE_OPERATION_FLAGS.has(stage[0]) ? await validateFileOperationStage(stage, workspaceRoot) : validateShellStage(stage, parsed.stages.length > 1);
|
|
1091
|
+
if (!allowed.ok) {
|
|
1092
|
+
return rejectShell(allowed.reason);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
return { response: "approve" };
|
|
1096
|
+
}
|
|
1097
|
+
var MAX_SHELL_COMMAND_LENGTH = 16384;
|
|
1098
|
+
function parseShellPipeline(command) {
|
|
1099
|
+
if (command.length > MAX_SHELL_COMMAND_LENGTH) {
|
|
1100
|
+
return rejectShell(`Rescue rejects shell commands longer than ${MAX_SHELL_COMMAND_LENGTH} characters (this one has ${command.length}); split the work into shorter commands.`);
|
|
1101
|
+
}
|
|
1102
|
+
if (/[\r\n]/.test(command)) {
|
|
1103
|
+
return rejectShell(`Rescue rejects multi-line shell commands: ${JSON.stringify(command)}`);
|
|
1104
|
+
}
|
|
1105
|
+
if (hasUnsafeShellSyntax(command)) {
|
|
1106
|
+
return rejectShell(`Rescue rejects command substitution, process substitution, or backticks: ${command}`);
|
|
1107
|
+
}
|
|
1108
|
+
const parsed = parse(command);
|
|
1109
|
+
const stages = [[]];
|
|
1110
|
+
for (const token of parsed) {
|
|
1111
|
+
if (typeof token === "string") {
|
|
1112
|
+
stages.at(-1).push(token);
|
|
1113
|
+
continue;
|
|
1114
|
+
}
|
|
1115
|
+
if ("op" in token && token.op === "|") {
|
|
1116
|
+
stages.push([]);
|
|
1117
|
+
continue;
|
|
1118
|
+
}
|
|
1119
|
+
return rejectShell(`Rescue rejects shell syntax outside simple pipelines: ${command}`);
|
|
1120
|
+
}
|
|
1121
|
+
if (stages.some((stage) => stage.length === 0)) {
|
|
1122
|
+
return rejectShell(`Rescue rejects malformed shell pipelines: ${command}`);
|
|
1123
|
+
}
|
|
1124
|
+
return { stages };
|
|
1125
|
+
}
|
|
1126
|
+
var FILE_OPERATION_FLAGS = new Map([
|
|
1127
|
+
["rm", new Set(["-f", "-r", "-R", "-rf", "-fr"])],
|
|
1128
|
+
["mkdir", new Set(["-p"])],
|
|
1129
|
+
["mv", new Set(["-f", "-n"])],
|
|
1130
|
+
["cp", new Set(["-R", "-r", "-p", "-f", "-n"])]
|
|
1131
|
+
]);
|
|
1132
|
+
var FILE_OPERAND = /^[\p{L}\p{N}._+@%,:/ -]+$/u;
|
|
1133
|
+
async function validateFileOperationStage(tokens, workspaceRoot) {
|
|
1134
|
+
const [command, ...args] = tokens;
|
|
1135
|
+
const allowedFlags = FILE_OPERATION_FLAGS.get(command);
|
|
1136
|
+
const shown = tokens.join(" ");
|
|
1137
|
+
if (process.platform === "win32") {
|
|
1138
|
+
return { ok: false, reason: `Rescue does not allow ${command} on Windows: ${shown}` };
|
|
1139
|
+
}
|
|
1140
|
+
const flags = new Set;
|
|
1141
|
+
const operands = [];
|
|
1142
|
+
let endOfFlags = false;
|
|
1143
|
+
for (const arg of args) {
|
|
1144
|
+
if (!endOfFlags && arg === "--") {
|
|
1145
|
+
endOfFlags = true;
|
|
1146
|
+
continue;
|
|
1147
|
+
}
|
|
1148
|
+
if (!endOfFlags && arg.startsWith("-")) {
|
|
1149
|
+
if (!allowedFlags.has(arg)) {
|
|
1150
|
+
return {
|
|
1151
|
+
ok: false,
|
|
1152
|
+
reason: `Rescue allows ${command} only with ${[...allowedFlags].join(", ")} and --: ${shown}`
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
flags.add(arg);
|
|
1156
|
+
continue;
|
|
1157
|
+
}
|
|
1158
|
+
endOfFlags = true;
|
|
1159
|
+
if (!FILE_OPERAND.test(arg)) {
|
|
1160
|
+
return {
|
|
1161
|
+
ok: false,
|
|
1162
|
+
reason: `Rescue rejects ${command} operands with glob, expansion or other special characters: ${shown}`
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
if (!path2.isAbsolute(arg)) {
|
|
1166
|
+
return {
|
|
1167
|
+
ok: false,
|
|
1168
|
+
reason: `Rescue requires absolute paths for ${command}; use paths under ${workspaceRoot}: ${shown}`
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
if (arg.split("/").includes("..")) {
|
|
1172
|
+
return { ok: false, reason: `Rescue rejects ${command} operands containing "..": ${shown}` };
|
|
1173
|
+
}
|
|
1174
|
+
operands.push(arg);
|
|
1175
|
+
}
|
|
1176
|
+
const minimum = command === "mv" || command === "cp" ? 2 : 1;
|
|
1177
|
+
if (operands.length < minimum) {
|
|
1178
|
+
return { ok: false, reason: `Rescue requires ${command} to name at least ${minimum} path operand(s): ${shown}` };
|
|
1179
|
+
}
|
|
1180
|
+
try {
|
|
1181
|
+
const resolved = [];
|
|
1182
|
+
for (const operand of operands) {
|
|
1183
|
+
const outcome = await resolveFileOperand(workspaceRoot, operand);
|
|
1184
|
+
if (outcome === "symlink") {
|
|
1185
|
+
return { ok: false, reason: `Rescue rejects ${command} on a symlink operand: ${operand}` };
|
|
1186
|
+
}
|
|
1187
|
+
if (outcome === "reject") {
|
|
1188
|
+
return {
|
|
1189
|
+
ok: false,
|
|
1190
|
+
reason: `Rescue rejects ${command} operands outside the workspace or inside .git: ${operand}`
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
resolved.push(outcome);
|
|
1194
|
+
}
|
|
1195
|
+
const sources = command === "mv" || command === "cp" ? resolved.slice(0, -1) : resolved;
|
|
1196
|
+
if (command !== "mkdir" && sources.some((operand) => operand.path === workspaceRoot)) {
|
|
1197
|
+
return { ok: false, reason: `Rescue rejects ${command} on the workspace root itself: ${shown}` };
|
|
1198
|
+
}
|
|
1199
|
+
if (command === "mv" || command === "cp") {
|
|
1200
|
+
const missing = sources.find((source) => source.stats === null);
|
|
1201
|
+
if (missing !== undefined) {
|
|
1202
|
+
return { ok: false, reason: `Rescue requires every ${command} source to exist: ${missing.path}` };
|
|
1203
|
+
}
|
|
1204
|
+
const destination = resolved.at(-1);
|
|
1205
|
+
const landing = sources.map((source) => destination.stats?.isDirectory() ? path2.join(destination.path, path2.basename(source.path)) : destination.path);
|
|
1206
|
+
for (const [index, source] of sources.entries()) {
|
|
1207
|
+
if (landing.some((target, other) => other !== index && isWithin2(target, source.path))) {
|
|
1208
|
+
return { ok: false, reason: `Rescue rejects ${command} where a source lies under another source's destination: ${shown}` };
|
|
1209
|
+
}
|
|
1210
|
+
const inside = (target) => target !== source.path && isWithin2(source.path, target);
|
|
1211
|
+
if (inside(destination.path) || inside(landing[index])) {
|
|
1212
|
+
return { ok: false, reason: `Rescue rejects ${command} whose destination lies under one of its sources: ${shown}` };
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
const recursive = flags.has("-r") || flags.has("-R") || flags.has("-rf") || flags.has("-fr");
|
|
1217
|
+
const treeOperation = command === "rm" && recursive ? { label: "rm -r", remedy: "delete" } : command === "mv" ? { label: "mv", remedy: "move" } : command === "cp" && recursive ? { label: "cp -R", remedy: "copy" } : null;
|
|
1218
|
+
if (treeOperation !== null) {
|
|
1219
|
+
const scan = await scanTreesForGit(sources.filter((operand) => operand.stats?.isDirectory()).map((operand) => operand.path));
|
|
1220
|
+
if (scan === "git") {
|
|
1221
|
+
return {
|
|
1222
|
+
ok: false,
|
|
1223
|
+
reason: `Rescue rejects ${treeOperation.label} of a tree that holds a .git entry at any depth: ${shown}`
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
if (scan !== "clean") {
|
|
1227
|
+
return {
|
|
1228
|
+
ok: false,
|
|
1229
|
+
reason: `Rescue could not prove ${treeOperation.label} leaves every .git intact (${scan}); ` + `${treeOperation.remedy} in smaller pieces: ${shown}`
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
if (command === "mv" || command === "cp") {
|
|
1234
|
+
const destination = resolved.at(-1);
|
|
1235
|
+
if (command === "cp" && recursive && destination.stats !== null && sources.some((source) => source.stats?.isDirectory())) {
|
|
1236
|
+
return {
|
|
1237
|
+
ok: false,
|
|
1238
|
+
reason: `Rescue allows cp -R of a directory only to a destination that does not exist yet: ${shown}`
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
if (command === "cp" && isHardLinkedFile(destination.stats)) {
|
|
1242
|
+
return { ok: false, reason: `${HARD_LINK_REASON}: ${destination.path}` };
|
|
1243
|
+
}
|
|
1244
|
+
if (destination.stats?.isDirectory()) {
|
|
1245
|
+
for (const source of sources) {
|
|
1246
|
+
const target = path2.join(destination.path, path2.basename(source.path));
|
|
1247
|
+
const targetStats = await statIfExists(target);
|
|
1248
|
+
if (targetStats?.isSymbolicLink()) {
|
|
1249
|
+
return { ok: false, reason: `Rescue rejects ${command} onto a symlink: ${target}` };
|
|
1250
|
+
}
|
|
1251
|
+
if (command === "cp" && isHardLinkedFile(targetStats)) {
|
|
1252
|
+
return { ok: false, reason: `${HARD_LINK_REASON}: ${target}` };
|
|
1253
|
+
}
|
|
1254
|
+
if (!isWithinWorkspaceOutsideAnyGit(workspaceRoot, target)) {
|
|
1255
|
+
return { ok: false, reason: `Rescue rejects ${command} into .git: ${target}` };
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
} catch (err) {
|
|
1261
|
+
return { ok: false, reason: `Rescue cannot inspect ${command} operands: ${err.message}` };
|
|
1262
|
+
}
|
|
1263
|
+
return { ok: true };
|
|
1264
|
+
}
|
|
1265
|
+
async function resolveFileOperand(workspaceRoot, operand) {
|
|
1266
|
+
const absolute = path2.resolve(operand);
|
|
1267
|
+
const stats = await statIfExists(absolute);
|
|
1268
|
+
if (stats?.isSymbolicLink())
|
|
1269
|
+
return "symlink";
|
|
1270
|
+
let candidate;
|
|
1271
|
+
if (stats !== null) {
|
|
1272
|
+
candidate = await realpath2(absolute);
|
|
1273
|
+
} else {
|
|
1274
|
+
let ancestor = path2.dirname(absolute);
|
|
1275
|
+
let ancestorReal = null;
|
|
1276
|
+
while (ancestorReal === null) {
|
|
1277
|
+
try {
|
|
1278
|
+
ancestorReal = await realpath2(ancestor);
|
|
1279
|
+
} catch (err) {
|
|
1280
|
+
if (err.code !== "ENOENT")
|
|
1281
|
+
throw err;
|
|
1282
|
+
if (await statIfExists(ancestor) !== null)
|
|
1283
|
+
return "reject";
|
|
1284
|
+
const parent = path2.dirname(ancestor);
|
|
1285
|
+
if (parent === ancestor)
|
|
1286
|
+
return "reject";
|
|
1287
|
+
ancestor = parent;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
candidate = path2.join(ancestorReal, path2.relative(ancestor, absolute));
|
|
1291
|
+
}
|
|
1292
|
+
return isWithinWorkspaceOutsideAnyGit(workspaceRoot, candidate) ? { path: candidate, stats } : "reject";
|
|
1293
|
+
}
|
|
1294
|
+
function validateShellStage(tokens, pipelineMode) {
|
|
1295
|
+
const [command, ...args] = tokens;
|
|
1296
|
+
if (!command || path2.isAbsolute(command) || command.includes(path2.sep)) {
|
|
1297
|
+
return { ok: false, reason: `Rescue rejects non-standard shell entrypoints: ${tokens.join(" ")}` };
|
|
1298
|
+
}
|
|
1299
|
+
if (hasMutatingFlag(command === "grep" ? args.filter((arg) => arg !== "-i") : args)) {
|
|
1300
|
+
return { ok: false, reason: `Rescue rejects mutating shell flags: ${tokens.join(" ")}` };
|
|
1301
|
+
}
|
|
1302
|
+
if (hasExecDelegatingFlag(args)) {
|
|
1303
|
+
return {
|
|
1304
|
+
ok: false,
|
|
1305
|
+
reason: `Rescue rejects flags that execute an external command/tool (e.g. --open-files-in-pager, -vettool, -exec, -toolexec): ${tokens.join(" ")}`
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
if (command === "git") {
|
|
1309
|
+
const gitArgs = args[0] === "--no-pager" ? args.slice(1) : args;
|
|
1310
|
+
const firstArg = gitArgs[0] ?? "";
|
|
1311
|
+
if (firstArg.startsWith("-")) {
|
|
1312
|
+
return {
|
|
1313
|
+
ok: false,
|
|
1314
|
+
reason: `Rescue rejects git pre-subcommand flags (e.g. -c/-C/-p/--exec-path): ${tokens.join(" ")}. Put the read-only subcommand immediately after \`git\` or \`git --no-pager\`.`
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
if (args.some((arg) => arg === "-O" || /^-O./.test(arg))) {
|
|
1318
|
+
return {
|
|
1319
|
+
ok: false,
|
|
1320
|
+
reason: `Rescue rejects git -O/--open-files-in-pager (executes the pager value as a command): ${tokens.join(" ")}.`
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
return GIT_READONLY_SUBCOMMANDS.has(firstArg) ? { ok: true } : { ok: false, reason: `Rescue rejects git mutation commands: ${tokens.join(" ")}` };
|
|
1324
|
+
}
|
|
1325
|
+
if (command === "find") {
|
|
1326
|
+
return args.some((arg) => BANNED_FIND_ACTIONS.has(arg)) ? {
|
|
1327
|
+
ok: false,
|
|
1328
|
+
reason: `Rescue rejects find actions that execute or write files: ${tokens.join(" ")}`
|
|
1329
|
+
} : { ok: true };
|
|
1330
|
+
}
|
|
1331
|
+
if (command === "tsc") {
|
|
1332
|
+
const tscLowerNames = args.map((arg) => flagName(arg).toLowerCase());
|
|
1333
|
+
if (!tscLowerNames.includes("--noemit")) {
|
|
1334
|
+
return { ok: false, reason: "Rescue allows tsc only with --noEmit." };
|
|
1335
|
+
}
|
|
1336
|
+
if (tscLowerNames.some((name) => TSC_WRITE_FLAGS_LC.has(name))) {
|
|
1337
|
+
return {
|
|
1338
|
+
ok: false,
|
|
1339
|
+
reason: `Rescue rejects tsc write flags (--generateCpuProfile, --generateTrace, --tsBuildInfoFile, --outFile, --outDir, --out, --declarationDir — case-insensitive): ${tokens.join(" ")}.`
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
return { ok: true };
|
|
1343
|
+
}
|
|
1344
|
+
if (command === "biome") {
|
|
1345
|
+
if (args[0] !== "check") {
|
|
1346
|
+
return { ok: false, reason: "Rescue allows biome only in check mode." };
|
|
1347
|
+
}
|
|
1348
|
+
if (args.some((arg) => /^--(apply|write|fix)/.test(arg))) {
|
|
1349
|
+
return {
|
|
1350
|
+
ok: false,
|
|
1351
|
+
reason: `Rescue rejects biome check write flags (--apply, --apply-unsafe, --write, --fix, and -unsafe/-only variants): ${tokens.join(" ")}.`
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
return { ok: true };
|
|
1355
|
+
}
|
|
1356
|
+
if (command === "ruff") {
|
|
1357
|
+
if (args[0] === "check") {
|
|
1358
|
+
if (hasWriteShortFlag(args)) {
|
|
1359
|
+
return {
|
|
1360
|
+
ok: false,
|
|
1361
|
+
reason: `Rescue rejects ruff -o (writes the report to a file): ${tokens.join(" ")}.`
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
if (hasFlagFromSet(args, RUFF_WRITE_FLAGS)) {
|
|
1365
|
+
return {
|
|
1366
|
+
ok: false,
|
|
1367
|
+
reason: `Rescue rejects ruff write flags (--add-noqa, --fix-only, --cache-dir, --output-file): ${tokens.join(" ")}.`
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
return { ok: true };
|
|
1371
|
+
}
|
|
1372
|
+
if (args[0] === "format") {
|
|
1373
|
+
return args.some((arg) => arg === "--check" || arg === "--diff") ? { ok: true } : { ok: false, reason: "Rescue allows ruff format only with --check or --diff." };
|
|
1374
|
+
}
|
|
1375
|
+
return { ok: false, reason: `Rescue rejects ruff subcommand: ${tokens.join(" ")}` };
|
|
1376
|
+
}
|
|
1377
|
+
if (command === "cargo") {
|
|
1378
|
+
if (args[0] === "fmt") {
|
|
1379
|
+
return args.includes("--check") ? { ok: true } : { ok: false, reason: "Rescue allows cargo fmt only with --check." };
|
|
1380
|
+
}
|
|
1381
|
+
if (!CARGO_SUBCOMMANDS.has(args[0] ?? "")) {
|
|
1382
|
+
return { ok: false, reason: `Rescue rejects cargo subcommand: ${tokens.join(" ")}` };
|
|
1383
|
+
}
|
|
1384
|
+
if (hasFlagFromSet(args, CARGO_WRITE_FLAGS)) {
|
|
1385
|
+
return {
|
|
1386
|
+
ok: false,
|
|
1387
|
+
reason: `Rescue rejects cargo --target-dir/--out-dir (writes artifacts to an arbitrary path): ${tokens.join(" ")}.`
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
return { ok: true };
|
|
1391
|
+
}
|
|
1392
|
+
if (command === "go") {
|
|
1393
|
+
if (!GO_SUBCOMMANDS.has(args[0] ?? "")) {
|
|
1394
|
+
return { ok: false, reason: `Rescue rejects go subcommand: ${tokens.join(" ")}` };
|
|
1395
|
+
}
|
|
1396
|
+
if (hasWriteShortFlag(args)) {
|
|
1397
|
+
return {
|
|
1398
|
+
ok: false,
|
|
1399
|
+
reason: `Rescue rejects go -o (writes a binary to an arbitrary path): ${tokens.join(" ")}.`
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
if (hasFlagFromSet(args, GO_WRITE_FLAGS)) {
|
|
1403
|
+
return {
|
|
1404
|
+
ok: false,
|
|
1405
|
+
reason: `Rescue rejects go profile/output flags (-coverprofile, -cpuprofile, -memprofile, -blockprofile, -mutexprofile, -trace, -outputdir write to arbitrary paths): ${tokens.join(" ")}.`
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
return { ok: true };
|
|
1409
|
+
}
|
|
1410
|
+
if (command === "python" || command === "python3") {
|
|
1411
|
+
if (args[0] !== "-m" || args[1] !== "pytest") {
|
|
1412
|
+
return { ok: false, reason: `Rescue rejects ${command} shell command: ${tokens.join(" ")}` };
|
|
1413
|
+
}
|
|
1414
|
+
if (hasPytestReportFlag(args.slice(2))) {
|
|
1415
|
+
return pytestReportFlagRejection(tokens);
|
|
1416
|
+
}
|
|
1417
|
+
return { ok: true };
|
|
1418
|
+
}
|
|
1419
|
+
if (command === "npm" || command === "pnpm" || command === "yarn" || command === "bun" || command === "uv") {
|
|
1420
|
+
return validatePackageManagerCommand(command, args);
|
|
1421
|
+
}
|
|
1422
|
+
if (command === "eslint") {
|
|
1423
|
+
if (hasWriteShortFlag(args)) {
|
|
1424
|
+
return {
|
|
1425
|
+
ok: false,
|
|
1426
|
+
reason: `Rescue rejects eslint -o (writes report to a file): ${tokens.join(" ")}. Drop the flag or use a path-checked Write tool call.`
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
if (hasFlagFromSet(args, ESLINT_WRITE_FLAGS)) {
|
|
1430
|
+
return {
|
|
1431
|
+
ok: false,
|
|
1432
|
+
reason: `Rescue rejects eslint --cache-location/--output-file (writes to an arbitrary path): ${tokens.join(" ")}.`
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
if (hasFlagFromSet(args, ESLINT_CODELOAD_FLAGS)) {
|
|
1436
|
+
return {
|
|
1437
|
+
ok: false,
|
|
1438
|
+
reason: `Rescue rejects eslint --parser/--rulesdir/--resolve-plugins-relative-to (loads and executes a module from the given path): ${tokens.join(" ")}.`
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
return { ok: true };
|
|
1442
|
+
}
|
|
1443
|
+
if (command === "mypy") {
|
|
1444
|
+
if (matchesAbbreviatedFlag(args, MYPY_WRITE_FLAGS_ABBREV)) {
|
|
1445
|
+
return {
|
|
1446
|
+
ok: false,
|
|
1447
|
+
reason: `Rescue rejects mypy report/cache/install flags (--junit-xml, --*-report, --cache-dir, --install-types — incl. argparse abbreviations — write outside the workspace or run pip): ${tokens.join(" ")}.`
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
return { ok: true };
|
|
1451
|
+
}
|
|
1452
|
+
if (command === "pytest") {
|
|
1453
|
+
if (hasPytestReportFlag(args)) {
|
|
1454
|
+
return pytestReportFlagRejection(tokens);
|
|
1455
|
+
}
|
|
1456
|
+
return { ok: true };
|
|
1457
|
+
}
|
|
1458
|
+
if (["rg", "grep", "ls", "cat", "pwd", "pyright"].includes(command)) {
|
|
1459
|
+
return { ok: true };
|
|
1460
|
+
}
|
|
1461
|
+
if (pipelineMode && PIPELINE_PLUMBING.has(command)) {
|
|
1462
|
+
if (hasWriteShortFlag(args) || args.includes("--output")) {
|
|
1463
|
+
return {
|
|
1464
|
+
ok: false,
|
|
1465
|
+
reason: `Rescue rejects ${command} -o/--output (writes to an arbitrary file): ${tokens.join(" ")}.`
|
|
1466
|
+
};
|
|
1467
|
+
}
|
|
1468
|
+
if (command === "sort" && (args.some((arg) => sortShortClusterWrites(arg)) || args.includes("--temporary-directory") || args.some((arg) => arg.startsWith("--temporary-directory=")))) {
|
|
1469
|
+
return {
|
|
1470
|
+
ok: false,
|
|
1471
|
+
reason: `Rescue rejects sort -o/-T (incl. bundled short clusters like -rT) and --temporary-directory (write to an arbitrary path): ${tokens.join(" ")}.`
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
if (command === "uniq" && args.filter((arg) => arg === "-" || !arg.startsWith("-")).length >= 2) {
|
|
1475
|
+
return {
|
|
1476
|
+
ok: false,
|
|
1477
|
+
reason: `Rescue rejects uniq with an output-file argument (uniq IN OUT writes OUT): ${tokens.join(" ")}.`
|
|
1478
|
+
};
|
|
68
1479
|
}
|
|
69
|
-
|
|
1480
|
+
return { ok: true };
|
|
1481
|
+
}
|
|
1482
|
+
return { ok: false, reason: `Rescue rejects shell command: ${tokens.join(" ")}` };
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
class ShellExpansionError extends Error {
|
|
1486
|
+
}
|
|
1487
|
+
function throwingExpansionEnv(key) {
|
|
1488
|
+
if (key !== "")
|
|
1489
|
+
throw new ShellExpansionError(key);
|
|
1490
|
+
return "$";
|
|
1491
|
+
}
|
|
1492
|
+
function hasShellExpansion(command) {
|
|
1493
|
+
try {
|
|
1494
|
+
parse(command, throwingExpansionEnv);
|
|
1495
|
+
return false;
|
|
1496
|
+
} catch {
|
|
1497
|
+
return true;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
function isBraceExpansion(s, open) {
|
|
1501
|
+
if (open > 0 && s[open - 1] === "$")
|
|
1502
|
+
return false;
|
|
1503
|
+
let depth = 0;
|
|
1504
|
+
let sawSeparator = false;
|
|
1505
|
+
for (let j = open;j < s.length; j += 1) {
|
|
1506
|
+
const ch = s[j];
|
|
1507
|
+
if (ch === "\\") {
|
|
1508
|
+
j += 1;
|
|
1509
|
+
continue;
|
|
1510
|
+
}
|
|
1511
|
+
if (ch === "'" || ch === '"')
|
|
1512
|
+
return false;
|
|
1513
|
+
if (ch === "{") {
|
|
1514
|
+
depth += 1;
|
|
1515
|
+
} else if (ch === "}") {
|
|
1516
|
+
depth -= 1;
|
|
1517
|
+
if (depth === 0)
|
|
1518
|
+
return sawSeparator;
|
|
1519
|
+
} else if (depth === 1 && (ch === "," || ch === "." && s[j + 1] === ".")) {
|
|
1520
|
+
sawSeparator = true;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
return false;
|
|
1524
|
+
}
|
|
1525
|
+
function scanUnsafeUnquoted(command) {
|
|
1526
|
+
const n = command.length;
|
|
1527
|
+
let i = 0;
|
|
1528
|
+
while (i < n) {
|
|
1529
|
+
const c = command[i];
|
|
1530
|
+
if (c === "\\") {
|
|
1531
|
+
i += 2;
|
|
1532
|
+
continue;
|
|
1533
|
+
}
|
|
1534
|
+
if (c === "'") {
|
|
1535
|
+
const end = command.indexOf("'", i + 1);
|
|
1536
|
+
if (end === -1)
|
|
1537
|
+
return true;
|
|
1538
|
+
i = end + 1;
|
|
1539
|
+
continue;
|
|
1540
|
+
}
|
|
1541
|
+
if (c === '"') {
|
|
1542
|
+
i += 1;
|
|
1543
|
+
while (i < n && command[i] !== '"') {
|
|
1544
|
+
if (command[i] === "\\") {
|
|
1545
|
+
i += 2;
|
|
1546
|
+
continue;
|
|
1547
|
+
}
|
|
1548
|
+
if (command[i] === "`")
|
|
1549
|
+
return true;
|
|
1550
|
+
if (command[i] === "$" && command[i + 1] === "(")
|
|
1551
|
+
return true;
|
|
1552
|
+
i += 1;
|
|
1553
|
+
}
|
|
1554
|
+
if (i >= n)
|
|
1555
|
+
return true;
|
|
1556
|
+
i += 1;
|
|
1557
|
+
continue;
|
|
1558
|
+
}
|
|
1559
|
+
if (c === "`")
|
|
1560
|
+
return true;
|
|
1561
|
+
if (c === "$" && (command[i + 1] === "'" || command[i + 1] === '"'))
|
|
1562
|
+
return true;
|
|
1563
|
+
if (c === "$" && command[i + 1] === "(")
|
|
1564
|
+
return true;
|
|
1565
|
+
if ((c === "<" || c === ">") && command[i + 1] === "(")
|
|
1566
|
+
return true;
|
|
1567
|
+
if (c === "{" && isBraceExpansion(command, i))
|
|
1568
|
+
return true;
|
|
1569
|
+
i += 1;
|
|
1570
|
+
}
|
|
1571
|
+
return false;
|
|
1572
|
+
}
|
|
1573
|
+
function hasUnsafeShellSyntax(command) {
|
|
1574
|
+
return scanUnsafeUnquoted(command) || hasShellExpansion(command);
|
|
1575
|
+
}
|
|
1576
|
+
function hasMutatingFlag(args) {
|
|
1577
|
+
for (const arg of args) {
|
|
1578
|
+
if (MUTATING_FLAGS_EXACT.has(arg)) {
|
|
1579
|
+
return true;
|
|
1580
|
+
}
|
|
1581
|
+
if (MUTATING_FLAG_PREFIXES.some((prefix) => arg.startsWith(prefix))) {
|
|
1582
|
+
return true;
|
|
1583
|
+
}
|
|
1584
|
+
if (/^-i[.=]/.test(arg)) {
|
|
1585
|
+
return true;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
return false;
|
|
1589
|
+
}
|
|
1590
|
+
function hasExecDelegatingFlag(args) {
|
|
1591
|
+
return args.some((arg) => EXEC_DELEGATING_FLAGS_EXACT.has(arg) || EXEC_DELEGATING_FLAG_PREFIXES.some((prefix) => arg.startsWith(prefix)));
|
|
1592
|
+
}
|
|
1593
|
+
function hasWriteShortFlag(args) {
|
|
1594
|
+
return args.some((arg) => arg === "-o" || /^-o./.test(arg));
|
|
1595
|
+
}
|
|
1596
|
+
function sortShortClusterWrites(token) {
|
|
1597
|
+
if (token.length < 2 || token[0] !== "-" || token[1] === "-")
|
|
1598
|
+
return false;
|
|
1599
|
+
for (let i = 1;i < token.length; i += 1) {
|
|
1600
|
+
const ch = token[i];
|
|
1601
|
+
if (ch === "o" || ch === "T")
|
|
1602
|
+
return true;
|
|
1603
|
+
if (ch === "t" || ch === "k" || ch === "S")
|
|
1604
|
+
return false;
|
|
1605
|
+
}
|
|
1606
|
+
return false;
|
|
1607
|
+
}
|
|
1608
|
+
function hasPytestReportFlag(args) {
|
|
1609
|
+
return matchesAbbreviatedFlag(args, PYTEST_REPORT_FLAGS);
|
|
1610
|
+
}
|
|
1611
|
+
function pytestReportFlagRejection(tokens) {
|
|
1612
|
+
return {
|
|
1613
|
+
ok: false,
|
|
1614
|
+
reason: `Rescue rejects pytest report-writing flags (--junitxml, --result-log, --report-log): ${tokens.join(" ")}.`
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
function validatePackageManagerCommand(command, args) {
|
|
1618
|
+
if (args[0] === "test") {
|
|
1619
|
+
return { ok: true };
|
|
1620
|
+
}
|
|
1621
|
+
return {
|
|
1622
|
+
ok: false,
|
|
1623
|
+
reason: `Rescue rejects ${command} ${args.join(" ")}. Use direct tools (tsc --noEmit, pyright, mypy, ruff check, eslint, pytest) instead of package.json scripts.`
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
function isWithin2(root, target) {
|
|
1627
|
+
return target === root || target.startsWith(`${root}${path2.sep}`);
|
|
1628
|
+
}
|
|
1629
|
+
function isGitName(segment) {
|
|
1630
|
+
return segment.replace(/[. ]+$/, "").toLowerCase() === ".git";
|
|
1631
|
+
}
|
|
1632
|
+
function isWithinWorkspaceOutsideAnyGit(root, target) {
|
|
1633
|
+
return isWithin2(root, target) && !path2.relative(root, target).split(path2.sep).some(isGitName);
|
|
1634
|
+
}
|
|
1635
|
+
var RM_RECURSIVE_SCAN_ENTRY_CAP = 20000;
|
|
1636
|
+
var GIT_SCAN_DEADLINE_MS = 3000;
|
|
1637
|
+
async function scanTreesForGit(roots, { cap = RM_RECURSIVE_SCAN_ENTRY_CAP, deadlineMs = GIT_SCAN_DEADLINE_MS } = {}) {
|
|
1638
|
+
const deadline = Date.now() + deadlineMs;
|
|
1639
|
+
const late = () => Date.now() >= deadline;
|
|
1640
|
+
const pending = [];
|
|
1641
|
+
for (const root of roots) {
|
|
1642
|
+
pending.push({ directory: root, device: (await lstat2(root)).dev });
|
|
1643
|
+
}
|
|
1644
|
+
let seen = 0;
|
|
1645
|
+
while (pending.length > 0) {
|
|
1646
|
+
if (late())
|
|
1647
|
+
return `took longer than ${deadlineMs} ms`;
|
|
1648
|
+
const { directory, device } = pending.pop();
|
|
1649
|
+
let entries;
|
|
1650
|
+
try {
|
|
1651
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
1652
|
+
} catch (err) {
|
|
1653
|
+
return `cannot read ${directory}: ${err.code ?? err.message}`;
|
|
1654
|
+
}
|
|
1655
|
+
for (const entry of entries) {
|
|
1656
|
+
seen += 1;
|
|
1657
|
+
if (seen > cap)
|
|
1658
|
+
return `more than ${cap} entries`;
|
|
1659
|
+
if (isGitName(entry.name))
|
|
1660
|
+
return "git";
|
|
1661
|
+
if (!entry.isDirectory())
|
|
1662
|
+
continue;
|
|
1663
|
+
const child = path2.join(directory, entry.name);
|
|
1664
|
+
let childDevice;
|
|
1665
|
+
try {
|
|
1666
|
+
childDevice = (await lstat2(child)).dev;
|
|
1667
|
+
} catch (err) {
|
|
1668
|
+
return `cannot read ${child}: ${err.code ?? err.message}`;
|
|
1669
|
+
}
|
|
1670
|
+
if (childDevice !== device)
|
|
1671
|
+
return `crosses a filesystem boundary at ${child}`;
|
|
1672
|
+
if (late())
|
|
1673
|
+
return `took longer than ${deadlineMs} ms`;
|
|
1674
|
+
pending.push({ directory: child, device });
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
return "clean";
|
|
1678
|
+
}
|
|
1679
|
+
function rejectShell(feedback) {
|
|
1680
|
+
return { response: "reject", feedback };
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
// runtime/hooks/approval-hook.ts
|
|
1684
|
+
var STDIN_TIMEOUT_MS = 5000;
|
|
1685
|
+
async function main() {
|
|
1686
|
+
armDecisionDeadline();
|
|
1687
|
+
const stdinText = await readStdinWithTimeout(STDIN_TIMEOUT_MS);
|
|
1688
|
+
let input;
|
|
1689
|
+
try {
|
|
1690
|
+
const parsed = JSON.parse(stdinText);
|
|
1691
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
1692
|
+
throw new Error("hook payload must be a JSON object");
|
|
1693
|
+
}
|
|
1694
|
+
input = parsed;
|
|
1695
|
+
} catch (err) {
|
|
1696
|
+
failClosed(`stdin was not a JSON object: ${formatErr(err)}`);
|
|
1697
|
+
return;
|
|
1698
|
+
}
|
|
1699
|
+
await testOnlyDelay(process.env[HOOK_TEST_DELAY_ENV]);
|
|
1700
|
+
const decision = await decideHookOutcome(input, {
|
|
1701
|
+
commandLabel: process.env.KIMI_PLUGIN_CC_CMD,
|
|
1702
|
+
operationKind: process.env.KIMI_PLUGIN_CC_OPERATION,
|
|
1703
|
+
swarmPolicy: process.env[SWARM_POLICY_ENV],
|
|
1704
|
+
swarmWaveSize: process.env[SWARM_WAVE_SIZE_ENV],
|
|
1705
|
+
rescueEvaluator: evaluateRescueHookRequest,
|
|
1706
|
+
trustedWorkspaceRoot: process.env.KIMI_PLUGIN_CC_WORKSPACE_ROOT,
|
|
1707
|
+
readRoots: process.env[READ_ROOTS_ENV],
|
|
1708
|
+
network: process.env[NETWORK_ENV]
|
|
1709
|
+
});
|
|
1710
|
+
if (decision.decision === "deny") {
|
|
1711
|
+
process.stderr.write(`${decision.reason ?? "denied"}
|
|
1712
|
+
`);
|
|
1713
|
+
process.exit(2);
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
process.exit(0);
|
|
70
1717
|
}
|
|
71
|
-
/**
|
|
72
|
-
* A timed-out hook is ALLOW upstream, so a labelled call that has not decided
|
|
73
|
-
* within HOOK_DECISION_DEADLINE_MS (below the installed timeout) denies. The
|
|
74
|
-
* timer is unref'd so it never keeps a decided process alive; a stall with
|
|
75
|
-
* nothing pending would then drain the loop and exit 0, so `beforeExit`
|
|
76
|
-
* denies too. Every decision path exits explicitly before either fires.
|
|
77
|
-
* Unlabelled calls are out-of-plugin use and keep their exit-0 behaviour.
|
|
78
|
-
*/
|
|
79
1718
|
function armDecisionDeadline() {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
1719
|
+
const label = process.env.KIMI_PLUGIN_CC_CMD;
|
|
1720
|
+
if (label === undefined || label.length === 0)
|
|
1721
|
+
return;
|
|
1722
|
+
const reason = `kimi-plugin-cc safety hook: no decision within ${HOOK_DECISION_DEADLINE_MS / 1000}s; ` + "the tool call is denied because a hook that times out would be read as allow.";
|
|
1723
|
+
setTimeout(() => {
|
|
1724
|
+
process.stderr.write(`${reason}
|
|
1725
|
+
`);
|
|
1726
|
+
process.exit(2);
|
|
1727
|
+
}, HOOK_DECISION_DEADLINE_MS).unref();
|
|
1728
|
+
process.once("beforeExit", () => {
|
|
1729
|
+
process.stderr.write(`${reason}
|
|
1730
|
+
`);
|
|
1731
|
+
process.exit(2);
|
|
1732
|
+
});
|
|
93
1733
|
}
|
|
94
1734
|
async function testOnlyDelay(value) {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
1735
|
+
if (value === undefined || value.length === 0)
|
|
1736
|
+
return;
|
|
1737
|
+
if (value === "hang") {
|
|
1738
|
+
await new Promise(() => {});
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
const ms = Number(value);
|
|
1742
|
+
if (Number.isSafeInteger(ms) && ms > 0)
|
|
1743
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
104
1744
|
}
|
|
105
1745
|
function failClosed(reason) {
|
|
106
|
-
|
|
107
|
-
|
|
1746
|
+
process.stderr.write(`kimi-plugin-cc safety hook misconfigured: ${reason}
|
|
1747
|
+
`);
|
|
1748
|
+
process.exit(2);
|
|
108
1749
|
}
|
|
109
1750
|
function formatErr(err) {
|
|
110
|
-
|
|
1751
|
+
return err instanceof Error ? err.message : String(err);
|
|
111
1752
|
}
|
|
112
1753
|
function readStdinWithTimeout(timeoutMs) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
process.stdin.on("data", (chunk) => {
|
|
137
|
-
buf += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
138
|
-
});
|
|
139
|
-
process.stdin.on("end", () => finish(buf));
|
|
140
|
-
process.stdin.on("error", (err) => finish(err instanceof Error ? err : new Error(String(err))));
|
|
1754
|
+
return new Promise((resolve, reject) => {
|
|
1755
|
+
let buf = "";
|
|
1756
|
+
let settled = false;
|
|
1757
|
+
const finish = (value) => {
|
|
1758
|
+
if (settled)
|
|
1759
|
+
return;
|
|
1760
|
+
settled = true;
|
|
1761
|
+
clearTimeout(timer);
|
|
1762
|
+
if (value instanceof Error)
|
|
1763
|
+
reject(value);
|
|
1764
|
+
else
|
|
1765
|
+
resolve(value);
|
|
1766
|
+
};
|
|
1767
|
+
const timer = setTimeout(() => {
|
|
1768
|
+
finish(new Error(`stdin did not close within ${timeoutMs}ms`));
|
|
1769
|
+
}, timeoutMs);
|
|
1770
|
+
timer.unref();
|
|
1771
|
+
try {
|
|
1772
|
+
process.stdin.setEncoding("utf8");
|
|
1773
|
+
} catch {}
|
|
1774
|
+
process.stdin.on("data", (chunk) => {
|
|
1775
|
+
buf += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
141
1776
|
});
|
|
1777
|
+
process.stdin.on("end", () => finish(buf));
|
|
1778
|
+
process.stdin.on("error", (err) => finish(err instanceof Error ? err : new Error(String(err))));
|
|
1779
|
+
});
|
|
142
1780
|
}
|
|
143
1781
|
main().catch((err) => {
|
|
144
|
-
|
|
1782
|
+
failClosed(`uncaught error: ${formatErr(err)}`);
|
|
145
1783
|
});
|