@zibby/skills 0.2.9 → 0.2.11

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/artifact.js CHANGED
@@ -1,4 +1,4 @@
1
- import{SKILL_META as b}from"@zibby/skill-ids";import{existsSync as y,readFileSync as k}from"node:fs";import{homedir as O}from"node:os";import{join as g,dirname as _,resolve as v}from"node:path";import{fileURLToPath as S}from"node:url";function T(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let i=_(S(import.meta.url)),t=v(i,"..","bin","mcp-skill.mjs");return y(t)?t:null}function l(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let i=g(O(),".zibby","config.json");return y(i)&&JSON.parse(k(i,"utf-8")).sessionToken||null}catch{return null}}function p(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function N(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function h(i){return`${N()}:artifact:${i}`}async function u(i){let t=l();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${p()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`artifact write failed (${e.status}): ${r.slice(0,300)}`)}return e.json()}async function P(i){let t=l();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${p()}/credits/artifacts/${encodeURIComponent(i)}`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`artifact get failed (${e.status}): ${r.slice(0,300)}`)}return e.json()}async function f(i,t){let e=l();if(!e)return;let r=await fetch(`${p()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:h(i),content:JSON.stringify(t)})});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`artifact index write failed (${r.status}): ${n.slice(0,200)}`)}}async function R(i){let t=l();if(!t)return null;let e=await fetch(`${p()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:h(i)})});if(!e.ok)return null;let r=await e.json().catch(()=>null);if(!r?.found||!r?.memory?.content)return null;try{return JSON.parse(r.memory.content)}catch{return null}}function m(i){return typeof i?.html=="string"&&i.html.length>0?{format:"html",content:i.html}:typeof i?.markdown=="string"&&i.markdown.length>0?{format:"markdown",content:i.markdown}:null}var x={id:"artifact",callsBackend:!0,meta:b.artifact,serverName:"artifact",allowedTools:["mcp__artifact__*"],description:"Artifacts \u2014 publish a self-contained, shareable HTML/Markdown page to Zibby and get back a URL; the index of what you published is your memory.",promptFragment:`## Artifacts (publish a shareable page, remember what you made)
1
+ import{SKILL_META as b}from"@zibby/skill-ids";import{existsSync as m,readFileSync as O}from"node:fs";import{homedir as g}from"node:os";import{join as T,dirname as k,resolve as S}from"node:path";import{fileURLToPath as N}from"node:url";function v(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let i=k(N(import.meta.url)),t=S(i,"..","bin","mcp-skill.mjs");return m(t)?t:null}function l(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let i=T(g(),".zibby","config.json");return m(i)&&JSON.parse(O(i,"utf-8")).sessionToken||null}catch{return null}}function p(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function _(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function y(i){return`${_()}:artifact:${i}`}async function u(i){let t=l();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${p()}/credits/artifacts`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`artifact write failed (${e.status}): ${r.slice(0,300)}`)}return e.json()}async function I(i){let t=l();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Artifacts are only available inside a Zibby run.");let e=await fetch(`${p()}/credits/artifacts/${encodeURIComponent(i)}`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`artifact get failed (${e.status}): ${r.slice(0,300)}`)}return e.json()}async function f(i,t){let e=l();if(!e)return;let r=await fetch(`${p()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:"store",scope:y(i),content:JSON.stringify(t)})});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`artifact index write failed (${r.status}): ${n.slice(0,200)}`)}}async function E(i){let t=l();if(!t)return null;let e=await fetch(`${p()}/credits/review-memory`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:"recall",scope:y(i)})});if(!e.ok)return null;let r=await e.json().catch(()=>null);if(!r?.found||!r?.memory?.content)return null;try{return JSON.parse(r.memory.content)}catch{return null}}function h(i){return typeof i?.html=="string"&&i.html.length>0?{format:"html",content:i.html}:typeof i?.markdown=="string"&&i.markdown.length>0?{format:"markdown",content:i.markdown}:null}var B={id:"artifact",callsBackend:!0,meta:b.artifact,serverName:"artifact",allowedTools:["mcp__artifact__*"],description:"Artifacts \u2014 publish a self-contained, shareable HTML/Markdown page to Zibby and get back a URL; the index of what you published is your memory.",promptFragment:`## Artifacts (publish a shareable page, remember what you made)
2
2
  You can PUBLISH a standalone page \u2014 a status report, a plan, a comparison table,
3
3
  a dashboard-y summary, a diagram, a "here's what I found" write-up \u2014 and get back
4
4
  a shareable URL. The page is a self-contained HTML (or Markdown) document; it is
@@ -6,6 +6,22 @@ sandboxed when viewed (no external network, no ambient credentials), so keep all
6
6
  CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 external URLs will
7
7
  be blocked.
8
8
 
9
+ THE CONTENT COMES FROM THIS CONVERSATION \u2014 NEVER FROM YOUR IMAGINATION.
10
+ When someone says "make me a page / an artifact / a report", they mean THE THING
11
+ YOU WERE JUST TALKING ABOUT. Build the page from what is actually in this
12
+ transcript (or from data you fetch with your tools THIS turn for that specific
13
+ subject). The page is about the USER'S subject matter \u2014 their tickets, their
14
+ repos, their incidents, their data.
15
+
16
+ If you do NOT know what the page should be about \u2014 the request is vague and the
17
+ transcript does not tell you \u2014 then ASK ONE SHORT QUESTION ("which part should I
18
+ turn into a page?") and publish NOTHING. Do NOT fall back on a demo, a sample, a
19
+ placeholder, or a "here's an overview of your account" page, and do NOT go
20
+ inventory the account (projects / agents / integrations) just to have something to
21
+ render. A page the user did not ask for is worse than a question: it wastes the
22
+ link, buries the real answer, and reads as if you ignored them. There is no
23
+ situation in which "\u793A\u4F8B / sample / demo" belongs in a title you publish.
24
+
9
25
  Tools:
10
26
  - artifact_publish: Publish a NEW page. Pass a \`title\` and EITHER \`html\` OR
11
27
  \`markdown\` (not both). Optional \`kind\` (e.g. "report", "plan", "dashboard"),
@@ -19,4 +35,4 @@ Tools:
19
35
  To recall WHAT YOU HAVE ALREADY PUBLISHED, use your kv-memory tool
20
36
  kv_recall_prefix with keyPrefix "artifact:" \u2014 each entry is the index record
21
37
  { id, title, url, kind, createdAt, summary } for a page you made. (Publishing
22
- records this automatically; you don't store it yourself.)`,resolve(){let i=T();if(!i)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[i,"../dist/artifact.js","artifactSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(i,t){try{switch(i){case"artifact_publish":{let e=typeof t?.title=="string"?t.title.trim():"";if(!e)return JSON.stringify({error:"title is required"});let r=m(t);if(!r)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let n={title:e,[r.format]:r.content};typeof t?.kind=="string"&&t.kind.trim()&&(n.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(n.favicon=t.favicon.trim());let a=await u(n),o=a?.id,s=a?.url;if(!o||!s)return JSON.stringify({error:"artifact write returned no id/url",response:a});let d={id:o,title:e,url:s,kind:n.kind||null,createdAt:a.createdAt||new Date().toISOString(),summary:typeof t?.summary=="string"&&t.summary.trim()?t.summary.trim():e};try{await f(o,d)}catch(c){return JSON.stringify({id:o,url:s,indexWarning:c.message})}return JSON.stringify({id:o,url:s})}case"artifact_update":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let r=m(t),n=typeof t?.title=="string"?t.title.trim():"";if(!r&&!n)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let a={id:e};n&&(a.title=n),r&&(a[r.format]=r.content),typeof t?.kind=="string"&&t.kind.trim()&&(a.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(a.favicon=t.favicon.trim());let o=await u(a),s=o?.url;if(!s)return JSON.stringify({error:"artifact update returned no url",response:o});let d=await R(e)||{},c={...d,id:e,url:s,title:n||d.title||"Untitled",kind:a.kind||d.kind||null,createdAt:d.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof t?.summary=="string"&&t.summary.trim()?c.summary=t.summary.trim():c.summary||(c.summary=c.title);try{await f(e,c)}catch(w){return JSON.stringify({id:e,url:s,indexWarning:w.message})}return JSON.stringify({id:e,url:s})}case"artifact_get":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let r=await P(e);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"artifact_publish",description:"Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. Pass a title and EITHER html OR markdown. Keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 the page is sandboxed on view and external URLs are blocked. Returns { id, url }.",input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},html:{type:"string",description:"The page content as a self-contained HTML document (or fragment). Provide this OR markdown, not both."},markdown:{type:"string",description:"The page content as Markdown (rendered to HTML on serve). Provide this OR html, not both."},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or html|markdown). Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},html:{type:"string",description:"New HTML content (optional). Provide this OR markdown."},markdown:{type:"string",description:"New Markdown content (optional). Provide this OR html."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}}]};export{x as artifactSkill};
38
+ records this automatically; you don't store it yourself.)`,resolve(){let i=v();if(!i)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[i,"../dist/artifact.js","artifactSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(i,t){try{switch(i){case"artifact_publish":{let e=typeof t?.title=="string"?t.title.trim():"";if(!e)return JSON.stringify({error:"title is required"});let r=h(t);if(!r)return JSON.stringify({error:"provide exactly one of html or markdown (non-empty string)"});let n={title:e,[r.format]:r.content};typeof t?.kind=="string"&&t.kind.trim()&&(n.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(n.favicon=t.favicon.trim());let a=await u(n),o=a?.id,s=a?.url;if(!o||!s)return JSON.stringify({error:"artifact write returned no id/url",response:a});let d={id:o,title:e,url:s,kind:n.kind||null,createdAt:a.createdAt||new Date().toISOString(),summary:typeof t?.summary=="string"&&t.summary.trim()?t.summary.trim():e};try{await f(o,d)}catch(c){return JSON.stringify({id:o,url:s,indexWarning:c.message})}return JSON.stringify({id:o,url:s})}case"artifact_update":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let r=h(t),n=typeof t?.title=="string"?t.title.trim():"";if(!r&&!n)return JSON.stringify({error:"nothing to update \u2014 pass a new title and/or html|markdown"});let a={id:e};n&&(a.title=n),r&&(a[r.format]=r.content),typeof t?.kind=="string"&&t.kind.trim()&&(a.kind=t.kind.trim()),typeof t?.favicon=="string"&&t.favicon.trim()&&(a.favicon=t.favicon.trim());let o=await u(a),s=o?.url;if(!s)return JSON.stringify({error:"artifact update returned no url",response:o});let d=await E(e)||{},c={...d,id:e,url:s,title:n||d.title||"Untitled",kind:a.kind||d.kind||null,createdAt:d.createdAt||o.createdAt||new Date().toISOString(),updatedAt:o.updatedAt||new Date().toISOString()};typeof t?.summary=="string"&&t.summary.trim()?c.summary=t.summary.trim():c.summary||(c.summary=c.title);try{await f(e,c)}catch(w){return JSON.stringify({id:e,url:s,indexWarning:w.message})}return JSON.stringify({id:e,url:s})}case"artifact_get":{let e=typeof t?.id=="string"?t.id.trim():"";if(!e)return JSON.stringify({error:"id is required"});let r=await I(e);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"artifact_publish",description:"Publish a NEW self-contained, shareable page (report/plan/table/dashboard/diagram/write-up) and get back a shareable URL. The content MUST come from the current conversation or data you fetched this turn for that subject \u2014 if you are not sure what the page should be about, ASK the user instead of calling this tool; never publish a demo/sample/placeholder or an account-overview page as a stand-in. Pass a title and EITHER html OR markdown. Keep all CSS/JS/images INLINE (inline <style>/<script>, data: URIs) \u2014 the page is sandboxed on view and external URLs are blocked. Returns { id, url }.",input_schema:{type:"object",properties:{title:{type:"string",description:"The page title (also the browser tab title)."},html:{type:"string",description:"The page content as a self-contained HTML document (or fragment). Provide this OR markdown, not both."},markdown:{type:"string",description:"The page content as Markdown (rendered to HTML on serve). Provide this OR html, not both."},kind:{type:"string",description:'Optional label for what this is, e.g. "report", "plan", "dashboard", "diagram". Stored in your index.'},favicon:{type:"string",description:'Optional emoji used as the browser-tab icon, e.g. "\u{1F4CA}".'},summary:{type:"string",description:"Optional one-line summary for your own index (defaults to the title). Helps you recall later what this page was."}},required:["title"]}},{name:"artifact_update",description:"Revise an EXISTING artifact by id \u2014 the shareable URL stays the same, the content is replaced (new version). Pass the fields to change (title and/or html|markdown). Returns { id, url }.",input_schema:{type:"object",properties:{id:{type:"string",description:'The id of the artifact to update (from a prior artifact_publish, or your kv-memory "artifact:" index).'},title:{type:"string",description:"New title (optional)."},html:{type:"string",description:"New HTML content (optional). Provide this OR markdown."},markdown:{type:"string",description:"New Markdown content (optional). Provide this OR html."},kind:{type:"string",description:"Optional updated kind label."},favicon:{type:"string",description:"Optional updated emoji favicon."},summary:{type:"string",description:"Optional updated one-line index summary."}},required:["id"]}},{name:"artifact_get",description:'Fetch ONE artifact you published, by id \u2192 { metadata, content }. Use to reuse / edit / re-publish a page. To LIST what you have published, use your kv-memory tool kv_recall_prefix with keyPrefix "artifact:".',input_schema:{type:"object",properties:{id:{type:"string",description:"The artifact id."}},required:["id"]}}]};export{B as artifactSkill};
package/dist/git-write.js CHANGED
@@ -1,4 +1,4 @@
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
1
+ import{spawn as ee,execSync as te}from"child_process";import{existsSync as v,mkdirSync as re,readdirSync as K,statSync as ie,readFileSync as se}from"fs";import{resolve as J,join as j,basename as ne}from"path";var x=".zibby/repos";function D(d,o){try{let i=new URL(d);return i.protocol==="https:"&&i.host.toLowerCase()===o.toLowerCase()}catch{return!1}}function F(d,o,i){let t=new URL(d);return t.username=encodeURIComponent(o),t.password=encodeURIComponent(i),t.toString()}function oe(d){let o=String(d??"");for(let i of[process.env.GITHUB_TOKEN,process.env.GITLAB_TOKEN])i&&(o=o.split(i).join("***"));return o.replace(/x-access-token:[^@\s]*@/g,"x-access-token:***@").replace(/oauth2:[^@\s]*@/g,"oauth2:***@").replace(/https?:\/\/[^/@\s:]+:[^@\s]+@/g,i=>i.replace(/:[^@\s]+@/,":***@"))}function I(d,o,i,t,r="clone"){try{d(`git -C "${o}" remote set-url origin "${i}"`,{stdio:"pipe"})}catch(e){let s=String(e?.message||e);t&&(s=s.split(t).join("***")),console.error(`[${r}] WARNING: failed to strip token from .git/config: ${s}`)}}function L(d,o,i={}){return new Promise((t,r)=>{let e=ee(d,{cwd:o,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...i}}),s="",n="";e.stdout.on("data",a=>{s+=a.toString()}),e.stderr.on("data",a=>{n+=a.toString()}),e.on("close",a=>{a!==0?r(new Error(`Exit ${a}: ${n.trim()||s.trim()}`)):t(s.trim())}),e.on("error",a=>r(a))})}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
@@ -8,11 +8,11 @@ When your task needs repository context you don't have yet:
8
8
  1. Clone the relevant repo with git_checkout
9
9
  2. Use git_explore to understand the project structure
10
10
  3. Use shell commands (grep, cat) to read specific files for deeper understanding
11
- 4. Use GitHub/GitLab skills to read related PRs and commits when history matters`,resolve(){return null},async handleToolCall(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(d,o,i){let t=i?.options?.workspace||process.cwd();try{switch(d){case"git_checkout":return await ae(o,t);case"git_list_repos":return ce(o,t);case"git_explore":return pe(o,t);default:return JSON.stringify({error:`Unknown tool: ${d}`})}}catch(r){return JSON.stringify({error:oe(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 ae(d,o){let{url:i,branch:t,shallow:r=!0,name:e}=d;!i.includes("://")&&!i.startsWith("git@")&&(i=`https://github.com/${i}`);let s=e||ne(i.replace(/\.git$/,"")),n=J(o,x);re(n,{recursive:!0});let a=j(n,s),p=i,l=process.env.GITHUB_TOKEN,c=process.env.GITLAB_TOKEN,b=process.env.GITLAB_URL;if(D(i,"github.com")&&l)p=F(i,"x-access-token",l);else if(c&&b)try{let _=new URL(b).host;D(i,_)&&(p=F(i,"oauth2",c))}catch{}if(v(j(a,".git"))){let _=t?`git -C "${a}" fetch "${p}" ${t} && git -C "${a}" checkout ${t} && git -C "${a}" merge --ff-only FETCH_HEAD`:`git -C "${a}" pull "${p}"`;await L(_,o);let g=await L(`git -C "${a}" log -1 --format="%h %s"`,o);return JSON.stringify({action:"updated",repo:s,path:a,branch:t||"default",head:g})}let u=["git","clone"];r&&u.push("--depth","1"),t&&u.push("--branch",t),u.push(`"${p}"`,`"${a}"`),await L(u.join(" "),o),I(te,a,i,l||c,"git_checkout");let f=await L(`git -C "${a}" log -1 --format="%h %s"`,o);return JSON.stringify({action:"cloned",repo:s,path:a,branch:t||"default",shallow:r,head:f})}function ce(d,o){let i=J(o,x);if(!v(i))return JSON.stringify({repos:[],message:"No repos cloned yet"});let t=[];for(let r of K(i,{withFileTypes:!0})){if(!r.isDirectory())continue;let e=j(i,r.name);if(!v(j(e,".git")))continue;let s=ie(e);t.push({name:r.name,path:e,lastModified:s.mtime.toISOString()})}return JSON.stringify({repos:t,total:t.length,directory:i})}function pe(d,o){let{repo:i,depth:t=2}=d,r=J(o,x,i);if(!v(r))return JSON.stringify({error:`Repo not found: ${i}. Run git_checkout first.`});let e={repo:i,path:r},s=j(r,"package.json");if(v(s))try{let u=JSON.parse(se(s,"utf-8"));e.packageJson={name:u.name,version:u.version,scripts:u.scripts?Object.keys(u.scripts):[],dependencies:u.dependencies?Object.keys(u.dependencies).slice(0,30):[],devDependencies:u.devDependencies?Object.keys(u.devDependencies).slice(0,20):[]},u.dependencies?.react?e.framework="React":u.dependencies?.next?e.framework="Next.js":u.dependencies?.vue?e.framework="Vue":u.dependencies?.angular?e.framework="Angular":u.dependencies?.express?e.framework="Express":u.dependencies?.fastify&&(e.framework="Fastify")}catch{}let n=j(r,"pyproject.toml");v(n)&&(e.language="Python");let a=j(r,"go.mod");v(a)&&(e.language="Go");let p=j(r,"Cargo.toml");v(p)&&(e.language="Rust"),v(s)&&(e.language=e.language||"JavaScript/TypeScript");let l=[];function c(u,f,_){if(_>t)return;let g;try{g=K(u,{withFileTypes:!0})}catch{return}let S=g.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 S){let h=m.isDirectory();l.push(`${f}${h?"\u{1F4C1}":"\u{1F4C4}"} ${m.name}`),h&&_<t&&c(j(u,m.name),`${f} `,_+1)}}c(r,"",1),e.tree=l.slice(0,80),l.length>80&&(e.treeTruncated=!0);let b=["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=b.filter(u=>v(j(r,u))),JSON.stringify(e)}import{existsSync as he}from"fs";import{fileURLToPath as ge}from"url";import{dirname as be,resolve as ye}from"path";import{resolveIntegrationToken as Y}from"@zibby/core/backend-client.js";var T=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"}),Ge=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 de from"crypto";var z=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,W=/<!--\s*zbreview-summary\s*-->/i;function le(d){return String(d||"").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 ue(d,o){return de.createHash("sha256").update(`${String(d||"")}\0${le(o)}`).digest("hex").slice(0,12)}function me(d){return`
12
12
 
13
- <!-- zbfp:${l} -->`}var k=`
13
+ <!-- zbfp:${d} -->`}var k=`
14
14
 
15
- <!-- zbreview-summary -->`;function q(l){let n=z.exec(String(l||""));return n?n[1].toLowerCase():null}function G(l){return W.test(String(l||""))}function E(l,n){let t=new Set([...n||[]].map(e=>String(e).toLowerCase())),i=[],r=0;for(let e of Array.isArray(l)?l:[]){if(!e||!e.body)continue;let s=le(e.path,e.body);if(t.has(s)){r+=1;continue}t.add(s),i.push({...e,_fp:s,body:`${String(e.body)}${ue(s)}`})}return{toPost:i,skipped:r}}function ye(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let l=ge(he(import.meta.url)),n=be(l,"..","bin","mcp-skill.mjs");return me(n)?n:null}async function f(l,n={}){let{token:t}=await Y("github"),i=l.startsWith("https://")?l:`https://api.github.com${l}`,r={Authorization:`Bearer ${t}`,Accept:n.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...n.body?{"Content-Type":"application/json"}:{}},e=await fetch(i,{method:n.method||"GET",headers:r,body:n.body?JSON.stringify(n.body):void 0});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`GitHub API ${e.status}: ${s.slice(0,300)}`)}return n.raw?e.text():e.json()}var U={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:L.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
15
+ <!-- zbreview-summary -->`;function q(d){let o=z.exec(String(d||""));return o?o[1].toLowerCase():null}function G(d){return W.test(String(d||""))}function E(d,o){let i=new Set([...o||[]].map(e=>String(e).toLowerCase())),t=[],r=0;for(let e of Array.isArray(d)?d:[]){if(!e||!e.body)continue;let s=ue(e.path,e.body);if(i.has(s)){r+=1;continue}i.add(s),t.push({...e,_fp:s,body:`${String(e.body)}${me(s)}`})}return{toPost:t,skipped:r}}function fe(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let d=be(ge(import.meta.url)),o=ye(d,"..","bin","mcp-skill.mjs");return he(o)?o:null}async function y(d,o={}){let{token:i}=await Y("github"),t=d.startsWith("https://")?d:`https://api.github.com${d}`,r={Authorization:`Bearer ${i}`,Accept:o.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...o.body?{"Content-Type":"application/json"}:{}},e=await fetch(t,{method:o.method||"GET",headers:r,body:o.body?JSON.stringify(o.body):void 0});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`GitHub API ${e.status}: ${s.slice(0,300)}`)}return o.raw?e.text():e.json()}var U={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:T.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
16
16
  You have access to the user's GitHub repositories. Available tools:
17
17
 
18
18
  ### Discovery
@@ -55,9 +55,9 @@ When user says "check out repo-name" or "clone repo-name":
55
55
  3. STOP. Do not offer to inspect files or ask what to do next.
56
56
 
57
57
  When user just wants to "look at" or "read" files (not clone):
58
- - Use github_get_file to read individual files via API`,resolve(){let l=ye();if(!l)return{command:null,args:[],env:{},description:this.description};let n={};for(let t of this.envKeys)process.env[t]&&(n[t]=process.env[t]);return{type:"stdio",command:"node",args:[l,"../dist/github.js","githubSkill"],env:n,description:this.description,alwaysLoad:!0}},async handleToolCall(l,n){try{switch(l){case"github_search_issues":{let t=n.query;if(!t)return JSON.stringify({error:"query is required"});let i=await f(`/search/issues?q=${encodeURIComponent(t)}&per_page=${n.limit||20}`),r=(i.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(s=>s.name),createdAt:e.created_at}));return JSON.stringify({total:i.total_count,items:r})}case"github_search_code":{let t=n.query;if(!t)return JSON.stringify({error:"query is required"});let i=n.repo?`+repo:${n.repo}`:"",r=n.language?`+language:${n.language}`:"",e=await f(`/search/code?q=${encodeURIComponent(t)}${i}${r}&per_page=${n.limit||15}`),s=(e.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:e.total_count,items:s})}case"github_get_pr":{let{owner:t,repo:i,number:r}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await f(`/repos/${t}/${i}/pulls/${r}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,headSha:e.head?.sha,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(s=>s.name)})}case"github_get_pr_diff":{let{owner:t,repo:i,number:r}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await f(`/repos/${t}/${i}/pulls/${r}`,{accept:"application/vnd.github.v3.diff",raw:!0}),s=e.length>15e3;return JSON.stringify({number:r,diff:s?e.slice(0,15e3):e,truncated:s,totalLength:e.length})}case"github_list_pr_files":{let{owner:t,repo:i,number:r}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await f(`/repos/${t}/${i}/pulls/${r}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(s=>({filename:s.filename,status:s.status,additions:s.additions,deletions:s.deletions,patch:s.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:t,repo:i,number:r}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await f(`/repos/${t}/${i}/pulls/${r}/comments?per_page=50`),s=await f(`/repos/${t}/${i}/issues/${r}/comments?per_page=50`),a=[...e.map(o=>({type:"review",user:o.user?.login,body:o.body?.slice(0,1e3),path:o.path,line:o.line,createdAt:o.created_at})),...s.map(o=>({type:"issue",user:o.user?.login,body:o.body?.slice(0,1e3),createdAt:o.created_at}))].sort((o,p)=>new Date(o.createdAt)-new Date(p.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:t,repo:i,number:r,commentId:e}=n||{};if(!t||!i||!r||!e)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let s=await f(`/repos/${t}/${i}/pulls/comments/${e}`),a=s.in_reply_to_id||s.id,o=[];try{o=await f(`/repos/${t}/${i}/pulls/${r}/comments?per_page=100`)}catch{o=[s]}(!Array.isArray(o)||o.length===0)&&(o=[s]);let p=o.filter(d=>d.id===a||d.in_reply_to_id===a).sort((d,b)=>new Date(d.created_at)-new Date(b.created_at)),c=p.length?p:[s],u=c.find(d=>d.id===a)||c[0];return JSON.stringify({rootCommentId:a,path:u.path,line:u.line??u.original_line??null,side:u.side||"RIGHT",diffHunk:typeof u.diff_hunk=="string"?u.diff_hunk.slice(0,3e3):null,commitId:u.commit_id||u.original_commit_id||null,notes:c.map(d=>({id:d.id,user:d.user?.login,body:(d.body||"").slice(0,4e3),createdAt:d.created_at,isRoot:d.id===a,url:d.html_url}))})}case"github_reply_review_thread":{let{owner:t,repo:i,number:r,commentId:e,body:s}=n||{};if(!t||!i||!r||!e||!s)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await f(`/repos/${t}/${i}/pulls/${r}/comments/${e}/replies`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:t,repo:i,number:r,body:e}=n||{};if(!t||!i||!r||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await f(`/repos/${t}/${i}/issues/${r}/comments`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_create_review":{let{owner:t,repo:i,number:r,body:e,event:s,comments:a}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let o=(s||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(o))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${s})`});let p=Array.isArray(a)?a.filter(m=>m&&m.path&&m.body&&(m.line!=null||m.position!=null)).map(m=>{let h={path:m.path,body:String(m.body)};return m.line!=null?(h.line=Number(m.line),h.side=m.side==="LEFT"?"LEFT":"RIGHT"):h.position=Number(m.position),h}):[];if(o!=="APPROVE"&&!e&&p.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let c=new Set,u=null;try{for(let m=1;m<=20;m+=1){let h=await f(`/repos/${t}/${i}/pulls/${r}/comments?per_page=100&page=${m}`);if(!Array.isArray(h)||h.length===0)break;for(let R of h){let A=q(R.body);A&&c.add(A)}if(h.length<100)break}for(let m=1;m<=20&&u==null;m+=1){let h=await f(`/repos/${t}/${i}/issues/${r}/comments?per_page=100&page=${m}`);if(!Array.isArray(h)||h.length===0)break;for(let R of h)if(G(R.body)){u=R.id;break}if(h.length<100)break}}catch{}let d=!1,b=!1;if(e){let m=`${String(e)}${k}`;try{u!=null?(await f(`/repos/${t}/${i}/issues/comments/${u}`,{method:"PATCH",body:{body:m}}),d=!0):await f(`/repos/${t}/${i}/issues/${r}/comments`,{method:"POST",body:{body:m}}),b=!0}catch{}}let{toPost:_,skipped:g}=E(p,c),w=_.map(({_fp:m,...h})=>h),y=null;if(w.length>0||o==="APPROVE"||o==="REQUEST_CHANGES"){let m={event:o};w.length>0&&(m.comments=w),w.length===0&&o==="REQUEST_CHANGES"&&(m.body="Changes requested \u2014 see the review summary comment."),y=await f(`/repos/${t}/${i}/pulls/${r}/reviews`,{method:"POST",body:m})}return JSON.stringify({ok:!0,id:y?y.id:void 0,state:y?y.state:void 0,event:o,notePosted:b,summaryUpdated:d,commentsPosted:w.length,inlineSkipped:g||void 0,url:y?y.html_url:void 0})}case"github_list_commits":{let{owner:t,repo:i,branch:r,path:e,limit:s,since:a,until:o,page:p}=n;if(!t||!i)return JSON.stringify({error:"owner and repo are required"});let c=Math.min(Number(s)||20,100),u=`/repos/${t}/${i}/commits?per_page=${c}&page=${Number(p)||1}`;r&&(u+=`&sha=${encodeURIComponent(r)}`),e&&(u+=`&path=${encodeURIComponent(e)}`),a&&(u+=`&since=${encodeURIComponent(a)}`),o&&(u+=`&until=${encodeURIComponent(o)}`);let d=await f(u);return JSON.stringify({total:d.length,page:Number(p)||1,hasMore:d.length>=c,commits:d.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:i,sha:r,includePrs:e}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await f(`/repos/${t}/${i}/commits/${r}`),a;if(e)try{let o=await f(`/repos/${t}/${i}/commits/${r}/pulls`);a=(Array.isArray(o)?o:[]).map(p=>({number:p.number,title:p.title,state:p.state,merged:!!p.merged_at,webUrl:p.html_url}))}catch{a=[]}return JSON.stringify({sha:s.sha?.slice(0,8),message:s.commit?.message,author:s.commit?.author?.name,date:s.commit?.author?.date,stats:s.stats,files:(s.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:t,repo:i,path:r,ref:e}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and path are required"});let s=`/repos/${t}/${i}/contents/${encodeURIComponent(r)}`;e&&(s+=`?ref=${encodeURIComponent(e)}`);let a=await f(s);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:r,entries:a.map(c=>({name:c.name,type:c.type,size:c.size,path:c.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let o=Buffer.from(a.content||"","base64").toString("utf-8"),p=o.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:p?o.slice(0,2e4):o,truncated:p})}case"github_get_user":try{let t=await f("/installation/repositories?per_page=1");if(t.repositories&&t.repositories.length>0){let i=t.repositories[0],r=i.owner.login,e=i.owner.type,s=e==="Organization"?`/orgs/${r}`:`/users/${r}`,a=await f(s);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:e,isOrg:e==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(t){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${t.message})`})}case"github_list_orgs":try{let i=(await f("/installation/repositories?per_page=100")).repositories||[],r=new Map;for(let s of i)s.owner.type==="Organization"&&(r.has(s.owner.login)||r.set(s.owner.login,{login:s.owner.login,description:null,url:s.owner.url}));let e=Array.from(r.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 _=function(m){let h=m.replace(/^~(?=$|\/|\\)/,b);return a(h)},{owner:t,repo:i,destination:r}=n;if(!t||!i)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:s,resolve:a}=await import("path"),{existsSync:o,mkdirSync:p}=await import("fs"),{homedir:c,platform:u}=await import("os"),{token:d}=await Y("github"),b=c(),g=r?_(r):s(b,"zibby-repos"),w=s(g,i);if(p(g,{recursive:!0}),o(w))return JSON.stringify({error:`Directory ${w} already exists. Remove it first or use a different destination.`,existingPath:w});let y=`https://x-access-token:${d}@github.com/${t}/${i}.git`;try{e(`git clone ${y} "${w}"`,{stdio:"pipe"});let m=`https://github.com/${t}/${i}.git`;P(e,w,m,d,"github_clone");let h=u()==="win32",R;return h?R=e(`dir "${w}"`,{encoding:"utf-8",shell:"cmd.exe"}):R=e(`ls -la "${w}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:w,message:`Cloned ${t}/${i} to ${w}`,contents:R.split(`
58
+ - Use github_get_file to read individual files via API`,resolve(){let d=fe();if(!d)return{command:null,args:[],env:{},description:this.description};let o={};for(let i of this.envKeys)process.env[i]&&(o[i]=process.env[i]);return{type:"stdio",command:"node",args:[d,"../dist/github.js","githubSkill"],env:o,description:this.description,alwaysLoad:!0}},async handleToolCall(d,o){try{switch(d){case"github_search_issues":{let i=o.query;if(!i)return JSON.stringify({error:"query is required"});let t=await y(`/search/issues?q=${encodeURIComponent(i)}&per_page=${o.limit||20}`),r=(t.items||[]).map(e=>({number:e.number,title:e.title,state:e.state,repo:e.repository_url?.split("/").slice(-2).join("/"),url:e.html_url,user:e.user?.login,isPR:!!e.pull_request,labels:(e.labels||[]).map(s=>s.name),createdAt:e.created_at}));return JSON.stringify({total:t.total_count,items:r})}case"github_search_code":{let i=o.query;if(!i)return JSON.stringify({error:"query is required"});let t=o.repo?`+repo:${o.repo}`:"",r=o.language?`+language:${o.language}`:"",e=await y(`/search/code?q=${encodeURIComponent(i)}${t}${r}&per_page=${o.limit||15}`),s=(e.items||[]).map(n=>({name:n.name,path:n.path,repo:n.repository?.full_name,url:n.html_url,score:n.score}));return JSON.stringify({total:e.total_count,items:s})}case"github_get_pr":{let{owner:i,repo:t,number:r}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await y(`/repos/${i}/${t}/pulls/${r}`);return JSON.stringify({number:e.number,title:e.title,state:e.state,merged:e.merged,body:e.body?.slice(0,5e3),user:e.user?.login,branch:e.head?.ref,headSha:e.head?.sha,base:e.base?.ref,changedFiles:e.changed_files,additions:e.additions,deletions:e.deletions,createdAt:e.created_at,mergedAt:e.merged_at,url:e.html_url,labels:(e.labels||[]).map(s=>s.name)})}case"github_get_pr_diff":{let{owner:i,repo:t,number:r}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await y(`/repos/${i}/${t}/pulls/${r}`,{accept:"application/vnd.github.v3.diff",raw:!0}),s=e.length>15e3;return JSON.stringify({number:r,diff:s?e.slice(0,15e3):e,truncated:s,totalLength:e.length})}case"github_list_pr_files":{let{owner:i,repo:t,number:r}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await y(`/repos/${i}/${t}/pulls/${r}/files?per_page=100`);return JSON.stringify({total:e.length,files:e.map(s=>({filename:s.filename,status:s.status,additions:s.additions,deletions:s.deletions,patch:s.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:i,repo:t,number:r}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await y(`/repos/${i}/${t}/pulls/${r}/comments?per_page=50`),s=await y(`/repos/${i}/${t}/issues/${r}/comments?per_page=50`),n=[...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})),...s.map(a=>({type:"issue",user:a.user?.login,body:a.body?.slice(0,1e3),createdAt:a.created_at}))].sort((a,p)=>new Date(a.createdAt)-new Date(p.createdAt));return JSON.stringify({total:n.length,comments:n})}case"github_get_review_thread":{let{owner:i,repo:t,number:r,commentId:e}=o||{};if(!i||!t||!r||!e)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let s=await y(`/repos/${i}/${t}/pulls/comments/${e}`),n=s.in_reply_to_id||s.id,a=[];try{a=await y(`/repos/${i}/${t}/pulls/${r}/comments?per_page=100`)}catch{a=[s]}(!Array.isArray(a)||a.length===0)&&(a=[s]);let p=a.filter(b=>b.id===n||b.in_reply_to_id===n).sort((b,u)=>new Date(b.created_at)-new Date(u.created_at)),l=p.length?p:[s],c=l.find(b=>b.id===n)||l[0];return JSON.stringify({rootCommentId:n,path:c.path,line:c.line??c.original_line??null,side:c.side||"RIGHT",diffHunk:typeof c.diff_hunk=="string"?c.diff_hunk.slice(0,3e3):null,commitId:c.commit_id||c.original_commit_id||null,notes:l.map(b=>({id:b.id,user:b.user?.login,body:(b.body||"").slice(0,4e3),createdAt:b.created_at,isRoot:b.id===n,url:b.html_url}))})}case"github_reply_review_thread":{let{owner:i,repo:t,number:r,commentId:e,body:s}=o||{};if(!i||!t||!r||!e||!s)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let n=await y(`/repos/${i}/${t}/pulls/${r}/comments/${e}/replies`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:n.id,url:n.html_url,inReplyTo:n.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:i,repo:t,number:r,body:e}=o||{};if(!i||!t||!r||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await y(`/repos/${i}/${t}/issues/${r}/comments`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_create_review":{let{owner:i,repo:t,number:r,body:e,event:s,comments:n}=o||{};if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let a=(s||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(a))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${s})`});let p=Array.isArray(n)?n.filter(m=>m&&m.path&&m.body&&(m.line!=null||m.position!=null)).map(m=>{let h={path:m.path,body:String(m.body)};return m.line!=null?(h.line=Number(m.line),h.side=m.side==="LEFT"?"LEFT":"RIGHT"):h.position=Number(m.position),h}):[];if(a!=="APPROVE"&&!e&&p.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l=new Set,c=null;try{for(let m=1;m<=20;m+=1){let h=await y(`/repos/${i}/${t}/pulls/${r}/comments?per_page=100&page=${m}`);if(!Array.isArray(h)||h.length===0)break;for(let R of h){let A=q(R.body);A&&l.add(A)}if(h.length<100)break}for(let m=1;m<=20&&c==null;m+=1){let h=await y(`/repos/${i}/${t}/issues/${r}/comments?per_page=100&page=${m}`);if(!Array.isArray(h)||h.length===0)break;for(let R of h)if(G(R.body)){c=R.id;break}if(h.length<100)break}}catch{}let b=!1,u=!1;if(e){let m=`${String(e)}${k}`;try{c!=null?(await y(`/repos/${i}/${t}/issues/comments/${c}`,{method:"PATCH",body:{body:m}}),b=!0):await y(`/repos/${i}/${t}/issues/${r}/comments`,{method:"POST",body:{body:m}}),u=!0}catch{}}let{toPost:f,skipped:_}=E(p,l),g=f.map(({_fp:m,...h})=>h),S=null;if(g.length>0||a==="APPROVE"||a==="REQUEST_CHANGES"){let m={event:a};g.length>0&&(m.comments=g),g.length===0&&a==="REQUEST_CHANGES"&&(m.body="Changes requested \u2014 see the review summary comment."),S=await y(`/repos/${i}/${t}/pulls/${r}/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:u,summaryUpdated:b,commentsPosted:g.length,inlineSkipped:_||void 0,url:S?S.html_url:void 0})}case"github_list_commits":{let{owner:i,repo:t,branch:r,path:e,limit:s,since:n,until:a,page:p}=o;if(!i||!t)return JSON.stringify({error:"owner and repo are required"});let l=Math.min(Number(s)||20,100),c=`/repos/${i}/${t}/commits?per_page=${l}&page=${Number(p)||1}`;r&&(c+=`&sha=${encodeURIComponent(r)}`),e&&(c+=`&path=${encodeURIComponent(e)}`),n&&(c+=`&since=${encodeURIComponent(n)}`),a&&(c+=`&until=${encodeURIComponent(a)}`);let b=await y(c);return JSON.stringify({total:b.length,page:Number(p)||1,hasMore:b.length>=l,commits:b.map(u=>({sha:u.sha?.slice(0,8),fullSha:u.sha,message:u.commit?.message?.slice(0,300),author:u.commit?.author?.name,authorEmail:u.commit?.author?.email,date:u.commit?.author?.date,url:u.html_url}))})}case"github_get_commit":{let{owner:i,repo:t,sha:r,includePrs:e}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and sha are required"});let s=await y(`/repos/${i}/${t}/commits/${r}`),n;if(e)try{let a=await y(`/repos/${i}/${t}/commits/${r}/pulls`);n=(Array.isArray(a)?a:[]).map(p=>({number:p.number,title:p.title,state:p.state,merged:!!p.merged_at,webUrl:p.html_url}))}catch{n=[]}return JSON.stringify({sha:s.sha?.slice(0,8),message:s.commit?.message,author:s.commit?.author?.name,date:s.commit?.author?.date,stats:s.stats,files:(s.files||[]).map(a=>({filename:a.filename,status:a.status,additions:a.additions,deletions:a.deletions,patch:a.patch?.slice(0,3e3)})),...n?{pullRequests:n}:{}})}case"github_get_file":{let{owner:i,repo:t,path:r,ref:e}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and path are required"});let s=`/repos/${i}/${t}/contents/${encodeURIComponent(r)}`;e&&(s+=`?ref=${encodeURIComponent(e)}`);let n=await y(s);if(n.type!=="file")return Array.isArray(n)?JSON.stringify({type:"directory",path:r,entries:n.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${n.type}`});let a=Buffer.from(n.content||"","base64").toString("utf-8"),p=a.length>2e4;return JSON.stringify({path:n.path,size:n.size,sha:n.sha?.slice(0,8),content:p?a.slice(0,2e4):a,truncated:p})}case"github_get_user":try{let i=await y("/installation/repositories?per_page=1");if(i.repositories&&i.repositories.length>0){let t=i.repositories[0],r=t.owner.login,e=t.owner.type,s=e==="Organization"?`/orgs/${r}`:`/users/${r}`,n=await y(s);return JSON.stringify({login:n.login,name:n.name||n.login,avatar:n.avatar_url,bio:n.bio||n.description,type:e,isOrg:e==="Organization",publicRepos:n.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(i){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${i.message})`})}case"github_list_orgs":try{let t=(await y("/installation/repositories?per_page=100")).repositories||[],r=new Map;for(let s of t)s.owner.type==="Organization"&&(r.has(s.owner.login)||r.set(s.owner.login,{login:s.owner.login,description:null,url:s.owner.url}));let e=Array.from(r.values());return JSON.stringify({count:e.length,orgs:e,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(i){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${i.message}`})}case"github_clone":{let f=function(m){let h=m.replace(/^~(?=$|\/|\\)/,u);return n(h)},{owner:i,repo:t,destination:r}=o;if(!i||!t)return JSON.stringify({error:"owner and repo are required"});let{execSync:e}=await import("child_process"),{join:s,resolve:n}=await import("path"),{existsSync:a,mkdirSync:p}=await import("fs"),{homedir:l,platform:c}=await import("os"),{token:b}=await Y("github"),u=l(),_=r?f(r):s(u,"zibby-repos"),g=s(_,t);if(p(_,{recursive:!0}),a(g))return JSON.stringify({error:`Directory ${g} already exists. Remove it first or use a different destination.`,existingPath:g});let S=`https://x-access-token:${b}@github.com/${i}/${t}.git`;try{e(`git clone ${S} "${g}"`,{stdio:"pipe"});let m=`https://github.com/${i}/${t}.git`;I(e,g,m,b,"github_clone");let h=c()==="win32",R;return h?R=e(`dir "${g}"`,{encoding:"utf-8",shell:"cmd.exe"}):R=e(`ls -la "${g}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:g,message:`Cloned ${i}/${t} to ${g}`,contents:R.split(`
59
59
  `).slice(0,30).join(`
60
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(m){let R=String(m.message||m).split(d).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${R}`})}}case"github_search_repos":{let{query:t,limit:i}=n;if(!t)return JSON.stringify({error:"query is required"});let r=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(r);if(e.error)return JSON.stringify(e);let s=t.toLowerCase(),a=e.repos.filter(o=>o.name.toLowerCase().includes(s)||o.fullName.toLowerCase().includes(s)||o.description&&o.description.toLowerCase().includes(s));return JSON.stringify({query:t,count:a.length,repos:a.slice(0,i||20)})}case"github_list_repos":{let{owner:t,type:i,sort:r,direction:e,limit:s,query:a}=n,o=100,p=s||200,c=[],u=h=>({name:h.name,fullName:h.full_name,private:h.private,description:h.description,language:h.language,defaultBranch:h.default_branch,updatedAt:h.updated_at,stars:h.stargazers_count,url:h.html_url,fullPath:h.full_name,webUrl:h.html_url,visibility:h.visibility||(h.private?"private":"public")}),d=h=>{if(!a)return!0;let R=String(a).toLowerCase();return h.name&&h.name.toLowerCase().includes(R)||h.fullName&&h.fullName.toLowerCase().includes(R)||h.description&&h.description.toLowerCase().includes(R)};if(!t){let h=1,R=!0;for(;R&&c.length<p;){let I=`/installation/repositories?per_page=${o}&page=${h}`,C=(await f(I)).repositories||[];if(C.length===0)break;c=c.concat(C),R=C.length===o,h++}let A=c.map(u).filter(d),j=A.slice(0,p),Z=A.length>j.length,H=j.filter(I=>I.private).length,B=j.filter(I=>!I.private).length;return JSON.stringify({count:j.length,repos:j,truncated:Z,privateCount:H,publicCount:B,message:`Found ${H} private and ${B} public repos`})}let b=await f(`/orgs/${t}`).then(()=>!0).catch(()=>!1),_=1,g=!0;for(;g&&c.length<p;){let h;b?h=`/orgs/${t}/repos?per_page=${o}&page=${_}&type=${i||"all"}&sort=${r||"updated"}&direction=${e||"desc"}`:h=`/users/${t}/repos?per_page=${o}&page=${_}&type=${i||"all"}&sort=${r||"updated"}&direction=${e||"desc"}`;let R=await f(h),A=Array.isArray(R)?R:[];if(A.length===0)break;c=c.concat(A),g=A.length===o,_++}let w=c.map(u).filter(d),y=w.slice(0,p),m=w.length>y.length;return JSON.stringify({count:y.length,repos:y,truncated:m})}case"github_create_pr":{let{owner:t,repo:i,head:r,title:e}=n||{};if(!t||!i||!r||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let s=n.base;if(!s)try{s=(await f(`/repos/${t}/${i}`)).default_branch||"main"}catch{s="main"}let a={title:String(e),head:String(r),base:String(s),body:n.body?String(n.body):"",draft:!!n.draft};try{let o=await f(`/repos/${t}/${i}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.html_url,number:o.number,branch:r,base:s,repo:`${t}/${i}`,provider:"github",draft:!!o.draft,state:o.state})}catch(o){let p=String(o.message||o);if(/GitHub API 422/.test(p))return JSON.stringify({success:!1,branch:r,base:s,repo:`${t}/${i}`,provider:"github",skippedReason:p});throw o}}case"github_merge_pr":{let{owner:t,repo:i,number:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=n.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(e))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${e})`});let s={merge_method:e};n.commitTitle&&(s.commit_title=String(n.commitTitle)),n.commitMessage&&(s.commit_message=String(n.commitMessage));try{let a=await f(`/repos/${t}/${i}/pulls/${r}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:r,provider:"github"})}catch(a){let o=String(a.message||a);if(/GitHub API (405|409|404)/.test(o))return JSON.stringify({success:!1,number:r,provider:"github",skippedReason:o});throw a}}case"github_create_issue":{let{owner:t,repo:i,title:r,body:e}=n;if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and title are required"});let s=await f(`/repos/${t}/${i}/issues`,{method:"POST",body:{title:r,body:e||""}});return JSON.stringify({number:s.number,url:s.html_url,title:s.title})}case"github_list_issues":{let{owner:t,repo:i,state:r,labels:e,since:s,assignee:a,sort:o,direction:p,limit:c}=n||{};if(!t||!i)return JSON.stringify({error:"owner and repo are required"});let u=new URLSearchParams;u.set("state",r||"open"),u.set("per_page",String(c||30)),u.set("sort",o||"updated"),u.set("direction",p||"desc"),e&&u.set("labels",Array.isArray(e)?e.join(","):e),s&&u.set("since",s),a&&u.set("assignee",a);let d=await f(`/repos/${t}/${i}/issues?${u.toString()}`),b=(Array.isArray(d)?d:[]).filter(_=>!_.pull_request).map(_=>({number:_.number,title:_.title,state:_.state,labels:(_.labels||[]).map(g=>typeof g=="string"?g:g.name),assignee:_.assignee?.login||null,assignees:(_.assignees||[]).map(g=>g.login),user:_.user?.login,comments:_.comments,url:_.html_url,createdAt:_.created_at,updatedAt:_.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"github_get_issue":{let{owner:t,repo:i,number:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await f(`/repos/${t}/${i}/issues/${r}`);return e.pull_request?JSON.stringify({error:`#${r} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(s=>typeof s=="string"?s:s.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(s=>s.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:t,repo:i,number:r,limit:e}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s=await f(`/repos/${t}/${i}/issues/${r}/comments?per_page=${e||100}`),a=(Array.isArray(s)?s:[]).map(o=>({id:o.id,user:o.user?.login,body:o.body||"",createdAt:o.created_at,updatedAt:o.updated_at,url:o.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:t,repo:i,number:r,body:e}=n||{};if(!t||!i||!r||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await f(`/repos/${t}/${i}/issues/${r}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_close_issue":{let{owner:t,repo:i,number:r,stateReason:e}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s={state:"closed"};e&&(s.state_reason=e);let a=await f(`/repos/${t}/${i}/issues/${r}`,{method:"PATCH",body:s});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:t,repo:i,number:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await f(`/repos/${t}/${i}/issues/${r}`,{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:i,number:r,labels:e,mode:s}=n||{};if(!t||!i||!r)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(e)?e:e?[e]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let o=s||"add";if(o==="set"){let c=await f(`/repos/${t}/${i}/issues/${r}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:c.number,labels:(c.labels||[]).map(u=>typeof u=="string"?u:u.name)})}if(o==="remove"){for(let u of a)await f(`/repos/${t}/${i}/issues/${r}/labels/${encodeURIComponent(u)}`,{method:"DELETE"});let c=await f(`/repos/${t}/${i}/issues/${r}`);return JSON.stringify({ok:!0,number:c.number,labels:(c.labels||[]).map(u=>typeof u=="string"?u:u.name)})}let p=await f(`/repos/${t}/${i}/issues/${r}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:r,labels:(Array.isArray(p)?p:[]).map(c=>typeof c=="string"?c:c.name)})}default:return JSON.stringify({error:`Unknown tool: ${l}`})}}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"]}}]};import{existsSync as fe}from"fs";import{fileURLToPath as _e}from"url";import{dirname as we,resolve as Re}from"path";function Se(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let l=we(_e(import.meta.url)),n=Re(l,"..","bin","mcp-skill.mjs");return fe(n)?n:null}function Oe(){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 Ae(){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 S(l,n={}){let t=/^https?:\/\//.test(l)?l:`${Oe()}${l}`,i={Accept:"application/json","User-Agent":"Zibby-App",...Ae(),...n.body?{"Content-Type":"application/json"}:{}},r=await fetch(t,{method:n.method||"GET",headers:i,body:n.body?JSON.stringify(n.body):void 0});if(!r.ok){let e=await r.text().catch(()=>"");throw new Error(`GitLab API ${r.status}: ${e.slice(0,300)}`)}return n.raw?r.text():r.json()}function Q(){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 $e(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function O(l){let n=String(l);return/^\d+$/.test(n)?n:encodeURIComponent(n)}var M={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:L.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
60
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(m){let R=String(m.message||m).split(b).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${R}`})}}case"github_search_repos":{let{query:i,limit:t}=o;if(!i)return JSON.stringify({error:"query is required"});let r=await this.handleToolCall("github_list_repos",{limit:200},{}),e=JSON.parse(r);if(e.error)return JSON.stringify(e);let s=i.toLowerCase(),n=e.repos.filter(a=>a.name.toLowerCase().includes(s)||a.fullName.toLowerCase().includes(s)||a.description&&a.description.toLowerCase().includes(s));return JSON.stringify({query:i,count:n.length,repos:n.slice(0,t||20)})}case"github_list_repos":{let{owner:i,type:t,sort:r,direction:e,limit:s,query:n}=o,a=100,p=s||200,l=[],c=h=>({name:h.name,fullName:h.full_name,private:h.private,description:h.description,language:h.language,defaultBranch:h.default_branch,updatedAt:h.updated_at,stars:h.stargazers_count,url:h.html_url,fullPath:h.full_name,webUrl:h.html_url,visibility:h.visibility||(h.private?"private":"public")}),b=h=>{if(!n)return!0;let R=String(n).toLowerCase();return h.name&&h.name.toLowerCase().includes(R)||h.fullName&&h.fullName.toLowerCase().includes(R)||h.description&&h.description.toLowerCase().includes(R)};if(!i){let h=1,R=!0;for(;R&&l.length<p;){let P=`/installation/repositories?per_page=${a}&page=${h}`,M=(await y(P)).repositories||[];if(M.length===0)break;l=l.concat(M),R=M.length===a,h++}let A=l.map(c).filter(b),$=A.slice(0,p),X=A.length>$.length,H=$.filter(P=>P.private).length,B=$.filter(P=>!P.private).length;return JSON.stringify({count:$.length,repos:$,truncated:X,privateCount:H,publicCount:B,message:`Found ${H} private and ${B} public repos`})}let u=await y(`/orgs/${i}`).then(()=>!0).catch(()=>!1),f=1,_=!0;for(;_&&l.length<p;){let h;u?h=`/orgs/${i}/repos?per_page=${a}&page=${f}&type=${t||"all"}&sort=${r||"updated"}&direction=${e||"desc"}`:h=`/users/${i}/repos?per_page=${a}&page=${f}&type=${t||"all"}&sort=${r||"updated"}&direction=${e||"desc"}`;let R=await y(h),A=Array.isArray(R)?R:[];if(A.length===0)break;l=l.concat(A),_=A.length===a,f++}let g=l.map(c).filter(b),S=g.slice(0,p),m=g.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:m})}case"github_create_pr":{let{owner:i,repo:t,head:r,title:e}=o||{};if(!i||!t||!r||!e)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let s=o.base;if(!s)try{s=(await y(`/repos/${i}/${t}`)).default_branch||"main"}catch{s="main"}let n={title:String(e),head:String(r),base:String(s),body:o.body?String(o.body):"",draft:!!o.draft};try{let a=await y(`/repos/${i}/${t}/pulls`,{method:"POST",body:n});return JSON.stringify({success:!0,pr_url:a.html_url,number:a.number,branch:r,base:s,repo:`${i}/${t}`,provider:"github",draft:!!a.draft,state:a.state})}catch(a){let p=String(a.message||a);if(/GitHub API 422/.test(p))return JSON.stringify({success:!1,branch:r,base:s,repo:`${i}/${t}`,provider:"github",skippedReason:p});throw a}}case"github_merge_pr":{let{owner:i,repo:t,number:r}=o||{};if(!i||!t||!r)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 s={merge_method:e};o.commitTitle&&(s.commit_title=String(o.commitTitle)),o.commitMessage&&(s.commit_message=String(o.commitMessage));try{let n=await y(`/repos/${i}/${t}/pulls/${r}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:n.sha,number:r,provider:"github"})}catch(n){let a=String(n.message||n);if(/GitHub API (405|409|404)/.test(a))return JSON.stringify({success:!1,number:r,provider:"github",skippedReason:a});throw n}}case"github_create_issue":{let{owner:i,repo:t,title:r,body:e}=o;if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and title are required"});let s=await y(`/repos/${i}/${t}/issues`,{method:"POST",body:{title:r,body:e||""}});return JSON.stringify({number:s.number,url:s.html_url,title:s.title})}case"github_list_issues":{let{owner:i,repo:t,state:r,labels:e,since:s,assignee:n,sort:a,direction:p,limit:l}=o||{};if(!i||!t)return JSON.stringify({error:"owner and repo are required"});let c=new URLSearchParams;c.set("state",r||"open"),c.set("per_page",String(l||30)),c.set("sort",a||"updated"),c.set("direction",p||"desc"),e&&c.set("labels",Array.isArray(e)?e.join(","):e),s&&c.set("since",s),n&&c.set("assignee",n);let b=await y(`/repos/${i}/${t}/issues?${c.toString()}`),u=(Array.isArray(b)?b:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(_=>typeof _=="string"?_:_.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(_=>_.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:u.length,issues:u})}case"github_get_issue":{let{owner:i,repo:t,number:r}=o||{};if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await y(`/repos/${i}/${t}/issues/${r}`);return e.pull_request?JSON.stringify({error:`#${r} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:e.number,title:e.title,body:e.body||"",state:e.state,stateReason:e.state_reason||null,labels:(e.labels||[]).map(s=>typeof s=="string"?s:s.name),assignee:e.assignee?.login||null,assignees:(e.assignees||[]).map(s=>s.login),user:e.user?.login,milestone:e.milestone?.title||null,comments:e.comments,url:e.html_url,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at})}case"github_get_issue_comments":{let{owner:i,repo:t,number:r,limit:e}=o||{};if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s=await y(`/repos/${i}/${t}/issues/${r}/comments?per_page=${e||100}`),n=(Array.isArray(s)?s:[]).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:n.length,comments:n})}case"github_add_issue_comment":{let{owner:i,repo:t,number:r,body:e}=o||{};if(!i||!t||!r||!e)return JSON.stringify({error:"owner, repo, number, and body are required"});let s=await y(`/repos/${i}/${t}/issues/${r}/comments`,{method:"POST",body:{body:e}});return JSON.stringify({ok:!0,id:s.id,url:s.html_url})}case"github_close_issue":{let{owner:i,repo:t,number:r,stateReason:e}=o||{};if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let s={state:"closed"};e&&(s.state_reason=e);let n=await y(`/repos/${i}/${t}/issues/${r}`,{method:"PATCH",body:s});return JSON.stringify({ok:!0,number:n.number,state:n.state,stateReason:n.state_reason||null,url:n.html_url})}case"github_reopen_issue":{let{owner:i,repo:t,number:r}=o||{};if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let e=await y(`/repos/${i}/${t}/issues/${r}`,{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:i,repo:t,number:r,labels:e,mode:s}=o||{};if(!i||!t||!r)return JSON.stringify({error:"owner, repo, and number are required"});let n=Array.isArray(e)?e:e?[e]:[];if(!n.length)return JSON.stringify({error:"labels (string or array) is required"});let a=s||"add";if(a==="set"){let l=await y(`/repos/${i}/${t}/issues/${r}`,{method:"PATCH",body:{labels:n}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(c=>typeof c=="string"?c:c.name)})}if(a==="remove"){for(let c of n)await y(`/repos/${i}/${t}/issues/${r}/labels/${encodeURIComponent(c)}`,{method:"DELETE"});let l=await y(`/repos/${i}/${t}/issues/${r}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(c=>typeof c=="string"?c:c.name)})}let p=await y(`/repos/${i}/${t}/issues/${r}/labels`,{method:"POST",body:{labels:n}});return JSON.stringify({ok:!0,number:r,labels:(Array.isArray(p)?p:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${d}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as _e}from"fs";import{fileURLToPath as we}from"url";import{dirname as Re,resolve as Se}from"path";function Oe(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let d=Re(we(import.meta.url)),o=Se(d,"..","bin","mcp-skill.mjs");return _e(o)?o:null}function Ae(){let d=process.env.GITLAB_API_URL;if(d)return d.replace(/\/+$/,"");let o=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(o)?o:`${o}/api/v4`}function $e(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let d=process.env.GITLAB_TOKEN;if(!d)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":d}}async function w(d,o={}){let i=/^https?:\/\//.test(d)?d:`${Ae()}${d}`,t={Accept:"application/json","User-Agent":"Zibby-App",...$e(),...o.body?{"Content-Type":"application/json"}:{}},r=await fetch(i,{method:o.method||"GET",headers:t,body:o.body?JSON.stringify(o.body):void 0});if(!r.ok){let e=await r.text().catch(()=>"");throw new Error(`GitLab API ${r.status}: ${e.slice(0,300)}`)}return o.raw?r.text():r.json()}function Q(){let d=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(d?d.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function ve(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function O(d){let o=String(d);return/^\d+$/.test(o)?o:encodeURIComponent(o)}function je(){let d=process.env.GITLAB_ALLOWED_REPOS;if(typeof d!="string"||!d.trim())return null;let o=new Set(d.split(",").map(i=>i.trim().replace(/^\/+|\/+$/g,"").toLowerCase()).filter(Boolean));return o.size?o:null}function V(d,o){if(!d)return!0;let i=String(o||"").trim().replace(/^\/+|\/+$/g,"").toLowerCase();return i!==""&&d.has(i)}function Ne(d){if(!d||typeof d!="object")return null;for(let o of["projectPath","projectId","project","repo","repoPath"]){let i=d[o];if(i!=null&&String(i).trim()!=="")return String(i).trim()}return null}async function Pe(d){if(!/^\d+$/.test(d))return d;try{let o=await w(`/projects/${O(d)}`);return o&&o.path_with_namespace||null}catch{return null}}var C={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:T.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
61
61
  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:
62
62
 
63
63
  ### Discovery
@@ -83,9 +83,9 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
83
83
 
84
84
  ### Notes
85
85
  - 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.
86
- - 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=Se();if(!l)return{command:null,args:[],env:{},description:this.description};let n={};for(let t of this.envKeys)process.env[t]&&(n[t]=process.env[t]);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:t,projectId:i,destination:r,branch:e}=n||{},s=t&&String(t).trim();if(!s&&i!=null&&(/^\d+$/.test(String(i))?s=(await S(`/projects/${O(i)}`))?.path_with_namespace:s=String(i).trim()),!s)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=$e();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:c}=await import("path"),{existsSync:u,mkdirSync:d}=await import("fs"),b=r?c(r):c(process.cwd(),".zibby","repos"),_=s.split("/").filter(Boolean).pop(),g=p(b,_);if(d(b,{recursive:!0}),u(g))return JSON.stringify({success:!0,path:g,message:`Already cloned at ${g}`,alreadyCloned:!0});let w=Q().replace(/^https?:\/\//,""),y=Q().startsWith("http://")?"http":"https",m=`${y}://oauth2:${a}@${w}/${s}.git`,h=e?`--branch "${String(e).replace(/"/g,"")}" `:"";try{o(`git clone --depth 1 ${h}${m} "${g}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let R=`${y}://${w}/${s}.git`;P(o,g,R,a,"gitlab_clone");let A=o(`ls -la "${g}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:g,message:`Cloned ${s} to ${g}`,contents:A.split(`
86
+ - 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 d=Oe();if(!d)return{command:null,args:[],env:{},description:this.description};let o={};for(let i of this.envKeys)process.env[i]&&(o[i]=process.env[i]);return{type:"stdio",command:"node",args:[d,"../dist/gitlab.js","gitlabSkill"],env:o,description:this.description,alwaysLoad:!0}},async handleToolCall(d,o){try{let i=je();if(i){let t=Ne(o);if(t){let r=await Pe(t);if(!V(i,r))return JSON.stringify({error:`Repository "${r||t}" is not available to this project. This project's agents may only use: ${[...i].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...i]})}}switch(d){case"gitlab_clone":{let{projectPath:t,projectId:r,destination:e,branch:s}=o||{},n=t&&String(t).trim();if(!n&&r!=null&&(/^\d+$/.test(String(r))?n=(await w(`/projects/${O(r)}`))?.path_with_namespace:n=String(r).trim()),!n)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=ve();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:p}=await import("child_process"),{join:l,resolve:c}=await import("path"),{existsSync:b,mkdirSync:u}=await import("fs"),f=e?c(e):c(process.cwd(),".zibby","repos"),_=n.split("/").filter(Boolean).pop(),g=l(f,_);if(u(f,{recursive:!0}),b(g))return JSON.stringify({success:!0,path:g,message:`Already cloned at ${g}`,alreadyCloned:!0});let S=Q().replace(/^https?:\/\//,""),m=Q().startsWith("http://")?"http":"https",h=`${m}://oauth2:${a}@${S}/${n}.git`,R=s?`--branch "${String(s).replace(/"/g,"")}" `:"";try{p(`git clone --depth 1 ${R}${h} "${g}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let A=`${m}://${S}/${n}.git`;I(p,g,A,a,"gitlab_clone");let $=p(`ls -la "${g}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:g,message:`Cloned ${n} to ${g}`,contents:$.split(`
87
87
  `).slice(0,30).join(`
88
- `)})}catch(R){let A=String(R.message||R).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${A}`})}}case"gitlab_create_mr":{let t=n?.project??n?.projectId,i=n?.source_branch??n?.sourceBranch,{title:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let e=O(t),s=n?.target_branch??n?.targetBranch;if(!s)try{s=(await S(`/projects/${e}`)).default_branch||"main"}catch{s="main"}let a={source_branch:String(i),target_branch:String(s),title:String(r),description:n?.description?String(n.description):""};try{let o=await S(`/projects/${e}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:o.web_url,number:o.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),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(t),provider:"gitlab",skippedReason:p});throw o}}case"gitlab_accept_mr":{let t=n?.project??n?.projectId,{iid:i}=n||{};if(!t||!i)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let r=O(t),e={};n.squash!=null&&(e.squash=!!n.squash),n.mergeCommitMessage&&(e.merge_commit_message=String(n.mergeCommitMessage)),n.mergeWhenPipelineSucceeds!=null&&(e.merge_when_pipeline_succeeds=!!n.mergeWhenPipelineSucceeds);try{let s=await S(`/projects/${r}/merge_requests/${i}/merge`,{method:"PUT",body:e});return JSON.stringify({success:!0,merged:!0,sha:s.merge_commit_sha??s.sha??null,iid:s.iid??i,project:String(t),provider:"gitlab",state:s.state})}catch(s){let a=String(s.message||s);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:i,project:String(t),provider:"gitlab",skippedReason:a});throw s}}case"gitlab_get_mr":{let{projectId:t,iid:i}=n||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await S(`/projects/${O(t)}/merge_requests/${i}`);return JSON.stringify({iid:r.iid,projectId:r.project_id,title:r.title,description:(r.description||"").slice(0,5e3),state:r.state,author:r.author?.username,sourceBranch:r.source_branch,targetBranch:r.target_branch,draft:r.draft??r.work_in_progress??!1,mergeStatus:r.merge_status,changesCount:r.changes_count,labels:Array.isArray(r.labels)?r.labels:[],webUrl:r.web_url,createdAt:r.created_at,updatedAt:r.updated_at,mergedAt:r.merged_at,diffRefs:r.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:t,iid:i}=n||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await S(`/projects/${O(t)}/merge_requests/${i}/changes`),e=Array.isArray(r.changes)?r.changes:[];return JSON.stringify({iid:r.iid,total:e.length,diffRefs:r.diff_refs||null,files:e.map(s=>({oldPath:s.old_path,newPath:s.new_path,newFile:!!s.new_file,deletedFile:!!s.deleted_file,renamedFile:!!s.renamed_file,diff:typeof s.diff=="string"?s.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:t,since:i,until:r,refName:e,page:s,perPage:a,withStats:o}=n||{};if(!t)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(s)||1)),i&&p.set("since",i),r&&p.set("until",r),e&&p.set("ref_name",e),o!==!1&&p.set("with_stats","true");let c=await S(`/projects/${O(t)}/repository/commits?${p.toString()}`),u=(Array.isArray(c)?c:[]).map(d=>({id:d.id,shortId:d.short_id,title:d.title,authorName:d.author_name,authorEmail:d.author_email,authoredDate:d.authored_date,committedDate:d.committed_date,parentIds:Array.isArray(d.parent_ids)?d.parent_ids:[],stats:d.stats||null}));return JSON.stringify({page:Number(s)||1,count:u.length,hasMore:u.length>=Math.min(Number(a)||50,100),commits:u})}case"gitlab_get_commit":{let{projectId:t,sha:i,includeDiff:r,includeMrs:e}=n||{};if(!t||!i)return JSON.stringify({error:"projectId and sha are required"});let s=await S(`/projects/${O(t)}/repository/commits/${encodeURIComponent(i)}`),a;if(e)try{let p=await S(`/projects/${O(t)}/repository/commits/${encodeURIComponent(i)}/merge_requests`);a=(Array.isArray(p)?p:[]).map(c=>({iid:c.iid,title:c.title,state:c.state,webUrl:c.web_url}))}catch{a=[]}let o;if(r!==!1){let p=await S(`/projects/${O(t)}/repository/commits/${encodeURIComponent(i)}/diff`);o=(Array.isArray(p)?p:[]).map(c=>({oldPath:c.old_path,newPath:c.new_path,newFile:!!c.new_file,deletedFile:!!c.deleted_file,renamedFile:!!c.renamed_file,diff:typeof c.diff=="string"?c.diff.slice(0,3e3):""}))}return JSON.stringify({id:s.id,shortId:s.short_id,title:s.title,message:typeof s.message=="string"?s.message.slice(0,2e3):"",authorName:s.author_name,authorEmail:s.author_email,authoredDate:s.authored_date,committedDate:s.committed_date,parentIds:Array.isArray(s.parent_ids)?s.parent_ids:[],stats:s.stats||null,webUrl:s.web_url,...o?{filesChanged:o.length,files:o}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:i,targetBranch:r,sourceBranch:e,authorUsername:s,labels:a,search:o,sort:p,orderBy:c,limit:u}=n||{};if(!t)return JSON.stringify({error:"projectId is required"});let d=new URLSearchParams;d.set("state",i||"opened"),d.set("per_page",String(u||20)),d.set("order_by",c||"updated_at"),d.set("sort",p||"desc"),r&&d.set("target_branch",r),e&&d.set("source_branch",e),s&&d.set("author_username",s),a&&d.set("labels",Array.isArray(a)?a.join(","):a),o&&d.set("search",o);let b=await S(`/projects/${O(t)}/merge_requests?${d.toString()}`),_=(Array.isArray(b)?b:[]).map(g=>({iid:g.iid,title:g.title,state:g.state,author:g.author?.username,sourceBranch:g.source_branch,targetBranch:g.target_branch,draft:g.draft??g.work_in_progress??!1,labels:Array.isArray(g.labels)?g.labels:[],webUrl:g.web_url,createdAt:g.created_at,updatedAt:g.updated_at}));return JSON.stringify({count:_.length,mergeRequests:_})}case"gitlab_list_mr_notes":{let{projectId:t,iid:i,limit:r}=n||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let e=await S(`/projects/${O(t)}/merge_requests/${i}/notes?per_page=${r||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(e)?e.length:0,notes:(Array.isArray(e)?e:[]).map(s=>({id:s.id,author:s.author?.username,body:(s.body||"").slice(0,1e3),system:!!s.system,createdAt:s.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:i,body:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let e=await S(`/projects/${O(t)}/merge_requests/${i}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:e.id,createdAt:e.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:i,path:r,oldPath:e,newLine:s,oldLine:a,body:o}=n||{};if(!t||!i||!r||!o)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(s==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let p=O(t),c=n.diffRefs||null;if(c||(c=(await S(`/projects/${p}/merge_requests/${i}`)).diff_refs||null),!c||!c.head_sha)return JSON.stringify({error:"could not resolve diff_refs for this MR \u2014 cannot anchor an inline comment. Use gitlab_post_mr_note instead."});let u={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:r,old_path:e||r};s!=null&&(u.new_line=Number(s)),a!=null&&(u.old_line=Number(a));try{let d=await S(`/projects/${p}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(o),position:u}});return JSON.stringify({ok:!0,discussionId:d.id})}catch(d){return JSON.stringify({ok:!1,error:`inline anchor rejected (${d.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:t,iid:i,body:r,comments:e}=n||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let s=O(t),a=Array.isArray(e)?e.filter(y=>y&&y.path&&y.body&&(y.newLine!=null||y.oldLine!=null)):[];if(!r&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let o=n.diffRefs||null;a.length>0&&!o&&(o=(await S(`/projects/${s}/merge_requests/${i}`)).diff_refs||null);let p=new Set,c=null;try{for(let y=1;y<=20;y+=1){let m=await S(`/projects/${s}/merge_requests/${i}/discussions?per_page=100&page=${y}`);if(!Array.isArray(m)||m.length===0)break;for(let h of m)for(let R of h.notes||[]){let A=q(R.body);A&&p.add(A),c==null&&G(R.body)&&(c=R.id)}if(m.length<100)break}}catch{}let u=!1,d=!1;if(r){let y=`${String(r)}${k}`;try{c!=null?(await S(`/projects/${s}/merge_requests/${i}/notes/${c}`,{method:"PUT",body:{body:y}}),d=!0):await S(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:y}}),u=!0}catch{await S(`/projects/${s}/merge_requests/${i}/notes`,{method:"POST",body:{body:y}}),u=!0}}let{toPost:b,skipped:_}=E(a,p),g=0,w=[];if(b.length>0&&o)for(let y of b){let m={base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha,position_type:"text",new_path:y.path,old_path:y.oldPath||y.path};y.newLine!=null&&(m.new_line=Number(y.newLine)),y.oldLine!=null&&(m.old_line=Number(y.oldLine));try{await S(`/projects/${s}/merge_requests/${i}/discussions`,{method:"POST",body:{body:String(y.body),position:m}}),g+=1}catch(h){w.push(`${y.path}:${y.newLine??y.oldLine} \u2014 ${h.message}`)}}else b.length>0&&!o&&w.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:u,summaryUpdated:d,inlinePosted:g,inlineSkipped:_||void 0,inlineErrors:w.length?w:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:i,discussionId:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let e=await S(`/projects/${O(t)}/merge_requests/${i}/discussions/${encodeURIComponent(r)}`),s=Array.isArray(e.notes)?e.notes:[],a=s.find(p=>p.position)||null,o=a?a.position:null;return JSON.stringify({discussionId:e.id,individualNote:!!e.individual_note,path:o&&(o.new_path||o.old_path)||null,newLine:o?o.new_line??null:null,oldLine:o?o.old_line??null:null,diffRefs:o?{base_sha:o.base_sha,start_sha:o.start_sha,head_sha:o.head_sha}:null,notes:s.map(p=>({id:p.id,author:p.author?.username,body:(p.body||"").slice(0,4e3),system:!!p.system,createdAt:p.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:i,discussionId:r,body:e}=n||{};if(!t||!i||!r||!e)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let s=await S(`/projects/${O(t)}/merge_requests/${i}/discussions/${encodeURIComponent(r)}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_list_projects":{let{query:t,limit:i}=n||{},r=Math.min(Number(i)>0?Number(i):50,200),e=new URLSearchParams;e.set("membership","true"),e.set("simple","true"),e.set("order_by","last_activity_at"),e.set("sort","desc"),e.set("per_page",String(Math.min(r+1,100))),t&&e.set("search",String(t));let s=await S(`/projects?${e.toString()}`),a=Array.isArray(s)?s:[],o=a.length>r,p=a.slice(0,r).map(c=>({fullPath:c.path_with_namespace,name:c.name,webUrl:c.web_url,defaultBranch:c.default_branch||null,visibility:c.visibility||null}));return JSON.stringify({count:p.length,truncated:o,projects:p})}case"gitlab_list_issues":{let{projectId:t,state:i,labels:r,assigneeUsername:e,authorUsername:s,updatedAfter:a,search:o,sort:p,orderBy:c,limit:u}=n||{};if(!t)return JSON.stringify({error:"projectId is required"});let d=new URLSearchParams;d.set("state",i||"opened"),d.set("per_page",String(u||30)),d.set("order_by",c||"updated_at"),d.set("sort",p||"desc"),r&&d.set("labels",Array.isArray(r)?r.join(","):r),e&&d.set("assignee_username",e),s&&d.set("author_username",s),a&&d.set("updated_after",a),o&&d.set("search",o);let b=await S(`/projects/${O(t)}/issues?${d.toString()}`),_=(Array.isArray(b)?b:[]).map(g=>({iid:g.iid,title:g.title,state:g.state,labels:Array.isArray(g.labels)?g.labels:[],author:g.author?.username,assignees:(g.assignees||[]).map(w=>w.username),userNotesCount:g.user_notes_count,webUrl:g.web_url,createdAt:g.created_at,updatedAt:g.updated_at}));return JSON.stringify({count:_.length,issues:_})}case"gitlab_get_issue":{let{projectId:t,iid:i}=n||{};if(!t||!i)return JSON.stringify({error:"projectId and iid are required"});let r=await S(`/projects/${O(t)}/issues/${i}`);return JSON.stringify({iid:r.iid,projectId:r.project_id,title:r.title,description:(r.description||"").slice(0,5e3),state:r.state,labels:Array.isArray(r.labels)?r.labels:[],author:r.author?.username,assignees:(r.assignees||[]).map(e=>e.username),milestone:r.milestone?.title||null,webUrl:r.web_url,createdAt:r.created_at,updatedAt:r.updated_at,closedAt:r.closed_at})}case"gitlab_add_issue_comment":{let{projectId:t,iid:i,body:r}=n||{};if(!t||!i||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let e=await S(`/projects/${O(t)}/issues/${i}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:e.id,createdAt:e.created_at})}default:return JSON.stringify({error:`Unknown tool: ${l}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};function V(l){let n=(l||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return n?{provider:"github",owner:n[1],repo:n[2]}:(n=(l||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),n?{provider:"gitlab",owner:n[1],repo:n[2]}:null)}var Xe={...N,id:"git-write",envKeys:[...N.envKeys||[],...U.envKeys||[],...M.envKeys||[]].filter((l,n,t)=>t.indexOf(l)===n),promptFragment:`${N.promptFragment}
88
+ `)})}catch(A){let $=String(A.message||A).split(a).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${$}`})}}case"gitlab_create_mr":{let t=o?.project??o?.projectId,r=o?.source_branch??o?.sourceBranch,{title:e}=o||{};if(!t||!r||!e)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let s=O(t),n=o?.target_branch??o?.targetBranch;if(!n)try{n=(await w(`/projects/${s}`)).default_branch||"main"}catch{n="main"}let a={source_branch:String(r),target_branch:String(n),title:String(e),description:o?.description?String(o.description):""};try{let p=await w(`/projects/${s}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:p.web_url,number:p.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",state:p.state})}catch(p){let l=String(p.message||p);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:a.source_branch,targetBranch:a.target_branch,project:String(t),provider:"gitlab",skippedReason:l});throw p}}case"gitlab_accept_mr":{let t=o?.project??o?.projectId,{iid:r}=o||{};if(!t||!r)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let e=O(t),s={};o.squash!=null&&(s.squash=!!o.squash),o.mergeCommitMessage&&(s.merge_commit_message=String(o.mergeCommitMessage)),o.mergeWhenPipelineSucceeds!=null&&(s.merge_when_pipeline_succeeds=!!o.mergeWhenPipelineSucceeds);try{let n=await w(`/projects/${e}/merge_requests/${r}/merge`,{method:"PUT",body:s});return JSON.stringify({success:!0,merged:!0,sha:n.merge_commit_sha??n.sha??null,iid:n.iid??r,project:String(t),provider:"gitlab",state:n.state})}catch(n){let a=String(n.message||n);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:r,project:String(t),provider:"gitlab",skippedReason:a});throw n}}case"gitlab_get_mr":{let{projectId:t,iid:r}=o||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let e=await w(`/projects/${O(t)}/merge_requests/${r}`);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:t,iid:r}=o||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let e=await w(`/projects/${O(t)}/merge_requests/${r}/changes`),s=Array.isArray(e.changes)?e.changes:[];return JSON.stringify({iid:e.iid,total:s.length,diffRefs:e.diff_refs||null,files:s.map(n=>({oldPath:n.old_path,newPath:n.new_path,newFile:!!n.new_file,deletedFile:!!n.deleted_file,renamedFile:!!n.renamed_file,diff:typeof n.diff=="string"?n.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:t,since:r,until:e,refName:s,page:n,perPage:a,withStats:p}=o||{};if(!t)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(a)||50,100))),l.set("page",String(Number(n)||1)),r&&l.set("since",r),e&&l.set("until",e),s&&l.set("ref_name",s),p!==!1&&l.set("with_stats","true");let c=await w(`/projects/${O(t)}/repository/commits?${l.toString()}`),b=(Array.isArray(c)?c:[]).map(u=>({id:u.id,shortId:u.short_id,title:u.title,authorName:u.author_name,authorEmail:u.author_email,authoredDate:u.authored_date,committedDate:u.committed_date,parentIds:Array.isArray(u.parent_ids)?u.parent_ids:[],stats:u.stats||null}));return JSON.stringify({page:Number(n)||1,count:b.length,hasMore:b.length>=Math.min(Number(a)||50,100),commits:b})}case"gitlab_get_commit":{let{projectId:t,sha:r,includeDiff:e,includeMrs:s}=o||{};if(!t||!r)return JSON.stringify({error:"projectId and sha are required"});let n=await w(`/projects/${O(t)}/repository/commits/${encodeURIComponent(r)}`),a;if(s)try{let l=await w(`/projects/${O(t)}/repository/commits/${encodeURIComponent(r)}/merge_requests`);a=(Array.isArray(l)?l:[]).map(c=>({iid:c.iid,title:c.title,state:c.state,webUrl:c.web_url}))}catch{a=[]}let p;if(e!==!1){let l=await w(`/projects/${O(t)}/repository/commits/${encodeURIComponent(r)}/diff`);p=(Array.isArray(l)?l:[]).map(c=>({oldPath:c.old_path,newPath:c.new_path,newFile:!!c.new_file,deletedFile:!!c.deleted_file,renamedFile:!!c.renamed_file,diff:typeof c.diff=="string"?c.diff.slice(0,3e3):""}))}return JSON.stringify({id:n.id,shortId:n.short_id,title:n.title,message:typeof n.message=="string"?n.message.slice(0,2e3):"",authorName:n.author_name,authorEmail:n.author_email,authoredDate:n.authored_date,committedDate:n.committed_date,parentIds:Array.isArray(n.parent_ids)?n.parent_ids:[],stats:n.stats||null,webUrl:n.web_url,...p?{filesChanged:p.length,files:p}:{},...a?{mergeRequests:a}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:r,targetBranch:e,sourceBranch:s,authorUsername:n,labels:a,search:p,sort:l,orderBy:c,limit:b}=o||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",r||"opened"),u.set("per_page",String(b||20)),u.set("order_by",c||"updated_at"),u.set("sort",l||"desc"),e&&u.set("target_branch",e),s&&u.set("source_branch",s),n&&u.set("author_username",n),a&&u.set("labels",Array.isArray(a)?a.join(","):a),p&&u.set("search",p);let f=await w(`/projects/${O(t)}/merge_requests?${u.toString()}`),_=(Array.isArray(f)?f:[]).map(g=>({iid:g.iid,title:g.title,state:g.state,author:g.author?.username,sourceBranch:g.source_branch,targetBranch:g.target_branch,draft:g.draft??g.work_in_progress??!1,labels:Array.isArray(g.labels)?g.labels:[],webUrl:g.web_url,createdAt:g.created_at,updatedAt:g.updated_at}));return JSON.stringify({count:_.length,mergeRequests:_})}case"gitlab_list_mr_notes":{let{projectId:t,iid:r,limit:e}=o||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let s=await w(`/projects/${O(t)}/merge_requests/${r}/notes?per_page=${e||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(s)?s.length:0,notes:(Array.isArray(s)?s:[]).map(n=>({id:n.id,author:n.author?.username,body:(n.body||"").slice(0,1e3),system:!!n.system,createdAt:n.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:r,body:e}=o||{};if(!t||!r||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await w(`/projects/${O(t)}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:r,path:e,oldPath:s,newLine:n,oldLine:a,body:p}=o||{};if(!t||!r||!e||!p)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(n==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let l=O(t),c=o.diffRefs||null;if(c||(c=(await w(`/projects/${l}/merge_requests/${r}`)).diff_refs||null),!c||!c.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 b={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:e,old_path:s||e};n!=null&&(b.new_line=Number(n)),a!=null&&(b.old_line=Number(a));try{let u=await w(`/projects/${l}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(p),position:b}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.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:t,iid:r,body:e,comments:s}=o||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let n=O(t),a=Array.isArray(s)?s.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 p=o.diffRefs||null;a.length>0&&!p&&(p=(await w(`/projects/${n}/merge_requests/${r}`)).diff_refs||null);let l=new Set,c=null;try{for(let m=1;m<=20;m+=1){let h=await w(`/projects/${n}/merge_requests/${r}/discussions?per_page=100&page=${m}`);if(!Array.isArray(h)||h.length===0)break;for(let R of h)for(let A of R.notes||[]){let $=q(A.body);$&&l.add($),c==null&&G(A.body)&&(c=A.id)}if(h.length<100)break}}catch{}let b=!1,u=!1;if(e){let m=`${String(e)}${k}`;try{c!=null?(await w(`/projects/${n}/merge_requests/${r}/notes/${c}`,{method:"PUT",body:{body:m}}),u=!0):await w(`/projects/${n}/merge_requests/${r}/notes`,{method:"POST",body:{body:m}}),b=!0}catch{await w(`/projects/${n}/merge_requests/${r}/notes`,{method:"POST",body:{body:m}}),b=!0}}let{toPost:f,skipped:_}=E(a,l),g=0,S=[];if(f.length>0&&p)for(let m of f){let h={base_sha:p.base_sha,start_sha:p.start_sha,head_sha:p.head_sha,position_type:"text",new_path:m.path,old_path:m.oldPath||m.path};m.newLine!=null&&(h.new_line=Number(m.newLine)),m.oldLine!=null&&(h.old_line=Number(m.oldLine));try{await w(`/projects/${n}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(m.body),position:h}}),g+=1}catch(R){S.push(`${m.path}:${m.newLine??m.oldLine} \u2014 ${R.message}`)}}else f.length>0&&!p&&S.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:b,summaryUpdated:u,inlinePosted:g,inlineSkipped:_||void 0,inlineErrors:S.length?S:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:r,discussionId:e}=o||{};if(!t||!r||!e)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let s=await w(`/projects/${O(t)}/merge_requests/${r}/discussions/${encodeURIComponent(e)}`),n=Array.isArray(s.notes)?s.notes:[],a=n.find(l=>l.position)||null,p=a?a.position:null;return JSON.stringify({discussionId:s.id,individualNote:!!s.individual_note,path:p&&(p.new_path||p.old_path)||null,newLine:p?p.new_line??null:null,oldLine:p?p.old_line??null:null,diffRefs:p?{base_sha:p.base_sha,start_sha:p.start_sha,head_sha:p.head_sha}:null,notes:n.map(l=>({id:l.id,author:l.author?.username,body:(l.body||"").slice(0,4e3),system:!!l.system,createdAt:l.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:r,discussionId:e,body:s}=o||{};if(!t||!r||!e||!s)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let n=await w(`/projects/${O(t)}/merge_requests/${r}/discussions/${encodeURIComponent(e)}/notes`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}case"gitlab_list_projects":{let{query:t,limit:r}=o||{},e=Math.min(Number(r)>0?Number(r):50,200),s=new URLSearchParams;s.set("membership","true"),s.set("simple","true"),s.set("order_by","last_activity_at"),s.set("sort","desc"),s.set("per_page",String(Math.min(e+1,100))),t&&s.set("search",String(t));let n=await w(`/projects?${s.toString()}`),a=Array.isArray(n)?n:[];i&&(a=a.filter(c=>V(i,c&&c.path_with_namespace)));let p=a.length>e,l=a.slice(0,e).map(c=>({fullPath:c.path_with_namespace,name:c.name,webUrl:c.web_url,defaultBranch:c.default_branch||null,visibility:c.visibility||null}));return JSON.stringify({count:l.length,truncated:p,projects:l})}case"gitlab_list_issues":{let{projectId:t,state:r,labels:e,assigneeUsername:s,authorUsername:n,updatedAfter:a,search:p,sort:l,orderBy:c,limit:b}=o||{};if(!t)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",r||"opened"),u.set("per_page",String(b||30)),u.set("order_by",c||"updated_at"),u.set("sort",l||"desc"),e&&u.set("labels",Array.isArray(e)?e.join(","):e),s&&u.set("assignee_username",s),n&&u.set("author_username",n),a&&u.set("updated_after",a),p&&u.set("search",p);let f=await w(`/projects/${O(t)}/issues?${u.toString()}`),_=(Array.isArray(f)?f:[]).map(g=>({iid:g.iid,title:g.title,state:g.state,labels:Array.isArray(g.labels)?g.labels:[],author:g.author?.username,assignees:(g.assignees||[]).map(S=>S.username),userNotesCount:g.user_notes_count,webUrl:g.web_url,createdAt:g.created_at,updatedAt:g.updated_at}));return JSON.stringify({count:_.length,issues:_})}case"gitlab_get_issue":{let{projectId:t,iid:r}=o||{};if(!t||!r)return JSON.stringify({error:"projectId and iid are required"});let e=await w(`/projects/${O(t)}/issues/${r}`);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(s=>s.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:t,iid:r,body:e}=o||{};if(!t||!r||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let s=await w(`/projects/${O(t)}/issues/${r}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}default:return JSON.stringify({error:`Unknown tool: ${d}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_commits",description:"List a project's repository commits (the commit HISTORY \u2014 not MRs), optionally bounded by since/until ISO dates and a ref/branch, with per-commit stats (additions/deletions). Paginated: keep calling with page+1 while hasMore is true. This is the ONLY correct way to enumerate commits in a date window \u2014 gitlab_clone is shallow (depth 1) and its git log shows just one commit.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},since:{type:"string",description:'Only commits after this ISO-8601 date/time (inclusive), e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:'Only commits before this ISO-8601 date/time, e.g. "2026-07-01T00:00:00Z"'},refName:{type:"string",description:"Branch/tag to list (defaults to the default branch)"},page:{type:"number",description:"Page number, 1-based (default 1)"},perPage:{type:"number",description:"Commits per page, max 100 (default 50)"},withStats:{type:"boolean",description:"Include per-commit additions/deletions stats (default true)"}},required:["projectId"]}},{name:"gitlab_get_commit",description:"Get ONE commit's full detail \u2014 message, author, timestamps, stats, and (by default) its per-file diffs (each capped at 3000 chars) \u2014 so you can judge the nature/complexity of the change. Use after gitlab_list_commits.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},sha:{type:"string",description:"The commit sha (full or short)"},includeDiff:{type:"boolean",description:"Include per-file diffs (default true; set false for metadata-only)"},includeMrs:{type:"boolean",description:"Also return the merge request(s) containing this commit ({iid,title,state,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["projectId","sha"]}},{name:"gitlab_list_mrs",description:"List a GitLab project's merge requests, filtered by state and other criteria. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","merged","locked","all"],description:"Filter by state (default: opened)"},targetBranch:{type:"string",description:"Filter by target branch"},sourceBranch:{type:"string",description:"Filter by source branch"},authorUsername:{type:"string",description:"Filter by author username"},labels:{type:"array",items:{type:"string"},description:"Only MRs carrying ALL of these labels"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at","title"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max MRs (default: 20)"}},required:["projectId"]}},{name:"gitlab_list_mr_notes",description:"List the discussion notes on a GitLab merge request (chronological).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},limit:{type:"number",description:"Max notes (default 50)"}},required:["projectId","iid"]}},{name:"gitlab_post_mr_note",description:"Post a general (non-inline) comment on a GitLab merge request. Use for a review summary or a top-level remark.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}},{name:"gitlab_post_mr_discussion",description:"Post an INLINE review comment anchored to a file + line in a GitLab merge request diff. Provide newLine (added/changed line) or oldLine (removed/context line). Pass diffRefs from gitlab_get_mr/gitlab_get_mr_changes, or omit to have the tool fetch them. If the line anchor is rejected, fall back to gitlab_post_mr_note.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr. Omit and the tool fetches them."}},required:["projectId","iid","path","body"]}},{name:"gitlab_create_mr_review",description:"Post a full review on a GitLab merge request in one call: a summary note plus optional inline comments anchored to file/line in the diff. Convenience wrapper over gitlab_post_mr_note + gitlab_post_mr_discussion.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},body:{type:"string",description:"The review summary (markdown). Posted as a top-level MR note."},diffRefs:{type:"object",description:"The MR diff_refs ({ base_sha, start_sha, head_sha }) from gitlab_get_mr \u2014 required to anchor inline comments. Omit and the tool fetches them."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line in a file.",items:{type:"object",properties:{path:{type:"string",description:"New file path as it appears in the diff"},oldPath:{type:"string",description:"Old file path (defaults to path)"},newLine:{type:"number",description:"Line number in the NEW version of the file (for added/changed lines)"},oldLine:{type:"number",description:"Line number in the OLD version (for removed/context lines)"},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","body"]}}},required:["projectId","iid"]}},{name:"gitlab_get_discussion",description:"Read a single GitLab merge-request DISCUSSION (thread) by its discussion id: all notes in order plus the diff position (file + line) it is anchored to. Use this to understand a human's reply to a previous review discussion before replying in-thread.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id (from the Note Hook payload or gitlab_list_mr_notes)"}},required:["projectId","iid","discussionId"]}},{name:"gitlab_reply_discussion",description:"Reply IN-THREAD to an existing GitLab merge-request discussion (a conversational reply appended to the SAME thread \u2014 NOT a fresh review). Use after gitlab_get_discussion to answer a human's reply to a review comment.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Merge request iid"},discussionId:{type:"string",description:"The discussion id to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["projectId","iid","discussionId","body"]}},{name:"gitlab_list_issues",description:"List a GitLab project's issues, filtered by state, labels, and an updatedAfter polling cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},state:{type:"string",enum:["opened","closed","all"],description:"Filter by state (default: opened)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},assigneeUsername:{type:"string",description:"Filter by assignee username"},authorUsername:{type:"string",description:"Filter by author username"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},search:{type:"string",description:"Search title and description"},orderBy:{type:"string",enum:["created_at","updated_at"],description:"Sort field (default: updated_at)"},sort:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30)"}},required:["projectId"]}},{name:"gitlab_get_issue",description:"Get a single GitLab issue with full detail (title, description, state, labels, assignees, web url).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid (the per-project issue number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_add_issue_comment",description:"Add a comment to a GitLab issue. Also the way to record an MR link on a ticket (post a markdown link).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"Project numeric id OR full path"},iid:{type:"number",description:"Issue iid"},body:{type:"string",description:"Comment body (markdown)"}},required:["projectId","iid","body"]}}]};function Z(d){let o=(d||"").match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);return o?{provider:"github",owner:o[1],repo:o[2]}:(o=(d||"").match(/gitlab\.com[/:](.+?)\/([^/]+?)(?:\.git)?$/),o?{provider:"gitlab",owner:o[1],repo:o[2]}:null)}var it={...N,id:"git-write",envKeys:[...N.envKeys||[],...U.envKeys||[],...C.envKeys||[]].filter((d,o,i)=>i.indexOf(d)===o),promptFragment:`${N.promptFragment}
89
89
 
90
90
  ## Opening a pull request / merge request (git_open_pr)
91
91
  After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
@@ -97,4 +97,4 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
97
97
  To MERGE an open PR/MR, use the provider-agnostic tool:
98
98
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
99
99
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
100
- Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(l,n,t){if(l!=="git_open_pr"&&l!=="git_merge_pr")return N.handleToolCall(l,n,t);try{let i=n||{},r=i.repoUrl||i.repo_url||i.url;if(!r)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(l==="git_merge_pr"){let c=i.number??i.iid??i.prNumber;if(c==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let u=V(r);return u?u.provider==="github"?U.handleToolCall("github_merge_pr",{owner:u.owner,repo:u.repo,number:c,mergeMethod:i.mergeMethod},t):M.handleToolCall("gitlab_accept_mr",{project:`${u.owner}/${u.repo}`,iid:c},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_merge_pr supports github.com and gitlab.com.`})}let e=i.head||i.source_branch||i.sourceBranch||i.branch,s=i.base||i.target_branch||i.targetBranch,{title:a,body:o}=i;if(!e||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let p=V(r);return p?p.provider==="github"?U.handleToolCall("github_create_pr",{owner:p.owner,repo:p.repo,head:e,base:s,title:a,body:o},t):M.handleToolCall("gitlab_create_mr",{project:`${p.owner}/${p.repo}`,source_branch:e,target_branch:s,title:a,description:o},t):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_open_pr supports github.com and gitlab.com.`})}catch(i){return JSON.stringify({error:i.message})}},tools:[...N.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};export{V as detectProvider,Xe as gitWriteSkill};
100
+ Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(d,o,i){if(d!=="git_open_pr"&&d!=="git_merge_pr")return N.handleToolCall(d,o,i);try{let t=o||{},r=t.repoUrl||t.repo_url||t.url;if(!r)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(d==="git_merge_pr"){let l=t.number??t.iid??t.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let c=Z(r);return c?c.provider==="github"?U.handleToolCall("github_merge_pr",{owner:c.owner,repo:c.repo,number:l,mergeMethod:t.mergeMethod},i):C.handleToolCall("gitlab_accept_mr",{project:`${c.owner}/${c.repo}`,iid:l},i):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_merge_pr supports github.com and gitlab.com.`})}let e=t.head||t.source_branch||t.sourceBranch||t.branch,s=t.base||t.target_branch||t.targetBranch,{title:n,body:a}=t;if(!e||!n)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let p=Z(r);return p?p.provider==="github"?U.handleToolCall("github_create_pr",{owner:p.owner,repo:p.repo,head:e,base:s,title:n,body:a},i):C.handleToolCall("gitlab_create_mr",{project:`${p.owner}/${p.repo}`,source_branch:e,target_branch:s,title:n,description:a},i):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${r}. git_open_pr supports github.com and gitlab.com.`})}catch(t){return JSON.stringify({error:t.message})}},tools:[...N.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};export{Z as detectProvider,it as gitWriteSkill};