@zibby/skills 0.2.4 → 0.2.5

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/git-write.js CHANGED
@@ -1,15 +1,14 @@
1
- import{spawn as X,execSync as ee}from"child_process";import{existsSync as $,mkdirSync as te,readdirSync as K,statSync as re,readFileSync as ie}from"fs";import{resolve as J,join as v,basename as se}from"path";var x=".zibby/repos";function D(l,n){try{let t=new URL(l);return t.protocol==="https:"&&t.host.toLowerCase()===n.toLowerCase()}catch{return!1}}function F(l,n,t){let i=new URL(l);return i.username=encodeURIComponent(n),i.password=encodeURIComponent(t),i.toString()}function ne(l){let n=String(l??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(n=n.split(t).join("***"));return n.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function P(l,n,t,i,r="clone"){try{l(`git -C "${n}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(e){let s=String(e?.message||e);i&&(s=s.split(i).join("***")),console.error(`[${r}] WARNING: failed to strip token from .git/config: ${s}`)}}function T(l,n,t={}){return new Promise((i,r)=>{let e=X(l,{cwd:n,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),s="",a="";e.stdout.on("data",o=>{s+=o.toString()}),e.stderr.on("data",o=>{a+=o.toString()}),e.on("close",o=>{o!==0?r(new Error(`Exit ${o}: ${a.trim()||s.trim()}`)):i(s.trim())}),e.on("error",o=>r(o))})}var N={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
1
+ import{spawn as X,execSync as ee}from"child_process";import{existsSync as $,mkdirSync as te,readdirSync as K,statSync as re,readFileSync as ie}from"fs";import{resolve as J,join as v,basename as se}from"path";var x=".zibby/repos";function D(l,n){try{let t=new URL(l);return t.protocol==="https:"&&t.host.toLowerCase()===n.toLowerCase()}catch{return!1}}function F(l,n,t){let i=new URL(l);return i.username=encodeURIComponent(n),i.password=encodeURIComponent(t),i.toString()}function ne(l){let n=String(l??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(n=n.split(t).join("***"));return n.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function P(l,n,t,i,r="clone"){try{l(`git -C "${n}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(e){let s=String(e?.message||e);i&&(s=s.split(i).join("***")),console.error(`[${r}] WARNING: failed to strip token from .git/config: ${s}`)}}function T(l,n,t={}){return new Promise((i,r)=>{let e=X(l,{cwd:n,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),s="",a="";e.stdout.on("data",o=>{s+=o.toString()}),e.stderr.on("data",o=>{a+=o.toString()}),e.on("close",o=>{o!==0?r(new Error(`Exit ${o}: ${a.trim()||s.trim()}`)):i(s.trim())}),e.on("error",o=>r(o))})}var N={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
5
5
  - git_explore: Quick overview of a cloned repo's structure (key files, package.json, routes, etc.)
6
6
 
7
- When a test ticket lacks context, use this workflow:
7
+ 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
12
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(l,n,t){let i=t?.options?.workspace||process.cwd();try{switch(l){case"git_checkout":return await oe(n,i);case"git_list_repos":return ae(n,i);case"git_explore":return ce(n,i);default:return JSON.stringify({error:`Unknown tool: ${l}`})}}catch(r){return JSON.stringify({error:ne(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 oe(l,n){let{url:t,branch:i,shallow:r=!0,name:e}=l;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let s=e||se(t.replace(/\.git$/,"")),a=J(n,x);te(a,{recursive:!0});let o=v(a,s),p=t,c=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,d=process.env.GITLAB_URL;if(D(t,"github.com")&&c)p=F(t,"x-access-token",c);else if(u&&d)try{let g=new URL(d).host;D(t,g)&&(p=F(t,"oauth2",u))}catch{}if($(v(o,".git"))){let g=i?`git -C "${o}" fetch "${p}" ${i} && git -C "${o}" checkout ${i} && git -C "${o}" merge --ff-only FETCH_HEAD`:`git -C "${o}" pull "${p}"`;await T(g,n);let w=await T(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"updated",repo:s,path:o,branch:i||"default",head:w})}let b=["git","clone"];r&&b.push("--depth","1"),i&&b.push("--branch",i),b.push(`"${p}"`,`"${o}"`),await T(b.join(" "),n),P(ee,o,t,c||u,"git_checkout");let _=await T(`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 ae(l,n){let t=J(n,x);if(!$(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let r of K(t,{withFileTypes:!0})){if(!r.isDirectory())continue;let e=v(t,r.name);if(!$(v(e,".git")))continue;let s=re(e);i.push({name:r.name,path:e,lastModified:s.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:t})}function ce(l,n){let{repo:t,depth:i=2}=l,r=J(n,x,t);if(!$(r))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let e={repo:t,path:r},s=v(r,"package.json");if($(s))try{let b=JSON.parse(ie(s,"utf-8"));e.packageJson={name:b.name,version:b.version,scripts:b.scripts?Object.keys(b.scripts):[],dependencies:b.dependencies?Object.keys(b.dependencies).slice(0,30):[],devDependencies:b.devDependencies?Object.keys(b.devDependencies).slice(0,20):[]},b.dependencies?.react?e.framework="React":b.dependencies?.next?e.framework="Next.js":b.dependencies?.vue?e.framework="Vue":b.dependencies?.angular?e.framework="Angular":b.dependencies?.express?e.framework="Express":b.dependencies?.fastify&&(e.framework="Fastify")}catch{}let a=v(r,"pyproject.toml");$(a)&&(e.language="Python");let o=v(r,"go.mod");$(o)&&(e.language="Go");let p=v(r,"Cargo.toml");$(p)&&(e.language="Rust"),$(s)&&(e.language=e.language||"JavaScript/TypeScript");let c=[];function u(b,_,g){if(g>i)return;let w;try{w=K(b,{withFileTypes:!0})}catch{return}let y=w.filter(m=>!m.name.startsWith(".")&&m.name!=="node_modules"&&m.name!=="__pycache__"&&m.name!=="dist"&&m.name!=="build"&&m.name!==".git").sort((m,h)=>m.isDirectory()!==h.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(h.name));for(let m of y){let h=m.isDirectory();c.push(`${_}${h?"\u{1F4C1}":"\u{1F4C4}"} ${m.name}`),h&&g<i&&u(v(b,m.name),`${_} `,g+1)}}u(r,"",1),e.tree=c.slice(0,80),c.length>80&&(e.treeTruncated=!0);let d=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return e.keyFilesFound=d.filter(b=>$(v(r,b))),JSON.stringify(e)}import{existsSync as me}from"fs";import{fileURLToPath as he}from"url";import{dirname as ge,resolve as be}from"path";import{resolveIntegrationToken as Y}from"@zibby/core/backend-client.js";var L=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Te=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});import pe from"crypto";var z=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,W=/<!--\s*zbreview-summary\s*-->/i;function de(l){return String(l||"").replace(z,"").replace(W,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function le(l,n){return pe.createHash("sha256").update(`${String(l||"")}\0${de(n)}`).digest("hex").slice(0,12)}function ue(l){return`
11
+ 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(l,n,t){let i=t?.options?.workspace||process.cwd();try{switch(l){case"git_checkout":return await oe(n,i);case"git_list_repos":return ae(n,i);case"git_explore":return ce(n,i);default:return JSON.stringify({error:`Unknown tool: ${l}`})}}catch(r){return JSON.stringify({error:ne(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 oe(l,n){let{url:t,branch:i,shallow:r=!0,name:e}=l;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let s=e||se(t.replace(/\.git$/,"")),a=J(n,x);te(a,{recursive:!0});let o=v(a,s),p=t,c=process.env.GITHUB_TOKEN,u=process.env.GITLAB_TOKEN,d=process.env.GITLAB_URL;if(D(t,"github.com")&&c)p=F(t,"x-access-token",c);else if(u&&d)try{let g=new URL(d).host;D(t,g)&&(p=F(t,"oauth2",u))}catch{}if($(v(o,".git"))){let g=i?`git -C "${o}" fetch "${p}" ${i} && git -C "${o}" checkout ${i} && git -C "${o}" merge --ff-only FETCH_HEAD`:`git -C "${o}" pull "${p}"`;await T(g,n);let w=await T(`git -C "${o}" log -1 --format="%h %s"`,n);return JSON.stringify({action:"updated",repo:s,path:o,branch:i||"default",head:w})}let b=["git","clone"];r&&b.push("--depth","1"),i&&b.push("--branch",i),b.push(`"${p}"`,`"${o}"`),await T(b.join(" "),n),P(ee,o,t,c||u,"git_checkout");let _=await T(`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 ae(l,n){let t=J(n,x);if(!$(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let i=[];for(let r of K(t,{withFileTypes:!0})){if(!r.isDirectory())continue;let e=v(t,r.name);if(!$(v(e,".git")))continue;let s=re(e);i.push({name:r.name,path:e,lastModified:s.mtime.toISOString()})}return JSON.stringify({repos:i,total:i.length,directory:t})}function ce(l,n){let{repo:t,depth:i=2}=l,r=J(n,x,t);if(!$(r))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let e={repo:t,path:r},s=v(r,"package.json");if($(s))try{let b=JSON.parse(ie(s,"utf-8"));e.packageJson={name:b.name,version:b.version,scripts:b.scripts?Object.keys(b.scripts):[],dependencies:b.dependencies?Object.keys(b.dependencies).slice(0,30):[],devDependencies:b.devDependencies?Object.keys(b.devDependencies).slice(0,20):[]},b.dependencies?.react?e.framework="React":b.dependencies?.next?e.framework="Next.js":b.dependencies?.vue?e.framework="Vue":b.dependencies?.angular?e.framework="Angular":b.dependencies?.express?e.framework="Express":b.dependencies?.fastify&&(e.framework="Fastify")}catch{}let a=v(r,"pyproject.toml");$(a)&&(e.language="Python");let o=v(r,"go.mod");$(o)&&(e.language="Go");let p=v(r,"Cargo.toml");$(p)&&(e.language="Rust"),$(s)&&(e.language=e.language||"JavaScript/TypeScript");let c=[];function u(b,_,g){if(g>i)return;let w;try{w=K(b,{withFileTypes:!0})}catch{return}let y=w.filter(m=>!m.name.startsWith(".")&&m.name!=="node_modules"&&m.name!=="__pycache__"&&m.name!=="dist"&&m.name!=="build"&&m.name!==".git").sort((m,h)=>m.isDirectory()!==h.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(h.name));for(let m of y){let h=m.isDirectory();c.push(`${_}${h?"\u{1F4C1}":"\u{1F4C4}"} ${m.name}`),h&&g<i&&u(v(b,m.name),`${_} `,g+1)}}u(r,"",1),e.tree=c.slice(0,80),c.length>80&&(e.treeTruncated=!0);let d=["README.md","README.rst","src/App.tsx","src/App.jsx","src/App.js","src/routes.tsx","src/routes.js","app/routes.tsx","app/routes.js","src/index.tsx","src/index.ts","src/main.tsx","src/main.ts","pages/_app.tsx","pages/_app.js","app/layout.tsx","docker-compose.yml","Dockerfile",".env.example"];return e.keyFilesFound=d.filter(b=>$(v(r,b))),JSON.stringify(e)}import{existsSync as me}from"fs";import{fileURLToPath as he}from"url";import{dirname as ge,resolve as be}from"path";import{resolveIntegrationToken as Y}from"@zibby/core/backend-client.js";var L=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Te=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});import pe from"crypto";var z=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,W=/<!--\s*zbreview-summary\s*-->/i;function de(l){return String(l||"").replace(z,"").replace(W,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function le(l,n){return pe.createHash("sha256").update(`${String(l||"")}\0${de(n)}`).digest("hex").slice(0,12)}function ue(l){return`
13
12
 
14
13
  <!-- zbfp:${l} -->`}var k=`
15
14
 
package/dist/git.js CHANGED
@@ -1,12 +1,11 @@
1
- import{spawn as R,execSync as L}from"child_process";import{existsSync as l,mkdirSync as N,readdirSync as $,statSync as O,readFileSync as j}from"fs";import{resolve as x,join as u,basename as E}from"path";var S=".zibby/repos";function v(c,o){try{let e=new URL(c);return e.protocol==="https:"&&e.host.toLowerCase()===o.toLowerCase()}catch{return!1}}function T(c,o,e){let r=new URL(c);return r.username=encodeURIComponent(o),r.password=encodeURIComponent(e),r.toString()}function G(c){let o=String(c??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(o=o.split(e).join("***"));return o.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function U(c,o,e,r,n="clone"){try{c(`git -C "${o}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(t){let a=String(t?.message||t);r&&(a=a.split(r).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${a}`)}}function b(c,o,e={}){return new Promise((r,n)=>{let t=R(c,{cwd:o,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),a="",d="";t.stdout.on("data",i=>{a+=i.toString()}),t.stderr.on("data",i=>{d+=i.toString()}),t.on("close",i=>{i!==0?n(new Error(`Exit ${i}: ${d.trim()||a.trim()}`)):r(a.trim())}),t.on("error",i=>n(i))})}var B={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
1
+ import{spawn as R,execSync as O}from"child_process";import{existsSync as l,mkdirSync as L,readdirSync as $,statSync as N,readFileSync as j}from"fs";import{resolve as x,join as u,basename as E}from"path";var S=".zibby/repos";function v(c,o){try{let e=new URL(c);return e.protocol==="https:"&&e.host.toLowerCase()===o.toLowerCase()}catch{return!1}}function T(c,o,e){let r=new URL(c);return r.username=encodeURIComponent(o),r.password=encodeURIComponent(e),r.toString()}function G(c){let o=String(c??"");for(let e of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])e&&(o=o.split(e).join("***"));return o.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,e=>e.replace(/:[^@\s]+@/,":***@"))}function U(c,o,e,r,n="clone"){try{c(`git -C "${o}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(t){let a=String(t?.message||t);r&&(a=a.split(r).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${a}`)}}function b(c,o,e={}){return new Promise((r,n)=>{let t=R(c,{cwd:o,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),a="",d="";t.stdout.on("data",i=>{a+=i.toString()}),t.stderr.on("data",i=>{d+=i.toString()}),t.on("close",i=>{i!==0?n(new Error(`Exit ${i}: ${d.trim()||a.trim()}`)):r(a.trim())}),t.on("error",i=>n(i))})}var P={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
5
5
  - git_explore: Quick overview of a cloned repo's structure (key files, package.json, routes, etc.)
6
6
 
7
- When a test ticket lacks context, use this workflow:
7
+ 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
12
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(c,o,e){let r=e?.options?.workspace||process.cwd();try{switch(c){case"git_checkout":return await A(o,r);case"git_list_repos":return D(o,r);case"git_explore":return I(o,r);default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(n){return JSON.stringify({error:G(n.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 A(c,o){let{url:e,branch:r,shallow:n=!0,name:t}=c;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let a=t||E(e.replace(/\.git$/,"")),d=x(o,S);N(d,{recursive:!0});let i=u(d,a),f=e,g=process.env.GITHUB_TOKEN,m=process.env.GITLAB_TOKEN,k=process.env.GITLAB_URL;if(v(e,"github.com")&&g)f=T(e,"x-access-token",g);else if(m&&k)try{let h=new URL(k).host;v(e,h)&&(f=T(e,"oauth2",m))}catch{}if(l(u(i,".git"))){let h=r?`git -C "${i}" fetch "${f}" ${r} && git -C "${i}" checkout ${r} && git -C "${i}" merge --ff-only FETCH_HEAD`:`git -C "${i}" pull "${f}"`;await b(h,o);let w=await b(`git -C "${i}" log -1 --format="%h %s"`,o);return JSON.stringify({action:"updated",repo:a,path:i,branch:r||"default",head:w})}let s=["git","clone"];n&&s.push("--depth","1"),r&&s.push("--branch",r),s.push(`"${f}"`,`"${i}"`),await b(s.join(" "),o),U(L,i,e,g||m,"git_checkout");let _=await b(`git -C "${i}" log -1 --format="%h %s"`,o);return JSON.stringify({action:"cloned",repo:a,path:i,branch:r||"default",shallow:n,head:_})}function D(c,o){let e=x(o,S);if(!l(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let r=[];for(let n of $(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let t=u(e,n.name);if(!l(u(t,".git")))continue;let a=O(t);r.push({name:n.name,path:t,lastModified:a.mtime.toISOString()})}return JSON.stringify({repos:r,total:r.length,directory:e})}function I(c,o){let{repo:e,depth:r=2}=c,n=x(o,S,e);if(!l(n))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let t={repo:e,path:n},a=u(n,"package.json");if(l(a))try{let s=JSON.parse(j(a,"utf-8"));t.packageJson={name:s.name,version:s.version,scripts:s.scripts?Object.keys(s.scripts):[],dependencies:s.dependencies?Object.keys(s.dependencies).slice(0,30):[],devDependencies:s.devDependencies?Object.keys(s.devDependencies).slice(0,20):[]},s.dependencies?.react?t.framework="React":s.dependencies?.next?t.framework="Next.js":s.dependencies?.vue?t.framework="Vue":s.dependencies?.angular?t.framework="Angular":s.dependencies?.express?t.framework="Express":s.dependencies?.fastify&&(t.framework="Fastify")}catch{}let d=u(n,"pyproject.toml");l(d)&&(t.language="Python");let i=u(n,"go.mod");l(i)&&(t.language="Go");let f=u(n,"Cargo.toml");l(f)&&(t.language="Rust"),l(a)&&(t.language=t.language||"JavaScript/TypeScript");let g=[];function m(s,_,h){if(h>r)return;let w;try{w=$(s,{withFileTypes:!0})}catch{return}let C=w.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules"&&p.name!=="__pycache__"&&p.name!=="dist"&&p.name!=="build"&&p.name!==".git").sort((p,y)=>p.isDirectory()!==y.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(y.name));for(let p of C){let y=p.isDirectory();g.push(`${_}${y?"\u{1F4C1}":"\u{1F4C4}"} ${p.name}`),y&&h<r&&m(u(s,p.name),`${_} `,h+1)}}m(n,"",1),t.tree=g.slice(0,80),g.length>80&&(t.treeTruncated=!0);let k=["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=k.filter(s=>l(u(n,s))),JSON.stringify(t)}export{B as gitSkill,v as isHttpsHost,U as scrubClonedRemoteSync,T as withCredentials};
11
+ 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(c,o,e){let r=e?.options?.workspace||process.cwd();try{switch(c){case"git_checkout":return await A(o,r);case"git_list_repos":return D(o,r);case"git_explore":return I(o,r);default:return JSON.stringify({error:`Unknown tool: ${c}`})}}catch(n){return JSON.stringify({error:G(n.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 A(c,o){let{url:e,branch:r,shallow:n=!0,name:t}=c;!e.includes("://")&&!e.startsWith("git@")&&(e=`https://github.com/${e}`);let a=t||E(e.replace(/\.git$/,"")),d=x(o,S);L(d,{recursive:!0});let i=u(d,a),g=e,f=process.env.GITHUB_TOKEN,y=process.env.GITLAB_TOKEN,k=process.env.GITLAB_URL;if(v(e,"github.com")&&f)g=T(e,"x-access-token",f);else if(y&&k)try{let h=new URL(k).host;v(e,h)&&(g=T(e,"oauth2",y))}catch{}if(l(u(i,".git"))){let h=r?`git -C "${i}" fetch "${g}" ${r} && git -C "${i}" checkout ${r} && git -C "${i}" merge --ff-only FETCH_HEAD`:`git -C "${i}" pull "${g}"`;await b(h,o);let w=await b(`git -C "${i}" log -1 --format="%h %s"`,o);return JSON.stringify({action:"updated",repo:a,path:i,branch:r||"default",head:w})}let s=["git","clone"];n&&s.push("--depth","1"),r&&s.push("--branch",r),s.push(`"${g}"`,`"${i}"`),await b(s.join(" "),o),U(O,i,e,f||y,"git_checkout");let _=await b(`git -C "${i}" log -1 --format="%h %s"`,o);return JSON.stringify({action:"cloned",repo:a,path:i,branch:r||"default",shallow:n,head:_})}function D(c,o){let e=x(o,S);if(!l(e))return JSON.stringify({repos:[],message:"No repos cloned yet"});let r=[];for(let n of $(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let t=u(e,n.name);if(!l(u(t,".git")))continue;let a=N(t);r.push({name:n.name,path:t,lastModified:a.mtime.toISOString()})}return JSON.stringify({repos:r,total:r.length,directory:e})}function I(c,o){let{repo:e,depth:r=2}=c,n=x(o,S,e);if(!l(n))return JSON.stringify({error:`Repo not found: ${e}. Run git_checkout first.`});let t={repo:e,path:n},a=u(n,"package.json");if(l(a))try{let s=JSON.parse(j(a,"utf-8"));t.packageJson={name:s.name,version:s.version,scripts:s.scripts?Object.keys(s.scripts):[],dependencies:s.dependencies?Object.keys(s.dependencies).slice(0,30):[],devDependencies:s.devDependencies?Object.keys(s.devDependencies).slice(0,20):[]},s.dependencies?.react?t.framework="React":s.dependencies?.next?t.framework="Next.js":s.dependencies?.vue?t.framework="Vue":s.dependencies?.angular?t.framework="Angular":s.dependencies?.express?t.framework="Express":s.dependencies?.fastify&&(t.framework="Fastify")}catch{}let d=u(n,"pyproject.toml");l(d)&&(t.language="Python");let i=u(n,"go.mod");l(i)&&(t.language="Go");let g=u(n,"Cargo.toml");l(g)&&(t.language="Rust"),l(a)&&(t.language=t.language||"JavaScript/TypeScript");let f=[];function y(s,_,h){if(h>r)return;let w;try{w=$(s,{withFileTypes:!0})}catch{return}let C=w.filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules"&&p.name!=="__pycache__"&&p.name!=="dist"&&p.name!=="build"&&p.name!==".git").sort((p,m)=>p.isDirectory()!==m.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(m.name));for(let p of C){let m=p.isDirectory();f.push(`${_}${m?"\u{1F4C1}":"\u{1F4C4}"} ${p.name}`),m&&h<r&&y(u(s,p.name),`${_} `,h+1)}}y(n,"",1),t.tree=f.slice(0,80),f.length>80&&(t.treeTruncated=!0);let k=["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=k.filter(s=>l(u(n,s))),JSON.stringify(t)}export{P as gitSkill,v as isHttpsHost,U as scrubClonedRemoteSync,T as withCredentials};
package/dist/gitlab.js CHANGED
@@ -2,7 +2,7 @@ import{existsSync as x}from"fs";import{fileURLToPath as E}from"url";import{dirna
2
2
 
3
3
  <!-- zbfp:${l} -->`}var N=`
4
4
 
5
- <!-- zbreview-summary -->`;function v(l){let n=L.exec(String(l||""));return n?n[1].toLowerCase():null}function P(l){return O.test(String(l||""))}function k(l,n){let r=new Set([...n||[]].map(i=>String(i).toLowerCase())),s=[],e=0;for(let i of Array.isArray(l)?l:[]){if(!i||!i.body)continue;let t=G(i.path,i.body);if(r.has(t)){e+=1;continue}r.add(t),s.push({...i,_fp:t,body:`${String(i.body)}${U(t)}`})}return{toPost:s,skipped:e}}function B(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let l=M(E(import.meta.url)),n=C(l,"..","bin","mcp-skill.mjs");return x(n)?n:null}function J(){let l=process.env.GITLAB_API_URL;if(l)return l.replace(/\/+$/,"");let n=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(n)?n:`${n}/api/v4`}function D(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let l=process.env.GITLAB_TOKEN;if(!l)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":l}}async function h(l,n={}){let r=/^https?:\/\//.test(l)?l:`${J()}${l}`,s={Accept:"application/json","User-Agent":"Zibby-App",...D(),...n.body?{"Content-Type":"application/json"}:{}},e=await fetch(r,{method:n.method||"GET",headers:s,body:n.body?JSON.stringify(n.body):void 0});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`GitLab API ${e.status}: ${i.slice(0,300)}`)}return n.raw?e.text():e.json()}function T(){let l=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(l?l.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function F(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function g(l){let n=String(l);return/^\d+$/.test(n)?n:encodeURIComponent(n)}var ge={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:A.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
5
+ <!-- zbreview-summary -->`;function v(l){let n=L.exec(String(l||""));return n?n[1].toLowerCase():null}function P(l){return O.test(String(l||""))}function T(l,n){let r=new Set([...n||[]].map(i=>String(i).toLowerCase())),s=[],e=0;for(let i of Array.isArray(l)?l:[]){if(!i||!i.body)continue;let t=G(i.path,i.body);if(r.has(t)){e+=1;continue}r.add(t),s.push({...i,_fp:t,body:`${String(i.body)}${U(t)}`})}return{toPost:s,skipped:e}}function B(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let l=M(E(import.meta.url)),n=C(l,"..","bin","mcp-skill.mjs");return x(n)?n:null}function J(){let l=process.env.GITLAB_API_URL;if(l)return l.replace(/\/+$/,"");let n=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(n)?n:`${n}/api/v4`}function D(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let l=process.env.GITLAB_TOKEN;if(!l)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":l}}async function h(l,n={}){let r=/^https?:\/\//.test(l)?l:`${J()}${l}`,s={Accept:"application/json","User-Agent":"Zibby-App",...D(),...n.body?{"Content-Type":"application/json"}:{}},e=await fetch(r,{method:n.method||"GET",headers:s,body:n.body?JSON.stringify(n.body):void 0});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`GitLab API ${e.status}: ${i.slice(0,300)}`)}return n.raw?e.text():e.json()}function k(){let l=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(l?l.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function F(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function g(l){let n=String(l);return/^\d+$/.test(n)?n:encodeURIComponent(n)}var ge={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:A.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
6
6
  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:
7
7
 
8
8
  ### Discovery
@@ -28,6 +28,6 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
28
28
 
29
29
  ### Notes
30
30
  - 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.
31
- - 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 l=B();if(!l)return{command:null,args:[],env:{},description:this.description};let n={};for(let r of this.envKeys)process.env[r]&&(n[r]=process.env[r]);return{type:"stdio",command:"node",args:[l,"../dist/gitlab.js","gitlabSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(l,n){try{switch(l){case"gitlab_clone":{let{projectPath:r,projectId:s,destination:e,branch:i}=n||{},t=r&&String(r).trim();if(!t&&s!=null&&(/^\d+$/.test(String(s))?t=(await h(`/projects/${g(s)}`))?.path_with_namespace:t=String(s).trim()),!t)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=F();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:o}=await import("child_process"),{join:p,resolve:d}=await import("path"),{existsSync:f,mkdirSync:c}=await import("fs"),_=e?d(e):d(process.cwd(),".zibby","repos"),b=t.split("/").filter(Boolean).pop(),u=p(_,b);if(c(_,{recursive:!0}),f(u))return JSON.stringify({success:!0,path:u,message:`Already cloned at ${u}`,alreadyCloned:!0});let j=T().replace(/^https?:\/\//,""),m=T().startsWith("http://")?"http":"https",y=`${m}://oauth2:${a}@${j}/${t}.git`,I=i?`--branch "${String(i).replace(/"/g,"")}" `:"";try{o(`git clone --depth 1 ${I}${y} "${u}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let w=`${m}://${j}/${t}.git`;R(o,u,w,a,"gitlab_clone");let S=o(`ls -la "${u}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:u,message:`Cloned ${t} to ${u}`,contents:S.split(`
31
+ - 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 l=B();if(!l)return{command:null,args:[],env:{},description:this.description};let n={};for(let r of this.envKeys)process.env[r]&&(n[r]=process.env[r]);return{type:"stdio",command:"node",args:[l,"../dist/gitlab.js","gitlabSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(l,n){try{switch(l){case"gitlab_clone":{let{projectPath:r,projectId:s,destination:e,branch:i}=n||{},t=r&&String(r).trim();if(!t&&s!=null&&(/^\d+$/.test(String(s))?t=(await h(`/projects/${g(s)}`))?.path_with_namespace:t=String(s).trim()),!t)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=F();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:o}=await import("child_process"),{join:p,resolve:d}=await import("path"),{existsSync:f,mkdirSync:c}=await import("fs"),_=e?d(e):d(process.cwd(),".zibby","repos"),b=t.split("/").filter(Boolean).pop(),u=p(_,b);if(c(_,{recursive:!0}),f(u))return JSON.stringify({success:!0,path:u,message:`Already cloned at ${u}`,alreadyCloned:!0});let j=k().replace(/^https?:\/\//,""),m=k().startsWith("http://")?"http":"https",y=`${m}://oauth2:${a}@${j}/${t}.git`,I=i?`--branch "${String(i).replace(/"/g,"")}" `:"";try{o(`git clone --depth 1 ${I}${y} "${u}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let w=`${m}://${j}/${t}.git`;R(o,u,w,a,"gitlab_clone");let S=o(`ls -la "${u}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:u,message:`Cloned ${t} to ${u}`,contents:S.split(`
32
32
  `).slice(0,30).join(`
33
- `)})}catch(w){let S=String(w.message||w).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"gitlab_create_mr":{let r=n?.project??n?.projectId,s=n?.source_branch??n?.sourceBranch,{title:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let i=g(r),t=n?.target_branch??n?.targetBranch;if(!t)try{t=(await h(`/projects/${i}`)).default_branch||"main"}catch{t="main"}let a={source_branch:String(s),target_branch:String(t),title:String(e),description:n?.description?String(n.description):""};try{let o=await h(`/projects/${i}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.web_url,number:o.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(r),provider:"gitlab",state:o.state})}catch(o){let p=String(o.message||o);if(/GitLab API (409|400)/.test(p))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(r),provider:"gitlab",skippedReason:p});throw o}}case"gitlab_accept_mr":{let r=n?.project??n?.projectId,{iid:s}=n||{};if(!r||!s)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let e=g(r),i={};n.squash!=null&&(i.squash=!!n.squash),n.mergeCommitMessage&&(i.merge_commit_message=String(n.mergeCommitMessage)),n.mergeWhenPipelineSucceeds!=null&&(i.merge_when_pipeline_succeeds=!!n.mergeWhenPipelineSucceeds);try{let t=await h(`/projects/${e}/merge_requests/${s}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:t.merge_commit_sha??t.sha??null,iid:t.iid??s,project:String(r),provider:"gitlab",state:t.state})}catch(t){let a=String(t.message||t);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:s,project:String(r),provider:"gitlab",skippedReason:a});throw t}}case"gitlab_get_mr":{let{projectId:r,iid:s}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let e=await h(`/projects/${g(r)}/merge_requests/${s}`);return JSON.stringify({iid:e.iid,projectId:e.project_id,title:e.title,description:(e.description||"").slice(0,5e3),state:e.state,author:e.author?.username,sourceBranch:e.source_branch,targetBranch:e.target_branch,draft:e.draft??e.work_in_progress??!1,mergeStatus:e.merge_status,changesCount:e.changes_count,labels:Array.isArray(e.labels)?e.labels:[],webUrl:e.web_url,createdAt:e.created_at,updatedAt:e.updated_at,mergedAt:e.merged_at,diffRefs:e.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:r,iid:s}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let e=await h(`/projects/${g(r)}/merge_requests/${s}/changes`),i=Array.isArray(e.changes)?e.changes:[];return JSON.stringify({iid:e.iid,total:i.length,diffRefs:e.diff_refs||null,files:i.map(t=>({oldPath:t.old_path,newPath:t.new_path,newFile:!!t.new_file,deletedFile:!!t.deleted_file,renamedFile:!!t.renamed_file,diff:typeof t.diff=="string"?t.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:r,since:s,until:e,refName:i,page:t,perPage:a,withStats:o}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("per_page",String(Math.min(Number(a)||50,100))),p.set("page",String(Number(t)||1)),s&&p.set("since",s),e&&p.set("until",e),i&&p.set("ref_name",i),o!==!1&&p.set("with_stats","true");let d=await h(`/projects/${g(r)}/repository/commits?${p.toString()}`),f=(Array.isArray(d)?d:[]).map(c=>({id:c.id,shortId:c.short_id,title:c.title,authorName:c.author_name,authorEmail:c.author_email,authoredDate:c.authored_date,committedDate:c.committed_date,parentIds:Array.isArray(c.parent_ids)?c.parent_ids:[],stats:c.stats||null}));return JSON.stringify({page:Number(t)||1,count:f.length,hasMore:f.length>=Math.min(Number(a)||50,100),commits:f})}case"gitlab_get_commit":{let{projectId:r,sha:s,includeDiff:e,includeMrs:i}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and sha are required"});let t=await h(`/projects/${g(r)}/repository/commits/${encodeURIComponent(s)}`),a;if(i)try{let p=await h(`/projects/${g(r)}/repository/commits/${encodeURIComponent(s)}/merge_requests`);a=(Array.isArray(p)?p:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let o;if(e!==!1){let p=await h(`/projects/${g(r)}/repository/commits/${encodeURIComponent(s)}/diff`);o=(Array.isArray(p)?p:[]).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:t.id,shortId:t.short_id,title:t.title,message:typeof t.message=="string"?t.message.slice(0,2e3):"",authorName:t.author_name,authorEmail:t.author_email,authoredDate:t.authored_date,committedDate:t.committed_date,parentIds:Array.isArray(t.parent_ids)?t.parent_ids:[],stats:t.stats||null,webUrl:t.web_url,...o?{filesChanged:o.length,files:o}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:r,state:s,targetBranch:e,sourceBranch:i,authorUsername:t,labels:a,search:o,sort:p,orderBy:d,limit:f}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let c=new URLSearchParams;c.set("state",s||"opened"),c.set("per_page",String(f||20)),c.set("order_by",d||"updated_at"),c.set("sort",p||"desc"),e&&c.set("target_branch",e),i&&c.set("source_branch",i),t&&c.set("author_username",t),a&&c.set("labels",Array.isArray(a)?a.join(","):a),o&&c.set("search",o);let _=await h(`/projects/${g(r)}/merge_requests?${c.toString()}`),b=(Array.isArray(_)?_:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,author:u.author?.username,sourceBranch:u.source_branch,targetBranch:u.target_branch,draft:u.draft??u.work_in_progress??!1,labels:Array.isArray(u.labels)?u.labels:[],webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:b.length,mergeRequests:b})}case"gitlab_list_mr_notes":{let{projectId:r,iid:s,limit:e}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let i=await h(`/projects/${g(r)}/merge_requests/${s}/notes?per_page=${e||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(i)?i.length:0,notes:(Array.isArray(i)?i:[]).map(t=>({id:t.id,author:t.author?.username,body:(t.body||"").slice(0,1e3),system:!!t.system,createdAt:t.created_at}))})}case"gitlab_post_mr_note":{let{projectId:r,iid:s,body:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await h(`/projects/${g(r)}/merge_requests/${s}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_post_mr_discussion":{let{projectId:r,iid:s,path:e,oldPath:i,newLine:t,oldLine:a,body:o}=n||{};if(!r||!s||!e||!o)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(t==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let p=g(r),d=n.diffRefs||null;if(d||(d=(await h(`/projects/${p}/merge_requests/${s}`)).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 f={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:e,old_path:i||e};t!=null&&(f.new_line=Number(t)),a!=null&&(f.old_line=Number(a));try{let c=await h(`/projects/${p}/merge_requests/${s}/discussions`,{method:"POST",body:{body:String(o),position:f}});return JSON.stringify({ok:!0,discussionId:c.id})}catch(c){return JSON.stringify({ok:!1,error:`inline anchor rejected (${c.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:r,iid:s,body:e,comments:i}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let t=g(r),a=Array.isArray(i)?i.filter(m=>m&&m.path&&m.body&&(m.newLine!=null||m.oldLine!=null)):[];if(!e&&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 h(`/projects/${t}/merge_requests/${s}`)).diff_refs||null);let p=new Set,d=null;try{for(let m=1;m<=20;m+=1){let y=await h(`/projects/${t}/merge_requests/${s}/discussions?per_page=100&page=${m}`);if(!Array.isArray(y)||y.length===0)break;for(let I of y)for(let w of I.notes||[]){let S=v(w.body);S&&p.add(S),d==null&&P(w.body)&&(d=w.id)}if(y.length<100)break}}catch{}let f=!1,c=!1;if(e){let m=`${String(e)}${N}`;try{d!=null?(await h(`/projects/${t}/merge_requests/${s}/notes/${d}`,{method:"PUT",body:{body:m}}),c=!0):await h(`/projects/${t}/merge_requests/${s}/notes`,{method:"POST",body:{body:m}}),f=!0}catch{await h(`/projects/${t}/merge_requests/${s}/notes`,{method:"POST",body:{body:m}}),f=!0}}let{toPost:_,skipped:b}=k(a,p),u=0,j=[];if(_.length>0&&o)for(let m of _){let y={base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha,position_type:"text",new_path:m.path,old_path:m.oldPath||m.path};m.newLine!=null&&(y.new_line=Number(m.newLine)),m.oldLine!=null&&(y.old_line=Number(m.oldLine));try{await h(`/projects/${t}/merge_requests/${s}/discussions`,{method:"POST",body:{body:String(m.body),position:y}}),u+=1}catch(I){j.push(`${m.path}:${m.newLine??m.oldLine} \u2014 ${I.message}`)}}else _.length>0&&!o&&j.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:f,summaryUpdated:c,inlinePosted:u,inlineSkipped:b||void 0,inlineErrors:j.length?j:void 0})}case"gitlab_get_discussion":{let{projectId:r,iid:s,discussionId:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let i=await h(`/projects/${g(r)}/merge_requests/${s}/discussions/${encodeURIComponent(e)}`),t=Array.isArray(i.notes)?i.notes:[],a=t.find(p=>p.position)||null,o=a?a.position:null;return JSON.stringify({discussionId:i.id,individualNote:!!i.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:t.map(p=>({id:p.id,author:p.author?.username,body:(p.body||"").slice(0,4e3),system:!!p.system,createdAt:p.created_at}))})}case"gitlab_reply_discussion":{let{projectId:r,iid:s,discussionId:e,body:i}=n||{};if(!r||!s||!e||!i)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let t=await h(`/projects/${g(r)}/merge_requests/${s}/discussions/${encodeURIComponent(e)}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:t.id,createdAt:t.created_at})}case"gitlab_list_projects":{let{query:r,limit:s}=n||{},e=Math.min(Number(s)>0?Number(s):50,200),i=new URLSearchParams;i.set("membership","true"),i.set("simple","true"),i.set("order_by","last_activity_at"),i.set("sort","desc"),i.set("per_page",String(Math.min(e+1,100))),r&&i.set("search",String(r));let t=await h(`/projects?${i.toString()}`),a=Array.isArray(t)?t:[],o=a.length>e,p=a.slice(0,e).map(d=>({fullPath:d.path_with_namespace,name:d.name,webUrl:d.web_url,defaultBranch:d.default_branch||null,visibility:d.visibility||null}));return JSON.stringify({count:p.length,truncated:o,projects:p})}case"gitlab_list_issues":{let{projectId:r,state:s,labels:e,assigneeUsername:i,authorUsername:t,updatedAfter:a,search:o,sort:p,orderBy:d,limit:f}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let c=new URLSearchParams;c.set("state",s||"opened"),c.set("per_page",String(f||30)),c.set("order_by",d||"updated_at"),c.set("sort",p||"desc"),e&&c.set("labels",Array.isArray(e)?e.join(","):e),i&&c.set("assignee_username",i),t&&c.set("author_username",t),a&&c.set("updated_after",a),o&&c.set("search",o);let _=await h(`/projects/${g(r)}/issues?${c.toString()}`),b=(Array.isArray(_)?_:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,labels:Array.isArray(u.labels)?u.labels:[],author:u.author?.username,assignees:(u.assignees||[]).map(j=>j.username),userNotesCount:u.user_notes_count,webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"gitlab_get_issue":{let{projectId:r,iid:s}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let e=await h(`/projects/${g(r)}/issues/${s}`);return JSON.stringify({iid:e.iid,projectId:e.project_id,title:e.title,description:(e.description||"").slice(0,5e3),state:e.state,labels:Array.isArray(e.labels)?e.labels:[],author:e.author?.username,assignees:(e.assignees||[]).map(i=>i.username),milestone:e.milestone?.title||null,webUrl:e.web_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"gitlab_add_issue_comment":{let{projectId:r,iid:s,body:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await h(`/projects/${g(r)}/issues/${s}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}default:return JSON.stringify({error:`Unknown tool: ${l}`})}}catch(r){return JSON.stringify({error:r.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_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"]}}]};export{ge as gitlabSkill,h as glFetch};
33
+ `)})}catch(w){let S=String(w.message||w).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"gitlab_create_mr":{let r=n?.project??n?.projectId,s=n?.source_branch??n?.sourceBranch,{title:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let i=g(r),t=n?.target_branch??n?.targetBranch;if(!t)try{t=(await h(`/projects/${i}`)).default_branch||"main"}catch{t="main"}let a={source_branch:String(s),target_branch:String(t),title:String(e),description:n?.description?String(n.description):""};try{let o=await h(`/projects/${i}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.web_url,number:o.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(r),provider:"gitlab",state:o.state})}catch(o){let p=String(o.message||o);if(/GitLab API (409|400)/.test(p))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(r),provider:"gitlab",skippedReason:p});throw o}}case"gitlab_accept_mr":{let r=n?.project??n?.projectId,{iid:s}=n||{};if(!r||!s)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let e=g(r),i={};n.squash!=null&&(i.squash=!!n.squash),n.mergeCommitMessage&&(i.merge_commit_message=String(n.mergeCommitMessage)),n.mergeWhenPipelineSucceeds!=null&&(i.merge_when_pipeline_succeeds=!!n.mergeWhenPipelineSucceeds);try{let t=await h(`/projects/${e}/merge_requests/${s}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:t.merge_commit_sha??t.sha??null,iid:t.iid??s,project:String(r),provider:"gitlab",state:t.state})}catch(t){let a=String(t.message||t);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:s,project:String(r),provider:"gitlab",skippedReason:a});throw t}}case"gitlab_get_mr":{let{projectId:r,iid:s}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let e=await h(`/projects/${g(r)}/merge_requests/${s}`);return JSON.stringify({iid:e.iid,projectId:e.project_id,title:e.title,description:(e.description||"").slice(0,5e3),state:e.state,author:e.author?.username,sourceBranch:e.source_branch,targetBranch:e.target_branch,draft:e.draft??e.work_in_progress??!1,mergeStatus:e.merge_status,changesCount:e.changes_count,labels:Array.isArray(e.labels)?e.labels:[],webUrl:e.web_url,createdAt:e.created_at,updatedAt:e.updated_at,mergedAt:e.merged_at,diffRefs:e.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:r,iid:s}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let e=await h(`/projects/${g(r)}/merge_requests/${s}/changes`),i=Array.isArray(e.changes)?e.changes:[];return JSON.stringify({iid:e.iid,total:i.length,diffRefs:e.diff_refs||null,files:i.map(t=>({oldPath:t.old_path,newPath:t.new_path,newFile:!!t.new_file,deletedFile:!!t.deleted_file,renamedFile:!!t.renamed_file,diff:typeof t.diff=="string"?t.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:r,since:s,until:e,refName:i,page:t,perPage:a,withStats:o}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let p=new URLSearchParams;p.set("per_page",String(Math.min(Number(a)||50,100))),p.set("page",String(Number(t)||1)),s&&p.set("since",s),e&&p.set("until",e),i&&p.set("ref_name",i),o!==!1&&p.set("with_stats","true");let d=await h(`/projects/${g(r)}/repository/commits?${p.toString()}`),f=(Array.isArray(d)?d:[]).map(c=>({id:c.id,shortId:c.short_id,title:c.title,authorName:c.author_name,authorEmail:c.author_email,authoredDate:c.authored_date,committedDate:c.committed_date,parentIds:Array.isArray(c.parent_ids)?c.parent_ids:[],stats:c.stats||null}));return JSON.stringify({page:Number(t)||1,count:f.length,hasMore:f.length>=Math.min(Number(a)||50,100),commits:f})}case"gitlab_get_commit":{let{projectId:r,sha:s,includeDiff:e,includeMrs:i}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and sha are required"});let t=await h(`/projects/${g(r)}/repository/commits/${encodeURIComponent(s)}`),a;if(i)try{let p=await h(`/projects/${g(r)}/repository/commits/${encodeURIComponent(s)}/merge_requests`);a=(Array.isArray(p)?p:[]).map(d=>({iid:d.iid,title:d.title,state:d.state,webUrl:d.web_url}))}catch{a=[]}let o;if(e!==!1){let p=await h(`/projects/${g(r)}/repository/commits/${encodeURIComponent(s)}/diff`);o=(Array.isArray(p)?p:[]).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:t.id,shortId:t.short_id,title:t.title,message:typeof t.message=="string"?t.message.slice(0,2e3):"",authorName:t.author_name,authorEmail:t.author_email,authoredDate:t.authored_date,committedDate:t.committed_date,parentIds:Array.isArray(t.parent_ids)?t.parent_ids:[],stats:t.stats||null,webUrl:t.web_url,...o?{filesChanged:o.length,files:o}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:r,state:s,targetBranch:e,sourceBranch:i,authorUsername:t,labels:a,search:o,sort:p,orderBy:d,limit:f}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let c=new URLSearchParams;c.set("state",s||"opened"),c.set("per_page",String(f||20)),c.set("order_by",d||"updated_at"),c.set("sort",p||"desc"),e&&c.set("target_branch",e),i&&c.set("source_branch",i),t&&c.set("author_username",t),a&&c.set("labels",Array.isArray(a)?a.join(","):a),o&&c.set("search",o);let _=await h(`/projects/${g(r)}/merge_requests?${c.toString()}`),b=(Array.isArray(_)?_:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,author:u.author?.username,sourceBranch:u.source_branch,targetBranch:u.target_branch,draft:u.draft??u.work_in_progress??!1,labels:Array.isArray(u.labels)?u.labels:[],webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:b.length,mergeRequests:b})}case"gitlab_list_mr_notes":{let{projectId:r,iid:s,limit:e}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let i=await h(`/projects/${g(r)}/merge_requests/${s}/notes?per_page=${e||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(i)?i.length:0,notes:(Array.isArray(i)?i:[]).map(t=>({id:t.id,author:t.author?.username,body:(t.body||"").slice(0,1e3),system:!!t.system,createdAt:t.created_at}))})}case"gitlab_post_mr_note":{let{projectId:r,iid:s,body:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await h(`/projects/${g(r)}/merge_requests/${s}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_post_mr_discussion":{let{projectId:r,iid:s,path:e,oldPath:i,newLine:t,oldLine:a,body:o}=n||{};if(!r||!s||!e||!o)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(t==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let p=g(r),d=n.diffRefs||null;if(d||(d=(await h(`/projects/${p}/merge_requests/${s}`)).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 f={base_sha:d.base_sha,start_sha:d.start_sha,head_sha:d.head_sha,position_type:"text",new_path:e,old_path:i||e};t!=null&&(f.new_line=Number(t)),a!=null&&(f.old_line=Number(a));try{let c=await h(`/projects/${p}/merge_requests/${s}/discussions`,{method:"POST",body:{body:String(o),position:f}});return JSON.stringify({ok:!0,discussionId:c.id})}catch(c){return JSON.stringify({ok:!1,error:`inline anchor rejected (${c.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:r,iid:s,body:e,comments:i}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let t=g(r),a=Array.isArray(i)?i.filter(m=>m&&m.path&&m.body&&(m.newLine!=null||m.oldLine!=null)):[];if(!e&&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 h(`/projects/${t}/merge_requests/${s}`)).diff_refs||null);let p=new Set,d=null;try{for(let m=1;m<=20;m+=1){let y=await h(`/projects/${t}/merge_requests/${s}/discussions?per_page=100&page=${m}`);if(!Array.isArray(y)||y.length===0)break;for(let I of y)for(let w of I.notes||[]){let S=v(w.body);S&&p.add(S),d==null&&P(w.body)&&(d=w.id)}if(y.length<100)break}}catch{}let f=!1,c=!1;if(e){let m=`${String(e)}${N}`;try{d!=null?(await h(`/projects/${t}/merge_requests/${s}/notes/${d}`,{method:"PUT",body:{body:m}}),c=!0):await h(`/projects/${t}/merge_requests/${s}/notes`,{method:"POST",body:{body:m}}),f=!0}catch{await h(`/projects/${t}/merge_requests/${s}/notes`,{method:"POST",body:{body:m}}),f=!0}}let{toPost:_,skipped:b}=T(a,p),u=0,j=[];if(_.length>0&&o)for(let m of _){let y={base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha,position_type:"text",new_path:m.path,old_path:m.oldPath||m.path};m.newLine!=null&&(y.new_line=Number(m.newLine)),m.oldLine!=null&&(y.old_line=Number(m.oldLine));try{await h(`/projects/${t}/merge_requests/${s}/discussions`,{method:"POST",body:{body:String(m.body),position:y}}),u+=1}catch(I){j.push(`${m.path}:${m.newLine??m.oldLine} \u2014 ${I.message}`)}}else _.length>0&&!o&&j.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:f,summaryUpdated:c,inlinePosted:u,inlineSkipped:b||void 0,inlineErrors:j.length?j:void 0})}case"gitlab_get_discussion":{let{projectId:r,iid:s,discussionId:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let i=await h(`/projects/${g(r)}/merge_requests/${s}/discussions/${encodeURIComponent(e)}`),t=Array.isArray(i.notes)?i.notes:[],a=t.find(p=>p.position)||null,o=a?a.position:null;return JSON.stringify({discussionId:i.id,individualNote:!!i.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:t.map(p=>({id:p.id,author:p.author?.username,body:(p.body||"").slice(0,4e3),system:!!p.system,createdAt:p.created_at}))})}case"gitlab_reply_discussion":{let{projectId:r,iid:s,discussionId:e,body:i}=n||{};if(!r||!s||!e||!i)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let t=await h(`/projects/${g(r)}/merge_requests/${s}/discussions/${encodeURIComponent(e)}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:t.id,createdAt:t.created_at})}case"gitlab_list_projects":{let{query:r,limit:s}=n||{},e=Math.min(Number(s)>0?Number(s):50,200),i=new URLSearchParams;i.set("membership","true"),i.set("simple","true"),i.set("order_by","last_activity_at"),i.set("sort","desc"),i.set("per_page",String(Math.min(e+1,100))),r&&i.set("search",String(r));let t=await h(`/projects?${i.toString()}`),a=Array.isArray(t)?t:[],o=a.length>e,p=a.slice(0,e).map(d=>({fullPath:d.path_with_namespace,name:d.name,webUrl:d.web_url,defaultBranch:d.default_branch||null,visibility:d.visibility||null}));return JSON.stringify({count:p.length,truncated:o,projects:p})}case"gitlab_list_issues":{let{projectId:r,state:s,labels:e,assigneeUsername:i,authorUsername:t,updatedAfter:a,search:o,sort:p,orderBy:d,limit:f}=n||{};if(!r)return JSON.stringify({error:"projectId is required"});let c=new URLSearchParams;c.set("state",s||"opened"),c.set("per_page",String(f||30)),c.set("order_by",d||"updated_at"),c.set("sort",p||"desc"),e&&c.set("labels",Array.isArray(e)?e.join(","):e),i&&c.set("assignee_username",i),t&&c.set("author_username",t),a&&c.set("updated_after",a),o&&c.set("search",o);let _=await h(`/projects/${g(r)}/issues?${c.toString()}`),b=(Array.isArray(_)?_:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,labels:Array.isArray(u.labels)?u.labels:[],author:u.author?.username,assignees:(u.assignees||[]).map(j=>j.username),userNotesCount:u.user_notes_count,webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"gitlab_get_issue":{let{projectId:r,iid:s}=n||{};if(!r||!s)return JSON.stringify({error:"projectId and iid are required"});let e=await h(`/projects/${g(r)}/issues/${s}`);return JSON.stringify({iid:e.iid,projectId:e.project_id,title:e.title,description:(e.description||"").slice(0,5e3),state:e.state,labels:Array.isArray(e.labels)?e.labels:[],author:e.author?.username,assignees:(e.assignees||[]).map(i=>i.username),milestone:e.milestone?.title||null,webUrl:e.web_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"gitlab_add_issue_comment":{let{projectId:r,iid:s,body:e}=n||{};if(!r||!s||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let i=await h(`/projects/${g(r)}/issues/${s}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}default:return JSON.stringify({error:`Unknown tool: ${l}`})}}catch(r){return JSON.stringify({error:r.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_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"]}}]};export{ge as gitlabSkill,h as glFetch};
package/dist/index.js CHANGED
@@ -71,18 +71,17 @@ When user asks to move/transition ticket status:
71
71
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
72
72
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
73
73
  5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
74
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=yo();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let t of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[t]&&(e[t]=process.env[t]);return{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await L("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await L(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await L("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await Fr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await L(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await L(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await Fr(t),f=bo(i,h)}catch{}let b={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let g=await L("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&ue(f.requested)!==ue(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(_.sprintMove=await zt({issueKey:g.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Kr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await L(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(b=>({key:b.key,project:b.fields?.project?.key,summary:b.fields?.summary,status:b.fields?.status?.name,assignee:b.fields?.assignee?.displayName||"Unassigned",priority:b.fields?.priority?.name,type:b.fields?.issuetype?.name})),h={};for(let b of f)h[b.status]=(h[b.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await L(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ct(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await L(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await L(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Le(a),m=p.find(f=>Le(f?.name||"")===u||Le(f?.to?.name||"")===u);if(!m){let f=Ht(a);f.length>=2&&(m=p.find(h=>{let b=Ht(h?.name||""),g=Ht(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),y=g.length>=2&&(g.includes(f)||f.includes(g));return _||y}))}if(!m){let f=p.map(_=>{let y=lt(a,_?.name||""),k=lt(a,_?.to?.name||"");return{t:_,score:Math.max(y,k)}}).sort((_,y)=>y.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await L(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await L(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Uo}from"fs";import{fileURLToPath as Jo}from"url";import{dirname as Bo,resolve as qo}from"path";import{resolveIntegrationToken as Vr}from"@zibby/core/backend-client.js";import{spawn as Io,execSync as vo}from"child_process";import{existsSync as V,mkdirSync as No,readdirSync as Yr,statSync as Oo,readFileSync as To}from"fs";import{resolve as Yt,join as Q,basename as Ro}from"path";var Wt=".zibby/repos";function Hr(r,e){try{let t=new URL(r);return t.protocol==="https:"&&t.host.toLowerCase()===e.toLowerCase()}catch{return!1}}function zr(r,e,t){let n=new URL(r);return n.username=encodeURIComponent(e),n.password=encodeURIComponent(t),n.toString()}function Ao(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function Ge(r,e,t,n,i="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function dt(r,e,t={}){return new Promise((n,i)=>{let s=Io(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var me={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=yo();if(!r)return null;let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);process.env.ATLASSIAN_INSTANCE_URL&&(e.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let t of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[t]&&(e[t]=process.env[t]);return{command:"node",args:[r],env:e,description:this.description}},async handleToolCall(r,e){try{switch(r){case"jira_list_projects":{let t=await L("/rest/api/3/project"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:n.length,projects:n})}case"jira_list_statuses":{let{projectKey:t}=e||{};if(t){let s=await L(`/rest/api/3/project/${encodeURIComponent(t)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:t,count:c.length,statuses:c})}let n=await L("/rest/api/3/status"),i=(Array.isArray(n)?n:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:t}=e||{};if(!t)return JSON.stringify({error:"projectKey is required"});let n=await Fr(t);return JSON.stringify({projectKey:t,count:n.length,issueTypes:n})}case"jira_search":{let t=e.jql||"",n=e.maxResults||20;t.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(t=`created >= -365d ${t}`.trim());let s=`jql=${encodeURIComponent(t)}&maxResults=${n}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await L(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let t=e.issueKey;if(!t)return JSON.stringify({error:"issueKey is required"});let n=await L(`/rest/api/3/issue/${t}`);return JSON.stringify({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,description:n.fields?.description,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name,labels:n.fields?.labels,created:n.fields?.created,updated:n.fields?.updated})}case"jira_create_issue":{let{projectKey:t,summary:n,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=e;if(!t||!n)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await Fr(t),f=bo(i,h)}catch{}let b={project:{key:t},summary:n,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};s&&(b.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:s}]}]}),o&&(b.priority={name:o}),a?.length&&(b.labels=a),c&&(b.assignee={id:c});let g=await L("/rest/api/3/issue",{method:"POST",body:{fields:b}}),_={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(_.issueType=f.resolved.name,_.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&ue(f.requested)!==ue(f.resolved.name)&&(_.issueTypeWarning=`Requested "${f.requested}" is not available in ${t}; used "${f.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(_.sprintMove=await zt({issueKey:g.key,projectKey:t,sprintId:p,sprintName:u,target:m})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:t,state:n}=e,i=await Kr(t,n);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o}=e||{},a=await zt({issueKey:t,projectKey:n,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:t,sprintId:n,projectKey:i,status:s,maxResults:o}=e;if(!t&&!n)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=n?`sprint = ${n}`:`sprint = "${t}"`,d=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await L(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(b=>({key:b.key,project:b.fields?.project?.key,summary:b.fields?.summary,status:b.fields?.status?.name,assignee:b.fields?.assignee?.displayName||"Unassigned",priority:b.fields?.priority?.name,type:b.fields?.issuetype?.name})),h={};for(let b of f)h[b.status]=(h[b.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:t,maxResults:n}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let s=await L(`/rest/api/3/issue/${t}/comment?maxResults=${n||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ct(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:t,body:n}=e;return!t||!n?JSON.stringify({error:"issueKey and body are required"}):(await L(`/rest/api/3/issue/${t}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_edit_issue":{let{issueKey:t,fields:n}=e;return!t||!n?JSON.stringify({error:"issueKey and fields are required"}):(await L(`/rest/api/3/issue/${t}`,{method:"PUT",body:{fields:n}}),JSON.stringify({ok:!0,issueKey:t}))}case"jira_transition_issue":{let{issueKey:t,transitionId:n,toStatus:i,statusName:s,status:o}=e;if(!t)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!n&&!a){let p=((await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:t,availableTransitions:p})}let c=n;if(!c){let p=(await L(`/rest/api/3/issue/${t}/transitions`)).transitions||[],u=Le(a),m=p.find(f=>Le(f?.name||"")===u||Le(f?.to?.name||"")===u);if(!m){let f=Ht(a);f.length>=2&&(m=p.find(h=>{let b=Ht(h?.name||""),g=Ht(h?.to?.name||""),_=b.length>=2&&(b.includes(f)||f.includes(b)),y=g.length>=2&&(g.includes(f)||f.includes(g));return _||y}))}if(!m){let f=p.map(_=>{let y=lt(a,_?.name||""),k=lt(a,_?.to?.name||"");return{t:_,score:Math.max(y,k)}}).sort((_,y)=>y.score-_.score),h=f[0],b=f[1];h&&h.score>=.45&&(!b||h.score-b.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:t,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await L(`/rest/api/3/issue/${t}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await L(`/rest/api/3/issue/${t}?fields=status`);return JSON.stringify({ok:!0,issueKey:t,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Uo}from"fs";import{fileURLToPath as Jo}from"url";import{dirname as Bo,resolve as qo}from"path";import{resolveIntegrationToken as Vr}from"@zibby/core/backend-client.js";import{spawn as Io,execSync as vo}from"child_process";import{existsSync as V,mkdirSync as No,readdirSync as Yr,statSync as Oo,readFileSync as To}from"fs";import{resolve as Yt,join as Q,basename as Ro}from"path";var Wt=".zibby/repos";function Hr(r,e){try{let t=new URL(r);return t.protocol==="https:"&&t.host.toLowerCase()===e.toLowerCase()}catch{return!1}}function zr(r,e,t){let n=new URL(r);return n.username=encodeURIComponent(e),n.password=encodeURIComponent(t),n.toString()}function Ao(r){let e=String(r??"");for(let t of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])t&&(e=e.split(t).join("***"));return e.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,t=>t.replace(/:[^@\s]+@/,":***@"))}function Ge(r,e,t,n,i="clone"){try{r(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);n&&(o=o.split(n).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}function dt(r,e,t={}){return new Promise((n,i)=>{let s=Io(r,{cwd:e,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...t}}),o="",a="";s.stdout.on("data",c=>{o+=c.toString()}),s.stderr.on("data",c=>{a+=c.toString()}),s.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):n(o.trim())}),s.on("error",c=>i(c))})}var me={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],inProcessOnly:!0,promptFragment:`## Git Repositories
75
75
  You can clone and explore git repositories locally for codebase analysis:
76
76
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
77
77
  - git_list_repos: List locally cloned repos
78
78
  - git_explore: Quick overview of a cloned repo's structure (key files, package.json, routes, etc.)
79
79
 
80
- When a test ticket lacks context, use this workflow:
80
+ When your task needs repository context you don't have yet:
81
81
  1. Clone the relevant repo with git_checkout
82
82
  2. Use git_explore to understand the project structure
83
83
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
84
- 4. Use GitHub/GitLab skills to read related PRs and commits
85
- 5. Build well-informed test specs and save them to files before running tests`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await Eo(e,n);case"git_list_repos":return xo(e,n);case"git_explore":return Lo(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:Ao(i.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 Eo(r,e){let{url:t,branch:n,shallow:i=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||Ro(t.replace(/\.git$/,"")),a=Yt(e,Wt);No(a,{recursive:!0});let c=Q(a,o),d=t,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(Hr(t,"github.com")&&l)d=zr(t,"x-access-token",l);else if(p&&u)try{let h=new URL(u).host;Hr(t,h)&&(d=zr(t,"oauth2",p))}catch{}if(V(Q(c,".git"))){let h=n?`git -C "${c}" fetch "${d}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await dt(h,e);let b=await dt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:b})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await dt(m.join(" "),e),Ge(vo,c,t,l||p,"git_checkout");let f=await dt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function xo(r,e){let t=Yt(e,Wt);if(!V(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of Yr(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=Q(t,i.name);if(!V(Q(s,".git")))continue;let o=Oo(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function Lo(r,e){let{repo:t,depth:n=2}=r,i=Yt(e,Wt,t);if(!V(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=Q(i,"package.json");if(V(o))try{let m=JSON.parse(To(o,"utf-8"));s.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?s.framework="React":m.dependencies?.next?s.framework="Next.js":m.dependencies?.vue?s.framework="Vue":m.dependencies?.angular?s.framework="Angular":m.dependencies?.express?s.framework="Express":m.dependencies?.fastify&&(s.framework="Fastify")}catch{}let a=Q(i,"pyproject.toml");V(a)&&(s.language="Python");let c=Q(i,"go.mod");V(c)&&(s.language="Go");let d=Q(i,"Cargo.toml");V(d)&&(s.language="Rust"),V(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>n)return;let b;try{b=Yr(m,{withFileTypes:!0})}catch{return}let g=b.filter(_=>!_.name.startsWith(".")&&_.name!=="node_modules"&&_.name!=="__pycache__"&&_.name!=="dist"&&_.name!=="build"&&_.name!==".git").sort((_,y)=>_.isDirectory()!==y.isDirectory()?_.isDirectory()?-1:1:_.name.localeCompare(y.name));for(let _ of g){let y=_.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${_.name}`),y&&h<n&&p(Q(m,_.name),`${f} `,h+1)}}p(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["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 s.keyFilesFound=u.filter(m=>V(Q(i,m))),JSON.stringify(s)}import jo from"crypto";var Wr=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Zr=/<!--\s*zbreview-summary\s*-->/i;function $o(r){return String(r||"").replace(Wr,"").replace(Zr,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Po(r,e){return jo.createHash("sha256").update(`${String(r||"")}\0${$o(e)}`).digest("hex").slice(0,12)}function Co(r){return`
84
+ 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(r,e,t){let n=t?.options?.workspace||process.cwd();try{switch(r){case"git_checkout":return await Eo(e,n);case"git_list_repos":return xo(e,n);case"git_explore":return Lo(e,n);default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(i){return JSON.stringify({error:Ao(i.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 Eo(r,e){let{url:t,branch:n,shallow:i=!0,name:s}=r;!t.includes("://")&&!t.startsWith("git@")&&(t=`https://github.com/${t}`);let o=s||Ro(t.replace(/\.git$/,"")),a=Yt(e,Wt);No(a,{recursive:!0});let c=Q(a,o),d=t,l=process.env.GITHUB_TOKEN,p=process.env.GITLAB_TOKEN,u=process.env.GITLAB_URL;if(Hr(t,"github.com")&&l)d=zr(t,"x-access-token",l);else if(p&&u)try{let h=new URL(u).host;Hr(t,h)&&(d=zr(t,"oauth2",p))}catch{}if(V(Q(c,".git"))){let h=n?`git -C "${c}" fetch "${d}" ${n} && git -C "${c}" checkout ${n} && git -C "${c}" merge --ff-only FETCH_HEAD`:`git -C "${c}" pull "${d}"`;await dt(h,e);let b=await dt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"updated",repo:o,path:c,branch:n||"default",head:b})}let m=["git","clone"];i&&m.push("--depth","1"),n&&m.push("--branch",n),m.push(`"${d}"`,`"${c}"`),await dt(m.join(" "),e),Ge(vo,c,t,l||p,"git_checkout");let f=await dt(`git -C "${c}" log -1 --format="%h %s"`,e);return JSON.stringify({action:"cloned",repo:o,path:c,branch:n||"default",shallow:i,head:f})}function xo(r,e){let t=Yt(e,Wt);if(!V(t))return JSON.stringify({repos:[],message:"No repos cloned yet"});let n=[];for(let i of Yr(t,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=Q(t,i.name);if(!V(Q(s,".git")))continue;let o=Oo(s);n.push({name:i.name,path:s,lastModified:o.mtime.toISOString()})}return JSON.stringify({repos:n,total:n.length,directory:t})}function Lo(r,e){let{repo:t,depth:n=2}=r,i=Yt(e,Wt,t);if(!V(i))return JSON.stringify({error:`Repo not found: ${t}. Run git_checkout first.`});let s={repo:t,path:i},o=Q(i,"package.json");if(V(o))try{let m=JSON.parse(To(o,"utf-8"));s.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?s.framework="React":m.dependencies?.next?s.framework="Next.js":m.dependencies?.vue?s.framework="Vue":m.dependencies?.angular?s.framework="Angular":m.dependencies?.express?s.framework="Express":m.dependencies?.fastify&&(s.framework="Fastify")}catch{}let a=Q(i,"pyproject.toml");V(a)&&(s.language="Python");let c=Q(i,"go.mod");V(c)&&(s.language="Go");let d=Q(i,"Cargo.toml");V(d)&&(s.language="Rust"),V(o)&&(s.language=s.language||"JavaScript/TypeScript");let l=[];function p(m,f,h){if(h>n)return;let b;try{b=Yr(m,{withFileTypes:!0})}catch{return}let g=b.filter(_=>!_.name.startsWith(".")&&_.name!=="node_modules"&&_.name!=="__pycache__"&&_.name!=="dist"&&_.name!=="build"&&_.name!==".git").sort((_,y)=>_.isDirectory()!==y.isDirectory()?_.isDirectory()?-1:1:_.name.localeCompare(y.name));for(let _ of g){let y=_.isDirectory();l.push(`${f}${y?"\u{1F4C1}":"\u{1F4C4}"} ${_.name}`),y&&h<n&&p(Q(m,_.name),`${f} `,h+1)}}p(i,"",1),s.tree=l.slice(0,80),l.length>80&&(s.treeTruncated=!0);let u=["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 s.keyFilesFound=u.filter(m=>V(Q(i,m))),JSON.stringify(s)}import jo from"crypto";var Wr=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Zr=/<!--\s*zbreview-summary\s*-->/i;function $o(r){return String(r||"").replace(Wr,"").replace(Zr,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Po(r,e){return jo.createHash("sha256").update(`${String(r||"")}\0${$o(e)}`).digest("hex").slice(0,12)}function Co(r){return`
86
85
 
87
86
  <!-- zbfp:${r} -->`}var pt=`
88
87
 
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/skills",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Built-in skill definitions for the Zibby agent-workflow framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -47,4 +47,4 @@ When user says "check out repo-name" or "clone repo-name":
47
47
  When user just wants to "look at" or "read" files (not clone):
48
48
  - Use github_get_file to read individual files via API`,resolve(){let p=ne();if(!p)return{command:null,args:[],env:{},description:this.description};let o={};for(let t of this.envKeys)process.env[t]&&(o[t]=process.env[t]);return{type:"stdio",command:"node",args:[p,"../dist/github.js","githubSkill"],env:o,description:this.description,alwaysLoad:!0}},async handleToolCall(p,o){try{switch(p){case"github_search_issues":{let t=o.query;if(!t)return JSON.stringify({error:"query is required"});let r=await u(`/search/issues?q=${encodeURIComponent(t)}&per_page=${o.limit||20}`),i=(r.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(n=>n.name),createdAt:e.created_at}));return JSON.stringify({total:r.total_count,items:i})}case"github_search_code":{let t=o.query;if(!t)return JSON.stringify({error:"query is required"});let r=o.repo?`+repo:${o.repo}`:"",i=o.language?`+language:${o.language}`:"",e=await u(`/search/code?q=${encodeURIComponent(t)}${r}${i}&per_page=${o.limit||15}`),n=(e.items||[]).map(s=>({name:s.name,path:s.path,repo:s.repository?.full_name,url:s.html_url,score:s.score}));return JSON.stringify({total:e.total_count,items:n})}case"github_get_pr":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,headSha:e.head?.sha,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(n=>n.name)})}case"github_get_pr_diff":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),n=e.length>15e3;return JSON.stringify({number:i,diff:n?e.slice(0,15e3):e,truncated:n,totalLength:e.length})}case"github_list_pr_files":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(n=>({filename:n.filename,status:n.status,additions:n.additions,deletions:n.deletions,patch:n.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:r,number:i}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/pulls/${i}/comments?per_page=50`),n=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=50`),s=[...e.map(a=>({type:"review",user:a.user?.login,body:a.body?.slice(0,1e3),path:a.path,line:a.line,createdAt:a.created_at})),...n.map(a=>({type:"issue",user:a.user?.login,body:a.body?.slice(0,1e3),createdAt:a.created_at}))].sort((a,g)=>new Date(a.createdAt)-new Date(g.createdAt));return JSON.stringify({total:s.length,comments:s})}case"github_get_review_thread":{let{owner:t,repo:r,number:i,commentId:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let n=await u(`/repos/${t}/${r}/pulls/comments/${e}`),s=n.in_reply_to_id||n.id,a=[];try{a=await u(`/repos/${t}/${r}/pulls/${i}/comments?per_page=100`)}catch{a=[n]}(!Array.isArray(a)||a.length===0)&&(a=[n]);let g=a.filter(h=>h.id===s||h.in_reply_to_id===s).sort((h,b)=>new Date(h.created_at)-new Date(b.created_at)),d=g.length?g:[n],l=d.find(h=>h.id===s)||d[0];return JSON.stringify({rootCommentId:s,path:l.path,line:l.line??l.original_line??null,side:l.side||"RIGHT",diffHunk:typeof l.diff_hunk=="string"?l.diff_hunk.slice(0,3e3):null,commitId:l.commit_id||l.original_commit_id||null,notes:d.map(h=>({id:h.id,user:h.user?.login,body:(h.body||"").slice(0,4e3),createdAt:h.created_at,isRoot:h.id===s,url:h.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:r,number:i,commentId:e,body:n}=o||{};if(!t||!r||!i||!e||!n)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let s=await u(`/repos/${t}/${r}/pulls/${i}/comments/${e}/replies`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url,inReplyTo:s.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:r,number:i,body:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url})}case"github_create_review":{let{owner:t,repo:r,number:i,body:e,event:n,comments:s}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=(n||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(a))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${n})`});let g=Array.isArray(s)?s.filter(m=>m&&m.path&&m.body&&(m.line!=null||m.position!=null)).map(m=>{let c={path:m.path,body:String(m.body)};return m.line!=null?(c.line=Number(m.line),c.side=m.side==="LEFT"?"LEFT":"RIGHT"):c.position=Number(m.position),c}):[];if(a!=="APPROVE"&&!e&&g.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let d=new Set,l=null;try{for(let m=1;m<=20;m+=1){let c=await u(`/repos/${t}/${r}/pulls/${i}/comments?per_page=100&page=${m}`);if(!Array.isArray(c)||c.length===0)break;for(let f of c){let $=H(f.body);$&&d.add($)}if(c.length<100)break}for(let m=1;m<=20&&l==null;m+=1){let c=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=100&page=${m}`);if(!Array.isArray(c)||c.length===0)break;for(let f of c)if(J(f.body)){l=f.id;break}if(c.length<100)break}}catch{}let h=!1,b=!1;if(e){let m=`${String(e)}${x}`;try{l!=null?(await u(`/repos/${t}/${r}/issues/comments/${l}`,{method:"PATCH",body:{body:m}}),h=!0):await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:m}}),b=!0}catch{}}let{toPost:y,skipped:w}=U(g,d),_=y.map(({_fp:m,...c})=>c),S=null;if(_.length>0||a==="APPROVE"||a==="REQUEST_CHANGES"){let m={event:a};_.length>0&&(m.comments=_),_.length===0&&a==="REQUEST_CHANGES"&&(m.body="Changes requested \u2014 see the review summary comment."),S=await u(`/repos/${t}/${r}/pulls/${i}/reviews`,{method:"POST",body:m})}return JSON.stringify({ok:!0,id:S?S.id:void 0,state:S?S.state:void 0,event:a,notePosted:b,summaryUpdated:h,commentsPosted:_.length,inlineSkipped:w||void 0,url:S?S.html_url:void 0})}case"github_list_commits":{let{owner:t,repo:r,branch:i,path:e,limit:n,since:s,until:a,page:g}=o;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let d=Math.min(Number(n)||20,100),l=`/repos/${t}/${r}/commits?per_page=${d}&page=${Number(g)||1}`;i&&(l+=`&sha=${encodeURIComponent(i)}`),e&&(l+=`&path=${encodeURIComponent(e)}`),s&&(l+=`&since=${encodeURIComponent(s)}`),a&&(l+=`&until=${encodeURIComponent(a)}`);let h=await u(l);return JSON.stringify({total:h.length,page:Number(g)||1,hasMore:h.length>=d,commits:h.map(b=>({sha:b.sha?.slice(0,8),fullSha:b.sha,message:b.commit?.message?.slice(0,300),author:b.commit?.author?.name,authorEmail:b.commit?.author?.email,date:b.commit?.author?.date,url:b.html_url}))})}case"github_get_commit":{let{owner:t,repo:r,sha:i,includePrs:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let n=await u(`/repos/${t}/${r}/commits/${i}`),s;if(e)try{let a=await u(`/repos/${t}/${r}/commits/${i}/pulls`);s=(Array.isArray(a)?a:[]).map(g=>({number:g.number,title:g.title,state:g.state,merged:!!g.merged_at,webUrl:g.html_url}))}catch{s=[]}return JSON.stringify({sha:n.sha?.slice(0,8),message:n.commit?.message,author:n.commit?.author?.name,date:n.commit?.author?.date,stats:n.stats,files:(n.files||[]).map(a=>({filename:a.filename,status:a.status,additions:a.additions,deletions:a.deletions,patch:a.patch?.slice(0,3e3)})),...s?{pullRequests:s}:{}})}case"github_get_file":{let{owner:t,repo:r,path:i,ref:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and path are required"});let n=`/repos/${t}/${r}/contents/${encodeURIComponent(i)}`;e&&(n+=`?ref=${encodeURIComponent(e)}`);let s=await u(n);if(s.type!=="file")return Array.isArray(s)?JSON.stringify({type:"directory",path:i,entries:s.map(d=>({name:d.name,type:d.type,size:d.size,path:d.path}))}):JSON.stringify({error:`Not a file: ${s.type}`});let a=Buffer.from(s.content||"","base64").toString("utf-8"),g=a.length>2e4;return JSON.stringify({path:s.path,size:s.size,sha:s.sha?.slice(0,8),content:g?a.slice(0,2e4):a,truncated:g})}case"github_get_user":try{let t=await u("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let r=t.repositories[0],i=r.owner.login,e=r.owner.type,n=e==="Organization"?`/orgs/${i}`:`/users/${i}`,s=await u(n);return JSON.stringify({login:s.login,name:s.name||s.login,avatar:s.avatar_url,bio:s.bio||s.description,type:e,isOrg:e==="Organization",publicRepos:s.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(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let r=(await u("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let n of r)n.owner.type==="Organization"&&(i.has(n.owner.login)||i.set(n.owner.login,{login:n.owner.login,description:null,url:n.owner.url}));let e=Array.from(i.values());return JSON.stringify({count:e.length,orgs:e,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(t){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${t.message}`})}case"github_clone":{let y=function(m){let c=m.replace(/^~(?=$|\/|\\)/,b);return s(c)},{owner:t,repo:r,destination:i}=o;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:n,resolve:s}=await import("path"),{existsSync:a,mkdirSync:g}=await import("fs"),{homedir:d,platform:l}=await import("os"),{token:h}=await j("github"),b=d(),w=i?y(i):n(b,"zibby-repos"),_=n(w,r);if(g(w,{recursive:!0}),a(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});let S=`https://x-access-token:${h}@github.com/${t}/${r}.git`;try{e(`git clone ${S} "${_}"`,{stdio:"pipe"});let m=`https://github.com/${t}/${r}.git`;G(e,_,m,h,"github_clone");let c=l()==="win32",f;return c?f=e(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):f=e(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${t}/${r} to ${_}`,contents:f.split(`
49
49
  `).slice(0,30).join(`
50
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(m){let f=String(m.message||m).split(h).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${f}`})}}case"github_search_repos":{let{query:t,limit:r}=o;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(i);if(e.error)return JSON.stringify(e);let n=t.toLowerCase(),s=e.repos.filter(a=>a.name.toLowerCase().includes(n)||a.fullName.toLowerCase().includes(n)||a.description&&a.description.toLowerCase().includes(n));return JSON.stringify({query:t,count:s.length,repos:s.slice(0,r||20)})}case"github_list_repos":{let{owner:t,type:r,sort:i,direction:e,limit:n,query:s}=o,a=100,g=n||200,d=[],l=c=>({name:c.name,fullName:c.full_name,private:c.private,description:c.description,language:c.language,defaultBranch:c.default_branch,updatedAt:c.updated_at,stars:c.stargazers_count,url:c.html_url,fullPath:c.full_name,webUrl:c.html_url,visibility:c.visibility||(c.private?"private":"public")}),h=c=>{if(!s)return!0;let f=String(s).toLowerCase();return c.name&&c.name.toLowerCase().includes(f)||c.fullName&&c.fullName.toLowerCase().includes(f)||c.description&&c.description.toLowerCase().includes(f)};if(!t){let c=1,f=!0;for(;f&&d.length<g;){let k=`/installation/repositories?per_page=${a}&page=${c}`,P=(await u(k)).repositories||[];if(P.length===0)break;d=d.concat(P),f=P.length===a,c++}let $=d.map(l).filter(h),N=$.slice(0,g),W=$.length>N.length,T=N.filter(k=>k.private).length,C=N.filter(k=>!k.private).length;return JSON.stringify({count:N.length,repos:N,truncated:W,privateCount:T,publicCount:C,message:`Found ${T} private and ${C} public repos`})}let b=await u(`/orgs/${t}`).then(()=>!0).catch(()=>!1),y=1,w=!0;for(;w&&d.length<g;){let c;b?c=`/orgs/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`:c=`/users/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`;let f=await u(c),$=Array.isArray(f)?f:[];if($.length===0)break;d=d.concat($),w=$.length===a,y++}let _=d.map(l).filter(h),S=_.slice(0,g),m=_.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:m})}case"github_create_pr":{let{owner:t,repo:r,head:i,title:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let n=o.base;if(!n)try{n=(await u(`/repos/${t}/${r}`)).default_branch||"main"}catch{n="main"}let s={title:String(e),head:String(i),base:String(n),body:o.body?String(o.body):"",draft:!!o.draft};try{let a=await u(`/repos/${t}/${r}/pulls`,{method:"POST",body:s});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:i,base:n,repo:`${t}/${r}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let g=String(a.message||a);if(/GitHub API 422/.test(g))return JSON.stringify({success:!1,branch:i,base:n,repo:`${t}/${r}`,provider:"github",skippedReason:g});throw a}}case"github_merge_pr":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=o.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let n={merge_method:e};o.commitTitle&&(n.commit_title=String(o.commitTitle)),o.commitMessage&&(n.commit_message=String(o.commitMessage));try{let s=await u(`/repos/${t}/${r}/pulls/${i}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:s.sha,number:i,provider:"github"})}catch(s){let a=String(s.message||s);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:a});throw s}}case"github_create_issue":{let{owner:t,repo:r,title:i,body:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let n=await u(`/repos/${t}/${r}/issues`,{method:"POST",body:{title:i,body:e||""}});return JSON.stringify({number:n.number,url:n.html_url,title:n.title})}case"github_list_issues":{let{owner:t,repo:r,state:i,labels:e,since:n,assignee:s,sort:a,direction:g,limit:d}=o||{};if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let l=new URLSearchParams;l.set("state",i||"open"),l.set("per_page",String(d||30)),l.set("sort",a||"updated"),l.set("direction",g||"desc"),e&&l.set("labels",Array.isArray(e)?e.join(","):e),n&&l.set("since",n),s&&l.set("assignee",s);let h=await u(`/repos/${t}/${r}/issues?${l.toString()}`),b=(Array.isArray(h)?h:[]).filter(y=>!y.pull_request).map(y=>({number:y.number,title:y.title,state:y.state,labels:(y.labels||[]).map(w=>typeof w=="string"?w:w.name),assignee:y.assignee?.login||null,assignees:(y.assignees||[]).map(w=>w.login),user:y.user?.login,comments:y.comments,url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"github_get_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`);return e.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(n=>typeof n=="string"?n:n.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(n=>n.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:r,number:i,limit:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=${e||100}`),s=(Array.isArray(n)?n:[]).map(a=>({id:a.id,user:a.user?.login,body:a.body||"",createdAt:a.created_at,updatedAt:a.updated_at,url:a.html_url}));return JSON.stringify({count:s.length,comments:s})}case"github_add_issue_comment":{let{owner:t,repo:r,number:i,body:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url})}case"github_close_issue":{let{owner:t,repo:r,number:i,stateReason:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n={state:"closed"};e&&(n.state_reason=e);let s=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:n});return JSON.stringify({ok:!0,number:s.number,state:s.state,stateReason:s.state_reason||null,url:s.html_url})}case"github_reopen_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:e.number,state:e.state,url:e.html_url})}case"github_label_issue":{let{owner:t,repo:r,number:i,labels:e,mode:n}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=Array.isArray(e)?e:e?[e]:[];if(!s.length)return JSON.stringify({error:"labels (string or array) is required"});let a=n||"add";if(a==="set"){let d=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{labels:s}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}if(a==="remove"){for(let l of s)await u(`/repos/${t}/${r}/issues/${i}/labels/${encodeURIComponent(l)}`,{method:"DELETE"});let d=await u(`/repos/${t}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}let g=await u(`/repos/${t}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:s}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(g)?g:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${p}`})}}catch(t){return JSON.stringify({error:t.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"]}}]};var F=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,z=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,ie=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,oe=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,M="in progress",D="blocked";function K(p,o=[]){if(p==="closed")return"done";if(p!=="open")return"unknown";let t=(o||[]).map(String);return t.some(r=>F.test(r))?"blocked":t.some(r=>z.test(r))?"in_progress":"todo"}function v(p={}){let o=p.owner||process.env.GITHUB_OWNER,t=p.repo||process.env.GITHUB_REPO;if(!o||!t)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:o,repo:t}}function O(p){let o=JSON.parse(p);if(o&&o.error)throw new Error(o.error);return o}function E(p,o={}){let t=p.labels||[],r=p.number,i=o.owner&&o.repo?`${o.owner}/${o.repo}#${r}`:`#${r}`;return{id:String(r),key:i,title:p.title||"",body:p.body||"",state:p.state||null,stateCategory:K(p.state,t),assignee:p.assignee||p.assignees&&p.assignees[0]||null,url:p.url||null,_raw:p}}var se={id:"github",toStateCategory:K,toNeutral:E,IN_PROGRESS_LABEL:M,BLOCKED_LABEL:D,async listCandidates(p={}){let o=p.ctx||{},{owner:t,repo:r}=v(o);return(O(await R.handleToolCall("github_list_issues",{owner:t,repo:r,state:p.state||"open",labels:p.labels,since:p.updatedAfter,limit:p.limit})).issues||[]).map(e=>E(e,{owner:t,repo:r}))},async getTicket(p,o={}){let{owner:t,repo:r}=v(o),i=A(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let e=JSON.parse(await R.handleToolCall("github_get_issue",{owner:t,repo:r,number:i}));return e.error?null:E(e,{owner:t,repo:r})},async getComments(p,o={}){let{owner:t,repo:r}=v(o),i=A(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);return(O(await R.handleToolCall("github_get_issue_comments",{owner:t,repo:r,number:i})).comments||[]).map(n=>({id:String(n.id),author:n.user||"Unknown",body:n.body||"",createdAt:n.createdAt||null,updatedAt:n.updatedAt||null,_raw:n})).sort((n,s)=>String(s.createdAt).localeCompare(String(n.createdAt)))},async addComment(p,o,t={}){let{owner:r,repo:i}=v(t),e=A(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("body is required");let n=O(await R.handleToolCall("github_add_issue_comment",{owner:r,repo:i,number:e,body:o}));return{ok:!!n.ok,id:n.id?String(n.id):null}},async transition(p,o,t={}){let{owner:r,repo:i}=v(t),e=A(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let n=String(o||"");if(ie.test(n)){let s=O(await R.handleToolCall("github_close_issue",{owner:r,repo:i,number:e,stateReason:"completed"}));return{ok:!!s.ok,stateAfter:s.state||"closed",stateCategoryAfter:"done",_raw:s}}if(F.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[D],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:s}}if(z.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[M],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:s}}if(oe.test(n)){let s=O(await R.handleToolCall("github_reopen_issue",{owner:r,repo:i,number:e}));return{ok:!!s.ok,stateAfter:s.state||"open",stateCategoryAfter:"todo",_raw:s}}return{ok:!1,error:`GitHub issues have no "${o}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(p,o,t,r={}){let{owner:i,repo:e}=v(r),n=A(p);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("prUrl is required");let s=`${t?`${t}: `:"Linked PR: "}${o}`;return{ok:!!O(await R.handleToolCall("github_add_issue_comment",{owner:i,repo:e,number:n,body:s})).ok,via:"comment"}}};async function B(p,o,t){await R.handleToolCall("github_reopen_issue",{owner:p,repo:o,number:t})}function A(p){if(p==null)return null;if(typeof p=="number")return p;let o=/(\d+)\s*$/.exec(String(p));return o?Number(o[1]):null}var qe=se;export{qe as default,se as githubAdapter};
50
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(m){let f=String(m.message||m).split(h).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${f}`})}}case"github_search_repos":{let{query:t,limit:r}=o;if(!t)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(i);if(e.error)return JSON.stringify(e);let n=t.toLowerCase(),s=e.repos.filter(a=>a.name.toLowerCase().includes(n)||a.fullName.toLowerCase().includes(n)||a.description&&a.description.toLowerCase().includes(n));return JSON.stringify({query:t,count:s.length,repos:s.slice(0,r||20)})}case"github_list_repos":{let{owner:t,type:r,sort:i,direction:e,limit:n,query:s}=o,a=100,g=n||200,d=[],l=c=>({name:c.name,fullName:c.full_name,private:c.private,description:c.description,language:c.language,defaultBranch:c.default_branch,updatedAt:c.updated_at,stars:c.stargazers_count,url:c.html_url,fullPath:c.full_name,webUrl:c.html_url,visibility:c.visibility||(c.private?"private":"public")}),h=c=>{if(!s)return!0;let f=String(s).toLowerCase();return c.name&&c.name.toLowerCase().includes(f)||c.fullName&&c.fullName.toLowerCase().includes(f)||c.description&&c.description.toLowerCase().includes(f)};if(!t){let c=1,f=!0;for(;f&&d.length<g;){let A=`/installation/repositories?per_page=${a}&page=${c}`,P=(await u(A)).repositories||[];if(P.length===0)break;d=d.concat(P),f=P.length===a,c++}let $=d.map(l).filter(h),N=$.slice(0,g),W=$.length>N.length,T=N.filter(A=>A.private).length,C=N.filter(A=>!A.private).length;return JSON.stringify({count:N.length,repos:N,truncated:W,privateCount:T,publicCount:C,message:`Found ${T} private and ${C} public repos`})}let b=await u(`/orgs/${t}`).then(()=>!0).catch(()=>!1),y=1,w=!0;for(;w&&d.length<g;){let c;b?c=`/orgs/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`:c=`/users/${t}/repos?per_page=${a}&page=${y}&type=${r||"all"}&sort=${i||"updated"}&direction=${e||"desc"}`;let f=await u(c),$=Array.isArray(f)?f:[];if($.length===0)break;d=d.concat($),w=$.length===a,y++}let _=d.map(l).filter(h),S=_.slice(0,g),m=_.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:m})}case"github_create_pr":{let{owner:t,repo:r,head:i,title:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let n=o.base;if(!n)try{n=(await u(`/repos/${t}/${r}`)).default_branch||"main"}catch{n="main"}let s={title:String(e),head:String(i),base:String(n),body:o.body?String(o.body):"",draft:!!o.draft};try{let a=await u(`/repos/${t}/${r}/pulls`,{method:"POST",body:s});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:i,base:n,repo:`${t}/${r}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let g=String(a.message||a);if(/GitHub API 422/.test(g))return JSON.stringify({success:!1,branch:i,base:n,repo:`${t}/${r}`,provider:"github",skippedReason:g});throw a}}case"github_merge_pr":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=o.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let n={merge_method:e};o.commitTitle&&(n.commit_title=String(o.commitTitle)),o.commitMessage&&(n.commit_message=String(o.commitMessage));try{let s=await u(`/repos/${t}/${r}/pulls/${i}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:s.sha,number:i,provider:"github"})}catch(s){let a=String(s.message||s);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:a});throw s}}case"github_create_issue":{let{owner:t,repo:r,title:i,body:e}=o;if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let n=await u(`/repos/${t}/${r}/issues`,{method:"POST",body:{title:i,body:e||""}});return JSON.stringify({number:n.number,url:n.html_url,title:n.title})}case"github_list_issues":{let{owner:t,repo:r,state:i,labels:e,since:n,assignee:s,sort:a,direction:g,limit:d}=o||{};if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let l=new URLSearchParams;l.set("state",i||"open"),l.set("per_page",String(d||30)),l.set("sort",a||"updated"),l.set("direction",g||"desc"),e&&l.set("labels",Array.isArray(e)?e.join(","):e),n&&l.set("since",n),s&&l.set("assignee",s);let h=await u(`/repos/${t}/${r}/issues?${l.toString()}`),b=(Array.isArray(h)?h:[]).filter(y=>!y.pull_request).map(y=>({number:y.number,title:y.title,state:y.state,labels:(y.labels||[]).map(w=>typeof w=="string"?w:w.name),assignee:y.assignee?.login||null,assignees:(y.assignees||[]).map(w=>w.login),user:y.user?.login,comments:y.comments,url:y.html_url,createdAt:y.created_at,updatedAt:y.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"github_get_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`);return e.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(n=>typeof n=="string"?n:n.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(n=>n.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:r,number:i,limit:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments?per_page=${e||100}`),s=(Array.isArray(n)?n:[]).map(a=>({id:a.id,user:a.user?.login,body:a.body||"",createdAt:a.created_at,updatedAt:a.updated_at,url:a.html_url}));return JSON.stringify({count:s.length,comments:s})}case"github_add_issue_comment":{let{owner:t,repo:r,number:i,body:e}=o||{};if(!t||!r||!i||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let n=await u(`/repos/${t}/${r}/issues/${i}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url})}case"github_close_issue":{let{owner:t,repo:r,number:i,stateReason:e}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n={state:"closed"};e&&(n.state_reason=e);let s=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:n});return JSON.stringify({ok:!0,number:s.number,state:s.state,stateReason:s.state_reason||null,url:s.html_url})}case"github_reopen_issue":{let{owner:t,repo:r,number:i}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let e=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:e.number,state:e.state,url:e.html_url})}case"github_label_issue":{let{owner:t,repo:r,number:i,labels:e,mode:n}=o||{};if(!t||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=Array.isArray(e)?e:e?[e]:[];if(!s.length)return JSON.stringify({error:"labels (string or array) is required"});let a=n||"add";if(a==="set"){let d=await u(`/repos/${t}/${r}/issues/${i}`,{method:"PATCH",body:{labels:s}});return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}if(a==="remove"){for(let l of s)await u(`/repos/${t}/${r}/issues/${i}/labels/${encodeURIComponent(l)}`,{method:"DELETE"});let d=await u(`/repos/${t}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:d.number,labels:(d.labels||[]).map(l=>typeof l=="string"?l:l.name)})}let g=await u(`/repos/${t}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:s}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(g)?g:[]).map(d=>typeof d=="string"?d:d.name)})}default:return JSON.stringify({error:`Unknown tool: ${p}`})}}catch(t){return JSON.stringify({error:t.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"]}}]};var F=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,z=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,ie=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,oe=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,M="in progress",D="blocked";function K(p,o=[]){if(p==="closed")return"done";if(p!=="open")return"unknown";let t=(o||[]).map(String);return t.some(r=>F.test(r))?"blocked":t.some(r=>z.test(r))?"in_progress":"todo"}function v(p={}){let o=p.owner||process.env.GITHUB_OWNER,t=p.repo||process.env.GITHUB_REPO;if(!o||!t)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:o,repo:t}}function O(p){let o=JSON.parse(p);if(o&&o.error)throw new Error(o.error);return o}function E(p,o={}){let t=p.labels||[],r=p.number,i=o.owner&&o.repo?`${o.owner}/${o.repo}#${r}`:`#${r}`;return{id:String(r),key:i,title:p.title||"",body:p.body||"",state:p.state||null,stateCategory:K(p.state,t),assignee:p.assignee||p.assignees&&p.assignees[0]||null,url:p.url||null,_raw:p}}var se={id:"github",toStateCategory:K,toNeutral:E,IN_PROGRESS_LABEL:M,BLOCKED_LABEL:D,async listCandidates(p={}){let o=p.ctx||{},{owner:t,repo:r}=v(o);return(O(await R.handleToolCall("github_list_issues",{owner:t,repo:r,state:p.state||"open",labels:p.labels,since:p.updatedAfter,limit:p.limit})).issues||[]).map(e=>E(e,{owner:t,repo:r}))},async getTicket(p,o={}){let{owner:t,repo:r}=v(o),i=k(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let e=JSON.parse(await R.handleToolCall("github_get_issue",{owner:t,repo:r,number:i}));return e.error?null:E(e,{owner:t,repo:r})},async getComments(p,o={}){let{owner:t,repo:r}=v(o),i=k(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);return(O(await R.handleToolCall("github_get_issue_comments",{owner:t,repo:r,number:i})).comments||[]).map(n=>({id:String(n.id),author:n.user||"Unknown",body:n.body||"",createdAt:n.createdAt||null,updatedAt:n.updatedAt||null,_raw:n})).sort((n,s)=>String(s.createdAt).localeCompare(String(n.createdAt)))},async addComment(p,o,t={}){let{owner:r,repo:i}=v(t),e=k(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("body is required");let n=O(await R.handleToolCall("github_add_issue_comment",{owner:r,repo:i,number:e,body:o}));return{ok:!!n.ok,id:n.id?String(n.id):null}},async transition(p,o,t={}){let{owner:r,repo:i}=v(t),e=k(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let n=String(o||"");if(ie.test(n)){let s=O(await R.handleToolCall("github_close_issue",{owner:r,repo:i,number:e,stateReason:"completed"}));return{ok:!!s.ok,stateAfter:s.state||"closed",stateCategoryAfter:"done",_raw:s}}if(F.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[D],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:s}}if(z.test(n)){await B(r,i,e);let s=O(await R.handleToolCall("github_label_issue",{owner:r,repo:i,number:e,labels:[M],mode:"add"}));return{ok:!!s.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:s}}if(oe.test(n)){let s=O(await R.handleToolCall("github_reopen_issue",{owner:r,repo:i,number:e}));return{ok:!!s.ok,stateAfter:s.state||"open",stateCategoryAfter:"todo",_raw:s}}return{ok:!1,error:`GitHub issues have no "${o}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(p,o,t,r={}){let{owner:i,repo:e}=v(r),n=k(p);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!o)throw new Error("prUrl is required");let s=`${t?`${t}: `:"Linked PR: "}${o}`;return{ok:!!O(await R.handleToolCall("github_add_issue_comment",{owner:i,repo:e,number:n,body:s})).ok,via:"comment"}}};async function B(p,o,t){await R.handleToolCall("github_reopen_issue",{owner:p,repo:o,number:t})}function k(p){if(p==null)return null;if(typeof p=="number")return p;let o=/(\d+)\s*$/.exec(String(p));return o?Number(o[1]):null}var qe=se;export{qe as default,se as githubAdapter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/skills",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Built-in skill definitions for the Zibby agent-workflow framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",