@zibby/skills 2.0.24 → 2.0.26

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/gitlab.js CHANGED
@@ -1,10 +1,10 @@
1
- import{existsSync as ee}from"fs";import{AsyncLocalStorage as te}from"async_hooks";import{fileURLToPath as re}from"url";import{dirname as ie,resolve as ne}from"path";var v=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),ue=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark Chat",connectPath:"/integrations?provider=lark"},lark_docs:{id:"lark_docs",name:"Lark App",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});import{spawn as ge,execSync as fe}from"child_process";import{existsSync as be,mkdirSync as ye,readdirSync as we,statSync as Ie,readFileSync as Se}from"fs";import{resolve as Ae,join as Le,basename as Oe}from"path";function k(s,r,t,n,e="clone"){try{s(`git -C "${r}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(o){let i=String(o?.message||o);n&&(i=i.split(n).join("***")),console.error(`[${e}] WARNING: failed to strip token from .git/config: ${i}`)}}import F from"crypto";var $=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,P=/<!--\s*zbreview-summary\s*-->/i;function H(s){return String(s||"").replace($,"").replace(P,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function W(s,r){return F.createHash("sha256").update(`${String(s||"")}\0${H(r)}`).digest("hex").slice(0,12)}function z(s){return`
1
+ import{existsSync as _e}from"fs";import{AsyncLocalStorage as ye}from"async_hooks";import{fileURLToPath as we}from"url";import{dirname as Se,resolve as Ie}from"path";var D=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Ee=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark Chat",connectPath:"/integrations?provider=lark"},lark_docs:{id:"lark_docs",name:"Lark App",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});import{spawn as Ue,execSync as qe}from"child_process";import{existsSync as Be,mkdirSync as Je,readdirSync as De,statSync as Fe,readFileSync as Ke}from"fs";import{resolve as We,join as ze,basename as Ye}from"path";var se="REPO_ALLOWLIST",M="REPO_NOT_SELECTED",x=Object.freeze(["github","gitlab"]),oe=Object.freeze({github:"GitHub",gitlab:"GitLab"});function U(i){return String(i??"").trim().replace(/^\/+|\/+$/g,"").replace(/\.git$/i,"").replace(/\/+$/g,"").toLowerCase()}function T(i=process.env){let e=i?i[se]:void 0;if(e==null||String(e).trim()==="")return null;let t={github:new Set,gitlab:new Set,unreadable:!1},n;try{n=JSON.parse(String(e))}catch{return t.unreadable=!0,t}if(!n||typeof n!="object"||Array.isArray(n))return t.unreadable=!0,t;for(let r of x){let o=n[r];if(Array.isArray(o))for(let s of o){let l=U(s);l&&t[r].add(l)}}return t}function F(i=process.env){return T(i)!==null}function R(i,e,t){let n=oe[i]||i,r=t&&t[i]?[...t[i]].sort():[],o=String(e||"").trim()||"(unnamed repository)",s=r.length?`The ${n} repositories selected for this project are: ${r.join(", ")}.`:`This project has no ${n} repositories selected.`;return{error:`The ${n} repository "${o}" is not selected for this project, so this project's agents cannot use it. ${s} A project owner can change this in Project Settings \u2192 Repository access.`,code:M,provider:i,repo:o,allowedRepos:r,fix:r.length?"Work only with the selected repositories listed in allowedRepos. If the task needs this one, tell the person it has to be selected in Project Settings first. Do not retry the same repository under another spelling or id.":"Tell the person this project has no repositories selected, and that one has to be selected in Project Settings \u2192 Repository access before agents can use it. Do not retry."}}var j=class extends Error{constructor(e){super(e.error),this.name="RepoNotSelectedError",this.code=M,this.refusal=e}};function q(i){return!!(i&&i.code===M&&i.refusal)}function ae(i,e,t=process.env){let n=T(t);if(!n)return{allowed:!0};if(!x.includes(i))return{allowed:!0};let r=U(e);return r&&n[i].has(r)?{allowed:!0}:{allowed:!1,refusal:R(i,e,n)}}function K(i,e,t=process.env){let n=ae(i,e,t);if(!n.allowed)throw new j(n.refusal)}function H(i,e,t,n=process.env){if(!Array.isArray(e))return e;let r=T(n);return!r||!x.includes(i)?e:e.filter(o=>{let s=t(o);return s==null||s===""?!0:r[i].has(U(s))})}function N(i,e=process.env){let t=T(e);return t?t[i]?[...t[i]].sort():[]:null}async function ce(i){try{let e=await import("@zibby/agent-workflow");return typeof e.collectRepositoryRules!="function"||typeof e.renderRepositoryRules!="function"?"":e.renderRepositoryRules(e.collectRepositoryRules([{dir:i,declared:!0}]))||""}catch{return""}}async function k(i){let e=await ce(i);return e?{repositoryRules:e}:{}}function W(i,e,t,n,r="clone"){try{i(`git -C "${e}" remote set-url origin "${t}"`,{stdio:"pipe"})}catch(o){let s=String(o?.message||o);n&&(s=s.split(n).join("***")),console.error(`[${r}] WARNING: failed to strip token from .git/config: ${s}`)}}import le from"crypto";var z=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Y=/<!--\s*zbreview-summary\s*-->/i;function de(i){return String(i||"").replace(z,"").replace(Y,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function pe(i,e){return le.createHash("sha256").update(`${String(i||"")}\0${de(e)}`).digest("hex").slice(0,12)}function ue(i){return`
2
2
 
3
- <!-- zbfp:${s} -->`}var E=`
3
+ <!-- zbfp:${i} -->`}var V=`
4
4
 
5
- <!-- zbreview-summary -->`;function M(s){let r=$.exec(String(s||""));return r?r[1].toLowerCase():null}function G(s){return P.test(String(s||""))}function U(s,r){let t=new Set([...r||[]].map(o=>String(o).toLowerCase())),n=[],e=0;for(let o of Array.isArray(s)?s:[]){if(!o||!o.body)continue;let i=W(o.path,o.body);if(t.has(i)){e+=1;continue}t.add(i),n.push({...o,_fp:i,body:`${String(o.body)}${z(i)}`})}return{toPost:n,skipped:e}}var L={api:{knob:"SKILL_API_TIMEOUT_MS",fallback:3e4},transfer:{knob:"SKILL_TRANSFER_TIMEOUT_MS",fallback:12e4},job:{knob:"SKILL_JOB_TIMEOUT_MS",fallback:3e5}};function Y(s,r,t=process.env){let n=Number(t?.[s]);return Number.isFinite(n)&&n>0?Math.min(6e5,Math.max(1e3,Math.floor(n))):r}function V(s="api",r=process.env){let t=L[s]||L.api;return Y(t.knob,t.fallback,r)}function Z(s){return s?.name==="TimeoutError"||s?.name==="AbortError"}function Q(s){try{return new URL(String(s?.url??s)).host||"unknown host"}catch{return"unknown host"}}function X(s,r){if(!s)return r;let t=new AbortController,n=i=>{t.signal.aborted||t.abort(i)},e=()=>n(s.reason),o=()=>n(r.reason);return t.signal.addEventListener("abort",()=>{s.removeEventListener("abort",e),r.removeEventListener("abort",o)},{once:!0}),s.aborted?n(s.reason):r.aborted?n(r.reason):(s.addEventListener("abort",e,{once:!0}),r.addEventListener("abort",o,{once:!0})),t.signal}async function x(s,r={},t={}){let n=t.kind||"api",e=(L[n]||L.api).knob,o=t.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(t.timeoutMs))):V(n),i=r?.signal;if(i?.aborted)throw i.reason??new DOMException("This operation was aborted","AbortError");let d=AbortSignal.timeout(o),c=X(i,d);try{return await fetch(s,{...r,signal:c})}catch(l){throw d.aborted&&Z(l)?new Error(`${t.what||"request"} TIMED OUT after ${o}ms against ${Q(s)} (${e})`):l}}function se(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=ie(re(import.meta.url)),r=ne(s,"..","bin","mcp-skill.mjs");return ee(r)?r:null}function A(s){return String(s??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var O=null;function oe(s){let r;try{r=JSON.parse(s)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(r)||r.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let t=[],n=new Map;return r.forEach((e,o)=>{let i=e&&typeof e.host=="string"?e.host.trim().replace(/\/+$/,""):"",d=e&&typeof e.token=="string"?e.token.trim():"",c=e&&Array.isArray(e.repos)?e.repos:null;if(!i)throw new Error(`GITLAB_INSTANCES[${o}] is missing "host".`);if(!d)throw new Error(`GITLAB_INSTANCES[${o}] (${i}) is missing "token".`);if(!c||c.length===0)throw new Error(`GITLAB_INSTANCES[${o}] (${i}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let l=i.replace(/\/api\/v\d+$/,""),p=new Set;for(let g of c){let a=A(g);if(!a)continue;let f=n.get(a);if(f!==void 0&&f!==o)throw new Error(`GITLAB_INSTANCES claims "${a}" on more than one server (${t[f].webHost} and ${l}). A repo path must name exactly one server.`);n.set(a,o),p.add(a)}if(p.size===0)throw new Error(`GITLAB_INSTANCES[${o}] (${i}) declares no usable "repos".`);t.push({webHost:l,apiBase:/\/api\/v\d+$/.test(i)?i:`${l}/api/v4`,token:d,repos:p})}),t}function T(){let s=process.env.GITLAB_INSTANCES;if(typeof s!="string"||!s.trim())return null;if(O&&O.raw===s)return O.value;let r=oe(s);return O={raw:s,value:r},r}var R=new te,ae="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function N(){let s=R.getStore();if(s)return s;if(T())throw new Error(ae);return null}function q(){let s=N();if(s)return s.apiBase;let r=process.env.GITLAB_API_URL;if(r)return r.replace(/\/+$/,"");let t=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(t)?t:`${t}/api/v4`}function ce(){let s=N();if(s)return{"PRIVATE-TOKEN":s.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let r=process.env.GITLAB_TOKEN;if(!r)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":r}}async function m(s,r={}){let t=/^https?:\/\//.test(s)?s:`${q()}${s}`,n={Accept:"application/json","User-Agent":"Zibby-App",...ce(),...r.body?{"Content-Type":"application/json"}:{}},e=await x(t,{method:r.method||"GET",headers:n,body:r.body?JSON.stringify(r.body):void 0},{kind:"api",what:`GitLab ${r.method||"GET"} ${s}`});if(!e.ok){let o=await e.text().catch(()=>""),i=`GitLab API ${e.status} @ ${q()}`;throw new Error(`${i}: ${o.slice(0,300)}`)}return r.raw?e.text():e.json()}function C(){let s=N();if(s)return s.webHost;let r=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(r?r.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function de(){let s=N();return s?s.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function _(s){let r=String(s);return/^\d+$/.test(r)?r:encodeURIComponent(r)}function D(){let s=T();if(s){let n=new Set;for(let e of s)for(let o of e.repos)n.add(o);return n}let r=process.env.GITLAB_ALLOWED_REPOS;if(typeof r!="string"||!r.trim())return null;let t=new Set(r.split(",").map(A).filter(Boolean));return t.size?t:null}function K(s,r){if(!s)return!0;let t=A(r);return t!==""&&s.has(t)}function le(s){if(!s||typeof s!="object")return null;for(let r of["projectPath","projectId","project","repo","repoPath"]){let t=s[r];if(t!=null&&String(t).trim()!=="")return String(t).trim()}return null}async function B(s){if(!/^\d+$/.test(s))return s;try{let r=await m(`/projects/${_(s)}`);return r&&r.path_with_namespace||null}catch{return null}}async function pe(s,r){if(!r)return{path:await B(s),instance:null};if(!/^\d+$/.test(s)){let n=A(s);return{path:s,instance:r.find(e=>e.repos.has(n))||null}}let t=null;for(let n of r){let e=await R.run(n,()=>B(s));if(e&&(t===null&&(t=e),n.repos.has(A(e))))return{path:e,instance:n}}return{path:t,instance:null}}async function J(s,r){switch(s){case"gitlab_clone":{let{projectPath:t,projectId:n,destination:e,branch:o}=r||{},i=t&&String(t).trim();if(!i&&n!=null&&(/^\d+$/.test(String(n))?i=(await m(`/projects/${_(n)}`))?.path_with_namespace:i=String(n).trim()),!i)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let d=de();if(!d)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:l,resolve:p}=await import("path"),{existsSync:g,mkdirSync:a}=await import("fs"),f=e?p(e):p(process.cwd(),".zibby","repos"),b=i.split("/").filter(Boolean).pop(),u=l(f,b);if(a(f,{recursive:!0}),g(u))return JSON.stringify({success:!0,path:u,message:`Already cloned at ${u}`,alreadyCloned:!0});let w=C().replace(/^https?:\/\//,""),h=C().startsWith("http://")?"http":"https",y=`${h}://oauth2:${d}@${w}/${i}.git`,j=o?`--branch "${String(o).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${j}${y} "${u}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let I=`${h}://${w}/${i}.git`;k(c,u,I,d,"gitlab_clone");let S=c(`ls -la "${u}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:u,message:`Cloned ${i} to ${u}`,contents:S.split(`
5
+ <!-- zbreview-summary -->`;function Z(i){let e=z.exec(String(i||""));return e?e[1].toLowerCase():null}function Q(i){return Y.test(String(i||""))}function X(i,e){let t=new Set([...e||[]].map(o=>String(o).toLowerCase())),n=[],r=0;for(let o of Array.isArray(i)?i:[]){if(!o||!o.body)continue;let s=pe(o.path,o.body);if(t.has(s)){r+=1;continue}t.add(s),n.push({...o,_fp:s,body:`${String(o.body)}${ue(s)}`})}return{toPost:n,skipped:r}}var v={api:{knob:"SKILL_API_TIMEOUT_MS",fallback:3e4},transfer:{knob:"SKILL_TRANSFER_TIMEOUT_MS",fallback:12e4},job:{knob:"SKILL_JOB_TIMEOUT_MS",fallback:3e5}};function he(i,e,t=process.env){let n=Number(t?.[i]);return Number.isFinite(n)&&n>0?Math.min(6e5,Math.max(1e3,Math.floor(n))):e}function fe(i="api",e=process.env){let t=v[i]||v.api;return he(t.knob,t.fallback,e)}function me(i){return i?.name==="TimeoutError"||i?.name==="AbortError"}function ge(i){try{return new URL(String(i?.url??i)).host||"unknown host"}catch{return"unknown host"}}function be(i,e){if(!i)return e;let t=new AbortController,n=s=>{t.signal.aborted||t.abort(s)},r=()=>n(i.reason),o=()=>n(e.reason);return t.signal.addEventListener("abort",()=>{i.removeEventListener("abort",r),e.removeEventListener("abort",o)},{once:!0}),i.aborted?n(i.reason):e.aborted?n(e.reason):(i.addEventListener("abort",r,{once:!0}),e.addEventListener("abort",o,{once:!0})),t.signal}async function ee(i,e={},t={}){let n=t.kind||"api",r=(v[n]||v.api).knob,o=t.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(t.timeoutMs))):fe(n),s=e?.signal;if(s?.aborted)throw s.reason??new DOMException("This operation was aborted","AbortError");let l=AbortSignal.timeout(o),c=be(s,l);try{return await fetch(i,{...e,signal:c})}catch(d){throw l.aborted&&me(d)?new Error(`${t.what||"request"} TIMED OUT after ${o}ms against ${ge(i)} (${r})`):d}}function je(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let i=Se(we(import.meta.url)),e=Ie(i,"..","bin","mcp-skill.mjs");return _e(e)?e:null}function O(i){return String(i??"").trim().replace(/^\/+|\/+$/g,"").toLowerCase()}var E=null;function Ae(i){let e;try{e=JSON.parse(i)}catch{throw new Error("GITLAB_INSTANCES is set but is not valid JSON. Expected an array of { host, token, repos: [...] }.")}if(!Array.isArray(e)||e.length===0)throw new Error("GITLAB_INSTANCES must be a non-empty JSON array of { host, token, repos: [...] }.");let t=[],n=new Map;return e.forEach((r,o)=>{let s=r&&typeof r.host=="string"?r.host.trim().replace(/\/+$/,""):"",l=r&&typeof r.token=="string"?r.token.trim():"",c=r&&Array.isArray(r.repos)?r.repos:null;if(!s)throw new Error(`GITLAB_INSTANCES[${o}] is missing "host".`);if(!l)throw new Error(`GITLAB_INSTANCES[${o}] (${s}) is missing "token".`);if(!c||c.length===0)throw new Error(`GITLAB_INSTANCES[${o}] (${s}) declares no "repos" \u2014 an entry that routes nothing is a config error, not an empty selection.`);let d=s.replace(/\/api\/v\d+$/,""),u=new Set;for(let m of c){let a=O(m);if(!a)continue;let g=n.get(a);if(g!==void 0&&g!==o)throw new Error(`GITLAB_INSTANCES claims "${a}" on more than one server (${t[g].webHost} and ${d}). A repo path must name exactly one server.`);n.set(a,o),u.add(a)}if(u.size===0)throw new Error(`GITLAB_INSTANCES[${o}] (${s}) declares no usable "repos".`);t.push({webHost:d,apiBase:/\/api\/v\d+$/.test(s)?s:`${d}/api/v4`,token:l,repos:u})}),t}function P(){let i=process.env.GITLAB_INSTANCES;if(typeof i!="string"||!i.trim())return null;if(E&&E.raw===i)return E.value;let e=Ae(i);return E={raw:i,value:e},e}var $=new ye,Le="GitLab: this call was not routed to a connected server. With GITLAB_INSTANCES set, every call must name a project one of the declared servers owns.";function G(){let i=$.getStore();if(i)return i;if(P())throw new Error(Le);return null}function B(){let i=G();if(i)return i.apiBase;let e=process.env.GITLAB_API_URL;if(e)return e.replace(/\/+$/,"");let t=(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||"https://gitlab.com").trim().replace(/\/+$/,"");return/\/api\/v\d+$/.test(t)?t:`${t}/api/v4`}function Re(){let i=G();if(i)return{"PRIVATE-TOKEN":i.token};if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let e=process.env.GITLAB_TOKEN;if(!e)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":e}}async function f(i,e={}){if(!F())return A(i,e);let t=Oe(i);if(t.kind==="project"){let r=/^\d+$/.test(t.ident)?await Te(t.ident):t.ident;if(!r)throw new j(R("gitlab",t.ident,{gitlab:new Set(N("gitlab")||[])}));return K("gitlab",r),A(i,e)}if(t.kind==="list"){let r=await A(i,e);return Array.isArray(r)?H("gitlab",r,o=>o&&o.path_with_namespace):r}if(t.kind==="meta")return A(i,e);let n=R("gitlab",String(i).split("?")[0],{gitlab:new Set(N("gitlab")||[])});throw n.error="This GitLab request is not addressed to one of this project's selected repositories, so it is not allowed. Address the repository as /projects/<group%2Frepo>/\u2026 instead. "+n.error,new j(n)}function Oe(i){let e=String(i||"");if(/^https?:\/\//i.test(e))try{e=new URL(e).pathname}catch{return{kind:"other"}}e=e.split("?")[0].replace(/^\/api\/v\d+/,"");let t=e.match(/^\/projects\/([^/]+)/);if(t){let n=t[1];try{n=decodeURIComponent(n)}catch{}return{kind:"project",ident:n}}return/^\/projects\/?$/.test(e)||/^\/groups\/[^/]+\/projects\/?$/.test(e)?{kind:"list"}:/^\/(user|version|metadata)\/?$/.test(e)?{kind:"meta"}:{kind:"other"}}var C=new Map;async function Te(i){let e=`${B()}|${i}`;if(C.has(e))return C.get(e)??null;let t=null;try{let n=await A(`/projects/${i}`);t=n&&n.path_with_namespace||null}catch{t=null}return t&&C.set(e,t),t}async function A(i,e={}){let t=/^https?:\/\//.test(i)?i:`${B()}${i}`,n={Accept:"application/json","User-Agent":"Zibby-App",...Re(),...e.body?{"Content-Type":"application/json"}:{}},r=await ee(t,{method:e.method||"GET",headers:n,body:e.body?JSON.stringify(e.body):void 0},{kind:"api",what:`GitLab ${e.method||"GET"} ${i}`});if(!r.ok){let o=await r.text().catch(()=>""),s=`GitLab API ${r.status} @ ${B()}`;throw new Error(`${s}: ${o.slice(0,300)}`)}return e.raw?r.text():r.json()}function te(){let i=G();if(i)return i.webHost;let e=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(e?e.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Ne(){let i=G();return i?i.token:process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function b(i){let e=String(i);return/^\d+$/.test(e)?e:encodeURIComponent(e)}function ne(){let i=N("gitlab");if(i)return new Set(i);let e=P();if(e){let r=new Set;for(let o of e)for(let s of o.repos)r.add(s);return r}let t=process.env.GITLAB_ALLOWED_REPOS;if(typeof t!="string"||!t.trim())return null;let n=new Set(t.split(",").map(O).filter(Boolean));return n.size?n:null}function J(i,e){if(!i)return!0;let t=O(e);return t!==""&&i.has(t)}function ke(i){if(!i||typeof i!="object")return null;for(let e of["projectPath","projectId","project","repo","repoPath"]){let t=i[e];if(t!=null&&String(t).trim()!=="")return String(t).trim()}return null}async function re(i){if(!/^\d+$/.test(i))return i;try{let e=await A(`/projects/${b(i)}`);return e&&e.path_with_namespace||null}catch{return null}}async function ve(i,e){if(!e)return{path:await re(i),instance:null};if(!/^\d+$/.test(i)){let n=O(i);return{path:i,instance:e.find(r=>r.repos.has(n))||null}}let t=null;for(let n of e){let r=await $.run(n,()=>re(i));if(r&&(t===null&&(t=r),n.repos.has(O(r))))return{path:r,instance:n}}return{path:t,instance:null}}async function ie(i,e){switch(i){case"gitlab_clone":{let{projectPath:t,projectId:n,destination:r,branch:o}=e||{},s=t&&String(t).trim();if(!s&&n!=null&&(/^\d+$/.test(String(n))?s=(await f(`/projects/${b(n)}`))?.path_with_namespace:s=String(n).trim()),!s)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let l=Ne();if(!l)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:u}=await import("path"),{existsSync:m,mkdirSync:a}=await import("fs"),g=r?u(r):u(process.cwd(),".zibby","repos"),_=s.split("/").filter(Boolean).pop(),p=d(g,_);if(a(g,{recursive:!0}),m(p))return JSON.stringify({success:!0,path:p,message:`Already cloned at ${p}`,alreadyCloned:!0,...await k(p)});let w=te().replace(/^https?:\/\//,""),h=te().startsWith("http://")?"http":"https",y=`${h}://oauth2:${l}@${w}/${s}.git`,L=o?`--branch "${String(o).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${L}${y} "${p}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let S=`${h}://${w}/${s}.git`;W(c,p,S,l,"gitlab_clone");let I=c(`ls -la "${p}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:p,message:`Cloned ${s} to ${p}`,contents:I.split(`
6
6
  `).slice(0,30).join(`
7
- `)})}catch(I){let S=String(I.message||I).split(d).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"gitlab_create_mr":{let t=r?.project??r?.projectId,n=r?.source_branch??r?.sourceBranch,{title:e}=r||{};if(!t||!n||!e)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let o=_(t),i=r?.target_branch??r?.targetBranch;if(!i)try{i=(await m(`/projects/${o}`)).default_branch||"main"}catch{i="main"}let d={source_branch:String(n),target_branch:String(i),title:String(e),description:r?.description?String(r.description):""};try{let c=await m(`/projects/${o}/merge_requests`,{method:"POST",body:d});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:d.source_branch,targetBranch:d.target_branch,project:String(t),provider:"gitlab",state:c.state})}catch(c){let l=String(c.message||c);if(/GitLab API (409|400)/.test(l))return JSON.stringify({success:!1,branch:d.source_branch,targetBranch:d.target_branch,project:String(t),provider:"gitlab",skippedReason:l});throw c}}case"gitlab_accept_mr":{let t=r?.project??r?.projectId,{iid:n}=r||{};if(!t||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let e=_(t),o={};r.squash!=null&&(o.squash=!!r.squash),r.mergeCommitMessage&&(o.merge_commit_message=String(r.mergeCommitMessage)),r.mergeWhenPipelineSucceeds!=null&&(o.merge_when_pipeline_succeeds=!!r.mergeWhenPipelineSucceeds);try{let i=await m(`/projects/${e}/merge_requests/${n}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:i.merge_commit_sha??i.sha??null,iid:i.iid??n,project:String(t),provider:"gitlab",state:i.state})}catch(i){let d=String(i.message||i);if(/GitLab API (405|406|404)/.test(d))return JSON.stringify({success:!1,iid:n,project:String(t),provider:"gitlab",skippedReason:d});throw i}}case"gitlab_get_mr":{let{projectId:t,iid:n}=r||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let e=await m(`/projects/${_(t)}/merge_requests/${n}`);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:n}=r||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let e=await m(`/projects/${_(t)}/merge_requests/${n}/changes`),o=Array.isArray(e.changes)?e.changes:[];return JSON.stringify({iid:e.iid,total:o.length,diffRefs:e.diff_refs||null,files:o.map(i=>({oldPath:i.old_path,newPath:i.new_path,newFile:!!i.new_file,deletedFile:!!i.deleted_file,renamedFile:!!i.renamed_file,diff:typeof i.diff=="string"?i.diff.slice(0,3e3):""}))})}case"gitlab_list_commits":{let{projectId:t,since:n,until:e,refName:o,page:i,perPage:d,withStats:c}=r||{};if(!t)return JSON.stringify({error:"projectId is required"});let l=new URLSearchParams;l.set("per_page",String(Math.min(Number(d)||50,100))),l.set("page",String(Number(i)||1)),n&&l.set("since",n),e&&l.set("until",e),o&&l.set("ref_name",o),c!==!1&&l.set("with_stats","true");let p=await m(`/projects/${_(t)}/repository/commits?${l.toString()}`),g=(Array.isArray(p)?p:[]).map(a=>({id:a.id,shortId:a.short_id,title:a.title,authorName:a.author_name,authorEmail:a.author_email,authoredDate:a.authored_date,committedDate:a.committed_date,parentIds:Array.isArray(a.parent_ids)?a.parent_ids:[],stats:a.stats||null}));return JSON.stringify({page:Number(i)||1,count:g.length,hasMore:g.length>=Math.min(Number(d)||50,100),commits:g})}case"gitlab_get_commit":{let{projectId:t,sha:n,includeDiff:e,includeMrs:o}=r||{};if(!t||!n)return JSON.stringify({error:"projectId and sha are required"});let i=await m(`/projects/${_(t)}/repository/commits/${encodeURIComponent(n)}`),d;if(o)try{let l=await m(`/projects/${_(t)}/repository/commits/${encodeURIComponent(n)}/merge_requests`);d=(Array.isArray(l)?l:[]).map(p=>({iid:p.iid,title:p.title,state:p.state,webUrl:p.web_url}))}catch{d=[]}let c;if(e!==!1){let l=await m(`/projects/${_(t)}/repository/commits/${encodeURIComponent(n)}/diff`);c=(Array.isArray(l)?l:[]).map(p=>({oldPath:p.old_path,newPath:p.new_path,newFile:!!p.new_file,deletedFile:!!p.deleted_file,renamedFile:!!p.renamed_file,diff:typeof p.diff=="string"?p.diff.slice(0,3e3):""}))}return JSON.stringify({id:i.id,shortId:i.short_id,title:i.title,message:typeof i.message=="string"?i.message.slice(0,2e3):"",authorName:i.author_name,authorEmail:i.author_email,authoredDate:i.authored_date,committedDate:i.committed_date,parentIds:Array.isArray(i.parent_ids)?i.parent_ids:[],stats:i.stats||null,webUrl:i.web_url,...c?{filesChanged:c.length,files:c}:{},...d?{mergeRequests:d}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:n,targetBranch:e,sourceBranch:o,authorUsername:i,labels:d,search:c,sort:l,orderBy:p,limit:g}=r||{};if(!t)return JSON.stringify({error:"projectId is required"});let a=new URLSearchParams;a.set("state",n||"opened"),a.set("per_page",String(g||20)),a.set("order_by",p||"updated_at"),a.set("sort",l||"desc"),e&&a.set("target_branch",e),o&&a.set("source_branch",o),i&&a.set("author_username",i),d&&a.set("labels",Array.isArray(d)?d.join(","):d),c&&a.set("search",c);let f=await m(`/projects/${_(t)}/merge_requests?${a.toString()}`),b=(Array.isArray(f)?f:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,author:u.author?.username,sourceBranch:u.source_branch,targetBranch:u.target_branch,draft:u.draft??u.work_in_progress??!1,labels:Array.isArray(u.labels)?u.labels:[],webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:b.length,mergeRequests:b})}case"gitlab_list_mr_notes":{let{projectId:t,iid:n,limit:e}=r||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let o=await m(`/projects/${_(t)}/merge_requests/${n}/notes?per_page=${e||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(o)?o.length:0,notes:(Array.isArray(o)?o:[]).map(i=>({id:i.id,author:i.author?.username,body:(i.body||"").slice(0,1e3),system:!!i.system,createdAt:i.created_at}))})}case"gitlab_post_mr_note":{let{projectId:t,iid:n,body:e}=r||{};if(!t||!n||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let o=await m(`/projects/${_(t)}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:n,path:e,oldPath:o,newLine:i,oldLine:d,body:c}=r||{};if(!t||!n||!e||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(i==null&&d==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let l=_(t),p=r.diffRefs||null;if(p||(p=(await m(`/projects/${l}/merge_requests/${n}`)).diff_refs||null),!p||!p.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 g={base_sha:p.base_sha,start_sha:p.start_sha,head_sha:p.head_sha,position_type:"text",new_path:e,old_path:o||e};i!=null&&(g.new_line=Number(i)),d!=null&&(g.old_line=Number(d));try{let a=await m(`/projects/${l}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:g}});return JSON.stringify({ok:!0,discussionId:a.id})}catch(a){return JSON.stringify({ok:!1,error:`inline anchor rejected (${a.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:n,body:e,comments:o}=r||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let i=_(t),d=Array.isArray(o)?o.filter(h=>h&&h.path&&h.body&&(h.newLine!=null||h.oldLine!=null)):[];if(!e&&d.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=r.diffRefs||null;d.length>0&&!c&&(c=(await m(`/projects/${i}/merge_requests/${n}`)).diff_refs||null);let l=new Set,p=null;try{for(let h=1;h<=20;h+=1){let y=await m(`/projects/${i}/merge_requests/${n}/discussions?per_page=100&page=${h}`);if(!Array.isArray(y)||y.length===0)break;for(let j of y)for(let I of j.notes||[]){let S=M(I.body);S&&l.add(S),p==null&&G(I.body)&&(p=I.id)}if(y.length<100)break}}catch{}let g=!1,a=!1;if(e){let h=`${String(e)}${E}`;try{p!=null?(await m(`/projects/${i}/merge_requests/${n}/notes/${p}`,{method:"PUT",body:{body:h}}),a=!0):await m(`/projects/${i}/merge_requests/${n}/notes`,{method:"POST",body:{body:h}}),g=!0}catch{await m(`/projects/${i}/merge_requests/${n}/notes`,{method:"POST",body:{body:h}}),g=!0}}let{toPost:f,skipped:b}=U(d,l),u=0,w=[];if(f.length>0&&c)for(let h of f){let y={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:h.path,old_path:h.oldPath||h.path};h.newLine!=null&&(y.new_line=Number(h.newLine)),h.oldLine!=null&&(y.old_line=Number(h.oldLine));try{await m(`/projects/${i}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(h.body),position:y}}),u+=1}catch(j){w.push(`${h.path}:${h.newLine??h.oldLine} \u2014 ${j.message}`)}}else f.length>0&&!c&&w.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:g,summaryUpdated:a,inlinePosted:u,inlineSkipped:b||void 0,inlineErrors:w.length?w:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:n,discussionId:e}=r||{};if(!t||!n||!e)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let o=await m(`/projects/${_(t)}/merge_requests/${n}/discussions/${encodeURIComponent(e)}`),i=Array.isArray(o.notes)?o.notes:[],d=i.find(l=>l.position)||null,c=d?d.position:null;return JSON.stringify({discussionId:o.id,individualNote:!!o.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:i.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:n,discussionId:e,body:o}=r||{};if(!t||!n||!e||!o)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let i=await m(`/projects/${_(t)}/merge_requests/${n}/discussions/${encodeURIComponent(e)}/notes`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:i.id,createdAt:i.created_at})}case"gitlab_list_projects":{let{query:t,limit:n}=r||{},e=Math.min(Number(n)>0?Number(n):50,200),o=new URLSearchParams;o.set("membership","true"),o.set("simple","true"),o.set("order_by","last_activity_at"),o.set("sort","desc"),o.set("per_page",String(Math.min(e+1,100))),t&&o.set("search",String(t));let i=async()=>{let a=await m(`/projects?${o.toString()}`);return Array.isArray(a)?a:[]},d=T(),c=D(),l=[];for(let a of d||[null]){let f=a?await R.run(a,i):await i();for(let b of f)K(a?a.repos:c,b&&b.path_with_namespace)&&l.push({p:b,host:a?a.webHost:null})}let p=l.length>e,g=l.slice(0,e).map(({p:a,host:f})=>({fullPath:a.path_with_namespace,name:a.name,webUrl:a.web_url,defaultBranch:a.default_branch||null,visibility:a.visibility||null,...f?{host:f}:{}}));return JSON.stringify({count:g.length,truncated:p,projects:g})}case"gitlab_list_issues":{let{projectId:t,state:n,labels:e,assigneeUsername:o,authorUsername:i,updatedAfter:d,search:c,sort:l,orderBy:p,limit:g}=r||{};if(!t)return JSON.stringify({error:"projectId is required"});let a=new URLSearchParams;a.set("state",n||"opened"),a.set("per_page",String(g||30)),a.set("order_by",p||"updated_at"),a.set("sort",l||"desc"),e&&a.set("labels",Array.isArray(e)?e.join(","):e),o&&a.set("assignee_username",o),i&&a.set("author_username",i),d&&a.set("updated_after",d),c&&a.set("search",c);let f=await m(`/projects/${_(t)}/issues?${a.toString()}`),b=(Array.isArray(f)?f:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,labels:Array.isArray(u.labels)?u.labels:[],author:u.author?.username,assignees:(u.assignees||[]).map(w=>w.username),userNotesCount:u.user_notes_count,webUrl:u.web_url,createdAt:u.created_at,updatedAt:u.updated_at}));return JSON.stringify({count:b.length,issues:b})}case"gitlab_get_issue":{let{projectId:t,iid:n}=r||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let e=await m(`/projects/${_(t)}/issues/${n}`);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(o=>o.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:n,body:e}=r||{};if(!t||!n||!e)return JSON.stringify({error:"projectId, iid, and body are required"});let o=await m(`/projects/${_(t)}/issues/${n}/notes`,{method:"POST",body:{body:String(e)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}var qe={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:v.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
7
+ `),...await k(p)})}catch(S){let I=String(S.message||S).split(l).join("***").replace(/oauth2:[^@]*@/g,"oauth2:***@");return JSON.stringify({error:`Clone failed: ${I}`})}}case"gitlab_create_mr":{let t=e?.project??e?.projectId,n=e?.source_branch??e?.sourceBranch,{title:r}=e||{};if(!t||!n||!r)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let o=b(t),s=e?.target_branch??e?.targetBranch;if(!s)try{s=(await f(`/projects/${o}`)).default_branch||"main"}catch{s="main"}let l={source_branch:String(n),target_branch:String(s),title:String(r),description:e?.description?String(e.description):""};try{let c=await f(`/projects/${o}/merge_requests`,{method:"POST",body:l});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:l.source_branch,targetBranch:l.target_branch,project:String(t),provider:"gitlab",state:c.state})}catch(c){let d=String(c.message||c);if(/GitLab API (409|400)/.test(d))return JSON.stringify({success:!1,branch:l.source_branch,targetBranch:l.target_branch,project:String(t),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let t=e?.project??e?.projectId,{iid:n}=e||{};if(!t||!n)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let r=b(t),o={};e.squash!=null&&(o.squash=!!e.squash),e.mergeCommitMessage&&(o.merge_commit_message=String(e.mergeCommitMessage)),e.mergeWhenPipelineSucceeds!=null&&(o.merge_when_pipeline_succeeds=!!e.mergeWhenPipelineSucceeds);try{let s=await f(`/projects/${r}/merge_requests/${n}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:s.merge_commit_sha??s.sha??null,iid:s.iid??n,project:String(t),provider:"gitlab",state:s.state})}catch(s){let l=String(s.message||s);if(/GitLab API (405|406|404)/.test(l))return JSON.stringify({success:!1,iid:n,project:String(t),provider:"gitlab",skippedReason:l});throw s}}case"gitlab_get_mr":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let r=await f(`/projects/${b(t)}/merge_requests/${n}`);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:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let r=await f(`/projects/${b(t)}/merge_requests/${n}/changes`),o=Array.isArray(r.changes)?r.changes:[];return JSON.stringify({iid:r.iid,total:o.length,diffRefs:r.diff_refs||null,files:o.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:n,until:r,refName:o,page:s,perPage:l,withStats:c}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let d=new URLSearchParams;d.set("per_page",String(Math.min(Number(l)||50,100))),d.set("page",String(Number(s)||1)),n&&d.set("since",n),r&&d.set("until",r),o&&d.set("ref_name",o),c!==!1&&d.set("with_stats","true");let u=await f(`/projects/${b(t)}/repository/commits?${d.toString()}`),m=(Array.isArray(u)?u:[]).map(a=>({id:a.id,shortId:a.short_id,title:a.title,authorName:a.author_name,authorEmail:a.author_email,authoredDate:a.authored_date,committedDate:a.committed_date,parentIds:Array.isArray(a.parent_ids)?a.parent_ids:[],stats:a.stats||null}));return JSON.stringify({page:Number(s)||1,count:m.length,hasMore:m.length>=Math.min(Number(l)||50,100),commits:m})}case"gitlab_get_commit":{let{projectId:t,sha:n,includeDiff:r,includeMrs:o}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and sha are required"});let s=await f(`/projects/${b(t)}/repository/commits/${encodeURIComponent(n)}`),l;if(o)try{let d=await f(`/projects/${b(t)}/repository/commits/${encodeURIComponent(n)}/merge_requests`);l=(Array.isArray(d)?d:[]).map(u=>({iid:u.iid,title:u.title,state:u.state,webUrl:u.web_url}))}catch{l=[]}let c;if(r!==!1){let d=await f(`/projects/${b(t)}/repository/commits/${encodeURIComponent(n)}/diff`);c=(Array.isArray(d)?d:[]).map(u=>({oldPath:u.old_path,newPath:u.new_path,newFile:!!u.new_file,deletedFile:!!u.deleted_file,renamedFile:!!u.renamed_file,diff:typeof u.diff=="string"?u.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,...c?{filesChanged:c.length,files:c}:{},...l?{mergeRequests:l}:{}})}case"gitlab_list_mrs":{let{projectId:t,state:n,targetBranch:r,sourceBranch:o,authorUsername:s,labels:l,search:c,sort:d,orderBy:u,limit:m}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let a=new URLSearchParams;a.set("state",n||"opened"),a.set("per_page",String(m||20)),a.set("order_by",u||"updated_at"),a.set("sort",d||"desc"),r&&a.set("target_branch",r),o&&a.set("source_branch",o),s&&a.set("author_username",s),l&&a.set("labels",Array.isArray(l)?l.join(","):l),c&&a.set("search",c);let g=await f(`/projects/${b(t)}/merge_requests?${a.toString()}`),_=(Array.isArray(g)?g:[]).map(p=>({iid:p.iid,title:p.title,state:p.state,author:p.author?.username,sourceBranch:p.source_branch,targetBranch:p.target_branch,draft:p.draft??p.work_in_progress??!1,labels:Array.isArray(p.labels)?p.labels:[],webUrl:p.web_url,createdAt:p.created_at,updatedAt:p.updated_at}));return JSON.stringify({count:_.length,mergeRequests:_})}case"gitlab_list_mr_notes":{let{projectId:t,iid:n,limit:r}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let o=await f(`/projects/${b(t)}/merge_requests/${n}/notes?per_page=${r||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(o)?o.length:0,notes:(Array.isArray(o)?o:[]).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:n,body:r}=e||{};if(!t||!n||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let o=await f(`/projects/${b(t)}/merge_requests/${n}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_post_mr_discussion":{let{projectId:t,iid:n,path:r,oldPath:o,newLine:s,oldLine:l,body:c}=e||{};if(!t||!n||!r||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(s==null&&l==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=b(t),u=e.diffRefs||null;if(u||(u=(await f(`/projects/${d}/merge_requests/${n}`)).diff_refs||null),!u||!u.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 m={base_sha:u.base_sha,start_sha:u.start_sha,head_sha:u.head_sha,position_type:"text",new_path:r,old_path:o||r};s!=null&&(m.new_line=Number(s)),l!=null&&(m.old_line=Number(l));try{let a=await f(`/projects/${d}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(c),position:m}});return JSON.stringify({ok:!0,discussionId:a.id})}catch(a){return JSON.stringify({ok:!1,error:`inline anchor rejected (${a.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:n,body:r,comments:o}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let s=b(t),l=Array.isArray(o)?o.filter(h=>h&&h.path&&h.body&&(h.newLine!=null||h.oldLine!=null)):[];if(!r&&l.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=e.diffRefs||null;l.length>0&&!c&&(c=(await f(`/projects/${s}/merge_requests/${n}`)).diff_refs||null);let d=new Set,u=null;try{for(let h=1;h<=20;h+=1){let y=await f(`/projects/${s}/merge_requests/${n}/discussions?per_page=100&page=${h}`);if(!Array.isArray(y)||y.length===0)break;for(let L of y)for(let S of L.notes||[]){let I=Z(S.body);I&&d.add(I),u==null&&Q(S.body)&&(u=S.id)}if(y.length<100)break}}catch{}let m=!1,a=!1;if(r){let h=`${String(r)}${V}`;try{u!=null?(await f(`/projects/${s}/merge_requests/${n}/notes/${u}`,{method:"PUT",body:{body:h}}),a=!0):await f(`/projects/${s}/merge_requests/${n}/notes`,{method:"POST",body:{body:h}}),m=!0}catch{await f(`/projects/${s}/merge_requests/${n}/notes`,{method:"POST",body:{body:h}}),m=!0}}let{toPost:g,skipped:_}=X(l,d),p=0,w=[];if(g.length>0&&c)for(let h of g){let y={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:h.path,old_path:h.oldPath||h.path};h.newLine!=null&&(y.new_line=Number(h.newLine)),h.oldLine!=null&&(y.old_line=Number(h.oldLine));try{await f(`/projects/${s}/merge_requests/${n}/discussions`,{method:"POST",body:{body:String(h.body),position:y}}),p+=1}catch(L){w.push(`${h.path}:${h.newLine??h.oldLine} \u2014 ${L.message}`)}}else g.length>0&&!c&&w.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:m,summaryUpdated:a,inlinePosted:p,inlineSkipped:_||void 0,inlineErrors:w.length?w:void 0})}case"gitlab_get_discussion":{let{projectId:t,iid:n,discussionId:r}=e||{};if(!t||!n||!r)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let o=await f(`/projects/${b(t)}/merge_requests/${n}/discussions/${encodeURIComponent(r)}`),s=Array.isArray(o.notes)?o.notes:[],l=s.find(d=>d.position)||null,c=l?l.position:null;return JSON.stringify({discussionId:o.id,individualNote:!!o.individual_note,path:c&&(c.new_path||c.old_path)||null,newLine:c?c.new_line??null:null,oldLine:c?c.old_line??null:null,diffRefs:c?{base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha}:null,notes:s.map(d=>({id:d.id,author:d.author?.username,body:(d.body||"").slice(0,4e3),system:!!d.system,createdAt:d.created_at}))})}case"gitlab_reply_discussion":{let{projectId:t,iid:n,discussionId:r,body:o}=e||{};if(!t||!n||!r||!o)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let s=await f(`/projects/${b(t)}/merge_requests/${n}/discussions/${encodeURIComponent(r)}/notes`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:s.id,createdAt:s.created_at})}case"gitlab_list_projects":{let{query:t,limit:n}=e||{},r=Math.min(Number(n)>0?Number(n):50,200),o=new URLSearchParams;o.set("membership","true"),o.set("simple","true"),o.set("order_by","last_activity_at"),o.set("sort","desc"),o.set("per_page",String(Math.min(r+1,100))),t&&o.set("search",String(t));let s=async()=>{let a=await f(`/projects?${o.toString()}`);return Array.isArray(a)?a:[]},l=P(),c=ne(),d=[];for(let a of l||[null]){let g=a?await $.run(a,s):await s();for(let _ of g){let p=_&&_.path_with_namespace;J(c,p)&&(!a||J(a.repos,p))&&d.push({p:_,host:a?a.webHost:null})}}let u=d.length>r,m=d.slice(0,r).map(({p:a,host:g})=>({fullPath:a.path_with_namespace,name:a.name,webUrl:a.web_url,defaultBranch:a.default_branch||null,visibility:a.visibility||null,...g?{host:g}:{}}));return JSON.stringify({count:m.length,truncated:u,projects:m})}case"gitlab_list_issues":{let{projectId:t,state:n,labels:r,assigneeUsername:o,authorUsername:s,updatedAfter:l,search:c,sort:d,orderBy:u,limit:m}=e||{};if(!t)return JSON.stringify({error:"projectId is required"});let a=new URLSearchParams;a.set("state",n||"opened"),a.set("per_page",String(m||30)),a.set("order_by",u||"updated_at"),a.set("sort",d||"desc"),r&&a.set("labels",Array.isArray(r)?r.join(","):r),o&&a.set("assignee_username",o),s&&a.set("author_username",s),l&&a.set("updated_after",l),c&&a.set("search",c);let g=await f(`/projects/${b(t)}/issues?${a.toString()}`),_=(Array.isArray(g)?g:[]).map(p=>({iid:p.iid,title:p.title,state:p.state,labels:Array.isArray(p.labels)?p.labels:[],author:p.author?.username,assignees:(p.assignees||[]).map(w=>w.username),userNotesCount:p.user_notes_count,webUrl:p.web_url,createdAt:p.created_at,updatedAt:p.updated_at}));return JSON.stringify({count:_.length,issues:_})}case"gitlab_get_issue":{let{projectId:t,iid:n}=e||{};if(!t||!n)return JSON.stringify({error:"projectId and iid are required"});let r=await f(`/projects/${b(t)}/issues/${n}`);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(o=>o.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:n,body:r}=e||{};if(!t||!n||!r)return JSON.stringify({error:"projectId, iid, and body are required"});let o=await f(`/projects/${b(t)}/issues/${n}/notes`,{method:"POST",body:{body:String(r)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}default:return JSON.stringify({error:`Unknown tool: ${i}`})}}var ut={id:"gitlab",callsBackend:!0,serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:D.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_URL","GITLAB_INSTANCE_URL","GITLAB_API_URL","GITLAB_ALLOWED_REPOS","REPO_ALLOWLIST","GITLAB_INSTANCES","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab
8
8
  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:
9
9
 
10
10
  ### Discovery
@@ -30,4 +30,4 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
30
30
 
31
31
  ### Notes
32
32
  - 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.
33
- - 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 s=se();if(!s)return{command:null,args:[],env:{},description:this.description};let r={};for(let t of this.envKeys)process.env[t]&&(r[t]=process.env[t]);return{type:"stdio",command:"node",args:[s,"../dist/gitlab.js","gitlabSkill"],env:r,description:this.description}},async handleToolCall(s,r){try{let t=T(),n=D(),e=null;if(n){let o=le(r);if(o){let{path:i,instance:d}=await pe(o,t);if(!K(n,i)||t&&!d)return JSON.stringify({error:`Repository "${i||o}" is not available to this project. This project's agents may only use: ${[...n].join(", ")}. An owner changes this in Project Settings \u2192 Repository access.`,allowedRepos:[...n]});e=d}}return e?await R.run(e,()=>J(s,r)):await J(s,r)}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"]}}]};export{qe as gitlabSkill,m as glFetch};
33
+ - 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 i=je();if(!i)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of this.envKeys)process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[i,"../dist/gitlab.js","gitlabSkill"],env:e,description:this.description}},async handleToolCall(i,e){try{let t=P(),n=ne(),r=null;if(n){let o=ke(e);if(o){let{path:s,instance:l}=await ve(o,t);if(!J(n,s)||t&&!l)return JSON.stringify(R("gitlab",s||o,{gitlab:n}));r=l}}return r?await $.run(r,()=>ie(i,e)):await ie(i,e)}catch(t){return q(t)?JSON.stringify(t.refusal):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"]}}]};export{ut as gitlabSkill,f as glFetch};
@@ -0,0 +1,59 @@
1
+ /**
2
+ * graphMemory.ts — memory-graph skill, brokered through the control-plane.
3
+ *
4
+ * WHAT IT IS
5
+ * ──────────
6
+ * Gives an agent a write / recall surface over a per-tenant MEMORY GRAPH — our
7
+ * open-source `agent-graph` engine (Postgres + pgvector) run as an on-demand
8
+ * sidecar. The graph is persisted as a Stores-v2 store whose TYPE is the
9
+ * protocol name `graph-memory` (never a product name); `graph-memory` is also
10
+ * THIS skill's id. gbrain.ts with the engine swapped: same brokering, same
11
+ * store resolution, same auth.
12
+ *
13
+ * ARCHITECTURE — brokered, NOT a direct sidecar dial (security)
14
+ * ─────────────────────────────────────────────────────────────
15
+ * Run containers reach ONLY the control-plane, never a sidecar. So this skill
16
+ * hits the token-gated control-plane store API
17
+ *
18
+ * POST {ZIBBY_ACCOUNT_API_URL}/datasets/stores/{storeId}/<op>
19
+ * op ∈ put | link | recall_many | subgraph | trace (the ops this skill exposes)
20
+ *
21
+ * with the run's PROJECT_API_TOKEN (Bearer). The control-plane resolves +
22
+ * authorizes the tenant from the token, derives the sidecar's `graphId`
23
+ * SERVER-SIDE from (account, project, storeId), resolves the OWNING agent's
24
+ * embedding config + memory policy + writer identity (`origin`) from its own
25
+ * row, and forwards to the engine. The agent never sees the sidecar URL, a
26
+ * graphId, or an origin — and anything it sends under those names is STRIPPED
27
+ * by the control-plane (backend/src/handlers/graph-memory-store.js).
28
+ *
29
+ * PROVENANCE — a model writes 'claimed', full stop
30
+ * ────────────────────────────────────────────────
31
+ * The engine distinguishes 'observed' (a runtime saw it) from 'claimed' (an
32
+ * agent judged it). This skill runs INSIDE a model's run, so the control-plane
33
+ * never marks its calls trusted and the engine refuses 'observed'. The tools
34
+ * below therefore do not even offer a `provenance` argument; one that arrives
35
+ * anyway is dropped here so the call is not refused for a field the model
36
+ * could never legitimately set.
37
+ *
38
+ * STORES v2 — NAME-BASED RESOLUTION: identical to gbrain.ts / datasetStore.ts
39
+ * (`ZIBBY_STORE__<name>=<storeId>` is both the allowlist and the resolver; a
40
+ * single bound store may be addressed without naming it).
41
+ *
42
+ * TIER / GATING: tier ③ (heavy resident runtime → sidecar), brokered by the
43
+ * control-plane, fully server-side, no user connection → UNGATED. Toggleable
44
+ * via SKILL_META['graph-memory'].
45
+ */
46
+ /**
47
+ * Resolve a logical store NAME to its backend storeId against the bound map.
48
+ * Returns `{ storeId, name }` or `{ error }` — never throws (gbrain.ts rules).
49
+ */
50
+ type StoreTarget = {
51
+ storeId: string;
52
+ name: string;
53
+ } | {
54
+ error: string;
55
+ };
56
+ export declare function resolveStore(store: unknown): StoreTarget;
57
+ export declare const TOOL_OP: Readonly<Record<string, string>>;
58
+ export declare const graphMemorySkill: any;
59
+ export default graphMemorySkill;
@@ -0,0 +1,17 @@
1
+ import{existsSync as g,readFileSync as b}from"node:fs";import{homedir as _}from"node:os";import{join as v,dirname as w,resolve as k}from"node:path";import{fileURLToPath as O}from"node:url";import{SKILL_META as E}from"@zibby/skill-ids";var T=3e4,u=1,p="graph-memory";function S(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=w(O(import.meta.url)),e=k(r,"..","bin","mcp-skill.mjs");return g(e)?e:null}function A(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=v(_(),".zibby","config.json");return g(r)&&JSON.parse(b(r,"utf-8")).sessionToken||null}catch{return null}}function I(){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 R(){let r={};for(let[e,t]of Object.entries(process.env)){let n=/^ZIBBY_STORE__(.+)$/.exec(e);if(!n)continue;let i=typeof t=="string"?t.trim():"";i&&(r[n[1]]=i)}return r}var N=r=>"error"in r;function C(r){let e=R(),t=Object.keys(e),n=typeof r=="string"?r.trim():"";return n?Object.prototype.hasOwnProperty.call(e,n)?{storeId:e[n],name:n}:{error:`unknown store '${n}'; available: ${t.join(", ")}`}:t.length===1?{storeId:e[t[0]],name:t[0]}:t.length===0?{error:"no memory-graph store is bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${t.join(", ")})`}}async function B(r,e,t){let n=A();if(!n)throw new Error("No backend credential (PROJECT_API_TOKEN). The memory graph is only available inside a Zibby run.");let i=`${I()}/datasets/stores/${encodeURIComponent(r)}/${e}`,s={Authorization:`Bearer ${n}`,"Content-Type":"application/json"},l=JSON.stringify(t),h;for(let d=0;d<=u;d++){let y=new AbortController,f=setTimeout(()=>y.abort(),T);try{let o=await fetch(i,{method:"POST",headers:s,body:l,signal:y.signal}),c=await o.text().catch(()=>"");if(o.status>=500&&d<u){h=new Error(`store ${o.status}`);continue}if(!o.ok)throw new Error(`${p} ${e} failed (${o.status}): ${c.slice(0,300)}`);try{return JSON.parse(c)}catch{throw new Error(`store returned non-JSON: ${c.slice(0,200)}`)}}catch(o){if(h=o,!((o?.name==="AbortError"||o?.code==="ECONNREFUSED"||/fetch failed|network/i.test(String(o?.message)))&&d<u))break}finally{clearTimeout(f)}}throw h||new Error(`${p} ${e} request failed`)}function x(r){let{store:e,provenance:t,...n}=r&&typeof r=="object"?r:{};return n}var m={type:"object",description:"One recall query (agent-graph RecallQuery): seeds and/or match as entry points; rels/kinds/direction/scope/provenance shape the walk; maxCost bounds it; validAt/asOf/recordedBetween are the time filters.",properties:{seeds:{type:"array",items:{type:"string"},description:"Entry points by node id."},match:{type:"object",description:"Entry points by exact match: { kind?, label?, labelContains?, attrs?, limit? }."},maxCost:{type:"number",description:"Budget: max accumulated edge cost from any seed (default 2)."},rels:{type:"array",items:{type:"string"},description:"Only traverse these relation names."},kinds:{type:"array",items:{type:"string"},description:"Only RETURN nodes of these kinds."},scope:{description:"Only traverse edges with this scope (string or array); null-scope edges are global."},provenance:{type:"array",items:{type:"string",enum:["observed","claimed"]},description:"Only traverse edges with these provenances."},direction:{type:"string",enum:["out","in","both"],description:"Edge direction relative to the frontier (default 'both')."},limit:{type:"integer",description:"Cap on returned hits (default 50)."},order:{type:"string",enum:["cost","recent","oldest"],description:"'cost' (default) = closest first."},includeSeeds:{type:"boolean",description:"Include the seed nodes themselves as hits."},project:{type:"string",enum:["summary","full"],description:"How much of each hit to return: 'summary' (default) = id, kind, label, provenance, time and the path's relation names; 'full' = whole records including attrs."},validAt:{type:"integer",description:"WORLD-time filter (ms epoch): only edges valid at this instant."},asOf:{type:"integer",description:"KNOWLEDGE-time filter (ms epoch): what the graph knew then."},recordedBetween:{type:"array",items:{type:["integer","null"]},description:"KNOWLEDGE-time window [from, to] (ms epoch or null)."}}},a={type:"string",description:"The bound memory-graph store NAME (from AVAILABLE STORES). Omit if exactly one store is bound."},P=Object.freeze({graph_put:"put",graph_link:"link",graph_get:"get",graph_recall:"recall_many",graph_subgraph:"subgraph",graph_trace:"trace"}),j={id:p,callsBackend:!0,serverName:"graph_memory",allowedTools:["mcp__graph_memory__*"],meta:E[p],description:"Memory graph \u2014 write entities and time-aware assertions into, and recall by traversal from, a per-tenant memory graph (a `graph-memory`-type store, brokered by the control-plane)",promptFragment:`## Memory Graph (per-tenant, shared by the fleet)
2
+ You have a MEMORY GRAPH bound as a \`graph-memory\`-type store in the "AVAILABLE
3
+ STORES" block below: entities are NODES (id \`kind:namespace/key\`, e.g.
4
+ \`file:github.com/org/repo/src/x.ts\`, \`ticket:vikunja/292\`, \`run:exec-7f3a\`) and
5
+ relations are EDGES \u2014 assertions with a cost, a scope, world time (validFrom/validTo)
6
+ and knowledge time. Nothing is deleted: a wrong assertion is superseded. Your writes
7
+ are recorded as provenance 'claimed' (you are an agent; 'observed' is for runtimes).
8
+ Mint ids deterministically from the real-world identity so one entity is one node.
9
+ If exactly one store is bound you may omit \`store\`; otherwise pass its NAME.
10
+ Tools:
11
+ - graph_put({ id, kind, label, attrs?, store? }): create/update a node (upsert by id, versions kept).
12
+ - graph_link({ src, dst, rel, cost?, scope?, validFrom?, validTo?, attrs?, store? }): assert src \u2192rel\u2192 dst.
13
+ - graph_get({ id | edgeId, store? }): one node or edge, latest version, no traversal \u2014 check before you put.
14
+ - graph_recall({ queries: [{ seeds?, match?, rels?, kinds?, maxCost?, direction?, validAt?, asOf? }], store? }):
15
+ batched traversal; each hit carries its cost and the exact path of edges.
16
+ - graph_subgraph({ seeds?, match?, rels?, kinds?, maxCost?, store? }): the induced subgraph (nodes + all live edges) for visualisation/hand-off.
17
+ - graph_trace({ id, store? }): a node's full history \u2014 every version and every edge, superseded ones included.`,resolve(){let r=S();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);for(let t of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(t)&&process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/graphMemory.js","graphMemorySkill"],env:e,description:this.description}},async handleToolCall(r,e){try{let t=P[r];if(!t)return JSON.stringify({error:`Unknown tool: ${r}`});switch(r){case"graph_put":for(let s of["id","kind","label"])if(typeof e?.[s]!="string"||!e[s].trim())return JSON.stringify({error:`${s} (a non-empty string) is required`});break;case"graph_link":for(let s of["src","dst","rel"])if(typeof e?.[s]!="string"||!e[s].trim())return JSON.stringify({error:`${s} (a non-empty string) is required`});break;case"graph_get":{let s=typeof e?.id=="string"&&!!e.id.trim(),l=typeof e?.edgeId=="string"&&!!e.edgeId.trim();if(s===l)return JSON.stringify({error:"exactly one of id (a node) or edgeId (an edge) is required"});break}case"graph_recall":if(!Array.isArray(e?.queries)||e.queries.length===0)return JSON.stringify({error:"queries is required (non-empty array of recall queries)"});break;case"graph_trace":if(typeof e?.id!="string"||!e.id.trim())return JSON.stringify({error:"id (a non-empty string) is required"});break;default:break}let n=C(e?.store);if(N(n))return JSON.stringify({error:n.error});let i=await B(n.storeId,t,x(e));return JSON.stringify({...i,store:n.name,storeId:n.storeId})}catch(t){return JSON.stringify({error:String(t?.message||t)})}},tools:[{name:"graph_put",description:"Create or update a node (an entity: a file, ticket, run, person, repo, conclusion) in the memory graph. Upsert by id (`kind:namespace/key`); an existing id appends a version, so history is kept. Call it before graph_link so both ends exist. Recorded as provenance 'claimed'. Credential-shaped values are rejected \u2014 never put secrets here.",input_schema:{type:"object",properties:{id:{type:"string",description:"Canonical node id, e.g. `file:github.com/org/repo/src/x.ts`, `ticket:vikunja/292`, `run:exec-7f3a`. Mint it deterministically from the real-world identity."},kind:{type:"string",description:"Free-string kind: 'file', 'ticket', 'run', 'member', 'repo', 'epic', 'note', \u2026"},label:{type:"string",description:"Human-readable name (a path, a ticket title, a run name)."},attrs:{type:"object",description:"Free-form JSON attributes. Never secrets."},recordedAt:{type:"integer",description:"Knowledge time of this version (ms epoch). Defaults to now."},store:a},required:["id","kind","label"]}},{name:"graph_link",description:"Assert a relation between two nodes (src \u2192rel\u2192 dst). Every call appends a NEW edge with its own id. cost shapes later recall (cheap = close; a hub relation like in_repo might be 10); validFrom/validTo say when the fact held in the world (omitted validTo = still holds); scope is a branch/environment. Recorded as provenance 'claimed'.",input_schema:{type:"object",properties:{src:{type:"string",description:"Source node id (create it with graph_put first)."},dst:{type:"string",description:"Destination node id (create it with graph_put first)."},rel:{type:"string",description:"Relation name, snake_case by convention: 'touched', 'worked_on', 'depends_on', 'in_repo', 'notes', 'returned'."},cost:{type:"number",description:"Traversal cost; lower = closer (default 1)."},directed:{type:"boolean",description:"Default true. An undirected edge is traversable both ways."},scope:{type:["string","null"],description:"Branch / version / environment the assertion applies to. Omitted = global."},attrs:{type:"object",description:"Free-form JSON attributes ({ reason }, { text }, { status }). Never secrets."},validFrom:{type:["integer","null"],description:'World time the fact started to hold (ms epoch). Omitted = unbounded past; pass Date.now() for "starts now".'},validTo:{type:["integer","null"],description:"World time the fact stopped holding (ms epoch). Omitted = still holds (an OPEN fact)."},recordedAt:{type:"integer",description:"Knowledge time (ms epoch). Defaults to now; set only when back-filling."},store:a},required:["src","dst","rel"]}},{name:"graph_get",description:"Fetch one node (by `id`) or one edge (by `edgeId`) \u2014 latest version, no traversal. Returns null when unknown. The cheapest way to check existence or read current attrs before a graph_put.",input_schema:{type:"object",properties:{id:{type:"string",description:"Node id to fetch."},edgeId:{type:"string",description:"Edge id to fetch instead of a node."},store:a}}},{name:"graph_recall",description:'The main read, BATCHED: several recall queries in one call. Each starts from seeds (ids) and/or match (kind/label/attrs) and walks the graph cheapest-first within maxCost, returning every reachable node with its cost, the exact path of edges walked (origin, provenance, scope, validity) and which seed reached it. Shape the walk with rels (which hops), kinds (what to return), direction, scope, provenance; validAt = world time ("what was true then"), asOf = knowledge time ("what did the graph know then"). Results stay grouped per query; node records are in the shared `nodes` map.',input_schema:{type:"object",properties:{queries:{type:"array",items:m,minItems:1,description:"The recall queries, answered in order."},store:a},required:["queries"]}},{name:"graph_subgraph",description:"Export the induced subgraph around a query: every node the same recall would reach, plus ALL live edges among those nodes (not just the cheapest paths). The input for visualisation and for hand-offs that need the full local structure. Same filters as a recall query; the seeds are always included.",input_schema:{...m,properties:{...m.properties,store:a}}},{name:"graph_trace",description:"A node's full history: every version (oldest first) and every edge ever attached to it, in or out, including superseded ones. Use it to audit how an entity was described over time.",input_schema:{type:"object",properties:{id:{type:"string",description:"Node id to trace."},store:a},required:["id"]}}]},J=j;export{P as TOOL_OP,J as default,j as graphMemorySkill,C as resolveStore};
package/dist/index.d.ts CHANGED
@@ -34,6 +34,7 @@ import { gitWriteSkill } from './git-write.js';
34
34
  import { chatMemorySkill } from './chat-memory.js';
35
35
  import { kvMemorySkill } from './kvMemory.js';
36
36
  import { agentMessagingSkill } from './agentMessaging.js';
37
+ import { personVerificationSkill } from './personVerification.js';
37
38
  import { datasetStoreSkill } from './datasetStore.js';
38
39
  import { artifactSkill } from './artifact.js';
39
40
  import { chartRenderSkill } from './chartRender.js';
@@ -44,10 +45,11 @@ import { socialCardSkill } from './socialCard.js';
44
45
  import { codeScanSkill } from './code-scan.js';
45
46
  import { codebaseMemorySkill } from './codebaseMemory.js';
46
47
  import { gbrainSkill } from './gbrain.js';
48
+ import { graphMemorySkill } from './graphMemory.js';
47
49
  import { workflowBuilderSkill } from './workflow-builder.js';
48
50
  export { SKILL_IDS as SKILLS } from '@zibby/skill-ids';
49
51
  export { devServerPreviewRecipe } from './browser.js';
50
- export { browserSkill, jiraSkill, githubSkill, gitlabSkill, figmaSkill, hubspotSkill, linearSkill, vikunjaSkill, planeSkill, opendesignSkill, gitSkill, gitWriteSkill, slackSkill, larkSkill, discordSkill, notionSkill, linkedinSkill, googleDocsSkill, larkDocsSkill, larkAttendanceSkill, chatNotifySkill, sentrySkill, memorySkill, chatMemorySkill, kvMemorySkill, agentMessagingSkill, datasetStoreSkill, artifactSkill, chartRenderSkill, reportCheckSkill, codeStatsSkill, chatProgressSkill, socialCardSkill, codeScanSkill, codebaseMemorySkill, gbrainSkill, testRunnerSkill, testRunnerSkill as runnerSkill, skillInstallerSkill, coreToolsSkill, workflowBuilderSkill };
52
+ export { browserSkill, jiraSkill, githubSkill, gitlabSkill, figmaSkill, hubspotSkill, linearSkill, vikunjaSkill, planeSkill, opendesignSkill, gitSkill, gitWriteSkill, slackSkill, larkSkill, discordSkill, notionSkill, linkedinSkill, googleDocsSkill, larkDocsSkill, larkAttendanceSkill, chatNotifySkill, sentrySkill, memorySkill, chatMemorySkill, kvMemorySkill, agentMessagingSkill, personVerificationSkill, datasetStoreSkill, artifactSkill, chartRenderSkill, reportCheckSkill, codeStatsSkill, chatProgressSkill, socialCardSkill, codeScanSkill, codebaseMemorySkill, gbrainSkill, graphMemorySkill, testRunnerSkill, testRunnerSkill as runnerSkill, skillInstallerSkill, coreToolsSkill, workflowBuilderSkill };
51
53
  export { openaiBillingSkill, anthropicBillingSkill, cursorAdminSkill, fetchOpenAICosts, fetchOpenAIProjects, fetchAnthropicCosts, fetchAnthropicWorkspaces, fetchCursorSpend, fetchAllProviders, groupByKey, meanStddev, } from './llm-billing.js';
52
54
  export { reportObjectSchema, reportToBlockKit, reportToLarkCard, reportToNotionBlocks, reportToMarkdown, SEVERITIES as REPORT_SEVERITIES, } from './report.js';
53
55
  export { checkRenderedReport, REPORT_CODES } from './reportCheck.js';