import{spawn as D}from"child_process";import{existsSync as O,mkdirSync as F,readdirSync as U,statSync as K,readFileSync as z}from"fs";import{resolve as G,join as A,basename as W}from"path";var E=".zibby/repos";function I(m,n,r={}){return new Promise((i,t)=>{let e=D(m,{cwd:n,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...r}}),s="",a="";e.stdout.on("data",o=>{s+=o.toString()}),e.stderr.on("data",o=>{a+=o.toString()}),e.on("close",o=>{o!==0?t(new Error(`Exit ${o}: ${a.trim()||s.trim()}`)):i(s.trim())}),e.on("error",o=>t(o))})}var j={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
You can clone and explore git repositories locally for codebase analysis:
- git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
- git_list_repos: List locally cloned repos
- git_explore: Quick overview of a cloned repo's structure (key files, package.json, routes, etc.)

When a test ticket lacks context, use this workflow:
1. Clone the relevant repo with git_checkout
2. Use git_explore to understand the project structure
3. Use shell commands (grep, cat) to read specific files for deeper understanding
4. Use GitHub/GitLab skills to read related PRs and commits
5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(m,n,r){let i=r?.options?.workspace||process.cwd();try{switch(m){case"git_checkout":return await Q(n,i);case"git_list_repos":return V(n,i);case"git_explore":return Y(n,i);default:return JSON.stringify({error:`Unknown tool: ${m}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"git_checkout",description:"Clone a git repository locally (or pull latest if already cloned). Auto-authenticates with GitHub/GitLab tokens if available.",input_schema:{type:"object",properties:{url:{type:"string",description:'Repository URL (e.g. "https://github.com/org/repo" or "org/repo" shorthand for GitHub)'},branch:{type:"string",description:"Branch to checkout (default: repo default branch)"},shallow:{type:"boolean",description:"Shallow clone with depth 1 (default: true, faster)"},name:{type:"string",description:"Local directory name override (default: repo name from URL)"}},required:["url"]}},{name:"git_list_repos",description:"List locally cloned repositories",input_schema:{type:"object",properties:{}}},{name:"git_explore",description:"Quick structural overview of a cloned repo: key files, package.json info, directory tree (top 2 levels), detected framework/language",input_schema:{type:"object",properties:{repo:{type:"string",description:"Repo name (as listed by git_list_repos)"},depth:{type:"number",description:"Directory tree depth (default: 2)"}},required:["repo"]}}]};async function Q(m,n){let{url:r,branch:i,shallow:t=!0,name:e}=m;!r.includes("://")&&!r.startsWith("git@")&&(r=`https://github.com/${r}`);let s=e||W(r.replace(/\.git$/,"")),a=G(n,E);F(a,{recursive:!0});let o=A(a,s),p=r,d=process.env.GITHUB_TOKEN,l=process.env.GITLAB_TOKEN,c=process.env.GITLAB_URL;if(r.includes("github.com")&&d)p=r.replace("https://github.com",`https://x-access-token:${d}@github.com`);else if(l&&c)try{let u=new URL(c).host;r.includes(u)&&(p=r.replace(`https://${u}`,`https://oauth2:${l}@${u}`))}catch{}if(O(A(o,".git"))){let u=i?`git -C "${o}" fetch origin ${i} && git -C "${o}" checkout ${i} && git -C "${o}" pull origin ${i}`:`git -C "${o}" pull`;await I(u,n);let _=await I(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"updated",repo:s,path:o,branch:i||"default",head:_})}let h=["git","clone"];t&&h.push("--depth","1"),i&&h.push("--branch",i),h.push(`"${p}"`,`"${o}"`),await I(h.join(" "),n);let y=await I(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"cloned",repo:s,path:o,branch:i||"default",shallow:t,head:y})}function V(m,n){let r=G(n,E);if(!O(r))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let t of U(r,{withFileTypes:!0})){if(!t.isDirectory())continue;let e=A(r,t.name);if(!O(A(e,".git")))continue;let s=K(e);i.push({name:t.name,path:e,lastModified:s.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:r})}function Y(m,n){let{repo:r,depth:i=2}=m,t=G(n,E,r);if(!O(t))return JSON.stringify({error:`Repo not found: ${r}. Run git_checkout first.`});let e={repo:r,path:t},s=A(t,"package.json");if(O(s))try{let h=JSON.parse(z(s,"utf-8"));e.packageJson={name:h.name,version:h.version,scripts:h.scripts?Object.keys(h.scripts):[],dependencies:h.dependencies?Object.keys(h.dependencies).slice(0,30):[],devDependencies:h.devDependencies?Object.keys(h.devDependencies).slice(0,20):[]},h.dependencies?.react?e.framework="React":h.dependencies?.next?e.framework="Next.js":h.dependencies?.vue?e.framework="Vue":h.dependencies?.angular?e.framework="Angular":h.dependencies?.express?e.framework="Express":h.dependencies?.fastify&&(e.framework="Fastify")}catch{}let a=A(t,"pyproject.toml");O(a)&&(e.language="Python");let o=A(t,"go.mod");O(o)&&(e.language="Go");let p=A(t,"Cargo.toml");O(p)&&(e.language="Rust"),O(s)&&(e.language=e.language||"JavaScript/TypeScript");let d=[];function l(h,y,u){if(u>i)return;let _;try{_=U(h,{withFileTypes:!0})}catch{return}let v=_.filter(f=>!f.name.startsWith(".")&&f.name!=="node_modules"&&f.name!=="__pycache__"&&f.name!=="dist"&&f.name!=="build"&&f.name!==".git").sort((f,g)=>f.isDirectory()!==g.isDirectory()?f.isDirectory()?-1:1:f.name.localeCompare(g.name));for(let f of v){let g=f.isDirectory();d.push(`${y}${g?"\u{1F4C1}":"\u{1F4C4}"} ${f.name}`),g&&u<i&&l(A(h,f.name),`${y}  `,u+1)}}l(t,"",1),e.tree=d.slice(0,80),d.length>80&&(e.treeTruncated=!0);let c=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return e.keyFilesFound=c.filter(h=>O(A(t,h))),JSON.stringify(e)}import{existsSync as Z}from"fs";import{fileURLToPath as X}from"url";import{dirname as ee,resolve as te}from"path";import{resolveIntegrationToken as C}from"@zibby/core/backend-client.js";var L=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),be=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function re(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let m=ee(X(import.meta.url)),n=te(m,"..","bin","mcp-skill.mjs");return Z(n)?n:null}async function b(m,n={}){let{token:r}=await C("github"),i=m.startsWith("https://")?m:`https://api.github.com${m}`,t={Authorization:`Bearer ${r}`,Accept:n.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...n.body?{"Content-Type":"application/json"}:{}},e=await fetch(i,{method:n.method||"GET",headers:t,body:n.body?JSON.stringify(n.body):void 0});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`GitHub API ${e.status}: ${s.slice(0,300)}`)}return n.raw?e.text():e.json()}var q={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:L.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
You have access to the user's GitHub repositories. Available tools:

### Discovery
- github_list_repos: Lists ALL accessible repos (personal + orgs, private + public, up to 200 repos). Use to find a RELATED repo worth cloning for cross-repo context.
- github_search_repos: Search for a specific repo by name (e.g., "electron", "my-app")
- github_get_user: Get authenticated user's profile
- github_list_orgs: List organizations with accessible repos

### Clone & Code Reading
- github_clone: Clone a repo locally. If the user specifies a destination (e.g. "to my Desktop", "to ~/Downloads"), pass that as the destination param. Otherwise it defaults to ~/zibby-repos/. ALWAYS show the contents field in the response.
- github_get_file: Read a file's content from a repo (without cloning)
- github_list_commits: List recent commits
- github_get_commit: Get commit details and diff

### Issues & PRs
- github_search_issues: Search issues and PRs
- github_search_code: Search code across repos
- github_get_pr: Get PR details
- github_get_pr_diff: Get PR diff
- github_list_pr_files: List PR changed files
- github_list_pr_comments: Get PR comments
- github_get_review_thread: Read a review-comment THREAD (root + replies) with its diff context, given any comment id in it
- github_reply_review_thread: Reply IN-THREAD to an existing review-comment thread (conversational reply, not a new review)
- github_reply_issue_comment: Reply on the PR's top-level conversation (for non-inline/summary comments)
- github_create_review: Post a review on a PR \u2014 a summary body plus optional inline comments on specific file/line positions, with an event (COMMENT, APPROVE, or REQUEST_CHANGES)
- github_create_pr: OPEN a pull request (POST /repos/{owner}/{repo}/pulls). The branch must already be pushed. Returns the REAL pr_url from GitHub (never fabricate a PR url). Expected business errors (no commits between base and head, a PR already exists, base==head) come back as { success:false, skippedReason } \u2014 not a hard failure.
- github_merge_pr: MERGE a pull request (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is 'merge'|'squash'|'rebase' (default 'squash'). Returns { success:true, merged:true, sha } on a real merge. Expected non-mergeable cases (405 = draft / failing checks / not mergeable, 409 = head sha moved / conflict, 404) come back as { success:false, skippedReason } \u2014 not a hard failure.
- github_create_issue: Create new issue
- github_list_issues: List issues in a repo (filter by state/labels/since cursor) \u2014 excludes PRs
- github_get_issue: Get a single issue's full detail (title, body, state, labels, assignee, url)
- github_get_issue_comments: Get the comment thread on an issue
- github_add_issue_comment: Add a comment to an issue (also used to record a PR link)
- github_close_issue / github_reopen_issue: Close (optionally completed/not_planned) or reopen an issue
- github_label_issue: Add / set / remove labels on an issue

### Important: "Check out" / "Clone"
When user says "check out repo-name" or "clone repo-name":
1. Call github_clone. Pass the user's requested destination if given (e.g. "~/Downloads", "/Users/me/Desktop"). The tool handles ~ expansion and absolute paths.
2. Display the path and contents field (directory listing)
3. STOP. Do not offer to inspect files or ask what to do next.

When user just wants to "look at" or "read" files (not clone):
- Use github_get_file to read individual files via API`,resolve(){let m=re();if(!m)return{command:null,args:[],env:{},description:this.description};let n={};for(let r of this.envKeys)process.env[r]&&(n[r]=process.env[r]);return{type:"stdio",command:"node",args:[m,"../dist/github.js","githubSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(m,n){try{switch(m){case"github_search_issues":{let r=n.query;if(!r)return JSON.stringify({error:"query is required"});let i=await b(`/search/issues?q=${encodeURIComponent(r)}&per_page=${n.limit||20}`),t=(i.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(s=>s.name),createdAt:e.created_at}));return JSON.stringify({total:i.total_count,items:t})}case"github_search_code":{let r=n.query;if(!r)return JSON.stringify({error:"query is required"});let i=n.repo?`+repo:${n.repo}`:"",t=n.language?`+language:${n.language}`:"",e=await b(`/search/code?q=${encodeURIComponent(r)}${i}${t}&per_page=${n.limit||15}`),s=(e.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:e.total_count,items:s})}case"github_get_pr":{let{owner:r,repo:i,number:t}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=await b(`/repos/${r}/${i}/pulls/${t}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,headSha:e.head?.sha,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(s=>s.name)})}case"github_get_pr_diff":{let{owner:r,repo:i,number:t}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=await b(`/repos/${r}/${i}/pulls/${t}`,{accept:"application/vnd.github.v3.diff",raw:!0}),s=e.length>15e3;return JSON.stringify({number:t,diff:s?e.slice(0,15e3):e,truncated:s,totalLength:e.length})}case"github_list_pr_files":{let{owner:r,repo:i,number:t}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=await b(`/repos/${r}/${i}/pulls/${t}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(s=>({filename:s.filename,status:s.status,additions:s.additions,deletions:s.deletions,patch:s.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:r,repo:i,number:t}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=await b(`/repos/${r}/${i}/pulls/${t}/comments?per_page=50`),s=await b(`/repos/${r}/${i}/issues/${t}/comments?per_page=50`),a=[...e.map(o=>({type:"review",user:o.user?.login,body:o.body?.slice(0,1e3),path:o.path,line:o.line,createdAt:o.created_at})),...s.map(o=>({type:"issue",user:o.user?.login,body:o.body?.slice(0,1e3),createdAt:o.created_at}))].sort((o,p)=>new Date(o.createdAt)-new Date(p.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:r,repo:i,number:t,commentId:e}=n||{};if(!r||!i||!t||!e)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let s=await b(`/repos/${r}/${i}/pulls/comments/${e}`),a=s.in_reply_to_id||s.id,o=[];try{o=await b(`/repos/${r}/${i}/pulls/${t}/comments?per_page=100`)}catch{o=[s]}(!Array.isArray(o)||o.length===0)&&(o=[s]);let p=o.filter(c=>c.id===a||c.in_reply_to_id===a).sort((c,h)=>new Date(c.created_at)-new Date(h.created_at)),d=p.length?p:[s],l=d.find(c=>c.id===a)||d[0];return JSON.stringify({rootCommentId:a,path:l.path,line:l.line??l.original_line??null,side:l.side||"RIGHT",diffHunk:typeof l.diff_hunk=="string"?l.diff_hunk.slice(0,3e3):null,commitId:l.commit_id||l.original_commit_id||null,notes:d.map(c=>({id:c.id,user:c.user?.login,body:(c.body||"").slice(0,4e3),createdAt:c.created_at,isRoot:c.id===a,url:c.html_url}))})}case"github_reply_review_thread":{let{owner:r,repo:i,number:t,commentId:e,body:s}=n||{};if(!r||!i||!t||!e||!s)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await b(`/repos/${r}/${i}/pulls/${t}/comments/${e}/replies`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:r,repo:i,number:t,body:e}=n||{};if(!r||!i||!t||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await b(`/repos/${r}/${i}/issues/${t}/comments`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_create_review":{let{owner:r,repo:i,number:t,body:e,event:s,comments:a}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let o=(s||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(o))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${s})`});let p=Array.isArray(a)?a.filter(c=>c&&c.path&&c.body&&(c.line!=null||c.position!=null)).map(c=>{let h={path:c.path,body:String(c.body)};return c.line!=null?(h.line=Number(c.line),h.side=c.side==="LEFT"?"LEFT":"RIGHT"):h.position=Number(c.position),h}):[];if(o!=="APPROVE"&&!e&&p.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d={event:o};e&&(d.body=String(e)),p.length>0&&(d.comments=p);let l=await b(`/repos/${r}/${i}/pulls/${t}/reviews`,{method:"POST",body:d});return JSON.stringify({ok:!0,id:l.id,state:l.state,event:o,commentsPosted:p.length,url:l.html_url})}case"github_list_commits":{let{owner:r,repo:i,branch:t,path:e,limit:s}=n;if(!r||!i)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${r}/${i}/commits?per_page=${s||20}`;t&&(a+=`&sha=${encodeURIComponent(t)}`),e&&(a+=`&path=${encodeURIComponent(e)}`);let o=await b(a);return JSON.stringify({total:o.length,commits:o.map(p=>({sha:p.sha?.slice(0,8),fullSha:p.sha,message:p.commit?.message?.slice(0,300),author:p.commit?.author?.name,date:p.commit?.author?.date,url:p.html_url}))})}case"github_get_commit":{let{owner:r,repo:i,sha:t}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and sha are required"});let e=await b(`/repos/${r}/${i}/commits/${t}`);return JSON.stringify({sha:e.sha?.slice(0,8),message:e.commit?.message,author:e.commit?.author?.name,date:e.commit?.author?.date,stats:e.stats,files:(e.files||[]).map(s=>({filename:s.filename,status:s.status,additions:s.additions,deletions:s.deletions,patch:s.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:r,repo:i,path:t,ref:e}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and path are required"});let s=`/repos/${r}/${i}/contents/${encodeURIComponent(t)}`;e&&(s+=`?ref=${encodeURIComponent(e)}`);let a=await b(s);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:t,entries:a.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let o=Buffer.from(a.content||"","base64").toString("utf-8"),p=o.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:p?o.slice(0,2e4):o,truncated:p})}case"github_get_user":try{let r=await b("/installation/repositories?per_page=1");if(r.repositories&&r.repositories.length>0){let i=r.repositories[0],t=i.owner.login,e=i.owner.type,s=e==="Organization"?`/orgs/${t}`:`/users/${t}`,a=await b(s);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:e,isOrg:e==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(r){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${r.message})`})}case"github_list_orgs":try{let i=(await b("/installation/repositories?per_page=100")).repositories||[],t=new Map;for(let s of i)s.owner.type==="Organization"&&(t.has(s.owner.login)||t.set(s.owner.login,{login:s.owner.login,description:null,url:s.owner.url}));let e=Array.from(t.values());return JSON.stringify({count:e.length,orgs:e,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(r){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${r.message}`})}case"github_clone":{let y=function(v){let f=v.replace(/^~(?=$|\/|\\)/,h);return a(f)},{owner:r,repo:i,destination:t}=n;if(!r||!i)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:s,resolve:a}=await import("path"),{existsSync:o,mkdirSync:p}=await import("fs"),{homedir:d,platform:l}=await import("os"),{token:c}=await C("github"),h=d(),u=t?y(t):s(h,"zibby-repos"),_=s(u,i);if(p(u,{recursive:!0}),o(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});try{let v=`https://x-access-token:${c}@github.com/${r}/${i}.git`;e(`git clone ${v} "${_}"`,{stdio:"pipe"});let f=l()==="win32",g;return f?g=e(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):g=e(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${r}/${i} to ${_}`,contents:g.split(`
`).slice(0,30).join(`
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(v){return JSON.stringify({error:`Clone failed: ${v.message}`})}}case"github_search_repos":{let{query:r,limit:i}=n;if(!r)return JSON.stringify({error:"query is required"});let t=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(t);if(e.error)return JSON.stringify(e);let s=r.toLowerCase(),a=e.repos.filter(o=>o.name.toLowerCase().includes(s)||o.fullName.toLowerCase().includes(s)||o.description&&o.description.toLowerCase().includes(s));return JSON.stringify({query:r,count:a.length,repos:a.slice(0,i||20)})}case"github_list_repos":{let{owner:r,type:i,sort:t,direction:e,limit:s,query:a}=n,o=100,p=s||200,d=[],l=g=>({name:g.name,fullName:g.full_name,private:g.private,description:g.description,language:g.language,defaultBranch:g.default_branch,updatedAt:g.updated_at,stars:g.stargazers_count,url:g.html_url,fullPath:g.full_name,webUrl:g.html_url,visibility:g.visibility||(g.private?"private":"public")}),c=g=>{if(!a)return!0;let R=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(R)||g.fullName&&g.fullName.toLowerCase().includes(R)||g.description&&g.description.toLowerCase().includes(R)};if(!r){let g=1,R=!0;for(;R&&d.length<p;){let P=`/installation/repositories?per_page=${o}&page=${g}`,k=(await b(P)).repositories||[];if(k.length===0)break;d=d.concat(k),R=k.length===o,g++}let N=d.map(l).filter(c),$=N.slice(0,p),B=N.length>$.length,J=$.filter(P=>P.private).length,M=$.filter(P=>!P.private).length;return JSON.stringify({count:$.length,repos:$,truncated:B,privateCount:J,publicCount:M,message:`Found ${J} private and ${M} public repos`})}let h=await b(`/orgs/${r}`).then(()=>!0).catch(()=>!1),y=1,u=!0;for(;u&&d.length<p;){let g;h?g=`/orgs/${r}/repos?per_page=${o}&page=${y}&type=${i||"all"}&sort=${t||"updated"}&direction=${e||"desc"}`:g=`/users/${r}/repos?per_page=${o}&page=${y}&type=${i||"all"}&sort=${t||"updated"}&direction=${e||"desc"}`;let R=await b(g),N=Array.isArray(R)?R:[];if(N.length===0)break;d=d.concat(N),u=N.length===o,y++}let _=d.map(l).filter(c),v=_.slice(0,p),f=_.length>v.length;return JSON.stringify({count:v.length,repos:v,truncated:f})}case"github_create_pr":{let{owner:r,repo:i,head:t,title:e}=n||{};if(!r||!i||!t||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let s=n.base;if(!s)try{s=(await b(`/repos/${r}/${i}`)).default_branch||"main"}catch{s="main"}let a={title:String(e),head:String(t),base:String(s),body:n.body?String(n.body):"",draft:!!n.draft};try{let o=await b(`/repos/${r}/${i}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.html_url,number:o.number,branch:t,base:s,repo:`${r}/${i}`,provider:"github",draft:!!o.draft,state:o.state})}catch(o){let p=String(o.message||o);if(/GitHub API 422/.test(p))return JSON.stringify({success:!1,branch:t,base:s,repo:`${r}/${i}`,provider:"github",skippedReason:p});throw o}}case"github_merge_pr":{let{owner:r,repo:i,number:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=n.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let s={merge_method:e};n.commitTitle&&(s.commit_title=String(n.commitTitle)),n.commitMessage&&(s.commit_message=String(n.commitMessage));try{let a=await b(`/repos/${r}/${i}/pulls/${t}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:t,provider:"github"})}catch(a){let o=String(a.message||a);if(/GitHub API (405|409|404)/.test(o))return JSON.stringify({success:!1,number:t,provider:"github",skippedReason:o});throw a}}case"github_create_issue":{let{owner:r,repo:i,title:t,body:e}=n;if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and title are required"});let s=await b(`/repos/${r}/${i}/issues`,{method:"POST",body:{title:t,body:e||""}});return JSON.stringify({number:s.number,url:s.html_url,title:s.title})}case"github_list_issues":{let{owner:r,repo:i,state:t,labels:e,since:s,assignee:a,sort:o,direction:p,limit:d}=n||{};if(!r||!i)return JSON.stringify({error:"owner and repo are required"});let l=new URLSearchParams;l.set("state",t||"open"),l.set("per_page",String(d||30)),l.set("sort",o||"updated"),l.set("direction",p||"desc"),e&&l.set("labels",Array.isArray(e)?e.join(","):e),s&&l.set("since",s),a&&l.set("assignee",a);let c=await b(`/repos/${r}/${i}/issues?${l.toString()}`),h=(Array.isArray(c)?c:[]).filter(y=>!y.pull_request).map(y=>({number:y.number,title:y.title,state:y.state,labels:(y.labels||[]).map(u=>typeof u=="string"?u:u.name),assignee:y.assignee?.login||null,assignees:(y.assignees||[]).map(u=>u.login),user:y.user?.login,comments:y.comments,url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:h.length,issues:h})}case"github_get_issue":{let{owner:r,repo:i,number:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=await b(`/repos/${r}/${i}/issues/${t}`);return e.pull_request?JSON.stringify({error:`#${t} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(s=>typeof s=="string"?s:s.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(s=>s.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:r,repo:i,number:t,limit:e}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let s=await b(`/repos/${r}/${i}/issues/${t}/comments?per_page=${e||100}`),a=(Array.isArray(s)?s:[]).map(o=>({id:o.id,user:o.user?.login,body:o.body||"",createdAt:o.created_at,updatedAt:o.updated_at,url:o.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:r,repo:i,number:t,body:e}=n||{};if(!r||!i||!t||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await b(`/repos/${r}/${i}/issues/${t}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_close_issue":{let{owner:r,repo:i,number:t,stateReason:e}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let s={state:"closed"};e&&(s.state_reason=e);let a=await b(`/repos/${r}/${i}/issues/${t}`,{method:"PATCH",body:s});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:r,repo:i,number:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let e=await b(`/repos/${r}/${i}/issues/${t}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:e.number,state:e.state,url:e.html_url})}case"github_label_issue":{let{owner:r,repo:i,number:t,labels:e,mode:s}=n||{};if(!r||!i||!t)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(e)?e:e?[e]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let o=s||"add";if(o==="set"){let d=await b(`/repos/${r}/${i}/issues/${t}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}if(o==="remove"){for(let l of a)await b(`/repos/${r}/${i}/issues/${t}/labels/${encodeURIComponent(l)}`,{method:"DELETE"});let d=await b(`/repos/${r}/${i}/issues/${t}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}let p=await b(`/repos/${r}/${i}/issues/${t}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:t,labels:(Array.isArray(p)?p:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${m}`})}}catch(r){return JSON.stringify({error:r.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List recent commits on a branch, optionally filtered by file path",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Max commits (default: 20)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as ie}from"fs";import{fileURLToPath as se}from"url";import{dirname as ne,resolve as oe}from"path";function ae(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let m=ne(se(import.meta.url)),n=oe(m,"..","bin","mcp-skill.mjs");return ie(n)?n:null}function ce(){let m=process.env.GITLAB_API_URL;if(m)return m.replace(/\/+$/,"");let n=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(n)?n:`${n}/api/v4`}function pe(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let m=process.env.GITLAB_TOKEN;if(!m)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":m}}async function w(m,n={}){let r=/^https?:\/\//.test(m)?m:`${ce()}${m}`,i={Accept:"application/json","User-Agent":"Zibby-App",...pe(),...n.body?{"Content-Type":"application/json"}:{}},t=await fetch(r,{method:n.method||"GET",headers:i,body:n.body?JSON.stringify(n.body):void 0});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`GitLab API ${t.status}: ${e.slice(0,300)}`)}return n.raw?t.text():t.json()}function x(){let m=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(m?m.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function de(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function S(m){let n=String(m);return/^\d+$/.test(n)?n:encodeURIComponent(n)}var T={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:L.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab (connected)
You have access to the user's GitLab projects via the REST API (cloud gitlab.com OR self-hosted). A "merge request" (MR) is GitLab's pull request. An MR is addressed by a PROJECT (numeric id OR full path like "group/repo") and an \`iid\` (the per-project MR number shown in the URL). For projects, prefer the full path form ("group/subgroup/repo") \u2014 it's what users have. Available tools:

### Discovery
- gitlab_list_projects: List the projects this token can access (the ones you're a member of), optionally filtered by a search query. Use to find a RELATED project worth cloning for cross-repo context.
- gitlab_clone: Clone a project locally (shallow, auto-authenticated) to read code OUTSIDE the MR diff \u2014 callers, shared types, an existing util, or a cross-repo dependency. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY (only when correctness needs context beyond the diff).

### Merge requests
- gitlab_create_mr: OPEN a merge request (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR's web_url) from GitLab \u2014 never fabricate it. Expected business errors (no changes between branches, an MR already exists, source==target) come back as { success:false, skippedReason } \u2014 not a hard failure.
- gitlab_accept_mr: ACCEPT (merge) an MR (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha (merge_commit_sha) } on a real merge. Expected non-mergeable cases (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404) come back as { success:false, skippedReason } \u2014 not a hard failure.
- gitlab_get_mr: Get an MR's details (title, description, author, source/target branch, state, web url, diff_refs)
- gitlab_get_mr_changes: Get the MR's changed files with per-file diffs \u2014 THIS is the code to review
- gitlab_list_mrs: List a project's merge requests (filter by state: opened|closed|merged|all)
- gitlab_list_mr_notes: Get the discussion/notes thread on an MR
- gitlab_get_discussion: Read a single MR discussion (thread) by id \u2014 all its notes + the file/line it is anchored to
- gitlab_reply_discussion: Reply IN-THREAD to an existing MR discussion (conversational reply, not a new review)
- gitlab_post_mr_note: Post a general (non-inline) comment on an MR
- gitlab_post_mr_discussion: Post an INLINE review comment anchored to a file + line in the MR diff. Needs diff_refs (pass them from gitlab_get_mr / gitlab_get_mr_changes, or omit and the tool fetches them). Provide newLine for added/changed lines (or oldLine for removed/context lines).

### Issues
- gitlab_get_issue: Get a single issue (by project + issue iid) \u2014 title, description, state, labels, assignee, web url
- gitlab_list_issues: List a project's issues (filter by state: opened|closed|all, labels, updatedAfter cursor)
- gitlab_add_issue_comment: Add a comment to an issue (also the way to record an MR link on a ticket)

### Notes
- A code-review flow is: gitlab_get_mr (context + diff_refs) \u2192 gitlab_get_mr_changes (the diff) \u2192 gitlab_post_mr_discussion per inline finding \u2192 gitlab_post_mr_note for the summary.
- If an inline position is rejected by GitLab (bad line anchor), fall back to gitlab_post_mr_note with the file/line in the text.`,resolve(){let m=ae();if(!m)return{command:null,args:[],env:{},description:this.description};let n={};for(let r of this.envKeys)process.env[r]&&(n[r]=process.env[r]);return{type:"stdio",command:"node",args:[m,"../dist/gitlab.js","gitlabSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(m,n){try{switch(m){case"gitlab_clone":{let{projectPath:r,projectId:i,destination:t,branch:e}=n||{},s=r&&String(r).trim();if(!s&&i!=null&&(/^\d+$/.test(String(i))?s=(await w(`/projects/${S(i)}`))?.path_with_namespace:s=String(i).trim()),!s)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=de();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:o}=await import("child_process"),{join:p,resolve:d}=await import("path"),{existsSync:l,mkdirSync:c}=await import("fs"),h=t?d(t):d(process.cwd(),".zibby","repos"),y=s.split("/").filter(Boolean).pop(),u=p(h,y);if(c(h,{recursive:!0}),l(u))return JSON.stringify({success:!0,path:u,message:`Already cloned at ${u}`,alreadyCloned:!0});let _=x().replace(/^https?:\/\//,""),f=`${x().startsWith("http://")?"http":"https"}://oauth2:${a}@${_}/${s}.git`,g=e?`--branch "${String(e).replace(/"/g,"")}" `:"";try{o(`git clone --depth 1 ${g}${f} "${u}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let R=o(`ls -la "${u}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:u,message:`Cloned ${s} to ${u}`,contents:R.split(`
`).slice(0,30).join(`
`)})}catch(R){let N=String(R.message||R).split(a).join("***");return JSON.stringify({error:`Clone failed: ${N}`})}}case"gitlab_create_mr":{let r=n?.project??n?.projectId,i=n?.source_branch??n?.sourceBranch,{title:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let e=S(r),s=n?.target_branch??n?.targetBranch;if(!s)try{s=(await w(`/projects/${e}`)).default_branch||"main"}catch{s="main"}let a={source_branch:String(i),target_branch:String(s),title:String(t),description:n?.description?String(n.description):""};try{let o=await w(`/projects/${e}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.web_url,number:o.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(r),provider:"gitlab",state:o.state})}catch(o){let p=String(o.message||o);if(/GitLab API (409|400)/.test(p))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(r),provider:"gitlab",skippedReason:p});throw o}}case"gitlab_accept_mr":{let r=n?.project??n?.projectId,{iid:i}=n||{};if(!r||!i)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let t=S(r),e={};n.squash!=null&&(e.squash=!!n.squash),n.mergeCommitMessage&&(e.merge_commit_message=String(n.mergeCommitMessage)),n.mergeWhenPipelineSucceeds!=null&&(e.merge_when_pipeline_succeeds=!!n.mergeWhenPipelineSucceeds);try{let s=await w(`/projects/${t}/merge_requests/${i}/merge`,{method:"PUT",body:e});return JSON.stringify({success:!0,merged:!0,sha:s.merge_commit_sha??s.sha??null,iid:s.iid??i,project:String(r),provider:"gitlab",state:s.state})}catch(s){let a=String(s.message||s);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:i,project:String(r),provider:"gitlab",skippedReason:a});throw s}}case"gitlab_get_mr":{let{projectId:r,iid:i}=n||{};if(!r||!i)return JSON.stringify({error:"projectId and iid are required"});let t=await w(`/projects/${S(r)}/merge_requests/${i}`);return JSON.stringify({iid:t.iid,projectId:t.project_id,title:t.title,description:(t.description||"").slice(0,5e3),state:t.state,author:t.author?.username,sourceBranch:t.source_branch,targetBranch:t.target_branch,draft:t.draft??t.work_in_progress??!1,mergeStatus:t.merge_status,changesCount:t.changes_count,labels:Array.isArray(t.labels)?t.labels:[],webUrl:t.web_url,createdAt:t.created_at,updatedAt:t.updated_at,mergedAt:t.merged_at,diffRefs:t.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:r,iid:i}=n||{};if(!r||!i)return JSON.stringify({error:"projectId and iid are required"});let t=await w(`/projects/${S(r)}/merge_requests/${i}/changes`),e=Array.isArray(t.changes)?t.changes:[];return JSON.stringify({iid:t.iid,total:e.length,diffRefs:t.diff_refs||null,files:e.map(s=>({oldPath:s.old_path,newPath:s.new_path,newFile:!!s.new_file,deletedFile:!!s.deleted_file,renamedFile:!!s.renamed_file,diff:typeof s.diff=="string"?s.diff.slice(0,3e3):""}))})}case"gitlab_list_mrs":{let{projectId:r,state:i,targetBranch:t,sourceBranch:e,authorUsername:s,labels:a,search:o,sort:p,orderBy:d,limit:l}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let c=new URLSearchParams;c.set("state",i||"opened"),c.set("per_page",String(l||20)),c.set("order_by",d||"updated_at"),c.set("sort",p||"desc"),t&&c.set("target_branch",t),e&&c.set("source_branch",e),s&&c.set("author_username",s),a&&c.set("labels",Array.isArray(a)?a.join(","):a),o&&c.set("search",o);let h=await w(`/projects/${S(r)}/merge_requests?${c.toString()}`),y=(Array.isArray(h)?h:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,author:u.author?.username,sourceBranch:u.source_branch,targetBranch:u.target_branch,draft:u.draft??u.work_in_progress??!1,labels:Array.isArray(u.labels)?u.labels:[],webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:y.length,mergeRequests:y})}case"gitlab_list_mr_notes":{let{projectId:r,iid:i,limit:t}=n||{};if(!r||!i)return JSON.stringify({error:"projectId and iid are required"});let e=await w(`/projects/${S(r)}/merge_requests/${i}/notes?per_page=${t||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(e)?e.length:0,notes:(Array.isArray(e)?e:[]).map(s=>({id:s.id,author:s.author?.username,body:(s.body||"").slice(0,1e3),system:!!s.system,createdAt:s.created_at}))})}case"gitlab_post_mr_note":{let{projectId:r,iid:i,body:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:"projectId, iid, and body are required"});let e=await w(`/projects/${S(r)}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(t)}});return JSON.stringify({ok:!0,id:e.id,createdAt:e.created_at})}case"gitlab_post_mr_discussion":{let{projectId:r,iid:i,path:t,oldPath:e,newLine:s,oldLine:a,body:o}=n||{};if(!r||!i||!t||!o)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(s==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let p=S(r),d=n.diffRefs||null;if(d||(d=(await w(`/projects/${p}/merge_requests/${i}`)).diff_refs||null),!d||!d.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let l={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:t,old_path:e||t};s!=null&&(l.new_line=Number(s)),a!=null&&(l.old_line=Number(a));try{let c=await w(`/projects/${p}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(o),position:l}});return JSON.stringify({ok:!0,discussionId:c.id})}catch(c){return JSON.stringify({ok:!1,error:`inline anchor rejected (${c.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:r,iid:i,body:t,comments:e}=n||{};if(!r||!i)return JSON.stringify({error:"projectId and iid are required"});let s=S(r),a=Array.isArray(e)?e.filter(c=>c&&c.path&&c.body&&(c.newLine!=null||c.oldLine!=null)):[];if(!t&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let o=n.diffRefs||null;a.length>0&&!o&&(o=(await w(`/projects/${s}/merge_requests/${i}`)).diff_refs||null);let p=!1;t&&(await w(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(t)}}),p=!0);let d=0,l=[];if(a.length>0&&o)for(let c of a){let h={base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha,position_type:"text",new_path:c.path,old_path:c.oldPath||c.path};c.newLine!=null&&(h.new_line=Number(c.newLine)),c.oldLine!=null&&(h.old_line=Number(c.oldLine));try{await w(`/projects/${s}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(c.body),position:h}}),d+=1}catch(y){l.push(`${c.path}:${c.newLine??c.oldLine} \u2014 ${y.message}`)}}else a.length>0&&!o&&l.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:p,inlinePosted:d,inlineErrors:l.length?l:void 0})}case"gitlab_get_discussion":{let{projectId:r,iid:i,discussionId:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let e=await w(`/projects/${S(r)}/merge_requests/${i}/discussions/${encodeURIComponent(t)}`),s=Array.isArray(e.notes)?e.notes:[],a=s.find(p=>p.position)||null,o=a?a.position:null;return JSON.stringify({discussionId:e.id,individualNote:!!e.individual_note,path:o&&(o.new_path||o.old_path)||null,newLine:o?o.new_line??null:null,oldLine:o?o.old_line??null:null,diffRefs:o?{base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha}:null,notes:s.map(p=>({id:p.id,author:p.author?.username,body:(p.body||"").slice(0,4e3),system:!!p.system,createdAt:p.created_at}))})}case"gitlab_reply_discussion":{let{projectId:r,iid:i,discussionId:t,body:e}=n||{};if(!r||!i||!t||!e)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let s=await w(`/projects/${S(r)}/merge_requests/${i}/discussions/${encodeURIComponent(t)}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_list_projects":{let{query:r,limit:i}=n||{},t=Math.min(Number(i)>0?Number(i):50,200),e=new URLSearchParams;e.set("membership","true"),e.set("simple","true"),e.set("order_by","last_activity_at"),e.set("sort","desc"),e.set("per_page",String(Math.min(t+1,100))),r&&e.set("search",String(r));let s=await w(`/projects?${e.toString()}`),a=Array.isArray(s)?s:[],o=a.length>t,p=a.slice(0,t).map(d=>({fullPath:d.path_with_namespace,name:d.name,webUrl:d.web_url,defaultBranch:d.default_branch||null,visibility:d.visibility||null}));return JSON.stringify({count:p.length,truncated:o,projects:p})}case"gitlab_list_issues":{let{projectId:r,state:i,labels:t,assigneeUsername:e,authorUsername:s,updatedAfter:a,search:o,sort:p,orderBy:d,limit:l}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let c=new URLSearchParams;c.set("state",i||"opened"),c.set("per_page",String(l||30)),c.set("order_by",d||"updated_at"),c.set("sort",p||"desc"),t&&c.set("labels",Array.isArray(t)?t.join(","):t),e&&c.set("assignee_username",e),s&&c.set("author_username",s),a&&c.set("updated_after",a),o&&c.set("search",o);let h=await w(`/projects/${S(r)}/issues?${c.toString()}`),y=(Array.isArray(h)?h:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,labels:Array.isArray(u.labels)?u.labels:[],author:u.author?.username,assignees:(u.assignees||[]).map(_=>_.username),userNotesCount:u.user_notes_count,webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:y.length,issues:y})}case"gitlab_get_issue":{let{projectId:r,iid:i}=n||{};if(!r||!i)return JSON.stringify({error:"projectId and iid are required"});let t=await w(`/projects/${S(r)}/issues/${i}`);return JSON.stringify({iid:t.iid,projectId:t.project_id,title:t.title,description:(t.description||"").slice(0,5e3),state:t.state,labels:Array.isArray(t.labels)?t.labels:[],author:t.author?.username,assignees:(t.assignees||[]).map(e=>e.username),milestone:t.milestone?.title||null,webUrl:t.web_url,createdAt:t.created_at,updatedAt:t.updated_at,closedAt:t.closed_at})}case"gitlab_add_issue_comment":{let{projectId:r,iid:i,body:t}=n||{};if(!r||!i||!t)return JSON.stringify({error:"projectId, iid, and body are required"});let e=await w(`/projects/${S(r)}/issues/${i}/notes`,{method:"POST",body:{body:String(t)}});return JSON.stringify({ok:!0,id:e.id,createdAt:e.created_at})}default:return JSON.stringify({error:`Unknown tool: ${m}`})}}catch(r){return JSON.stringify({error:r.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};function H(m){let n=(m||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return n?{provider:"github",owner:n[1],repo:n[2]}:(n=(m||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),n?{provider:"gitlab",owner:n[1],repo:n[2]}:null)}var qe={...j,id:"git-write",envKeys:[...j.envKeys||[],...q.envKeys||[],...T.envKeys||[]].filter((m,n,r)=>r.indexOf(m)===n),promptFragment:`${j.promptFragment}

## Opening a pull request / merge request (git_open_pr)
After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
- git_open_pr: Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. Provider is auto-detected from \`repoUrl\` (github.com or gitlab.com). Args:
    { repoUrl, head (the pushed source branch), base? (target branch; default the repo default), title, body? }
  Returns the REAL provider url (\`pr_url\` = GitHub html_url / GitLab web_url) \u2014 NEVER fabricate a PR url; only ever report the url this tool returns. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) come back as { success:false, skippedReason } \u2014 that is a normal "nothing to open", not a hard failure.

## Merging a pull request / merge request (git_merge_pr)
To MERGE an open PR/MR, use the provider-agnostic tool:
- git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
    { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
  Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(m,n,r){if(m!=="git_open_pr"&&m!=="git_merge_pr")return j.handleToolCall(m,n,r);try{let i=n||{},t=i.repoUrl||i.repo_url||i.url;if(!t)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(m==="git_merge_pr"){let d=i.number??i.iid??i.prNumber;if(d==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let l=H(t);return l?l.provider==="github"?q.handleToolCall("github_merge_pr",{owner:l.owner,repo:l.repo,number:d,mergeMethod:i.mergeMethod},r):T.handleToolCall("gitlab_accept_mr",{project:`${l.owner}/${l.repo}`,iid:d},r):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${t}. git_merge_pr supports github.com and gitlab.com.`})}let e=i.head||i.source_branch||i.sourceBranch||i.branch,s=i.base||i.target_branch||i.targetBranch,{title:a,body:o}=i;if(!e||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let p=H(t);return p?p.provider==="github"?q.handleToolCall("github_create_pr",{owner:p.owner,repo:p.repo,head:e,base:s,title:a,body:o},r):T.handleToolCall("gitlab_create_mr",{project:`${p.owner}/${p.repo}`,source_branch:e,target_branch:s,title:a,description:o},r):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${t}. git_open_pr supports github.com and gitlab.com.`})}catch(i){return JSON.stringify({error:i.message})}},tools:[...j.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};export{H as detectProvider,qe as gitWriteSkill};
