rigcode 0.1.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.
- rigcode/__init__.py +4 -0
- rigcode/__main__.py +4 -0
- rigcode/agent/__init__.py +0 -0
- rigcode/agent/loop.py +627 -0
- rigcode/agent/mentions.py +70 -0
- rigcode/agent/prompts.py +195 -0
- rigcode/agent/runtime.py +535 -0
- rigcode/agent/session.py +165 -0
- rigcode/agent/state.py +161 -0
- rigcode/cli.py +283 -0
- rigcode/config.py +284 -0
- rigcode/doctor.py +158 -0
- rigcode/extensions.py +275 -0
- rigcode/hooks.py +142 -0
- rigcode/llm/__init__.py +0 -0
- rigcode/llm/client.py +259 -0
- rigcode/llm/probe.py +229 -0
- rigcode/llm/stream.py +240 -0
- rigcode/llm/textmode.py +161 -0
- rigcode/llm/types.py +92 -0
- rigcode/llm/wire.py +76 -0
- rigcode/mcp.py +329 -0
- rigcode/permissions.py +221 -0
- rigcode/prompts/agents/coder.md +13 -0
- rigcode/prompts/agents/debugger.md +14 -0
- rigcode/prompts/agents/explore.md +22 -0
- rigcode/prompts/agents/plan.md +21 -0
- rigcode/prompts/agents/researcher.md +14 -0
- rigcode/prompts/agents/reviewer.md +18 -0
- rigcode/prompts/agents/verifier.md +15 -0
- rigcode/prompts/commit.md +5 -0
- rigcode/prompts/compact.md +24 -0
- rigcode/prompts/init.md +10 -0
- rigcode/prompts/system.md +27 -0
- rigcode/tools/__init__.py +0 -0
- rigcode/tools/base.py +245 -0
- rigcode/tools/bashsafety.py +262 -0
- rigcode/tools/editmatch.py +367 -0
- rigcode/tools/files.py +534 -0
- rigcode/tools/interact.py +69 -0
- rigcode/tools/search.py +309 -0
- rigcode/tools/shell.py +424 -0
- rigcode/tools/skill.py +37 -0
- rigcode/tools/task.py +54 -0
- rigcode/tools/todo.py +62 -0
- rigcode/tools/web.py +346 -0
- rigcode/ui/__init__.py +0 -0
- rigcode/ui/base.py +69 -0
- rigcode/ui/commands.py +581 -0
- rigcode/ui/plain.py +321 -0
- rigcode/ui/render.py +207 -0
- rigcode/ui/terminal.py +1154 -0
- rigcode/utils/__init__.py +0 -0
- rigcode/utils/files.py +176 -0
- rigcode/utils/frontmatter.py +38 -0
- rigcode/utils/globmatch.py +91 -0
- rigcode/utils/jsonrepair.py +110 -0
- rigcode/utils/paths.py +83 -0
- rigcode/utils/text.py +105 -0
- rigcode-0.1.0.dist-info/METADATA +203 -0
- rigcode-0.1.0.dist-info/RECORD +64 -0
- rigcode-0.1.0.dist-info/WHEEL +4 -0
- rigcode-0.1.0.dist-info/entry_points.txt +2 -0
- rigcode-0.1.0.dist-info/licenses/LICENSE +21 -0
rigcode/tools/base.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Tool interface, result type, argument validation and the registry."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from rigcode.utils.text import one_line
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
11
|
+
from rigcode.agent.loop import Agent
|
|
12
|
+
from rigcode.agent.runtime import Runtime
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class ToolResult:
|
|
17
|
+
content: str # what the model sees
|
|
18
|
+
is_error: bool = False
|
|
19
|
+
summary: str | None = None # one-line UI summary ("Read 120 lines")
|
|
20
|
+
display: dict | None = None # rich UI payload: {"type": "diff"|"todos"|"output"|"markdown", ...}
|
|
21
|
+
images: list[dict] = field(default_factory=list) # [{"mime": "image/png", "data": b64}]
|
|
22
|
+
stop_turn: bool = False # end the agent turn after this result (e.g. user said stop)
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def error(cls, message: str, summary: str | None = None) -> ToolResult:
|
|
26
|
+
return cls(content=message, is_error=True, summary=summary or one_line(message, 100))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ToolContext:
|
|
31
|
+
rt: Runtime
|
|
32
|
+
agent: Agent
|
|
33
|
+
call_id: str = ""
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def cwd(self):
|
|
37
|
+
return self.rt.cwd
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Tool:
|
|
41
|
+
name: str = ""
|
|
42
|
+
description: str = ""
|
|
43
|
+
parameters: dict = {"type": "object", "properties": {}}
|
|
44
|
+
read_only: bool = False
|
|
45
|
+
# Permission category: read | edit | exec | web | agent | interact | mcp
|
|
46
|
+
kind: str = "read"
|
|
47
|
+
# Parameter names other harnesses use -> ours (applied before validation).
|
|
48
|
+
aliases: dict[str, str] = {}
|
|
49
|
+
|
|
50
|
+
def apply_aliases(self, args: dict) -> dict:
|
|
51
|
+
for alias, canonical in self.aliases.items():
|
|
52
|
+
if alias in args and canonical not in args:
|
|
53
|
+
args[canonical] = args.pop(alias)
|
|
54
|
+
return args
|
|
55
|
+
|
|
56
|
+
def schema(self) -> dict:
|
|
57
|
+
return {"type": "function", "function": {
|
|
58
|
+
"name": self.name, "description": self.description.strip(), "parameters": self.parameters}}
|
|
59
|
+
|
|
60
|
+
def is_read_only(self, args: dict) -> bool:
|
|
61
|
+
return self.read_only
|
|
62
|
+
|
|
63
|
+
def permission_target(self, args: dict) -> str:
|
|
64
|
+
"""The string permission rules match against (path, command, URL...)."""
|
|
65
|
+
return ""
|
|
66
|
+
|
|
67
|
+
def label(self, args: dict, ctx: ToolContext | None = None) -> str:
|
|
68
|
+
"""Short human-readable call description for the UI: Name(arg)."""
|
|
69
|
+
target = self.permission_target(args)
|
|
70
|
+
return f"{self.name}({one_line(target, 70)})" if target else self.name
|
|
71
|
+
|
|
72
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult: # pragma: no cover - abstract
|
|
73
|
+
raise NotImplementedError
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ---------------------------------------------------------------- validation
|
|
77
|
+
|
|
78
|
+
_TYPE_NAMES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _coerce(value: Any, spec: dict) -> tuple[Any, str | None]:
|
|
82
|
+
typ = spec.get("type")
|
|
83
|
+
if isinstance(typ, list):
|
|
84
|
+
for t in typ:
|
|
85
|
+
v, err = _coerce(value, {**spec, "type": t})
|
|
86
|
+
if err is None:
|
|
87
|
+
return v, None
|
|
88
|
+
return value, f"expected one of {typ}"
|
|
89
|
+
if typ is None or value is None:
|
|
90
|
+
return value, None
|
|
91
|
+
if typ == "integer":
|
|
92
|
+
if isinstance(value, bool):
|
|
93
|
+
return value, "expected integer"
|
|
94
|
+
if isinstance(value, int):
|
|
95
|
+
return value, None
|
|
96
|
+
if isinstance(value, float) and value.is_integer():
|
|
97
|
+
return int(value), None
|
|
98
|
+
if isinstance(value, str) and value.strip().lstrip("-").isdigit():
|
|
99
|
+
return int(value.strip()), None
|
|
100
|
+
return value, "expected integer"
|
|
101
|
+
if typ == "number":
|
|
102
|
+
if isinstance(value, bool):
|
|
103
|
+
return value, "expected number"
|
|
104
|
+
if isinstance(value, (int, float)):
|
|
105
|
+
return value, None
|
|
106
|
+
try:
|
|
107
|
+
return float(value), None
|
|
108
|
+
except (TypeError, ValueError):
|
|
109
|
+
return value, "expected number"
|
|
110
|
+
if typ == "boolean":
|
|
111
|
+
if isinstance(value, bool):
|
|
112
|
+
return value, None
|
|
113
|
+
if isinstance(value, str) and value.strip().lower() in ("true", "false", "1", "0", "yes", "no"):
|
|
114
|
+
return value.strip().lower() in ("true", "1", "yes"), None
|
|
115
|
+
if isinstance(value, int):
|
|
116
|
+
return bool(value), None
|
|
117
|
+
return value, "expected boolean"
|
|
118
|
+
if typ == "string":
|
|
119
|
+
if isinstance(value, str):
|
|
120
|
+
return value, None
|
|
121
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
122
|
+
return str(value), None
|
|
123
|
+
if isinstance(value, (dict, list)):
|
|
124
|
+
return json.dumps(value, ensure_ascii=False, indent=2), None
|
|
125
|
+
return value, "expected string"
|
|
126
|
+
if typ == "array":
|
|
127
|
+
if isinstance(value, str):
|
|
128
|
+
try:
|
|
129
|
+
parsed = json.loads(value)
|
|
130
|
+
if isinstance(parsed, list):
|
|
131
|
+
value = parsed
|
|
132
|
+
except json.JSONDecodeError:
|
|
133
|
+
return value, "expected array"
|
|
134
|
+
if not isinstance(value, list):
|
|
135
|
+
return value, "expected array"
|
|
136
|
+
item_spec = spec.get("items")
|
|
137
|
+
if isinstance(item_spec, dict):
|
|
138
|
+
out = []
|
|
139
|
+
for i, item in enumerate(value):
|
|
140
|
+
v, err = _coerce(item, item_spec)
|
|
141
|
+
if err:
|
|
142
|
+
return value, f"item {i}: {err}"
|
|
143
|
+
out.append(v)
|
|
144
|
+
value = out
|
|
145
|
+
return value, None
|
|
146
|
+
if typ == "object":
|
|
147
|
+
if isinstance(value, str):
|
|
148
|
+
try:
|
|
149
|
+
parsed = json.loads(value)
|
|
150
|
+
if isinstance(parsed, dict):
|
|
151
|
+
value = parsed
|
|
152
|
+
except json.JSONDecodeError:
|
|
153
|
+
return value, "expected object"
|
|
154
|
+
if not isinstance(value, dict):
|
|
155
|
+
return value, "expected object"
|
|
156
|
+
if "properties" in spec:
|
|
157
|
+
return validate_object(value, spec)
|
|
158
|
+
return value, None
|
|
159
|
+
return value, None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def validate_object(args: dict, schema: dict) -> tuple[dict, str | None]:
|
|
163
|
+
props = schema.get("properties") or {}
|
|
164
|
+
out = dict(args)
|
|
165
|
+
missing = [k for k in schema.get("required") or [] if out.get(k) is None]
|
|
166
|
+
if missing:
|
|
167
|
+
return out, f"missing required parameter(s): {', '.join(missing)}"
|
|
168
|
+
for key, spec in props.items():
|
|
169
|
+
if key in out and out[key] is not None:
|
|
170
|
+
v, err = _coerce(out[key], spec)
|
|
171
|
+
if err:
|
|
172
|
+
return out, f"parameter '{key}': {err}"
|
|
173
|
+
if "enum" in spec and v not in spec["enum"]:
|
|
174
|
+
return out, f"parameter '{key}' must be one of {spec['enum']}"
|
|
175
|
+
out[key] = v
|
|
176
|
+
return out, None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def validate_args(tool: Tool, args: dict) -> tuple[dict, str | None]:
|
|
180
|
+
return validate_object(args, tool.parameters)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# ---------------------------------------------------------------- registry
|
|
184
|
+
|
|
185
|
+
class ToolRegistry:
|
|
186
|
+
def __init__(self) -> None:
|
|
187
|
+
self._tools: dict[str, Tool] = {}
|
|
188
|
+
|
|
189
|
+
def register(self, tool: Tool) -> None:
|
|
190
|
+
self._tools[tool.name] = tool
|
|
191
|
+
|
|
192
|
+
def unregister(self, name: str) -> None:
|
|
193
|
+
self._tools.pop(name, None)
|
|
194
|
+
|
|
195
|
+
def get(self, name: str) -> Tool | None:
|
|
196
|
+
tool = self._tools.get(name)
|
|
197
|
+
if tool is None:
|
|
198
|
+
# Tolerate case/underscore drift from the model (read_file -> Read handled by aliases).
|
|
199
|
+
low = name.lower().replace("_", "").replace("-", "")
|
|
200
|
+
for t in self._tools.values():
|
|
201
|
+
if t.name.lower().replace("_", "") == low:
|
|
202
|
+
return t
|
|
203
|
+
alias = TOOL_ALIASES.get(name.lower())
|
|
204
|
+
if alias:
|
|
205
|
+
return self._tools.get(alias)
|
|
206
|
+
return tool
|
|
207
|
+
|
|
208
|
+
def names(self) -> list[str]:
|
|
209
|
+
return list(self._tools)
|
|
210
|
+
|
|
211
|
+
def all(self) -> list[Tool]:
|
|
212
|
+
return list(self._tools.values())
|
|
213
|
+
|
|
214
|
+
def subset(self, names: list[str] | None, exclude: set[str] | None = None) -> ToolRegistry:
|
|
215
|
+
reg = ToolRegistry()
|
|
216
|
+
exclude = exclude or set()
|
|
217
|
+
for t in self._tools.values():
|
|
218
|
+
if t.name in exclude:
|
|
219
|
+
continue
|
|
220
|
+
if names is None or t.name in names or ("mcp" in names and t.name.startswith("mcp__")):
|
|
221
|
+
reg.register(t)
|
|
222
|
+
return reg
|
|
223
|
+
|
|
224
|
+
def schemas(self) -> list[dict]:
|
|
225
|
+
return [t.schema() for t in self._tools.values()]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# Common names other harnesses use, mapped to ours.
|
|
229
|
+
TOOL_ALIASES = {
|
|
230
|
+
"read_file": "Read", "readfile": "Read", "view": "Read", "cat": "Read", "open_file": "Read",
|
|
231
|
+
"write_file": "Write", "writefile": "Write", "create_file": "Write",
|
|
232
|
+
"edit_file": "Edit", "str_replace": "Edit", "strreplacefile": "Edit", "replace_in_file": "Edit",
|
|
233
|
+
"str_replace_editor": "Edit", "apply_edit": "Edit",
|
|
234
|
+
"multi_edit": "MultiEdit",
|
|
235
|
+
"shell": "Bash", "run_shell_command": "Bash", "execute_command": "Bash", "run_command": "Bash",
|
|
236
|
+
"terminal": "Bash", "exec": "Bash", "powershell": "Bash",
|
|
237
|
+
"glob_search": "Glob", "find_files": "Glob", "list_files": "Glob",
|
|
238
|
+
"grep_search": "Grep", "search": "Grep", "search_files": "Grep", "ripgrep": "Grep",
|
|
239
|
+
"fetch": "WebFetch", "fetch_url": "WebFetch", "fetchurl": "WebFetch", "web_fetch": "WebFetch",
|
|
240
|
+
"search_web": "WebSearch", "searchweb": "WebSearch", "web_search": "WebSearch",
|
|
241
|
+
"todo_write": "TodoWrite", "settodolist": "TodoWrite", "update_todos": "TodoWrite",
|
|
242
|
+
"agent": "Task", "subagent": "Task", "dispatch_agent": "Task",
|
|
243
|
+
"ask_user": "AskUser", "askuserquestion": "AskUser", "ask_followup_question": "AskUser",
|
|
244
|
+
"exit_plan_mode": "ExitPlanMode",
|
|
245
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Shell command analysis: read-only classification, danger detection, rule
|
|
2
|
+
suggestions. Conservative by design: anything unrecognized needs approval."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
|
|
9
|
+
READ_ONLY = {
|
|
10
|
+
"ls", "dir", "pwd", "cat", "head", "tail", "wc", "echo", "printf", "grep", "egrep", "fgrep", "rg", "ag",
|
|
11
|
+
"tree", "which", "where", "whereis", "type", "file", "stat", "du", "df", "uname", "whoami", "id", "date",
|
|
12
|
+
"hostname", "ps", "sort", "uniq", "cut", "basename", "dirname", "realpath", "readlink", "nl", "diff",
|
|
13
|
+
"cmp", "comm", "column", "jq", "true", "false", "test", "[", "env", "printenv", "md5sum", "sha1sum",
|
|
14
|
+
"sha256sum", "cksum", "od", "hexdump", "strings", "free", "uptime", "nproc", "arch", "lscpu", "seq",
|
|
15
|
+
"findstr", "ver", "tasklist", "systeminfo", "wsl.exe-version",
|
|
16
|
+
# PowerShell read-only cmdlets (and aliases)
|
|
17
|
+
"get-childitem", "gci", "get-content", "gc", "select-string", "sls", "get-location", "gl", "get-item",
|
|
18
|
+
"gi", "test-path", "get-command", "gcm", "resolve-path", "measure-object", "measure", "get-process",
|
|
19
|
+
"gps", "format-table", "ft", "format-list", "fl", "select-object", "select", "where-object", "sort-object", "out-string", "get-date", "get-itemproperty", "get-filehash", "get-help", "write-output",
|
|
20
|
+
"write-host",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
GIT_READ_ONLY = {
|
|
24
|
+
"status", "diff", "log", "show", "rev-parse", "ls-files", "ls-tree", "blame", "describe", "shortlog",
|
|
25
|
+
"grep", "cat-file", "show-ref", "name-rev", "merge-base", "whatchanged", "count-objects", "for-each-ref",
|
|
26
|
+
"var", "help", "version", "--version", "fetch --dry-run",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
VERSION_ONLY = {"python", "python3", "py", "node", "ruby", "go", "cargo", "rustc", "java", "javac", "gcc",
|
|
30
|
+
"clang", "dotnet", "deno", "bun", "npm", "pnpm", "yarn", "pip", "pip3", "uv", "conda", "make",
|
|
31
|
+
"cmake", "perl", "php", "tsc", "kubectl", "docker", "terraform", "gh", "git"}
|
|
32
|
+
|
|
33
|
+
PKG_READ_ONLY = {
|
|
34
|
+
"npm": {"ls", "list", "view", "info", "outdated", "why", "explain", "config"},
|
|
35
|
+
"pnpm": {"ls", "list", "why", "outdated"},
|
|
36
|
+
"yarn": {"list", "info", "why", "outdated"},
|
|
37
|
+
"pip": {"list", "show", "freeze", "check"},
|
|
38
|
+
"pip3": {"list", "show", "freeze", "check"},
|
|
39
|
+
"conda": {"list", "info"},
|
|
40
|
+
"docker": {"ps", "images", "logs", "inspect", "version", "info"},
|
|
41
|
+
"kubectl": {"get", "describe", "logs", "version"},
|
|
42
|
+
"go": {"version", "env", "list", "doc", "vet"},
|
|
43
|
+
"cargo": {"tree", "metadata"},
|
|
44
|
+
"gh": {"status"},
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
MULTI_WORD = {"npm", "pnpm", "yarn", "bun", "git", "cargo", "go", "uv", "pip", "pip3", "docker", "kubectl",
|
|
48
|
+
"make", "poetry", "dotnet", "gh", "conda", "pytest", "mvn", "gradle", "./gradlew", "terraform"}
|
|
49
|
+
|
|
50
|
+
DANGEROUS_PATTERNS = [
|
|
51
|
+
(r"\brm\s+(-[a-zA-Z]*[rf][a-zA-Z]*\s+)+(/|~|\*|\.\.?)(\s|$)", "recursive delete of a broad path"),
|
|
52
|
+
(r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f|\brm\s+-[a-zA-Z]*f[a-zA-Z]*r", "rm -rf"),
|
|
53
|
+
(r"\b(rmdir|rd)\s+/s\b|\bdel\s+/[sfq]", "recursive delete (cmd)"),
|
|
54
|
+
(r"remove-item\b.*-recurse", "recursive delete (PowerShell)"),
|
|
55
|
+
(r"\bgit\s+push\b.*(--force\b|-f\b|--force-with-lease)", "force push"),
|
|
56
|
+
(r"\bgit\s+reset\s+--hard", "git reset --hard (discards changes)"),
|
|
57
|
+
(r"\bgit\s+clean\s+-[a-zA-Z]*[fdx]", "git clean (deletes untracked files)"),
|
|
58
|
+
(r"\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)", "discards working-tree changes"),
|
|
59
|
+
(r"\bgit\s+branch\s+-D\b", "force-deletes a branch"),
|
|
60
|
+
(r"\bsudo\b|\bsu\s+-", "elevated privileges"),
|
|
61
|
+
(r"\bmkfs\b|\bdd\s+if=|>\s*/dev/sd|\bformat\s+[a-z]:", "disk-level operation"),
|
|
62
|
+
(r"\b(shutdown|reboot|halt|poweroff)\b|stop-computer|restart-computer", "shuts down or reboots"),
|
|
63
|
+
(r"(curl|wget|iwr|invoke-webrequest)\b[^|]*\|\s*(sh|bash|zsh|python|iex|invoke-expression)", "pipes a download into a shell"),
|
|
64
|
+
(r"\bchmod\s+(-R\s+)?777\b", "world-writable permissions"),
|
|
65
|
+
(r":\(\)\s*\{.*\};\s*:", "fork bomb"),
|
|
66
|
+
(r"\b(npm|pnpm|yarn|cargo|twine|uv)\s+publish\b", "publishes a package"),
|
|
67
|
+
(r"\bdocker\s+(system|volume|image)\s+prune\b", "docker prune"),
|
|
68
|
+
(r"\bdrop\s+(table|database)\b|\btruncate\s+table\b", "destructive SQL"),
|
|
69
|
+
]
|
|
70
|
+
_CASE_SENSITIVE = {"force-deletes a branch"} # git branch -D (unlike -d) is the dangerous one
|
|
71
|
+
_DANGER = [(re.compile(p, 0 if reason in _CASE_SENSITIVE else re.I), reason) for p, reason in DANGEROUS_PATTERNS]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def split_segments(command: str) -> list[str] | None:
|
|
75
|
+
"""Split on unquoted && || ; | & and newlines. Returns None if the command
|
|
76
|
+
uses constructs we refuse to auto-approve (substitution, output redirection)."""
|
|
77
|
+
segs: list[str] = []
|
|
78
|
+
cur: list[str] = []
|
|
79
|
+
i, n = 0, len(command)
|
|
80
|
+
quote = None
|
|
81
|
+
while i < n:
|
|
82
|
+
c = command[i]
|
|
83
|
+
if quote == "'":
|
|
84
|
+
cur.append(c)
|
|
85
|
+
if c == "'":
|
|
86
|
+
quote = None
|
|
87
|
+
i += 1
|
|
88
|
+
continue
|
|
89
|
+
if quote == '"':
|
|
90
|
+
if c == "\\" and i + 1 < n:
|
|
91
|
+
cur.append(command[i:i + 2])
|
|
92
|
+
i += 2
|
|
93
|
+
continue
|
|
94
|
+
if c == "`" or command.startswith("$(", i):
|
|
95
|
+
return None
|
|
96
|
+
cur.append(c)
|
|
97
|
+
if c == '"':
|
|
98
|
+
quote = None
|
|
99
|
+
i += 1
|
|
100
|
+
continue
|
|
101
|
+
if c in "'\"":
|
|
102
|
+
quote = c
|
|
103
|
+
cur.append(c)
|
|
104
|
+
i += 1
|
|
105
|
+
continue
|
|
106
|
+
if c == "\\" and i + 1 < n:
|
|
107
|
+
cur.append(command[i:i + 2])
|
|
108
|
+
i += 2
|
|
109
|
+
continue
|
|
110
|
+
if c == "`" or command.startswith("$(", i) or command.startswith("<(", i) or command.startswith(">(", i):
|
|
111
|
+
return None
|
|
112
|
+
if c == ">":
|
|
113
|
+
rest = command[i:]
|
|
114
|
+
ok = re.match(r">&\s*[12]\b|>\s*/dev/null\b|>\s*\$null\b|>\s*nul\b", rest, re.I)
|
|
115
|
+
prev = "".join(cur).rstrip()
|
|
116
|
+
if ok or (prev.endswith("2") and re.match(r">\s*/dev/null|>&1", rest)):
|
|
117
|
+
m = ok or re.match(r">\s*/dev/null|>&1", rest)
|
|
118
|
+
cur.append(m.group(0))
|
|
119
|
+
i += len(m.group(0))
|
|
120
|
+
continue
|
|
121
|
+
return None
|
|
122
|
+
if command.startswith("&&", i) or command.startswith("||", i):
|
|
123
|
+
segs.append("".join(cur))
|
|
124
|
+
cur = []
|
|
125
|
+
i += 2
|
|
126
|
+
continue
|
|
127
|
+
if c in ";|&\n":
|
|
128
|
+
segs.append("".join(cur))
|
|
129
|
+
cur = []
|
|
130
|
+
i += 1
|
|
131
|
+
continue
|
|
132
|
+
cur.append(c)
|
|
133
|
+
i += 1
|
|
134
|
+
if quote:
|
|
135
|
+
return None
|
|
136
|
+
segs.append("".join(cur))
|
|
137
|
+
return [s.strip() for s in segs if s.strip()]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _tokens(segment: str) -> list[str]:
|
|
141
|
+
try:
|
|
142
|
+
toks = shlex.split(segment, posix=True)
|
|
143
|
+
except ValueError:
|
|
144
|
+
toks = segment.split()
|
|
145
|
+
while toks and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", toks[0]):
|
|
146
|
+
toks.pop(0)
|
|
147
|
+
return toks
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _base(word: str) -> str:
|
|
151
|
+
w = word.replace("\\", "/").rsplit("/", 1)[-1].lower()
|
|
152
|
+
for ext in (".exe", ".cmd", ".bat"):
|
|
153
|
+
if w.endswith(ext):
|
|
154
|
+
w = w[: -len(ext)]
|
|
155
|
+
return w
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def segment_is_read_only(segment: str) -> bool:
|
|
159
|
+
toks = _tokens(segment)
|
|
160
|
+
if not toks:
|
|
161
|
+
return True
|
|
162
|
+
cmd = _base(toks[0])
|
|
163
|
+
args = toks[1:]
|
|
164
|
+
low_args = [a.lower() for a in args]
|
|
165
|
+
if cmd in ("cd", "set-location", "sl", "pushd", "popd"):
|
|
166
|
+
return True
|
|
167
|
+
if cmd == "find":
|
|
168
|
+
return not any(a in ("-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprintf", "-fls") for a in args)
|
|
169
|
+
if cmd == "sed":
|
|
170
|
+
return not any(a.startswith("-i") or a == "--in-place" for a in args)
|
|
171
|
+
if cmd == "git":
|
|
172
|
+
while args and args[0].startswith("-"):
|
|
173
|
+
opt = args.pop(0)
|
|
174
|
+
if opt in ("-C", "-c") and args:
|
|
175
|
+
args.pop(0)
|
|
176
|
+
if not args:
|
|
177
|
+
return True
|
|
178
|
+
sub = args[0]
|
|
179
|
+
rest = args[1:]
|
|
180
|
+
if sub in GIT_READ_ONLY:
|
|
181
|
+
return True
|
|
182
|
+
if sub == "branch":
|
|
183
|
+
return not any(a in ("-d", "-D", "-m", "-M", "--delete", "--move", "-c", "-C", "--copy", "-f", "--force",
|
|
184
|
+
"--set-upstream-to", "-u", "--unset-upstream", "--edit-description") for a in rest) and \
|
|
185
|
+
all(a.startswith("-") for a in rest)
|
|
186
|
+
if sub == "tag":
|
|
187
|
+
return not rest or all(a in ("-l", "--list", "-n") or a.startswith("--sort") or a.startswith("--contains") for a in rest)
|
|
188
|
+
if sub == "remote":
|
|
189
|
+
return not rest or rest[0] in ("-v", "show", "get-url")
|
|
190
|
+
if sub == "stash":
|
|
191
|
+
return bool(rest) and rest[0] in ("list", "show")
|
|
192
|
+
if sub == "config":
|
|
193
|
+
return any(a in ("--get", "--list", "-l", "--get-all", "--get-regexp") for a in rest)
|
|
194
|
+
if sub == "reflog":
|
|
195
|
+
return not rest or rest[0] == "show"
|
|
196
|
+
return False
|
|
197
|
+
if cmd in READ_ONLY:
|
|
198
|
+
return True
|
|
199
|
+
if cmd in VERSION_ONLY and low_args and low_args[0] in ("--version", "-v", "-V", "version"):
|
|
200
|
+
return True
|
|
201
|
+
if cmd in PKG_READ_ONLY and args and args[0] in PKG_READ_ONLY[cmd]:
|
|
202
|
+
if cmd == "npm" and args[0] == "config":
|
|
203
|
+
return len(args) > 1 and args[1] in ("get", "list", "ls")
|
|
204
|
+
return True
|
|
205
|
+
if cmd == "uv" and args[:2] in (["pip", "list"], ["pip", "show"], ["pip", "freeze"]) or (cmd == "uv" and args[:1] == ["tree"]):
|
|
206
|
+
return True
|
|
207
|
+
return False
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def is_read_only_command(command: str) -> bool:
|
|
211
|
+
segs = split_segments(command)
|
|
212
|
+
if segs is None:
|
|
213
|
+
return False
|
|
214
|
+
return all(segment_is_read_only(s) for s in segs)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def danger_reason(command: str) -> str | None:
|
|
218
|
+
for rx, reason in _DANGER:
|
|
219
|
+
if rx.search(command):
|
|
220
|
+
return reason
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def command_prefix(segment: str) -> str:
|
|
225
|
+
toks = _tokens(segment)
|
|
226
|
+
if not toks:
|
|
227
|
+
return segment.strip()
|
|
228
|
+
word = toks[0]
|
|
229
|
+
base = _base(word)
|
|
230
|
+
if base in ("python", "python3", "py") and len(toks) > 2 and toks[1] == "-m":
|
|
231
|
+
return " ".join(toks[:3])
|
|
232
|
+
if base in ("npm", "pnpm", "yarn", "bun", "uv", "poetry") and len(toks) > 2 and toks[1] == "run":
|
|
233
|
+
return " ".join(toks[:3])
|
|
234
|
+
if base in MULTI_WORD and len(toks) > 1 and not toks[1].startswith("-"):
|
|
235
|
+
return " ".join(toks[:2])
|
|
236
|
+
return word
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def suggest_rule(command: str) -> str:
|
|
240
|
+
segs = split_segments(command) or [command]
|
|
241
|
+
return f"Bash({command_prefix(segs[0])}:*)"
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def rule_matches_segment(rule_body: str, segment: str) -> bool:
|
|
245
|
+
"""rule_body: 'npm test:*' (prefix), 'git *' (glob) or an exact command."""
|
|
246
|
+
seg = " ".join(segment.split())
|
|
247
|
+
body = " ".join(rule_body.split())
|
|
248
|
+
if body.endswith(":*"):
|
|
249
|
+
prefix = body[:-2].rstrip()
|
|
250
|
+
return seg == prefix or seg.startswith(prefix + " ")
|
|
251
|
+
if "*" in body or "?" in body:
|
|
252
|
+
return fnmatch.fnmatchcase(seg, body)
|
|
253
|
+
return seg == body
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def command_matches_rule(rule_body: str, command: str) -> bool:
|
|
257
|
+
"""Every segment of a compound command must match (or be read-only)."""
|
|
258
|
+
segs = split_segments(command)
|
|
259
|
+
if segs is None:
|
|
260
|
+
return rule_matches_segment(rule_body, command)
|
|
261
|
+
return all(rule_matches_segment(rule_body, s) or segment_is_read_only(s) for s in segs) and \
|
|
262
|
+
any(rule_matches_segment(rule_body, s) for s in segs)
|