@zibby/skills 2.0.8 → 2.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gbrain.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync as f,readFileSync as b}from"node:fs";import{homedir as h}from"node:os";import{join as I,dirname as _,resolve as S}from"node:path";import{fileURLToPath as O}from"node:url";import{SKILL_META as E}from"@zibby/skill-ids";var T=3e4,l=1;function w(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let o=_(O(import.meta.url)),r=S(o,"..","bin","mcp-skill.mjs");return f(r)?r:null}function A(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=I(h(),".zibby","config.json");return f(o)&&JSON.parse(b(o,"utf-8")).sessionToken||null}catch{return null}}function k(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function v(){let o={};for(let[r,e]of Object.entries(process.env)){let t=/^ZIBBY_STORE__(.+)$/.exec(r);if(!t)continue;let n=typeof e=="string"?e.trim():"";n&&(o[t[1]]=n)}return o}function p(o){let r=v(),e=Object.keys(r),t=typeof o=="string"?o.trim():"";return t?Object.prototype.hasOwnProperty.call(r,t)?{storeId:r[t],name:t}:{error:`unknown store '${t}'; available: ${e.join(", ")}`}:e.length===1?{storeId:r[e[0]],name:e[0]}:e.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function m(o,r,e){let t=A();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let n=`${k()}/datasets/stores/${encodeURIComponent(o)}/${r}`,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"},u=JSON.stringify(e),i;for(let c=0;c<=l;c++){let y=new AbortController,g=setTimeout(()=>y.abort(),T);try{let a=await fetch(n,{method:"POST",headers:s,body:u,signal:y.signal}),d=await a.text().catch(()=>"");if(a.status>=500&&c<l){i=new Error(`store ${a.status}`);continue}if(!a.ok)throw new Error(`gbrain ${r} failed (${a.status}): ${d.slice(0,300)}`);try{return JSON.parse(d)}catch{throw new Error(`store returned non-JSON: ${d.slice(0,200)}`)}}catch(a){if(i=a,!((a?.name==="AbortError"||a?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(a?.message)))&&c<l))break}finally{clearTimeout(g)}}throw i||new Error(`gbrain ${r} request failed`)}var N={id:"gbrain",callsBackend:!0,serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:E.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
1
+ import{existsSync as f,readFileSync as b}from"node:fs";import{homedir as h}from"node:os";import{join as I,dirname as _,resolve as S}from"node:path";import{fileURLToPath as O}from"node:url";import{SKILL_META as E}from"@zibby/skill-ids";var T=3e4,l=1;function A(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let o=_(O(import.meta.url)),r=S(o,"..","bin","mcp-skill.mjs");return f(r)?r:null}function w(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let o=I(h(),".zibby","config.json");return f(o)&&JSON.parse(b(o,"utf-8")).sessionToken||null}catch{return null}}function k(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function v(){let o={};for(let[r,e]of Object.entries(process.env)){let t=/^ZIBBY_STORE__(.+)$/.exec(r);if(!t)continue;let n=typeof e=="string"?e.trim():"";n&&(o[t[1]]=n)}return o}function p(o){let r=v(),e=Object.keys(r),t=typeof o=="string"?o.trim():"";return t?Object.prototype.hasOwnProperty.call(r,t)?{storeId:r[t],name:t}:{error:`unknown store '${t}'; available: ${e.join(", ")}`}:e.length===1?{storeId:r[e[0]],name:e[0]}:e.length===0?{error:"no knowledge-base store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function m(o,r,e){let t=w();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). The knowledge base is only available inside a Zibby run.");let n=`${k()}/datasets/stores/${encodeURIComponent(o)}/${r}`,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"},u=JSON.stringify(e),i;for(let c=0;c<=l;c++){let y=new AbortController,g=setTimeout(()=>y.abort(),T);try{let a=await fetch(n,{method:"POST",headers:s,body:u,signal:y.signal}),d=await a.text().catch(()=>"");if(a.status>=500&&c<l){i=new Error(`store ${a.status}`);continue}if(!a.ok)throw new Error(`gbrain ${r} failed (${a.status}): ${d.slice(0,300)}`);try{return JSON.parse(d)}catch{throw new Error(`store returned non-JSON: ${d.slice(0,200)}`)}}catch(a){if(i=a,!((a?.name==="AbortError"||a?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(a?.message)))&&c<l))break}finally{clearTimeout(g)}}throw i||new Error(`gbrain ${r} request failed`)}var N={id:"gbrain",callsBackend:!0,serverName:"gbrain",allowedTools:["mcp__gbrain__*"],meta:E.gbrain,description:"Knowledge base (GBrain) \u2014 ingest source documents into, semantically query, and prune a per-tenant Postgres/pgvector brain (a `postgres`-type store, brokered by the control-plane)",promptFragment:`## Knowledge Base (GBrain \u2014 per-tenant document brain)
2
2
  You have a per-tenant KNOWLEDGE BASE (a Postgres + pgvector "brain"), bound as a
3
3
  \`postgres\`-type store in the "AVAILABLE STORES" block below. Ingested documents
4
4
  are addressed by a STABLE \`sourceId\` so re-ingesting the same source UPSERTS
@@ -9,4 +9,4 @@ Tools:
9
9
  Pass deleted:true to remove a source that no longer exists upstream.
10
10
  - gbrain_query({ query, topK, store? }): semantic search; returns the topK most
11
11
  relevant document chunks with their sourceId and relevance score.
12
- - gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let o=w();if(!o)return{command:null,args:[],env:{},description:this.description};let r={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(r[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"node",args:[o,"../dist/gbrain.js","gbrainSkill"],env:r,description:this.description,alwaysLoad:!0}},async handleToolCall(o,r){try{switch(o){case"gbrain_ingest":{let e=Array.isArray(r?.docs)?r.docs:null;if(!e)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(e.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(e.find(i=>!i||typeof i.sourceId!="string"||!i.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let n=e.find(i=>i.deleted!==!0&&(typeof i.markdown!="string"||!i.markdown.length));if(n!==void 0)return JSON.stringify({error:`doc "${n.sourceId}" has no markdown (required unless deleted:true)`});let s=p(r?.store);if(s.error)return JSON.stringify({error:s.error});let u=await m(s.storeId,"ingest",{docs:e});return JSON.stringify({...u,store:s.name,storeId:s.storeId})}case"gbrain_query":{let e=typeof r?.query=="string"?r.query.trim():"";if(!e)return JSON.stringify({error:"query is required"});let t=p(r?.store);if(t.error)return JSON.stringify({error:t.error});let n={query:e};Number.isInteger(r?.topK)&&r.topK>0&&(n.topK=Math.min(r.topK,50));let s=await m(t.storeId,"query",n);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"gbrain_delete":{let e=Array.isArray(r?.sourceIds)?r.sourceIds.filter(s=>typeof s=="string"&&s.trim()):null;if(!e||e.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let t=p(r?.store);if(t.error)return JSON.stringify({error:t.error});let n=await m(t.storeId,"delete",{sourceIds:e});return JSON.stringify({...n,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${o}`})}}catch(e){return JSON.stringify({error:String(e?.message||e)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]},U=N;export{U as default,N as gbrainSkill};
12
+ - gbrain_delete({ sourceIds, store? }): remove documents by their stable sourceId(s).`,resolve(){let o=A();if(!o)return{command:null,args:[],env:{},description:this.description};let r={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(r[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"node",args:[o,"../dist/gbrain.js","gbrainSkill"],env:r,description:this.description}},async handleToolCall(o,r){try{switch(o){case"gbrain_ingest":{let e=Array.isArray(r?.docs)?r.docs:null;if(!e)return JSON.stringify({error:"docs is required (array of { sourceId, markdown, deleted? })"});if(e.length===0)return JSON.stringify({ok:!0,upserted:0,deleted:0,chunks:0,note:"empty docs \u2014 nothing to ingest"});if(e.find(i=>!i||typeof i.sourceId!="string"||!i.sourceId.trim())!==void 0)return JSON.stringify({error:"every doc requires a non-empty string sourceId"});let n=e.find(i=>i.deleted!==!0&&(typeof i.markdown!="string"||!i.markdown.length));if(n!==void 0)return JSON.stringify({error:`doc "${n.sourceId}" has no markdown (required unless deleted:true)`});let s=p(r?.store);if(s.error)return JSON.stringify({error:s.error});let u=await m(s.storeId,"ingest",{docs:e});return JSON.stringify({...u,store:s.name,storeId:s.storeId})}case"gbrain_query":{let e=typeof r?.query=="string"?r.query.trim():"";if(!e)return JSON.stringify({error:"query is required"});let t=p(r?.store);if(t.error)return JSON.stringify({error:t.error});let n={query:e};Number.isInteger(r?.topK)&&r.topK>0&&(n.topK=Math.min(r.topK,50));let s=await m(t.storeId,"query",n);return JSON.stringify({...s,store:t.name,storeId:t.storeId})}case"gbrain_delete":{let e=Array.isArray(r?.sourceIds)?r.sourceIds.filter(s=>typeof s=="string"&&s.trim()):null;if(!e||e.length===0)return JSON.stringify({error:"sourceIds is required (non-empty array of strings)"});let t=p(r?.store);if(t.error)return JSON.stringify({error:t.error});let n=await m(t.storeId,"delete",{sourceIds:e});return JSON.stringify({...n,store:t.name,storeId:t.storeId})}default:return JSON.stringify({error:`Unknown tool: ${o}`})}}catch(e){return JSON.stringify({error:String(e?.message||e)})}},tools:[{name:"gbrain_ingest",description:'Upsert documents into the knowledge base. Each doc is { sourceId, markdown, deleted? }; sourceId is a STABLE id (e.g. "owner/repo#docs/x.md" or a Lark doc token) so re-ingesting the same source UPDATES in place instead of duplicating. Set deleted:true to remove a source.',input_schema:{type:"object",properties:{docs:{type:"array",description:"Documents to upsert.",items:{type:"object",properties:{sourceId:{type:"string",description:"Stable source id \u2014 the upsert/delete key."},markdown:{type:"string",description:"The normalized markdown content of the document."},deleted:{type:"boolean",description:"When true, remove this sourceId from the brain (markdown ignored)."}},required:["sourceId"]}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["docs"]}},{name:"gbrain_query",description:"Semantic-search the knowledge base and return the most relevant document chunks (each with its sourceId and relevance score).",input_schema:{type:"object",properties:{query:{type:"string",description:"Natural-language query."},topK:{type:"integer",description:"How many chunks to return (default 8, max 50)."},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["query"]}},{name:"gbrain_delete",description:"Remove documents from the knowledge base by their stable sourceId(s).",input_schema:{type:"object",properties:{sourceIds:{type:"array",description:"Stable source ids to delete.",items:{type:"string"}},store:{type:"string",description:"The bound knowledge-base store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."}},required:["sourceIds"]}}]},U=N;export{U as default,N as gbrainSkill};
package/dist/git-write.js CHANGED
@@ -1,4 +1,4 @@
1
- import{spawn as de,execSync as ue}from"child_process";import{existsSync as I,mkdirSync as me,readdirSync as X,statSync as he,readFileSync as ge}from"fs";import{resolve as z,join as v,basename as be}from"path";var W=".zibby/repos";function Q(c,n){try{let e=new URL(c);return e.protocol==="https:"&&e.host.toLowerCase()===n.toLowerCase()}catch{return!1}}function Z(c,n,e){let i=new URL(c);return i.username=encodeURIComponent(n),i.password=encodeURIComponent(e),i.toString()}function fe(c){let n=String(c??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(n=n.split(e).join("***"));return n.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function j(c,n,e,i,r="clone"){try{c(`git -C "${n}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(t){let s=String(t?.message||t);i&&(s=s.split(i).join("***")),console.error(`[${r}] WARNING: failed to strip token from .git/config: ${s}`)}}function P(c,n,e={}){return new Promise((i,r)=>{let t=de(c,{cwd:n,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),s="",a="";t.stdout.on("data",o=>{s+=o.toString()}),t.stderr.on("data",o=>{a+=o.toString()}),t.on("close",o=>{o!==0?r(new Error(`Exit ${o}: ${a.trim()||s.trim()}`)):i(s.trim())}),t.on("error",o=>r(o))})}var $={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
1
+ import{spawn as he,execSync as ge}from"child_process";import{existsSync as I,mkdirSync as be,readdirSync as re,statSync as fe,readFileSync as ye}from"fs";import{resolve as Y,join as $,basename as _e}from"path";var V=".zibby/repos";function ee(c,n){try{let e=new URL(c);return e.protocol==="https:"&&e.host.toLowerCase()===n.toLowerCase()}catch{return!1}}function te(c,n,e){let i=new URL(c);return i.username=encodeURIComponent(n),i.password=encodeURIComponent(e),i.toString()}function we(c){let n=String(c??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(n=n.split(e).join("***"));return n.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function L(c,n,e,i,r="clone"){try{c(`git -C "${n}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(t){let s=String(t?.message||t);i&&(s=s.split(i).join("***")),console.error(`[${r}] WARNING: failed to strip token from .git/config: ${s}`)}}function k(c,n,e={}){return new Promise((i,r)=>{let t=he(c,{cwd:n,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),s="",a="";t.stdout.on("data",o=>{s+=o.toString()}),t.stderr.on("data",o=>{a+=o.toString()}),t.on("close",o=>{o!==0?r(new Error(`Exit ${o}: ${a.trim()||s.trim()}`)):i(s.trim())}),t.on("error",o=>r(o))})}var T={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
2
2
  You can clone and explore git repositories locally for codebase analysis:
3
3
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
4
4
  - git_list_repos: List locally cloned repos
@@ -8,11 +8,11 @@ When your task needs repository context you don't have yet:
8
8
  1. Clone the relevant repo with git_checkout
9
9
  2. Use git_explore to understand the project structure
10
10
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
11
- 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(c,n,e){let i=e?.options?.workspace||process.cwd();try{switch(c){case"git_checkout":return await ye(n,i);case"git_list_repos":return _e(n,i);case"git_explore":return we(n,i);default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(r){return JSON.stringify({error:fe(r.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 ye(c,n){let{url:e,branch:i,shallow:r=!0,name:t}=c;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let s=t||be(e.replace(/\.git$/,"")),a=z(n,W);me(a,{recursive:!0});let o=v(a,s),l=e,d=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=process.env.GITLAB_URL;if(Q(e,"github.com")&&d)l=Z(e,"x-access-token",d);else if(u&&p)try{let b=new URL(p).host;Q(e,b)&&(l=Z(e,"oauth2",u))}catch{}if(I(v(o,".git"))){let b=i?`git -C "${o}" fetch "${l}" ${i} && git -C "${o}" checkout ${i} && git -C "${o}" merge --ff-only FETCH_HEAD`:`git -C "${o}" pull "${l}"`;await P(b,n);let w=await P(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"updated",repo:s,path:o,branch:i||"default",head:w})}let m=["git","clone"];r&&m.push("--depth","1"),i&&m.push("--branch",i),m.push(`"${l}"`,`"${o}"`),await P(m.join(" "),n),j(ue,o,e,d||u,"git_checkout");let y=await P(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"cloned",repo:s,path:o,branch:i||"default",shallow:r,head:y})}function _e(c,n){let e=z(n,W);if(!I(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let r of X(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let t=v(e,r.name);if(!I(v(t,".git")))continue;let s=he(t);i.push({name:r.name,path:t,lastModified:s.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:e})}function we(c,n){let{repo:e,depth:i=2}=c,r=z(n,W,e);if(!I(r))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let t={repo:e,path:r},s=v(r,"package.json");if(I(s))try{let m=JSON.parse(ge(s,"utf-8"));t.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?t.framework="React":m.dependencies?.next?t.framework="Next.js":m.dependencies?.vue?t.framework="Vue":m.dependencies?.angular?t.framework="Angular":m.dependencies?.express?t.framework="Express":m.dependencies?.fastify&&(t.framework="Fastify")}catch{}let a=v(r,"pyproject.toml");I(a)&&(t.language="Python");let o=v(r,"go.mod");I(o)&&(t.language="Go");let l=v(r,"Cargo.toml");I(l)&&(t.language="Rust"),I(s)&&(t.language=t.language||"JavaScript/TypeScript");let d=[];function u(m,y,b){if(b>i)return;let w;try{w=X(m,{withFileTypes:!0})}catch{return}let f=w.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules"&&h.name!=="__pycache__"&&h.name!=="dist"&&h.name!=="build"&&h.name!==".git").sort((h,g)=>h.isDirectory()!==g.isDirectory()?h.isDirectory()?-1:1:h.name.localeCompare(g.name));for(let h of f){let g=h.isDirectory();d.push(`${y}${g?"\u{1F4C1}":"\u{1F4C4}"} ${h.name}`),g&&b<i&&u(v(m,h.name),`${y} `,b+1)}}u(r,"",1),t.tree=d.slice(0,80),d.length>80&&(t.treeTruncated=!0);let p=["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 t.keyFilesFound=p.filter(m=>I(v(r,m))),JSON.stringify(t)}import{existsSync as je}from"fs";import{fileURLToPath as Le}from"url";import{dirname as Pe,resolve as ke}from"path";import{resolveIntegrationToken as re}from"@zibby/core/backend-client.js";var k=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Ze=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 Chat",connectPath:"/integrations?provider=lark"},lark_docs:{id:"lark_docs",name:"Lark App",connectPath:"/integrations?provider=lark_docs"},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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},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"}});import Se from"crypto";var ee=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,te=/<!--\s*zbreview-summary\s*-->/i;function Re(c){return String(c||"").replace(ee,"").replace(te,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Oe(c,n){return Se.createHash("sha256").update(`${String(c||"")}\0${Re(n)}`).digest("hex").slice(0,12)}function Ae(c){return`
11
+ 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(c,n,e){let i=e?.options?.workspace||process.cwd();try{switch(c){case"git_checkout":return await Se(n,i);case"git_list_repos":return Re(n,i);case"git_explore":return Ae(n,i);default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(r){return JSON.stringify({error:we(r.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 Se(c,n){let{url:e,branch:i,shallow:r=!0,name:t}=c;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let s=t||_e(e.replace(/\.git$/,"")),a=Y(n,V);be(a,{recursive:!0});let o=$(a,s),l=e,d=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,p=process.env.GITLAB_URL;if(ee(e,"github.com")&&d)l=te(e,"x-access-token",d);else if(u&&p)try{let b=new URL(p).host;ee(e,b)&&(l=te(e,"oauth2",u))}catch{}if(I($(o,".git"))){let b=i?`git -C "${o}" fetch "${l}" ${i} && git -C "${o}" checkout ${i} && git -C "${o}" merge --ff-only FETCH_HEAD`:`git -C "${o}" pull "${l}"`;await k(b,n);let w=await k(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"updated",repo:s,path:o,branch:i||"default",head:w})}let m=["git","clone"];r&&m.push("--depth","1"),i&&m.push("--branch",i),m.push(`"${l}"`,`"${o}"`),await k(m.join(" "),n),L(ge,o,e,d||u,"git_checkout");let _=await k(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"cloned",repo:s,path:o,branch:i||"default",shallow:r,head:_})}function Re(c,n){let e=Y(n,V);if(!I(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let r of re(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let t=$(e,r.name);if(!I($(t,".git")))continue;let s=fe(t);i.push({name:r.name,path:t,lastModified:s.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:e})}function Ae(c,n){let{repo:e,depth:i=2}=c,r=Y(n,V,e);if(!I(r))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let t={repo:e,path:r},s=$(r,"package.json");if(I(s))try{let m=JSON.parse(ye(s,"utf-8"));t.packageJson={name:m.name,version:m.version,scripts:m.scripts?Object.keys(m.scripts):[],dependencies:m.dependencies?Object.keys(m.dependencies).slice(0,30):[],devDependencies:m.devDependencies?Object.keys(m.devDependencies).slice(0,20):[]},m.dependencies?.react?t.framework="React":m.dependencies?.next?t.framework="Next.js":m.dependencies?.vue?t.framework="Vue":m.dependencies?.angular?t.framework="Angular":m.dependencies?.express?t.framework="Express":m.dependencies?.fastify&&(t.framework="Fastify")}catch{}let a=$(r,"pyproject.toml");I(a)&&(t.language="Python");let o=$(r,"go.mod");I(o)&&(t.language="Go");let l=$(r,"Cargo.toml");I(l)&&(t.language="Rust"),I(s)&&(t.language=t.language||"JavaScript/TypeScript");let d=[];function u(m,_,b){if(b>i)return;let w;try{w=re(m,{withFileTypes:!0})}catch{return}let f=w.filter(g=>!g.name.startsWith(".")&&g.name!=="node_modules"&&g.name!=="__pycache__"&&g.name!=="dist"&&g.name!=="build"&&g.name!==".git").sort((g,h)=>g.isDirectory()!==h.isDirectory()?g.isDirectory()?-1:1:g.name.localeCompare(h.name));for(let g of f){let h=g.isDirectory();d.push(`${_}${h?"\u{1F4C1}":"\u{1F4C4}"} ${g.name}`),h&&b<i&&u($(m,g.name),`${_} `,b+1)}}u(r,"",1),t.tree=d.slice(0,80),d.length>80&&(t.treeTruncated=!0);let p=["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 t.keyFilesFound=p.filter(m=>I($(r,m))),JSON.stringify(t)}import{existsSync as ke}from"fs";import{fileURLToPath as Ee}from"url";import{dirname as qe,resolve as Ge}from"path";import{resolveIntegrationToken as ne}from"@zibby/core/backend-client.js";var E=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),et=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 Chat",connectPath:"/integrations?provider=lark"},lark_docs:{id:"lark_docs",name:"Lark App",connectPath:"/integrations?provider=lark_docs"},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"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},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"}});import Oe from"crypto";var ie=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,se=/<!--\s*zbreview-summary\s*-->/i;function Ie(c){return String(c||"").replace(ie,"").replace(se,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function $e(c,n){return Oe.createHash("sha256").update(`${String(c||"")}\0${Ie(n)}`).digest("hex").slice(0,12)}function ve(c){return`
12
12
 
13
- <!-- zbfp:${c} -->`}var E=`
13
+ <!-- zbfp:${c} -->`}var q=`
14
14
 
15
- <!-- zbreview-summary -->`;function q(c){let n=ee.exec(String(c||""));return n?n[1].toLowerCase():null}function G(c){return te.test(String(c||""))}function M(c,n){let e=new Set([...n||[]].map(t=>String(t).toLowerCase())),i=[],r=0;for(let t of Array.isArray(c)?c:[]){if(!t||!t.body)continue;let s=Oe(t.path,t.body);if(e.has(s)){r+=1;continue}e.add(s),i.push({...t,_fp:s,body:`${String(t.body)}${Ae(s)}`})}return{toPost:i,skipped:r}}var U={api:{knob:"SKILL_API_TIMEOUT_MS",fallback:3e4},transfer:{knob:"SKILL_TRANSFER_TIMEOUT_MS",fallback:12e4},job:{knob:"SKILL_JOB_TIMEOUT_MS",fallback:3e5}};function Ie(c,n,e=process.env){let i=Number(e?.[c]);return Number.isFinite(i)&&i>0?Math.min(6e5,Math.max(1e3,Math.floor(i))):n}function ve(c="api",n=process.env){let e=U[c]||U.api;return Ie(e.knob,e.fallback,n)}function $e(c){return c?.name==="TimeoutError"||c?.name==="AbortError"}function Ne(c){try{return new URL(String(c?.url??c)).host||"unknown host"}catch{return"unknown host"}}function Te(c,n){if(!c)return n;let e=new AbortController,i=s=>{e.signal.aborted||e.abort(s)},r=()=>i(c.reason),t=()=>i(n.reason);return e.signal.addEventListener("abort",()=>{c.removeEventListener("abort",r),n.removeEventListener("abort",t)},{once:!0}),c.aborted?i(c.reason):n.aborted?i(n.reason):(c.addEventListener("abort",r,{once:!0}),n.addEventListener("abort",t,{once:!0})),e.signal}async function C(c,n={},e={}){let i=e.kind||"api",r=(U[i]||U.api).knob,t=e.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(e.timeoutMs))):ve(i),s=n?.signal;if(s?.aborted)throw s.reason??new DOMException("This operation was aborted","AbortError");let a=AbortSignal.timeout(t),o=Te(s,a);try{return await fetch(c,{...n,signal:o})}catch(l){throw a.aborted&&$e(l)?new Error(`${e.what||"request"} TIMED OUT after ${t}ms against ${Ne(c)} (${r})`):l}}function Ee(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let c=Pe(Le(import.meta.url)),n=ke(c,"..","bin","mcp-skill.mjs");return je(n)?n:null}async function _(c,n={}){let{token:e}=await re("github"),i=c.startsWith("https://")?c:`https://api.github.com${c}`,r={Authorization:`Bearer ${e}`,Accept:n.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...n.body?{"Content-Type":"application/json"}:{}},t=await C(i,{method:n.method||"GET",headers:r,body:n.body?JSON.stringify(n.body):void 0},{kind:"api",what:`GitHub ${n.method||"GET"} ${c}`});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`GitHub API ${t.status}: ${s.slice(0,300)}`)}return n.raw?t.text():t.json()}var x={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:k.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
15
+ <!-- zbreview-summary -->`;function G(c){let n=ie.exec(String(c||""));return n?n[1].toLowerCase():null}function M(c){return se.test(String(c||""))}function U(c,n){let e=new Set([...n||[]].map(t=>String(t).toLowerCase())),i=[],r=0;for(let t of Array.isArray(c)?c:[]){if(!t||!t.body)continue;let s=$e(t.path,t.body);if(e.has(s)){r+=1;continue}e.add(s),i.push({...t,_fp:s,body:`${String(t.body)}${ve(s)}`})}return{toPost:i,skipped:r}}var C={api:{knob:"SKILL_API_TIMEOUT_MS",fallback:3e4},transfer:{knob:"SKILL_TRANSFER_TIMEOUT_MS",fallback:12e4},job:{knob:"SKILL_JOB_TIMEOUT_MS",fallback:3e5}};function Ne(c,n,e=process.env){let i=Number(e?.[c]);return Number.isFinite(i)&&i>0?Math.min(6e5,Math.max(1e3,Math.floor(i))):n}function Te(c="api",n=process.env){let e=C[c]||C.api;return Ne(e.knob,e.fallback,n)}function je(c){return c?.name==="TimeoutError"||c?.name==="AbortError"}function Le(c){try{return new URL(String(c?.url??c)).host||"unknown host"}catch{return"unknown host"}}function Pe(c,n){if(!c)return n;let e=new AbortController,i=s=>{e.signal.aborted||e.abort(s)},r=()=>i(c.reason),t=()=>i(n.reason);return e.signal.addEventListener("abort",()=>{c.removeEventListener("abort",r),n.removeEventListener("abort",t)},{once:!0}),c.aborted?i(c.reason):n.aborted?i(n.reason):(c.addEventListener("abort",r,{once:!0}),n.addEventListener("abort",t,{once:!0})),e.signal}async function x(c,n={},e={}){let i=e.kind||"api",r=(C[i]||C.api).knob,t=e.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(e.timeoutMs))):Te(i),s=n?.signal;if(s?.aborted)throw s.reason??new DOMException("This operation was aborted","AbortError");let a=AbortSignal.timeout(t),o=Pe(s,a);try{return await fetch(c,{...n,signal:o})}catch(l){throw a.aborted&&je(l)?new Error(`${e.what||"request"} TIMED OUT after ${t}ms against ${Le(c)} (${r})`):l}}function Me(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let c=qe(Ee(import.meta.url)),n=Ge(c,"..","bin","mcp-skill.mjs");return ke(n)?n:null}async function y(c,n={}){let{token:e}=await ne("github"),i=c.startsWith("https://")?c:`https://api.github.com${c}`,r={Authorization:`Bearer ${e}`,Accept:n.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...n.body?{"Content-Type":"application/json"}:{}},t=await x(i,{method:n.method||"GET",headers:r,body:n.body?JSON.stringify(n.body):void 0},{kind:"api",what:`GitHub ${n.method||"GET"} ${c}`});if(!t.ok){let s=await t.text().catch(()=>""),a=new Error(`GitHub API ${t.status}: ${s.slice(0,300)}`);throw a.status=t.status,a}return n.raw?t.text():t.json()}var J={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:E.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
16
16
  You have access to the user's GitHub repositories. Available tools:
17
17
 
18
18
  ### Discovery
@@ -55,11 +55,11 @@ When user says "check out repo-name" or "clone repo-name":
55
55
  3. STOP. Do not offer to inspect files or ask what to do next.
56
56
 
57
57
  When user just wants to "look at" or "read" files (not clone):
58
- - Use github_get_file to read individual files via API`,resolve(){let c=Ee();if(!c)return{command:null,args:[],env:{},description:this.description};let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"node",args:[c,"../dist/github.js","githubSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(c,n){try{switch(c){case"github_search_issues":{let e=n.query;if(!e)return JSON.stringify({error:"query is required"});let i=await _(`/search/issues?q=${encodeURIComponent(e)}&per_page=${n.limit||20}`),r=(i.items||[]).map(t=>({number:t.number,title:t.title,state:t.state,repo:t.repository_url?.split("/").slice(-2).join("/"),url:t.html_url,user:t.user?.login,isPR:!!t.pull_request,labels:(t.labels||[]).map(s=>s.name),createdAt:t.created_at}));return JSON.stringify({total:i.total_count,items:r})}case"github_search_code":{let e=n.query;if(!e)return JSON.stringify({error:"query is required"});let i=n.repo?`+repo:${n.repo}`:"",r=n.language?`+language:${n.language}`:"",t=await _(`/search/code?q=${encodeURIComponent(e)}${i}${r}&per_page=${n.limit||15}`),s=(t.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:t.total_count,items:s})}case"github_get_pr":{let{owner:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await _(`/repos/${e}/${i}/pulls/${r}`);return JSON.stringify({number:t.number,title:t.title,state:t.state,merged:t.merged,body:t.body?.slice(0,5e3),user:t.user?.login,branch:t.head?.ref,headSha:t.head?.sha,base:t.base?.ref,changedFiles:t.changed_files,additions:t.additions,deletions:t.deletions,createdAt:t.created_at,mergedAt:t.merged_at,url:t.html_url,labels:(t.labels||[]).map(s=>s.name)})}case"github_get_pr_diff":{let{owner:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await _(`/repos/${e}/${i}/pulls/${r}`,{accept:"application/vnd.github.v3.diff",raw:!0}),s=t.length>15e3;return JSON.stringify({number:r,diff:s?t.slice(0,15e3):t,truncated:s,totalLength:t.length})}case"github_list_pr_files":{let{owner:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await _(`/repos/${e}/${i}/pulls/${r}/files?per_page=100`);return JSON.stringify({total:t.length,files:t.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:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await _(`/repos/${e}/${i}/pulls/${r}/comments?per_page=50`),s=await _(`/repos/${e}/${i}/issues/${r}/comments?per_page=50`),a=[...t.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,l)=>new Date(o.createdAt)-new Date(l.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:i,number:r,commentId:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let s=await _(`/repos/${e}/${i}/pulls/comments/${t}`),a=s.in_reply_to_id||s.id,o=[];try{o=await _(`/repos/${e}/${i}/pulls/${r}/comments?per_page=100`)}catch{o=[s]}(!Array.isArray(o)||o.length===0)&&(o=[s]);let l=o.filter(p=>p.id===a||p.in_reply_to_id===a).sort((p,m)=>new Date(p.created_at)-new Date(m.created_at)),d=l.length?l:[s],u=d.find(p=>p.id===a)||d[0];return JSON.stringify({rootCommentId:a,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:d.map(p=>({id:p.id,user:p.user?.login,body:(p.body||"").slice(0,4e3),createdAt:p.created_at,isRoot:p.id===a,url:p.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:i,number:r,commentId:t,body:s}=n||{};if(!e||!i||!r||!t||!s)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await _(`/repos/${e}/${i}/pulls/${r}/comments/${t}/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:e,repo:i,number:r,body:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await _(`/repos/${e}/${i}/issues/${r}/comments`,{method:"POST",body:{body:String(t)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_create_review":{let{owner:e,repo:i,number:r,body:t,event:s,comments:a}=n||{};if(!e||!i||!r)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 l=Array.isArray(a)?a.filter(h=>h&&h.path&&h.body&&(h.line!=null||h.position!=null)).map(h=>{let g={path:h.path,body:String(h.body)};return h.line!=null?(g.line=Number(h.line),g.side=h.side==="LEFT"?"LEFT":"RIGHT"):g.position=Number(h.position),g}):[];if(o!=="APPROVE"&&!t&&l.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,u=null;try{for(let h=1;h<=20;h+=1){let g=await _(`/repos/${e}/${i}/pulls/${r}/comments?per_page=100&page=${h}`);if(!Array.isArray(g)||g.length===0)break;for(let S of g){let A=q(S.body);A&&d.add(A)}if(g.length<100)break}for(let h=1;h<=20&&u==null;h+=1){let g=await _(`/repos/${e}/${i}/issues/${r}/comments?per_page=100&page=${h}`);if(!Array.isArray(g)||g.length===0)break;for(let S of g)if(G(S.body)){u=S.id;break}if(g.length<100)break}}catch{}let p=!1,m=!1;if(t){let h=`${String(t)}${E}`;try{u!=null?(await _(`/repos/${e}/${i}/issues/comments/${u}`,{method:"PATCH",body:{body:h}}),p=!0):await _(`/repos/${e}/${i}/issues/${r}/comments`,{method:"POST",body:{body:h}}),m=!0}catch{}}let{toPost:y,skipped:b}=M(l,d),w=y.map(({_fp:h,...g})=>g),f=null;if(w.length>0||o==="APPROVE"||o==="REQUEST_CHANGES"){let h={event:o};w.length>0&&(h.comments=w),w.length===0&&o==="REQUEST_CHANGES"&&(h.body="Changes requested \u2014 see the review summary comment."),f=await _(`/repos/${e}/${i}/pulls/${r}/reviews`,{method:"POST",body:h})}return JSON.stringify({ok:!0,id:f?f.id:void 0,state:f?f.state:void 0,event:o,notePosted:m,summaryUpdated:p,commentsPosted:w.length,inlineSkipped:b||void 0,url:f?f.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:i,branch:r,path:t,limit:s,since:a,until:o,page:l}=n;if(!e||!i)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(s)||20,100),u=`/repos/${e}/${i}/commits?per_page=${d}&page=${Number(l)||1}`;r&&(u+=`&sha=${encodeURIComponent(r)}`),t&&(u+=`&path=${encodeURIComponent(t)}`),a&&(u+=`&since=${encodeURIComponent(a)}`),o&&(u+=`&until=${encodeURIComponent(o)}`);let p=await _(u);return JSON.stringify({total:p.length,page:Number(l)||1,hasMore:p.length>=d,commits:p.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:e,repo:i,sha:r,includePrs:t}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await _(`/repos/${e}/${i}/commits/${r}`),a;if(t)try{let o=await _(`/repos/${e}/${i}/commits/${r}/pulls`);a=(Array.isArray(o)?o:[]).map(l=>({number:l.number,title:l.title,state:l.state,merged:!!l.merged_at,webUrl:l.html_url}))}catch{a=[]}return JSON.stringify({sha:s.sha?.slice(0,8),message:s.commit?.message,author:s.commit?.author?.name,date:s.commit?.author?.date,stats:s.stats,files:(s.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:i,path:r,ref:t}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and path are required"});let s=`/repos/${e}/${i}/contents/${encodeURIComponent(r)}`;t&&(s+=`?ref=${encodeURIComponent(t)}`);let a=await _(s);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:r,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"),l=o.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:l?o.slice(0,2e4):o,truncated:l})}case"github_get_user":try{let e=await _("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let i=e.repositories[0],r=i.owner.login,t=i.owner.type,s=t==="Organization"?`/orgs/${r}`:`/users/${r}`,a=await _(s);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:t,isOrg:t==="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(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let i=(await _("/installation/repositories?per_page=100")).repositories||[],r=new Map;for(let s of i)s.owner.type==="Organization"&&(r.has(s.owner.login)||r.set(s.owner.login,{login:s.owner.login,description:null,url:s.owner.url}));let t=Array.from(r.values());return JSON.stringify({count:t.length,orgs:t,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let y=function(h){let g=h.replace(/^~(?=$|\/|\\)/,m);return a(g)},{owner:e,repo:i,destination:r}=n;if(!e||!i)return JSON.stringify({error:"owner and repo are required"});let{execSync:t}=await import("child_process"),{join:s,resolve:a}=await import("path"),{existsSync:o,mkdirSync:l}=await import("fs"),{homedir:d,platform:u}=await import("os"),{token:p}=await re("github"),m=d(),b=r?y(r):s(m,"zibby-repos"),w=s(b,i);if(l(b,{recursive:!0}),o(w))return JSON.stringify({error:`Directory ${w} already exists. Remove it first or use a different destination.`,existingPath:w});let f=`https://x-access-token:${p}@github.com/${e}/${i}.git`;try{t(`git clone ${f} "${w}"`,{stdio:"pipe"});let h=`https://github.com/${e}/${i}.git`;j(t,w,h,p,"github_clone");let g=u()==="win32",S;return g?S=t(`dir "${w}"`,{encoding:"utf-8",shell:"cmd.exe"}):S=t(`ls -la "${w}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:w,message:`Cloned ${e}/${i} to ${w}`,contents:S.split(`
58
+ - Use github_get_file to read individual files via API`,resolve(){let c=Me();if(!c)return{command:null,args:[],env:{},description:this.description};let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"node",args:[c,"../dist/github.js","githubSkill"],env:n,description:this.description}},async handleToolCall(c,n){try{switch(c){case"github_search_issues":{let e=n.query;if(!e)return JSON.stringify({error:"query is required"});let i=await y(`/search/issues?q=${encodeURIComponent(e)}&per_page=${n.limit||20}`),r=(i.items||[]).map(t=>({number:t.number,title:t.title,state:t.state,repo:t.repository_url?.split("/").slice(-2).join("/"),url:t.html_url,user:t.user?.login,isPR:!!t.pull_request,labels:(t.labels||[]).map(s=>s.name),createdAt:t.created_at}));return JSON.stringify({total:i.total_count,items:r})}case"github_search_code":{let e=n.query;if(!e)return JSON.stringify({error:"query is required"});let i=n.repo?`+repo:${n.repo}`:"",r=n.language?`+language:${n.language}`:"",t=await y(`/search/code?q=${encodeURIComponent(e)}${i}${r}&per_page=${n.limit||15}`),s=(t.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:t.total_count,items:s})}case"github_get_pr":{let{owner:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await y(`/repos/${e}/${i}/pulls/${r}`);return JSON.stringify({number:t.number,title:t.title,state:t.state,merged:t.merged,body:t.body?.slice(0,5e3),user:t.user?.login,branch:t.head?.ref,headSha:t.head?.sha,base:t.base?.ref,changedFiles:t.changed_files,additions:t.additions,deletions:t.deletions,createdAt:t.created_at,mergedAt:t.merged_at,url:t.html_url,labels:(t.labels||[]).map(s=>s.name)})}case"github_get_pr_diff":{let{owner:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await y(`/repos/${e}/${i}/pulls/${r}`,{accept:"application/vnd.github.v3.diff",raw:!0}),s=t.length>15e3;return JSON.stringify({number:r,diff:s?t.slice(0,15e3):t,truncated:s,totalLength:t.length})}case"github_list_pr_files":{let{owner:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await y(`/repos/${e}/${i}/pulls/${r}/files?per_page=100`);return JSON.stringify({total:t.length,files:t.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:e,repo:i,number:r}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await y(`/repos/${e}/${i}/pulls/${r}/comments?per_page=50`),s=await y(`/repos/${e}/${i}/issues/${r}/comments?per_page=50`),a=[...t.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,l)=>new Date(o.createdAt)-new Date(l.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:i,number:r,commentId:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let s=await y(`/repos/${e}/${i}/pulls/comments/${t}`),a=s.in_reply_to_id||s.id,o=[];try{o=await y(`/repos/${e}/${i}/pulls/${r}/comments?per_page=100`)}catch{o=[s]}(!Array.isArray(o)||o.length===0)&&(o=[s]);let l=o.filter(p=>p.id===a||p.in_reply_to_id===a).sort((p,m)=>new Date(p.created_at)-new Date(m.created_at)),d=l.length?l:[s],u=d.find(p=>p.id===a)||d[0];return JSON.stringify({rootCommentId:a,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:d.map(p=>({id:p.id,user:p.user?.login,body:(p.body||"").slice(0,4e3),createdAt:p.created_at,isRoot:p.id===a,url:p.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:i,number:r,commentId:t,body:s}=n||{};if(!e||!i||!r||!t||!s)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await y(`/repos/${e}/${i}/pulls/${r}/comments/${t}/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:e,repo:i,number:r,body:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await y(`/repos/${e}/${i}/issues/${r}/comments`,{method:"POST",body:{body:String(t)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_create_review":{let{owner:e,repo:i,number:r,body:t,event:s,comments:a}=n||{};if(!e||!i||!r)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 l=Array.isArray(a)?a.filter(g=>g&&g.path&&g.body&&(g.line!=null||g.position!=null)).map(g=>{let h={path:g.path,body:String(g.body)};return g.line!=null?(h.line=Number(g.line),h.side=g.side==="LEFT"?"LEFT":"RIGHT"):h.position=Number(g.position),h}):[];if(o!=="APPROVE"&&!t&&l.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,u=null;try{for(let g=1;g<=20;g+=1){let h=await y(`/repos/${e}/${i}/pulls/${r}/comments?per_page=100&page=${g}`);if(!Array.isArray(h)||h.length===0)break;for(let S of h){let O=G(S.body);O&&d.add(O)}if(h.length<100)break}for(let g=1;g<=20&&u==null;g+=1){let h=await y(`/repos/${e}/${i}/issues/${r}/comments?per_page=100&page=${g}`);if(!Array.isArray(h)||h.length===0)break;for(let S of h)if(M(S.body)){u=S.id;break}if(h.length<100)break}}catch{}let p=!1,m=!1;if(t){let g=`${String(t)}${q}`;try{u!=null?(await y(`/repos/${e}/${i}/issues/comments/${u}`,{method:"PATCH",body:{body:g}}),p=!0):await y(`/repos/${e}/${i}/issues/${r}/comments`,{method:"POST",body:{body:g}}),m=!0}catch{}}let{toPost:_,skipped:b}=U(l,d),w=_.map(({_fp:g,...h})=>h),f=null;if(w.length>0||o==="APPROVE"||o==="REQUEST_CHANGES"){let g={event:o};w.length>0&&(g.comments=w),w.length===0&&o==="REQUEST_CHANGES"&&(g.body="Changes requested \u2014 see the review summary comment."),f=await y(`/repos/${e}/${i}/pulls/${r}/reviews`,{method:"POST",body:g})}return JSON.stringify({ok:!0,id:f?f.id:void 0,state:f?f.state:void 0,event:o,notePosted:m,summaryUpdated:p,commentsPosted:w.length,inlineSkipped:b||void 0,url:f?f.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:i,branch:r,path:t,limit:s,since:a,until:o,page:l}=n;if(!e||!i)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(s)||20,100),u=`/repos/${e}/${i}/commits?per_page=${d}&page=${Number(l)||1}`;r&&(u+=`&sha=${encodeURIComponent(r)}`),t&&(u+=`&path=${encodeURIComponent(t)}`),a&&(u+=`&since=${encodeURIComponent(a)}`),o&&(u+=`&until=${encodeURIComponent(o)}`);let p=await y(u);return JSON.stringify({total:p.length,page:Number(l)||1,hasMore:p.length>=d,commits:p.map(m=>({sha:m.sha?.slice(0,8),fullSha:m.sha,message:m.commit?.message?.slice(0,300),author:m.commit?.author?.name,authorEmail:m.commit?.author?.email,date:m.commit?.author?.date,url:m.html_url}))})}case"github_get_commit":{let{owner:e,repo:i,sha:r,includePrs:t}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await y(`/repos/${e}/${i}/commits/${r}`),a;if(t)try{let o=await y(`/repos/${e}/${i}/commits/${r}/pulls`);a=(Array.isArray(o)?o:[]).map(l=>({number:l.number,title:l.title,state:l.state,merged:!!l.merged_at,webUrl:l.html_url}))}catch{a=[]}return JSON.stringify({sha:s.sha?.slice(0,8),message:s.commit?.message,author:s.commit?.author?.name,date:s.commit?.author?.date,stats:s.stats,files:(s.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:i,path:r,ref:t}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and path are required"});let s=`/repos/${e}/${i}/contents/${encodeURIComponent(r)}`;t&&(s+=`?ref=${encodeURIComponent(t)}`);let a=await y(s);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:r,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"),l=o.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:l?o.slice(0,2e4):o,truncated:l})}case"github_get_user":try{let e=await y("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let i=e.repositories[0],r=i.owner.login,t=i.owner.type,s=t==="Organization"?`/orgs/${r}`:`/users/${r}`,a=await y(s);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:t,isOrg:t==="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(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let i=(await y("/installation/repositories?per_page=100")).repositories||[],r=new Map;for(let s of i)s.owner.type==="Organization"&&(r.has(s.owner.login)||r.set(s.owner.login,{login:s.owner.login,description:null,url:s.owner.url}));let t=Array.from(r.values());return JSON.stringify({count:t.length,orgs:t,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let _=function(g){let h=g.replace(/^~(?=$|\/|\\)/,m);return a(h)},{owner:e,repo:i,destination:r}=n;if(!e||!i)return JSON.stringify({error:"owner and repo are required"});let{execSync:t}=await import("child_process"),{join:s,resolve:a}=await import("path"),{existsSync:o,mkdirSync:l}=await import("fs"),{homedir:d,platform:u}=await import("os"),{token:p}=await ne("github"),m=d(),b=r?_(r):s(m,"zibby-repos"),w=s(b,i);if(l(b,{recursive:!0}),o(w))return JSON.stringify({error:`Directory ${w} already exists. Remove it first or use a different destination.`,existingPath:w});let f=`https://x-access-token:${p}@github.com/${e}/${i}.git`;try{t(`git clone ${f} "${w}"`,{stdio:"pipe"});let g=`https://github.com/${e}/${i}.git`;L(t,w,g,p,"github_clone");let h=u()==="win32",S;return h?S=t(`dir "${w}"`,{encoding:"utf-8",shell:"cmd.exe"}):S=t(`ls -la "${w}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:w,message:`Cloned ${e}/${i} to ${w}`,contents:S.split(`
59
59
  `).slice(0,30).join(`
60
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(h){let S=String(h.message||h).split(p).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"github_search_repos":{let{query:e,limit:i}=n;if(!e)return JSON.stringify({error:"query is required"});let r=await this.handleToolCall("github_list_repos",{limit:200},{}),t=JSON.parse(r);if(t.error)return JSON.stringify(t);let s=e.toLowerCase(),a=t.repos.filter(o=>o.name.toLowerCase().includes(s)||o.fullName.toLowerCase().includes(s)||o.description&&o.description.toLowerCase().includes(s));return JSON.stringify({query:e,count:a.length,repos:a.slice(0,i||20)})}case"github_list_repos":{let{owner:e,type:i,sort:r,direction:t,limit:s,query:a}=n,o=100,l=s||200,d=[],u=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")}),p=g=>{if(!a)return!0;let S=String(a).toLowerCase();return g.name&&g.name.toLowerCase().includes(S)||g.fullName&&g.fullName.toLowerCase().includes(S)||g.description&&g.description.toLowerCase().includes(S)};if(!e){let g=1,S=!0;for(;S&&d.length<l;){let T=`/installation/repositories?per_page=${o}&page=${g}`,K=(await _(T)).repositories||[];if(K.length===0)break;d=d.concat(K),S=K.length===o,g++}let A=d.map(u).filter(p),N=A.slice(0,l),le=A.length>N.length,Y=N.filter(T=>T.private).length,V=N.filter(T=>!T.private).length;return JSON.stringify({count:N.length,repos:N,truncated:le,privateCount:Y,publicCount:V,message:`Found ${Y} private and ${V} public repos`})}let m=await _(`/orgs/${e}`).then(()=>!0).catch(()=>!1),y=1,b=!0;for(;b&&d.length<l;){let g;m?g=`/orgs/${e}/repos?per_page=${o}&page=${y}&type=${i||"all"}&sort=${r||"updated"}&direction=${t||"desc"}`:g=`/users/${e}/repos?per_page=${o}&page=${y}&type=${i||"all"}&sort=${r||"updated"}&direction=${t||"desc"}`;let S=await _(g),A=Array.isArray(S)?S:[];if(A.length===0)break;d=d.concat(A),b=A.length===o,y++}let w=d.map(u).filter(p),f=w.slice(0,l),h=w.length>f.length;return JSON.stringify({count:f.length,repos:f,truncated:h})}case"github_create_pr":{let{owner:e,repo:i,head:r,title:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let s=n.base;if(!s)try{s=(await _(`/repos/${e}/${i}`)).default_branch||"main"}catch{s="main"}let a={title:String(t),head:String(r),base:String(s),body:n.body?String(n.body):"",draft:!!n.draft};try{let o=await _(`/repos/${e}/${i}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.html_url,number:o.number,branch:r,base:s,repo:`${e}/${i}`,provider:"github",draft:!!o.draft,state:o.state})}catch(o){let l=String(o.message||o);if(/GitHub API 422/.test(l))return JSON.stringify({success:!1,branch:r,base:s,repo:`${e}/${i}`,provider:"github",skippedReason:l});throw o}}case"github_merge_pr":{let{owner:e,repo:i,number:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=n.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(t))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${t})`});let s={merge_method:t};n.commitTitle&&(s.commit_title=String(n.commitTitle)),n.commitMessage&&(s.commit_message=String(n.commitMessage));try{let a=await _(`/repos/${e}/${i}/pulls/${r}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:r,provider:"github"})}catch(a){let o=String(a.message||a);if(/GitHub API (405|409|404)/.test(o))return JSON.stringify({success:!1,number:r,provider:"github",skippedReason:o});throw a}}case"github_create_issue":{let{owner:e,repo:i,title:r,body:t}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and title are required"});let s=await _(`/repos/${e}/${i}/issues`,{method:"POST",body:{title:r,body:t||""}});return JSON.stringify({number:s.number,url:s.html_url,title:s.title})}case"github_list_issues":{let{owner:e,repo:i,state:r,labels:t,since:s,assignee:a,sort:o,direction:l,limit:d}=n||{};if(!e||!i)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",r||"open"),u.set("per_page",String(d||30)),u.set("sort",o||"updated"),u.set("direction",l||"desc"),t&&u.set("labels",Array.isArray(t)?t.join(","):t),s&&u.set("since",s),a&&u.set("assignee",a);let p=await _(`/repos/${e}/${i}/issues?${u.toString()}`),m=(Array.isArray(p)?p:[]).filter(y=>!y.pull_request).map(y=>({number:y.number,title:y.title,state:y.state,labels:(y.labels||[]).map(b=>typeof b=="string"?b:b.name),assignee:y.assignee?.login||null,assignees:(y.assignees||[]).map(b=>b.login),user:y.user?.login,comments:y.comments,url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:i,number:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await _(`/repos/${e}/${i}/issues/${r}`);return t.pull_request?JSON.stringify({error:`#${r} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:t.number,title:t.title,body:t.body||"",state:t.state,stateReason:t.state_reason||null,labels:(t.labels||[]).map(s=>typeof s=="string"?s:s.name),assignee:t.assignee?.login||null,assignees:(t.assignees||[]).map(s=>s.login),user:t.user?.login,milestone:t.milestone?.title||null,comments:t.comments,url:t.html_url,createdAt:t.created_at,updatedAt:t.updated_at,closedAt:t.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:i,number:r,limit:t}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${i}/issues/${r}/comments?per_page=${t||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:e,repo:i,number:r,body:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await _(`/repos/${e}/${i}/issues/${r}/comments`,{method:"POST",body:{body:t}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_close_issue":{let{owner:e,repo:i,number:r,stateReason:t}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s={state:"closed"};t&&(s.state_reason=t);let a=await _(`/repos/${e}/${i}/issues/${r}`,{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:e,repo:i,number:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await _(`/repos/${e}/${i}/issues/${r}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:t.number,state:t.state,url:t.html_url})}case"github_label_issue":{let{owner:e,repo:i,number:r,labels:t,mode:s}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(t)?t:t?[t]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let o=s||"add";if(o==="set"){let d=await _(`/repos/${e}/${i}/issues/${r}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(o==="remove"){for(let u of a)await _(`/repos/${e}/${i}/issues/${r}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let d=await _(`/repos/${e}/${i}/issues/${r}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let l=await _(`/repos/${e}/${i}/issues/${r}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:r,labels:(Array.isArray(l)?l:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(e){return JSON.stringify({error:e.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 commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). 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:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},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)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},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 qe}from"fs";import{AsyncLocalStorage as Ge}from"async_hooks";import{fileURLToPath as Me}from"url";import{dirname as Ue,resolve as Ce}from"path";function xe(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let c=Ue(Me(import.meta.url)),n=Ce(c,"..","bin","mcp-skill.mjs");return qe(n)?n:null}function L(c){return String(c??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var J=null;function Je(c){let n;try{n=JSON.parse(c)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(n)||n.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let e=[],i=new Map;return n.forEach((r,t)=>{let s=r&&typeof r.host=="string"?r.host.trim().replace(/\/+$/,""):"",a=r&&typeof r.token=="string"?r.token.trim():"",o=r&&Array.isArray(r.repos)?r.repos:null;if(!s)throw new Error(`GITLAB_INSTANCES[${t}] is missing "host".`);if(!a)throw new Error(`GITLAB_INSTANCES[${t}] (${s}) is missing "token".`);if(!o||o.length===0)throw new Error(`GITLAB_INSTANCES[${t}] (${s}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let l=s.replace(/\/api\/v\d+$/,""),d=new Set;for(let u of o){let p=L(u);if(!p)continue;let m=i.get(p);if(m!==void 0&&m!==t)throw new Error(`GITLAB_INSTANCES claims "${p}" on more than one server (${e[m].webHost} and ${l}). A repo path must name exactly one server.`);i.set(p,t),d.add(p)}if(d.size===0)throw new Error(`GITLAB_INSTANCES[${t}] (${s}) declares no usable "repos".`);e.push({webHost:l,apiBase:/\/api\/v\d+$/.test(s)?s:`${l}/api/v4`,token:a,repos:d})}),e}function H(){let c=process.env.GITLAB_INSTANCES;if(typeof c!="string"||!c.trim())return null;if(J&&J.raw===c)return J.value;let n=Je(c);return J={raw:c,value:n},n}var B=new Ge,He="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function D(){let c=B.getStore();if(c)return c;if(H())throw new Error(He);return null}function ie(){let c=D();if(c)return c.apiBase;let n=process.env.GITLAB_API_URL;if(n)return n.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function Be(){let c=D();if(c)return{"PRIVATE-TOKEN":c.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let n=process.env.GITLAB_TOKEN;if(!n)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":n}}async function R(c,n={}){let e=/^https?:\/\//.test(c)?c:`${ie()}${c}`,i={Accept:"application/json","User-Agent":"Zibby-App",...Be(),...n.body?{"Content-Type":"application/json"}:{}},r=await C(e,{method:n.method||"GET",headers:i,body:n.body?JSON.stringify(n.body):void 0},{kind:"api",what:`GitLab ${n.method||"GET"} ${c}`});if(!r.ok){let t=await r.text().catch(()=>""),s=`GitLab API ${r.status} @ ${ie()}`;throw new Error(`${s}: ${t.slice(0,300)}`)}return n.raw?r.text():r.json()}function se(){let c=D();if(c)return c.webHost;let n=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(n?n.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function De(){let c=D();return c?c.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function O(c){let n=String(c);return/^\d+$/.test(n)?n:encodeURIComponent(n)}function ae(){let c=H();if(c){let i=new Set;for(let r of c)for(let t of r.repos)i.add(t);return i}let n=process.env.GITLAB_ALLOWED_REPOS;if(typeof n!="string"||!n.trim())return null;let e=new Set(n.split(",").map(L).filter(Boolean));return e.size?e:null}function ce(c,n){if(!c)return!0;let e=L(n);return e!==""&&c.has(e)}function Fe(c){if(!c||typeof c!="object")return null;for(let n of["projectPath","projectId","project","repo","repoPath"]){let e=c[n];if(e!=null&&String(e).trim()!=="")return String(e).trim()}return null}async function ne(c){if(!/^\d+$/.test(c))return c;try{let n=await R(`/projects/${O(c)}`);return n&&n.path_with_namespace||null}catch{return null}}async function Ke(c,n){if(!n)return{path:await ne(c),instance:null};if(!/^\d+$/.test(c)){let i=L(c);return{path:c,instance:n.find(r=>r.repos.has(i))||null}}let e=null;for(let i of n){let r=await B.run(i,()=>ne(c));if(r&&(e===null&&(e=r),i.repos.has(L(r))))return{path:r,instance:i}}return{path:e,instance:null}}async function oe(c,n){switch(c){case"gitlab_clone":{let{projectPath:e,projectId:i,destination:r,branch:t}=n||{},s=e&&String(e).trim();if(!s&&i!=null&&(/^\d+$/.test(String(i))?s=(await R(`/projects/${O(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:l,resolve:d}=await import("path"),{existsSync:u,mkdirSync:p}=await import("fs"),m=r?d(r):d(process.cwd(),".zibby","repos"),y=s.split("/").filter(Boolean).pop(),b=l(m,y);if(p(m,{recursive:!0}),u(b))return JSON.stringify({success:!0,path:b,message:`Already cloned at ${b}`,alreadyCloned:!0});let w=se().replace(/^https?:\/\//,""),f=se().startsWith("http://")?"http":"https",h=`${f}://oauth2:${a}@${w}/${s}.git`,g=t?`--branch "${String(t).replace(/"/g,"")}" `:"";try{o(`git clone --depth 1 ${g}${h} "${b}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let S=`${f}://${w}/${s}.git`;j(o,b,S,a,"gitlab_clone");let A=o(`ls -la "${b}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:b,message:`Cloned ${s} to ${b}`,contents:A.split(`
60
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(g){let S=String(g.message||g).split(p).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"github_search_repos":{let{query:e,limit:i}=n;if(!e)return JSON.stringify({error:"query is required"});let r=await this.handleToolCall("github_list_repos",{limit:200},{}),t=JSON.parse(r);if(t.error)return JSON.stringify(t);let s=e.toLowerCase(),a=t.repos.filter(o=>o.name.toLowerCase().includes(s)||o.fullName.toLowerCase().includes(s)||o.description&&o.description.toLowerCase().includes(s));return JSON.stringify({query:e,count:a.length,repos:a.slice(0,i||20)})}case"github_list_repos":{let{owner:e,type:i,sort:r,direction:t,limit:s,query:a}=n,o=100,l=s||200,d=[],u=h=>({name:h.name,fullName:h.full_name,private:h.private,description:h.description,language:h.language,defaultBranch:h.default_branch,updatedAt:h.updated_at,stars:h.stargazers_count,url:h.html_url,fullPath:h.full_name,webUrl:h.html_url,visibility:h.visibility||(h.private?"private":"public")}),p=h=>{if(!a)return!0;let S=String(a).toLowerCase();return h.name&&h.name.toLowerCase().includes(S)||h.fullName&&h.fullName.toLowerCase().includes(S)||h.description&&h.description.toLowerCase().includes(S)};if(!e){let h=1,S=!0,O=!1;for(;S&&d.length<l;){let v=`/installation/repositories?per_page=${o}&page=${h}`,N;try{N=await y(v)}catch(W){if((W?.status===401||W?.status===403)&&h===1){O=!0;break}throw W}let z=N.repositories||[];if(z.length===0)break;d=d.concat(z),S=z.length===o,h++}if(O)for(h=1,S=!0;S&&d.length<l;){let v=await y(`/user/repos?per_page=${o}&page=${h}&affiliation=owner,collaborator,organization_member&sort=${r||"updated"}&direction=${t||"desc"}`),N=Array.isArray(v)?v:[];if(N.length===0)break;d=d.concat(N),S=N.length===o,h++}let Q=d.map(u).filter(p),j=Q.slice(0,l),me=Q.length>j.length,Z=j.filter(v=>v.private).length,X=j.filter(v=>!v.private).length;return JSON.stringify({count:j.length,repos:j,truncated:me,privateCount:Z,publicCount:X,message:`Found ${Z} private and ${X} public repos`})}let m=await y(`/orgs/${e}`).then(()=>!0).catch(()=>!1),_=1,b=!0;for(;b&&d.length<l;){let h;m?h=`/orgs/${e}/repos?per_page=${o}&page=${_}&type=${i||"all"}&sort=${r||"updated"}&direction=${t||"desc"}`:h=`/users/${e}/repos?per_page=${o}&page=${_}&type=${i||"all"}&sort=${r||"updated"}&direction=${t||"desc"}`;let S=await y(h),O=Array.isArray(S)?S:[];if(O.length===0)break;d=d.concat(O),b=O.length===o,_++}let w=d.map(u).filter(p),f=w.slice(0,l),g=w.length>f.length;return JSON.stringify({count:f.length,repos:f,truncated:g})}case"github_create_pr":{let{owner:e,repo:i,head:r,title:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let s=n.base;if(!s)try{s=(await y(`/repos/${e}/${i}`)).default_branch||"main"}catch{s="main"}let a={title:String(t),head:String(r),base:String(s),body:n.body?String(n.body):"",draft:!!n.draft};try{let o=await y(`/repos/${e}/${i}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.html_url,number:o.number,branch:r,base:s,repo:`${e}/${i}`,provider:"github",draft:!!o.draft,state:o.state})}catch(o){let l=String(o.message||o);if(/GitHub API 422/.test(l))return JSON.stringify({success:!1,branch:r,base:s,repo:`${e}/${i}`,provider:"github",skippedReason:l});throw o}}case"github_merge_pr":{let{owner:e,repo:i,number:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=n.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(t))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${t})`});let s={merge_method:t};n.commitTitle&&(s.commit_title=String(n.commitTitle)),n.commitMessage&&(s.commit_message=String(n.commitMessage));try{let a=await y(`/repos/${e}/${i}/pulls/${r}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:r,provider:"github"})}catch(a){let o=String(a.message||a);if(/GitHub API (405|409|404)/.test(o))return JSON.stringify({success:!1,number:r,provider:"github",skippedReason:o});throw a}}case"github_create_issue":{let{owner:e,repo:i,title:r,body:t}=n;if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and title are required"});let s=await y(`/repos/${e}/${i}/issues`,{method:"POST",body:{title:r,body:t||""}});return JSON.stringify({number:s.number,url:s.html_url,title:s.title})}case"github_list_issues":{let{owner:e,repo:i,state:r,labels:t,since:s,assignee:a,sort:o,direction:l,limit:d}=n||{};if(!e||!i)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",r||"open"),u.set("per_page",String(d||30)),u.set("sort",o||"updated"),u.set("direction",l||"desc"),t&&u.set("labels",Array.isArray(t)?t.join(","):t),s&&u.set("since",s),a&&u.set("assignee",a);let p=await y(`/repos/${e}/${i}/issues?${u.toString()}`),m=(Array.isArray(p)?p:[]).filter(_=>!_.pull_request).map(_=>({number:_.number,title:_.title,state:_.state,labels:(_.labels||[]).map(b=>typeof b=="string"?b:b.name),assignee:_.assignee?.login||null,assignees:(_.assignees||[]).map(b=>b.login),user:_.user?.login,comments:_.comments,url:_.html_url,createdAt:_.created_at,updatedAt:_.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:i,number:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await y(`/repos/${e}/${i}/issues/${r}`);return t.pull_request?JSON.stringify({error:`#${r} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:t.number,title:t.title,body:t.body||"",state:t.state,stateReason:t.state_reason||null,labels:(t.labels||[]).map(s=>typeof s=="string"?s:s.name),assignee:t.assignee?.login||null,assignees:(t.assignees||[]).map(s=>s.login),user:t.user?.login,milestone:t.milestone?.title||null,comments:t.comments,url:t.html_url,createdAt:t.created_at,updatedAt:t.updated_at,closedAt:t.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:i,number:r,limit:t}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s=await y(`/repos/${e}/${i}/issues/${r}/comments?per_page=${t||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:e,repo:i,number:r,body:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await y(`/repos/${e}/${i}/issues/${r}/comments`,{method:"POST",body:{body:t}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_close_issue":{let{owner:e,repo:i,number:r,stateReason:t}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s={state:"closed"};t&&(s.state_reason=t);let a=await y(`/repos/${e}/${i}/issues/${r}`,{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:e,repo:i,number:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let t=await y(`/repos/${e}/${i}/issues/${r}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:t.number,state:t.state,url:t.html_url})}case"github_label_issue":{let{owner:e,repo:i,number:r,labels:t,mode:s}=n||{};if(!e||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(t)?t:t?[t]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let o=s||"add";if(o==="set"){let d=await y(`/repos/${e}/${i}/issues/${r}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(o==="remove"){for(let u of a)await y(`/repos/${e}/${i}/issues/${r}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let d=await y(`/repos/${e}/${i}/issues/${r}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let l=await y(`/repos/${e}/${i}/issues/${r}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:r,labels:(Array.isArray(l)?l:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(e){return JSON.stringify({error:e.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 commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). 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:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},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)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},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 Ue}from"fs";import{AsyncLocalStorage as Ce}from"async_hooks";import{fileURLToPath as xe}from"url";import{dirname as Je,resolve as He}from"path";function Be(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let c=Je(xe(import.meta.url)),n=He(c,"..","bin","mcp-skill.mjs");return Ue(n)?n:null}function P(c){return String(c??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var H=null;function De(c){let n;try{n=JSON.parse(c)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(n)||n.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let e=[],i=new Map;return n.forEach((r,t)=>{let s=r&&typeof r.host=="string"?r.host.trim().replace(/\/+$/,""):"",a=r&&typeof r.token=="string"?r.token.trim():"",o=r&&Array.isArray(r.repos)?r.repos:null;if(!s)throw new Error(`GITLAB_INSTANCES[${t}] is missing "host".`);if(!a)throw new Error(`GITLAB_INSTANCES[${t}] (${s}) is missing "token".`);if(!o||o.length===0)throw new Error(`GITLAB_INSTANCES[${t}] (${s}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let l=s.replace(/\/api\/v\d+$/,""),d=new Set;for(let u of o){let p=P(u);if(!p)continue;let m=i.get(p);if(m!==void 0&&m!==t)throw new Error(`GITLAB_INSTANCES claims "${p}" on more than one server (${e[m].webHost} and ${l}). A repo path must name exactly one server.`);i.set(p,t),d.add(p)}if(d.size===0)throw new Error(`GITLAB_INSTANCES[${t}] (${s}) declares no usable "repos".`);e.push({webHost:l,apiBase:/\/api\/v\d+$/.test(s)?s:`${l}/api/v4`,token:a,repos:d})}),e}function B(){let c=process.env.GITLAB_INSTANCES;if(typeof c!="string"||!c.trim())return null;if(H&&H.raw===c)return H.value;let n=De(c);return H={raw:c,value:n},n}var D=new Ce,Fe="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function F(){let c=D.getStore();if(c)return c;if(B())throw new Error(Fe);return null}function oe(){let c=F();if(c)return c.apiBase;let n=process.env.GITLAB_API_URL;if(n)return n.replace(/\/+$/,"");let e=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(e)?e:`${e}/api/v4`}function Ke(){let c=F();if(c)return{"PRIVATE-TOKEN":c.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let n=process.env.GITLAB_TOKEN;if(!n)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":n}}async function R(c,n={}){let e=/^https?:\/\//.test(c)?c:`${oe()}${c}`,i={Accept:"application/json","User-Agent":"Zibby-App",...Ke(),...n.body?{"Content-Type":"application/json"}:{}},r=await x(e,{method:n.method||"GET",headers:i,body:n.body?JSON.stringify(n.body):void 0},{kind:"api",what:`GitLab ${n.method||"GET"} ${c}`});if(!r.ok){let t=await r.text().catch(()=>""),s=`GitLab API ${r.status} @ ${oe()}`;throw new Error(`${s}: ${t.slice(0,300)}`)}return n.raw?r.text():r.json()}function ae(){let c=F();if(c)return c.webHost;let n=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(n?n.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function ze(){let c=F();return c?c.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function A(c){let n=String(c);return/^\d+$/.test(n)?n:encodeURIComponent(n)}function le(){let c=B();if(c){let i=new Set;for(let r of c)for(let t of r.repos)i.add(t);return i}let n=process.env.GITLAB_ALLOWED_REPOS;if(typeof n!="string"||!n.trim())return null;let e=new Set(n.split(",").map(P).filter(Boolean));return e.size?e:null}function de(c,n){if(!c)return!0;let e=P(n);return e!==""&&c.has(e)}function We(c){if(!c||typeof c!="object")return null;for(let n of["projectPath","projectId","project","repo","repoPath"]){let e=c[n];if(e!=null&&String(e).trim()!=="")return String(e).trim()}return null}async function ce(c){if(!/^\d+$/.test(c))return c;try{let n=await R(`/projects/${A(c)}`);return n&&n.path_with_namespace||null}catch{return null}}async function Ye(c,n){if(!n)return{path:await ce(c),instance:null};if(!/^\d+$/.test(c)){let i=P(c);return{path:c,instance:n.find(r=>r.repos.has(i))||null}}let e=null;for(let i of n){let r=await D.run(i,()=>ce(c));if(r&&(e===null&&(e=r),i.repos.has(P(r))))return{path:r,instance:i}}return{path:e,instance:null}}async function pe(c,n){switch(c){case"gitlab_clone":{let{projectPath:e,projectId:i,destination:r,branch:t}=n||{},s=e&&String(e).trim();if(!s&&i!=null&&(/^\d+$/.test(String(i))?s=(await R(`/projects/${A(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=ze();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:o}=await import("child_process"),{join:l,resolve:d}=await import("path"),{existsSync:u,mkdirSync:p}=await import("fs"),m=r?d(r):d(process.cwd(),".zibby","repos"),_=s.split("/").filter(Boolean).pop(),b=l(m,_);if(p(m,{recursive:!0}),u(b))return JSON.stringify({success:!0,path:b,message:`Already cloned at ${b}`,alreadyCloned:!0});let w=ae().replace(/^https?:\/\//,""),f=ae().startsWith("http://")?"http":"https",g=`${f}://oauth2:${a}@${w}/${s}.git`,h=t?`--branch "${String(t).replace(/"/g,"")}" `:"";try{o(`git clone --depth 1 ${h}${g} "${b}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let S=`${f}://${w}/${s}.git`;L(o,b,S,a,"gitlab_clone");let O=o(`ls -la "${b}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:b,message:`Cloned ${s} to ${b}`,contents:O.split(`
61
61
  `).slice(0,30).join(`
62
- `)})}catch(S){let A=String(S.message||S).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${A}`})}}case"gitlab_create_mr":{let e=n?.project??n?.projectId,i=n?.source_branch??n?.sourceBranch,{title:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let t=O(e),s=n?.target_branch??n?.targetBranch;if(!s)try{s=(await R(`/projects/${t}`)).default_branch||"main"}catch{s="main"}let a={source_branch:String(i),target_branch:String(s),title:String(r),description:n?.description?String(n.description):""};try{let o=await R(`/projects/${t}/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(e),provider:"gitlab",state:o.state})}catch(o){let l=String(o.message||o);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:l});throw o}}case"gitlab_accept_mr":{let e=n?.project??n?.projectId,{iid:i}=n||{};if(!e||!i)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let r=O(e),t={};n.squash!=null&&(t.squash=!!n.squash),n.mergeCommitMessage&&(t.merge_commit_message=String(n.mergeCommitMessage)),n.mergeWhenPipelineSucceeds!=null&&(t.merge_when_pipeline_succeeds=!!n.mergeWhenPipelineSucceeds);try{let s=await R(`/projects/${r}/merge_requests/${i}/merge`,{method:"PUT",body:t});return JSON.stringify({success:!0,merged:!0,sha:s.merge_commit_sha??s.sha??null,iid:s.iid??i,project:String(e),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(e),provider:"gitlab",skippedReason:a});throw s}}case"gitlab_get_mr":{let{projectId:e,iid:i}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await R(`/projects/${O(e)}/merge_requests/${i}`);return JSON.stringify({iid:r.iid,projectId:r.project_id,title:r.title,description:(r.description||"").slice(0,5e3),state:r.state,author:r.author?.username,sourceBranch:r.source_branch,targetBranch:r.target_branch,draft:r.draft??r.work_in_progress??!1,mergeStatus:r.merge_status,changesCount:r.changes_count,labels:Array.isArray(r.labels)?r.labels:[],webUrl:r.web_url,createdAt:r.created_at,updatedAt:r.updated_at,mergedAt:r.merged_at,diffRefs:r.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:i}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await R(`/projects/${O(e)}/merge_requests/${i}/changes`),t=Array.isArray(r.changes)?r.changes:[];return JSON.stringify({iid:r.iid,total:t.length,diffRefs:r.diff_refs||null,files:t.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_commits":{let{projectId:e,since:i,until:r,refName:t,page:s,perPage:a,withStats:o}=n||{};if(!e)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(a)||50,100))),l.set("page",String(Number(s)||1)),i&&l.set("since",i),r&&l.set("until",r),t&&l.set("ref_name",t),o!==!1&&l.set("with_stats","true");let d=await R(`/projects/${O(e)}/repository/commits?${l.toString()}`),u=(Array.isArray(d)?d:[]).map(p=>({id:p.id,shortId:p.short_id,title:p.title,authorName:p.author_name,authorEmail:p.author_email,authoredDate:p.authored_date,committedDate:p.committed_date,parentIds:Array.isArray(p.parent_ids)?p.parent_ids:[],stats:p.stats||null}));return JSON.stringify({page:Number(s)||1,count:u.length,hasMore:u.length>=Math.min(Number(a)||50,100),commits:u})}case"gitlab_get_commit":{let{projectId:e,sha:i,includeDiff:r,includeMrs:t}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and sha are required"});let s=await R(`/projects/${O(e)}/repository/commits/${encodeURIComponent(i)}`),a;if(t)try{let l=await R(`/projects/${O(e)}/repository/commits/${encodeURIComponent(i)}/merge_requests`);a=(Array.isArray(l)?l:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let o;if(r!==!1){let l=await R(`/projects/${O(e)}/repository/commits/${encodeURIComponent(i)}/diff`);o=(Array.isArray(l)?l:[]).map(d=>({oldPath:d.old_path,newPath:d.new_path,newFile:!!d.new_file,deletedFile:!!d.deleted_file,renamedFile:!!d.renamed_file,diff:typeof d.diff=="string"?d.diff.slice(0,3e3):""}))}return JSON.stringify({id:s.id,shortId:s.short_id,title:s.title,message:typeof s.message=="string"?s.message.slice(0,2e3):"",authorName:s.author_name,authorEmail:s.author_email,authoredDate:s.authored_date,committedDate:s.committed_date,parentIds:Array.isArray(s.parent_ids)?s.parent_ids:[],stats:s.stats||null,webUrl:s.web_url,...o?{filesChanged:o.length,files:o}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:e,state:i,targetBranch:r,sourceBranch:t,authorUsername:s,labels:a,search:o,sort:l,orderBy:d,limit:u}=n||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",i||"opened"),p.set("per_page",String(u||20)),p.set("order_by",d||"updated_at"),p.set("sort",l||"desc"),r&&p.set("target_branch",r),t&&p.set("source_branch",t),s&&p.set("author_username",s),a&&p.set("labels",Array.isArray(a)?a.join(","):a),o&&p.set("search",o);let m=await R(`/projects/${O(e)}/merge_requests?${p.toString()}`),y=(Array.isArray(m)?m:[]).map(b=>({iid:b.iid,title:b.title,state:b.state,author:b.author?.username,sourceBranch:b.source_branch,targetBranch:b.target_branch,draft:b.draft??b.work_in_progress??!1,labels:Array.isArray(b.labels)?b.labels:[],webUrl:b.web_url,createdAt:b.created_at,updatedAt:b.updated_at}));return JSON.stringify({count:y.length,mergeRequests:y})}case"gitlab_list_mr_notes":{let{projectId:e,iid:i,limit:r}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let t=await R(`/projects/${O(e)}/merge_requests/${i}/notes?per_page=${r||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(t)?t.length:0,notes:(Array.isArray(t)?t:[]).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:e,iid:i,body:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let t=await R(`/projects/${O(e)}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:t.id,createdAt:t.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:i,path:r,oldPath:t,newLine:s,oldLine:a,body:o}=n||{};if(!e||!i||!r||!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 l=O(e),d=n.diffRefs||null;if(d||(d=(await R(`/projects/${l}/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 u={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:r,old_path:t||r};s!=null&&(u.new_line=Number(s)),a!=null&&(u.old_line=Number(a));try{let p=await R(`/projects/${l}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(o),position:u}});return JSON.stringify({ok:!0,discussionId:p.id})}catch(p){return JSON.stringify({ok:!1,error:`inline anchor rejected (${p.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:e,iid:i,body:r,comments:t}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let s=O(e),a=Array.isArray(t)?t.filter(f=>f&&f.path&&f.body&&(f.newLine!=null||f.oldLine!=null)):[];if(!r&&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 R(`/projects/${s}/merge_requests/${i}`)).diff_refs||null);let l=new Set,d=null;try{for(let f=1;f<=20;f+=1){let h=await R(`/projects/${s}/merge_requests/${i}/discussions?per_page=100&page=${f}`);if(!Array.isArray(h)||h.length===0)break;for(let g of h)for(let S of g.notes||[]){let A=q(S.body);A&&l.add(A),d==null&&G(S.body)&&(d=S.id)}if(h.length<100)break}}catch{}let u=!1,p=!1;if(r){let f=`${String(r)}${E}`;try{d!=null?(await R(`/projects/${s}/merge_requests/${i}/notes/${d}`,{method:"PUT",body:{body:f}}),p=!0):await R(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:f}}),u=!0}catch{await R(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:f}}),u=!0}}let{toPost:m,skipped:y}=M(a,l),b=0,w=[];if(m.length>0&&o)for(let f of m){let h={base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha,position_type:"text",new_path:f.path,old_path:f.oldPath||f.path};f.newLine!=null&&(h.new_line=Number(f.newLine)),f.oldLine!=null&&(h.old_line=Number(f.oldLine));try{await R(`/projects/${s}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(f.body),position:h}}),b+=1}catch(g){w.push(`${f.path}:${f.newLine??f.oldLine} \u2014 ${g.message}`)}}else m.length>0&&!o&&w.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:u,summaryUpdated:p,inlinePosted:b,inlineSkipped:y||void 0,inlineErrors:w.length?w:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:i,discussionId:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let t=await R(`/projects/${O(e)}/merge_requests/${i}/discussions/${encodeURIComponent(r)}`),s=Array.isArray(t.notes)?t.notes:[],a=s.find(l=>l.position)||null,o=a?a.position:null;return JSON.stringify({discussionId:t.id,individualNote:!!t.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(l=>({id:l.id,author:l.author?.username,body:(l.body||"").slice(0,4e3),system:!!l.system,createdAt:l.created_at}))})}case"gitlab_reply_discussion":{let{projectId:e,iid:i,discussionId:r,body:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let s=await R(`/projects/${O(e)}/merge_requests/${i}/discussions/${encodeURIComponent(r)}/notes`,{method:"POST",body:{body:String(t)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_list_projects":{let{query:e,limit:i}=n||{},r=Math.min(Number(i)>0?Number(i):50,200),t=new URLSearchParams;t.set("membership","true"),t.set("simple","true"),t.set("order_by","last_activity_at"),t.set("sort","desc"),t.set("per_page",String(Math.min(r+1,100))),e&&t.set("search",String(e));let s=async()=>{let p=await R(`/projects?${t.toString()}`);return Array.isArray(p)?p:[]},a=H(),o=ae(),l=[];for(let p of a||[null]){let m=p?await B.run(p,s):await s();for(let y of m)ce(p?p.repos:o,y&&y.path_with_namespace)&&l.push({p:y,host:p?p.webHost:null})}let d=l.length>r,u=l.slice(0,r).map(({p,host:m})=>({fullPath:p.path_with_namespace,name:p.name,webUrl:p.web_url,defaultBranch:p.default_branch||null,visibility:p.visibility||null,...m?{host:m}:{}}));return JSON.stringify({count:u.length,truncated:d,projects:u})}case"gitlab_list_issues":{let{projectId:e,state:i,labels:r,assigneeUsername:t,authorUsername:s,updatedAfter:a,search:o,sort:l,orderBy:d,limit:u}=n||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",i||"opened"),p.set("per_page",String(u||30)),p.set("order_by",d||"updated_at"),p.set("sort",l||"desc"),r&&p.set("labels",Array.isArray(r)?r.join(","):r),t&&p.set("assignee_username",t),s&&p.set("author_username",s),a&&p.set("updated_after",a),o&&p.set("search",o);let m=await R(`/projects/${O(e)}/issues?${p.toString()}`),y=(Array.isArray(m)?m:[]).map(b=>({iid:b.iid,title:b.title,state:b.state,labels:Array.isArray(b.labels)?b.labels:[],author:b.author?.username,assignees:(b.assignees||[]).map(w=>w.username),userNotesCount:b.user_notes_count,webUrl:b.web_url,createdAt:b.created_at,updatedAt:b.updated_at}));return JSON.stringify({count:y.length,issues:y})}case"gitlab_get_issue":{let{projectId:e,iid:i}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await R(`/projects/${O(e)}/issues/${i}`);return JSON.stringify({iid:r.iid,projectId:r.project_id,title:r.title,description:(r.description||"").slice(0,5e3),state:r.state,labels:Array.isArray(r.labels)?r.labels:[],author:r.author?.username,assignees:(r.assignees||[]).map(t=>t.username),milestone:r.milestone?.title||null,webUrl:r.web_url,createdAt:r.created_at,updatedAt:r.updated_at,closedAt:r.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:i,body:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let t=await R(`/projects/${O(e)}/issues/${i}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:t.id,createdAt:t.created_at})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}var F={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:k.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
62
+ `)})}catch(S){let O=String(S.message||S).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${O}`})}}case"gitlab_create_mr":{let e=n?.project??n?.projectId,i=n?.source_branch??n?.sourceBranch,{title:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let t=A(e),s=n?.target_branch??n?.targetBranch;if(!s)try{s=(await R(`/projects/${t}`)).default_branch||"main"}catch{s="main"}let a={source_branch:String(i),target_branch:String(s),title:String(r),description:n?.description?String(n.description):""};try{let o=await R(`/projects/${t}/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(e),provider:"gitlab",state:o.state})}catch(o){let l=String(o.message||o);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:l});throw o}}case"gitlab_accept_mr":{let e=n?.project??n?.projectId,{iid:i}=n||{};if(!e||!i)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let r=A(e),t={};n.squash!=null&&(t.squash=!!n.squash),n.mergeCommitMessage&&(t.merge_commit_message=String(n.mergeCommitMessage)),n.mergeWhenPipelineSucceeds!=null&&(t.merge_when_pipeline_succeeds=!!n.mergeWhenPipelineSucceeds);try{let s=await R(`/projects/${r}/merge_requests/${i}/merge`,{method:"PUT",body:t});return JSON.stringify({success:!0,merged:!0,sha:s.merge_commit_sha??s.sha??null,iid:s.iid??i,project:String(e),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(e),provider:"gitlab",skippedReason:a});throw s}}case"gitlab_get_mr":{let{projectId:e,iid:i}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await R(`/projects/${A(e)}/merge_requests/${i}`);return JSON.stringify({iid:r.iid,projectId:r.project_id,title:r.title,description:(r.description||"").slice(0,5e3),state:r.state,author:r.author?.username,sourceBranch:r.source_branch,targetBranch:r.target_branch,draft:r.draft??r.work_in_progress??!1,mergeStatus:r.merge_status,changesCount:r.changes_count,labels:Array.isArray(r.labels)?r.labels:[],webUrl:r.web_url,createdAt:r.created_at,updatedAt:r.updated_at,mergedAt:r.merged_at,diffRefs:r.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:i}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await R(`/projects/${A(e)}/merge_requests/${i}/changes`),t=Array.isArray(r.changes)?r.changes:[];return JSON.stringify({iid:r.iid,total:t.length,diffRefs:r.diff_refs||null,files:t.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_commits":{let{projectId:e,since:i,until:r,refName:t,page:s,perPage:a,withStats:o}=n||{};if(!e)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(a)||50,100))),l.set("page",String(Number(s)||1)),i&&l.set("since",i),r&&l.set("until",r),t&&l.set("ref_name",t),o!==!1&&l.set("with_stats","true");let d=await R(`/projects/${A(e)}/repository/commits?${l.toString()}`),u=(Array.isArray(d)?d:[]).map(p=>({id:p.id,shortId:p.short_id,title:p.title,authorName:p.author_name,authorEmail:p.author_email,authoredDate:p.authored_date,committedDate:p.committed_date,parentIds:Array.isArray(p.parent_ids)?p.parent_ids:[],stats:p.stats||null}));return JSON.stringify({page:Number(s)||1,count:u.length,hasMore:u.length>=Math.min(Number(a)||50,100),commits:u})}case"gitlab_get_commit":{let{projectId:e,sha:i,includeDiff:r,includeMrs:t}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and sha are required"});let s=await R(`/projects/${A(e)}/repository/commits/${encodeURIComponent(i)}`),a;if(t)try{let l=await R(`/projects/${A(e)}/repository/commits/${encodeURIComponent(i)}/merge_requests`);a=(Array.isArray(l)?l:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let o;if(r!==!1){let l=await R(`/projects/${A(e)}/repository/commits/${encodeURIComponent(i)}/diff`);o=(Array.isArray(l)?l:[]).map(d=>({oldPath:d.old_path,newPath:d.new_path,newFile:!!d.new_file,deletedFile:!!d.deleted_file,renamedFile:!!d.renamed_file,diff:typeof d.diff=="string"?d.diff.slice(0,3e3):""}))}return JSON.stringify({id:s.id,shortId:s.short_id,title:s.title,message:typeof s.message=="string"?s.message.slice(0,2e3):"",authorName:s.author_name,authorEmail:s.author_email,authoredDate:s.authored_date,committedDate:s.committed_date,parentIds:Array.isArray(s.parent_ids)?s.parent_ids:[],stats:s.stats||null,webUrl:s.web_url,...o?{filesChanged:o.length,files:o}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:e,state:i,targetBranch:r,sourceBranch:t,authorUsername:s,labels:a,search:o,sort:l,orderBy:d,limit:u}=n||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",i||"opened"),p.set("per_page",String(u||20)),p.set("order_by",d||"updated_at"),p.set("sort",l||"desc"),r&&p.set("target_branch",r),t&&p.set("source_branch",t),s&&p.set("author_username",s),a&&p.set("labels",Array.isArray(a)?a.join(","):a),o&&p.set("search",o);let m=await R(`/projects/${A(e)}/merge_requests?${p.toString()}`),_=(Array.isArray(m)?m:[]).map(b=>({iid:b.iid,title:b.title,state:b.state,author:b.author?.username,sourceBranch:b.source_branch,targetBranch:b.target_branch,draft:b.draft??b.work_in_progress??!1,labels:Array.isArray(b.labels)?b.labels:[],webUrl:b.web_url,createdAt:b.created_at,updatedAt:b.updated_at}));return JSON.stringify({count:_.length,mergeRequests:_})}case"gitlab_list_mr_notes":{let{projectId:e,iid:i,limit:r}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let t=await R(`/projects/${A(e)}/merge_requests/${i}/notes?per_page=${r||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(t)?t.length:0,notes:(Array.isArray(t)?t:[]).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:e,iid:i,body:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let t=await R(`/projects/${A(e)}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:t.id,createdAt:t.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:i,path:r,oldPath:t,newLine:s,oldLine:a,body:o}=n||{};if(!e||!i||!r||!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 l=A(e),d=n.diffRefs||null;if(d||(d=(await R(`/projects/${l}/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 u={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:r,old_path:t||r};s!=null&&(u.new_line=Number(s)),a!=null&&(u.old_line=Number(a));try{let p=await R(`/projects/${l}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(o),position:u}});return JSON.stringify({ok:!0,discussionId:p.id})}catch(p){return JSON.stringify({ok:!1,error:`inline anchor rejected (${p.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:e,iid:i,body:r,comments:t}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let s=A(e),a=Array.isArray(t)?t.filter(f=>f&&f.path&&f.body&&(f.newLine!=null||f.oldLine!=null)):[];if(!r&&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 R(`/projects/${s}/merge_requests/${i}`)).diff_refs||null);let l=new Set,d=null;try{for(let f=1;f<=20;f+=1){let g=await R(`/projects/${s}/merge_requests/${i}/discussions?per_page=100&page=${f}`);if(!Array.isArray(g)||g.length===0)break;for(let h of g)for(let S of h.notes||[]){let O=G(S.body);O&&l.add(O),d==null&&M(S.body)&&(d=S.id)}if(g.length<100)break}}catch{}let u=!1,p=!1;if(r){let f=`${String(r)}${q}`;try{d!=null?(await R(`/projects/${s}/merge_requests/${i}/notes/${d}`,{method:"PUT",body:{body:f}}),p=!0):await R(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:f}}),u=!0}catch{await R(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:f}}),u=!0}}let{toPost:m,skipped:_}=U(a,l),b=0,w=[];if(m.length>0&&o)for(let f of m){let g={base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha,position_type:"text",new_path:f.path,old_path:f.oldPath||f.path};f.newLine!=null&&(g.new_line=Number(f.newLine)),f.oldLine!=null&&(g.old_line=Number(f.oldLine));try{await R(`/projects/${s}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(f.body),position:g}}),b+=1}catch(h){w.push(`${f.path}:${f.newLine??f.oldLine} \u2014 ${h.message}`)}}else m.length>0&&!o&&w.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:u,summaryUpdated:p,inlinePosted:b,inlineSkipped:_||void 0,inlineErrors:w.length?w:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:i,discussionId:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let t=await R(`/projects/${A(e)}/merge_requests/${i}/discussions/${encodeURIComponent(r)}`),s=Array.isArray(t.notes)?t.notes:[],a=s.find(l=>l.position)||null,o=a?a.position:null;return JSON.stringify({discussionId:t.id,individualNote:!!t.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(l=>({id:l.id,author:l.author?.username,body:(l.body||"").slice(0,4e3),system:!!l.system,createdAt:l.created_at}))})}case"gitlab_reply_discussion":{let{projectId:e,iid:i,discussionId:r,body:t}=n||{};if(!e||!i||!r||!t)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let s=await R(`/projects/${A(e)}/merge_requests/${i}/discussions/${encodeURIComponent(r)}/notes`,{method:"POST",body:{body:String(t)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_list_projects":{let{query:e,limit:i}=n||{},r=Math.min(Number(i)>0?Number(i):50,200),t=new URLSearchParams;t.set("membership","true"),t.set("simple","true"),t.set("order_by","last_activity_at"),t.set("sort","desc"),t.set("per_page",String(Math.min(r+1,100))),e&&t.set("search",String(e));let s=async()=>{let p=await R(`/projects?${t.toString()}`);return Array.isArray(p)?p:[]},a=B(),o=le(),l=[];for(let p of a||[null]){let m=p?await D.run(p,s):await s();for(let _ of m)de(p?p.repos:o,_&&_.path_with_namespace)&&l.push({p:_,host:p?p.webHost:null})}let d=l.length>r,u=l.slice(0,r).map(({p,host:m})=>({fullPath:p.path_with_namespace,name:p.name,webUrl:p.web_url,defaultBranch:p.default_branch||null,visibility:p.visibility||null,...m?{host:m}:{}}));return JSON.stringify({count:u.length,truncated:d,projects:u})}case"gitlab_list_issues":{let{projectId:e,state:i,labels:r,assigneeUsername:t,authorUsername:s,updatedAfter:a,search:o,sort:l,orderBy:d,limit:u}=n||{};if(!e)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("state",i||"opened"),p.set("per_page",String(u||30)),p.set("order_by",d||"updated_at"),p.set("sort",l||"desc"),r&&p.set("labels",Array.isArray(r)?r.join(","):r),t&&p.set("assignee_username",t),s&&p.set("author_username",s),a&&p.set("updated_after",a),o&&p.set("search",o);let m=await R(`/projects/${A(e)}/issues?${p.toString()}`),_=(Array.isArray(m)?m:[]).map(b=>({iid:b.iid,title:b.title,state:b.state,labels:Array.isArray(b.labels)?b.labels:[],author:b.author?.username,assignees:(b.assignees||[]).map(w=>w.username),userNotesCount:b.user_notes_count,webUrl:b.web_url,createdAt:b.created_at,updatedAt:b.updated_at}));return JSON.stringify({count:_.length,issues:_})}case"gitlab_get_issue":{let{projectId:e,iid:i}=n||{};if(!e||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await R(`/projects/${A(e)}/issues/${i}`);return JSON.stringify({iid:r.iid,projectId:r.project_id,title:r.title,description:(r.description||"").slice(0,5e3),state:r.state,labels:Array.isArray(r.labels)?r.labels:[],author:r.author?.username,assignees:(r.assignees||[]).map(t=>t.username),milestone:r.milestone?.title||null,webUrl:r.web_url,createdAt:r.created_at,updatedAt:r.updated_at,closedAt:r.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:i,body:r}=n||{};if(!e||!i||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let t=await R(`/projects/${A(e)}/issues/${i}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:t.id,createdAt:t.created_at})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}var K={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:E.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
63
63
  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:
64
64
 
65
65
  ### Discovery
@@ -85,7 +85,7 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
85
85
 
86
86
  ### Notes
87
87
  - 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.
88
- - 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 c=xe();if(!c)return{command:null,args:[],env:{},description:this.description};let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"node",args:[c,"../dist/gitlab.js","gitlabSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(c,n){try{let e=H(),i=ae(),r=null;if(i){let t=Fe(n);if(t){let{path:s,instance:a}=await Ke(t,e);if(!ce(i,s)||e&&!a)return JSON.stringify({error:`Repository "${s||t}" is not available to this project. This project's agents may only use: ${[...i].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...i]});r=a}}return r?await B.run(r,()=>oe(c,n)):await oe(c,n)}catch(e){return JSON.stringify({error:e.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_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{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 pe(c){let n=(c||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return n?{provider:"github",owner:n[1],repo:n[2]}:(n=(c||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),n?{provider:"gitlab",owner:n[1],repo:n[2]}:null)}var At={...$,id:"git-write",envKeys:[...$.envKeys||[],...x.envKeys||[],...F.envKeys||[]].filter((c,n,e)=>e.indexOf(c)===n),promptFragment:`${$.promptFragment}
88
+ - 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 c=Be();if(!c)return{command:null,args:[],env:{},description:this.description};let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);return{type:"stdio",command:"node",args:[c,"../dist/gitlab.js","gitlabSkill"],env:n,description:this.description}},async handleToolCall(c,n){try{let e=B(),i=le(),r=null;if(i){let t=We(n);if(t){let{path:s,instance:a}=await Ye(t,e);if(!de(i,s)||e&&!a)return JSON.stringify({error:`Repository "${s||t}" is not available to this project. This project's agents may only use: ${[...i].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...i]});r=a}}return r?await D.run(r,()=>pe(c,n)):await pe(c,n)}catch(e){return JSON.stringify({error:e.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_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{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 ue(c){let n=(c||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return n?{provider:"github",owner:n[1],repo:n[2]}:(n=(c||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),n?{provider:"gitlab",owner:n[1],repo:n[2]}:null)}var $t={...T,id:"git-write",envKeys:[...T.envKeys||[],...J.envKeys||[],...K.envKeys||[]].filter((c,n,e)=>e.indexOf(c)===n),promptFragment:`${T.promptFragment}
89
89
 
90
90
  ## Opening a pull request / merge request (git_open_pr)
91
91
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -97,4 +97,4 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
97
97
  To MERGE an open PR/MR, use the provider-agnostic tool:
98
98
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
99
99
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
100
- 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(c,n,e){if(c!=="git_open_pr"&&c!=="git_merge_pr")return $.handleToolCall(c,n,e);try{let i=n||{},r=i.repoUrl||i.repo_url||i.url;if(!r)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(c==="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 u=pe(r);return u?u.provider==="github"?x.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:d,mergeMethod:i.mergeMethod},e):F.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:d},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_merge_pr supports github.com and gitlab.com.`})}let t=i.head||i.source_branch||i.sourceBranch||i.branch,s=i.base||i.target_branch||i.targetBranch,{title:a,body:o}=i;if(!t||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let l=pe(r);return l?l.provider==="github"?x.handleToolCall("github_create_pr",{owner:l.owner,repo:l.repo,head:t,base:s,title:a,body:o},e):F.handleToolCall("gitlab_create_mr",{project:`${l.owner}/${l.repo}`,source_branch:t,target_branch:s,title:a,description:o},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_open_pr supports github.com and gitlab.com.`})}catch(i){return JSON.stringify({error:i.message})}},tools:[...$.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{pe as detectProvider,At as gitWriteSkill};
100
+ 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(c,n,e){if(c!=="git_open_pr"&&c!=="git_merge_pr")return T.handleToolCall(c,n,e);try{let i=n||{},r=i.repoUrl||i.repo_url||i.url;if(!r)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(c==="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 u=ue(r);return u?u.provider==="github"?J.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:d,mergeMethod:i.mergeMethod},e):K.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:d},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_merge_pr supports github.com and gitlab.com.`})}let t=i.head||i.source_branch||i.sourceBranch||i.branch,s=i.base||i.target_branch||i.targetBranch,{title:a,body:o}=i;if(!t||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let l=ue(r);return l?l.provider==="github"?J.handleToolCall("github_create_pr",{owner:l.owner,repo:l.repo,head:t,base:s,title:a,body:o},e):K.handleToolCall("gitlab_create_mr",{project:`${l.owner}/${l.repo}`,source_branch:t,target_branch:s,title:a,description:o},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_open_pr supports github.com and gitlab.com.`})}catch(i){return JSON.stringify({error:i.message})}},tools:[...T.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{ue as detectProvider,$t as gitWriteSkill};