import{existsSync as M}from"fs";import{fileURLToPath as D}from"url";import{dirname as B,resolve as F}from"path";import{resolveIntegrationToken as G}from"@zibby/core/backend-client.js";var C=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"}),Y=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark",connectPath:"/integrations?provider=lark"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});function z(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let p=B(D(import.meta.url)),s=F(p,"..","bin","mcp-skill.mjs");return M(s)?s:null}async function l(p,s={}){let{token:t}=await G("github"),r=p.startsWith("https://")?p:`https://api.github.com${p}`,n={Authorization:`Bearer ${t}`,Accept:s.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...s.body?{"Content-Type":"application/json"}:{}},e=await fetch(r,{method:s.method||"GET",headers:n,body:s.body?JSON.stringify(s.body):void 0});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`GitHub API ${e.status}: ${i.slice(0,300)}`)}return s.raw?e.text():e.json()}var _={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:C.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
You have access to the user's GitHub repositories. Available tools:

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

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

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

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

When user just wants to "look at" or "read" files (not clone):
- Use github_get_file to read individual files via API`,resolve(){let p=z();if(!p)return{command:null,args:[],env:{},description:this.description};let s={};for(let t of this.envKeys)process.env[t]&&(s[t]=process.env[t]);return{type:"stdio",command:"node",args:[p,"../dist/github.js","githubSkill"],env:s,description:this.description,alwaysLoad:!0}},async handleToolCall(p,s){try{switch(p){case"github_search_issues":{let t=s.query;if(!t)return JSON.stringify({error:"query is required"});let r=await l(`/search/issues?q=${encodeURIComponent(t)}&per_page=${s.limit||20}`),n=(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(i=>i.name),createdAt:e.created_at}));return JSON.stringify({total:r.total_count,items:n})}case"github_search_code":{let t=s.query;if(!t)return JSON.stringify({error:"query is required"});let r=s.repo?`+repo:${s.repo}`:"",n=s.language?`+language:${s.language}`:"",e=await l(`/search/code?q=${encodeURIComponent(t)}${r}${n}&per_page=${s.limit||15}`),i=(e.items||[]).map(o=>({name:o.name,path:o.path,repo:o.repository?.full_name,url:o.html_url,score:o.score}));return JSON.stringify({total:e.total_count,items:i})}case"github_get_pr":{let{owner:t,repo:r,number:n}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=await l(`/repos/${t}/${r}/pulls/${n}`);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(i=>i.name)})}case"github_get_pr_diff":{let{owner:t,repo:r,number:n}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=await l(`/repos/${t}/${r}/pulls/${n}`,{accept:"application/vnd.github.v3.diff",raw:!0}),i=e.length>15e3;return JSON.stringify({number:n,diff:i?e.slice(0,15e3):e,truncated:i,totalLength:e.length})}case"github_list_pr_files":{let{owner:t,repo:r,number:n}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=await l(`/repos/${t}/${r}/pulls/${n}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(i=>({filename:i.filename,status:i.status,additions:i.additions,deletions:i.deletions,patch:i.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:r,number:n}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=await l(`/repos/${t}/${r}/pulls/${n}/comments?per_page=50`),i=await l(`/repos/${t}/${r}/issues/${n}/comments?per_page=50`),o=[...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})),...i.map(a=>({type:"issue",user:a.user?.login,body:a.body?.slice(0,1e3),createdAt:a.created_at}))].sort((a,d)=>new Date(a.createdAt)-new Date(d.createdAt));return JSON.stringify({total:o.length,comments:o})}case"github_get_review_thread":{let{owner:t,repo:r,number:n,commentId:e}=s||{};if(!t||!r||!n||!e)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let i=await l(`/repos/${t}/${r}/pulls/comments/${e}`),o=i.in_reply_to_id||i.id,a=[];try{a=await l(`/repos/${t}/${r}/pulls/${n}/comments?per_page=100`)}catch{a=[i]}(!Array.isArray(a)||a.length===0)&&(a=[i]);let d=a.filter(m=>m.id===o||m.in_reply_to_id===o).sort((m,b)=>new Date(m.created_at)-new Date(b.created_at)),c=d.length?d:[i],u=c.find(m=>m.id===o)||c[0];return JSON.stringify({rootCommentId:o,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:c.map(m=>({id:m.id,user:m.user?.login,body:(m.body||"").slice(0,4e3),createdAt:m.created_at,isRoot:m.id===o,url:m.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:r,number:n,commentId:e,body:i}=s||{};if(!t||!r||!n||!e||!i)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let o=await l(`/repos/${t}/${r}/pulls/${n}/comments/${e}/replies`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url,inReplyTo:o.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:r,number:n,body:e}=s||{};if(!t||!r||!n||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let i=await l(`/repos/${t}/${r}/issues/${n}/comments`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:i.id,url:i.html_url})}case"github_create_review":{let{owner:t,repo:r,number:n,body:e,event:i,comments:o}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let a=(i||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(a))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${i})`});let d=Array.isArray(o)?o.filter(m=>m&&m.path&&m.body&&(m.line!=null||m.position!=null)).map(m=>{let b={path:m.path,body:String(m.body)};return m.line!=null?(b.line=Number(m.line),b.side=m.side==="LEFT"?"LEFT":"RIGHT"):b.position=Number(m.position),b}):[];if(a!=="APPROVE"&&!e&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let c={event:a};e&&(c.body=String(e)),d.length>0&&(c.comments=d);let u=await l(`/repos/${t}/${r}/pulls/${n}/reviews`,{method:"POST",body:c});return JSON.stringify({ok:!0,id:u.id,state:u.state,event:a,commentsPosted:d.length,url:u.html_url})}case"github_list_commits":{let{owner:t,repo:r,branch:n,path:e,limit:i}=s;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let o=`/repos/${t}/${r}/commits?per_page=${i||20}`;n&&(o+=`&sha=${encodeURIComponent(n)}`),e&&(o+=`&path=${encodeURIComponent(e)}`);let a=await l(o);return JSON.stringify({total:a.length,commits:a.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:t,repo:r,sha:n}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and sha are required"});let e=await l(`/repos/${t}/${r}/commits/${n}`);return JSON.stringify({sha:e.sha?.slice(0,8),message:e.commit?.message,author:e.commit?.author?.name,date:e.commit?.author?.date,stats:e.stats,files:(e.files||[]).map(i=>({filename:i.filename,status:i.status,additions:i.additions,deletions:i.deletions,patch:i.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:t,repo:r,path:n,ref:e}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and path are required"});let i=`/repos/${t}/${r}/contents/${encodeURIComponent(n)}`;e&&(i+=`?ref=${encodeURIComponent(e)}`);let o=await l(i);if(o.type!=="file")return Array.isArray(o)?JSON.stringify({type:"directory",path:n,entries:o.map(c=>({name:c.name,type:c.type,size:c.size,path:c.path}))}):JSON.stringify({error:`Not a file: ${o.type}`});let a=Buffer.from(o.content||"","base64").toString("utf-8"),d=a.length>2e4;return JSON.stringify({path:o.path,size:o.size,sha:o.sha?.slice(0,8),content:d?a.slice(0,2e4):a,truncated:d})}case"github_get_user":try{let t=await l("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let r=t.repositories[0],n=r.owner.login,e=r.owner.type,i=e==="Organization"?`/orgs/${n}`:`/users/${n}`,o=await l(i);return JSON.stringify({login:o.login,name:o.name||o.login,avatar:o.avatar_url,bio:o.bio||o.description,type:e,isOrg:e==="Organization",publicRepos:o.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 l("/installation/repositories?per_page=100")).repositories||[],n=new Map;for(let i of r)i.owner.type==="Organization"&&(n.has(i.owner.login)||n.set(i.owner.login,{login:i.owner.login,description:null,url:i.owner.url}));let e=Array.from(n.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 h=function(w){let v=w.replace(/^~(?=$|\/|\\)/,b);return o(v)},{owner:t,repo:r,destination:n}=s;if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:i,resolve:o}=await import("path"),{existsSync:a,mkdirSync:d}=await import("fs"),{homedir:c,platform:u}=await import("os"),{token:m}=await G("github"),b=c(),y=n?h(n):i(b,"zibby-repos"),f=i(y,r);if(d(y,{recursive:!0}),a(f))return JSON.stringify({error:`Directory ${f} already exists. Remove it first or use a different destination.`,existingPath:f});try{let w=`https://x-access-token:${m}@github.com/${t}/${r}.git`;e(`git clone ${w} "${f}"`,{stdio:"pipe"});let v=u()==="win32",g;return v?g=e(`dir "${f}"`,{encoding:"utf-8",shell:"cmd.exe"}):g=e(`ls -la "${f}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:f,message:`Cloned ${t}/${r} to ${f}`,contents:g.split(`
`).slice(0,30).join(`
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(w){return JSON.stringify({error:`Clone failed: ${w.message}`})}}case"github_search_repos":{let{query:t,limit:r}=s;if(!t)return JSON.stringify({error:"query is required"});let n=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(n);if(e.error)return JSON.stringify(e);let i=t.toLowerCase(),o=e.repos.filter(a=>a.name.toLowerCase().includes(i)||a.fullName.toLowerCase().includes(i)||a.description&&a.description.toLowerCase().includes(i));return JSON.stringify({query:t,count:o.length,repos:o.slice(0,r||20)})}case"github_list_repos":{let{owner:t,type:r,sort:n,direction:e,limit:i,query:o}=s,a=100,d=i||200,c=[],u=g=>({name:g.name,fullName:g.full_name,private:g.private,description:g.description,language:g.language,defaultBranch:g.default_branch,updatedAt:g.updated_at,stars:g.stargazers_count,url:g.html_url,fullPath:g.full_name,webUrl:g.html_url,visibility:g.visibility||(g.private?"private":"public")}),m=g=>{if(!o)return!0;let R=String(o).toLowerCase();return g.name&&g.name.toLowerCase().includes(R)||g.fullName&&g.fullName.toLowerCase().includes(R)||g.description&&g.description.toLowerCase().includes(R)};if(!t){let g=1,R=!0;for(;R&&c.length<d;){let A=`/installation/repositories?per_page=${a}&page=${g}`,E=(await l(A)).repositories||[];if(E.length===0)break;c=c.concat(E),R=E.length===a,g++}let O=c.map(u).filter(m),N=O.slice(0,d),j=O.length>N.length,T=N.filter(A=>A.private).length,q=N.filter(A=>!A.private).length;return JSON.stringify({count:N.length,repos:N,truncated:j,privateCount:T,publicCount:q,message:`Found ${T} private and ${q} public repos`})}let b=await l(`/orgs/${t}`).then(()=>!0).catch(()=>!1),h=1,y=!0;for(;y&&c.length<d;){let g;b?g=`/orgs/${t}/repos?per_page=${a}&page=${h}&type=${r||"all"}&sort=${n||"updated"}&direction=${e||"desc"}`:g=`/users/${t}/repos?per_page=${a}&page=${h}&type=${r||"all"}&sort=${n||"updated"}&direction=${e||"desc"}`;let R=await l(g),O=Array.isArray(R)?R:[];if(O.length===0)break;c=c.concat(O),y=O.length===a,h++}let f=c.map(u).filter(m),w=f.slice(0,d),v=f.length>w.length;return JSON.stringify({count:w.length,repos:w,truncated:v})}case"github_create_pr":{let{owner:t,repo:r,head:n,title:e}=s||{};if(!t||!r||!n||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let i=s.base;if(!i)try{i=(await l(`/repos/${t}/${r}`)).default_branch||"main"}catch{i="main"}let o={title:String(e),head:String(n),base:String(i),body:s.body?String(s.body):"",draft:!!s.draft};try{let a=await l(`/repos/${t}/${r}/pulls`,{method:"POST",body:o});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:n,base:i,repo:`${t}/${r}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let d=String(a.message||a);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:n,base:i,repo:`${t}/${r}`,provider:"github",skippedReason:d});throw a}}case"github_merge_pr":{let{owner:t,repo:r,number:n}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=s.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let i={merge_method:e};s.commitTitle&&(i.commit_title=String(s.commitTitle)),s.commitMessage&&(i.commit_message=String(s.commitMessage));try{let o=await l(`/repos/${t}/${r}/pulls/${n}/merge`,{method:"PUT",body:i});return JSON.stringify({success:!0,merged:!0,sha:o.sha,number:n,provider:"github"})}catch(o){let a=String(o.message||o);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:n,provider:"github",skippedReason:a});throw o}}case"github_create_issue":{let{owner:t,repo:r,title:n,body:e}=s;if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and title are required"});let i=await l(`/repos/${t}/${r}/issues`,{method:"POST",body:{title:n,body:e||""}});return JSON.stringify({number:i.number,url:i.html_url,title:i.title})}case"github_list_issues":{let{owner:t,repo:r,state:n,labels:e,since:i,assignee:o,sort:a,direction:d,limit:c}=s||{};if(!t||!r)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",n||"open"),u.set("per_page",String(c||30)),u.set("sort",a||"updated"),u.set("direction",d||"desc"),e&&u.set("labels",Array.isArray(e)?e.join(","):e),i&&u.set("since",i),o&&u.set("assignee",o);let m=await l(`/repos/${t}/${r}/issues?${u.toString()}`),b=(Array.isArray(m)?m:[]).filter(h=>!h.pull_request).map(h=>({number:h.number,title:h.title,state:h.state,labels:(h.labels||[]).map(y=>typeof y=="string"?y:y.name),assignee:h.assignee?.login||null,assignees:(h.assignees||[]).map(y=>y.login),user:h.user?.login,comments:h.comments,url:h.html_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"github_get_issue":{let{owner:t,repo:r,number:n}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=await l(`/repos/${t}/${r}/issues/${n}`);return e.pull_request?JSON.stringify({error:`#${n} 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(i=>typeof i=="string"?i:i.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(i=>i.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:n,limit:e}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await l(`/repos/${t}/${r}/issues/${n}/comments?per_page=${e||100}`),o=(Array.isArray(i)?i:[]).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:o.length,comments:o})}case"github_add_issue_comment":{let{owner:t,repo:r,number:n,body:e}=s||{};if(!t||!r||!n||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let i=await l(`/repos/${t}/${r}/issues/${n}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:i.id,url:i.html_url})}case"github_close_issue":{let{owner:t,repo:r,number:n,stateReason:e}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i={state:"closed"};e&&(i.state_reason=e);let o=await l(`/repos/${t}/${r}/issues/${n}`,{method:"PATCH",body:i});return JSON.stringify({ok:!0,number:o.number,state:o.state,stateReason:o.state_reason||null,url:o.html_url})}case"github_reopen_issue":{let{owner:t,repo:r,number:n}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let e=await l(`/repos/${t}/${r}/issues/${n}`,{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:n,labels:e,mode:i}=s||{};if(!t||!r||!n)return JSON.stringify({error:"owner, repo, and number are required"});let o=Array.isArray(e)?e:e?[e]:[];if(!o.length)return JSON.stringify({error:"labels (string or array) is required"});let a=i||"add";if(a==="set"){let c=await l(`/repos/${t}/${r}/issues/${n}`,{method:"PATCH",body:{labels:o}});return JSON.stringify({ok:!0,number:c.number,labels:(c.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(a==="remove"){for(let u of o)await l(`/repos/${t}/${r}/issues/${n}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let c=await l(`/repos/${t}/${r}/issues/${n}`);return JSON.stringify({ok:!0,number:c.number,labels:(c.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let d=await l(`/repos/${t}/${r}/issues/${n}/labels`,{method:"POST",body:{labels:o}});return JSON.stringify({ok:!0,number:n,labels:(Array.isArray(d)?d:[]).map(c=>typeof c=="string"?c:c.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 recent commits on a branch, optionally filtered by file path",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Max commits (default: 20)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};var L=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,U=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,K=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,W=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,I="in progress",J="blocked";function x(p,s=[]){if(p==="closed")return"done";if(p!=="open")return"unknown";let t=(s||[]).map(String);return t.some(r=>L.test(r))?"blocked":t.some(r=>U.test(r))?"in_progress":"todo"}function $(p={}){let s=p.owner||process.env.GITHUB_OWNER,t=p.repo||process.env.GITHUB_REPO;if(!s||!t)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:s,repo:t}}function S(p){let s=JSON.parse(p);if(s&&s.error)throw new Error(s.error);return s}function k(p,s={}){let t=p.labels||[],r=p.number,n=s.owner&&s.repo?`${s.owner}/${s.repo}#${r}`:`#${r}`;return{id:String(r),key:n,title:p.title||"",body:p.body||"",state:p.state||null,stateCategory:x(p.state,t),assignee:p.assignee||p.assignees&&p.assignees[0]||null,url:p.url||null,_raw:p}}var Q={id:"github",toStateCategory:x,toNeutral:k,IN_PROGRESS_LABEL:I,BLOCKED_LABEL:J,async listCandidates(p={}){let s=p.ctx||{},{owner:t,repo:r}=$(s);return(S(await _.handleToolCall("github_list_issues",{owner:t,repo:r,state:p.state||"open",labels:p.labels,since:p.updatedAfter,limit:p.limit})).issues||[]).map(e=>k(e,{owner:t,repo:r}))},async getTicket(p,s={}){let{owner:t,repo:r}=$(s),n=P(p);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let e=JSON.parse(await _.handleToolCall("github_get_issue",{owner:t,repo:r,number:n}));return e.error?null:k(e,{owner:t,repo:r})},async getComments(p,s={}){let{owner:t,repo:r}=$(s),n=P(p);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);return(S(await _.handleToolCall("github_get_issue_comments",{owner:t,repo:r,number:n})).comments||[]).map(i=>({id:String(i.id),author:i.user||"Unknown",body:i.body||"",createdAt:i.createdAt||null,updatedAt:i.updatedAt||null,_raw:i})).sort((i,o)=>String(o.createdAt).localeCompare(String(i.createdAt)))},async addComment(p,s,t={}){let{owner:r,repo:n}=$(t),e=P(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!s)throw new Error("body is required");let i=S(await _.handleToolCall("github_add_issue_comment",{owner:r,repo:n,number:e,body:s}));return{ok:!!i.ok,id:i.id?String(i.id):null}},async transition(p,s,t={}){let{owner:r,repo:n}=$(t),e=P(p);if(e==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);let i=String(s||"");if(K.test(i)){let o=S(await _.handleToolCall("github_close_issue",{owner:r,repo:n,number:e,stateReason:"completed"}));return{ok:!!o.ok,stateAfter:o.state||"closed",stateCategoryAfter:"done",_raw:o}}if(L.test(i)){await H(r,n,e);let o=S(await _.handleToolCall("github_label_issue",{owner:r,repo:n,number:e,labels:[J],mode:"add"}));return{ok:!!o.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:o}}if(U.test(i)){await H(r,n,e);let o=S(await _.handleToolCall("github_label_issue",{owner:r,repo:n,number:e,labels:[I],mode:"add"}));return{ok:!!o.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:o}}if(W.test(i)){let o=S(await _.handleToolCall("github_reopen_issue",{owner:r,repo:n,number:e}));return{ok:!!o.ok,stateAfter:o.state||"open",stateCategoryAfter:"todo",_raw:o}}return{ok:!1,error:`GitHub issues have no "${s}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(p,s,t,r={}){let{owner:n,repo:e}=$(r),i=P(p);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${p}"`);if(!s)throw new Error("prUrl is required");let o=`${t?`${t}: `:"Linked PR: "}${s}`;return{ok:!!S(await _.handleToolCall("github_add_issue_comment",{owner:n,repo:e,number:i,body:o})).ok,via:"comment"}}};async function H(p,s,t){await _.handleToolCall("github_reopen_issue",{owner:p,repo:s,number:t})}function P(p){if(p==null)return null;if(typeof p=="number")return p;let s=/(\d+)\s*$/.exec(String(p));return s?Number(s[1]):null}var se=Q;export{se as default,Q as githubAdapter};
