kneepad 0.3.0__py3-none-any.whl
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.
- kneepad/__init__.py +3 -0
- kneepad/__main__.py +6 -0
- kneepad/adapters.py +277 -0
- kneepad/api.py +62 -0
- kneepad/argvtools.py +300 -0
- kneepad/audit.py +303 -0
- kneepad/badge.py +30 -0
- kneepad/cli.py +498 -0
- kneepad/config.py +185 -0
- kneepad/data/footguns.toml +2313 -0
- kneepad/data/footguns_ext.toml +755 -0
- kneepad/data/footguns_macos.toml +305 -0
- kneepad/data/footguns_windows.toml +594 -0
- kneepad/engine.py +1063 -0
- kneepad/hook.py +160 -0
- kneepad/installer.py +139 -0
- kneepad/integrations.py +254 -0
- kneepad/rules.py +210 -0
- kneepad/shellparse.py +489 -0
- kneepad/snapshots.py +360 -0
- kneepad/sqlscan.py +247 -0
- kneepad/util.py +78 -0
- kneepad/winshell.py +634 -0
- kneepad-0.3.0.dist-info/METADATA +104 -0
- kneepad-0.3.0.dist-info/RECORD +29 -0
- kneepad-0.3.0.dist-info/WHEEL +5 -0
- kneepad-0.3.0.dist-info/entry_points.txt +3 -0
- kneepad-0.3.0.dist-info/licenses/LICENSE +21 -0
- kneepad-0.3.0.dist-info/top_level.txt +1 -0
kneepad/__init__.py
ADDED
kneepad/__main__.py
ADDED
kneepad/adapters.py
ADDED
|
@@ -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
|
kneepad/api.py
ADDED
|
@@ -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
|
kneepad/argvtools.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""Turn parsed shell words into a normalised, matchable argument view."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Dict, List, Set, Tuple
|
|
9
|
+
|
|
10
|
+
from .shellparse import RESERVED, Word, is_assignment
|
|
11
|
+
|
|
12
|
+
SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ksh", "ash", "fish", "csh", "tcsh"})
|
|
13
|
+
INTERPRETERS = frozenset({"python", "node", "ruby", "perl", "php", "deno", "bun"})
|
|
14
|
+
|
|
15
|
+
_SUDO_VAL = {
|
|
16
|
+
"-u", "-g", "-h", "-p", "-C", "-D", "-R", "-r", "-t", "-T", "-U",
|
|
17
|
+
"--user", "--group", "--host", "--prompt", "--close-from", "--chdir", "--chroot",
|
|
18
|
+
"--role", "--type", "--command-timeout", "--other-user",
|
|
19
|
+
}
|
|
20
|
+
_XARGS_VAL = {
|
|
21
|
+
"-n", "--max-args", "-L", "--max-lines", "-P", "--max-procs", "-I", "-s", "--max-chars",
|
|
22
|
+
"-d", "--delimiter", "-E", "-a", "--arg-file", "--process-slot-var",
|
|
23
|
+
}
|
|
24
|
+
# name -> (options that take a value, number of leading positionals to skip)
|
|
25
|
+
_WRAPPERS: Dict[str, Tuple[Set[str], int]] = {
|
|
26
|
+
"sudo": (_SUDO_VAL, 0),
|
|
27
|
+
"doas": ({"-u", "-C"}, 0),
|
|
28
|
+
"nice": ({"-n", "--adjustment"}, 0),
|
|
29
|
+
"ionice": ({"-c", "-n", "-p", "-P", "-u", "--class", "--classdata"}, 0),
|
|
30
|
+
"nohup": (set(), 0),
|
|
31
|
+
"time": ({"-f", "--format", "-o", "--output"}, 0),
|
|
32
|
+
"stdbuf": ({"-i", "-o", "-e", "--input", "--output", "--error"}, 0),
|
|
33
|
+
"setsid": (set(), 0),
|
|
34
|
+
"timeout": ({"-s", "--signal", "-k", "--kill-after"}, 1),
|
|
35
|
+
"command": (set(), 0),
|
|
36
|
+
"builtin": (set(), 0),
|
|
37
|
+
"exec": ({"-a"}, 0),
|
|
38
|
+
"xargs": (_XARGS_VAL, 0),
|
|
39
|
+
"unbuffer": (set(), 0),
|
|
40
|
+
"npx": ({"-p", "--package", "-c", "--call"}, 0),
|
|
41
|
+
"pnpx": (set(), 0),
|
|
42
|
+
"bunx": (set(), 0),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
# Options that consume the next token, per command. Keeps values out of positionals.
|
|
46
|
+
VALUE_FLAGS: Dict[str, Set[str]] = {
|
|
47
|
+
"git": {"-C", "-c", "-b", "-B", "-m", "-F", "--git-dir", "--work-tree", "--namespace",
|
|
48
|
+
"--message", "--file", "--author", "--date", "-o", "--push-option", "--repo"},
|
|
49
|
+
"kubectl": {"-n", "--namespace", "--context", "--kubeconfig", "-s", "--server", "--cluster",
|
|
50
|
+
"--user", "--as", "--as-group", "--token", "-l", "--selector", "-f", "--filename",
|
|
51
|
+
"-k", "--kustomize", "-o", "--output", "--field-selector", "--timeout",
|
|
52
|
+
"--grace-period", "--request-timeout", "-c", "--container", "--cascade"},
|
|
53
|
+
"helm": {"-n", "--namespace", "--kube-context", "--kubeconfig", "-f", "--values", "--set",
|
|
54
|
+
"--version", "--timeout"},
|
|
55
|
+
"terraform": {"-var", "-var-file", "-target", "-state", "-backend-config", "-lock-timeout",
|
|
56
|
+
"-parallelism", "-replace", "-out"},
|
|
57
|
+
"tofu": {"-var", "-var-file", "-target", "-state", "-backend-config", "-lock-timeout",
|
|
58
|
+
"-parallelism", "-replace", "-out"},
|
|
59
|
+
"aws": {"--profile", "--region", "--endpoint-url", "--output", "--query", "--cli-input-json",
|
|
60
|
+
"--ca-bundle", "--cli-read-timeout", "--cli-connect-timeout", "--color"},
|
|
61
|
+
"gcloud": {"--project", "--account", "--format", "--configuration", "--impersonate-service-account"},
|
|
62
|
+
"az": {"--subscription", "--output", "-o", "--query", "--resource-group", "-g", "--name", "-n"},
|
|
63
|
+
# docker, podman and docker-compose reuse the same letters with different meanings per
|
|
64
|
+
# subcommand (-f is a compose file option but also "force"), so they are scoped below.
|
|
65
|
+
"docker": {"-H", "--host", "--context", "-c", "--config", "-l", "--log-level"},
|
|
66
|
+
"podman": {"-H", "--host", "--context", "-c", "--config", "-l", "--log-level"},
|
|
67
|
+
"docker-compose": {"-f", "--file", "-p", "--project-name", "--profile", "--env-file",
|
|
68
|
+
"--project-directory", "-H", "--host", "--context"},
|
|
69
|
+
"curl": {"-X", "--request", "-H", "--header", "-d", "--data", "--data-raw", "--data-binary",
|
|
70
|
+
"--data-urlencode", "-F", "--form", "-o", "--output", "-u", "--user", "-A",
|
|
71
|
+
"--user-agent", "-e", "--referer", "-T", "--upload-file", "-w", "--write-out",
|
|
72
|
+
"--connect-timeout", "-m", "--max-time", "-x", "--proxy", "--cacert", "--cert",
|
|
73
|
+
"--key", "-b", "--cookie", "-c", "--cookie-jar", "-K", "--config", "--url"},
|
|
74
|
+
"wget": {"-O", "-o", "-P", "-e", "--post-data", "--post-file", "--body-data", "--body-file",
|
|
75
|
+
"--header", "--user", "--password", "-t", "-T", "-w", "-i", "-a"},
|
|
76
|
+
"rsync": {"-e", "--rsh", "--exclude", "--include", "--exclude-from", "--include-from", "-f",
|
|
77
|
+
"--filter", "--port", "--bwlimit", "--timeout", "--max-size", "--min-size"},
|
|
78
|
+
"rclone": {"--config", "--transfers", "--checkers", "--exclude", "--include", "--filter",
|
|
79
|
+
"--bwlimit", "--log-file", "--backup-dir"},
|
|
80
|
+
"redis-cli": {"-h", "-p", "-a", "-n", "-u", "-s", "--user", "--pass"},
|
|
81
|
+
"valkey-cli": {"-h", "-p", "-a", "-n", "-u", "-s", "--user", "--pass"},
|
|
82
|
+
"gh": {"-R", "--repo"},
|
|
83
|
+
"heroku": {"-a", "--app", "-r", "--remote", "--confirm"},
|
|
84
|
+
"fly": {"-a", "--app", "-c", "--config", "-o", "--org"},
|
|
85
|
+
"flyctl": {"-a", "--app", "-c", "--config", "-o", "--org"},
|
|
86
|
+
"ssh": {"-i", "-l", "-p", "-o", "-F", "-J", "-L", "-R", "-D", "-b", "-c", "-e", "-m", "-O",
|
|
87
|
+
"-Q", "-S", "-W", "-w", "-E", "-B"},
|
|
88
|
+
"vercel": {"--token", "-t", "--scope", "-S", "-A"},
|
|
89
|
+
"supabase": {"--workdir", "--project-ref"},
|
|
90
|
+
"prisma": {"--schema", "--name", "--url"},
|
|
91
|
+
"kill": {"-s", "-n"},
|
|
92
|
+
"cp": {"-t", "--target-directory", "-S", "--suffix"},
|
|
93
|
+
"mv": {"-t", "--target-directory", "-S", "--suffix"},
|
|
94
|
+
"install": {"-t", "--target-directory", "-m", "--mode", "-o", "--owner", "-g", "--group"},
|
|
95
|
+
"ln": {"-t", "--target-directory", "-S", "--suffix"},
|
|
96
|
+
"psql": {"-c", "--command", "-f", "--file", "-d", "--dbname", "-h", "--host", "-p", "--port", "-U", "--username",
|
|
97
|
+
"-v", "--set", "--variable", "-o", "--output", "-L", "--log-file", "-F", "-R", "-P", "-T", "-l"},
|
|
98
|
+
"mysql": {"-e", "--execute", "-h", "--host", "-u", "--user", "-P", "--port", "-D", "--database", "-S", "--socket"},
|
|
99
|
+
"mariadb": {"-e", "--execute", "-h", "--host", "-u", "--user", "-P", "--port", "-D", "--database", "-S", "--socket"},
|
|
100
|
+
"mongosh": {"--eval", "--host", "--port", "-u", "--username", "-p", "--password", "--authenticationDatabase"},
|
|
101
|
+
"find": set(),
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
# Commands whose value-taking options differ before/after the subcommand.
|
|
105
|
+
_SCOPED = frozenset({"docker", "podman", "docker-compose"})
|
|
106
|
+
_COMPOSE_VALS = {"-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory"}
|
|
107
|
+
_SUB_VALUE_FLAGS: Dict[Tuple[str, str], Set[str]] = {
|
|
108
|
+
("docker", "compose"): _COMPOSE_VALS,
|
|
109
|
+
("podman", "compose"): _COMPOSE_VALS,
|
|
110
|
+
("docker", "exec"): {"-e", "--env", "-u", "--user", "-w", "--workdir", "--env-file", "--detach-keys"},
|
|
111
|
+
("podman", "exec"): {"-e", "--env", "-u", "--user", "-w", "--workdir", "--env-file", "--detach-keys"},
|
|
112
|
+
("docker", "run"): {"-e", "--env", "-u", "--user", "-w", "--workdir", "--env-file", "-v", "--volume", "-p", "--publish",
|
|
113
|
+
"--name", "--network", "--net", "-l", "--label", "--entrypoint", "-m", "--memory", "--restart",
|
|
114
|
+
"--mount", "-h", "--hostname", "--cpus", "--platform"},
|
|
115
|
+
("podman", "run"): {"-e", "--env", "-u", "--user", "-w", "--workdir", "--env-file", "-v", "--volume", "-p", "--publish",
|
|
116
|
+
"--name", "--network", "--net", "-l", "--label", "--entrypoint", "-m", "--memory", "--restart",
|
|
117
|
+
"--mount", "-h", "--hostname", "--cpus", "--platform"},
|
|
118
|
+
("docker", "build"): {"-t", "--tag", "-f", "--file", "--build-arg", "--target", "--platform"},
|
|
119
|
+
("docker", "logs"): {"--tail", "-n", "--since", "--until"},
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
_CLUSTER = re.compile(r"^[A-Za-z0-9]+$")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def cmd_name(text: str) -> str:
|
|
126
|
+
"""Canonical lowercase command name from argv[0]."""
|
|
127
|
+
base = os.path.basename(text.rstrip("/")) or text
|
|
128
|
+
base = base.lower()
|
|
129
|
+
if base.endswith(".exe"):
|
|
130
|
+
base = base[:-4]
|
|
131
|
+
if re.fullmatch(r"python[0-9.]*", base):
|
|
132
|
+
return "python"
|
|
133
|
+
if base in ("nodejs",):
|
|
134
|
+
return "node"
|
|
135
|
+
return base
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class ParsedArgv:
|
|
140
|
+
name: str
|
|
141
|
+
words: List[Word]
|
|
142
|
+
tokens: List[str]
|
|
143
|
+
flags: Set[str] = field(default_factory=set)
|
|
144
|
+
flag_values: Dict[str, str] = field(default_factory=dict)
|
|
145
|
+
pos: List[str] = field(default_factory=list)
|
|
146
|
+
pos_words: List[Word] = field(default_factory=list)
|
|
147
|
+
pos_idx: List[int] = field(default_factory=list) # index into .words of each positional
|
|
148
|
+
argstr: str = ""
|
|
149
|
+
meta: dict = field(default_factory=dict)
|
|
150
|
+
raw0: str = ""
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def strip_wrappers(words: List[Word]) -> Tuple[List[Word], dict]:
|
|
154
|
+
"""Remove env assignments, reserved words and wrapper commands (sudo, env, ...)."""
|
|
155
|
+
i, n = 0, len(words)
|
|
156
|
+
meta = {"xargs": False, "sudo": False, "query": False}
|
|
157
|
+
guard = 0
|
|
158
|
+
while i < n and guard < 40:
|
|
159
|
+
guard += 1
|
|
160
|
+
t = words[i].text
|
|
161
|
+
if t == "" or t in RESERVED:
|
|
162
|
+
i += 1
|
|
163
|
+
continue
|
|
164
|
+
if is_assignment(t):
|
|
165
|
+
i += 1
|
|
166
|
+
continue
|
|
167
|
+
name = cmd_name(t)
|
|
168
|
+
if name == "env":
|
|
169
|
+
i += 1
|
|
170
|
+
while i < n:
|
|
171
|
+
tt = words[i].text
|
|
172
|
+
if tt == "--":
|
|
173
|
+
i += 1
|
|
174
|
+
break
|
|
175
|
+
if is_assignment(tt):
|
|
176
|
+
i += 1
|
|
177
|
+
continue
|
|
178
|
+
if tt.startswith("-") and len(tt) > 1:
|
|
179
|
+
i += 1
|
|
180
|
+
if tt in ("-u", "--unset", "-C", "--chdir", "-S", "--split-string") and i < n:
|
|
181
|
+
i += 1
|
|
182
|
+
continue
|
|
183
|
+
break
|
|
184
|
+
continue
|
|
185
|
+
spec = _WRAPPERS.get(name)
|
|
186
|
+
if spec is None:
|
|
187
|
+
break
|
|
188
|
+
val_opts, npos = spec
|
|
189
|
+
i += 1
|
|
190
|
+
if name == "command":
|
|
191
|
+
while i < n and words[i].text.startswith("-") and words[i].text != "--":
|
|
192
|
+
if words[i].text in ("-v", "-V"):
|
|
193
|
+
meta["query"] = True
|
|
194
|
+
i += 1
|
|
195
|
+
if i < n and words[i].text == "--":
|
|
196
|
+
i += 1
|
|
197
|
+
continue
|
|
198
|
+
while i < n:
|
|
199
|
+
tt = words[i].text
|
|
200
|
+
if tt == "--":
|
|
201
|
+
i += 1
|
|
202
|
+
break
|
|
203
|
+
if tt.startswith("-") and len(tt) > 1:
|
|
204
|
+
i += 1
|
|
205
|
+
if tt in val_opts and i < n:
|
|
206
|
+
i += 1
|
|
207
|
+
continue
|
|
208
|
+
break
|
|
209
|
+
i += npos
|
|
210
|
+
if name in ("sudo", "doas"):
|
|
211
|
+
meta["sudo"] = True
|
|
212
|
+
if name == "xargs":
|
|
213
|
+
meta["xargs"] = True
|
|
214
|
+
return words[i:], meta
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def parse_argv(words: List[Word], meta: dict | None = None) -> ParsedArgv | None:
|
|
218
|
+
if not words:
|
|
219
|
+
return None
|
|
220
|
+
name = cmd_name(words[0].text)
|
|
221
|
+
tokens = [w.text for w in words[1:]]
|
|
222
|
+
pa = ParsedArgv(name=name, words=words, tokens=tokens, meta=meta or {}, raw0=words[0].text)
|
|
223
|
+
base_vals = VALUE_FLAGS.get(name, set())
|
|
224
|
+
vals = base_vals
|
|
225
|
+
i, after_dd = 0, False
|
|
226
|
+
while i < len(tokens):
|
|
227
|
+
t, w = tokens[i], words[i + 1]
|
|
228
|
+
if after_dd:
|
|
229
|
+
pa.pos.append(t)
|
|
230
|
+
pa.pos_words.append(w)
|
|
231
|
+
pa.pos_idx.append(i + 1)
|
|
232
|
+
i += 1
|
|
233
|
+
continue
|
|
234
|
+
if t == "--":
|
|
235
|
+
after_dd = True
|
|
236
|
+
i += 1
|
|
237
|
+
continue
|
|
238
|
+
if t.startswith("--") and len(t) > 2:
|
|
239
|
+
if "=" in t:
|
|
240
|
+
nm, val = t.split("=", 1)
|
|
241
|
+
pa.flags.add(nm)
|
|
242
|
+
pa.flag_values[nm] = val
|
|
243
|
+
else:
|
|
244
|
+
pa.flags.add(t)
|
|
245
|
+
if t in vals and i + 1 < len(tokens):
|
|
246
|
+
pa.flag_values[t] = tokens[i + 1]
|
|
247
|
+
i += 1
|
|
248
|
+
i += 1
|
|
249
|
+
continue
|
|
250
|
+
if t.startswith("-") and len(t) > 1:
|
|
251
|
+
body = t[1:]
|
|
252
|
+
if _CLUSTER.match(body):
|
|
253
|
+
for ch in body:
|
|
254
|
+
pa.flags.add("-" + ch)
|
|
255
|
+
if len(body) > 1:
|
|
256
|
+
pa.flags.add(t)
|
|
257
|
+
last = "-" + body[-1]
|
|
258
|
+
if (t in vals or last in vals) and i + 1 < len(tokens):
|
|
259
|
+
pa.flag_values[t if t in vals else last] = tokens[i + 1]
|
|
260
|
+
i += 1
|
|
261
|
+
else:
|
|
262
|
+
nm = t.split("=", 1)[0]
|
|
263
|
+
pa.flags.add(nm)
|
|
264
|
+
if "=" in t:
|
|
265
|
+
pa.flag_values[nm] = t.split("=", 1)[1]
|
|
266
|
+
elif t in vals and i + 1 < len(tokens):
|
|
267
|
+
pa.flag_values[t] = tokens[i + 1]
|
|
268
|
+
i += 1
|
|
269
|
+
i += 1
|
|
270
|
+
continue
|
|
271
|
+
pa.pos.append(t)
|
|
272
|
+
pa.pos_words.append(w)
|
|
273
|
+
pa.pos_idx.append(i + 1)
|
|
274
|
+
if name in _SCOPED:
|
|
275
|
+
# Value-taking options change meaning per subcommand, so rescope as positionals appear:
|
|
276
|
+
# global options -> subcommand options -> none (what follows belongs to the container command).
|
|
277
|
+
n = len(pa.pos)
|
|
278
|
+
if n == 1:
|
|
279
|
+
vals = set() if name == "docker-compose" else _SUB_VALUE_FLAGS.get((name, t), set())
|
|
280
|
+
elif n == 2:
|
|
281
|
+
vals = set()
|
|
282
|
+
i += 1
|
|
283
|
+
pa.argstr = " ".join(tokens)
|
|
284
|
+
return pa
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def alt_match(token: str, alts: List[str], icase: bool = False) -> bool:
|
|
288
|
+
for a in alts:
|
|
289
|
+
if a.startswith("re:"):
|
|
290
|
+
if re.search(a[3:], token, re.I if icase else 0):
|
|
291
|
+
return True
|
|
292
|
+
elif (a.lower() == token.lower()) if icase else (a == token):
|
|
293
|
+
return True
|
|
294
|
+
return False
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def sub_matches(pa: ParsedArgv, sub: List[List[str]], icase: bool = False) -> bool:
|
|
298
|
+
if len(pa.pos) < len(sub):
|
|
299
|
+
return False
|
|
300
|
+
return all(alt_match(p, alts, icase) for p, alts in zip(pa.pos, sub))
|