opencodekit 0.20.8 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/template/.opencode/AGENTS.md +25 -1
  3. package/dist/template/.opencode/memory.db +0 -0
  4. package/dist/template/.opencode/memory.db-shm +0 -0
  5. package/dist/template/.opencode/memory.db-wal +0 -0
  6. package/dist/template/.opencode/opencode.json +83 -609
  7. package/dist/template/.opencode/opencodex-fast.jsonc +1 -1
  8. package/dist/template/.opencode/package.json +2 -2
  9. package/dist/template/.opencode/plugin/copilot-auth.ts +86 -12
  10. package/dist/template/.opencode/plugin/prompt-leverage.ts +191 -0
  11. package/dist/template/.opencode/plugin/sdk/copilot/copilot-provider.ts +14 -2
  12. package/dist/template/.opencode/plugin/sdk/copilot/index.ts +2 -2
  13. package/dist/template/.opencode/plugin/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  14. package/dist/template/.opencode/plugin/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  15. package/dist/template/.opencode/plugin/sdk/copilot/responses/openai-config.ts +18 -0
  16. package/dist/template/.opencode/plugin/sdk/copilot/responses/openai-error.ts +22 -0
  17. package/dist/template/.opencode/plugin/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  18. package/dist/template/.opencode/plugin/sdk/copilot/responses/openai-responses-language-model.ts +1770 -0
  19. package/dist/template/.opencode/plugin/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  20. package/dist/template/.opencode/plugin/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  21. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  22. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/file-search.ts +127 -0
  23. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/image-generation.ts +114 -0
  24. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/local-shell.ts +64 -0
  25. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  26. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/web-search.ts +102 -0
  27. package/dist/template/.opencode/skill/gh-address-comments/SKILL.md +29 -0
  28. package/dist/template/.opencode/skill/gh-address-comments/scripts/fetch_comments.py +237 -0
  29. package/dist/template/.opencode/skill/gh-fix-ci/SKILL.md +38 -0
  30. package/dist/template/.opencode/skill/gh-fix-ci/scripts/inspect_pr_checks.py +509 -0
  31. package/dist/template/.opencode/skill/prompt-leverage/SKILL.md +90 -0
  32. package/dist/template/.opencode/skill/prompt-leverage/references/framework.md +91 -0
  33. package/dist/template/.opencode/skill/prompt-leverage/scripts/augment_prompt.py +157 -0
  34. package/dist/template/.opencode/skill/screenshot/SKILL.md +48 -0
  35. package/dist/template/.opencode/skill/screenshot/scripts/ensure_macos_permissions.sh +54 -0
  36. package/dist/template/.opencode/skill/screenshot/scripts/macos_display_info.swift +22 -0
  37. package/dist/template/.opencode/skill/screenshot/scripts/macos_permissions.swift +40 -0
  38. package/dist/template/.opencode/skill/screenshot/scripts/macos_window_info.swift +126 -0
  39. package/dist/template/.opencode/skill/screenshot/scripts/take_screenshot.ps1 +163 -0
  40. package/dist/template/.opencode/skill/screenshot/scripts/take_screenshot.py +585 -0
  41. package/dist/template/.opencode/skill/security-threat-model/SKILL.md +36 -0
  42. package/dist/template/.opencode/skill/security-threat-model/references/prompt-template.md +255 -0
  43. package/dist/template/.opencode/skill/security-threat-model/references/security-controls-and-assets.md +32 -0
  44. package/dist/template/.opencode/skill/skill-installer/SKILL.md +58 -0
  45. package/dist/template/.opencode/skill/skill-installer/scripts/github_utils.py +21 -0
  46. package/dist/template/.opencode/skill/skill-installer/scripts/install-skill-from-github.py +313 -0
  47. package/dist/template/.opencode/skill/skill-installer/scripts/list-skills.py +106 -0
  48. package/package.json +1 -1
@@ -0,0 +1,255 @@
1
+ # Threat Modeling Prompt Template for LLMs
2
+
3
+ This reference provides a disciplined, repo-grounded prompt that produces AppSec-usable threat models. Use it when you need a reliable output contract and a consistent process to assemble the threat model output
4
+
5
+ ## System prompt
6
+
7
+ Use this as a stable system prompt:
8
+
9
+ ````text
10
+ You are a senior application security engineer producing a threat model that will be read by other AppSec engineers.
11
+
12
+ Primary objective:
13
+ - Generate a threat model that is specific to THIS repository and its real-world usage.
14
+ - Prefer concrete, evidence-backed findings over generic vulnerability checklists.
15
+
16
+ Evidence and grounding rules:
17
+ - Do not invent components, data stores, endpoints, flows, or controls.
18
+ - Every architectural claim must be backed by at least one "Evidence anchor" referencing a repo path
19
+ (and a symbol name, config key, or a short quoted snippet if available).
20
+ - If information is missing, state assumptions explicitly and list the open questions needed to validate them.
21
+
22
+ Security hygiene:
23
+ - Never output secrets. If you encounter tokens/keys/passwords, redact them and only describe their presence and location.
24
+
25
+ Threat modeling approach:
26
+ - Model the system using data flows and trust boundaries.
27
+ - Enumerate threats and produce attack goals and abuse paths
28
+ - Prioritize threats using explicit likelihood and impact reasoning (qualitative is acceptable: low/medium/high).
29
+
30
+ Scope discipline:
31
+ - Clearly separate: production/runtime behavior vs CI/build/dev tooling vs tests/examples.
32
+ - Clearly separate attacker-controlled inputs vs operator-controlled inputs vs developer-controlled inputs.
33
+ - If a vulnerability class requires attacker control that likely does not exist for this repo's real usage, say so and downgrade severity.
34
+
35
+ Communication quality:
36
+ - Write for AppSec engineers: concise but specific.
37
+ - Use precise terminology. Include mitigations and residual risks.
38
+ - Avoid restating large blocks of README/spec; summarize and point to evidence.
39
+
40
+ Diagram requirements:
41
+ - Produce a single compact Mermaid flowchart showing primary components and trust boundaries.
42
+ - Mermaid must render cleanly. Use a conservative subset:
43
+ - Use `flowchart TD` or `flowchart LR` and only `-->` arrows.
44
+ - Use simple node IDs (letters/numbers/underscores only) and quoted labels (e.g., `A["Label"]`); avoid `A(Label)` shape syntax.
45
+ - Do not use Mermaid `title` lines or `style` directives.
46
+ - Keep edge labels to plain words/spaces only via `-->|label|`; avoid `{}`, `[]`, `()`, or quotes in edge labels (if needed, drop the label).
47
+ - Keep node labels short and readable: do not include file paths, URLs, or socket paths (put those details in prose outside the diagram).
48
+ - Wrap the diagram in a Markdown fenced block:
49
+ ```mermaid
50
+ <mermaid syntax here>
51
+ ```
52
+ ````
53
+
54
+ ## Repository summary prompt
55
+
56
+ ```
57
+ We have a codebase located at {repo_directory/path}, currently on branch {branch_name}.
58
+
59
+ Please produce a security-oriented summary of the repository (or the specified sub-path) with the goal of helping a follow-on security engineer quickly understand the system well enough to build an initial threat model and investigate potential security hypotheses.
60
+
61
+ Objectives
62
+ 1. Project overview
63
+ • Identify the primary programming languages, frameworks, and build system.
64
+ • Summarize the project’s core purpose and high-level architecture.
65
+ • Describe major components, services, or modules and how they interact.
66
+ 2. Security posture and entry points
67
+ • Identify likely user entry points and trust boundaries.
68
+ • Describe existing security layers (e.g., authentication, authorization, validation, sandboxing, isolation, privilege boundaries).
69
+ • Call out security-critical components and assumptions that must hold for the system to remain secure.
70
+
71
+ Guidance for Security Analysis
72
+
73
+ Structure the summary so an application security engineer can quickly answer questions such as:
74
+ • Where does user input originate?
75
+ • How is untrusted data parsed, validated, and handled?
76
+ • What security assumptions should not be violated?
77
+ • Where are the most likely choke points for security bugs?
78
+
79
+ Adapt the analysis to the project type. For example:
80
+ • Web applications: where requests enter, how user data is parsed, routed, authenticated, and stored.
81
+ • Command-line tools: supported inputs (arguments, files, environment variables, stdin) and how they are processed.
82
+ • Network daemons: exposed ports, supported protocols, message formats, and request handling paths.
83
+ • Operating system or low-level components: common vulnerability classes (e.g., memory corruption, logic flaws) that could lead to LPE or RCE.
84
+
85
+ Be thorough but pragmatic: the goal is to help a security engineer quickly determine whether a discovered bug is security-relevant and where deeper investigation should focus.
86
+
87
+ Tooling Notes
88
+
89
+ If Ripgrep (rg) is available, use it to explore the codebase. When using grep or rg, always include the -I flag to avoid searching through binary files.
90
+ ```
91
+
92
+
93
+
94
+ ## User prompt template
95
+
96
+ Use this as the task prompt, filling in what you know and marking the rest as assumptions:
97
+
98
+ ```text
99
+ # Inputs
100
+ Context (fill as available; otherwise infer and mark assumptions):
101
+ - intended_usage: {intended_usage}
102
+ - deployment_model: {deployment_model}
103
+ - data_sensitivity: {data_sensitivity}
104
+ - internet_exposure: {internet_exposure}
105
+ - authn_authz_expectations: {authn_authz_expectations}
106
+ - out_of_scope: {out_of_scope}
107
+
108
+ Provided summaries (may be incomplete):
109
+ - repository_summary: {repository_summary}
110
+
111
+
112
+ In-scope code locations (if known):
113
+ - in_scope_paths: {in_scope_paths}
114
+
115
+ # Task
116
+ Construct a repo-centric threat model that helps AppSec engineers understand the most important security risks and where to focus manual review.
117
+
118
+ You MUST follow this process and reflect outputs in the final document:
119
+
120
+ ## Process
121
+ 1) Repo discovery (evidence collection)
122
+ a. Identify the repo shape:
123
+ - languages and frameworks
124
+ - how it runs (server/cli/library), entrypoints, build artifacts
125
+ b. Identify security-relevant surfaces and controls by searching for evidences, such as:
126
+ - network listeners/routes/endpoints; RPC handlers; message consumers
127
+ - authentication, session/token handling, authorization checks, RBAC/ACL logic
128
+ - parsing/serialization/deserialization (JSON/YAML/XML/protobuf), template rendering, eval/dynamic code
129
+ - file upload/read paths, archive extraction, image/document parsing
130
+ - database/queue/cache clients and query construction
131
+ - secrets/config loading, environment variables, key management
132
+ - SSRF-capable HTTP clients, webhooks, URL fetchers
133
+ - sandboxing/isolation, privilege boundaries, subprocess execution
134
+ - logging/auditing and error handling paths
135
+ - CI/build/release: pipelines, dependency management, artifact publishing
136
+
137
+ 2) System model
138
+ a. Summarize the primary components (runtime plus critical build/CI components when relevant).
139
+ b. Enumerate data flows and trust boundaries.
140
+ - For each trust boundary, specify:
141
+ * source to destination
142
+ * data types crossing (e.g., credentials, PII, files, tokens, prompts)
143
+ * channel/protocol (HTTP/gRPC/IPC/file/db)
144
+ * security guarantees and validation (auth, mTLS, origin checks, schema validation, rate limits)
145
+ c. Provide a compact Mermaid diagram showing components and trust boundaries.
146
+
147
+ 3) Assets and security objectives
148
+ - List assets (data, credentials, integrity-critical state, availability-critical components, build artifacts).
149
+ - For each asset, state why it matters (confidentiality/integrity/availability, compliance, user harm).
150
+
151
+ 4) Attacker model
152
+ - Capabilities: realistic remote attacker assumptions based on intended usage and exposure.
153
+ - Non-capabilities: things attacker cannot plausibly do (unless explicitly in scope), to avoid inflated severity.
154
+
155
+ 5) Threat enumeration (concrete, system-specific)
156
+ - Generate threats as attacker stories tied to:
157
+ * entry points
158
+ * trust boundaries
159
+ * privileged components
160
+ - Prefer abuse paths (multi-step sequences) over single-line generic threats.
161
+
162
+ 6) Risk prioritization
163
+ - For each threat:
164
+ * Likelihood: low/medium/high with a 1 to 2 sentence justification
165
+ * Impact: low/medium/high with a 1 to 2 sentence justification
166
+ * Overall priority: critical/high/medium/low (based on likelihood x impact, adjusted for existing controls)
167
+ - Explicitly state which assumptions most affect risk.
168
+
169
+ 7) Validate assumptions and service context with the user (required before final report)
170
+ - Summarize key assumptions that materially affect scope or risk ranking.
171
+ - Ask 1 to 3 targeted questions to resolve missing service meta-context (service owner/environment, scale/users, deployment model, authn/authz, internet exposure, data sensitivity, multi-tenancy).
172
+ - Pause and wait for user feedback before producing the final report.
173
+ - If the user cannot answer, proceed with explicit assumptions and mark any conditional conclusions.
174
+
175
+ 8) Mitigations and recommendations
176
+ - For each high/critical threat:
177
+ * Existing mitigations (with evidence anchors)
178
+ * Gaps/weaknesses
179
+ * Recommended mitigations (code/config/process)
180
+ * Detection/monitoring ideas (logging, metrics, alerts)
181
+
182
+ 9) Focus paths for manual security review
183
+ - Output 2 to 30 repo-relative paths (files or directories) that merit deeper review.
184
+ - For each path, give a one-sentence reason tied to the threat model.
185
+
186
+ 10) Quality check
187
+ - Provide a short checklist confirming you covered:
188
+ * all entry points you discovered
189
+ * each trust boundary at least once in threats
190
+ * runtime vs CI/dev separation
191
+ * user clarifications (or explicit non-responses)
192
+ * assumptions and open questions
193
+
194
+ ## Required output format (exact)
195
+ Before producing the final Markdown report, first provide an assumption-validation check-in:
196
+ - List the key assumptions in 3 to 6 bullets.
197
+ - Ask 1 to 3 targeted context questions.
198
+ - Wait for the user response, then produce the final report below using the clarified context.
199
+
200
+ Produce valid Markdown with these sections in this order:
201
+
202
+ ## Executive summary
203
+ - 1 short paragraph on the top risk themes and highest-risk areas.
204
+
205
+ ## Scope and assumptions
206
+ - In-scope paths, out-of-scope items, and explicit assumptions.
207
+ - A short list of open questions that would materially change the risk ranking.
208
+
209
+
210
+ ## System model
211
+ ### Primary components
212
+ ### Data flows and trust boundaries
213
+ Represent the system as a sequence of arrow-style bullets (e.g., Internet → API Server, User Input -> Application Logic, etc). For each boundary, document:
214
+ • the primary data types crossing the boundary,
215
+ • the communication channel or protocol,
216
+ • the security guarantees (e.g., authentication, origin checks, encryption, rate limiting), and
217
+ • any input validation, normalization, or schema enforcement performed.
218
+
219
+ #### Diagram
220
+ - Include a single, compact Mermaid diagram (`flowchart TD` or `flowchart LR`) showing primary components and trust boundaries (e.g., separate trust zones via subgraphs). Keep it compact, use only `-->`, avoid `title`/`style`, keep node labels short (no paths/URLs), and keep edge labels to plain words only (avoid `{}`, `[]`, `()`, or quotes).
221
+
222
+
223
+ ## Assets and security objectives
224
+ - A table: Asset | Why it matters | Security objective (C/I/A)
225
+
226
+ ## Attacker model
227
+ ### Capabilities
228
+ ### Non-capabilities
229
+
230
+ ## Entry points and attack surfaces
231
+ - A table: Surface | How reached | Trust boundary | Notes | Evidence (repo path / symbol)
232
+
233
+ ## Top abuse paths
234
+ - 5 to 10 short abuse paths, each as a numbered sequence of steps (attacker goal -> steps -> impact).
235
+
236
+ ## Threat model table
237
+ - A Markdown table with columns:
238
+ Threat ID | Threat source | Prerequisites | Threat action | Impact | Impacted assets | Existing controls (evidence) | Gaps | Recommended mitigations | Detection ideas | Likelihood | Impact severity | Priority
239
+
240
+ Rules:
241
+ - Threat IDs must be stable and formatted: TM-001, TM-002, ...
242
+ - Priority must be one of: critical, high, medium, low.
243
+ - Keep prerequisites to 1 to 2 sentences. Keep recommended mitigations concrete.
244
+
245
+ ## Criticality calibration
246
+ - Define what counts as critical/high/medium/low for THIS repo and context.
247
+ - Include 2 to 3 examples per level (tailored to the repo's assets and exposure).
248
+
249
+ ## Focus paths for security review
250
+ - A table: Path | Why it matters | Related Threat IDs
251
+
252
+ ## Notes on use
253
+
254
+ - Fill in known context, but allow the model to infer and mark assumptions.
255
+ - Include 1–2 repo-path anchors per major claim; do not dump every match.
@@ -0,0 +1,32 @@
1
+ # Security Controls and Asset Categories
2
+
3
+ Use this as a lightweight checklist to keep outputs consistent across teams. Prefer concrete, system-specific items over generic text.
4
+
5
+ ## Asset categories (pick only what applies)
6
+ - User data (PII, content, uploads)
7
+ - Authentication artifacts (passwords, tokens, sessions, cookies)
8
+ - Authorization state (roles, policies, ACLs)
9
+ - Secrets and keys (API keys, signing keys, encryption keys)
10
+ - Configuration and feature flags
11
+ - Models and weights (if ML systems)
12
+ - Source code and build artifacts
13
+ - Audit logs and telemetry
14
+ - Availability-critical resources (queues, caches, rate limits, compute budgets)
15
+ - Tenant isolation boundaries and metadata
16
+
17
+ ## Security control categories
18
+ - Identity and access: authN, authZ, session handling, mTLS, key rotation
19
+ - Input protection: schema validation, parsing hardening, upload scanning, sandboxing
20
+ - Network safeguards: TLS, network policies, WAF, rate limiting, DoS controls
21
+ - Data protection: encryption at rest/in transit, tokenization, redaction
22
+ - Isolation: process sandboxing, container boundaries, tenant isolation, seccomp
23
+ - Observability: audit logs, alerting, anomaly detection, tamper resistance
24
+ - Supply chain: dependency pinning, SBOMs, provenance, signing
25
+ - Change control: CI checks, deployment approvals, config guardrails
26
+
27
+ ## Mitigation phrasing patterns
28
+ - "Enforce schema at <boundary> for <payload> before <component>."
29
+ - "Require authZ check for <action> on <resource> in <service>."
30
+ - "Isolate <parser/component> in a sandbox with <resource limits>."
31
+ - "Rate limit <endpoint> by <key> and apply burst caps."
32
+ - "Encrypt <data> at rest using <key management> and rotate <keys>."
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: skill-installer
3
+ description: Use when the user asks to list, import, or install skills from OpenAI or another GitHub repository into OpenCode skill directories.
4
+ version: 1.0.0
5
+ tags: [workflow, automation, integration]
6
+ dependencies: []
7
+ ---
8
+
9
+ # skill-installer
10
+
11
+ Import skills from GitHub into OpenCode-compatible skill directories.
12
+
13
+ ## When to Use
14
+
15
+ - User asks to “install skill X” from `openai/skills` or another repo
16
+ - User wants to list available curated skills before choosing
17
+ - User wants to copy one or more external skills into local OpenCode setup
18
+
19
+ ## When NOT to Use
20
+
21
+ - Skill already exists locally and only needs editing
22
+ - User asked for manual adaptation (copy + rewrite), not automated install
23
+
24
+ ## Default Destination
25
+
26
+ - Global OpenCode skill directory: `~/.config/opencode/skill`
27
+ - Override destination with `--dest <path>`
28
+
29
+ ## Scripts
30
+
31
+ - `scripts/list-skills.py`
32
+ - Lists skills from a GitHub repo path and marks already-installed skills.
33
+ - `scripts/install-skill-from-github.py`
34
+ - Installs one or many skill folders from GitHub into OpenCode skill directory.
35
+
36
+ ## Quick Start
37
+
38
+ ```bash
39
+ # List curated skills from openai/skills
40
+ python3 .opencode/skill/skill-installer/scripts/list-skills.py
41
+
42
+ # Install one curated skill into ~/.config/opencode/skill
43
+ python3 .opencode/skill/skill-installer/scripts/install-skill-from-github.py \
44
+ --repo openai/skills \
45
+ --path skills/.curated/screenshot
46
+
47
+ # Install into project-local skills directory
48
+ python3 .opencode/skill/skill-installer/scripts/install-skill-from-github.py \
49
+ --repo openai/skills \
50
+ --path skills/.curated/gh-fix-ci \
51
+ --dest .opencode/skill
52
+ ```
53
+
54
+ ## Notes
55
+
56
+ - Supports direct GitHub URLs (`--url`) and `owner/repo` (`--repo`) mode.
57
+ - Uses authenticated API requests if `GITHUB_TOKEN` or `GH_TOKEN` is set.
58
+ - Fails fast if destination skill directory already exists.
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env python3
2
+ """Shared GitHub helpers for skill install scripts."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import urllib.request
8
+
9
+
10
+ def github_request(url: str, user_agent: str) -> bytes:
11
+ headers = {"User-Agent": user_agent}
12
+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
13
+ if token:
14
+ headers["Authorization"] = f"token {token}"
15
+ req = urllib.request.Request(url, headers=headers)
16
+ with urllib.request.urlopen(req) as resp:
17
+ return resp.read()
18
+
19
+
20
+ def github_api_contents_url(repo: str, path: str, ref: str) -> str:
21
+ return f"https://api.github.com/repos/{repo}/contents/{path}?ref={ref}"
@@ -0,0 +1,313 @@
1
+ #!/usr/bin/env python3
2
+ """Install a skill from a GitHub repo path into OpenCode skill directory."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from dataclasses import dataclass
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import urllib.error
14
+ import urllib.parse
15
+ import zipfile
16
+
17
+ from github_utils import github_request
18
+
19
+ DEFAULT_REF = "main"
20
+
21
+
22
+ @dataclass
23
+ class Args:
24
+ url: str | None = None
25
+ repo: str | None = None
26
+ path: list[str] | None = None
27
+ ref: str = DEFAULT_REF
28
+ dest: str | None = None
29
+ name: str | None = None
30
+ method: str = "auto"
31
+
32
+
33
+ @dataclass
34
+ class Source:
35
+ owner: str
36
+ repo: str
37
+ ref: str
38
+ paths: list[str]
39
+ repo_url: str | None = None
40
+
41
+
42
+ class InstallError(Exception):
43
+ pass
44
+
45
+
46
+ def _opencode_home() -> str:
47
+ return os.environ.get("OPENCODE_HOME", os.path.expanduser("~/.config/opencode"))
48
+
49
+
50
+ def _tmp_root() -> str:
51
+ base = os.path.join(tempfile.gettempdir(), "opencode")
52
+ os.makedirs(base, exist_ok=True)
53
+ return base
54
+
55
+
56
+ def _request(url: str) -> bytes:
57
+ return github_request(url, "opencode-skill-install")
58
+
59
+
60
+ def _parse_github_url(url: str, default_ref: str) -> tuple[str, str, str, str | None]:
61
+ parsed = urllib.parse.urlparse(url)
62
+ if parsed.netloc != "github.com":
63
+ raise InstallError("Only GitHub URLs are supported for download mode.")
64
+ parts = [p for p in parsed.path.split("/") if p]
65
+ if len(parts) < 2:
66
+ raise InstallError("Invalid GitHub URL.")
67
+ owner, repo = parts[0], parts[1]
68
+ ref = default_ref
69
+ subpath = ""
70
+ if len(parts) > 2:
71
+ if parts[2] in ("tree", "blob"):
72
+ if len(parts) < 4:
73
+ raise InstallError("GitHub URL missing ref or path.")
74
+ ref = parts[3]
75
+ subpath = "/".join(parts[4:])
76
+ else:
77
+ subpath = "/".join(parts[2:])
78
+ return owner, repo, ref, subpath or None
79
+
80
+
81
+ def _download_repo_zip(owner: str, repo: str, ref: str, dest_dir: str) -> str:
82
+ zip_url = f"https://codeload.github.com/{owner}/{repo}/zip/{ref}"
83
+ zip_path = os.path.join(dest_dir, "repo.zip")
84
+ try:
85
+ payload = _request(zip_url)
86
+ except urllib.error.HTTPError as exc:
87
+ raise InstallError(f"Download failed: HTTP {exc.code}") from exc
88
+ with open(zip_path, "wb") as file_handle:
89
+ file_handle.write(payload)
90
+ with zipfile.ZipFile(zip_path, "r") as zip_file:
91
+ _safe_extract_zip(zip_file, dest_dir)
92
+ top_levels = {name.split("/")[0] for name in zip_file.namelist() if name}
93
+ if not top_levels:
94
+ raise InstallError("Downloaded archive was empty.")
95
+ if len(top_levels) != 1:
96
+ raise InstallError("Unexpected archive layout.")
97
+ return os.path.join(dest_dir, next(iter(top_levels)))
98
+
99
+
100
+ def _run_git(args: list[str]) -> None:
101
+ result = subprocess.run(
102
+ args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
103
+ )
104
+ if result.returncode != 0:
105
+ raise InstallError(result.stderr.strip() or "Git command failed.")
106
+
107
+
108
+ def _safe_extract_zip(zip_file: zipfile.ZipFile, dest_dir: str) -> None:
109
+ dest_root = os.path.realpath(dest_dir)
110
+ for info in zip_file.infolist():
111
+ extracted_path = os.path.realpath(os.path.join(dest_dir, info.filename))
112
+ if extracted_path == dest_root or extracted_path.startswith(dest_root + os.sep):
113
+ continue
114
+ raise InstallError("Archive contains files outside the destination.")
115
+ zip_file.extractall(dest_dir)
116
+
117
+
118
+ def _validate_relative_path(path: str) -> None:
119
+ if os.path.isabs(path) or os.path.normpath(path).startswith(".."):
120
+ raise InstallError("Skill path must be a relative path inside the repo.")
121
+
122
+
123
+ def _validate_skill_name(name: str) -> None:
124
+ altsep = os.path.altsep
125
+ if not name or os.path.sep in name or (altsep and altsep in name):
126
+ raise InstallError("Skill name must be a single path segment.")
127
+ if name in (".", ".."):
128
+ raise InstallError("Invalid skill name.")
129
+
130
+
131
+ def _git_sparse_checkout(
132
+ repo_url: str, ref: str, paths: list[str], dest_dir: str
133
+ ) -> str:
134
+ repo_dir = os.path.join(dest_dir, "repo")
135
+ clone_cmd = [
136
+ "git",
137
+ "clone",
138
+ "--filter=blob:none",
139
+ "--depth",
140
+ "1",
141
+ "--sparse",
142
+ "--single-branch",
143
+ "--branch",
144
+ ref,
145
+ repo_url,
146
+ repo_dir,
147
+ ]
148
+ try:
149
+ _run_git(clone_cmd)
150
+ except InstallError:
151
+ _run_git(
152
+ [
153
+ "git",
154
+ "clone",
155
+ "--filter=blob:none",
156
+ "--depth",
157
+ "1",
158
+ "--sparse",
159
+ "--single-branch",
160
+ repo_url,
161
+ repo_dir,
162
+ ]
163
+ )
164
+ _run_git(["git", "-C", repo_dir, "sparse-checkout", "set", *paths])
165
+ _run_git(["git", "-C", repo_dir, "checkout", ref])
166
+ return repo_dir
167
+
168
+
169
+ def _validate_skill(path: str) -> None:
170
+ if not os.path.isdir(path):
171
+ raise InstallError(f"Skill path not found: {path}")
172
+ skill_md = os.path.join(path, "SKILL.md")
173
+ if not os.path.isfile(skill_md):
174
+ raise InstallError("SKILL.md not found in selected skill directory.")
175
+
176
+
177
+ def _copy_skill(src: str, dest_dir: str) -> None:
178
+ os.makedirs(os.path.dirname(dest_dir), exist_ok=True)
179
+ if os.path.exists(dest_dir):
180
+ raise InstallError(f"Destination already exists: {dest_dir}")
181
+ shutil.copytree(src, dest_dir)
182
+
183
+
184
+ def _build_repo_url(owner: str, repo: str) -> str:
185
+ return f"https://github.com/{owner}/{repo}.git"
186
+
187
+
188
+ def _build_repo_ssh(owner: str, repo: str) -> str:
189
+ return f"git@github.com:{owner}/{repo}.git"
190
+
191
+
192
+ def _prepare_repo(source: Source, method: str, tmp_dir: str) -> str:
193
+ if method in ("download", "auto"):
194
+ try:
195
+ return _download_repo_zip(source.owner, source.repo, source.ref, tmp_dir)
196
+ except InstallError as exc:
197
+ if method == "download":
198
+ raise
199
+ err_msg = str(exc)
200
+ if "HTTP 401" in err_msg or "HTTP 403" in err_msg or "HTTP 404" in err_msg:
201
+ pass
202
+ else:
203
+ raise
204
+ if method in ("git", "auto"):
205
+ repo_url = source.repo_url or _build_repo_url(source.owner, source.repo)
206
+ try:
207
+ return _git_sparse_checkout(repo_url, source.ref, source.paths, tmp_dir)
208
+ except InstallError:
209
+ repo_url = _build_repo_ssh(source.owner, source.repo)
210
+ return _git_sparse_checkout(repo_url, source.ref, source.paths, tmp_dir)
211
+ raise InstallError("Unsupported method.")
212
+
213
+
214
+ def _resolve_source(args: Args) -> Source:
215
+ if args.url:
216
+ owner, repo, ref, url_path = _parse_github_url(args.url, args.ref)
217
+ if args.path is not None:
218
+ paths = list(args.path)
219
+ elif url_path:
220
+ paths = [url_path]
221
+ else:
222
+ paths = []
223
+ if not paths:
224
+ raise InstallError("Missing --path for GitHub URL.")
225
+ return Source(owner=owner, repo=repo, ref=ref, paths=paths)
226
+
227
+ if not args.repo:
228
+ raise InstallError("Provide --repo or --url.")
229
+ if "://" in args.repo:
230
+ return _resolve_source(
231
+ Args(url=args.repo, repo=None, path=args.path, ref=args.ref)
232
+ )
233
+
234
+ repo_parts = [p for p in args.repo.split("/") if p]
235
+ if len(repo_parts) != 2:
236
+ raise InstallError("--repo must be in owner/repo format.")
237
+ if not args.path:
238
+ raise InstallError("Missing --path for --repo.")
239
+ paths = list(args.path)
240
+ return Source(
241
+ owner=repo_parts[0],
242
+ repo=repo_parts[1],
243
+ ref=args.ref,
244
+ paths=paths,
245
+ )
246
+
247
+
248
+ def _default_dest() -> str:
249
+ return os.path.join(_opencode_home(), "skill")
250
+
251
+
252
+ def _parse_args(argv: list[str]) -> Args:
253
+ parser = argparse.ArgumentParser(description="Install a skill from GitHub.")
254
+ parser.add_argument("--repo", help="owner/repo")
255
+ parser.add_argument("--url", help="https://github.com/owner/repo[/tree/ref/path]")
256
+ parser.add_argument(
257
+ "--path",
258
+ nargs="+",
259
+ help="Path(s) to skill(s) inside repo",
260
+ )
261
+ parser.add_argument("--ref", default=DEFAULT_REF)
262
+ parser.add_argument("--dest", help="Destination skills directory")
263
+ parser.add_argument(
264
+ "--name", help="Destination skill name (defaults to basename of path)"
265
+ )
266
+ parser.add_argument(
267
+ "--method",
268
+ choices=["auto", "download", "git"],
269
+ default="auto",
270
+ )
271
+ return parser.parse_args(argv, namespace=Args())
272
+
273
+
274
+ def main(argv: list[str]) -> int:
275
+ args = _parse_args(argv)
276
+ try:
277
+ source = _resolve_source(args)
278
+ source.ref = source.ref or args.ref
279
+ if not source.paths:
280
+ raise InstallError("No skill paths provided.")
281
+ for path in source.paths:
282
+ _validate_relative_path(path)
283
+ dest_root = args.dest or _default_dest()
284
+ tmp_dir = tempfile.mkdtemp(prefix="skill-install-", dir=_tmp_root())
285
+ try:
286
+ repo_root = _prepare_repo(source, args.method, tmp_dir)
287
+ installed = []
288
+ for path in source.paths:
289
+ skill_name = args.name if len(source.paths) == 1 else None
290
+ skill_name = skill_name or os.path.basename(path.rstrip("/"))
291
+ _validate_skill_name(skill_name)
292
+ if not skill_name:
293
+ raise InstallError("Unable to derive skill name.")
294
+ dest_dir = os.path.join(dest_root, skill_name)
295
+ if os.path.exists(dest_dir):
296
+ raise InstallError(f"Destination already exists: {dest_dir}")
297
+ skill_src = os.path.join(repo_root, path)
298
+ _validate_skill(skill_src)
299
+ _copy_skill(skill_src, dest_dir)
300
+ installed.append((skill_name, dest_dir))
301
+ finally:
302
+ if os.path.isdir(tmp_dir):
303
+ shutil.rmtree(tmp_dir, ignore_errors=True)
304
+ for skill_name, dest_dir in installed:
305
+ print(f"Installed {skill_name} to {dest_dir}")
306
+ return 0
307
+ except InstallError as exc:
308
+ print(f"Error: {exc}", file=sys.stderr)
309
+ return 1
310
+
311
+
312
+ if __name__ == "__main__":
313
+ raise SystemExit(main(sys.argv[1:]))