library: skills install from any git repository, GitLab and a company's own among them (sunset on Discord)
ProbeSkills took only a GitHub source or a folder. It now also takes any
git repository's address: https/http on gitlab.com or a self-hosted
server (any depth of groups), a GitLab or Gitea page of a folder
(/-/tree/<ref>/<path>, /-/blob/..., /src/branch/...), ssh://,
git@host:group/repo.git, a bare host.name/group/repo, and file://.
Such a source is kind "git" (gitSource, skillgit.go).
It is fetched with the user's own git (proc.FindTool), so their
credential helpers and SSH keys reach an intranet host: git init, then
fetch --depth 1 --no-tags -- <url> <ref|HEAD>, checkout FETCH_HEAD into
a magpie-skill-* folder, .git removed; the same keepProbe/maxFetch path
GitHub's tarball takes.
What the user typed is data: an address starting with - and any
transport:: address (ext::, fd::, file::) are refused before git runs;
the address follows --; git runs with protocol.ext.allow=never and
core.symlinks=false, no shell, GIT_TERMINAL_PROMPT=0, and ssh -o
BatchMode=yes unless the user set their own SSH command (GIT_SSH,
GIT_SSH_COMMAND, core.sshCommand), so a sign-in it can't make fails
instead of waiting. An address with a password or token in it is
refused: library.json is shown and backed up. Git missing, a sign-in
refused, an unknown host key, a missing branch and an unreachable host
each say so plainly (gitError).
Updates: Commit keeps the repository head the skill was fetched at. A
check runs git ls-remote; another head is fetched (once per repository
and ref) and the skill's folder hashed, so a commit elsewhere in the
repository leaves it current and moves Commit on. UpdateSkill and the
edited-skill refusal work as for GitHub; EditedError and the page's
Changed here / Update / replace question name the repository instead of
GitHub. findNew, Group again, icons and the market stay GitHub's only
(documented).
Page, TUI and docs: the add box's placeholder in en/zh/zh-TW/ja/de
(zh: owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹),
a git skill's source shown as a link (https) or text (SSH), its own
Update and Check for updates; the TUI's prompt; library.md's Skills and
Skill updates rows. GIT_SSH/GIT_SSH_COMMAND are listed in agentenv's
notAnAgent (TestFolderVarsAreListed).
Tests (fail on the old code: gitSource/gitPath don't exist there, and
skill-git-source.test.cjs fails on the old assets' placeholder, checked
by stashing client.js/i18n.js): TestGitSourceReads,
TestInstallFromGitRepo (a local bare repo over file://: probe, install,
check finds an update, update, a commit elsewhere stays current, an
edit here is refused naming the repo), TestGitTreeURLInstallsFolder,
TestGitMissingSaysSo, TestGitSignInRefusedSaysSo (a local httptest 401,
GIT_CONFIG_NOSYSTEM so no Keychain), TestGitRefusesOptionsAndTransports,
TestGitErrorsSaid. No test reaches the network.
Run (worktree at origin/main 224ea7d5b, machine load average ~120-145
from other sessions):
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
clean.
- set -o pipefail; go test -timeout 45m ./...: 63 packages ok; one red,
internal/agent TestFolderVarsAreListed (GIT_SSH vars), fixed above
and rerun alone: ok.
- After later edits, rerun ./internal/library ./internal/cli
./internal/tui ok; internal/gui TestMainWindowCorners red once at
load 144 (76.5s, AppKit window test this change doesn't touch),
passed alone (28.6s); internal/agent timed out at 45m in that
combined rerun at load ~140 (it ran 962s in the full run) and passed
alone (1808s, load ~100).
- GUI: the 88 test files that load the library page, chromium and
webkit: 1420/1420 pass; skill-git-source + skill-update-edited rerun
after the last client.js edit: 20/20.
- Real use in a sandbox HOME (GIT_CONFIG_NOSYSTEM=1): a local bare repo
over file:// probed, installed, checked current, a new commit found as
update, updated to v2; ext:: and --upload-pack refused with nothing
run; https://gitlab.com/gitlab-org/ai/skills probed (52 skills), its
/-/tree/main/skills/glab installed and checked current; a private
gitlab.com address said "git couldn't sign in to gitlab.com ...".
- Not tried: a real self-hosted GitLab with credentials, ssh:// against
a real host, Windows.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -35,6 +35,8 @@ var notAnAgent = map[string]string{
|
||||
"MAGPIE_SITE_ORIGIN": "a site origin magpie's Omarchy theme answers, to try the site locally",
|
||||
"MAGPIE_PARTNERS": "where magpie's own partner list is read from (a URL, or off), not a folder",
|
||||
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "Claude Code's behaviour flag, not an agent's folder",
|
||||
"GIT_SSH": "the user's own SSH program for git, which a skill fetched with their git keeps",
|
||||
"GIT_SSH_COMMAND": "the same, as a command",
|
||||
}
|
||||
|
||||
// TestFolderVarsAreListed says every variable the packages that find an
|
||||
|
||||
@@ -139,7 +139,7 @@ func libraryCmd(args []string) error {
|
||||
if res, err = library.UpdateSkill(rest[1], len(rest) == 3); err == nil {
|
||||
fmt.Println(green.Render("✓"), rest[1], "is up to date")
|
||||
} else if errors.As(err, &edited) {
|
||||
err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes GitHub's in its place, keeping yours with the backups", err, rest[1])
|
||||
err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes the fetched one in its place, keeping yours with the backups", err, rest[1])
|
||||
}
|
||||
case len(rest) == 1 && rest[0] == "update":
|
||||
res, err = library.UpdateSkills()
|
||||
|
||||
@@ -2640,7 +2640,7 @@ magpie.plugin("library", (ctx) => {
|
||||
rh.append(el("span", "label", t("In the library")));
|
||||
const box = el("div", "lib-groups");
|
||||
if (lib.skills.length > 8) rh.append(skillFilter(box, all));
|
||||
const fresh = lib.skills.filter((s) => s.kind === "github" || s.origin);
|
||||
const fresh = lib.skills.filter((s) => s.kind === "github" || s.kind === "git" || s.origin);
|
||||
rh.append(el("span", "grow"));
|
||||
if (lib.skills.length > 1) rh.append(sortBy("libSkills", SKILL_SORTS(), () => { if (box.isConnected) drawSkills(box, all); }));
|
||||
if (lib.skills.length > 1) rh.append(foldAllButton(box, all));
|
||||
@@ -2656,9 +2656,11 @@ magpie.plugin("library", (ctx) => {
|
||||
if (lib.skills.length > 1 && all.length) rh.append(pickButton("skills"), ...everyButtons("skills", all));
|
||||
if (byAgentRows("skills").length) rh.append(byAgentButton("skills"));
|
||||
if (lib.skills.length > 1) rh.append(removeEveryButton("skills"));
|
||||
if (lib.skills.some((s) => s.kind === "github")) {
|
||||
if (lib.skills.some((s) => s.kind === "github" || s.kind === "git")) {
|
||||
const c = button(checking ? t("Checking…") : t("Check for updates"), "lib-updall", () => checkSkills());
|
||||
c.title = t("Ask GitHub which skills changed since they were installed");
|
||||
c.title = lib.skills.some((s) => s.kind === "git")
|
||||
? t("Ask the repositories your skills came from which skills changed since they were installed")
|
||||
: t("Ask GitHub which skills changed since they were installed");
|
||||
c.disabled = checking;
|
||||
if (checking) c.classList.add("busy");
|
||||
rh.append(c);
|
||||
@@ -2829,6 +2831,9 @@ magpie.plugin("library", (ctx) => {
|
||||
try { folds = JSON.parse(localStorage.getItem("magpie.libSkillFolds") || "{}") || {}; } catch {}
|
||||
function saveFolds() { try { localStorage.setItem("magpie.libSkillFolds", JSON.stringify(folds)); } catch {} }
|
||||
const repoOf = (u) => (u || "").replace(/^https:\/\/github\.com\//, "").split("/").slice(0, 2).join("/");
|
||||
// the repository a skill from another git host (kind "git") came from,
|
||||
// as the page names it: its address, without https:// or a folder in it
|
||||
const gitRepoOf = (s) => (s.kind === "git" ? (s.source || "").replace(/^https?:\/\//, "").replace(/\/-\/tree\/.*$/, "") : "");
|
||||
// the repository a skill came from, however it came in: magpie traces
|
||||
// one not installed from GitHub too (the skills CLI's lock, the git
|
||||
// checkout it's in), so a repository's skills are one group (White
|
||||
@@ -2934,6 +2939,11 @@ magpie.plugin("library", (ctx) => {
|
||||
const m = /^https:\/\/github\.com\/[^/]+\/[^/]+\/tree\/[^/]+\/(.+)$/.exec(s.source || "");
|
||||
return m ? m[1].split("/").slice(0, -1).join("/") : "";
|
||||
}
|
||||
if (s.kind === "git") {
|
||||
// GitLab's …/-/tree/<ref>/<path to the folder>/<skill>
|
||||
const m = /\/-\/tree\/[^/]+\/(.+)$/.exec(s.source || "");
|
||||
return m ? m[1].split("/").slice(0, -1).join("/") : "";
|
||||
}
|
||||
if (s.kind === "folder") return tilde((s.source || "").replace(/[\\/][^\\/]+[\\/]?$/, ""));
|
||||
return "";
|
||||
};
|
||||
@@ -2957,7 +2967,7 @@ magpie.plugin("library", (ctx) => {
|
||||
if (g.repo) {
|
||||
// the folder in the repository is known of those installed from it
|
||||
// only: one traced to it goes by its name with the rest
|
||||
let m = g.skills.every((s) => s.kind === "github") ? split(g.skills, folderIn) : null, mono = true;
|
||||
let m = g.skills.every((s) => s.kind === "github" || s.kind === "git") ? split(g.skills, folderIn) : null, mono = true;
|
||||
if (!m) { mono = false; m = byStart(); }
|
||||
if (!m) return null;
|
||||
return [...m].map(([key, skills]) => ({ key, skills, mono, label: label(key, mono) })).sort(order);
|
||||
@@ -4402,7 +4412,7 @@ magpie.plugin("library", (ctx) => {
|
||||
const inp = el("input");
|
||||
inp.type = "text";
|
||||
inp.dataset.lib = "source";
|
||||
inp.placeholder = t("owner/repo, a GitHub link, or a folder on this computer");
|
||||
inp.placeholder = t("owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer");
|
||||
inp.spellcheck = false;
|
||||
inp.autocomplete = "off";
|
||||
inp.value = probe?.source || "";
|
||||
@@ -4442,7 +4452,8 @@ magpie.plugin("library", (ctx) => {
|
||||
const left = (p.found.left || []).map((x) => el("div", "lib-none lib-left", t("{name} is too big to install: {size}, over the {limit} a skill may be", { name: x.path.split("/").pop() || p.found.source, size: Math.round(x.size / 1048576) + " MB", limit: "200 MB" })));
|
||||
if (!c.length) { box.append(...(left.length ? left : [el("div", "lib-none", t("No skills there — a skill is a folder with a SKILL.md in it."))])); return box; }
|
||||
const head = el("div", "lib-probehead");
|
||||
const src = p.found.kind === "github" ? "github.com/" + p.found.source.replace(/^https?:\/\/github\.com\//, "") : tilde(p.found.source);
|
||||
const src = p.found.kind === "github" ? "github.com/" + p.found.source.replace(/^https?:\/\/github\.com\//, "")
|
||||
: p.found.kind === "git" ? p.found.source.replace(/^https:\/\//, "") : tilde(p.found.source);
|
||||
head.append(el("span", "note", c.length === 1 ? t("1 skill in {src}", { src }) : t("{n} skills in {src}", { n: c.length, src })));
|
||||
head.append(el("span", "grow"));
|
||||
const fresh = c.filter((x) => !x.have);
|
||||
@@ -4519,7 +4530,9 @@ magpie.plugin("library", (ctx) => {
|
||||
}
|
||||
// changed here since it was fetched from GitHub (#1449): an update asks
|
||||
// before it replaces that
|
||||
if (s.edited) nm.append(tag(t("Changed here"), "warn lib-edited", t("You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.")));
|
||||
if (s.edited) nm.append(tag(t("Changed here"), "warn lib-edited", gitRepoOf(s)
|
||||
? t("You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.", { repo: gitRepoOf(s) })
|
||||
: t("You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.")));
|
||||
// a copy in an agent that differs from the library's skill (#896): a
|
||||
// sync makes it again
|
||||
if (s.behind?.length) {
|
||||
@@ -4544,13 +4557,23 @@ magpie.plugin("library", (ctx) => {
|
||||
a.href = s.source;
|
||||
a.onclick = (e) => { e.preventDefault(); e.stopPropagation(); browse(s.source); };
|
||||
src.append(a);
|
||||
} else if (s.kind === "git" && /^https?:\/\//.test(s.source)) {
|
||||
const a = el("a", "lib-srclink", s.source.replace(/^https:\/\//, ""));
|
||||
a.href = s.source;
|
||||
a.onclick = (e) => { e.preventDefault(); e.stopPropagation(); browse(s.source); };
|
||||
src.append(a);
|
||||
} else if (s.kind === "git") {
|
||||
// an SSH address (git@host:path) or a file:// one: no page to open
|
||||
const a = el("span", "lib-srclink", s.source);
|
||||
a.title = s.source;
|
||||
src.append(a);
|
||||
} else {
|
||||
src.append(el("span", "", t("linked from")), pathLink(s.source));
|
||||
}
|
||||
who.append(src);
|
||||
}
|
||||
const acts = el("div", "lib-rowacts");
|
||||
if (s.kind === "github" || s.origin) {
|
||||
if (s.kind === "github" || s.kind === "git" || s.origin) {
|
||||
const u = button("", "lib-icon", async (e, b) => {
|
||||
if (s.edited) return confirmUpdateEdited(s);
|
||||
b.classList.add("busy");
|
||||
@@ -4558,8 +4581,10 @@ magpie.plugin("library", (ctx) => {
|
||||
b.classList.remove("busy");
|
||||
});
|
||||
u.append(svg(GLYPH.up, 13, 1.5));
|
||||
u.title = s.origin ? t("Update from GitHub ({repo}, as CC Switch installed it)", { repo: s.origin.replace(/^https:\/\/github\.com\//, "") }) : t("Update from GitHub");
|
||||
if (c?.status === "current") u.title += "\n" + t("Up to date with GitHub") + "\n" + checkLine(c);
|
||||
const gitRepo = gitRepoOf(s);
|
||||
u.title = s.origin ? t("Update from GitHub ({repo}, as CC Switch installed it)", { repo: s.origin.replace(/^https:\/\/github\.com\//, "") })
|
||||
: gitRepo ? t("Update from {repo}", { repo: gitRepo }) : t("Update from GitHub");
|
||||
if (c?.status === "current") u.title += "\n" + (gitRepo ? t("Up to date with {repo}", { repo: gitRepo }) : t("Up to date with GitHub")) + "\n" + checkLine(c);
|
||||
else if (c?.status === "update") u.title += "\n" + checkLine(c);
|
||||
if (s.edited) u.title += "\n" + t("Changed here: asks before it replaces your changes");
|
||||
acts.append(u);
|
||||
@@ -4580,9 +4605,12 @@ magpie.plugin("library", (ctx) => {
|
||||
function confirmUpdateEdited(s) {
|
||||
const ed = el("div", "editor lib-editor lib-update-edited");
|
||||
const head = el("div", "ehead");
|
||||
head.append(glyph(GLYPH.up), el("b", "", t("Replace your changes to {name}?", { name: s.name })));
|
||||
const repo = gitRepoOf(s);
|
||||
head.append(glyph(GLYPH.up), el("b", "", repo ? t("Replace your changes to {name} with the version in {repo}?", { name: s.name, repo }) : t("Replace your changes to {name}?", { name: s.name })));
|
||||
ed.append(head);
|
||||
ed.append(el("p", "lib-confirm", t("You changed {name} here since it was fetched from GitHub. Updating puts GitHub's version in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).", { name: s.name })));
|
||||
ed.append(el("p", "lib-confirm", repo
|
||||
? t("You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).", { name: s.name, repo })
|
||||
: t("You changed {name} here since it was fetched from GitHub. Updating puts GitHub's version in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).", { name: s.name })));
|
||||
const bar = el("div", "bar");
|
||||
const go = button(t("Update"), "primary", async () => {
|
||||
go.disabled = true;
|
||||
|
||||
@@ -461,7 +461,13 @@ magpie.strings({
|
||||
"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "写入项目的 {files},与已有内容并存;magpie 新建的文件会列入 .gitignore。其中非 magpie 写入的同名服务器保持不动。",
|
||||
"Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code 启动项目服务器前会先询问;Codex 的 .codex/config.toml 和 Pi 的 .pi/mcp.json 仅在受信任的项目中读取。",
|
||||
"{agents} reads no project MCP file magpie knows of.": "{agents} 没有 magpie 已知的项目 MCP 文件。",
|
||||
"owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub 链接,或本机上的文件夹",
|
||||
"owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹",
|
||||
"Ask the repositories your skills came from which skills changed since they were installed": "向技能来源的仓库查询哪些技能在安装后有了改动",
|
||||
"Update from {repo}": "从 {repo} 更新",
|
||||
"Up to date with {repo}": "与 {repo} 一致",
|
||||
"You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "从 {repo} 获取后你在本地改动过它。更新前会先询问,不会直接覆盖你的改动。",
|
||||
"Replace your changes to {name} with the version in {repo}?": "用 {repo} 中的版本替换你对 {name} 的改动?",
|
||||
"You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "从 {repo} 获取 {name} 后你在本地改动过它。更新会用那里的版本替换它,你的版本会保存在 magpie 的备份里(资源库顶部的「备份」)。",
|
||||
"Find skills": "查找技能",
|
||||
"No SKILL.md found there": "那里没有找到 SKILL.md",
|
||||
"No skills there — a skill is a folder with a SKILL.md in it.": "那里没有技能 — 技能是一个含 SKILL.md 的文件夹。",
|
||||
@@ -1062,7 +1068,13 @@ magpie.strings({
|
||||
"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "寫入專案的 {files},與已有內容並存;magpie 新增的檔案會列入 .gitignore。其中非 magpie 寫入的同名伺服器保持不動。",
|
||||
"Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code 啟動專案伺服器前會先詢問;Codex 的 .codex/config.toml 和 Pi 的 .pi/mcp.json 僅在受信任的專案中讀取。",
|
||||
"{agents} reads no project MCP file magpie knows of.": "{agents} 沒有 magpie 已知的專案 MCP 檔案。",
|
||||
"owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub 連結,或本機上的資料夾",
|
||||
"owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo、GitHub 或 GitLab 連結、任何 git 儲存庫位址,或本機上的資料夾",
|
||||
"Ask the repositories your skills came from which skills changed since they were installed": "向技能來源的儲存庫查詢哪些技能在安裝後有了改動",
|
||||
"Update from {repo}": "從 {repo} 更新",
|
||||
"Up to date with {repo}": "與 {repo} 一致",
|
||||
"You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "從 {repo} 取得後你在本機改動過它。更新前會先詢問,不會直接覆蓋你的改動。",
|
||||
"Replace your changes to {name} with the version in {repo}?": "用 {repo} 中的版本取代你對 {name} 的改動?",
|
||||
"You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "從 {repo} 取得 {name} 後你在本機改動過它。更新會用那裡的版本取代它,你的版本會保存在 magpie 的備份裡(資源庫頂部的「備份」)。",
|
||||
"Find skills": "查詢技能",
|
||||
"No SKILL.md found there": "那裡沒有找到 SKILL.md",
|
||||
"No skills there — a skill is a folder with a SKILL.md in it.": "那裡沒有技能 — 技能是一個含 SKILL.md 的資料夾。",
|
||||
@@ -1658,7 +1670,13 @@ magpie.strings({
|
||||
"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "プロジェクトの {files} に、既存の内容と並べて書き込みます。magpie が作成したファイルは .gitignore に記載します。そこにある magpie のものでない同名のサーバーはそのままです。",
|
||||
"Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code はプロジェクトのサーバーを起動する前に確認します。Codex は .codex/config.toml を、Pi は .pi/mcp.json を、信頼したプロジェクトでのみ読みます。",
|
||||
"{agents} reads no project MCP file magpie knows of.": "{agents} は magpie が把握しているプロジェクトの MCP ファイルを読みません。",
|
||||
"owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub のリンク、またはこのコンピュータ上のフォルダ",
|
||||
"owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo、GitHub または GitLab のリンク、任意の git リポジトリのアドレス、またはこのコンピュータ上のフォルダ",
|
||||
"Ask the repositories your skills came from which skills changed since they were installed": "インストール後に変更されたスキルを、取得元のリポジトリに問い合わせます",
|
||||
"Update from {repo}": "{repo} からアップデート",
|
||||
"Up to date with {repo}": "{repo} と同じ",
|
||||
"You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "{repo} から取得した後、ここで変更されています。更新は変更を置き換える前に確認します。",
|
||||
"Replace your changes to {name} with the version in {repo}?": "{name} への変更を {repo} の版で置き換えますか?",
|
||||
"You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "{name} は {repo} から取得した後、ここで変更されています。更新するとそこの版に置き換わります。あなたの版は magpie のバックアップ(ライブラリ上部の「バックアップ」)に残ります。",
|
||||
"Find skills": "スキルを探す",
|
||||
"No SKILL.md found there": "そこに SKILL.md が見つかりません",
|
||||
"No skills there — a skill is a folder with a SKILL.md in it.": "そこにスキルはありません — スキルとは SKILL.md を含むフォルダです。",
|
||||
@@ -2257,7 +2275,13 @@ magpie.strings({
|
||||
"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "In {files} des Projekts geschrieben, neben dem vorhandenen Inhalt; eine von magpie erstellte Datei wird in seiner .gitignore eingetragen. Ein gleichnamiger Server dort, der nicht von magpie stammt, bleibt unverändert.",
|
||||
"Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code fragt nach, bevor es die Server eines Projekts startet; Codex liest .codex/config.toml und Pi .pi/mcp.json nur in einem Projekt, dem Sie vertrauen.",
|
||||
"{agents} reads no project MCP file magpie knows of.": "{agents} liest keine Projekt-MCP-Datei, die magpie kennt.",
|
||||
"owner/repo, a GitHub link, or a folder on this computer": "owner/repo, ein GitHub-Link oder ein Ordner auf diesem Computer",
|
||||
"owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo, ein GitHub- oder GitLab-Link, die Adresse eines beliebigen Git-Repositorys oder ein Ordner auf diesem Computer",
|
||||
"Ask the repositories your skills came from which skills changed since they were installed": "Bei den Repositorys, aus denen die Skills stammen, abfragen, welche sich seit der Installation geändert haben",
|
||||
"Update from {repo}": "Von {repo} aktualisieren",
|
||||
"Up to date with {repo}": "Auf dem Stand von {repo}",
|
||||
"You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "Du hast ihn geändert, seit er von {repo} geholt wurde. Ein Update fragt, bevor es deine Änderungen ersetzt.",
|
||||
"Replace your changes to {name} with the version in {repo}?": "Deine Änderungen an {name} durch die Version aus {repo} ersetzen?",
|
||||
"You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "Du hast {name} hier geändert, seit er von {repo} geholt wurde. Das Update setzt die Version von dort an seine Stelle. Deine bleibt in den Backups von magpie (Backups, oben in der Bibliothek).",
|
||||
"Find skills": "Skills suchen",
|
||||
"No SKILL.md found there": "Dort keine SKILL.md gefunden",
|
||||
"No skills there — a skill is a folder with a SKILL.md in it.": "Dort keine Skills – ein Skill ist ein Ordner mit einer SKILL.md darin.",
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// sunset on Discord: skills from GitLab, and from a company's own GitLab.
|
||||
// The add box says any git repository's address works. A skill from one
|
||||
// (kind "git") shows where it came from (a link for an https address, the
|
||||
// address as text for an SSH one), has its own Update naming the
|
||||
// repository, and Check for updates is offered for it. A probe of one
|
||||
// names the repository. In English and Chinese, in Chromium and WebKit,
|
||||
// wide and narrow. No backend: the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const HOME = "/Users/sunset";
|
||||
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` });
|
||||
const HTTPS = "https://gitlab.corp.example/team/skills/-/tree/HEAD/skills/pdf";
|
||||
const SSH = "git@gitlab.corp.example:team/private.git";
|
||||
const lib = () => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [agent("claude", "Claude Code")],
|
||||
instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], newSkills: [],
|
||||
checkDue: false,
|
||||
skills: [
|
||||
{ name: "pdf", description: "PDFs", kind: "git", source: HTTPS, agents: ["claude"] },
|
||||
{ name: "review", description: "Reviews", kind: "git", source: SSH, agents: ["claude"], edited: true },
|
||||
],
|
||||
});
|
||||
const probe = { source: "https://gitlab.corp.example/team/skills", kind: "git", candidates: [{ path: "skills/a", name: "a", description: "a", have: false }] };
|
||||
|
||||
function server(lang, posts) {
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
|
||||
if (url.pathname === "/api/library") return route.fulfill({ json: lib() });
|
||||
if (url.pathname === "/api/library/skills/probe") { posts.push(req.postDataJSON()); return route.fulfill({ json: probe }); }
|
||||
if (url.pathname.startsWith("/api/library/skills/")) { posts.push(url.pathname.split("/").pop()); return route.fulfill({ json: { ...lib(), result: { changed: [] } } }); }
|
||||
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
|
||||
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
|
||||
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
|
||||
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
|
||||
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { ph: "owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer", upd: "Update from gitlab.corp.example/team/skills", updSSH: "Update from " + SSH, check: "Check for updates", found: "1 skill in gitlab.corp.example/team/skills",
|
||||
tip: "You changed it since it was fetched from " + SSH + ". Updating asks before it replaces your changes.", ask: "Replace your changes to review with the version in " + SSH + "?" },
|
||||
zh: { ph: "owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹", upd: "从 gitlab.corp.example/team/skills 更新", updSSH: "从 " + SSH + " 更新", check: "检查更新", found: null,
|
||||
tip: "从 " + SSH + " 获取后你在本地改动过它。更新前会先询问,不会直接覆盖你的改动。", ask: "用 " + SSH + " 中的版本替换你对 review 的改动?" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a skill from a git repository shows it, updates from it, and the add box says so", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
if (errors.length) console.log(errors);
|
||||
await browser.close();
|
||||
});
|
||||
for (const width of [900, 400]) for (const lang of ["en", "zh"]) {
|
||||
await t.test(`${lang} at ${width}px`, async () => {
|
||||
const w = words[lang], posts = [];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 900 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const v = page.locator("#view-library");
|
||||
const src = v.locator('input[data-lib="source"]');
|
||||
await src.waitFor();
|
||||
assert.equal(await src.getAttribute("placeholder"), w.ph);
|
||||
|
||||
const row = (name) => v.locator(".lib-skill", { has: page.locator(".name", { hasText: new RegExp("^" + name) }) });
|
||||
await row("pdf").waitFor();
|
||||
const link = row("pdf").locator("a.lib-srclink");
|
||||
assert.equal(await link.getAttribute("href"), HTTPS);
|
||||
assert.equal((await link.textContent()).trim(), HTTPS.replace("https://", ""));
|
||||
const ssh = row("review").locator(".lib-src .lib-srclink");
|
||||
assert.equal(await ssh.evaluate((e) => e.tagName), "SPAN", "an SSH address isn't a link");
|
||||
assert.equal((await ssh.textContent()).trim(), SSH);
|
||||
assert.equal(await row("pdf").locator(".lib-rowacts button.lib-icon").first().getAttribute("title"), w.upd);
|
||||
assert.equal((await row("review").locator(".lib-rowacts button.lib-icon").first().getAttribute("title")).split("\n")[0], w.updSSH);
|
||||
const check = v.locator(".row-head button.lib-updall", { hasText: w.check });
|
||||
assert.equal(await check.count(), 1, "Check for updates is offered");
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
|
||||
|
||||
await row("pdf").locator(".lib-rowacts button.lib-icon").first().click();
|
||||
await page.waitForTimeout(200);
|
||||
assert.deepEqual(posts, ["update"]);
|
||||
// one changed here names the repository it would be replaced from
|
||||
assert.equal(await row("review").locator(".lib-tag.lib-edited").getAttribute("title"), w.tip);
|
||||
await row("review").locator(".lib-rowacts button.lib-icon").first().click();
|
||||
const modal = page.locator(".lib-update-edited");
|
||||
await modal.waitFor();
|
||||
assert.equal((await modal.locator(".ehead b").textContent()).trim(), w.ask);
|
||||
assert.match(await modal.locator(".lib-confirm").textContent(), new RegExp(SSH.replace(/[.]/g, "\\.")));
|
||||
assert.deepEqual(posts, ["update"], "asking sends nothing");
|
||||
await page.keyboard.press("Escape");
|
||||
await modal.waitFor({ state: "detached" });
|
||||
|
||||
await src.fill("https://gitlab.corp.example/team/skills");
|
||||
await src.press("Enter");
|
||||
const head = v.locator(".lib-probehead .note");
|
||||
await head.waitFor();
|
||||
assert.equal(posts[1].source, "https://gitlab.corp.example/team/skills");
|
||||
if (w.found) assert.equal((await head.textContent()).trim(), w.found);
|
||||
else assert.match(await head.textContent(), /gitlab\.corp\.example\/team\/skills/);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
@@ -21,11 +21,25 @@ import (
|
||||
)
|
||||
|
||||
// EditedError is an update refused because the skill was changed here
|
||||
// since it was fetched from GitHub.
|
||||
type EditedError struct{ Name string }
|
||||
// since it was fetched from GitHub, or From, the git repository it came
|
||||
// from.
|
||||
type EditedError struct{ Name, From string }
|
||||
|
||||
func (e *EditedError) Error() string {
|
||||
return fmt.Sprintf("%s was changed here since it was fetched from GitHub; updating it would replace those changes", e.Name)
|
||||
from := e.From
|
||||
if from == "" {
|
||||
from = "GitHub"
|
||||
}
|
||||
return fmt.Sprintf("%s was changed here since it was fetched from %s; updating it would replace those changes", e.Name, from)
|
||||
}
|
||||
|
||||
// editedError is the refusal of an update of s, naming where it came from.
|
||||
func editedError(s *Skill) *EditedError {
|
||||
e := &EditedError{Name: s.Name}
|
||||
if s.Source != nil && s.Source.Kind == "git" {
|
||||
e.From = s.Source.Repo
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// edits remembers, for each skill's library folder, its hash as of when
|
||||
@@ -72,7 +86,7 @@ func libraryHash(name string) string {
|
||||
// hash of what it fetched (installed before it did), or the folder can't
|
||||
// be read.
|
||||
func (l *Library) editState(s *Skill, targets []*Target) (edited, known bool) {
|
||||
if s.Source == nil || s.Source.Kind != "github" || s.Hash == "" {
|
||||
if !s.Source.remote() || s.Hash == "" {
|
||||
return false, false
|
||||
}
|
||||
lib := skillDir(s.Name)
|
||||
|
||||
@@ -30,6 +30,9 @@ func (tr *tracer) repoOf(s *Skill) string {
|
||||
if s.Source != nil && s.Source.Kind == "github" {
|
||||
return s.Source.Repo
|
||||
}
|
||||
if s.Source != nil && s.Source.Kind == "git" {
|
||||
return remoteRepo(s.Source.Repo) // host/path, as a checkout of it is
|
||||
}
|
||||
if o, ok := ccSwitchOrigin(s); ok {
|
||||
return o.Repo
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ const checkEvery = 12 * time.Hour
|
||||
// GitHub for updates: none checked since magpie started, or not for
|
||||
// checkEvery.
|
||||
func checkDue(l *Library) bool {
|
||||
if !slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.Source != nil && s.Source.Kind == "github" }) {
|
||||
if !slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.Source.remote() }) {
|
||||
return false
|
||||
}
|
||||
at := checkedAt.Load()
|
||||
@@ -275,7 +275,8 @@ func firstLine(s string) string {
|
||||
// that isn't known yet, by fetching the repository once and comparing the
|
||||
// folder's files with the skill's. A skill GitHub couldn't be asked about
|
||||
// is unknown, and the others are checked all the same; once GitHub limits
|
||||
// requests, the rest aren't asked about.
|
||||
// requests, the rest aren't asked about. A skill from another git
|
||||
// repository is checked with the user's git (checkGitSkill).
|
||||
func CheckSkills() ([]SkillCheck, error) {
|
||||
mu.Lock()
|
||||
l, err := load()
|
||||
@@ -285,8 +286,8 @@ func CheckSkills() ([]SkillCheck, error) {
|
||||
}
|
||||
byRepo := map[string][]*Skill{}
|
||||
for _, s := range l.Skills {
|
||||
if s.Source != nil && s.Source.Kind == "github" {
|
||||
byRepo[s.Source.Repo] = append(byRepo[s.Source.Repo], s)
|
||||
if s.Source.remote() {
|
||||
byRepo[s.Source.Kind+"\x00"+s.Source.Repo] = append(byRepo[s.Source.Kind+"\x00"+s.Source.Repo], s)
|
||||
}
|
||||
}
|
||||
f := &fetcher{}
|
||||
@@ -306,9 +307,16 @@ func CheckSkills() ([]SkillCheck, error) {
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
asked := map[string]*commit{} // a repository's skills in one folder are asked about once
|
||||
heads := map[string]string{} // a git repository's refs, asked about once
|
||||
refs := []string{}
|
||||
for _, s := range skills {
|
||||
c, sha, hash := checkSkill(s, f, asked, &limited)
|
||||
var c SkillCheck
|
||||
var sha, hash string
|
||||
if s.Source.Kind == "git" {
|
||||
c, sha, hash = checkGitSkill(s, f, heads)
|
||||
} else {
|
||||
c, sha, hash = checkSkill(s, f, asked, &limited)
|
||||
}
|
||||
omu.Lock()
|
||||
out = append(out, c)
|
||||
if sha != "" {
|
||||
@@ -319,8 +327,12 @@ func CheckSkills() ([]SkillCheck, error) {
|
||||
refs = append(refs, s.Source.Ref)
|
||||
}
|
||||
}
|
||||
// and what the repository has added beside them since
|
||||
// and what the repository has added beside them since: GitHub's
|
||||
// list of its files says, which another host has no API for
|
||||
for _, ref := range refs {
|
||||
if skills[0].Source.Kind != "github" {
|
||||
break
|
||||
}
|
||||
if found, ok := findNew(l, skills[0].Source.Repo, ref, f, &limited); ok {
|
||||
newFound.Lock()
|
||||
newFound.m[repoKey(skills[0].Source.Repo, ref)] = found
|
||||
@@ -338,7 +350,9 @@ func CheckSkills() ([]SkillCheck, error) {
|
||||
if l, err := load(); err == nil {
|
||||
for _, s := range l.Skills {
|
||||
k, ok := known[s.Name]
|
||||
if ok && s.Source != nil && s.Source.Kind == "github" && s.Commit == "" && (s.Hash == "" || s.Hash == k[1]) {
|
||||
// a git repository's commit is the whole repository's: a
|
||||
// check that found the files the same at a later one keeps that
|
||||
if ok && s.Source.remote() && (s.Commit == "" || s.Source.Kind == "git") && (s.Hash == "" || s.Hash == k[1]) {
|
||||
s.Commit, s.Hash = k[0], k[1]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package library
|
||||
|
||||
// Skills from any git repository (sunset on Discord): GitLab, a company's
|
||||
// own GitLab on its intranet, Gitea, a bare repository on this machine.
|
||||
// magpie can't ask such a host for a tarball or its commits the way it
|
||||
// asks GitHub, so it runs the user's own git, which signs in to the host
|
||||
// the way it does for the user (a credential helper, a token, an SSH key
|
||||
// in the agent). The address is data: it reaches git as an argument after
|
||||
// "--", never through a shell, and what git can't be told apart from an
|
||||
// option, or a transport that runs a command, is refused before git runs.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
// gitPath is where git is, "" when it isn't here; a variable for tests.
|
||||
var gitPath = func() string { return proc.FindTool("git") }
|
||||
|
||||
// gitTimeout is how long one git command may take before it is stopped:
|
||||
// a host that never answers, or a sign-in no one can see, ends there.
|
||||
var gitTimeout = 3 * time.Minute
|
||||
|
||||
var (
|
||||
// remoteHelper is git's <transport>::<address>, which hands the
|
||||
// address to a helper program (ext:: runs a command)
|
||||
remoteHelper = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*::`)
|
||||
// scpLike is git's user@host:path for SSH
|
||||
scpLike = regexp.MustCompile(`^(?:([\w.-]+)@)?([\w.-]+):(.+)$`)
|
||||
gitRef = regexp.MustCompile(`^[\w./+@-]+$`)
|
||||
hexRef = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`)
|
||||
)
|
||||
|
||||
// gitSchemes are the URL schemes a git source may have. file:// is a
|
||||
// repository on this machine or a mounted share, which the user named.
|
||||
var gitSchemes = map[string]bool{"https": true, "http": true, "ssh": true, "git": true, "git+ssh": true, "ssh+git": true, "file": true}
|
||||
|
||||
// gitSource reads a git repository out of what the user typed: a URL
|
||||
// (https://host/group/sub/repo(.git), ssh://, git://, file://), SSH's
|
||||
// git@host:group/repo.git, or host/group/repo. A GitLab page's
|
||||
// /-/tree/<ref>/<path> (or /-/blob/…/SKILL.md), and Gitea's
|
||||
// /src/branch/<ref>/<path>, name a branch and a folder in it; the ref is
|
||||
// the first part after them, so a branch with a / in its name is read
|
||||
// as a ref and a folder. ok is false for what isn't meant as one; an
|
||||
// error is one that is, refused.
|
||||
func gitSource(s string) (src Source, ok bool, err error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return Source{}, false, nil
|
||||
}
|
||||
if strings.HasPrefix(s, "-") {
|
||||
return Source{}, true, fmt.Errorf("a repository's address can't start with -")
|
||||
}
|
||||
if remoteHelper.MatchString(s) {
|
||||
return Source{}, true, fmt.Errorf("magpie doesn't install from a git address with a transport (%s): give the repository's https or SSH address", s[:strings.Index(s, "::")+2])
|
||||
}
|
||||
if strings.IndexFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 {
|
||||
return Source{}, false, nil
|
||||
}
|
||||
repo, rest := s, ""
|
||||
for _, sep := range []string{"/-/tree/", "/-/blob/", "/src/branch/", "/src/tag/", "/src/commit/"} {
|
||||
if i := strings.Index(s, sep); i > 0 {
|
||||
repo, rest = s[:i], s[i+len(sep):]
|
||||
break
|
||||
}
|
||||
}
|
||||
repo = strings.TrimSuffix(repo, "/")
|
||||
if strings.HasSuffix(repo, "/-") { // https://host/group/repo/-/ alone
|
||||
repo = strings.TrimSuffix(repo, "/-")
|
||||
}
|
||||
if !strings.Contains(repo, "://") {
|
||||
// user@host:path, or host.name:path; a Windows drive (C:) is a
|
||||
// folder, never a host
|
||||
if m := scpLike.FindStringSubmatch(repo); m != nil && len(m[2]) > 1 && (m[1] != "" || strings.Contains(m[2], ".")) {
|
||||
if strings.HasPrefix(m[3], "-") || strings.HasPrefix(m[2], "-") {
|
||||
return Source{}, true, fmt.Errorf("a repository's address can't start with -")
|
||||
}
|
||||
} else if first, _, _ := strings.Cut(repo, "/"); strings.Contains(first, ".") && strings.Count(repo, "/") >= 2 {
|
||||
repo = "https://" + repo // gitlab.example.com/group/repo
|
||||
} else {
|
||||
return Source{}, false, nil
|
||||
}
|
||||
}
|
||||
if strings.Contains(repo, "://") {
|
||||
u, err := url.Parse(repo)
|
||||
if err != nil || u.Scheme == "" {
|
||||
return Source{}, false, nil
|
||||
}
|
||||
if !gitSchemes[strings.ToLower(u.Scheme)] {
|
||||
return Source{}, true, fmt.Errorf("magpie doesn't install from a %s:// address: give the repository's https or SSH address", u.Scheme)
|
||||
}
|
||||
if _, set := u.User.Password(); set {
|
||||
// it would be kept in library.json, shown on the page and
|
||||
// carried to a backup
|
||||
return Source{}, true, fmt.Errorf("leave the password or token out of the address: magpie runs your own git, which signs in with its credential helper or your SSH key")
|
||||
}
|
||||
if strings.ToLower(u.Scheme) != "file" && (u.Host == "" || strings.HasPrefix(u.Host, "-")) {
|
||||
return Source{}, true, fmt.Errorf("%s names no host", repo)
|
||||
}
|
||||
if strings.Trim(u.Path, "/") == "" {
|
||||
return Source{}, true, fmt.Errorf("%s names no repository", repo)
|
||||
}
|
||||
}
|
||||
src = Source{Kind: "git", Repo: repo}
|
||||
if rest != "" {
|
||||
ref, path, _ := strings.Cut(strings.Trim(rest, "/"), "/")
|
||||
if ref != "HEAD" {
|
||||
src.Ref = ref
|
||||
}
|
||||
if q := strings.IndexAny(path, "?#"); q >= 0 {
|
||||
path = path[:q]
|
||||
}
|
||||
src.Path = strings.Trim(strings.TrimSuffix(strings.TrimSuffix(path, "SKILL.md"), "/"), "/")
|
||||
if src.Ref != "" && (!gitRef.MatchString(src.Ref) || strings.HasPrefix(src.Ref, "-") || strings.Contains(src.Ref, "..")) {
|
||||
return Source{}, true, fmt.Errorf("%q isn't a branch or tag git can fetch", src.Ref)
|
||||
}
|
||||
if strings.Contains("/"+src.Path+"/", "/../") {
|
||||
return Source{}, true, fmt.Errorf("%q isn't a folder in the repository", src.Path)
|
||||
}
|
||||
}
|
||||
return src, true, nil
|
||||
}
|
||||
|
||||
// gitURL is a git source as the user can type it again: the repository,
|
||||
// and its ref and folder as a GitLab page names them. An https address
|
||||
// loses its .git there, so it opens the repository's page; GitLab and
|
||||
// Gitea fetch it without one too.
|
||||
func gitURL(s *Source) string {
|
||||
if s.Ref == "" && s.Path == "" {
|
||||
return s.Repo
|
||||
}
|
||||
ref := s.Ref
|
||||
if ref == "" {
|
||||
ref = "HEAD"
|
||||
}
|
||||
u := s.Repo
|
||||
if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") {
|
||||
u = strings.TrimSuffix(u, ".git") // the page, not the clone
|
||||
}
|
||||
u += "/-/tree/" + ref
|
||||
if s.Path != "" {
|
||||
u += "/" + s.Path
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// sameGitRepo is whether two addresses are one repository: by host and
|
||||
// path, however it is reached (https, SSH, with .git or without).
|
||||
func sameGitRepo(a, b string) bool {
|
||||
if strings.EqualFold(strings.TrimSuffix(a, ".git"), strings.TrimSuffix(b, ".git")) {
|
||||
return true
|
||||
}
|
||||
ra, rb := remoteRepo(a), remoteRepo(b)
|
||||
return ra != "" && strings.EqualFold(ra, rb)
|
||||
}
|
||||
|
||||
// gitHeads is the commit each git download is at, by its folder.
|
||||
var gitHeads = struct {
|
||||
sync.Mutex
|
||||
m map[string]string
|
||||
}{m: map[string]string{}}
|
||||
|
||||
func gitHeadOf(dir string) string {
|
||||
gitHeads.Lock()
|
||||
defer gitHeads.Unlock()
|
||||
return gitHeads.m[dir]
|
||||
}
|
||||
|
||||
func noteGitHead(dir, sha string) {
|
||||
gitHeads.Lock()
|
||||
defer gitHeads.Unlock()
|
||||
for d := range gitHeads.m {
|
||||
if _, err := os.Stat(d); err != nil {
|
||||
delete(gitHeads.m, d) // a download removed since
|
||||
}
|
||||
}
|
||||
gitHeads.m[dir] = sha
|
||||
}
|
||||
|
||||
// errNoGit is git missing from this computer.
|
||||
func errNoGit() error {
|
||||
return errors.New("installing from a git repository runs git, and git isn't installed here (or isn't on PATH): install git and try again")
|
||||
}
|
||||
|
||||
// gitEnv is the environment git runs in: the user's, so their credential
|
||||
// helper, SSH agent and config work, with every question asked on a
|
||||
// terminal turned off (no one sees it, and it would wait for ever), and
|
||||
// git's messages in English, as magpie reads them.
|
||||
func gitEnv(git string) []string {
|
||||
env := append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "LC_ALL=C", "LANGUAGE=C")
|
||||
if os.Getenv("GIT_SSH_COMMAND") == "" && os.Getenv("GIT_SSH") == "" {
|
||||
// ssh asks for a passphrase or a new host's key on the terminal:
|
||||
// BatchMode refuses instead. A core.sshCommand of the user's own
|
||||
// (a key for the intranet) is kept, which GIT_SSH_COMMAND would
|
||||
// override.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cmd := proc.CommandContext(ctx, git, "config", "--global", "--get", "core.sshCommand")
|
||||
cmd.Env = env
|
||||
if out, _ := cmd.Output(); strings.TrimSpace(string(out)) == "" {
|
||||
env = append(env, "GIT_SSH_COMMAND=ssh -o BatchMode=yes")
|
||||
}
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// runGit runs git with args in dir, and gives back its output, or an
|
||||
// error saying plainly what went wrong for src.
|
||||
func runGit(ctx context.Context, git string, env []string, dir string, src Source, args ...string) ([]byte, error) {
|
||||
cmd := proc.CommandContext(ctx, git, append([]string{"-c", "protocol.ext.allow=never", "-c", "core.symlinks=false"}, args...)...)
|
||||
cmd.Dir, cmd.Env = dir, env
|
||||
var stderr strings.Builder
|
||||
cmd.Stderr = &stderr
|
||||
out, err := cmd.Output()
|
||||
if err == nil {
|
||||
return out, nil
|
||||
}
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return nil, fmt.Errorf("git took over %s to fetch %s and was stopped", gitTimeout, src.Repo)
|
||||
}
|
||||
var ee *exec.ExitError
|
||||
if !errors.As(err, &ee) {
|
||||
return nil, fmt.Errorf("couldn't run git: %w", err)
|
||||
}
|
||||
return nil, gitError(src, stderr.String())
|
||||
}
|
||||
|
||||
// gitError says what git's message means for the user.
|
||||
func gitError(src Source, msg string) error {
|
||||
low := strings.ToLower(msg)
|
||||
said := gitSaid(msg)
|
||||
host := gitHost(src.Repo)
|
||||
switch {
|
||||
case strings.Contains(low, "xcrun: error") || strings.Contains(low, "invalid active developer path") || strings.Contains(low, "no developer tools were found"):
|
||||
return errors.New("installing from a git repository runs git, and git isn't installed here: install Apple's command line tools (xcode-select --install) and try again")
|
||||
case strings.Contains(low, "host key verification failed"):
|
||||
return fmt.Errorf("SSH doesn't know %s's host key yet: connect to it once with ssh or git in a terminal to accept it, then try again (git said: %s)", host, said)
|
||||
case strings.Contains(low, "could not read username") || strings.Contains(low, "could not read password") ||
|
||||
strings.Contains(low, "terminal prompts disabled") || strings.Contains(low, "authentication failed") ||
|
||||
strings.Contains(low, "permission denied") || strings.Contains(low, "access denied") ||
|
||||
strings.Contains(low, "the requested url returned error: 401") || strings.Contains(low, "the requested url returned error: 403"):
|
||||
return fmt.Errorf("git couldn't sign in to %s. magpie runs your own git, so sign in the way git does there (a credential helper or an SSH key that can read the repository), check `git clone %s` works in a terminal, and try again (git said: %s)", host, src.Repo, said)
|
||||
case strings.Contains(low, "couldn't find remote ref") || strings.Contains(low, "unknown revision"):
|
||||
return fmt.Errorf("%s has no branch or tag %s", src.Repo, src.Ref)
|
||||
case strings.Contains(low, "repository not found") || strings.Contains(low, "does not appear to be a git repository") ||
|
||||
strings.Contains(low, "not found") && strings.Contains(low, "repository") || strings.Contains(low, "returned error: 404"):
|
||||
return fmt.Errorf("there's no git repository at %s, or it can't be read without signing in (git said: %s)", src.Repo, said)
|
||||
case strings.Contains(low, "could not resolve host") || strings.Contains(low, "connection refused") ||
|
||||
strings.Contains(low, "connection timed out") || strings.Contains(low, "network is unreachable") || strings.Contains(low, "couldn't connect"):
|
||||
return fmt.Errorf("git couldn't reach %s (git said: %s)", host, said)
|
||||
}
|
||||
return fmt.Errorf("git couldn't fetch %s: %s", src.Repo, said)
|
||||
}
|
||||
|
||||
// gitSaid is git's message, its last few lines, for an error.
|
||||
func gitSaid(s string) string {
|
||||
var keep []string
|
||||
for _, l := range strings.Split(strings.TrimSpace(s), "\n") {
|
||||
if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "hint:") {
|
||||
keep = append(keep, l)
|
||||
}
|
||||
}
|
||||
if len(keep) > 3 {
|
||||
keep = keep[len(keep)-3:]
|
||||
}
|
||||
out := strings.Join(keep, " / ")
|
||||
if r := []rune(out); len(r) > 400 {
|
||||
out = string(r[:399]) + "…"
|
||||
}
|
||||
if out == "" {
|
||||
out = "nothing"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// gitHost is the host of a repository's address, for a message.
|
||||
func gitHost(repo string) string {
|
||||
if u, err := url.Parse(repo); err == nil && u.Scheme != "" {
|
||||
if u.Host == "" {
|
||||
return repo
|
||||
}
|
||||
return u.Hostname()
|
||||
}
|
||||
if m := scpLike.FindStringSubmatch(repo); m != nil {
|
||||
return m[2]
|
||||
}
|
||||
return repo
|
||||
}
|
||||
|
||||
// fetchGit fetches the repository's ref (its default branch when "")
|
||||
// with the user's git, one commit deep, into a new folder, and gives it
|
||||
// back without its .git: what GitHub's tarball would have. Links are
|
||||
// checked out as small files holding where they point, as a tarball's
|
||||
// are left out: never followed out of the folder.
|
||||
func fetchGit(src Source) (string, error) {
|
||||
git := gitPath()
|
||||
if git == "" {
|
||||
return "", errNoGit()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)
|
||||
defer cancel()
|
||||
env := gitEnv(git)
|
||||
tmp, err := os.MkdirTemp("", skillTemp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
fail := func(err error) (string, error) {
|
||||
os.RemoveAll(tmp)
|
||||
return "", err
|
||||
}
|
||||
if _, err := runGit(ctx, git, env, tmp, src, "init", "-q"); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
ref := src.Ref
|
||||
if ref == "" {
|
||||
ref = "HEAD"
|
||||
}
|
||||
if _, err := runGit(ctx, git, env, tmp, src, "fetch", "-q", "--depth", "1", "--no-tags", "--", src.Repo, ref); err != nil {
|
||||
// a host that serves git over plain ("dumb") HTTP can't fetch one
|
||||
// commit deep: the whole history then
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "shallow") {
|
||||
return fail(err)
|
||||
}
|
||||
if _, err := runGit(ctx, git, env, tmp, src, "fetch", "-q", "--no-tags", "--", src.Repo, ref); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
if _, err := runGit(ctx, git, env, tmp, src, "-c", "advice.detachedHead=false", "checkout", "-q", "FETCH_HEAD"); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
out, err := runGit(ctx, git, env, tmp, src, "rev-parse", "FETCH_HEAD")
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(tmp, ".git")); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if size := dirSize(tmp); size > maxFetch {
|
||||
return fail(fmt.Errorf("%s is %s, over the %s magpie fetches", src.Repo, mb(size), mb(maxFetch)))
|
||||
}
|
||||
noteGitHead(tmp, strings.TrimSpace(string(out)))
|
||||
return tmp, nil
|
||||
}
|
||||
|
||||
func dirSize(dir string) int64 {
|
||||
var n int64
|
||||
filepath.Walk(dir, func(_ string, fi os.FileInfo, err error) error {
|
||||
if err == nil && fi.Mode().IsRegular() {
|
||||
n += fi.Size()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return n
|
||||
}
|
||||
|
||||
// gitRemoteHead asks the repository, with git ls-remote, which commit its
|
||||
// ref (its default branch when "") is at now. A ref that is a commit is
|
||||
// that commit.
|
||||
func gitRemoteHead(src Source) (string, error) {
|
||||
if hexRef.MatchString(src.Ref) {
|
||||
return strings.ToLower(src.Ref), nil
|
||||
}
|
||||
git := gitPath()
|
||||
if git == "" {
|
||||
return "", errNoGit()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)
|
||||
defer cancel()
|
||||
args := []string{"ls-remote", "--", src.Repo}
|
||||
if src.Ref == "" {
|
||||
args = append(args, "HEAD")
|
||||
} else {
|
||||
args = append(args, "refs/heads/"+src.Ref, "refs/tags/"+src.Ref, "refs/tags/"+src.Ref+"^{}")
|
||||
}
|
||||
out, err := runGit(ctx, git, gitEnv(git), os.TempDir(), src, args...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
refs := map[string]string{}
|
||||
for _, l := range strings.Split(string(out), "\n") {
|
||||
if sha, name, ok := strings.Cut(strings.TrimSpace(l), "\t"); ok {
|
||||
refs[name] = sha
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"HEAD", "refs/tags/" + src.Ref + "^{}", "refs/heads/" + src.Ref, "refs/tags/" + src.Ref} {
|
||||
if sha := refs[k]; hexRef.MatchString(sha) {
|
||||
return sha, nil
|
||||
}
|
||||
}
|
||||
if src.Ref == "" {
|
||||
return "", fmt.Errorf("%s names no default branch", src.Repo)
|
||||
}
|
||||
return "", fmt.Errorf("%s has no branch or tag %s any more", src.Repo, src.Ref)
|
||||
}
|
||||
|
||||
// checkGitSkill checks a skill from a git repository: git ls-remote says
|
||||
// which commit its ref is at; one the skill was fetched at is current,
|
||||
// and for another the repository is fetched and the skill's folder
|
||||
// compared with the library's, since a commit elsewhere in the repository
|
||||
// doesn't change it. When its files are the repository's, it gives back
|
||||
// the commit they're at and their hash, for the library to keep.
|
||||
func checkGitSkill(s *Skill, f *fetcher, asked map[string]string) (SkillCheck, string, string) {
|
||||
src := *s.Source
|
||||
c := SkillCheck{Name: s.Name, Status: "unknown"}
|
||||
head, ok := asked[src.Ref]
|
||||
if !ok {
|
||||
var err error
|
||||
if head, err = gitRemoteHead(src); err != nil {
|
||||
c.Error = err.Error()
|
||||
return c, "", ""
|
||||
}
|
||||
asked[src.Ref] = head
|
||||
}
|
||||
c.Commit = head
|
||||
if s.Commit != "" && strings.EqualFold(s.Commit, head) {
|
||||
c.Status = "current"
|
||||
return c, "", ""
|
||||
}
|
||||
tmp, err := f.fetch(src)
|
||||
if err != nil {
|
||||
c.Error = err.Error()
|
||||
return c, "", ""
|
||||
}
|
||||
from := filepath.Join(tmp, filepath.FromSlash(src.Path))
|
||||
if _, ok := readMeta(from); !ok {
|
||||
c.Error = fmt.Sprintf("%s has no SKILL.md at %s any more", src.Repo, src.Path)
|
||||
return c, "", ""
|
||||
}
|
||||
have := s.Hash
|
||||
if have == "" {
|
||||
have = hashDir(skillDir(s.Name))
|
||||
}
|
||||
if theirs := hashDir(from); theirs == "" || theirs != have {
|
||||
c.Status = "update"
|
||||
return c, "", ""
|
||||
}
|
||||
c.Status = "current"
|
||||
if h := gitHeadOf(tmp); h != "" {
|
||||
c.Commit = h
|
||||
}
|
||||
return c, c.Commit, have
|
||||
}
|
||||
|
||||
// isGit is whether what the user typed is a git repository's address
|
||||
// magpie fetches from.
|
||||
func isGit(s string) bool {
|
||||
_, ok, err := gitSource(s)
|
||||
return ok && err == nil
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// sunset on Discord: skills from GitLab, and from a company's own GitLab
|
||||
// on its intranet. What the user types is read as a git repository, with
|
||||
// a GitLab page's ref and folder; what git would take as an option, or a
|
||||
// transport that runs a command, is refused.
|
||||
func TestGitSourceReads(t *testing.T) {
|
||||
for _, c := range []struct{ in, repo, ref, path string }{
|
||||
{"https://gitlab.com/group/skills", "https://gitlab.com/group/skills", "", ""},
|
||||
{"https://gitlab.com/group/skills.git", "https://gitlab.com/group/skills.git", "", ""},
|
||||
{"https://git.corp.example/team/sub/deep/skills/", "https://git.corp.example/team/sub/deep/skills", "", ""},
|
||||
{"https://git.corp.example/team/sub/skills/-/tree/main/skills/pdf", "https://git.corp.example/team/sub/skills", "main", "skills/pdf"},
|
||||
{"https://gitlab.com/g/r/-/tree/HEAD", "https://gitlab.com/g/r", "", ""},
|
||||
{"https://gitlab.com/g/r/-/blob/v1.2/skills/pdf/SKILL.md", "https://gitlab.com/g/r", "v1.2", "skills/pdf"},
|
||||
{"https://gitea.corp/g/r/src/branch/dev/skills", "https://gitea.corp/g/r", "dev", "skills"},
|
||||
{"http://10.0.0.5/g/r.git", "http://10.0.0.5/g/r.git", "", ""},
|
||||
{"git@gitlab.corp.example:team/sub/skills.git", "git@gitlab.corp.example:team/sub/skills.git", "", ""},
|
||||
{"git@gitlab:team/skills.git", "git@gitlab:team/skills.git", "", ""},
|
||||
{"ssh://git@gitlab.corp:2222/team/skills.git", "ssh://git@gitlab.corp:2222/team/skills.git", "", ""},
|
||||
{"file:///srv/git/skills.git", "file:///srv/git/skills.git", "", ""},
|
||||
{"gitlab.com/group/skills", "https://gitlab.com/group/skills", "", ""},
|
||||
} {
|
||||
src, ok, err := gitSource(c.in)
|
||||
if !ok || err != nil {
|
||||
t.Errorf("%s: ok %v, %v", c.in, ok, err)
|
||||
continue
|
||||
}
|
||||
if src.Kind != "git" || src.Repo != c.repo || src.Ref != c.ref || src.Path != c.path {
|
||||
t.Errorf("%s: read as %+v", c.in, src)
|
||||
}
|
||||
// what the page shows is read back as the same source
|
||||
if back, _, err := gitSource(src.String()); err != nil || !sameGitRepo(back.Repo, src.Repo) || back.Ref != src.Ref || back.Path != src.Path {
|
||||
t.Errorf("%s: shown as %s, read back as %+v (%v)", c.in, src.String(), back, err)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{"owner/repo", "C:/Users/me/skills", "hello", "", "skills folder"} {
|
||||
if _, ok, _ := gitSource(in); ok {
|
||||
t.Errorf("%q read as a git repository", in)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{
|
||||
"-uhack", "--upload-pack=touch /tmp/x", "ext::sh -c touch% /tmp/x", "file::/tmp/x", "fd::3",
|
||||
"https://me:glpat-secret@gitlab.com/g/r.git", "ftp://host/g/r", "https://gitlab.com/",
|
||||
"https://gitlab.com/g/r/-/tree/--upload-pack=x/skills", "https://gitlab.com/g/r/-/tree/main/../../x",
|
||||
"git@-oProxyCommand=x:g/r",
|
||||
} {
|
||||
if _, ok, err := gitSource(in); ok && err == nil {
|
||||
t.Errorf("%q isn't refused", in)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gitRepo makes a bare repository with skills in it, and gives its
|
||||
// file:// address and a function to commit files to it. git runs with no
|
||||
// system or user config of the machine's (no credential helper, no
|
||||
// Keychain).
|
||||
func gitRepo(t *testing.T, files map[string]string) (string, func(map[string]string)) {
|
||||
t.Helper()
|
||||
git, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
t.Skip("git isn't installed")
|
||||
}
|
||||
old := gitPath
|
||||
gitPath = func() string { return git }
|
||||
t.Cleanup(func() { gitPath = old })
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig"))
|
||||
root := t.TempDir()
|
||||
bare, work := filepath.Join(root, "skills.git"), filepath.Join(root, "work")
|
||||
run := func(dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command(git, append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false"}, args...)...)
|
||||
cmd.Dir = dir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
run(root, "init", "-q", "--bare", bare)
|
||||
run(root, "init", "-q", work)
|
||||
commit := func(files map[string]string) {
|
||||
for p, body := range files {
|
||||
write(t, filepath.Join(work, filepath.FromSlash(p)), body)
|
||||
}
|
||||
run(work, "add", "-A")
|
||||
run(work, "commit", "-q", "-m", "skills")
|
||||
run(work, "push", "-q", bare, "HEAD:refs/heads/main")
|
||||
}
|
||||
commit(files)
|
||||
p := filepath.ToSlash(bare)
|
||||
if !strings.HasPrefix(p, "/") {
|
||||
p = "/" + p // C:/… on Windows
|
||||
}
|
||||
return "file://" + p, commit
|
||||
}
|
||||
|
||||
func TestInstallFromGitRepo(t *testing.T) {
|
||||
sandbox(t)
|
||||
addr, commit := gitRepo(t, map[string]string{
|
||||
"skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs\n---\nv1\n",
|
||||
"skills/pdf/notes.md": "one",
|
||||
"skills/review/SKILL.md": "---\nname: review\ndescription: Reviews\n---\n",
|
||||
"README.md": "hi",
|
||||
})
|
||||
p, err := ProbeSkills(addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Kind != "git" || len(p.Candidates) != 2 || p.Candidates[0].Path != "skills/pdf" {
|
||||
t.Fatalf("probe %+v", p)
|
||||
}
|
||||
if _, err := InstallSkills(addr, []string{"skills/pdf"}, []string{"claude"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, _ := load()
|
||||
s := l.skill("pdf")
|
||||
if s == nil || s.Source.Kind != "git" || s.Source.Repo != addr || s.Source.Path != "skills/pdf" || s.Hash == "" || len(s.Commit) != 40 {
|
||||
t.Fatalf("installed as %+v %+v", s, s.Source)
|
||||
}
|
||||
if b, err := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")); err != nil || string(b) != "one" {
|
||||
t.Fatalf("notes.md: %q %v", b, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(skillDir("pdf"), ".git")); err == nil {
|
||||
t.Fatal("the skill has git's folder")
|
||||
}
|
||||
installedAt := s.Commit
|
||||
|
||||
// the repository changes the skill: a check says so, an update takes it
|
||||
commit(map[string]string{"skills/pdf/notes.md": "two"})
|
||||
checks, err := CheckSkills()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(checks) != 1 || checks[0].Status != "update" {
|
||||
t.Fatalf("check %+v", checks)
|
||||
}
|
||||
if _, err := UpdateSkill("pdf", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")); string(b) != "two" {
|
||||
t.Fatalf("not updated: %q", b)
|
||||
}
|
||||
l, _ = load()
|
||||
updatedAt := l.skill("pdf").Commit
|
||||
if len(updatedAt) != 40 || updatedAt == installedAt {
|
||||
t.Fatalf("commit after the update %q (was %q)", updatedAt, installedAt)
|
||||
}
|
||||
if checks, _ := CheckSkills(); len(checks) != 1 || checks[0].Status != "current" {
|
||||
t.Fatalf("after the update %+v", checks)
|
||||
}
|
||||
|
||||
// a commit elsewhere in the repository leaves the skill current, at it
|
||||
commit(map[string]string{"README.md": "changed"})
|
||||
if checks, _ := CheckSkills(); len(checks) != 1 || checks[0].Status != "current" || checks[0].Error != "" {
|
||||
t.Fatalf("after a commit elsewhere %+v", checks)
|
||||
}
|
||||
l, _ = load()
|
||||
if c := l.skill("pdf").Commit; c == updatedAt || len(c) != 40 {
|
||||
t.Fatalf("the commit found the same isn't kept: %q", c)
|
||||
}
|
||||
|
||||
// installing it again is had already
|
||||
res, err := InstallSkills(addr, []string{"skills/pdf"}, nil)
|
||||
if err != nil || len(res.Had) != 1 {
|
||||
t.Fatalf("again: %+v %v", res, err)
|
||||
}
|
||||
|
||||
// changed here, an update is refused, naming the repository
|
||||
write(t, filepath.Join(skillDir("pdf"), "notes.md"), "mine")
|
||||
commit(map[string]string{"skills/pdf/notes.md": "three"})
|
||||
_, err = UpdateSkill("pdf", false)
|
||||
var edited *EditedError
|
||||
if !errors.As(err, &edited) || !strings.Contains(err.Error(), "fetched from "+addr) {
|
||||
t.Fatalf("an update over a change here: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A GitLab page's address of a folder on a branch installs that folder
|
||||
// from that branch.
|
||||
func TestGitTreeURLInstallsFolder(t *testing.T) {
|
||||
sandbox(t)
|
||||
addr, commit := gitRepo(t, map[string]string{"skills/a/SKILL.md": "---\nname: a\ndescription: on main\n---\n"})
|
||||
_ = commit
|
||||
p, err := ProbeSkills(addr + "/-/tree/main/skills/a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(p.Candidates) != 1 || p.Candidates[0].Name != "a" || p.Candidates[0].Path != "skills/a" {
|
||||
t.Fatalf("candidates %+v", p.Candidates)
|
||||
}
|
||||
if _, err := ProbeSkills(addr + "/-/tree/nope/skills/a"); err == nil || !strings.Contains(err.Error(), "no branch or tag nope") {
|
||||
t.Fatalf("a missing branch: %v", err)
|
||||
}
|
||||
if _, err := ProbeSkills(addr + "/-/tree/main/skills/zz"); err == nil || !strings.Contains(err.Error(), "has no folder skills/zz") {
|
||||
t.Fatalf("a missing folder: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Without git, the probe says git is needed; nothing else is tried.
|
||||
func TestGitMissingSaysSo(t *testing.T) {
|
||||
sandbox(t)
|
||||
old := gitPath
|
||||
gitPath = func() string { return "" }
|
||||
t.Cleanup(func() { gitPath = old })
|
||||
_, err := ProbeSkills("https://gitlab.example.com/team/skills.git")
|
||||
if err == nil || !strings.Contains(err.Error(), "git isn't installed") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A host that wants a sign-in git can't give it: the error says git
|
||||
// couldn't sign in, and how the user's own git signs in, never waits for
|
||||
// a password.
|
||||
func TestGitSignInRefusedSaysSo(t *testing.T) {
|
||||
sandbox(t)
|
||||
gitRepo(t, map[string]string{"a/SKILL.md": "---\nname: a\n---\n"})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="GitLab"`)
|
||||
w.WriteHeader(401)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
_, err := ProbeSkills(srv.URL + "/team/private-skills.git")
|
||||
if err == nil || !strings.Contains(err.Error(), "git couldn't sign in to 127.0.0.1") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// What git would read as an option, or a transport that runs a command,
|
||||
// never reaches git.
|
||||
func TestGitRefusesOptionsAndTransports(t *testing.T) {
|
||||
sandbox(t)
|
||||
old := gitPath
|
||||
gitPath = func() string { t.Error("git ran"); return "" }
|
||||
t.Cleanup(func() { gitPath = old })
|
||||
for in, want := range map[string]string{
|
||||
"-uhack": "can't start with -",
|
||||
"--upload-pack=touch x": "can't start with -",
|
||||
"ext::sh -c touch% x": "transport (ext::)",
|
||||
"file::/tmp/x": "transport (file::)",
|
||||
"https://u:tok@gitlab.com/g": "leave the password or token out",
|
||||
} {
|
||||
if _, err := ProbeSkills(in); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%q: %v", in, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// git's own words, as it prints them, read as what they mean.
|
||||
func TestGitErrorsSaid(t *testing.T) {
|
||||
src := Source{Kind: "git", Repo: "https://git.corp.example/team/skills.git", Ref: "dev"}
|
||||
for msg, want := range map[string]string{
|
||||
"fatal: could not read Username for 'https://git.corp.example': terminal prompts disabled\n": "git couldn't sign in to git.corp.example",
|
||||
"remote: HTTP Basic: Access denied\nfatal: Authentication failed for 'https://git.corp.example/team/skills.git/'\n": "git couldn't sign in",
|
||||
"git@git.corp.example: Permission denied (publickey).\nfatal: Could not read from remote repository.\n": "git couldn't sign in",
|
||||
"Host key verification failed.\nfatal: Could not read from remote repository.\n": "host key",
|
||||
"fatal: couldn't find remote ref dev\n": "has no branch or tag dev",
|
||||
"fatal: unable to access 'https://git.corp.example/team/skills.git/': Could not resolve host: git.corp.example\n": "couldn't reach git.corp.example",
|
||||
"xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun\n": "git isn't installed",
|
||||
} {
|
||||
if err := gitError(src, msg); !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%q said as %q", msg, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
-28
@@ -34,7 +34,8 @@ type Skill struct {
|
||||
// Hash is of the skill's files as last fetched from GitHub, and Commit
|
||||
// the last commit to have touched its folder there, once a check has
|
||||
// found the two to agree: together they tell whether GitHub has
|
||||
// changed the skill since.
|
||||
// changed the skill since. For one from another git repository,
|
||||
// Commit is the commit of the repository it was fetched at.
|
||||
Hash string `json:"hash,omitempty"`
|
||||
Commit string `json:"commit,omitempty"`
|
||||
// From is the repository one not installed from GitHub was found to
|
||||
@@ -43,11 +44,12 @@ type Skill struct {
|
||||
}
|
||||
|
||||
// Source is where a skill came from: a GitHub repository it can be updated
|
||||
// from, or a folder on this machine the library links to, so that editing
|
||||
// the folder is editing the skill.
|
||||
// from, another git repository (fetched with the user's own git), or a
|
||||
// folder on this machine the library links to, so that editing the folder
|
||||
// is editing the skill.
|
||||
type Source struct {
|
||||
Kind string `json:"kind"` // github | folder
|
||||
Repo string `json:"repo,omitempty"`
|
||||
Kind string `json:"kind"` // github | git | folder
|
||||
Repo string `json:"repo,omitempty"` // owner/repo for github, the address git fetches for git
|
||||
Ref string `json:"ref,omitempty"`
|
||||
Path string `json:"path,omitempty"` // in the repository
|
||||
Dir string `json:"dir,omitempty"` // the folder, for kind folder
|
||||
@@ -60,6 +62,9 @@ func (s *Source) String() string {
|
||||
if s.Kind == "folder" {
|
||||
return s.Dir
|
||||
}
|
||||
if s.Kind == "git" {
|
||||
return gitURL(s)
|
||||
}
|
||||
u := "https://github.com/" + s.Repo
|
||||
if s.Ref != "" || s.Path != "" {
|
||||
ref := s.Ref
|
||||
@@ -747,12 +752,20 @@ var tarballURL = func(repo, ref string) string {
|
||||
return "https://codeload.github.com/" + repo + "/tar.gz/" + url.PathEscape(ref)
|
||||
}
|
||||
|
||||
// fetch downloads the repository into a new folder and gives it back. A
|
||||
// remote is whether a skill's source is a repository it is fetched from
|
||||
// again to update: GitHub, or another git repository.
|
||||
func (s *Source) remote() bool { return s != nil && (s.Kind == "github" || s.Kind == "git") }
|
||||
|
||||
// fetch downloads the repository into a new folder and gives it back; one
|
||||
// not on GitHub is fetched with the user's git (fetchGit). A
|
||||
// repository codeload doesn't hand out without a token, a private one, is
|
||||
// asked of GitHub's API with the user's GitHub token (37FlowAI on X): the
|
||||
// API redirects to codeload, and the token, sent to the API's host alone,
|
||||
// isn't carried over to it.
|
||||
func fetch(src Source) (string, error) {
|
||||
if src.Kind == "git" {
|
||||
return fetchGit(src)
|
||||
}
|
||||
c := &http.Client{Timeout: 2 * time.Minute}
|
||||
get := func(u string) (*http.Response, bool, error) {
|
||||
req, _ := http.NewRequest("GET", u, nil)
|
||||
@@ -994,12 +1007,16 @@ func skillsCommand(input string) string {
|
||||
}
|
||||
|
||||
// ProbeSkills looks for skills at what the user typed: a GitHub repository
|
||||
// (or a folder in one), a folder on this machine, or a skills CLI command
|
||||
// for either.
|
||||
// (or a folder in one), any other git repository (GitLab, one on a
|
||||
// company's own server; fetched with the user's git), a folder on this
|
||||
// machine, or a skills CLI command for one of them.
|
||||
func ProbeSkills(input string) (*Probe, error) {
|
||||
input = strings.TrimSpace(skillsCommand(input))
|
||||
if input == "" {
|
||||
return nil, fmt.Errorf("paste a GitHub link or a folder's path")
|
||||
return nil, fmt.Errorf("paste a GitHub or git repository's link or a folder's path")
|
||||
}
|
||||
if strings.HasPrefix(input, "-") {
|
||||
return nil, fmt.Errorf("a repository's address can't start with -")
|
||||
}
|
||||
sweepStaleDownloads()
|
||||
|
||||
@@ -1011,12 +1028,15 @@ func ProbeSkills(input string) (*Probe, error) {
|
||||
}
|
||||
p.Kind, p.root, p.src = "folder", dir, Source{Kind: "folder", Dir: dir}
|
||||
p.Candidates = candidates(dir, "")
|
||||
} else if src, ok := githubSource(input); ok {
|
||||
} else if src, ok := githubSource(input); ok || isGit(input) {
|
||||
if !ok {
|
||||
src, _, _ = gitSource(input)
|
||||
}
|
||||
tmp, err := fetch(src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Kind, p.root, p.src = "github", tmp, src
|
||||
p.Kind, p.root, p.src = src.Kind, tmp, src
|
||||
if _, err := os.Stat(filepath.Join(tmp, filepath.FromSlash(src.Path))); src.Path != "" && err != nil {
|
||||
os.RemoveAll(tmp)
|
||||
return nil, fmt.Errorf("%s has no folder %s", src.Repo, src.Path)
|
||||
@@ -1024,8 +1044,10 @@ func ProbeSkills(input string) (*Probe, error) {
|
||||
p.Candidates = candidates(tmp, src.Path)
|
||||
p.Left = tookLeftOut(tmp, src.Path)
|
||||
keepProbe(input, p, tmp)
|
||||
} else if _, ok, err := gitSource(input); ok && err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return nil, fmt.Errorf("that's neither a GitHub repository nor a folder's full path")
|
||||
return nil, fmt.Errorf("that's neither a git repository's link (GitHub, GitLab or another host) nor a folder's full path")
|
||||
}
|
||||
if p.Candidates == nil {
|
||||
p.Candidates = []Candidate{}
|
||||
@@ -1104,6 +1126,8 @@ func fromSameSource(s *Skill, src Source, path, from string) bool {
|
||||
switch src.Kind {
|
||||
case "github":
|
||||
return strings.EqualFold(s.Source.Repo, src.Repo) && s.Source.Path == path
|
||||
case "git":
|
||||
return sameGitRepo(s.Source.Repo, src.Repo) && s.Source.Path == path
|
||||
case "folder":
|
||||
return realDir(s.Source.Dir) == realDir(from)
|
||||
}
|
||||
@@ -1152,7 +1176,7 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i
|
||||
switch {
|
||||
case src.Kind == "folder" && linked(dir) && realDir(dir) == realDir(from):
|
||||
src.Dir = from
|
||||
case src.Kind == "github" && !linked(dir) && sameTree(dir, from):
|
||||
case src.remote() && !linked(dir) && sameTree(dir, from):
|
||||
src.Path = c.Path
|
||||
case src.Kind == "folder" && realDir(from) == realDir(dir):
|
||||
// a folder already in the library's own (#595): linked to
|
||||
@@ -1193,6 +1217,9 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i
|
||||
in.added = append(in.added, c.Name)
|
||||
}
|
||||
sk := &Skill{Name: c.Name, Source: &src, Agents: slices.Clone(agents)}
|
||||
if src.Kind == "git" {
|
||||
sk.Hash, sk.Commit = hashDir(dir), gitHeadOf(p.root)
|
||||
}
|
||||
if src.Kind == "github" {
|
||||
sk.Hash = hashDir(dir)
|
||||
// every skill the picker showed was offered: a check
|
||||
@@ -1228,7 +1255,7 @@ func UpdateSkill(name string, replace bool) (*Result, error) {
|
||||
f := &fetcher{}
|
||||
defer f.clean()
|
||||
if edited, _ := l.editState(s, Targets()); edited && !replace {
|
||||
return nil, &EditedError{Name: name}
|
||||
return nil, editedError(s)
|
||||
}
|
||||
up, err := f.prepare(s)
|
||||
if err != nil {
|
||||
@@ -1239,7 +1266,7 @@ func UpdateSkill(name string, replace bool) (*Result, error) {
|
||||
if s := l.skill(name); s != nil && !replace {
|
||||
// changed while it was fetched
|
||||
if edited, _ := l.editState(s, targets); edited {
|
||||
return &EditedError{Name: name}
|
||||
return editedError(s)
|
||||
}
|
||||
}
|
||||
return up.apply(l, targets)
|
||||
@@ -1303,7 +1330,7 @@ func updateSkills(names []string) (*Result, error) {
|
||||
for _, up := range ups {
|
||||
if s := l.skill(up.name); s != nil {
|
||||
if edited, _ := l.editState(s, targets); edited {
|
||||
failed = append(failed, Problem{What: "skill:" + up.name, Error: (&EditedError{Name: up.name}).Error()})
|
||||
failed = append(failed, Problem{What: "skill:" + up.name, Error: editedError(s).Error()})
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -1327,10 +1354,10 @@ func updateSkills(names []string) (*Result, error) {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// updatable is whether a skill can be fetched again: one from GitHub, or
|
||||
// one CC Switch installed from there.
|
||||
// updatable is whether a skill can be fetched again: one from GitHub or
|
||||
// another git repository, or one CC Switch installed from GitHub.
|
||||
func updatable(s *Skill) bool {
|
||||
if s.Source != nil && s.Source.Kind == "github" {
|
||||
if s.Source.remote() {
|
||||
return true
|
||||
}
|
||||
_, ok := ccSwitchOrigin(s)
|
||||
@@ -1382,21 +1409,22 @@ func (f *fetcher) clean() {
|
||||
|
||||
// skillUpdate is a skill fetched again, ready to take the old one's place.
|
||||
type skillUpdate struct {
|
||||
name string
|
||||
src *Source
|
||||
adopt bool
|
||||
from string
|
||||
name string
|
||||
src *Source
|
||||
adopt bool
|
||||
from string
|
||||
commit string // the commit a git repository was fetched at
|
||||
}
|
||||
|
||||
func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) {
|
||||
name := s.Name
|
||||
src, adopt := s.Source, false
|
||||
if src == nil || src.Kind != "github" {
|
||||
if !src.remote() {
|
||||
// one CC Switch installed from GitHub becomes the library's own,
|
||||
// fetched from there, leaving CC Switch's folder as it is
|
||||
o, ok := ccSwitchOrigin(s)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s isn't from GitHub; it's kept as it is", name)
|
||||
return nil, fmt.Errorf("%s isn't from GitHub or a git repository; it's kept as it is", name)
|
||||
}
|
||||
src, adopt = &o, true
|
||||
} else {
|
||||
@@ -1422,7 +1450,11 @@ func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) {
|
||||
if _, ok := readMeta(from); !ok {
|
||||
return nil, fmt.Errorf("%s has no SKILL.md at %s any more", src.Repo, src.Path)
|
||||
}
|
||||
return &skillUpdate{name: name, src: src, adopt: adopt, from: from}, nil
|
||||
up := &skillUpdate{name: name, src: src, adopt: adopt, from: from}
|
||||
if src.Kind == "git" {
|
||||
up.commit = gitHeadOf(tmp)
|
||||
}
|
||||
return up, nil
|
||||
}
|
||||
|
||||
// apply puts the fetched skill in the old one's place; the agents' links
|
||||
@@ -1465,8 +1497,8 @@ func (up *skillUpdate) apply(l *Library, targets []*Target) error {
|
||||
s.Source = up.src
|
||||
}
|
||||
// the commit it's at is known again once a check finds the files
|
||||
// GitHub has to be these
|
||||
s.Hash, s.Commit = hash, ""
|
||||
// GitHub has to be these; a git repository's is the one fetched
|
||||
s.Hash, s.Commit = hash, up.commit
|
||||
}
|
||||
forgetCheck(name)
|
||||
if old == "" {
|
||||
|
||||
@@ -326,7 +326,7 @@ type SkillView struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Kind string `json:"kind"` // github, folder, or "" for one kept in the library
|
||||
Kind string `json:"kind"` // github, git, folder, or "" for one kept in the library
|
||||
Origin string `json:"origin,omitempty"` // on GitHub, as CC Switch installed it: it can be updated from there
|
||||
Repo string `json:"repo,omitempty"` // the repository it came from, however it came in, for the page to group by
|
||||
Icon string `json:"icon,omitempty"`
|
||||
|
||||
@@ -340,12 +340,12 @@ func (m *model) openLibAdd() {
|
||||
input: newInput("filter"),
|
||||
items: []agent.Option{
|
||||
{Value: "mcp server", Note: "a URL, or a command it runs"},
|
||||
{Value: "skills", Note: "from a GitHub repository, or a folder on this machine"},
|
||||
{Value: "skills", Note: "from GitHub, GitLab or any git repository, or a folder on this machine"},
|
||||
},
|
||||
onPick: func(v string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
if v == "skills" {
|
||||
in := newInput("a GitHub link (owner/repo, or a folder in one) or a folder's full path")
|
||||
in := newInput("owner/repo, a GitHub or GitLab link, a git address (git@host:group/repo.git), or a folder's full path")
|
||||
in.CharLimit = 400
|
||||
return askMsg{ask{crumbs: []string{"library", "add", "skills"}, input: in,
|
||||
hint: "magpie looks there for skills, then you pick one",
|
||||
|
||||
Reference in New Issue
Block a user