kneepad 0.3.0__tar.gz

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.
Files changed (43) hide show
  1. kneepad-0.3.0/LICENSE +21 -0
  2. kneepad-0.3.0/PKG-INFO +104 -0
  3. kneepad-0.3.0/README.md +87 -0
  4. kneepad-0.3.0/pyproject.toml +31 -0
  5. kneepad-0.3.0/setup.cfg +4 -0
  6. kneepad-0.3.0/src/kneepad/__init__.py +3 -0
  7. kneepad-0.3.0/src/kneepad/__main__.py +6 -0
  8. kneepad-0.3.0/src/kneepad/adapters.py +277 -0
  9. kneepad-0.3.0/src/kneepad/api.py +62 -0
  10. kneepad-0.3.0/src/kneepad/argvtools.py +300 -0
  11. kneepad-0.3.0/src/kneepad/audit.py +303 -0
  12. kneepad-0.3.0/src/kneepad/badge.py +30 -0
  13. kneepad-0.3.0/src/kneepad/cli.py +498 -0
  14. kneepad-0.3.0/src/kneepad/config.py +185 -0
  15. kneepad-0.3.0/src/kneepad/data/footguns.toml +2313 -0
  16. kneepad-0.3.0/src/kneepad/data/footguns_ext.toml +755 -0
  17. kneepad-0.3.0/src/kneepad/data/footguns_macos.toml +305 -0
  18. kneepad-0.3.0/src/kneepad/data/footguns_windows.toml +594 -0
  19. kneepad-0.3.0/src/kneepad/engine.py +1063 -0
  20. kneepad-0.3.0/src/kneepad/hook.py +160 -0
  21. kneepad-0.3.0/src/kneepad/installer.py +139 -0
  22. kneepad-0.3.0/src/kneepad/integrations.py +254 -0
  23. kneepad-0.3.0/src/kneepad/rules.py +210 -0
  24. kneepad-0.3.0/src/kneepad/shellparse.py +489 -0
  25. kneepad-0.3.0/src/kneepad/snapshots.py +360 -0
  26. kneepad-0.3.0/src/kneepad/sqlscan.py +247 -0
  27. kneepad-0.3.0/src/kneepad/util.py +78 -0
  28. kneepad-0.3.0/src/kneepad/winshell.py +634 -0
  29. kneepad-0.3.0/src/kneepad.egg-info/PKG-INFO +104 -0
  30. kneepad-0.3.0/src/kneepad.egg-info/SOURCES.txt +41 -0
  31. kneepad-0.3.0/src/kneepad.egg-info/dependency_links.txt +1 -0
  32. kneepad-0.3.0/src/kneepad.egg-info/entry_points.txt +3 -0
  33. kneepad-0.3.0/src/kneepad.egg-info/top_level.txt +1 -0
  34. kneepad-0.3.0/tests/test_audit_snapshots_hook.py +568 -0
  35. kneepad-0.3.0/tests/test_corpus.py +68 -0
  36. kneepad-0.3.0/tests/test_engine.py +556 -0
  37. kneepad-0.3.0/tests/test_hardening.py +68 -0
  38. kneepad-0.3.0/tests/test_integrations.py +248 -0
  39. kneepad-0.3.0/tests/test_platforms.py +478 -0
  40. kneepad-0.3.0/tests/test_robustness.py +66 -0
  41. kneepad-0.3.0/tests/test_rules_db.py +199 -0
  42. kneepad-0.3.0/tests/test_shellparse.py +121 -0
  43. kneepad-0.3.0/tests/test_sqlscan.py +121 -0
kneepad-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kneepad contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
kneepad-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: kneepad
3
+ Version: 0.3.0
4
+ Summary: Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log.
5
+ License: MIT
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Operating System :: POSIX :: Linux
8
+ Classifier: Operating System :: MacOS
9
+ Classifier: Operating System :: Microsoft :: Windows
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Topic :: Security
12
+ Classifier: Topic :: Software Development :: Quality Assurance
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # Kneepad
19
+
20
+ A local safety layer for AI coding agents. It sits in front of the commands your agent runs, stops the ones that cannot be undone, takes a safety copy of the ones that can, and keeps a tamper-evident record of what happened.
21
+
22
+ Zero dependencies. Python 3.11+. Linux, macOS and Windows. Runs entirely on your machine. MIT licensed.
23
+
24
+ ## What it does
25
+
26
+ - **Footgun database.** 249 rules (216 pattern rules plus 33 emitted by engine code) for the commands that ruin days: `rm -rf` on the wrong path, `git push --force` to main, `terraform destroy`, `DROP TABLE`, `kubectl delete ns`, `aws s3 rb --force`, `prisma migrate reset`, `curl | sh`, writes to `~/.ssh` and `.bashrc`, and more. Rules are pattern families (one rule covers every `delete`/`destroy`/`terminate` subcommand of a cloud CLI, for example), across about 560 named tools, including Windows and macOS tools. Count of rules is not coverage: more rules also means more false positives, so every rule must pass the benign corpus. Every rule ships with examples that the test suite executes.
27
+ - **Understands shell, not just text.** Quotes, `$(...)`, backticks, heredocs, pipes, `bash -c`, `eval`, `ssh host '...'`, `docker exec`, `kubectl exec --`, `sudo`/`env`/`nice` wrappers, `npx`/`poetry run`/`bundle exec`, and shell scripts the agent is about to run. `echo "rm -rf /"` is not flagged. `DIR=; rm -rf $DIR/` is.
28
+ - **Snapshots before risky-but-allowed actions.** Deleting untracked files, `git reset --hard`, `git clean`, `git branch -D` each take a copy first. Restore with `kneepad snapshots restore <id>`.
29
+ - **Hash-chained audit log.** Every decision is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
30
+ - **"Protected by Kneepad" badge.** `kneepad badge` writes an SVG, and refuses to if the hook is not installed or the log does not verify.
31
+
32
+ Decision model: Kneepad never says "allow". Safe commands pass through silently and keep your normal permission flow. Risky ones get `ask`. Catastrophic ones get `deny`. If Kneepad itself errors, it answers `ask`.
33
+
34
+ ## Works with
35
+
36
+ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, any tool with a command hook (generic JSON), any agent that runs `$SHELL -c` (`kneepad-shell`), and your own Python agents (`kneepad.api`). The decision is made on the action, so it does not matter which LLM is driving. Each integration is tested against the vendor's documented hook contract; none has yet been verified inside the real vendor app. See [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md) for the exact status and known vendor-side limits.
37
+
38
+ ## Platforms
39
+
40
+ | | Linux | macOS | Windows |
41
+ |---|---|---|---|
42
+ | Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
43
+ | Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
44
+ | Continuous integration | full suite | full suite | rule examples and platform tests (experimental, not yet seen green) |
45
+
46
+ Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The CI workflow runs on macOS and Windows runners, but until you have seen it pass there, treat both as unproven on real machines. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
47
+
48
+ ## Install
49
+
50
+ ```
51
+ pip install kneepad # Windows: py -m pip install kneepad
52
+ kneepad init --claude-code # Claude Code
53
+ kneepad init --target cursor --target gemini --target codex # others (or --target all)
54
+ kneepad doctor
55
+ ```
56
+
57
+ From a checkout instead:
58
+
59
+ ```
60
+ pip install .
61
+ kneepad init --claude-code --scope project # hook for this repo only
62
+ ```
63
+
64
+ `init` backs up your settings file, preserves everything in it, and is safe to run twice. `kneepad uninstall` removes only its own entry.
65
+
66
+ ## Try it without installing the hook
67
+
68
+ ```
69
+ kneepad check 'rm -rf /' # exit 20 (deny)
70
+ kneepad check 'terraform destroy' # exit 10 (ask)
71
+ kneepad check 'ls -la' # exit 0
72
+ kneepad run -- git push --force origin main
73
+ ```
74
+
75
+ ## Everyday commands
76
+
77
+ | command | purpose |
78
+ |---|---|
79
+ | `kneepad log` | recent decisions |
80
+ | `kneepad verify` | check the hash chain and signatures |
81
+ | `kneepad anchor` | print `SEQ:HASH` to store somewhere else (detects tail truncation) |
82
+ | `kneepad snapshots list/show/restore/prune` | safety copies |
83
+ | `kneepad rules list/show/validate` | browse and validate the footgun database |
84
+ | `kneepad badge` | write the badge SVG |
85
+
86
+ ## Configuration
87
+
88
+ User config at `~/.kneepad/config.toml` is trusted and can relax rules (`disable_rules`, `allow_patterns`, `allow_write_paths`, `mode = "monitor"`). A project `.kneepad.toml` is untrusted, because a cloned repo could carry one, so it can only tighten: extra `protected_paths`, `prod_markers`, `protected_branches`, `escalate`, a lower snapshot size cap. Rules marked `no_override` (for example `rm -rf /`) cannot be disabled by any config.
89
+
90
+ A production marker (`prod`, `production`, `prd` as a whole word) in a destructive infrastructure or database command escalates `ask` to `deny`.
91
+
92
+ ## What it is not
93
+
94
+ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short: this catches accidents and common agent mistakes. It is not a sandbox, and it does not stop a determined adversary who can obfuscate commands.
95
+
96
+ ## Development
97
+
98
+ ```
99
+ python3 -m unittest discover -s tests
100
+ ```
101
+
102
+ 258 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
103
+
104
+ Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
@@ -0,0 +1,87 @@
1
+ # Kneepad
2
+
3
+ A local safety layer for AI coding agents. It sits in front of the commands your agent runs, stops the ones that cannot be undone, takes a safety copy of the ones that can, and keeps a tamper-evident record of what happened.
4
+
5
+ Zero dependencies. Python 3.11+. Linux, macOS and Windows. Runs entirely on your machine. MIT licensed.
6
+
7
+ ## What it does
8
+
9
+ - **Footgun database.** 249 rules (216 pattern rules plus 33 emitted by engine code) for the commands that ruin days: `rm -rf` on the wrong path, `git push --force` to main, `terraform destroy`, `DROP TABLE`, `kubectl delete ns`, `aws s3 rb --force`, `prisma migrate reset`, `curl | sh`, writes to `~/.ssh` and `.bashrc`, and more. Rules are pattern families (one rule covers every `delete`/`destroy`/`terminate` subcommand of a cloud CLI, for example), across about 560 named tools, including Windows and macOS tools. Count of rules is not coverage: more rules also means more false positives, so every rule must pass the benign corpus. Every rule ships with examples that the test suite executes.
10
+ - **Understands shell, not just text.** Quotes, `$(...)`, backticks, heredocs, pipes, `bash -c`, `eval`, `ssh host '...'`, `docker exec`, `kubectl exec --`, `sudo`/`env`/`nice` wrappers, `npx`/`poetry run`/`bundle exec`, and shell scripts the agent is about to run. `echo "rm -rf /"` is not flagged. `DIR=; rm -rf $DIR/` is.
11
+ - **Snapshots before risky-but-allowed actions.** Deleting untracked files, `git reset --hard`, `git clean`, `git branch -D` each take a copy first. Restore with `kneepad snapshots restore <id>`.
12
+ - **Hash-chained audit log.** Every decision is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
13
+ - **"Protected by Kneepad" badge.** `kneepad badge` writes an SVG, and refuses to if the hook is not installed or the log does not verify.
14
+
15
+ Decision model: Kneepad never says "allow". Safe commands pass through silently and keep your normal permission flow. Risky ones get `ask`. Catastrophic ones get `deny`. If Kneepad itself errors, it answers `ask`.
16
+
17
+ ## Works with
18
+
19
+ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, any tool with a command hook (generic JSON), any agent that runs `$SHELL -c` (`kneepad-shell`), and your own Python agents (`kneepad.api`). The decision is made on the action, so it does not matter which LLM is driving. Each integration is tested against the vendor's documented hook contract; none has yet been verified inside the real vendor app. See [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md) for the exact status and known vendor-side limits.
20
+
21
+ ## Platforms
22
+
23
+ | | Linux | macOS | Windows |
24
+ |---|---|---|---|
25
+ | Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
26
+ | Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
27
+ | Continuous integration | full suite | full suite | rule examples and platform tests (experimental, not yet seen green) |
28
+
29
+ Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The CI workflow runs on macOS and Windows runners, but until you have seen it pass there, treat both as unproven on real machines. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
30
+
31
+ ## Install
32
+
33
+ ```
34
+ pip install kneepad # Windows: py -m pip install kneepad
35
+ kneepad init --claude-code # Claude Code
36
+ kneepad init --target cursor --target gemini --target codex # others (or --target all)
37
+ kneepad doctor
38
+ ```
39
+
40
+ From a checkout instead:
41
+
42
+ ```
43
+ pip install .
44
+ kneepad init --claude-code --scope project # hook for this repo only
45
+ ```
46
+
47
+ `init` backs up your settings file, preserves everything in it, and is safe to run twice. `kneepad uninstall` removes only its own entry.
48
+
49
+ ## Try it without installing the hook
50
+
51
+ ```
52
+ kneepad check 'rm -rf /' # exit 20 (deny)
53
+ kneepad check 'terraform destroy' # exit 10 (ask)
54
+ kneepad check 'ls -la' # exit 0
55
+ kneepad run -- git push --force origin main
56
+ ```
57
+
58
+ ## Everyday commands
59
+
60
+ | command | purpose |
61
+ |---|---|
62
+ | `kneepad log` | recent decisions |
63
+ | `kneepad verify` | check the hash chain and signatures |
64
+ | `kneepad anchor` | print `SEQ:HASH` to store somewhere else (detects tail truncation) |
65
+ | `kneepad snapshots list/show/restore/prune` | safety copies |
66
+ | `kneepad rules list/show/validate` | browse and validate the footgun database |
67
+ | `kneepad badge` | write the badge SVG |
68
+
69
+ ## Configuration
70
+
71
+ User config at `~/.kneepad/config.toml` is trusted and can relax rules (`disable_rules`, `allow_patterns`, `allow_write_paths`, `mode = "monitor"`). A project `.kneepad.toml` is untrusted, because a cloned repo could carry one, so it can only tighten: extra `protected_paths`, `prod_markers`, `protected_branches`, `escalate`, a lower snapshot size cap. Rules marked `no_override` (for example `rm -rf /`) cannot be disabled by any config.
72
+
73
+ A production marker (`prod`, `production`, `prd` as a whole word) in a destructive infrastructure or database command escalates `ask` to `deny`.
74
+
75
+ ## What it is not
76
+
77
+ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short: this catches accidents and common agent mistakes. It is not a sandbox, and it does not stop a determined adversary who can obfuscate commands.
78
+
79
+ ## Development
80
+
81
+ ```
82
+ python3 -m unittest discover -s tests
83
+ ```
84
+
85
+ 258 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
86
+
87
+ Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kneepad"
7
+ version = "0.3.0"
8
+ description = "Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ dependencies = []
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Operating System :: POSIX :: Linux",
16
+ "Operating System :: MacOS",
17
+ "Operating System :: Microsoft :: Windows",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Topic :: Security",
20
+ "Topic :: Software Development :: Quality Assurance",
21
+ ]
22
+
23
+ [project.scripts]
24
+ kneepad = "kneepad.cli:main"
25
+ kneepad-shell = "kneepad.cli:shell_main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+
30
+ [tool.setuptools.package-data]
31
+ kneepad = ["data/*.toml"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Kneepad: a kneepad for AI coding agents."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,277 @@
1
+ """Adapters: translate each agent's hook protocol to and from Kneepad's decisions.
2
+
3
+ Every contract below was taken from the vendor's public documentation (see docs/INTEGRATIONS.md
4
+ for links and the date checked). They are tested against the documented payloads. They have NOT
5
+ been exercised inside every vendor application, which is why docs/INTEGRATIONS.md labels each
6
+ integration's verification level.
7
+
8
+ Common rules:
9
+ * A protocol that has no "ask" answer maps ask to deny, because failing open would be worse.
10
+ * A protocol that requires an explicit "allow" answer gets one only when Kneepad has no objection.
11
+ * A Claude-style protocol (Claude Code, Codex) stays silent on allow so the user's own permission
12
+ prompts keep working.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Callable, Dict, Optional, Tuple
20
+
21
+ WRITE_TOOLS = {
22
+ "write", "edit", "multiedit", "notebookedit", "write_file", "replace", "create", "str_replace_editor",
23
+ "str_replace_based_edit_tool", "write_to_file", "replace_in_file", "insert_content", "apply_diff", "edit_file",
24
+ "create_file",
25
+ }
26
+ SHELL_TOOLS = {"bash", "run_shell_command", "execute_command", "shell", "powershell", "launch-process", "run_terminal_cmd"}
27
+
28
+
29
+ @dataclass
30
+ class Parsed:
31
+ kind: Optional[str] # "bash" | "write" | "mcp" | None (not our business)
32
+ tool: str = ""
33
+ tin: Dict[str, Any] = field(default_factory=dict)
34
+ cwd: str = ""
35
+ session: str = ""
36
+ use_id: str = ""
37
+
38
+
39
+ def _dict(v: Any) -> Dict[str, Any]:
40
+ if isinstance(v, dict):
41
+ return v
42
+ if isinstance(v, str):
43
+ try:
44
+ d = json.loads(v)
45
+ return d if isinstance(d, dict) else {}
46
+ except ValueError:
47
+ return {}
48
+ return {}
49
+
50
+
51
+ def _classify(tool: str, tin: Dict[str, Any]) -> Optional[str]:
52
+ t = tool.lower()
53
+ if t in SHELL_TOOLS or (t.startswith("bash") and "command" in tin):
54
+ return "bash"
55
+ if t in WRITE_TOOLS:
56
+ return "write"
57
+ if t.startswith("mcp") or "__" in t:
58
+ return "mcp"
59
+ return None
60
+
61
+
62
+ def _path_of(tin: Dict[str, Any]) -> str:
63
+ for k in ("file_path", "path", "filePath", "notebook_path", "target_file", "filename"):
64
+ if isinstance(tin.get(k), str) and tin[k]:
65
+ return tin[k]
66
+ return ""
67
+
68
+
69
+ class Adapter:
70
+ name = "base"
71
+ supports_ask = True
72
+ requires_explicit_allow = False
73
+
74
+ def parse(self, payload: Dict[str, Any]) -> Parsed: # pragma: no cover - interface
75
+ raise NotImplementedError
76
+
77
+ def render(self, action: str, reason: str) -> Tuple[int, str]: # pragma: no cover - interface
78
+ raise NotImplementedError
79
+
80
+ def event_ok(self, payload: Dict[str, Any]) -> bool:
81
+ return True
82
+
83
+ def effective(self, action: str) -> str:
84
+ if action == "ask" and not self.supports_ask:
85
+ return "deny"
86
+ return action
87
+
88
+
89
+ class ClaudeAdapter(Adapter):
90
+ """Claude Code. Also the shape OpenAI Codex documents for PreToolUse."""
91
+
92
+ name = "claude"
93
+
94
+ def event_ok(self, payload):
95
+ return payload.get("hook_event_name", "PreToolUse") == "PreToolUse"
96
+
97
+ def parse(self, payload):
98
+ tool = str(payload.get("tool_name", ""))
99
+ tin = _dict(payload.get("tool_input"))
100
+ kind = _classify(tool, tin)
101
+ if tool == "apply_patch":
102
+ kind = None
103
+ return Parsed(kind, tool, tin, str(payload.get("cwd") or ""), str(payload.get("session_id", "")), str(payload.get("tool_use_id", "")))
104
+
105
+ def render(self, action, reason):
106
+ if action == "allow":
107
+ return 0, ""
108
+ return 0, json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
109
+ "permissionDecision": self.effective(action),
110
+ "permissionDecisionReason": reason}})
111
+
112
+
113
+ class CodexAdapter(ClaudeAdapter):
114
+ """Codex documents PreToolUse with Claude-shaped input and output, but 'ask' is not supported yet."""
115
+
116
+ name = "codex"
117
+ supports_ask = False
118
+
119
+
120
+ class CopilotAdapter(Adapter):
121
+ """GitHub Copilot CLI. Accepts the camelCase payload and the PascalCase/VS Code-compatible payload."""
122
+
123
+ name = "copilot"
124
+
125
+ def event_ok(self, payload):
126
+ ev = payload.get("hook_event_name")
127
+ return ev in (None, "PreToolUse", "preToolUse")
128
+
129
+ def parse(self, payload):
130
+ if "toolName" in payload or "toolArgs" in payload:
131
+ tool = str(payload.get("toolName", ""))
132
+ tin = _dict(payload.get("toolArgs"))
133
+ sess = str(payload.get("sessionId", ""))
134
+ else:
135
+ tool = str(payload.get("tool_name", ""))
136
+ tin = _dict(payload.get("tool_input"))
137
+ sess = str(payload.get("session_id", ""))
138
+ return Parsed(_classify(tool, tin), tool, tin, str(payload.get("cwd") or ""), sess)
139
+
140
+ def render(self, action, reason):
141
+ if action == "allow":
142
+ return 0, ""
143
+ return 0, json.dumps({"permissionDecision": self.effective(action), "permissionDecisionReason": reason})
144
+
145
+
146
+ class CursorAdapter(Adapter):
147
+ """Cursor hooks: beforeShellExecution, beforeMCPExecution, preToolUse.
148
+
149
+ Cursor requires an explicit permission field in every response. Cursor's docs accept
150
+ permission "ask" for beforeShellExecution and beforeMCPExecution, but a user report on Cursor's
151
+ forum (sandbox mode, 2026-03) shows the command running anyway after "ask". An unenforced "ask"
152
+ would fail open, so Kneepad maps ask to deny for Cursor. Revisit when Cursor documents the fix.
153
+ """
154
+
155
+ name = "cursor"
156
+ supports_ask = False
157
+ requires_explicit_allow = True
158
+
159
+ def parse(self, payload):
160
+ ev = str(payload.get("hook_event_name", ""))
161
+ cwd = str(payload.get("cwd") or "")
162
+ if not cwd:
163
+ roots = payload.get("workspace_roots")
164
+ if isinstance(roots, list) and roots and isinstance(roots[0], str):
165
+ cwd = roots[0]
166
+ sess = str(payload.get("conversation_id") or payload.get("session_id") or "")
167
+ if ev == "beforeShellExecution" or ("command" in payload and "tool_name" not in payload):
168
+ return Parsed("bash", "Bash", {"command": payload.get("command", "")}, cwd, sess)
169
+ tool = str(payload.get("tool_name", ""))
170
+ tin = _dict(payload.get("tool_input"))
171
+ if ev == "beforeMCPExecution":
172
+ return Parsed("mcp", tool if tool.startswith("mcp") else f"mcp__{tool}", tin, cwd, sess)
173
+ if ev == "beforeReadFile":
174
+ return Parsed(None, tool, tin, cwd, sess)
175
+ return Parsed(_classify(tool, tin), tool, tin, cwd, sess)
176
+
177
+ def render(self, action, reason):
178
+ eff = self.effective(action)
179
+ if eff == "allow":
180
+ return 0, json.dumps({"permission": "allow"})
181
+ return 2, json.dumps({"permission": "deny", "user_message": reason, "agent_message": reason})
182
+
183
+
184
+ class GeminiAdapter(Adapter):
185
+ """Gemini CLI BeforeTool. stdout must be only the JSON object; there is no 'ask'."""
186
+
187
+ name = "gemini"
188
+ supports_ask = False
189
+ requires_explicit_allow = True
190
+
191
+ def event_ok(self, payload):
192
+ return payload.get("hook_event_name", "BeforeTool") == "BeforeTool"
193
+
194
+ def parse(self, payload):
195
+ tool = str(payload.get("tool_name", ""))
196
+ tin = _dict(payload.get("tool_input"))
197
+ kind = _classify(tool, tin)
198
+ if kind is None and tool.startswith("mcp"):
199
+ kind = "mcp"
200
+ return Parsed(kind, tool, tin, str(payload.get("cwd") or ""), str(payload.get("session_id", "")))
201
+
202
+ def render(self, action, reason):
203
+ if self.effective(action) == "allow":
204
+ return 0, json.dumps({"decision": "allow"})
205
+ return 0, json.dumps({"decision": "deny", "reason": reason})
206
+
207
+
208
+ class ClineAdapter(Adapter):
209
+ """Cline PreToolUse hook: input under 'preToolUse', output {cancel, errorMessage}."""
210
+
211
+ name = "cline"
212
+ supports_ask = False
213
+ requires_explicit_allow = True
214
+
215
+ def event_ok(self, payload):
216
+ return str(payload.get("hookName", "PreToolUse")).lower() == "pretooluse"
217
+
218
+ def parse(self, payload):
219
+ body = payload.get("preToolUse")
220
+ body = body if isinstance(body, dict) else {}
221
+ tool = str(body.get("toolName", ""))
222
+ params = _dict(body.get("parameters"))
223
+ roots = payload.get("workspaceRoots")
224
+ cwd = roots[0] if isinstance(roots, list) and roots and isinstance(roots[0], str) else ""
225
+ kind = _classify(tool, params)
226
+ if tool == "use_mcp_tool":
227
+ kind = "mcp"
228
+ tool = f"mcp__{params.get('server_name', 'server')}__{params.get('tool_name', 'tool')}"
229
+ params = _dict(params.get("arguments")) or params
230
+ return Parsed(kind, tool, params, cwd, str(payload.get("taskId", "")))
231
+
232
+ def render(self, action, reason):
233
+ if self.effective(action) == "allow":
234
+ return 0, json.dumps({"cancel": False})
235
+ return 0, json.dumps({"cancel": True, "errorMessage": reason})
236
+
237
+
238
+ class GenericAdapter(Adapter):
239
+ """For any tool that can run a command and honour exit code 2.
240
+
241
+ stdin: {"command": "...", "cwd": "..."} (or {"tool": "write", "path": "..."}). Exit 2 blocks;
242
+ the reason goes to stderr (returned here as stdout text, printed to stderr by the CLI).
243
+ """
244
+
245
+ name = "generic"
246
+ supports_ask = False
247
+
248
+ def parse(self, payload):
249
+ if isinstance(payload.get("command"), str):
250
+ return Parsed("bash", "Bash", {"command": payload["command"]}, str(payload.get("cwd") or ""), str(payload.get("session", "")))
251
+ path = _path_of(payload)
252
+ if path:
253
+ return Parsed("write", "Write", {"file_path": path}, str(payload.get("cwd") or ""))
254
+ return Parsed(None)
255
+
256
+ def render(self, action, reason):
257
+ if self.effective(action) == "allow":
258
+ return 0, ""
259
+ return 2, reason
260
+
261
+
262
+ ADAPTERS: Dict[str, Callable[[], Adapter]] = {
263
+ "claude": ClaudeAdapter,
264
+ "codex": CodexAdapter,
265
+ "copilot": CopilotAdapter,
266
+ "cursor": CursorAdapter,
267
+ "gemini": GeminiAdapter,
268
+ "cline": ClineAdapter,
269
+ "generic": GenericAdapter,
270
+ }
271
+
272
+
273
+ def get_adapter(name: str) -> Adapter:
274
+ try:
275
+ return ADAPTERS[name]()
276
+ except KeyError:
277
+ raise ValueError(f"unknown integration {name!r}; choose from {', '.join(sorted(ADAPTERS))}") from None
@@ -0,0 +1,62 @@
1
+ """Use Kneepad from your own agent code (LangChain, OpenAI Agents SDK, CrewAI, custom loops).
2
+
3
+ from kneepad.api import check_command, guard, KneepadBlocked
4
+
5
+ d = check_command("terraform destroy")
6
+ if d.action != "allow":
7
+ print(d.reason())
8
+
9
+ @guard # raises KneepadBlocked on deny or ask unless allow_ask=True
10
+ def run_shell(command: str): ...
11
+
12
+ Nothing here depends on which LLM drives your agent; Kneepad looks at the action, not the model.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import functools
18
+ import os
19
+ from typing import Any, Callable, Optional
20
+
21
+ from .config import load_config
22
+ from .engine import Analyzer, Decision
23
+
24
+
25
+ class KneepadBlocked(Exception):
26
+ def __init__(self, decision: Decision):
27
+ super().__init__(decision.reason())
28
+ self.decision = decision
29
+
30
+
31
+ def check_command(command: str, cwd: Optional[str] = None) -> Decision:
32
+ cwd = cwd or os.getcwd()
33
+ return Analyzer(config=load_config(cwd), cwd=cwd).analyze_shell(command)
34
+
35
+
36
+ def check_write(path: str, cwd: Optional[str] = None) -> Decision:
37
+ cwd = cwd or os.getcwd()
38
+ return Analyzer(config=load_config(cwd), cwd=cwd).analyze_write_path(path)
39
+
40
+
41
+ def check_mcp(tool_name: str, tool_input: Any, cwd: Optional[str] = None) -> Decision:
42
+ cwd = cwd or os.getcwd()
43
+ return Analyzer(config=load_config(cwd), cwd=cwd).analyze_mcp(tool_name, tool_input)
44
+
45
+
46
+ def guard(func: Optional[Callable] = None, *, arg: str = "command", allow_ask: bool = False):
47
+ """Decorator for a function that executes a shell command passed as its first argument or as ``arg``."""
48
+
49
+ def wrap(f: Callable) -> Callable:
50
+ @functools.wraps(f)
51
+ def inner(*args, **kwargs):
52
+ cmd = kwargs.get(arg) if arg in kwargs else (args[0] if args else None)
53
+ if not isinstance(cmd, str):
54
+ raise TypeError(f"guard expected a string command as the first argument or {arg}=")
55
+ d = check_command(cmd)
56
+ if d.action == "deny" or (d.action == "ask" and not allow_ask):
57
+ raise KneepadBlocked(d)
58
+ return f(*args, **kwargs)
59
+
60
+ return inner
61
+
62
+ return wrap(func) if func is not None else wrap