kasakir-agent-sync 0.11.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.
- agent_sync/__init__.py +6 -0
- agent_sync/__main__.py +3 -0
- agent_sync/agents.py +204 -0
- agent_sync/audit.py +207 -0
- agent_sync/backups.py +292 -0
- agent_sync/catalog.py +258 -0
- agent_sync/checks.py +38 -0
- agent_sync/cleanup.py +87 -0
- agent_sync/cli.py +1045 -0
- agent_sync/config.py +186 -0
- agent_sync/configure.py +602 -0
- agent_sync/duplicates.py +258 -0
- agent_sync/instructions.py +481 -0
- agent_sync/inventory.py +285 -0
- agent_sync/locking.py +39 -0
- agent_sync/log.py +128 -0
- agent_sync/mcp.py +627 -0
- agent_sync/membership.py +89 -0
- agent_sync/memory.py +278 -0
- agent_sync/notify.py +402 -0
- agent_sync/pending.py +161 -0
- agent_sync/plugins.py +216 -0
- agent_sync/privacy.py +71 -0
- agent_sync/registry.py +122 -0
- agent_sync/review.html +883 -0
- agent_sync/review.py +969 -0
- agent_sync/reviewpage.py +326 -0
- agent_sync/roles.py +75 -0
- agent_sync/schedule.py +321 -0
- agent_sync/setup.py +163 -0
- agent_sync/skill_catalog.json +2587 -0
- agent_sync/skills.py +515 -0
- agent_sync/statusline.py +380 -0
- agent_sync/statuslines.py +133 -0
- agent_sync/system.py +370 -0
- agent_sync/textmerge.py +144 -0
- agent_sync/tomledit.py +245 -0
- agent_sync/tools.py +762 -0
- agent_sync/upgrades.py +451 -0
- agent_sync/writes.py +537 -0
- kasakir_agent_sync-0.11.0.dist-info/METADATA +224 -0
- kasakir_agent_sync-0.11.0.dist-info/RECORD +47 -0
- kasakir_agent_sync-0.11.0.dist-info/WHEEL +5 -0
- kasakir_agent_sync-0.11.0.dist-info/entry_points.txt +3 -0
- kasakir_agent_sync-0.11.0.dist-info/licenses/LICENSE +21 -0
- kasakir_agent_sync-0.11.0.dist-info/licenses/THIRD_PARTY_LICENSES.md +27 -0
- kasakir_agent_sync-0.11.0.dist-info/top_level.txt +1 -0
agent_sync/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Keep AI coding agents in step (Claude Code, Codex, Cursor, Gemini CLI, Antigravity).
|
|
2
|
+
|
|
3
|
+
Skill packages, agents, model roles, MCP servers and the CLIs.
|
|
4
|
+
"""
|
|
5
|
+
__version__ = "0.11.0"
|
|
6
|
+
DISTRIBUTION = "kasakir-agent-sync" # the package's name on PyPI (pyproject.toml); the commands are agent-sync
|
agent_sync/__main__.py
ADDED
agent_sync/agents.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Mirror a skill package's agents/*.md into each enabled agent.
|
|
2
|
+
|
|
3
|
+
- Claude Code: ~/.claude/agents/<name>.md with the configured Claude model.
|
|
4
|
+
- Codex: ~/.codex/agents/<name>.toml (name, description, model, model_reasoning_effort, developer_instructions).
|
|
5
|
+
- Cursor: a local plugin, ~/.cursor/plugins/local/<package>-agents/. Cursor reads custom agents from a project's
|
|
6
|
+
.cursor/agents and from plugins, not from ~/.cursor/agents, so a small agents-only plugin makes them global.
|
|
7
|
+
- Gemini CLI: ~/.gemini/agents/<name>.md. Antigravity: ~/.gemini/config/agents/<name>.md.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from hashlib import sha256
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import backups, pending, system, writes
|
|
18
|
+
from .config import AgentModels
|
|
19
|
+
from .registry import DEFAULT_AGENTS, TOOLS, grouped_paths
|
|
20
|
+
from .tomledit import basic_string
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def description(front: str) -> tuple[str, str]:
|
|
24
|
+
"""Return the description as text for TOML and as written for YAML."""
|
|
25
|
+
found = re.search(r"^description:[ \t]*(.*)$", front, re.M)
|
|
26
|
+
if not found:
|
|
27
|
+
return "", ""
|
|
28
|
+
head = found.group(1).strip()
|
|
29
|
+
if not re.fullmatch(r"[>|](?:[1-9][+-]?|[+-][1-9]?)?(?:[ \t]+#.*)?", head):
|
|
30
|
+
return head, head
|
|
31
|
+
block = []
|
|
32
|
+
for line in front[found.end():].split("\n")[1:]:
|
|
33
|
+
if line.strip() and not line[:1].isspace():
|
|
34
|
+
break
|
|
35
|
+
block.append(line)
|
|
36
|
+
text = "\n".join(line.strip() for line in block)
|
|
37
|
+
text = (text if head[0] == "|" else re.sub(r"[ \t]*\n(?!\n)[ \t]*", " ", text)).strip()
|
|
38
|
+
return text, "\n".join([head, *block])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Agent:
|
|
43
|
+
name: str
|
|
44
|
+
description: str
|
|
45
|
+
description_yaml: str # the description as written after `description:` in front matter
|
|
46
|
+
front: list[str] # front-matter lines without `model:`
|
|
47
|
+
pins_model: bool
|
|
48
|
+
body: str
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def parse(cls, text: str) -> Agent:
|
|
52
|
+
m = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.S)
|
|
53
|
+
if not m:
|
|
54
|
+
raise ValueError("no YAML front matter")
|
|
55
|
+
front, body = m.group(1), m.group(2)
|
|
56
|
+
name = re.search(r"^name:\s*(.+)$", front, re.M)
|
|
57
|
+
desc, desc_yaml = description(front)
|
|
58
|
+
if not name or not desc:
|
|
59
|
+
raise ValueError("front matter needs name and description")
|
|
60
|
+
value = name.group(1).strip()
|
|
61
|
+
if not value or value in (".", "..") or "/" in value or "\\" in value:
|
|
62
|
+
raise ValueError(f"invalid agent name: {value!r}")
|
|
63
|
+
lines = [l for l in front.splitlines() if not l.startswith("model:")]
|
|
64
|
+
return cls(value, desc, desc_yaml, lines,
|
|
65
|
+
re.search(r"^model:", front, re.M) is not None, body.rstrip() + "\n")
|
|
66
|
+
|
|
67
|
+
def markdown(self, model: str) -> str:
|
|
68
|
+
front = self.front + ([f"model: {model}"] if self.pins_model else [])
|
|
69
|
+
return "---\n" + "\n".join(front) + "\n---\n" + self.body
|
|
70
|
+
|
|
71
|
+
def codex_toml(self, model: str, effort: str) -> str:
|
|
72
|
+
return (f"name = {basic_string(self.name)}\ndescription = {basic_string(self.description)}\n"
|
|
73
|
+
f"model = {basic_string(model)}\nmodel_reasoning_effort = {basic_string(effort)}\n"
|
|
74
|
+
f"developer_instructions = {basic_string(self.body.strip())}\n")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def write_if_changed(path: Path, text: str, dry: bool = False) -> bool:
|
|
78
|
+
if dry:
|
|
79
|
+
return not path.exists() or path.read_text(encoding="utf-8-sig") != text
|
|
80
|
+
return writes.update_text(path, lambda _: text)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def gemini_markdown(agent: Agent, models: AgentModels) -> str:
|
|
84
|
+
front = [f"name: {agent.name}", f"description: {agent.description_yaml}"]
|
|
85
|
+
if models.gemini:
|
|
86
|
+
front.append(f"model: {models.gemini}")
|
|
87
|
+
return "---\n" + "\n".join(front) + "\n---\n" + agent.body
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def antigravity_markdown(agent: Agent, models: AgentModels) -> str:
|
|
91
|
+
return (f"---\nname: {agent.name}\ndescription: {agent.description_yaml}\nsubagent: true\nmainAgent: false\n"
|
|
92
|
+
"tools: [read_file, edit_file, write_file, run_command, manage_task, search_web]\n---\n" + agent.body)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
FORMATS = {
|
|
96
|
+
"claude-md": (".md", lambda a, models: a.markdown(models.claude)),
|
|
97
|
+
"codex-toml": (".toml", lambda a, models: a.codex_toml(models.codex, models.codex_effort)),
|
|
98
|
+
"cursor-plugin": (".md", lambda a, models: a.markdown(models.cursor)),
|
|
99
|
+
"gemini-md": (".md", gemini_markdown),
|
|
100
|
+
"antigravity-md": (".md", antigravity_markdown),
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def ownership(content: bytes, package: str) -> tuple[bytes, bytes] | None:
|
|
105
|
+
opening = b"---\n" if content.startswith(b"---\n") else b""
|
|
106
|
+
marker, _, rest = content[len(opening):].partition(b"\n")
|
|
107
|
+
prefix = f"# agent-sync: {package} ".encode()
|
|
108
|
+
digest = marker.removeprefix(prefix)
|
|
109
|
+
if marker.startswith(prefix) and re.fullmatch(rb"[0-9a-f]{64}", digest):
|
|
110
|
+
return digest, opening + rest
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def mirror_agent(path: Path, text: str, package: str, key: str, dry: bool, changes: list[str]) -> None:
|
|
115
|
+
content = text.encode()
|
|
116
|
+
digest = sha256(content).hexdigest()
|
|
117
|
+
marker = f"# agent-sync: {package} {digest}\n"
|
|
118
|
+
marked = ("---\n" + marker + text[4:] if text.startswith("---\n") else marker + text).encode()
|
|
119
|
+
if system.is_link(path) or (path.exists() and not path.is_file()):
|
|
120
|
+
changes.append(f"WARN {path} is not an agent owned by {package}; left alone")
|
|
121
|
+
return
|
|
122
|
+
|
|
123
|
+
approval = None
|
|
124
|
+
|
|
125
|
+
def plan(before: bytes | None) -> bytes | None:
|
|
126
|
+
nonlocal approval
|
|
127
|
+
approval = None
|
|
128
|
+
if before is not None and before != marked:
|
|
129
|
+
record = ownership(before, package)
|
|
130
|
+
if record is None:
|
|
131
|
+
if before == content: # written before agent-sync marked its agents: adopt it as is
|
|
132
|
+
return marked
|
|
133
|
+
approval = f"{key}@unmarked-{sha256(before).hexdigest()[:12]}-{digest[:12]}" # a later edit asks again
|
|
134
|
+
if pending.keeps(key) or not pending.due(
|
|
135
|
+
approval, f"replace the agent {path} with the version from {package} (it has no agent-sync "
|
|
136
|
+
"mark, so it may be your own)"):
|
|
137
|
+
return None
|
|
138
|
+
return marked
|
|
139
|
+
old_digest, old_content = record
|
|
140
|
+
actual = sha256(old_content).hexdigest()
|
|
141
|
+
if old_digest != actual.encode():
|
|
142
|
+
approval = f"{key}@{actual[:12]}-{digest[:12]}"
|
|
143
|
+
if pending.keeps(key) or not pending.due(
|
|
144
|
+
approval, f"replace the edited agent {path} with the version from {package}"):
|
|
145
|
+
return None
|
|
146
|
+
return marked
|
|
147
|
+
|
|
148
|
+
if dry:
|
|
149
|
+
before = writes.read_bytes(path)
|
|
150
|
+
if (after := plan(before)) is not None and after != before:
|
|
151
|
+
changes.append(f"would update {path}")
|
|
152
|
+
elif writes.update(path, plan, follow_symlinks=False):
|
|
153
|
+
if approval is not None:
|
|
154
|
+
pending.removed(approval)
|
|
155
|
+
changes.append(f"updated {path}")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def mirror(package_dir: Path, package: str, home: Path, models: AgentModels, version: str = "0",
|
|
159
|
+
dry: bool = False, notes: dict[str, str] | None = None, *, enabled=DEFAULT_AGENTS) -> list[str]:
|
|
160
|
+
"""Write every agent of `package_dir/agents` for the enabled tools. Returns one line per changed file.
|
|
161
|
+
`notes` adds your own text to the end of an agent's prompt, by agent name.
|
|
162
|
+
With dry=True nothing is written and the lines say "would ..."."""
|
|
163
|
+
changes: list[str] = []
|
|
164
|
+
verb = "would update" if dry else "updated"
|
|
165
|
+
agents = [Agent.parse(f.read_text(encoding="utf-8-sig")) for f in sorted((package_dir / "agents").glob("*.md"))]
|
|
166
|
+
slug = package.split("/")[-1]
|
|
167
|
+
targets = grouped_paths({tool.id: home / tool.agents_dir.format(pkg=slug)
|
|
168
|
+
for tool in TOOLS.values() if tool.id in enabled and tool.agents_dir})
|
|
169
|
+
for a in agents:
|
|
170
|
+
if (notes or {}).get(a.name):
|
|
171
|
+
a.body = a.body.rstrip() + "\n\n" + notes[a.name].strip() + "\n"
|
|
172
|
+
for folder, readers in targets.items():
|
|
173
|
+
fmt = TOOLS[readers[0]].agent_format
|
|
174
|
+
if fmt == "gemini-md" and not re.fullmatch(r"[a-z0-9_-]+", a.name):
|
|
175
|
+
changes.append(f"WARN {a.name!r} is not a valid Gemini CLI agent name; skipped")
|
|
176
|
+
continue
|
|
177
|
+
suffix, render = FORMATS[fmt]
|
|
178
|
+
path = folder / (a.name + suffix)
|
|
179
|
+
key = f"agent:{folder.relative_to(home).as_posix()}:{a.name}"
|
|
180
|
+
mirror_agent(path, render(a, models), package, key, dry, changes)
|
|
181
|
+
for folder, readers in targets.items():
|
|
182
|
+
if not agents or TOOLS[readers[0]].agent_format != "cursor-plugin":
|
|
183
|
+
continue
|
|
184
|
+
plugin = folder.parent
|
|
185
|
+
manifest = {"name": f"{slug}-agents", "displayName": f"{package} agents", "version": version,
|
|
186
|
+
"description": f"The agents of {package}, mirrored by agent-sync (skills come from the skills "
|
|
187
|
+
"folder; this plugin only adds agents).", "agents": "./agents/"}
|
|
188
|
+
if write_if_changed(plugin / ".cursor-plugin/plugin.json", json.dumps(manifest, indent=2) + "\n", dry):
|
|
189
|
+
changes.append(f"{verb} {plugin}/.cursor-plugin/plugin.json")
|
|
190
|
+
names = {f"{a.name}.md" for a in agents}
|
|
191
|
+
for old in folder.glob("*.md"):
|
|
192
|
+
if old.name in names:
|
|
193
|
+
continue
|
|
194
|
+
if system.is_link(old) or not old.is_file() or ownership(old.read_bytes(), package) is None:
|
|
195
|
+
changes.append(f"WARN {old} is not an agent owned by {package}; left alone")
|
|
196
|
+
continue
|
|
197
|
+
key = f"agent:{folder.relative_to(home).as_posix()}:{old.stem}"
|
|
198
|
+
what = f"Cursor agent {old} (no longer in {package})"
|
|
199
|
+
if pending.due(key, what) and not dry:
|
|
200
|
+
backups.save(old)
|
|
201
|
+
old.unlink()
|
|
202
|
+
pending.removed(key)
|
|
203
|
+
changes.append(f"removed {what}")
|
|
204
|
+
return changes
|
agent_sync/audit.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Check the skills and MCP servers your agents load for credentials, unread scripts and reaches outside a skill.
|
|
2
|
+
|
|
3
|
+
RULES names each check. The scan functions read text, folders and server settings and return findings. A finding
|
|
4
|
+
names the kind of credential it found, never its value. The catalog review (scripts/build_catalog.py) applies the
|
|
5
|
+
same rules through `risky`.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import system
|
|
16
|
+
from .catalog import SKIP
|
|
17
|
+
from .mcp import credential_arg, credential_url
|
|
18
|
+
from .privacy import ASSIGNMENT, secret_rows, secret_values
|
|
19
|
+
from .review import shown
|
|
20
|
+
|
|
21
|
+
RULES = {
|
|
22
|
+
"credential": "a credential written out in full, not a reference such as ${TOKEN}",
|
|
23
|
+
"pipe-to-shell": "runs a downloaded script without saving it first (curl ... | sh)",
|
|
24
|
+
"outside-path": "reaches outside the skill: a link out of its folder, or keys and credentials in your home folder",
|
|
25
|
+
"broad-shell": "pre-approves broad shell commands in allowed-tools",
|
|
26
|
+
"runs-on-load": "runs a command when the skill loads (!`...`)",
|
|
27
|
+
"unpinned-latest": "runs a tool at its unpinned newest version (npx ...@latest)",
|
|
28
|
+
"skips-prompt": "skips a tool's own prompt with --yes",
|
|
29
|
+
"runtime-fetch": "fetches more skill instructions at runtime",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Finding:
|
|
35
|
+
rule: str # a key of RULES
|
|
36
|
+
target: str # what an agent loads: "skill pdf (Claude Code, Codex)", "MCP server github (~/.claude.json)"
|
|
37
|
+
path: str # the file, with the home folder as ~
|
|
38
|
+
line: int | None
|
|
39
|
+
detail: str # what matched, in words; never a credential's value
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def compiled(table: dict[str, tuple[tuple[str, str], ...]]) -> dict[str, tuple[tuple[re.Pattern, str], ...]]:
|
|
43
|
+
return {rule: tuple((re.compile(pattern), detail) for pattern, detail in rows) for rule, rows in table.items()}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
GET = r"(?P<get>curl|wget)\b"
|
|
47
|
+
SHELL = r"(?P<shell>sh|bash|zsh)\b"
|
|
48
|
+
WEB = r"(?P<get>iwr|irm|Invoke-WebRequest|Invoke-RestMethod|curl|wget|New-Object\s+(?:System\.)?Net\.WebClient)\b"
|
|
49
|
+
# Not /root: in a skill that is nearly always inside a container, such as a Dockerfile's secret mount at /root/.npmrc
|
|
50
|
+
HOME_DIR = r"(?:~|\$HOME|\$\{HOME\}|%USERPROFILE%|\$env:USERPROFILE|/Users/[^/\s]+|/home/[^/\s]+)[/\\]"
|
|
51
|
+
SECRET_PLACES = (r"\.ssh|\.aws|\.gnupg|\.netrc|\.git-credentials|\.npmrc|\.pypirc|\.docker/config\.json|\.kube/config"
|
|
52
|
+
r"|\.config/(?:gh|gcloud)|\.azure|Library/Keychains")
|
|
53
|
+
RUNNER = r"(?:npx|bunx|pnpm dlx|uvx)(?:\s+(?:-y|--yes|-p|--package)\b)*\s+"
|
|
54
|
+
PINNED = r"[\"']?(?:@[\w.-]+/)?[\w.-]+@\d+\.\d+\.\d+"
|
|
55
|
+
PATTERNS = compiled({ # rule -> (pattern, detail) pairs searched in every text file of a skill; groups fill the detail
|
|
56
|
+
"pipe-to-shell": (
|
|
57
|
+
(rf"\b{GET}[^\n|]*\|\s*(?:sudo\s+(?:-\S+\s+)*)?{SHELL}", "{get} output run by {shell}"),
|
|
58
|
+
(rf"\b{SHELL}\s+(?:-c\s+[\"']?\$\(|<\()\s*{GET}", "{get} output run by {shell}"),
|
|
59
|
+
(rf"(?i)\b{WEB}[^\n|]*\|\s*(?P<shell>iex|Invoke-Expression)\b", "{get} output run by {shell}"),
|
|
60
|
+
(rf"(?i)\b(?P<shell>iex|Invoke-Expression)\s*\(+\s*{WEB}", "{get} output run by {shell}"),
|
|
61
|
+
),
|
|
62
|
+
"outside-path": (
|
|
63
|
+
(rf"{HOME_DIR}(?P<place>{SECRET_PLACES})\b(?![/\\][\w.-]*\.pub\b)", "names ~/{place}"), # not a .pub
|
|
64
|
+
(r"(?<![\w.-])(?P<place>id_(?:rsa|dsa|ecdsa|ed25519))\b(?!\.pub)", "names {place}"),
|
|
65
|
+
(r"(?P<place>/etc/(?:shadow|gshadow|sudoers|master\.passwd))\b", "names {place}"),
|
|
66
|
+
(r"\bsecurity\s+(?P<place>dump-keychain|find-generic-password|find-internet-password)\b",
|
|
67
|
+
"reads the keychain (security {place})"),
|
|
68
|
+
),
|
|
69
|
+
"unpinned-latest": ( # scaffolders that start a new project (create-*, `new`, `init`) are left out
|
|
70
|
+
(rf"\b{RUNNER}(?!create-)(?P<package>[\w@/.-]+@latest)\b(?!\s+(?:new|init)\b)", "{package}"),
|
|
71
|
+
(r'"(?:npx|bunx|uvx)"\s*,\s*"args"\s*:\s*\[[^\]]*?"(?P<package>[^"\]]*@latest)"', "{package}"), # MCP JSON
|
|
72
|
+
),
|
|
73
|
+
"skips-prompt": ( # npx --yes before an exact version only accepts downloading that version
|
|
74
|
+
(rf"(?m)^.*\b(?P<tool>npx|bunx|pnpm|npm|yarn|uvx|skills|remotion)\b.*\s--yes\b(?!\s+{PINNED})",
|
|
75
|
+
"{tool} ... --yes"),
|
|
76
|
+
),
|
|
77
|
+
"runtime-fetch": (
|
|
78
|
+
(r"(?i)\.well-known/skills|fetch[^\n]{0,40}skill[^\n]{0,40}https?://", "fetches skill instructions"),
|
|
79
|
+
),
|
|
80
|
+
})
|
|
81
|
+
SKILL_MD = compiled({ # only in a SKILL.md: `!` and a one-line backquoted command, at a line start or after a space
|
|
82
|
+
"runs-on-load": ((r"(?m)(?:^|(?<=\s))!`[^`\n]+`", "a !`command` line"),),
|
|
83
|
+
})
|
|
84
|
+
ALLOWED_TOOLS = re.compile(r"(?m)^allowed-tools:(.*(?:\n[ \t-].*)*)")
|
|
85
|
+
BROAD_SHELL = re.compile(r"Bash\((?:\*|npx|npm|curl|sh|bash|python|node|uvx|pip)[:)*][^)\s]*\)?")
|
|
86
|
+
ENV_FORM = re.compile(r"\{env:([A-Za-z_]\w*)\}") # opencode's reference, rewritten as privacy.py skips it: ${VAR}
|
|
87
|
+
# A `token = ...` assignment in a skill counts only when the value looks like a token: 16+ characters with a letter
|
|
88
|
+
# and a digit, no code punctuation, not an ENV_NAME and no example word. Code such as `token = req.body[...]` or
|
|
89
|
+
# `secret: env.SECRET_KEY`, and examples such as `password: 'secretPassword123'`, are not credentials.
|
|
90
|
+
TOKEN = re.compile(r"(?![A-Z][A-Z0-9_]*$)(?=\D*\d)(?=[^A-Za-z]*[A-Za-z])"
|
|
91
|
+
r"(?!(?i:.*(?:password|secret|example|sample|test|your|dummy|fake|placeholder|changeme|demo)))"
|
|
92
|
+
r"[^\s()\[\]{}<>$.,;:\"'`]{16,}")
|
|
93
|
+
FRONT_MATTER = re.compile(r"^---\r?\n(.*?)\r?\n---", re.S)
|
|
94
|
+
MAX_BYTES = 1_000_000
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def env_references(text: str) -> str:
|
|
98
|
+
return ENV_FORM.sub(r"${\1}", text)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def scan_text(text: str, head: str | None = None) -> list[tuple[str, int, str]]:
|
|
102
|
+
"""(rule, line, detail) for each finding in one file, one per rule and line. `head` is a SKILL.md's front matter,
|
|
103
|
+
and None for any other file: allowed-tools and !`command` lines only take effect in a SKILL.md."""
|
|
104
|
+
lines = env_references(text).split("\n")
|
|
105
|
+
rows = secret_rows(lines)
|
|
106
|
+
found = []
|
|
107
|
+
for index, kinds in rows.items():
|
|
108
|
+
tokens = {f"{key.lower()} assignment" for key, value in ASSIGNMENT.findall(lines[index])
|
|
109
|
+
if TOKEN.fullmatch(value.strip("`.,;)]}"))}
|
|
110
|
+
found += [("credential", index + 1, kind) for kind in kinds
|
|
111
|
+
if (kind in tokens or not kind.endswith(" assignment"))
|
|
112
|
+
and (kind != "private key" or kind not in rows.get(index - 1, ()))] # a key block once, at its start
|
|
113
|
+
for rule, patterns in {**PATTERNS, **(SKILL_MD if head is not None else {})}.items():
|
|
114
|
+
found += [(rule, text.count("\n", 0, match.start()) + 1, detail.format_map(match.groupdict()))
|
|
115
|
+
for pattern, detail in patterns for match in pattern.finditer(text)]
|
|
116
|
+
if tools := ALLOWED_TOOLS.search(head or ""):
|
|
117
|
+
found += [("broad-shell", head.count("\n", 0, tools.start(1) + match.start()) + 2, match[0])
|
|
118
|
+
for match in BROAD_SHELL.finditer(tools[1])]
|
|
119
|
+
first = {(rule, line): detail for rule, line, detail in reversed(found)}
|
|
120
|
+
order = list(RULES)
|
|
121
|
+
return sorted(((rule, line, detail) for (rule, line), detail in first.items()),
|
|
122
|
+
key=lambda row: (row[1], order.index(row[0])))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def risky(fields: dict[str, str]) -> list[str]:
|
|
126
|
+
"""The catalog review of a SKILL.md (`_text`, with its front matter in `_head`): the explanation of each rule
|
|
127
|
+
that fires, in RULES order."""
|
|
128
|
+
fired = {rule for rule, _, _ in scan_text(fields.get("_text", ""), fields.get("_head", ""))}
|
|
129
|
+
return [explanation for rule, explanation in RULES.items() if rule in fired]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def files(root: Path) -> Iterator[tuple[Path, Path | None]]:
|
|
133
|
+
"""Each file in `root`, and each link with the place it leads to. Links are never followed, and folders named
|
|
134
|
+
in the catalog's SKIP (node_modules, .git and the like) are left out."""
|
|
135
|
+
todo = [root]
|
|
136
|
+
while todo:
|
|
137
|
+
try:
|
|
138
|
+
entries = sorted(os.scandir(todo.pop()), key=lambda entry: entry.name)
|
|
139
|
+
except OSError:
|
|
140
|
+
continue
|
|
141
|
+
for entry in entries:
|
|
142
|
+
if system.is_link(entry):
|
|
143
|
+
yield Path(entry.path), Path(os.path.realpath(entry.path))
|
|
144
|
+
elif entry.is_dir():
|
|
145
|
+
if entry.name not in SKIP:
|
|
146
|
+
todo.append(Path(entry.path))
|
|
147
|
+
elif entry.is_file():
|
|
148
|
+
yield Path(entry.path), None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def scan_skill(folder: Path, target: str, home: Path, problems: list[str]) -> list[Finding]:
|
|
152
|
+
"""Every finding in one skill's text files (binary files and those over MAX_BYTES are skipped). The folder itself
|
|
153
|
+
may be a link, as the skills CLI links each agent's copy to ~/.agents/skills: only a link inside it that leads
|
|
154
|
+
out of it is a finding."""
|
|
155
|
+
root = Path(os.path.realpath(folder))
|
|
156
|
+
found = []
|
|
157
|
+
for path, link in files(root):
|
|
158
|
+
where = shown(home, path)
|
|
159
|
+
if link is not None:
|
|
160
|
+
if not link.is_relative_to(root):
|
|
161
|
+
found.append(Finding("outside-path", target, where, None, f"links to {shown(home, link)}"))
|
|
162
|
+
continue
|
|
163
|
+
try:
|
|
164
|
+
if path.stat().st_size > MAX_BYTES:
|
|
165
|
+
continue
|
|
166
|
+
data = path.read_bytes()
|
|
167
|
+
except OSError as error:
|
|
168
|
+
problems.append(f"could not read {where}: {error.strerror or error}")
|
|
169
|
+
continue
|
|
170
|
+
if b"\0" in data[:8192]:
|
|
171
|
+
continue
|
|
172
|
+
text = data.decode("utf-8-sig", errors="replace")
|
|
173
|
+
head = None
|
|
174
|
+
if path == root / "SKILL.md":
|
|
175
|
+
head = match[1] if (match := FRONT_MATTER.match(text)) else ""
|
|
176
|
+
found += [Finding(rule, target, where, line, detail) for rule, line, detail in scan_text(text, head)]
|
|
177
|
+
return found
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def scan_server(server: dict, target: str, path: str) -> list[Finding]:
|
|
181
|
+
"""Credentials written into one MCP server's settings, and a command line that runs a downloaded script."""
|
|
182
|
+
details = []
|
|
183
|
+
env = server.get("env")
|
|
184
|
+
for var, value in env.items() if isinstance(env, dict) else ():
|
|
185
|
+
value = env_references(str(value))
|
|
186
|
+
details += [f"{kind} in env {var}" for kind in secret_values(value) or secret_values(f"{var}={value}")]
|
|
187
|
+
for key in ("headers", "http_headers"):
|
|
188
|
+
headers = server.get(key)
|
|
189
|
+
for name, value in headers.items() if isinstance(headers, dict) else ():
|
|
190
|
+
value = env_references(str(value))
|
|
191
|
+
kinds = secret_values(value) or (["a credential"] if credential_arg(f"{name}: {value}") else [])
|
|
192
|
+
details += [f"{kind} in header {name}" for kind in kinds]
|
|
193
|
+
args = server.get("args")
|
|
194
|
+
args = [env_references(arg) for arg in args if isinstance(arg, str)] if isinstance(args, list) else []
|
|
195
|
+
for flag, arg in zip(["", *args], args, strict=False):
|
|
196
|
+
kinds = secret_values(arg) or (["a credential"] if credential_arg(arg) else [])
|
|
197
|
+
if not kinds and flag.startswith("--") and "=" not in flag and not arg.startswith("-"): # --token VALUE
|
|
198
|
+
kinds = secret_values(f"{flag}={arg}")
|
|
199
|
+
details += [f"{kind} in args" for kind in kinds]
|
|
200
|
+
for key in ("url", "httpUrl", "serverUrl"):
|
|
201
|
+
if isinstance(url := server.get(key), str) and credential_url(env_references(url)):
|
|
202
|
+
details.append(f"a credential in {key}")
|
|
203
|
+
found = [Finding("credential", target, path, None, detail) for detail in dict.fromkeys(details)]
|
|
204
|
+
command = " ".join([str(server.get("command") or ""), *args])
|
|
205
|
+
found += [Finding("pipe-to-shell", target, path, None, detail.format_map(match.groupdict()))
|
|
206
|
+
for pattern, detail in PATTERNS["pipe-to-shell"] for match in pattern.finditer(command)]
|
|
207
|
+
return list(dict.fromkeys(found))
|