@zibby/skills 0.1.48 → 0.1.49

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/index.js CHANGED
@@ -21,7 +21,7 @@ ${"#".repeat(n)} ${i.trim()}
21
21
  ${i}
22
22
  `):e.push(i)}return e.join("").replace(/\n{3,}/g,`
23
23
 
24
- `)}function oe(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ke(s){return oe(s).replace(/[a-z0-9]+/g,"")}function Ne(s,t){let e=oe(s),r=oe(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},n=i(e),o=i(r),a=0,c=0,d=0;for(let l of n.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of n.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function Z(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function vs(s,t=[]){let e=Array.isArray(t)?t:[];if(e.length===0)return{requested:s||null,resolved:null,strategy:"none"};let r=e.filter(a=>!a.subtask),i=r.length>0?r:e,n=Z(s);if(n){let a=i.find(l=>Z(l.name)===n);if(a)return{requested:s,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>Z(u)===n))continue;let p=i.find(u=>l.some(m=>Z(m)===Z(u.name)));if(p)return{requested:s,resolved:p,strategy:"alias"}}let d=i.map(l=>({t:l,score:Ne(s,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:s,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>Z(d.name)===a);if(c)return{requested:s||null,resolved:c,strategy:"default-preferred"}}return{requested:s||null,resolved:i[0],strategy:"default-first"}}async function _t(s){let t=`projectKeys=${encodeURIComponent(s)}&expand=projects.issuetypes`,e=await $(`/rest/api/3/issue/createmeta?${t}`),r=Array.isArray(e?.projects)?e.projects:[],n=r.find(a=>String(a?.key||"").toUpperCase()===String(s||"").toUpperCase())||r[0]||null;return(Array.isArray(n?.issuetypes)?n.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function bt(s,t){if(!s)throw new Error("projectKey is required");let e="sprint is not EMPTY";t==="active"?e="sprint in openSprints()":t==="closed"?e="sprint in closedSprints()":t==="future"&&(e="sprint in futureSprints()");let r=`project = ${s} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(r)}&maxResults=100&fields=customfield_10020`,n=await $(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of n.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function Ns(s,{sprintId:t,sprintName:e,target:r}={}){let i=Array.isArray(s)?s:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(t!=null&&String(t).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(t))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(d=>({s:d,score:Ne(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let n=String(r||"current").trim().toLowerCase();return n==="active"||n==="current"||n==="latest"?{sprint:i[0],selectedBy:n}:{sprint:i[0],selectedBy:"default"}}function Is(s,t){let e=s?.fields?.customfield_10020;return Array.isArray(e)?e.some(r=>String(r?.id)===String(t)):!1}async function Rs({issueKey:s,projectKey:t,sprintId:e,attempts:r=3,delayMs:i=450}){let n=[];for(let o=0;o<r;o++){try{let a=`project = ${t} AND key = ${s} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await $(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return n.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:n};let p=await $(`/rest/api/3/issue/${s}?fields=customfield_10020,status`),u=Is(p,e);if(n.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:n}}catch(a){n.push({attempt:o+1,error:String(a?.message||a)})}o<r-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:n}}async function Ge({issueKey:s,projectKey:t,sprintId:e,sprintName:r,target:i}){if(!s)return{ok:!1,error:"issueKey is required"};let n=t;if(!n&&(n=(await $(`/rest/api/3/issue/${s}?fields=project`))?.fields?.project?.key||null,!n))return{ok:!1,error:`Could not resolve project for ${s}`};let o=await bt(n,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${n}`};let{sprint:a,selectedBy:c}=Ns(o,{sprintId:e,sprintName:r,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${n}`,requested:{sprintId:e??null,sprintName:r??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await $(`/rest/api/3/issue/${s}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await Rs({issueKey:s,projectKey:n,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:s,projectKey:n,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${s} in sprint ${a.id}`}}async function $(s,t={}){let e=async()=>{let{token:r,cloudId:i}=await gs("jira");if(typeof r!="string"||!r)throw new Error(`Invalid jira token type: ${typeof r}`);if(!i)throw new Error("Invalid jira cloudId: missing");let n=`https://api.atlassian.com/ex/jira/${i}${s}`,o=await fetch(n,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw r;return _s("jira"),e()}}var kt={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
24
+ `)}function oe(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ke(s){return oe(s).replace(/[a-z0-9]+/g,"")}function Ne(s,t){let e=oe(s),r=oe(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},n=i(e),o=i(r),a=0,c=0,d=0;for(let l of n.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of n.entries()){let u=o.get(l)||0;a+=Math.min(p,u)}return 2*a/Math.max(1,c+d)}function Z(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function vs(s,t=[]){let e=Array.isArray(t)?t:[];if(e.length===0)return{requested:s||null,resolved:null,strategy:"none"};let r=e.filter(a=>!a.subtask),i=r.length>0?r:e,n=Z(s);if(n){let a=i.find(l=>Z(l.name)===n);if(a)return{requested:s,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(u=>Z(u)===n))continue;let p=i.find(u=>l.some(m=>Z(m)===Z(u.name)));if(p)return{requested:s,resolved:p,strategy:"alias"}}let d=i.map(l=>({t:l,score:Ne(s,l.name)})).sort((l,p)=>p.score-l.score);if(d[0]&&d[0].score>=.5)return{requested:s,resolved:d[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(d=>Z(d.name)===a);if(c)return{requested:s||null,resolved:c,strategy:"default-preferred"}}return{requested:s||null,resolved:i[0],strategy:"default-first"}}async function _t(s){let t=`projectKeys=${encodeURIComponent(s)}&expand=projects.issuetypes`,e=await T(`/rest/api/3/issue/createmeta?${t}`),r=Array.isArray(e?.projects)?e.projects:[],n=r.find(a=>String(a?.key||"").toUpperCase()===String(s||"").toUpperCase())||r[0]||null;return(Array.isArray(n?.issuetypes)?n.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function bt(s,t){if(!s)throw new Error("projectKey is required");let e="sprint is not EMPTY";t==="active"?e="sprint in openSprints()":t==="closed"?e="sprint in closedSprints()":t==="future"&&(e="sprint in futureSprints()");let r=`project = ${s} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(r)}&maxResults=100&fields=customfield_10020`,n=await T(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of n.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let d={active:0,future:1,closed:2},l=(d[a.state]??3)-(d[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function Ns(s,{sprintId:t,sprintName:e,target:r}={}){let i=Array.isArray(s)?s:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(t!=null&&String(t).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(t))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=i.find(d=>String(d.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(d=>({s:d,score:Ne(o,d.name||"")})).sort((d,l)=>l.score-d.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let n=String(r||"current").trim().toLowerCase();return n==="active"||n==="current"||n==="latest"?{sprint:i[0],selectedBy:n}:{sprint:i[0],selectedBy:"default"}}function Is(s,t){let e=s?.fields?.customfield_10020;return Array.isArray(e)?e.some(r=>String(r?.id)===String(t)):!1}async function Rs({issueKey:s,projectKey:t,sprintId:e,attempts:r=3,delayMs:i=450}){let n=[];for(let o=0;o<r;o++){try{let a=`project = ${t} AND key = ${s} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,d=await T(`/rest/api/3/search/jql?${c}`);if(Number(d?.total||0)>0)return n.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:n};let p=await T(`/rest/api/3/issue/${s}?fields=customfield_10020,status`),u=Is(p,e);if(n.push({attempt:o+1,jql:!1,issueField:u}),u)return{ok:!0,method:"issue_field",traces:n}}catch(a){n.push({attempt:o+1,error:String(a?.message||a)})}o<r-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:n}}async function Ge({issueKey:s,projectKey:t,sprintId:e,sprintName:r,target:i}){if(!s)return{ok:!1,error:"issueKey is required"};let n=t;if(!n&&(n=(await T(`/rest/api/3/issue/${s}?fields=project`))?.fields?.project?.key||null,!n))return{ok:!1,error:`Could not resolve project for ${s}`};let o=await bt(n,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${n}`};let{sprint:a,selectedBy:c}=Ns(o,{sprintId:e,sprintName:r,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${n}`,requested:{sprintId:e??null,sprintName:r??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await T(`/rest/api/3/issue/${s}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let d=await Rs({issueKey:s,projectKey:n,sprintId:a.id}),l=d.ok;return{ok:l,issueKey:s,projectKey:n,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:d.method,verified:l,verificationTrace:d.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${s} in sprint ${a.id}`}}async function T(s,t={}){let e=async()=>{let{token:r,cloudId:i}=await gs("jira");if(typeof r!="string"||!r)throw new Error(`Invalid jira token type: ${typeof r}`);if(!i)throw new Error("Invalid jira cloudId: missing");let n=`https://api.atlassian.com/ex/jira/${i}${s}`,o=await fetch(n,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw r;return _s("jira"),e()}}var kt={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:N.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
25
25
  You have direct access to the user's Jira. Use these tools proactively:
26
26
 
27
27
  ### Issue tools
@@ -71,7 +71,7 @@ When user asks to move/transition ticket status:
71
71
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
72
72
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
73
73
  5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
74
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let s=ks();if(!s)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[s],env:t,description:this.description}},async handleToolCall(s,t){try{switch(s){case"jira_list_projects":{let e=await $("/rest/api/3/project"),r=(Array.isArray(e)?e:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:r.length,projects:r})}case"jira_list_statuses":{let{projectKey:e}=t||{};if(e){let n=await $(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(n)?n:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let r=await $("/rest/api/3/status"),i=(Array.isArray(r)?r:[]).map(n=>({id:n.id,name:n.name,category:n.statusCategory?.name||null})).sort((n,o)=>String(n.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:e}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let r=await _t(e);return JSON.stringify({projectKey:e,count:r.length,issueTypes:r})}case"jira_search":{let e=t.jql||"",r=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let n=`jql=${encodeURIComponent(e)}&maxResults=${r}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await $(`/rest/api/3/search/jql?${n}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let e=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let r=await $(`/rest/api/3/issue/${e}`);return JSON.stringify({key:r.key,project:r.fields?.project?.key,summary:r.fields?.summary,description:r.fields?.description,status:r.fields?.status?.name,assignee:r.fields?.assignee?.displayName||"Unassigned",priority:r.fields?.priority?.name,type:r.fields?.issuetype?.name,labels:r.fields?.labels,created:r.fields?.created,updated:r.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:r,issueType:i,description:n,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=t;if(!e||!r)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await _t(e),f=vs(i,h)}catch{}let _={project:{key:e},summary:r,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};n&&(_.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}),o&&(_.priority={name:o}),a?.length&&(_.labels=a),c&&(_.assignee={id:c});let g=await $("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&Z(f.requested)!==Z(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${e}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(b.sprintMove=await Ge({issueKey:g.key,projectKey:e,sprintId:p,sprintName:u,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:e,state:r}=t,i=await bt(e,r);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o}=t||{},a=await Ge({issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o}=t||{},a=await Ge({issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:r,projectKey:i,status:n,maxResults:o}=t;if(!e&&!r)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=r?`sprint = ${r}`:`sprint = "${e}"`,d=i?`project = ${i} AND `:"",l=n?` AND status = "${n}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await $(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),h={};for(let _ of f)h[_.status]=(h[_.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:e,maxResults:r}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await $(`/rest/api/3/issue/${e}/comment?maxResults=${r||50}&orderBy=-created`),o=(n.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ve(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:n.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:r}=t;return!e||!r?JSON.stringify({error:"issueKey and body are required"}):(await $(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:r}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:r}=t;return!e||!r?JSON.stringify({error:"issueKey and fields are required"}):(await $(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:r}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:r,toStatus:i,statusName:n,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||n||o||"").trim();if(!r&&!a){let p=((await $(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=r;if(!c){let p=(await $(`/rest/api/3/issue/${e}/transitions`)).transitions||[],u=oe(a),m=p.find(f=>oe(f?.name||"")===u||oe(f?.to?.name||"")===u);if(!m){let f=Ke(a);f.length>=2&&(m=p.find(h=>{let _=Ke(h?.name||""),g=Ke(h?.to?.name||""),b=_.length>=2&&(_.includes(f)||f.includes(_)),y=g.length>=2&&(g.includes(f)||f.includes(g));return b||y}))}if(!m){let f=p.map(b=>{let y=Ne(a,b?.name||""),S=Ne(a,b?.to?.name||"");return{t:b,score:Math.max(y,S)}}).sort((b,y)=>y.score-b.score),h=f[0],_=f[1];h&&h.score>=.45&&(!_||h.score-_.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await $(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await $(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Os}from"fs";import{fileURLToPath as As}from"url";import{dirname as js,resolve as $s}from"path";import{resolveIntegrationToken as wt}from"@zibby/core/backend-client.js";function Ts(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=js(As(import.meta.url)),t=$s(s,"..","bin","mcp-skill.mjs");return Os(t)?t:null}async function v(s,t={}){let{token:e}=await wt("github"),r=s.startsWith("https://")?s:`https://api.github.com${s}`,i={Authorization:`Bearer ${e}`,Accept:t.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(r,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`GitHub API ${n.status}: ${o.slice(0,300)}`)}return t.raw?n.text():n.json()}var ae={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
74
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let s=ks();if(!s)return null;let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return process.env.ATLASSIAN_INSTANCE_URL&&(t.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[s],env:t,description:this.description}},async handleToolCall(s,t){try{switch(s){case"jira_list_projects":{let e=await T("/rest/api/3/project"),r=(Array.isArray(e)?e:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:r.length,projects:r})}case"jira_list_statuses":{let{projectKey:e}=t||{};if(e){let n=await T(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(n)?n:[],a=new Map;for(let d of o)for(let l of d.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((d,l)=>String(d.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let r=await T("/rest/api/3/status"),i=(Array.isArray(r)?r:[]).map(n=>({id:n.id,name:n.name,category:n.statusCategory?.name||null})).sort((n,o)=>String(n.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:e}=t||{};if(!e)return JSON.stringify({error:"projectKey is required"});let r=await _t(e);return JSON.stringify({projectKey:e,count:r.length,issueTypes:r})}case"jira_search":{let e=t.jql||"",r=t.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let n=`jql=${encodeURIComponent(e)}&maxResults=${r}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await T(`/rest/api/3/search/jql?${n}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let e=t.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let r=await T(`/rest/api/3/issue/${e}`);return JSON.stringify({key:r.key,project:r.fields?.project?.key,summary:r.fields?.summary,description:r.fields?.description,status:r.fields?.status?.name,assignee:r.fields?.assignee?.displayName||"Unassigned",priority:r.fields?.priority?.name,type:r.fields?.issuetype?.name,labels:r.fields?.labels,created:r.fields?.created,updated:r.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:r,issueType:i,description:n,priority:o,labels:a,assigneeId:c,moveToSprint:d,moveToActiveSprint:l,sprintId:p,sprintName:u,target:m}=t;if(!e||!r)return JSON.stringify({error:"projectKey and summary are required"});let f={requested:i||null,resolved:null,strategy:"none"},h=[];try{h=await _t(e),f=vs(i,h)}catch{}let _={project:{key:e},summary:r,issuetype:f?.resolved?.id?{id:f.resolved.id}:{name:i||"Task"}};n&&(_.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}),o&&(_.priority={name:o}),a?.length&&(_.labels=a),c&&(_.assignee={id:c});let g=await T("/rest/api/3/issue",{method:"POST",body:{fields:_}}),b={ok:!0,key:g.key,id:g.id,self:g.self};return f?.resolved&&(b.issueType=f.resolved.name,b.issueTypeResolution=f.strategy,f.strategy!=="exact"&&f.requested&&Z(f.requested)!==Z(f.resolved.name)&&(b.issueTypeWarning=`Requested "${f.requested}" is not available in ${e}; used "${f.resolved.name}" instead.`)),h.length>0&&(b.availableIssueTypes=h.map(y=>y.name)),(d||l)&&(b.sprintMove=await Ge({issueKey:g.key,projectKey:e,sprintId:p,sprintName:u,target:m})),JSON.stringify(b)}case"jira_list_sprints":{let{projectKey:e,state:r}=t,i=await bt(e,r);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o}=t||{},a=await Ge({issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o}=t||{},a=await Ge({issueKey:e,projectKey:r,sprintId:i,sprintName:n,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:r,projectKey:i,status:n,maxResults:o}=t;if(!e&&!r)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=r?`sprint = ${r}`:`sprint = "${e}"`,d=i?`project = ${i} AND `:"",l=n?` AND status = "${n}"`:"",p=`${d}${c}${l} ORDER BY status ASC, priority DESC`,u=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,m=await T(`/rest/api/3/search/jql?${u}`),f=(m.issues||[]).map(_=>({key:_.key,project:_.fields?.project?.key,summary:_.fields?.summary,status:_.fields?.status?.name,assignee:_.fields?.assignee?.displayName||"Unassigned",priority:_.fields?.priority?.name,type:_.fields?.issuetype?.name})),h={};for(let _ of f)h[_.status]=(h[_.status]||0)+1;return JSON.stringify({count:f.length,total:m.total||f.length,statusCounts:h,issues:f})}case"jira_get_comments":{let{issueKey:e,maxResults:r}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await T(`/rest/api/3/issue/${e}/comment?maxResults=${r||50}&orderBy=-created`),o=(n.comments||[]).map(a=>{let c="";return a.body?.content&&(c=ve(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:n.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:r}=t;return!e||!r?JSON.stringify({error:"issueKey and body are required"}):(await T(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:r}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:r}=t;return!e||!r?JSON.stringify({error:"issueKey and fields are required"}):(await T(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:r}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:r,toStatus:i,statusName:n,status:o}=t;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||n||o||"").trim();if(!r&&!a){let p=((await T(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(u=>({id:u.id,name:u.name,to:u.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=r;if(!c){let p=(await T(`/rest/api/3/issue/${e}/transitions`)).transitions||[],u=oe(a),m=p.find(f=>oe(f?.name||"")===u||oe(f?.to?.name||"")===u);if(!m){let f=Ke(a);f.length>=2&&(m=p.find(h=>{let _=Ke(h?.name||""),g=Ke(h?.to?.name||""),b=_.length>=2&&(_.includes(f)||f.includes(_)),y=g.length>=2&&(g.includes(f)||f.includes(g));return b||y}))}if(!m){let f=p.map(b=>{let y=Ne(a,b?.name||""),S=Ne(a,b?.to?.name||"");return{t:b,score:Math.max(y,S)}}).sort((b,y)=>y.score-b.score),h=f[0],_=f[1];h&&h.score>=.45&&(!_||h.score-_.score>=.12)&&(m=h.t)}if(!m?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(f=>({id:f.id,name:f.name,to:f.to?.name}))});c=m.id}await T(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let d=await T(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:d?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};import{existsSync as Os}from"fs";import{fileURLToPath as As}from"url";import{dirname as js,resolve as Ts}from"path";import{resolveIntegrationToken as wt}from"@zibby/core/backend-client.js";function $s(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=js(As(import.meta.url)),t=Ts(s,"..","bin","mcp-skill.mjs");return Os(t)?t:null}async function v(s,t={}){let{token:e}=await wt("github"),r=s.startsWith("https://")?s:`https://api.github.com${s}`,i={Authorization:`Bearer ${e}`,Accept:t.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(r,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`GitHub API ${n.status}: ${o.slice(0,300)}`)}return t.raw?n.text():n.json()}var ae={id:"github",serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:N.GITHUB,envKeys:["GITHUB_TOKEN"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub (connected)
75
75
  You have access to the user's GitHub repositories. Available tools:
76
76
 
77
77
  ### Discovery
@@ -114,9 +114,9 @@ When user says "check out repo-name" or "clone repo-name":
114
114
  3. STOP. Do not offer to inspect files or ask what to do next.
115
115
 
116
116
  When user just wants to "look at" or "read" files (not clone):
117
- - Use github_get_file to read individual files via API`,resolve(){let s=Ts();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=await v(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.limit||20}`),i=(r.items||[]).map(n=>({number:n.number,title:n.title,state:n.state,repo:n.repository_url?.split("/").slice(-2).join("/"),url:n.html_url,user:n.user?.login,isPR:!!n.pull_request,labels:(n.labels||[]).map(o=>o.name),createdAt:n.created_at}));return JSON.stringify({total:r.total_count,items:i})}case"github_search_code":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=t.repo?`+repo:${t.repo}`:"",i=t.language?`+language:${t.language}`:"",n=await v(`/search/code?q=${encodeURIComponent(e)}${r}${i}&per_page=${t.limit||15}`),o=(n.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:n.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}`);return JSON.stringify({number:n.number,title:n.title,state:n.state,merged:n.merged,body:n.body?.slice(0,5e3),user:n.user?.login,branch:n.head?.ref,headSha:n.head?.sha,base:n.base?.ref,changedFiles:n.changed_files,additions:n.additions,deletions:n.deletions,createdAt:n.created_at,mergedAt:n.merged_at,url:n.html_url,labels:(n.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=n.length>15e3;return JSON.stringify({number:i,diff:o?n.slice(0,15e3):n,truncated:o,totalLength:n.length})}case"github_list_pr_files":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:n.length,files:n.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}/comments?per_page=50`),o=await v(`/repos/${e}/${r}/issues/${i}/comments?per_page=50`),a=[...n.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:r,number:i,commentId:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await v(`/repos/${e}/${r}/pulls/comments/${n}`),a=o.in_reply_to_id||o.id,c=[];try{c=await v(`/repos/${e}/${r}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),l=d.length?d:[o],p=l.find(u=>u.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:r,number:i,commentId:n,body:o}=t||{};if(!e||!r||!i||!n||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await v(`/repos/${e}/${r}/pulls/${i}/comments/${n}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:e,repo:r,number:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:r,number:i,body:n,event:o,comments:a}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(a)?a.filter(u=>u&&u.path&&u.body&&(u.line!=null||u.position!=null)).map(u=>{let m={path:u.path,body:String(u.body)};return u.line!=null?(m.line=Number(u.line),m.side=u.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(u.position),m}):[];if(c!=="APPROVE"&&!n&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:c};n&&(l.body=String(n)),d.length>0&&(l.comments=d);let p=await v(`/repos/${e}/${r}/pulls/${i}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:p.id,state:p.state,event:c,commentsPosted:d.length,url:p.html_url})}case"github_list_commits":{let{owner:e,repo:r,branch:i,path:n,limit:o}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${e}/${r}/commits?per_page=${o||20}`;i&&(a+=`&sha=${encodeURIComponent(i)}`),n&&(a+=`&path=${encodeURIComponent(n)}`);let c=await v(a);return JSON.stringify({total:c.length,commits:c.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:e,repo:r,sha:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let n=await v(`/repos/${e}/${r}/commits/${i}`);return JSON.stringify({sha:n.sha?.slice(0,8),message:n.commit?.message,author:n.commit?.author?.name,date:n.commit?.author?.date,stats:n.stats,files:(n.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:e,repo:r,path:i,ref:n}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${r}/contents/${encodeURIComponent(i)}`;n&&(o+=`?ref=${encodeURIComponent(n)}`);let a=await v(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),d=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:d?c.slice(0,2e4):c,truncated:d})}case"github_get_user":try{let e=await v("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let r=e.repositories[0],i=r.owner.login,n=r.owner.type,o=n==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await v(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:n,isOrg:n==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let r=(await v("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of r)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let n=Array.from(i.values());return JSON.stringify({count:n.length,orgs:n,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let f=function(g){let b=g.replace(/^~(?=$|\/|\\)/,m);return a(b)},{owner:e,repo:r,destination:i}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:n}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:u}=await wt("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),_=o(h,r);if(d(h,{recursive:!0}),c(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});try{let g=`https://x-access-token:${u}@github.com/${e}/${r}.git`;n(`git clone ${g} "${_}"`,{stdio:"pipe"});let b=p()==="win32",y;return b?y=n(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):y=n(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${e}/${r} to ${_}`,contents:y.split(`
117
+ - Use github_get_file to read individual files via API`,resolve(){let s=$s();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/github.js","githubSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"github_search_issues":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=await v(`/search/issues?q=${encodeURIComponent(e)}&per_page=${t.limit||20}`),i=(r.items||[]).map(n=>({number:n.number,title:n.title,state:n.state,repo:n.repository_url?.split("/").slice(-2).join("/"),url:n.html_url,user:n.user?.login,isPR:!!n.pull_request,labels:(n.labels||[]).map(o=>o.name),createdAt:n.created_at}));return JSON.stringify({total:r.total_count,items:i})}case"github_search_code":{let e=t.query;if(!e)return JSON.stringify({error:"query is required"});let r=t.repo?`+repo:${t.repo}`:"",i=t.language?`+language:${t.language}`:"",n=await v(`/search/code?q=${encodeURIComponent(e)}${r}${i}&per_page=${t.limit||15}`),o=(n.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:n.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}`);return JSON.stringify({number:n.number,title:n.title,state:n.state,merged:n.merged,body:n.body?.slice(0,5e3),user:n.user?.login,branch:n.head?.ref,headSha:n.head?.sha,base:n.base?.ref,changedFiles:n.changed_files,additions:n.additions,deletions:n.deletions,createdAt:n.created_at,mergedAt:n.merged_at,url:n.html_url,labels:(n.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=n.length>15e3;return JSON.stringify({number:i,diff:o?n.slice(0,15e3):n,truncated:o,totalLength:n.length})}case"github_list_pr_files":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:n.length,files:n.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:e,repo:r,number:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/pulls/${i}/comments?per_page=50`),o=await v(`/repos/${e}/${r}/issues/${i}/comments?per_page=50`),a=[...n.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,d)=>new Date(c.createdAt)-new Date(d.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:r,number:i,commentId:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await v(`/repos/${e}/${r}/pulls/comments/${n}`),a=o.in_reply_to_id||o.id,c=[];try{c=await v(`/repos/${e}/${r}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let d=c.filter(u=>u.id===a||u.in_reply_to_id===a).sort((u,m)=>new Date(u.created_at)-new Date(m.created_at)),l=d.length?d:[o],p=l.find(u=>u.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(u=>({id:u.id,user:u.user?.login,body:(u.body||"").slice(0,4e3),createdAt:u.created_at,isRoot:u.id===a,url:u.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:r,number:i,commentId:n,body:o}=t||{};if(!e||!r||!i||!n||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await v(`/repos/${e}/${r}/pulls/${i}/comments/${n}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:e,repo:r,number:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:r,number:i,body:n,event:o,comments:a}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let d=Array.isArray(a)?a.filter(u=>u&&u.path&&u.body&&(u.line!=null||u.position!=null)).map(u=>{let m={path:u.path,body:String(u.body)};return u.line!=null?(m.line=Number(u.line),m.side=u.side==="LEFT"?"LEFT":"RIGHT"):m.position=Number(u.position),m}):[];if(c!=="APPROVE"&&!n&&d.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l={event:c};n&&(l.body=String(n)),d.length>0&&(l.comments=d);let p=await v(`/repos/${e}/${r}/pulls/${i}/reviews`,{method:"POST",body:l});return JSON.stringify({ok:!0,id:p.id,state:p.state,event:c,commentsPosted:d.length,url:p.html_url})}case"github_list_commits":{let{owner:e,repo:r,branch:i,path:n,limit:o}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let a=`/repos/${e}/${r}/commits?per_page=${o||20}`;i&&(a+=`&sha=${encodeURIComponent(i)}`),n&&(a+=`&path=${encodeURIComponent(n)}`);let c=await v(a);return JSON.stringify({total:c.length,commits:c.map(d=>({sha:d.sha?.slice(0,8),fullSha:d.sha,message:d.commit?.message?.slice(0,300),author:d.commit?.author?.name,date:d.commit?.author?.date,url:d.html_url}))})}case"github_get_commit":{let{owner:e,repo:r,sha:i}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let n=await v(`/repos/${e}/${r}/commits/${i}`);return JSON.stringify({sha:n.sha?.slice(0,8),message:n.commit?.message,author:n.commit?.author?.name,date:n.commit?.author?.date,stats:n.stats,files:(n.files||[]).map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_get_file":{let{owner:e,repo:r,path:i,ref:n}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${r}/contents/${encodeURIComponent(i)}`;n&&(o+=`?ref=${encodeURIComponent(n)}`);let a=await v(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),d=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:d?c.slice(0,2e4):c,truncated:d})}case"github_get_user":try{let e=await v("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let r=e.repositories[0],i=r.owner.login,n=r.owner.type,o=n==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await v(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:n,isOrg:n==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let r=(await v("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of r)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let n=Array.from(i.values());return JSON.stringify({count:n.length,orgs:n,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let f=function(g){let b=g.replace(/^~(?=$|\/|\\)/,m);return a(b)},{owner:e,repo:r,destination:i}=t;if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let{execSync:n}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:d}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:u}=await wt("github"),m=l(),h=i?f(i):o(m,"zibby-repos"),_=o(h,r);if(d(h,{recursive:!0}),c(_))return JSON.stringify({error:`Directory ${_} already exists. Remove it first or use a different destination.`,existingPath:_});try{let g=`https://x-access-token:${u}@github.com/${e}/${r}.git`;n(`git clone ${g} "${_}"`,{stdio:"pipe"});let b=p()==="win32",y;return b?y=n(`dir "${_}"`,{encoding:"utf-8",shell:"cmd.exe"}):y=n(`ls -la "${_}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:_,message:`Cloned ${e}/${r} to ${_}`,contents:y.split(`
118
118
  `).slice(0,30).join(`
119
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(g){return JSON.stringify({error:`Clone failed: ${g.message}`})}}case"github_search_repos":{let{query:e,limit:r}=t;if(!e)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),n=JSON.parse(i);if(n.error)return JSON.stringify(n);let o=e.toLowerCase(),a=n.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:e,count:a.length,repos:a.slice(0,r||20)})}case"github_list_repos":{let{owner:e,type:r,sort:i,direction:n,limit:o,query:a}=t,c=100,d=o||200,l=[],p=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),u=y=>{if(!a)return!0;let S=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(S)||y.fullName&&y.fullName.toLowerCase().includes(S)||y.description&&y.description.toLowerCase().includes(S)};if(!e){let y=1,S=!0;for(;S&&l.length<d;){let U=`/installation/repositories?per_page=${c}&page=${y}`,Be=(await v(U)).repositories||[];if(Be.length===0)break;l=l.concat(Be),S=Be.length===c,y++}let j=l.map(p).filter(u),Y=j.slice(0,d),De=j.length>Y.length,A=Y.filter(U=>U.private).length,R=Y.filter(U=>!U.private).length;return JSON.stringify({count:Y.length,repos:Y,truncated:De,privateCount:A,publicCount:R,message:`Found ${A} private and ${R} public repos`})}let m=await v(`/orgs/${e}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${e}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${i||"updated"}&direction=${n||"desc"}`:y=`/users/${e}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${i||"updated"}&direction=${n||"desc"}`;let S=await v(y),j=Array.isArray(S)?S:[];if(j.length===0)break;l=l.concat(j),h=j.length===c,f++}let _=l.map(p).filter(u),g=_.slice(0,d),b=_.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:b})}case"github_create_pr":{let{owner:e,repo:r,head:i,title:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await v(`/repos/${e}/${r}`)).default_branch||"main"}catch{o="main"}let a={title:String(n),head:String(i),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let c=await v(`/repos/${e}/${r}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${r}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let d=String(c.message||c);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${r}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=t.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(n))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${n})`});let o={merge_method:n};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let a=await v(`/repos/${e}/${r}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:e,repo:r,title:i,body:n}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await v(`/repos/${e}/${r}/issues`,{method:"POST",body:{title:i,body:n||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:r,state:i,labels:n,since:o,assignee:a,sort:c,direction:d,limit:l}=t||{};if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),n&&p.set("labels",Array.isArray(n)?n.join(","):n),o&&p.set("since",o),a&&p.set("assignee",a);let u=await v(`/repos/${e}/${r}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/issues/${i}`);return n.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:n.number,title:n.title,body:n.body||"",state:n.state,stateReason:n.state_reason||null,labels:(n.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:n.assignee?.login||null,assignees:(n.assignees||[]).map(o=>o.login),user:n.user?.login,milestone:n.milestone?.title||null,comments:n.comments,url:n.html_url,createdAt:n.created_at,updatedAt:n.updated_at,closedAt:n.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:r,number:i,limit:n}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments?per_page=${n||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:e,repo:r,number:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments`,{method:"POST",body:{body:n}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:r,number:i,stateReason:n}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};n&&(o.state_reason=n);let a=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:n.number,state:n.state,url:n.html_url})}case"github_label_issue":{let{owner:e,repo:r,number:i,labels:n,mode:o}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(n)?n:n?[n]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await v(`/repos/${e}/${r}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await v(`/repos/${e}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await v(`/repos/${e}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List recent commits on a branch, optionally filtered by file path",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Max commits (default: 20)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as Es}from"fs";import{fileURLToPath as xs}from"url";import{dirname as Ls,resolve as Cs}from"path";function Ps(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ls(xs(import.meta.url)),t=Cs(s,"..","bin","mcp-skill.mjs");return Es(t)?t:null}function qs(){let s=process.env.GITLAB_API_URL;if(s)return s.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 Js(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let s=process.env.GITLAB_TOKEN;if(!s)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":s}}async function T(s,t={}){let e=/^https?:\/\//.test(s)?s:`${qs()}${s}`,r={Accept:"application/json","User-Agent":"Zibby-App",...Js(),...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(e,{method:t.method||"GET",headers:r,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${n.slice(0,300)}`)}return t.raw?i.text():i.json()}function St(){let s=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(s?s.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Us(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function x(s){let t=String(s);return/^\d+$/.test(t)?t:encodeURIComponent(t)}var ce={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:N.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab (connected)
119
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(g){return JSON.stringify({error:`Clone failed: ${g.message}`})}}case"github_search_repos":{let{query:e,limit:r}=t;if(!e)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),n=JSON.parse(i);if(n.error)return JSON.stringify(n);let o=e.toLowerCase(),a=n.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:e,count:a.length,repos:a.slice(0,r||20)})}case"github_list_repos":{let{owner:e,type:r,sort:i,direction:n,limit:o,query:a}=t,c=100,d=o||200,l=[],p=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),u=y=>{if(!a)return!0;let S=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(S)||y.fullName&&y.fullName.toLowerCase().includes(S)||y.description&&y.description.toLowerCase().includes(S)};if(!e){let y=1,S=!0;for(;S&&l.length<d;){let M=`/installation/repositories?per_page=${c}&page=${y}`,Be=(await v(M)).repositories||[];if(Be.length===0)break;l=l.concat(Be),S=Be.length===c,y++}let j=l.map(p).filter(u),Y=j.slice(0,d),De=j.length>Y.length,A=Y.filter(M=>M.private).length,R=Y.filter(M=>!M.private).length;return JSON.stringify({count:Y.length,repos:Y,truncated:De,privateCount:A,publicCount:R,message:`Found ${A} private and ${R} public repos`})}let m=await v(`/orgs/${e}`).then(()=>!0).catch(()=>!1),f=1,h=!0;for(;h&&l.length<d;){let y;m?y=`/orgs/${e}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${i||"updated"}&direction=${n||"desc"}`:y=`/users/${e}/repos?per_page=${c}&page=${f}&type=${r||"all"}&sort=${i||"updated"}&direction=${n||"desc"}`;let S=await v(y),j=Array.isArray(S)?S:[];if(j.length===0)break;l=l.concat(j),h=j.length===c,f++}let _=l.map(p).filter(u),g=_.slice(0,d),b=_.length>g.length;return JSON.stringify({count:g.length,repos:g,truncated:b})}case"github_create_pr":{let{owner:e,repo:r,head:i,title:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=t.base;if(!o)try{o=(await v(`/repos/${e}/${r}`)).default_branch||"main"}catch{o="main"}let a={title:String(n),head:String(i),base:String(o),body:t.body?String(t.body):"",draft:!!t.draft};try{let c=await v(`/repos/${e}/${r}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${r}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let d=String(c.message||c);if(/GitHub API 422/.test(d))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${r}`,provider:"github",skippedReason:d});throw c}}case"github_merge_pr":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=t.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(n))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${n})`});let o={merge_method:n};t.commitTitle&&(o.commit_title=String(t.commitTitle)),t.commitMessage&&(o.commit_message=String(t.commitMessage));try{let a=await v(`/repos/${e}/${r}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:e,repo:r,title:i,body:n}=t;if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await v(`/repos/${e}/${r}/issues`,{method:"POST",body:{title:i,body:n||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:r,state:i,labels:n,since:o,assignee:a,sort:c,direction:d,limit:l}=t||{};if(!e||!r)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",d||"desc"),n&&p.set("labels",Array.isArray(n)?n.join(","):n),o&&p.set("since",o),a&&p.set("assignee",a);let u=await v(`/repos/${e}/${r}/issues?${p.toString()}`),m=(Array.isArray(u)?u:[]).filter(f=>!f.pull_request).map(f=>({number:f.number,title:f.title,state:f.state,labels:(f.labels||[]).map(h=>typeof h=="string"?h:h.name),assignee:f.assignee?.login||null,assignees:(f.assignees||[]).map(h=>h.login),user:f.user?.login,comments:f.comments,url:f.html_url,createdAt:f.created_at,updatedAt:f.updated_at}));return JSON.stringify({count:m.length,issues:m})}case"github_get_issue":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/issues/${i}`);return n.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:n.number,title:n.title,body:n.body||"",state:n.state,stateReason:n.state_reason||null,labels:(n.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:n.assignee?.login||null,assignees:(n.assignees||[]).map(o=>o.login),user:n.user?.login,milestone:n.milestone?.title||null,comments:n.comments,url:n.html_url,createdAt:n.created_at,updatedAt:n.updated_at,closedAt:n.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:r,number:i,limit:n}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments?per_page=${n||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:e,repo:r,number:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await v(`/repos/${e}/${r}/issues/${i}/comments`,{method:"POST",body:{body:n}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:r,number:i,stateReason:n}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};n&&(o.state_reason=n);let a=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:e,repo:r,number:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let n=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:n.number,state:n.state,url:n.html_url})}case"github_label_issue":{let{owner:e,repo:r,number:i,labels:n,mode:o}=t||{};if(!e||!r||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(n)?n:n?[n]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await v(`/repos/${e}/${r}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await v(`/repos/${e}/${r}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await v(`/repos/${e}/${r}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let d=await v(`/repos/${e}/${r}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(d)?d:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List recent commits on a branch, optionally filtered by file path",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Max commits (default: 20)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};import{existsSync as Es}from"fs";import{fileURLToPath as Ls}from"url";import{dirname as xs,resolve as Cs}from"path";function Ps(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=xs(Ls(import.meta.url)),t=Cs(s,"..","bin","mcp-skill.mjs");return Es(t)?t:null}function qs(){let s=process.env.GITLAB_API_URL;if(s)return s.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 Js(){if(process.env.GITLAB_OAUTH_TOKEN)return{Authorization:`Bearer ${process.env.GITLAB_OAUTH_TOKEN}`};let s=process.env.GITLAB_TOKEN;if(!s)throw new Error("GitLab is not connected: set GITLAB_TOKEN (personal/project access token, api scope) or GITLAB_OAUTH_TOKEN.");return{"PRIVATE-TOKEN":s}}async function $(s,t={}){let e=/^https?:\/\//.test(s)?s:`${qs()}${s}`,r={Accept:"application/json","User-Agent":"Zibby-App",...Js(),...t.body?{"Content-Type":"application/json"}:{}},i=await fetch(e,{method:t.method||"GET",headers:r,body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`GitLab API ${i.status}: ${n.slice(0,300)}`)}return t.raw?i.text():i.json()}function St(){let s=process.env.GITLAB_API_URL;return(process.env.GITLAB_URL||process.env.GITLAB_INSTANCE_URL||(s?s.replace(/\/api\/v\d+\/?$/,""):"")||"https://gitlab.com").trim().replace(/\/+$/,"").replace(/\/api\/v\d+$/,"")}function Us(){return process.env.GITLAB_OAUTH_TOKEN||process.env.GITLAB_TOKEN||null}function L(s){let t=String(s);return/^\d+$/.test(t)?t:encodeURIComponent(t)}var ce={id:"gitlab",serverName:"gitlab",allowedTools:["mcp__gitlab__*"],requiresIntegration:N.GITLAB,envKeys:["GITLAB_TOKEN","GITLAB_OAUTH_TOKEN","GITLAB_INSTANCE_URL","GITLAB_API_URL"],description:"GitLab \u2014 merge requests, diffs, MR reviews/discussions, issues",promptFragment:`## GitLab (connected)
120
120
  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:
121
121
 
122
122
  ### Discovery
@@ -142,9 +142,9 @@ You have access to the user's GitLab projects via the REST API (cloud gitlab.com
142
142
 
143
143
  ### Notes
144
144
  - 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.
145
- - 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=Ps();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"gitlab_clone":{let{projectPath:e,projectId:r,destination:i,branch:n}=t||{},o=e&&String(e).trim();if(!o&&r!=null&&(/^\d+$/.test(String(r))?o=(await T(`/projects/${x(r)}`))?.path_with_namespace:o=String(r).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=Us();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let _=St().replace(/^https?:\/\//,""),b=`${St().startsWith("http://")?"http":"https"}://oauth2:${a}@${_}/${o}.git`,y=n?`--branch "${String(n).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${y}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let S=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:S.split(`
145
+ - 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=Ps();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/gitlab.js","gitlabSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"gitlab_clone":{let{projectPath:e,projectId:r,destination:i,branch:n}=t||{},o=e&&String(e).trim();if(!o&&r!=null&&(/^\d+$/.test(String(r))?o=(await $(`/projects/${L(r)}`))?.path_with_namespace:o=String(r).trim()),!o)return JSON.stringify({error:'projectPath (e.g. "group/repo") or a numeric projectId is required'});let a=Us();if(!a)return JSON.stringify({error:"GitLab is not connected (no token to authenticate the clone)."});let{execSync:c}=await import("child_process"),{join:d,resolve:l}=await import("path"),{existsSync:p,mkdirSync:u}=await import("fs"),m=i?l(i):l(process.cwd(),".zibby","repos"),f=o.split("/").filter(Boolean).pop(),h=d(m,f);if(u(m,{recursive:!0}),p(h))return JSON.stringify({success:!0,path:h,message:`Already cloned at ${h}`,alreadyCloned:!0});let _=St().replace(/^https?:\/\//,""),b=`${St().startsWith("http://")?"http":"https"}://oauth2:${a}@${_}/${o}.git`,y=n?`--branch "${String(n).replace(/"/g,"")}" `:"";try{c(`git clone --depth 1 ${y}${b} "${h}"`,{stdio:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});let S=c(`ls -la "${h}"`,{encoding:"utf-8"});return JSON.stringify({success:!0,path:h,message:`Cloned ${o} to ${h}`,contents:S.split(`
146
146
  `).slice(0,30).join(`
147
- `)})}catch(S){let j=String(S.message||S).split(a).join("***");return JSON.stringify({error:`Clone failed: ${j}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,r=t?.source_branch??t?.sourceBranch,{title:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let n=x(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await T(`/projects/${n}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(r),target_branch:String(o),title:String(i),description:t?.description?String(t.description):""};try{let c=await T(`/projects/${n}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),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:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:r}=t||{};if(!e||!r)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=x(e),n={};t.squash!=null&&(n.squash=!!t.squash),t.mergeCommitMessage&&(n.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(n.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await T(`/projects/${i}/merge_requests/${r}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??r,project:String(e),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:r,project:String(e),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await T(`/projects/${x(e)}/merge_requests/${r}`);return JSON.stringify({iid:i.iid,projectId:i.project_id,title:i.title,description:(i.description||"").slice(0,5e3),state:i.state,author:i.author?.username,sourceBranch:i.source_branch,targetBranch:i.target_branch,draft:i.draft??i.work_in_progress??!1,mergeStatus:i.merge_status,changesCount:i.changes_count,labels:Array.isArray(i.labels)?i.labels:[],webUrl:i.web_url,createdAt:i.created_at,updatedAt:i.updated_at,mergedAt:i.merged_at,diffRefs:i.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await T(`/projects/${x(e)}/merge_requests/${r}/changes`),n=Array.isArray(i.changes)?i.changes:[];return JSON.stringify({iid:i.iid,total:n.length,diffRefs:i.diff_refs||null,files:n.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_mrs":{let{projectId:e,state:r,targetBranch:i,sourceBranch:n,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",r||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("target_branch",i),n&&u.set("source_branch",n),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await T(`/projects/${x(e)}/merge_requests?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:e,iid:r,limit:i}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let n=await T(`/projects/${x(e)}/merge_requests/${r}/notes?per_page=${i||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(n)?n.length:0,notes:(Array.isArray(n)?n:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:e,iid:r,body:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let n=await T(`/projects/${x(e)}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:r,path:i,oldPath:n,newLine:o,oldLine:a,body:c}=t||{};if(!e||!r||!i||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=x(e),l=t.diffRefs||null;if(l||(l=(await T(`/projects/${d}/merge_requests/${r}`)).diff_refs||null),!l||!l.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 p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:i,old_path:n||i};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await T(`/projects/${d}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:r,body:i,comments:n}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let o=x(e),a=Array.isArray(n)?n.filter(u=>u&&u.path&&u.body&&(u.newLine!=null||u.oldLine!=null)):[];if(!i&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=t.diffRefs||null;a.length>0&&!c&&(c=(await T(`/projects/${o}/merge_requests/${r}`)).diff_refs||null);let d=!1;i&&(await T(`/projects/${o}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(i)}}),d=!0);let l=0,p=[];if(a.length>0&&c)for(let u of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:u.path,old_path:u.oldPath||u.path};u.newLine!=null&&(m.new_line=Number(u.newLine)),u.oldLine!=null&&(m.old_line=Number(u.oldLine));try{await T(`/projects/${o}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(u.body),position:m}}),l+=1}catch(f){p.push(`${u.path}:${u.newLine??u.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&p.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:d,inlinePosted:l,inlineErrors:p.length?p:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:r,discussionId:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let n=await T(`/projects/${x(e)}/merge_requests/${r}/discussions/${encodeURIComponent(i)}`),o=Array.isArray(n.notes)?n.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:n.id,individualNote:!!n.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:o.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:e,iid:r,discussionId:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await T(`/projects/${x(e)}/merge_requests/${r}/discussions/${encodeURIComponent(i)}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:e,limit:r}=t||{},i=Math.min(Number(r)>0?Number(r):50,200),n=new URLSearchParams;n.set("membership","true"),n.set("simple","true"),n.set("order_by","last_activity_at"),n.set("sort","desc"),n.set("per_page",String(Math.min(i+1,100))),e&&n.set("search",String(e));let o=await T(`/projects?${n.toString()}`),a=Array.isArray(o)?o:[],c=a.length>i,d=a.slice(0,i).map(l=>({fullPath:l.path_with_namespace,name:l.name,webUrl:l.web_url,defaultBranch:l.default_branch||null,visibility:l.visibility||null}));return JSON.stringify({count:d.length,truncated:c,projects:d})}case"gitlab_list_issues":{let{projectId:e,state:r,labels:i,assigneeUsername:n,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",r||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),n&&u.set("assignee_username",n),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await T(`/projects/${x(e)}/issues?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(_=>_.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await T(`/projects/${x(e)}/issues/${r}`);return JSON.stringify({iid:i.iid,projectId:i.project_id,title:i.title,description:(i.description||"").slice(0,5e3),state:i.state,labels:Array.isArray(i.labels)?i.labels:[],author:i.author?.username,assignees:(i.assignees||[]).map(n=>n.username),milestone:i.milestone?.title||null,webUrl:i.web_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:r,body:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let n=await T(`/projects/${x(e)}/issues/${r}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_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"]}}]};import{existsSync as Ms}from"fs";import{fileURLToPath as Ds}from"url";import{dirname as Bs,resolve as Ks}from"path";import{resolveIntegrationToken as Gs}from"@zibby/core/backend-client.js";function Fs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Bs(Ds(import.meta.url)),t=Ks(s,"..","bin","mcp-skill.mjs");return Ms(t)?t:null}async function ue(s,t={}){let{token:e}=await Gs("figma"),r=s.startsWith("https://")?s:`https://api.figma.com${s}`,i={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(r,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Figma API ${n.status}: ${o.slice(0,300)}`)}return n.json()}var vt={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:N.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes, comments, and render frames as PNGs",promptFragment:`## Figma (connected)
147
+ `)})}catch(S){let j=String(S.message||S).split(a).join("***");return JSON.stringify({error:`Clone failed: ${j}`})}}case"gitlab_create_mr":{let e=t?.project??t?.projectId,r=t?.source_branch??t?.sourceBranch,{title:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:'project (id or "group/repo" path), source_branch, and title are required'});let n=L(e),o=t?.target_branch??t?.targetBranch;if(!o)try{o=(await $(`/projects/${n}`)).default_branch||"main"}catch{o="main"}let a={source_branch:String(r),target_branch:String(o),title:String(i),description:t?.description?String(t.description):""};try{let c=await $(`/projects/${n}/merge_requests`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.web_url,number:c.iid,branch:a.source_branch,targetBranch:a.target_branch,project:String(e),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:a.source_branch,targetBranch:a.target_branch,project:String(e),provider:"gitlab",skippedReason:d});throw c}}case"gitlab_accept_mr":{let e=t?.project??t?.projectId,{iid:r}=t||{};if(!e||!r)return JSON.stringify({error:'project (id or "group/repo" path) and iid are required'});let i=L(e),n={};t.squash!=null&&(n.squash=!!t.squash),t.mergeCommitMessage&&(n.merge_commit_message=String(t.mergeCommitMessage)),t.mergeWhenPipelineSucceeds!=null&&(n.merge_when_pipeline_succeeds=!!t.mergeWhenPipelineSucceeds);try{let o=await $(`/projects/${i}/merge_requests/${r}/merge`,{method:"PUT",body:n});return JSON.stringify({success:!0,merged:!0,sha:o.merge_commit_sha??o.sha??null,iid:o.iid??r,project:String(e),provider:"gitlab",state:o.state})}catch(o){let a=String(o.message||o);if(/GitLab API (405|406|404)/.test(a))return JSON.stringify({success:!1,iid:r,project:String(e),provider:"gitlab",skippedReason:a});throw o}}case"gitlab_get_mr":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await $(`/projects/${L(e)}/merge_requests/${r}`);return JSON.stringify({iid:i.iid,projectId:i.project_id,title:i.title,description:(i.description||"").slice(0,5e3),state:i.state,author:i.author?.username,sourceBranch:i.source_branch,targetBranch:i.target_branch,draft:i.draft??i.work_in_progress??!1,mergeStatus:i.merge_status,changesCount:i.changes_count,labels:Array.isArray(i.labels)?i.labels:[],webUrl:i.web_url,createdAt:i.created_at,updatedAt:i.updated_at,mergedAt:i.merged_at,diffRefs:i.diff_refs||null})}case"gitlab_get_mr_changes":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await $(`/projects/${L(e)}/merge_requests/${r}/changes`),n=Array.isArray(i.changes)?i.changes:[];return JSON.stringify({iid:i.iid,total:n.length,diffRefs:i.diff_refs||null,files:n.map(o=>({oldPath:o.old_path,newPath:o.new_path,newFile:!!o.new_file,deletedFile:!!o.deleted_file,renamedFile:!!o.renamed_file,diff:typeof o.diff=="string"?o.diff.slice(0,3e3):""}))})}case"gitlab_list_mrs":{let{projectId:e,state:r,targetBranch:i,sourceBranch:n,authorUsername:o,labels:a,search:c,sort:d,orderBy:l,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",r||"opened"),u.set("per_page",String(p||20)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("target_branch",i),n&&u.set("source_branch",n),o&&u.set("author_username",o),a&&u.set("labels",Array.isArray(a)?a.join(","):a),c&&u.set("search",c);let m=await $(`/projects/${L(e)}/merge_requests?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,author:h.author?.username,sourceBranch:h.source_branch,targetBranch:h.target_branch,draft:h.draft??h.work_in_progress??!1,labels:Array.isArray(h.labels)?h.labels:[],webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,mergeRequests:f})}case"gitlab_list_mr_notes":{let{projectId:e,iid:r,limit:i}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let n=await $(`/projects/${L(e)}/merge_requests/${r}/notes?per_page=${i||50}&sort=asc&order_by=created_at`);return JSON.stringify({total:Array.isArray(n)?n.length:0,notes:(Array.isArray(n)?n:[]).map(o=>({id:o.id,author:o.author?.username,body:(o.body||"").slice(0,1e3),system:!!o.system,createdAt:o.created_at}))})}case"gitlab_post_mr_note":{let{projectId:e,iid:r,body:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let n=await $(`/projects/${L(e)}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}case"gitlab_post_mr_discussion":{let{projectId:e,iid:r,path:i,oldPath:n,newLine:o,oldLine:a,body:c}=t||{};if(!e||!r||!i||!c)return JSON.stringify({error:"projectId, iid, path, and body are required"});if(o==null&&a==null)return JSON.stringify({error:"newLine (added/changed line) or oldLine (removed/context line) is required to anchor an inline comment"});let d=L(e),l=t.diffRefs||null;if(l||(l=(await $(`/projects/${d}/merge_requests/${r}`)).diff_refs||null),!l||!l.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 p={base_sha:l.base_sha,start_sha:l.start_sha,head_sha:l.head_sha,position_type:"text",new_path:i,old_path:n||i};o!=null&&(p.new_line=Number(o)),a!=null&&(p.old_line=Number(a));try{let u=await $(`/projects/${d}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(c),position:p}});return JSON.stringify({ok:!0,discussionId:u.id})}catch(u){return JSON.stringify({ok:!1,error:`inline anchor rejected (${u.message}). The line must be part of the MR diff. Fall back to gitlab_post_mr_note with the file/line in the text.`})}}case"gitlab_create_mr_review":{let{projectId:e,iid:r,body:i,comments:n}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let o=L(e),a=Array.isArray(n)?n.filter(u=>u&&u.path&&u.body&&(u.newLine!=null||u.oldLine!=null)):[];if(!i&&a.length===0)return JSON.stringify({error:"a review needs a body and/or inline comments"});let c=t.diffRefs||null;a.length>0&&!c&&(c=(await $(`/projects/${o}/merge_requests/${r}`)).diff_refs||null);let d=!1;i&&(await $(`/projects/${o}/merge_requests/${r}/notes`,{method:"POST",body:{body:String(i)}}),d=!0);let l=0,p=[];if(a.length>0&&c)for(let u of a){let m={base_sha:c.base_sha,start_sha:c.start_sha,head_sha:c.head_sha,position_type:"text",new_path:u.path,old_path:u.oldPath||u.path};u.newLine!=null&&(m.new_line=Number(u.newLine)),u.oldLine!=null&&(m.old_line=Number(u.oldLine));try{await $(`/projects/${o}/merge_requests/${r}/discussions`,{method:"POST",body:{body:String(u.body),position:m}}),l+=1}catch(f){p.push(`${u.path}:${u.newLine??u.oldLine} \u2014 ${f.message}`)}}else a.length>0&&!c&&p.push("no diff_refs available \u2014 inline comments skipped (pass diffRefs from gitlab_get_mr)");return JSON.stringify({ok:!0,notePosted:d,inlinePosted:l,inlineErrors:p.length?p:void 0})}case"gitlab_get_discussion":{let{projectId:e,iid:r,discussionId:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and discussionId are required"});let n=await $(`/projects/${L(e)}/merge_requests/${r}/discussions/${encodeURIComponent(i)}`),o=Array.isArray(n.notes)?n.notes:[],a=o.find(d=>d.position)||null,c=a?a.position:null;return JSON.stringify({discussionId:n.id,individualNote:!!n.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:o.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:e,iid:r,discussionId:i,body:n}=t||{};if(!e||!r||!i||!n)return JSON.stringify({error:"projectId, iid, discussionId, and body are required"});let o=await $(`/projects/${L(e)}/merge_requests/${r}/discussions/${encodeURIComponent(i)}/notes`,{method:"POST",body:{body:String(n)}});return JSON.stringify({ok:!0,id:o.id,createdAt:o.created_at})}case"gitlab_list_projects":{let{query:e,limit:r}=t||{},i=Math.min(Number(r)>0?Number(r):50,200),n=new URLSearchParams;n.set("membership","true"),n.set("simple","true"),n.set("order_by","last_activity_at"),n.set("sort","desc"),n.set("per_page",String(Math.min(i+1,100))),e&&n.set("search",String(e));let o=await $(`/projects?${n.toString()}`),a=Array.isArray(o)?o:[],c=a.length>i,d=a.slice(0,i).map(l=>({fullPath:l.path_with_namespace,name:l.name,webUrl:l.web_url,defaultBranch:l.default_branch||null,visibility:l.visibility||null}));return JSON.stringify({count:d.length,truncated:c,projects:d})}case"gitlab_list_issues":{let{projectId:e,state:r,labels:i,assigneeUsername:n,authorUsername:o,updatedAfter:a,search:c,sort:d,orderBy:l,limit:p}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});let u=new URLSearchParams;u.set("state",r||"opened"),u.set("per_page",String(p||30)),u.set("order_by",l||"updated_at"),u.set("sort",d||"desc"),i&&u.set("labels",Array.isArray(i)?i.join(","):i),n&&u.set("assignee_username",n),o&&u.set("author_username",o),a&&u.set("updated_after",a),c&&u.set("search",c);let m=await $(`/projects/${L(e)}/issues?${u.toString()}`),f=(Array.isArray(m)?m:[]).map(h=>({iid:h.iid,title:h.title,state:h.state,labels:Array.isArray(h.labels)?h.labels:[],author:h.author?.username,assignees:(h.assignees||[]).map(_=>_.username),userNotesCount:h.user_notes_count,webUrl:h.web_url,createdAt:h.created_at,updatedAt:h.updated_at}));return JSON.stringify({count:f.length,issues:f})}case"gitlab_get_issue":{let{projectId:e,iid:r}=t||{};if(!e||!r)return JSON.stringify({error:"projectId and iid are required"});let i=await $(`/projects/${L(e)}/issues/${r}`);return JSON.stringify({iid:i.iid,projectId:i.project_id,title:i.title,description:(i.description||"").slice(0,5e3),state:i.state,labels:Array.isArray(i.labels)?i.labels:[],author:i.author?.username,assignees:(i.assignees||[]).map(n=>n.username),milestone:i.milestone?.title||null,webUrl:i.web_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"gitlab_add_issue_comment":{let{projectId:e,iid:r,body:i}=t||{};if(!e||!r||!i)return JSON.stringify({error:"projectId, iid, and body are required"});let n=await $(`/projects/${L(e)}/issues/${r}/notes`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:n.id,createdAt:n.created_at})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"gitlab_list_projects",description:"List the GitLab projects this token can access (the projects you are a member of), optionally filtered by a search query. Use this to discover a RELATED project worth cloning when a change's correctness depends on another accessible repo. Returns a normalized list of { fullPath, name, webUrl, defaultBranch, visibility } and a truncated flag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Optional search term matched against project name/path"},limit:{type:"number",description:"Max projects (default 50, hard max 200)"}}}},{name:"gitlab_clone",description:"Clone a GitLab repository locally (shallow) so you can read code OUTSIDE the MR diff \u2014 callers of a changed symbol, shared types/contracts, an existing util, or a cross-repo dependency. Auto-authenticates with the connected GitLab token. After cloning, use Grep/Glob/Read on the returned path. Clone SPARINGLY \u2014 only when the change's correctness depends on code beyond the diff.",input_schema:{type:"object",properties:{projectPath:{type:"string",description:'Full project path, e.g. "group/subgroup/repo" (preferred).'},projectId:{type:"string",description:"Alternatively a numeric project id (resolved to its path via the API)."},branch:{type:"string",description:"Branch to clone (default: the repo default branch)."},destination:{type:"string",description:"Destination dir (default: <workspace>/.zibby/repos/<repo>)."}}}},{name:"gitlab_create_mr",description:"Open a merge request on GitLab (POST /projects/{id}/merge_requests). The source_branch must already be pushed. Returns the REAL pr_url (the MR web_url) from GitLab \u2014 never fabricate it. Expected business outcomes (no changes between branches, an MR already exists, source==target) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},source_branch:{type:"string",description:"Source branch to merge FROM (must already be pushed)"},target_branch:{type:"string",description:"Target branch to merge INTO (default: the project's default branch)"},title:{type:"string",description:"MR title"},description:{type:"string",description:"MR description (markdown)"}},required:["project","source_branch","title"]}},{name:"gitlab_accept_mr",description:"Accept (merge) a merge request on GitLab (PUT /projects/{id}/merge_requests/{iid}/merge). Optional squash, mergeCommitMessage, mergeWhenPipelineSucceeds. Returns { success:true, merged:true, sha } with the REAL merge_commit_sha from GitLab. Expected non-mergeable outcomes (405/406 = not mergeable / WIP / conflicts / pipeline not done, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{project:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"},squash:{type:"boolean",description:"Squash the MR commits into one on merge (optional)"},mergeCommitMessage:{type:"string",description:"Custom merge commit message (optional)"},mergeWhenPipelineSucceeds:{type:"boolean",description:"Merge automatically once the pipeline succeeds (optional)"}},required:["project","iid"]}},{name:"gitlab_get_mr",description:"Get a GitLab merge request \u2014 title, description, branches, state, author, web url, and diff_refs (needed to anchor inline review comments).",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid (the per-project MR number in the URL)"}},required:["projectId","iid"]}},{name:"gitlab_get_mr_changes",description:"Get the changed files of a GitLab merge request with per-file diffs \u2014 the actual code changes to review. Also returns diff_refs for inline comments.",input_schema:{type:"object",properties:{projectId:{type:"string",description:'Project numeric id OR full path (e.g. "group/repo")'},iid:{type:"number",description:"Merge request iid"}},required:["projectId","iid"]}},{name:"gitlab_list_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"]}}]};import{existsSync as Ms}from"fs";import{fileURLToPath as Ds}from"url";import{dirname as Bs,resolve as Ks}from"path";import{resolveIntegrationToken as Gs}from"@zibby/core/backend-client.js";function Fs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Bs(Ds(import.meta.url)),t=Ks(s,"..","bin","mcp-skill.mjs");return Ms(t)?t:null}async function ue(s,t={}){let{token:e}=await Gs("figma"),r=s.startsWith("https://")?s:`https://api.figma.com${s}`,i={"X-Figma-Token":e,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{}},n=await fetch(r,{method:t.method||"GET",headers:i,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Figma API ${n.status}: ${o.slice(0,300)}`)}return n.json()}var vt={id:"figma",serverName:"figma",allowedTools:["mcp__figma__*"],requiresIntegration:N.FIGMA,envKeys:[],description:"Figma \u2014 read files, nodes, comments, and render frames as PNGs",promptFragment:`## Figma (connected)
148
148
  You have read access to the user's Figma files via the Figma REST API. Tools:
149
149
 
150
150
  ### Identity
@@ -162,7 +162,7 @@ You have read access to the user's Figma files via the Figma REST API. Tools:
162
162
 
163
163
  ### Notes
164
164
  - The fileKey is NOT the file name \u2014 it's the opaque id segment in the URL.
165
- - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes output.`,resolve(){let s=Fs();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"figma_get_me":{let e=await ue("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let{fileKey:e,depth:r}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let i=`/v1/files/${encodeURIComponent(e)}`;if(r!=null){let a=Number(r);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let n=await ue(i),o=(n.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:n.name,lastModified:n.lastModified,version:n.version,editorType:n.editorType,role:n.role,pages:o})}case"figma_get_nodes":{let{fileKey:e,ids:r,depth:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;if(a.set("ids",o.join(",")),i!=null){let l=Number(i);!Number.isNaN(l)&&l>0&&a.set("depth",String(l))}let c=await ue(`/v1/files/${encodeURIComponent(e)}/nodes?${a.toString()}`),d={};for(let[l,p]of Object.entries(c.nodes||{}))d[l]=p?.document?{id:p.document.id,name:p.document.name,type:p.document.type,document:p.document}:p;return JSON.stringify({name:c.name,nodes:d})}case"figma_render_png":{let{fileKey:e,ids:r,scale:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;a.set("ids",o.join(",")),a.set("format","png");let c=Number(i);(Number.isNaN(c)||c<=0)&&(c=1),c=Math.min(4,Math.max(.01,c)),a.set("scale",String(c));let d=await ue(`/v1/images/${encodeURIComponent(e)}?${a.toString()}`);return d.err?JSON.stringify({error:`Figma render error: ${d.err}`}):JSON.stringify({scale:c,format:"png",images:d.images||{}})}case"figma_get_comments":{let{fileKey:e}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let i=((await ue(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(n=>({id:n.id,message:n.message,user:n.user?.handle,createdAt:n.created_at,resolvedAt:n.resolved_at||null,parentId:n.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree by fileKey (the opaque id segment in a figma.com/file/<fileKey>/ or /design/<fileKey>/ URL \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'The file key from the Figma URL (e.g. "aBcD1234" in figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch (e.g. ["1:23","4:56"]). A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to PNG and return the image URLs (a map of nodeId \u2192 URL). Use this to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (e.g. ["1:23"]). A comma-separated string is also accepted.'},scale:{type:"number",description:"Render scale, 0.01\u20134 (default 1). 2 for retina/hi-dpi."}},required:["fileKey","ids"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"}},required:["fileKey"]}}]};import{existsSync as Hs}from"fs";import{fileURLToPath as zs}from"url";import{dirname as Ws,resolve as Ys}from"path";function Zs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ws(zs(import.meta.url)),t=Ys(s,"..","bin","mcp-skill.mjs");return Hs(t)?t:null}var Vs=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Qs(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let s=process.env.LINEAR_API_KEY;if(!s)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return s}async function M(s,t={}){let e=await fetch(Vs,{method:"POST",headers:{Authorization:Qs(),"Content-Type":"application/json"},body:JSON.stringify({query:s,variables:t})});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${i.slice(0,300)}`)}let r=await e.json().catch(()=>null);if(!r)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(r.errors)&&r.errors.length){let i=r.errors.map(n=>n?.message||String(n)).join("; ");throw new Error(`Linear GraphQL error: ${i.slice(0,300)}`)}return r.data}function fe(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Xs(s,t){let e=fe(s),r=fe(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},n=i(e),o=i(r),a=0,c=0,d=0;for(let l of n.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of n.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+d)}function ei(s,t){let e=Array.isArray(s)?s:[];if(!e.length)return{state:null,strategy:"no-states"};let r=fe(t);if(!r)return{state:null,strategy:"no-target"};let i=e.find(a=>fe(a.name)===r);if(i)return{state:i,strategy:"exact"};let n={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(n)){if(!c.some(l=>fe(l)===r))continue;let d=e.find(l=>l.type===a);if(d)return{state:d,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Xs(t,a.name)})).sort((a,c)=>c.score-a.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var ti=`
165
+ - Node ids look like "1:23" and come from figma_get_file / figma_get_nodes output.`,resolve(){let s=Fs();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/figma.js","figmaSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"figma_get_me":{let e=await ue("/v1/me");return JSON.stringify({id:e.id,handle:e.handle,email:e.email,imgUrl:e.img_url})}case"figma_get_file":{let{fileKey:e,depth:r}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let i=`/v1/files/${encodeURIComponent(e)}`;if(r!=null){let a=Number(r);!Number.isNaN(a)&&a>0&&(i+=`?depth=${a}`)}let n=await ue(i),o=(n.document?.children||[]).map(a=>({id:a.id,name:a.name,type:a.type,childCount:Array.isArray(a.children)?a.children.length:0,children:(a.children||[]).slice(0,50).map(c=>({id:c.id,name:c.name,type:c.type}))}));return JSON.stringify({name:n.name,lastModified:n.lastModified,version:n.version,editorType:n.editorType,role:n.role,pages:o})}case"figma_get_nodes":{let{fileKey:e,ids:r,depth:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;if(a.set("ids",o.join(",")),i!=null){let l=Number(i);!Number.isNaN(l)&&l>0&&a.set("depth",String(l))}let c=await ue(`/v1/files/${encodeURIComponent(e)}/nodes?${a.toString()}`),d={};for(let[l,p]of Object.entries(c.nodes||{}))d[l]=p?.document?{id:p.document.id,name:p.document.name,type:p.document.type,document:p.document}:p;return JSON.stringify({name:c.name,nodes:d})}case"figma_render_png":{let{fileKey:e,ids:r,scale:i}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let o=(Array.isArray(r)?r:r?String(r).split(","):[]).map(l=>String(l).trim()).filter(Boolean);if(o.length===0)return JSON.stringify({error:"ids is required (comma-separated or array of node ids)"});let a=new URLSearchParams;a.set("ids",o.join(",")),a.set("format","png");let c=Number(i);(Number.isNaN(c)||c<=0)&&(c=1),c=Math.min(4,Math.max(.01,c)),a.set("scale",String(c));let d=await ue(`/v1/images/${encodeURIComponent(e)}?${a.toString()}`);return d.err?JSON.stringify({error:`Figma render error: ${d.err}`}):JSON.stringify({scale:c,format:"png",images:d.images||{}})}case"figma_get_comments":{let{fileKey:e}=t||{};if(!e)return JSON.stringify({error:"fileKey is required"});let i=((await ue(`/v1/files/${encodeURIComponent(e)}/comments`)).comments||[]).map(n=>({id:n.id,message:n.message,user:n.user?.handle,createdAt:n.created_at,resolvedAt:n.resolved_at||null,parentId:n.parent_id||null}));return JSON.stringify({count:i.length,comments:i})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"figma_get_me",description:"Get the authenticated Figma user profile (handle, email, id)",input_schema:{type:"object",properties:{}}},{name:"figma_get_file",description:"Get a Figma file's document tree by fileKey (the opaque id segment in a figma.com/file/<fileKey>/ or /design/<fileKey>/ URL \u2014 NOT the file name). Returns a summarized map of pages and their top-level frames/nodes. Use figma_get_nodes to drill into a specific node.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:'The file key from the Figma URL (e.g. "aBcD1234" in figma.com/design/aBcD1234/My-File)'},depth:{type:"number",description:"Optional: limit how deep the node tree is traversed (1-2 is usually enough to list pages/frames). Omit for the full tree."}},required:["fileKey"]}},{name:"figma_get_nodes",description:"Get specific nodes from a Figma file by their node ids. Use after figma_get_file to inspect a particular frame/component without re-fetching the whole file.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to fetch (e.g. ["1:23","4:56"]). A comma-separated string is also accepted.'},depth:{type:"number",description:"Optional: limit traversal depth within each node."}},required:["fileKey","ids"]}},{name:"figma_render_png",description:"Render one or more Figma nodes to PNG and return the image URLs (a map of nodeId \u2192 URL). Use this to show or download a visual of a frame/component.",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"},ids:{type:"array",items:{type:"string"},description:'Node ids to render (e.g. ["1:23"]). A comma-separated string is also accepted.'},scale:{type:"number",description:"Render scale, 0.01\u20134 (default 1). 2 for retina/hi-dpi."}},required:["fileKey","ids"]}},{name:"figma_get_comments",description:"Read the comments on a Figma file",input_schema:{type:"object",properties:{fileKey:{type:"string",description:"The file key from the Figma URL"}},required:["fileKey"]}}]};import{existsSync as Hs}from"fs";import{fileURLToPath as zs}from"url";import{dirname as Ws,resolve as Ys}from"path";function Zs(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ws(zs(import.meta.url)),t=Ys(s,"..","bin","mcp-skill.mjs");return Hs(t)?t:null}var Vs=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Qs(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let s=process.env.LINEAR_API_KEY;if(!s)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return s}async function D(s,t={}){let e=await fetch(Vs,{method:"POST",headers:{Authorization:Qs(),"Content-Type":"application/json"},body:JSON.stringify({query:s,variables:t})});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${i.slice(0,300)}`)}let r=await e.json().catch(()=>null);if(!r)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(r.errors)&&r.errors.length){let i=r.errors.map(n=>n?.message||String(n)).join("; ");throw new Error(`Linear GraphQL error: ${i.slice(0,300)}`)}return r.data}function fe(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Xs(s,t){let e=fe(s),r=fe(t);if(!e||!r)return 0;if(e===r)return 1;if(e.length===1||r.length===1)return e===r?1:0;let i=l=>{let p=new Map;for(let u=0;u<l.length-1;u++){let m=l.slice(u,u+2);p.set(m,(p.get(m)||0)+1)}return p},n=i(e),o=i(r),a=0,c=0,d=0;for(let l of n.values())c+=l;for(let l of o.values())d+=l;for(let[l,p]of n.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+d)}function ei(s,t){let e=Array.isArray(s)?s:[];if(!e.length)return{state:null,strategy:"no-states"};let r=fe(t);if(!r)return{state:null,strategy:"no-target"};let i=e.find(a=>fe(a.name)===r);if(i)return{state:i,strategy:"exact"};let n={backlog:["backlog"],unstarted:["todo","unstarted","open"],started:["inprogress","started","doing","wip"],completed:["done","completed","closed","resolved","fixed"],canceled:["canceled","cancelled","wontfix","won'tfix"],triage:["triage"]};for(let[a,c]of Object.entries(n)){if(!c.some(l=>fe(l)===r))continue;let d=e.find(l=>l.type===a);if(d)return{state:d,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Xs(t,a.name)})).sort((a,c)=>c.score-a.score);return o[0]&&o[0].score>=.5?{state:o[0].s,strategy:"fuzzy"}:{state:null,strategy:"no-match"}}var ti=`
166
166
  id
167
167
  identifier
168
168
  number
@@ -194,32 +194,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
194
194
 
195
195
  ### Notes
196
196
  - Always resolve a team first when you need states or want to create/move issues by state name \u2014 states only make sense within their team.
197
- - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);process.env.LINEAR_API_URL&&(s.LINEAR_API_URL=process.env.LINEAR_API_URL);let t=Zs();return t?{type:"stdio",command:"node",args:[t,"../dist/linear.js","linearSkill"],env:s,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:s,description:this.description}},async handleToolCall(s,t){try{switch(s){case"linear_list_teams":{let r=(await M(`
197
+ - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);process.env.LINEAR_API_URL&&(s.LINEAR_API_URL=process.env.LINEAR_API_URL);let t=Zs();return t?{type:"stdio",command:"node",args:[t,"../dist/linear.js","linearSkill"],env:s,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:s,description:this.description}},async handleToolCall(s,t){try{switch(s){case"linear_list_teams":{let r=(await D(`
198
198
  query Teams($first: Int) {
199
199
  teams(first: $first) {
200
200
  nodes { id key name description }
201
201
  }
202
202
  }
203
- `,{first:t?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:r.length,teams:r})}case"linear_list_states":{let{teamId:e,teamKey:r}=t||{},i=e;if(!i&&r&&(i=await Nt(r)),i){let c=(await M(`
203
+ `,{first:t?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:r.length,teams:r})}case"linear_list_states":{let{teamId:e,teamKey:r}=t||{},i=e;if(!i&&r&&(i=await Nt(r)),i){let c=(await D(`
204
204
  query States($teamId: String!) {
205
205
  team(id: $teamId) {
206
206
  id key name
207
207
  states { nodes { id name type color position } }
208
208
  }
209
209
  }
210
- `,{teamId:i}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await M(`
210
+ `,{teamId:i}))?.team,d=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:d.length,states:d})}let o=(await D(`
211
211
  query AllStates($first: Int) {
212
212
  workflowStates(first: $first) {
213
213
  nodes { id name type color team { id key name } }
214
214
  }
215
215
  }
216
- `,{first:t?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=t||{},i=(await M(`
216
+ `,{first:t?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=t||{},i=(await D(`
217
217
  query Labels($first: Int, $filter: IssueLabelFilter) {
218
218
  issueLabels(first: $first, filter: $filter) {
219
219
  nodes { id name color team { id key } }
220
220
  }
221
221
  }
222
- `,{first:t?.limit||100,filter:e?{team:{id:{eq:e}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:i.length,labels:i})}case"linear_list_issues":{let{teamId:e,teamKey:r,stateId:i,stateName:n,label:o,assigneeId:a,updatedAfter:c,limit:d}=t||{},l={},p=e;!p&&r&&(p=await Nt(r)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:n&&(l.state={name:{eqIgnoreCase:n}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let m=((await M(`
222
+ `,{first:t?.limit||100,filter:e?{team:{id:{eq:e}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:i.length,labels:i})}case"linear_list_issues":{let{teamId:e,teamKey:r,stateId:i,stateName:n,label:o,assigneeId:a,updatedAfter:c,limit:d}=t||{},l={},p=e;!p&&r&&(p=await Nt(r)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:n&&(l.state={name:{eqIgnoreCase:n}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let m=((await D(`
223
223
  query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
224
224
  issues(first: $first, filter: $filter, orderBy: $orderBy) {
225
225
  nodes {
@@ -236,7 +236,7 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
236
236
  comments(first: ${Number(t?.limit)||50}) {
237
237
  nodes { id body createdAt updatedAt user { id name displayName } }
238
238
  }
239
- `);if(!r)return JSON.stringify({error:`Issue not found: ${e}`});let i=(r.comments?.nodes||[]).map(n=>({id:n.id,author:n.user?.displayName||n.user?.name||"Unknown",body:n.body||"",createdAt:n.createdAt,updatedAt:n.updatedAt})).sort((n,o)=>String(o.createdAt).localeCompare(String(n.createdAt)));return JSON.stringify({count:i.length,issue:r.identifier,comments:i})}case"linear_add_comment":{let e=t?.issueId||t?.identifier||t?.issueKey,r=t?.body;if(!e||!r)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await me(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await M(`
239
+ `);if(!r)return JSON.stringify({error:`Issue not found: ${e}`});let i=(r.comments?.nodes||[]).map(n=>({id:n.id,author:n.user?.displayName||n.user?.name||"Unknown",body:n.body||"",createdAt:n.createdAt,updatedAt:n.updatedAt})).sort((n,o)=>String(o.createdAt).localeCompare(String(n.createdAt)));return JSON.stringify({count:i.length,issue:r.identifier,comments:i})}case"linear_add_comment":{let e=t?.issueId||t?.identifier||t?.issueKey,r=t?.body;if(!e||!r)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await me(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await D(`
240
240
  mutation AddComment($input: CommentCreateInput!) {
241
241
  commentCreate(input: $input) {
242
242
  success
@@ -247,31 +247,31 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
247
247
  id identifier
248
248
  state { id name type }
249
249
  team { id key states { nodes { id name type position } } }
250
- `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=r,d=r?{strategy:"explicit-id"}:null;if(!c){let u=String(i||n||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,_)=>(h.position||0)-(_.position||0));if(!u)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=ei(m,u);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let p=(await M(`
250
+ `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=r,d=r?{strategy:"explicit-id"}:null;if(!c){let u=String(i||n||o||"").trim(),m=(a.team?.states?.nodes||[]).slice().sort((h,_)=>(h.position||0)-(_.position||0));if(!u)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});let f=ei(m,u);if(!f.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${u}" in team ${a.team?.key}`,issue:a.identifier,availableStates:m.map(h=>({id:h.id,name:h.name,type:h.type}))});c=f.state.id,d={strategy:f.strategy,matchedName:f.state.name}}let p=(await D(`
251
251
  mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
252
252
  issueUpdate(id: $id, input: $input) {
253
253
  success
254
254
  issue { id identifier state { id name type } }
255
255
  }
256
256
  }
257
- `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let e=t?.issueId||t?.identifier||t?.issueKey,{url:r,title:i,subtitle:n}=t||{};if(!e||!r)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await me(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await M(`
257
+ `,{id:a.id,input:{stateId:c}}))?.issueUpdate;return JSON.stringify({ok:!!p?.success,issue:p?.issue?.identifier||a.identifier,stateAfter:p?.issue?.state?.name||null,stateTypeAfter:p?.issue?.state?.type||null,resolution:d})}case"linear_link_attachment":{let e=t?.issueId||t?.identifier||t?.issueKey,{url:r,title:i,subtitle:n}=t||{};if(!e||!r)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await me(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await D(`
258
258
  mutation LinkAttachment($input: AttachmentCreateInput!) {
259
259
  attachmentCreate(input: $input) {
260
260
  success
261
261
  attachment { id url title }
262
262
  }
263
263
  }
264
- `,{input:{issueId:o.id,url:r,title:i||r,subtitle:n||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"linear_list_teams",description:"List Linear teams (id, key, name). Needed to scope workflow states and issue queries.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Max teams (default: 50)"}}}},{name:"linear_list_states",description:"List a team's workflow states (id, name, type: backlog|unstarted|started|completed|canceled|triage). Linear states are PER-TEAM. Omit team to list all states across the workspace.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved to an id if teamId omitted"},limit:{type:"number",description:"Max states when listing workspace-wide (default: 200)"}}}},{name:"linear_list_labels",description:"List issue labels, optionally scoped to a team.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Optional team uuid to scope labels"},limit:{type:"number",description:"Max labels (default: 100)"}}}},{name:"linear_list_issues",description:"List/poll Linear issues filtered by team, state, label, assignee, and an updatedAfter cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved if teamId omitted"},stateId:{type:"string",description:"Filter by workflow state uuid"},stateName:{type:"string",description:"Filter by state name (case-insensitive)"},label:{type:"string",description:"Filter by label name (case-insensitive)"},assigneeId:{type:"string",description:"Filter by assignee uuid"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},limit:{type:"number",description:"Max issues (default: 30)"}}}},{name:"linear_get_issue",description:"Get a single Linear issue by identifier (e.g. ENG-123) or internal uuid \u2014 title, description, state, labels, assignee, url.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"}}}},{name:"linear_get_comments",description:"Get comments on a Linear issue (newest first).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},limit:{type:"number",description:"Max comments (default: 50)"}}}},{name:"linear_add_comment",description:"Add a comment to a Linear issue (markdown supported).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},body:{type:"string",description:"Comment body (markdown)"}},required:["body"]}},{name:"linear_update_state",description:"Move a Linear issue to a different workflow state. Pass a state NAME (toStatus/stateName) and the tool resolves it to the issue's team's matching state id (exact -> type-alias -> fuzzy), or pass stateId directly. Linear has no transitions \u2014 this sets the state.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},stateId:{type:"string",description:"Target workflow state uuid (skips name resolution)"},stateName:{type:"string",description:'Target state name (e.g. "In Progress", "Done")'},toStatus:{type:"string",description:"Alias for stateName"}}}},{name:"linear_link_attachment",description:"Attach a URL (e.g. a GitHub PR) to a Linear issue via native attachments. Use this for PR links; fall back to linear_add_comment if it fails.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},url:{type:"string",description:"The URL to attach (e.g. a PR link)"},title:{type:"string",description:"Attachment title (defaults to the URL)"},subtitle:{type:"string",description:"Optional attachment subtitle"}},required:["url"]}}]};async function Nt(s){return(await M(`
264
+ `,{input:{issueId:o.id,url:r,title:i||r,subtitle:n||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"linear_list_teams",description:"List Linear teams (id, key, name). Needed to scope workflow states and issue queries.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Max teams (default: 50)"}}}},{name:"linear_list_states",description:"List a team's workflow states (id, name, type: backlog|unstarted|started|completed|canceled|triage). Linear states are PER-TEAM. Omit team to list all states across the workspace.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved to an id if teamId omitted"},limit:{type:"number",description:"Max states when listing workspace-wide (default: 200)"}}}},{name:"linear_list_labels",description:"List issue labels, optionally scoped to a team.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Optional team uuid to scope labels"},limit:{type:"number",description:"Max labels (default: 100)"}}}},{name:"linear_list_issues",description:"List/poll Linear issues filtered by team, state, label, assignee, and an updatedAfter cursor. Returns newest-updated first.",input_schema:{type:"object",properties:{teamId:{type:"string",description:"Team uuid"},teamKey:{type:"string",description:"Team key (e.g. ENG); resolved if teamId omitted"},stateId:{type:"string",description:"Filter by workflow state uuid"},stateName:{type:"string",description:"Filter by state name (case-insensitive)"},label:{type:"string",description:"Filter by label name (case-insensitive)"},assigneeId:{type:"string",description:"Filter by assignee uuid"},updatedAfter:{type:"string",description:"ISO-8601 timestamp; only issues updated after this (polling cursor)"},limit:{type:"number",description:"Max issues (default: 30)"}}}},{name:"linear_get_issue",description:"Get a single Linear issue by identifier (e.g. ENG-123) or internal uuid \u2014 title, description, state, labels, assignee, url.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"}}}},{name:"linear_get_comments",description:"Get comments on a Linear issue (newest first).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},limit:{type:"number",description:"Max comments (default: 50)"}}}},{name:"linear_add_comment",description:"Add a comment to a Linear issue (markdown supported).",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},body:{type:"string",description:"Comment body (markdown)"}},required:["body"]}},{name:"linear_update_state",description:"Move a Linear issue to a different workflow state. Pass a state NAME (toStatus/stateName) and the tool resolves it to the issue's team's matching state id (exact -> type-alias -> fuzzy), or pass stateId directly. Linear has no transitions \u2014 this sets the state.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},stateId:{type:"string",description:"Target workflow state uuid (skips name resolution)"},stateName:{type:"string",description:'Target state name (e.g. "In Progress", "Done")'},toStatus:{type:"string",description:"Alias for stateName"}}}},{name:"linear_link_attachment",description:"Attach a URL (e.g. a GitHub PR) to a Linear issue via native attachments. Use this for PR links; fall back to linear_add_comment if it fails.",input_schema:{type:"object",properties:{identifier:{type:"string",description:"Issue identifier, e.g. ENG-123"},issueId:{type:"string",description:"Internal issue uuid (alternative to identifier)"},url:{type:"string",description:"The URL to attach (e.g. a PR link)"},title:{type:"string",description:"Attachment title (defaults to the URL)"},subtitle:{type:"string",description:"Optional attachment subtitle"}},required:["url"]}}]};async function Nt(s){return(await D(`
265
265
  query TeamByKey($filter: TeamFilter) {
266
266
  teams(first: 1, filter: $filter) { nodes { id key } }
267
267
  }
268
- `,{filter:{key:{eq:s}}}))?.teams?.nodes?.[0]?.id||null}async function me(s,t=ti){let e=String(s).trim(),r=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(r){let n=r[1].toUpperCase(),o=Number(r[2]);return(await M(`
268
+ `,{filter:{key:{eq:s}}}))?.teams?.nodes?.[0]?.id||null}async function me(s,t=ti){let e=String(s).trim(),r=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(r){let n=r[1].toUpperCase(),o=Number(r[2]);return(await D(`
269
269
  query IssueByIdentifier($filter: IssueFilter) {
270
270
  issues(first: 1, filter: $filter) {
271
271
  nodes { ${t} }
272
272
  }
273
273
  }
274
- `,{filter:{number:{eq:o},team:{key:{eq:n}}}}))?.issues?.nodes?.[0]||null}return(await M(`
274
+ `,{filter:{number:{eq:o},team:{key:{eq:n}}}}))?.issues?.nodes?.[0]||null}return(await D(`
275
275
  query IssueById($id: String!) {
276
276
  issue(id: $id) { ${t} }
277
277
  }
@@ -303,32 +303,35 @@ You may have access to the user's OpenDesign workspace (the Zibby-managed design
303
303
 
304
304
  ### Notes
305
305
  - A design artifact lookup ALWAYS needs its projectId (it scopes the query).
306
- - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let s=ai();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/opendesign.js","opendesignSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"opendesign_health":{let{baseUrl:e}=await Ot(),r=await fetch(`${e}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await At(r,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let e=await V("/projects");return JSON.stringify(e)}case"opendesign_get_project":{let e=t?.id||t?.projectId;if(!e)return JSON.stringify({error:"id is required"});let r=await V(`/projects/${encodeURIComponent(e)}`);return JSON.stringify(r)}case"opendesign_list_designs":{let e=t?.projectId;if(!e)return JSON.stringify({error:"projectId is required"});let r=await V("/live-artifacts",{query:{projectId:e}});return JSON.stringify(r)}case"opendesign_get_design":{let e=t?.id,r=t?.projectId;if(!e)return JSON.stringify({error:"id is required"});if(!r)return JSON.stringify({error:"projectId is required"});let i=await V(`/live-artifacts/${encodeURIComponent(e)}`,{query:{projectId:r}});return JSON.stringify(i)}case"opendesign_export_pdf":{let e=t?.projectId||t?.id,{fileName:r,title:i,deck:n}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"fileName is required"});let o={fileName:r};i!==void 0&&(o.title=i),n!==void 0&&(o.deck=n);let a=await V(`/projects/${encodeURIComponent(e)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let e=t?.projectId||t?.id,r=t?.path;if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"path is required (the export sub-path)"});let n=String(r).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await V(`/projects/${encodeURIComponent(e)}/export/${n}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:e,message:r,projectId:i,conversationId:n,model:o}=t||{};if(!e)return JSON.stringify({error:"agentId is required"});if(!r)return JSON.stringify({error:"message is required"});let a={agentId:e,message:r};i!==void 0&&(a.projectId=i),n!==void 0&&(a.conversationId=n),o!==void 0&&(a.model=o);let c=await V("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let e=t?.id||t?.runId;if(!e)return JSON.stringify({error:"id (runId) is required"});let r=await V(`/runs/${encodeURIComponent(e)}`);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as ci}from"fs";import{fileURLToPath as li}from"url";import{dirname as di,resolve as pi}from"path";import{resolveIntegrationToken as ui}from"@zibby/core/backend-client.js";function mi(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let s=di(li(import.meta.url)),t=pi(s,"..","bin","mcp-slack.mjs");return ci(t)?t:null}async function J(s,t={}){let{token:e}=await ui("slack"),r=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(s),i=`https://slack.com/api/${s}`,n={Authorization:`Bearer ${e}`},o;if(r){let d=new URLSearchParams(t).toString();d&&(i+=`?${d}`)}else n["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(t);let c=await(await fetch(i,{method:r?"GET":"POST",headers:n,body:o})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var D={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:N.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
306
+ - After opendesign_cli_run, poll opendesign_cli_status with the returned runId until the run is no longer running.`,resolve(){let s=ai();if(!s)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s,"../dist/opendesign.js","opendesignSkill"],env:t,description:this.description,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"opendesign_health":{let{baseUrl:e}=await Ot(),r=await fetch(`${e}/api/health`,{method:"GET",headers:{Accept:"application/json"}}),i=await At(r,"OpenDesign");return JSON.stringify({ok:!0,health:i})}case"opendesign_list_projects":{let e=await V("/projects");return JSON.stringify(e)}case"opendesign_get_project":{let e=t?.id||t?.projectId;if(!e)return JSON.stringify({error:"id is required"});let r=await V(`/projects/${encodeURIComponent(e)}`);return JSON.stringify(r)}case"opendesign_list_designs":{let e=t?.projectId;if(!e)return JSON.stringify({error:"projectId is required"});let r=await V("/live-artifacts",{query:{projectId:e}});return JSON.stringify(r)}case"opendesign_get_design":{let e=t?.id,r=t?.projectId;if(!e)return JSON.stringify({error:"id is required"});if(!r)return JSON.stringify({error:"projectId is required"});let i=await V(`/live-artifacts/${encodeURIComponent(e)}`,{query:{projectId:r}});return JSON.stringify(i)}case"opendesign_export_pdf":{let e=t?.projectId||t?.id,{fileName:r,title:i,deck:n}=t||{};if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"fileName is required"});let o={fileName:r};i!==void 0&&(o.title=i),n!==void 0&&(o.deck=n);let a=await V(`/projects/${encodeURIComponent(e)}/export/pdf`,{method:"POST",body:o});return JSON.stringify(a)}case"opendesign_export_html":{let e=t?.projectId||t?.id,r=t?.path;if(!e)return JSON.stringify({error:"projectId is required"});if(!r)return JSON.stringify({error:"path is required (the export sub-path)"});let n=String(r).replace(/^\/+/,"").split("/").map(a=>encodeURIComponent(a)).join("/"),o=await V(`/projects/${encodeURIComponent(e)}/export/${n}`,{query:{inline:1}});return JSON.stringify(o)}case"opendesign_cli_run":{let{agentId:e,message:r,projectId:i,conversationId:n,model:o}=t||{};if(!e)return JSON.stringify({error:"agentId is required"});if(!r)return JSON.stringify({error:"message is required"});let a={agentId:e,message:r};i!==void 0&&(a.projectId=i),n!==void 0&&(a.conversationId=n),o!==void 0&&(a.model=o);let c=await V("/runs",{method:"POST",body:a});return JSON.stringify(c)}case"opendesign_cli_status":{let e=t?.id||t?.runId;if(!e)return JSON.stringify({error:"id (runId) is required"});let r=await V(`/runs/${encodeURIComponent(e)}`);return JSON.stringify(r)}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"opendesign_health",description:"Probe the OpenDesign instance (GET /api/health, no auth). Use to confirm connectivity before other calls.",input_schema:{type:"object",properties:{}}},{name:"opendesign_list_projects",description:"List the projects in the OpenDesign workspace.",input_schema:{type:"object",properties:{}}},{name:"opendesign_get_project",description:"Get a single OpenDesign project by id.",input_schema:{type:"object",properties:{id:{type:"string",description:"The project id."}},required:["id"]}},{name:"opendesign_list_designs",description:"List the live design artifacts in an OpenDesign project. Requires the projectId, which scopes the query.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id whose designs to list."}},required:["projectId"]}},{name:"opendesign_get_design",description:"Get a single live design artifact by id. Requires both the design id and its projectId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The live-artifact (design) id."},projectId:{type:"string",description:"The project id the design belongs to (scopes the lookup)."}},required:["id","projectId"]}},{name:"opendesign_export_pdf",description:"Export an OpenDesign project deck to PDF. Returns the export result (e.g. a download URL/path).",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},fileName:{type:"string",description:"The output PDF file name."},title:{type:"string",description:"Optional deck title for the PDF."},deck:{description:"Optional deck payload/override to render instead of the project's current deck."}},required:["projectId","fileName"]}},{name:"opendesign_export_html",description:"Fetch an OpenDesign project's HTML export by sub-path (requested inline). Requires projectId and the export path.",input_schema:{type:"object",properties:{projectId:{type:"string",description:"The project id to export."},path:{type:"string",description:'The export sub-path under /projects/:id/export/ (e.g. "index.html" or a slide path).'}},required:["projectId","path"]}},{name:"opendesign_cli_run",description:"Start an OpenDesign agent run. Returns a runId; poll opendesign_cli_status with it until the run finishes.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"The OpenDesign agent id to run."},message:{type:"string",description:"The instruction/message to send to the agent."},projectId:{type:"string",description:"Optional project id to scope the run to."},conversationId:{type:"string",description:"Optional conversation id to continue an existing thread."},model:{type:"string",description:"Optional model id override for the run."}},required:["agentId","message"]}},{name:"opendesign_cli_status",description:"Poll the status of an OpenDesign agent run by its runId.",input_schema:{type:"object",properties:{id:{type:"string",description:"The runId returned by opendesign_cli_run."}},required:["id"]}}]};import{existsSync as ci}from"fs";import{fileURLToPath as li}from"url";import{dirname as di,resolve as pi}from"path";import{resolveIntegrationToken as ui}from"@zibby/core/backend-client.js";function mi(){if(process.env.MCP_SLACK_PATH)return process.env.MCP_SLACK_PATH;let s=di(li(import.meta.url)),t=pi(s,"..","bin","mcp-slack.mjs");return ci(t)?t:null}async function U(s,t={}){let{token:e}=await ui("slack"),r=["conversations.list","users.list","users.profile.get","users.lookupByEmail","usergroups.list","usergroups.users.list","conversations.history","conversations.replies"].includes(s),i=`https://slack.com/api/${s}`,n={Authorization:`Bearer ${e}`},o;if(r){let d=new URLSearchParams(t).toString();d&&(i+=`?${d}`)}else n["Content-Type"]="application/json; charset=utf-8",o=JSON.stringify(t);let c=await(await fetch(i,{method:r?"GET":"POST",headers:n,body:o})).json();if(!c.ok)throw new Error(`Slack API error: ${c.error}`);return c}var x={id:"slack",serverName:"slack",allowedTools:["mcp__slack__*"],requiresIntegration:N.SLACK,envKeys:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"],description:"Slack MCP Server",promptFragment:`## Slack (connected)
307
307
  You have access to the user's Slack workspace. Use these tools:
308
308
  - slack_list_channels, slack_post_message, slack_reply_to_thread
309
309
  - slack_add_reaction, slack_get_channel_history, slack_get_thread_replies
310
310
  - slack_get_users, slack_get_user_profile
311
311
  - slack_lookup_user_by_email (precise email\u2192user_id, prefer this over scanning slack_get_users)
312
- - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let s=mi();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"slack_list_channels":{let e=await J("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(r=>({id:r.id,name:r.name,topic:r.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await J("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await J("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await J("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await J("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await J("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_users":{let e=await J("users.list",{limit:100});return JSON.stringify({users:(e.members||[]).filter(r=>!r.is_bot&&!r.deleted).map(r=>({id:r.id,name:r.real_name||r.name}))})}case"slack_get_user_profile":{if(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await J("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await J("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await J("usergroups.list",{});return JSON.stringify({usergroups:(e.usergroups||[]).map(r=>({id:r.id,handle:r.handle,name:r.name,description:r.description||"",user_count:Number(r.user_count||0)}))})}case"slack_get_usergroup_members":{if(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await J("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),i=[],n,o=5;for(let c=0;c<o;c+=1){let d={limit:200};n&&(d.cursor=n);let l=await J("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(n=l.response_metadata?.next_cursor,!n)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(e)&&(u+=100-Math.abs(d.length-e.length)),l.includes(e)&&(u+=60-Math.abs(l.length-e.length)),p.includes(e)&&(u+=30-Math.abs(p.length-e.length)),(d===e||l===e)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,r).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as fi}from"fs";import{fileURLToPath as hi}from"url";import{dirname as yi,resolve as gi}from"path";import{resolveIntegrationToken as _i}from"@zibby/core/backend-client.js";function bi(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let s=yi(hi(import.meta.url)),t=gi(s,"..","bin","mcp-lark.mjs");return fi(t)?t:null}var ki=6e3*1e3,he=null;async function wi(){let{appId:s,appSecret:t,host:e}=await _i("lark");if(he&&he.appId===s&&he.expiresAt>Date.now())return{token:he.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:s,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return he={token:i.tenant_access_token,expiresAt:Date.now()+ki,appId:s},{token:i.tenant_access_token,host:e}}async function re(s,t,e={}){let{token:r,host:i}=await wi(),n=`${i}${t}`,o={method:s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};s!=="GET"&&(o.body=JSON.stringify(e));let c=await(await fetch(n,o)).json();if(c.code!==0)throw new Error(`Lark API ${t} error: ${c.msg||c.code}`);return c.data||{}}function $t(s){return JSON.stringify({text:s})}function Si(s){return!s||typeof s!="string"||s.startsWith("oc_")?"chat_id":s.startsWith("ou_")?"open_id":s.startsWith("on_")?"union_id":s.startsWith("cli_")?"app_id":s.includes("@")?"email":"chat_id"}var K={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:N.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
312
+ - slack_list_usergroups, slack_get_usergroup_members (workspace-defined teams like @oncall, @platform)`,resolve(){let s=mi();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);for(let e of this.envKeys)process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t){try{switch(s){case"slack_list_channels":{let e=await U("conversations.list",{types:"public_channel",limit:100});return JSON.stringify({channels:(e.channels||[]).map(r=>({id:r.id,name:r.name,topic:r.topic?.value}))})}case"slack_post_message":{if(!t.channel||!t.text)return JSON.stringify({error:"channel and text are required"});let e=await U("chat.postMessage",{channel:t.channel,text:t.text,...t.blocks?{blocks:t.blocks}:{}});return JSON.stringify({ok:!0,ts:e.ts,channel:e.channel})}case"slack_reply_to_thread":{if(!t.channel||!t.thread_ts||!t.text)return JSON.stringify({error:"channel, thread_ts, and text are required"});let e=await U("chat.postMessage",{channel:t.channel,thread_ts:t.thread_ts,text:t.text});return JSON.stringify({ok:!0,ts:e.ts})}case"slack_add_reaction":return!t.channel||!t.timestamp||!t.reaction?JSON.stringify({error:"channel, timestamp, and reaction are required"}):(await U("reactions.add",{channel:t.channel,timestamp:t.timestamp,name:t.reaction}),JSON.stringify({ok:!0}));case"slack_get_channel_history":{if(!t.channel)return JSON.stringify({error:"channel is required"});let e=await U("conversations.history",{channel:t.channel,limit:t.limit||20});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_thread_replies":{if(!t.channel||!t.thread_ts)return JSON.stringify({error:"channel and thread_ts are required"});let e=await U("conversations.replies",{channel:t.channel,ts:t.thread_ts});return JSON.stringify({messages:(e.messages||[]).map(r=>({user:r.user,text:r.text,ts:r.ts}))})}case"slack_get_users":{let e=await U("users.list",{limit:100});return JSON.stringify({users:(e.members||[]).filter(r=>!r.is_bot&&!r.deleted).map(r=>({id:r.id,name:r.real_name||r.name}))})}case"slack_get_user_profile":{if(!t.user_id)return JSON.stringify({error:"user_id is required"});let e=await U("users.profile.get",{user:t.user_id});return JSON.stringify({profile:e.profile})}case"slack_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});try{let e=await U("users.lookupByEmail",{email:t.email});return JSON.stringify({ok:!0,user:{id:e.user?.id,name:e.user?.real_name||e.user?.name,email:e.user?.profile?.email||t.email}})}catch(e){if(/users_not_found/.test(e.message))return JSON.stringify({ok:!1,reason:"users_not_found"});throw e}}case"slack_list_usergroups":{let e=await U("usergroups.list",{});return JSON.stringify({usergroups:(e.usergroups||[]).map(r=>({id:r.id,handle:r.handle,name:r.name,description:r.description||"",user_count:Number(r.user_count||0)}))})}case"slack_get_usergroup_members":{if(!t.usergroup)return JSON.stringify({error:"usergroup id is required"});let e=await U("usergroups.users.list",{usergroup:t.usergroup});return JSON.stringify({users:e.users||[]})}case"slack_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),i=[],n,o=5;for(let c=0;c<o;c+=1){let d={limit:200};n&&(d.cursor=n);let l=await U("users.list",d);for(let p of l.members||[])p.deleted||p.is_bot||i.push(p);if(n=l.response_metadata?.next_cursor,!n)break}let a=[];for(let c of i){let d=(c.real_name||"").toLowerCase(),l=(c.profile?.display_name||"").toLowerCase(),p=(c.name||"").toLowerCase(),u=0;d.includes(e)&&(u+=100-Math.abs(d.length-e.length)),l.includes(e)&&(u+=60-Math.abs(l.length-e.length)),p.includes(e)&&(u+=30-Math.abs(p.length-e.length)),(d===e||l===e)&&(u+=200),u>0&&a.push({id:c.id,name:c.real_name||c.profile?.display_name||c.name,email:c.profile?.email||void 0,_score:u})}return a.sort((c,d)=>d._score-c._score),JSON.stringify({ok:!0,matches:a.slice(0,r).map(({_score:c,...d})=>d),scanned:i.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"slack_list_channels",description:"List public channels in the workspace",input_schema:{type:"object",properties:{}}},{name:"slack_post_message",description:"Post a message to a Slack channel or DM. Pass `blocks` (Block Kit) for a rich card; `text` is the required notification fallback.",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID or name"},text:{type:"string",description:"Notification/fallback text (required)"},blocks:{type:"array",description:"Block Kit blocks for rich formatting (optional). Each block is a Slack Block Kit object (header/section/divider/context). section blocks may carry a button accessory with a url."}},required:["channel","text"]}},{name:"slack_reply_to_thread",description:"Reply to a specific message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"},text:{type:"string",description:"Reply text"}},required:["channel","thread_ts","text"]}},{name:"slack_add_reaction",description:"Add an emoji reaction to a message",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},timestamp:{type:"string",description:"Message timestamp"},reaction:{type:"string",description:"Emoji name without colons"}},required:["channel","timestamp","reaction"]}},{name:"slack_get_channel_history",description:"Get recent messages from a channel",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},limit:{type:"number",description:"Number of messages"}},required:["channel"]}},{name:"slack_get_thread_replies",description:"Get all replies in a message thread",input_schema:{type:"object",properties:{channel:{type:"string",description:"Channel ID"},thread_ts:{type:"string",description:"Thread timestamp"}},required:["channel","thread_ts"]}},{name:"slack_get_users",description:"List workspace users with basic profiles",input_schema:{type:"object",properties:{}}},{name:"slack_get_user_profile",description:"Get detailed profile for a specific user",input_schema:{type:"object",properties:{user_id:{type:"string",description:"Slack user ID"}},required:["user_id"]}},{name:"slack_lookup_user_by_email",description:"Find a Slack user by email. Returns { ok:true, user:{id,name,email} } on hit, { ok:false } when no user has that email. Prefer this over slack_get_users for email-based routing \u2014 single API call, exact match.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"slack_list_usergroups",description:"List workspace-defined user groups (e.g. @oncall, @platform). Each item has { id, handle, name, description, user_count }. Use the id with slack_get_usergroup_members to expand the membership.",input_schema:{type:"object",properties:{}}},{name:"slack_get_usergroup_members",description:"List user IDs that belong to a Slack usergroup. Pair with slack_post_message to DM each member, or use the group id directly in a channel message as <!subteam^ID> to @-mention.",input_schema:{type:"object",properties:{usergroup:{type:"string",description:"Usergroup id, e.g. S012ABC"}},required:["usergroup"]}},{name:"slack_search_users",description:'Fuzzy-search workspace users by display name or real name. Use when the user said something like "send to Sam" without an email. Returns up to `limit` ranked matches { id, name, email }. Slack has no native name-search API \u2014 this scans paginated users.list + does substring scoring (real_name > display_name > name). For large workspaces consider higher limit + ask the user to confirm if multiple hit.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}]};import{existsSync as fi}from"fs";import{fileURLToPath as hi}from"url";import{dirname as yi,resolve as gi}from"path";import{resolveIntegrationToken as _i}from"@zibby/core/backend-client.js";function bi(){if(process.env.MCP_LARK_PATH)return process.env.MCP_LARK_PATH;let s=yi(hi(import.meta.url)),t=gi(s,"..","bin","mcp-lark.mjs");return fi(t)?t:null}var ki=6e3*1e3,he=null;async function wi(){let{appId:s,appSecret:t,host:e}=await _i("lark");if(he&&he.appId===s&&he.expiresAt>Date.now())return{token:he.token,host:e};let i=await(await fetch(`${e}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:s,app_secret:t})})).json();if(i.code!==0)throw new Error(`Lark tenant_access_token failed: ${i.msg||i.code}`);return he={token:i.tenant_access_token,expiresAt:Date.now()+ki,appId:s},{token:i.tenant_access_token,host:e}}async function re(s,t,e={}){let{token:r,host:i}=await wi(),n=`${i}${t}`,o={method:s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}};s!=="GET"&&(o.body=JSON.stringify(e));let c=await(await fetch(n,o)).json();if(c.code!==0)throw new Error(`Lark API ${t} error: ${c.msg||c.code}`);return c.data||{}}function Tt(s){return JSON.stringify({text:s})}function Si(s){return!s||typeof s!="string"||s.startsWith("oc_")?"chat_id":s.startsWith("ou_")?"open_id":s.startsWith("on_")?"union_id":s.startsWith("cli_")?"app_id":s.includes("@")?"email":"chat_id"}var K={id:"lark",serverName:"lark",allowedTools:["mcp__lark__*"],requiresIntegration:N.LARK,description:"Lark / Feishu messaging \u2014 send messages and reply in threads.",envKeys:[],promptFragment:`## Lark (connected)
313
313
  You can send messages and replies on Lark. Use:
314
314
  - lark_send_message: post a message to a chat, user, or DM
315
315
  - lark_reply: reply to an existing message (threaded)
316
316
  - lark_list_chats: list chats the bot is a member of
317
317
  - lark_get_chat_history: fetch recent messages in a chat
318
318
  - lark_lookup_user_by_email: resolve an email \u2192 open_id for direct DM (prefer this over emailing through lark_send_message when the agent has a user_id already)
319
- When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let s=bi();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(s,t){try{switch(s){case"lark_send_message":{if(!t.receive_id||!t.text)return JSON.stringify({error:"receive_id and text are required"});let e=Si(t.receive_id),r=await re("POST",`/open-apis/im/v1/messages?receive_id_type=${e}`,{receive_id:t.receive_id,msg_type:"text",content:$t(t.text)});return JSON.stringify({ok:!0,message_id:r.message_id})}case"lark_reply":{if(!t.message_id||!t.text)return JSON.stringify({error:"message_id and text are required"});let e=await re("POST",`/open-apis/im/v1/messages/${encodeURIComponent(t.message_id)}/reply`,{msg_type:"text",content:$t(t.text)});return JSON.stringify({ok:!0,message_id:e.message_id})}case"lark_list_chats":{let e=t.page_size||50,i=((await re("GET",`/open-apis/im/v1/chats?page_size=${e}`)).items||[]).map(n=>({chat_id:n.chat_id,name:n.name,description:n.description,owner_id:n.owner_id,chat_mode:n.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!t.chat_id)return JSON.stringify({error:"chat_id is required"});let e=t.page_size||20,i=((await re("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(t.chat_id)}&page_size=${e}&sort_type=ByCreateTimeDesc`)).items||[]).map(n=>({message_id:n.message_id,sender_id:n.sender?.id,sender_type:n.sender?.sender_type,msg_type:n.msg_type,content:n.body?.content,create_time:n.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});let r=((await re("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[t.email]})).user_list||[]).find(i=>i.email===t.email&&i.user_id);return JSON.stringify(r?{ok:!0,user:{open_id:r.user_id,email:r.email,name:r.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),i=200,o=((await re("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=i)break;try{let p=await re("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(e)&&(u+=100-Math.abs(p.length-e.length)),p===e&&(u+=200),u>0&&d.push({open_id:l.open_id,name:l.name,_score:u})}return d.sort((l,p)=>p._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,r).map(({_score:l,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}}};import{existsSync as vi}from"fs";import{fileURLToPath as Ni}from"url";import{dirname as Ii,resolve as Ri}from"path";import{resolveIntegrationToken as Oi,clearTokenCache as Ai}from"@zibby/core/backend-client.js";function ji(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ii(Ni(import.meta.url)),t=Ri(s,"..","bin","mcp-skill.mjs");return vi(t)?t:null}var $i="2022-06-28",Ti="https://api.notion.com/v1",Ie=2e4,Tt=25,Ei=25;function Et(s){if(!s||typeof s!="string")return null;let e=s.trim().split(/[?#]/)[0],r=e.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(r)return r[0].toLowerCase();let i=e.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let n=i[i.length-1].toLowerCase();return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return null}async function Fe(s,t={}){let e=async()=>{let{token:r}=await Oi("notion");if(typeof r!="string"||!r)throw new Error(`Invalid notion token type: ${typeof r}`);let i=await fetch(`${Ti}${s}`,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,"Notion-Version":$i,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let n=await i.text().catch(()=>"");if(!n||!n.trim())return{};try{return JSON.parse(n)}catch{return{raw:n}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw r;return Ai("notion"),e()}}function ye(s){if(!Array.isArray(s))return"";let t="";for(let e of s){let r=e?.plain_text??e?.text?.content??"";if(!r)continue;let i=e.annotations||{};i.code&&(r=`\`${r}\``),i.bold&&(r=`**${r}**`),i.italic&&(r=`_${r}_`),i.strikethrough&&(r=`~~${r}~~`);let n=e?.href||e?.text?.link?.url;n&&(r=`[${r}](${n})`),t+=r}return t}function xi(s,t,e){let r=s?.type,i=s?.[r]||{},n=" ".repeat(Math.max(0,t)),o=(d="rich_text")=>ye(i[d]),a;switch(r){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${n}- ${o()}`;break;case"numbered_list_item":a=`${n}1. ${o()}`;break;case"to_do":a=`${n}- [${i.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${n}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${i.icon?.emoji?`${i.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${i.language||""}
319
+ When responding to an incoming event, prefer lark_reply with the source message_id so the response threads cleanly.`,resolve(){let s=bi();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},tools:[{name:"lark_send_message",description:"Send a text message to a Lark chat, user, or DM. receive_id can be a chat_id (oc_*), open_id (ou_*), union_id (on_*), or email.",input_schema:{type:"object",properties:{receive_id:{type:"string",description:"Target id: chat_id (oc_*), open_id (ou_*), union_id (on_*), or email"},text:{type:"string",description:"Message text"}},required:["receive_id","text"]}},{name:"lark_reply",description:"Reply to an existing Lark message (creates a thread). Use the message_id from the inbound event.",input_schema:{type:"object",properties:{message_id:{type:"string",description:"Lark message id (om_*) to reply to"},text:{type:"string",description:"Reply text"}},required:["message_id","text"]}},{name:"lark_list_chats",description:"List chats (groups + DMs) the bot is a member of.",input_schema:{type:"object",properties:{page_size:{type:"number",description:"Max results (default 50)"}}}},{name:"lark_get_chat_history",description:"Fetch recent messages in a chat.",input_schema:{type:"object",properties:{chat_id:{type:"string",description:"Chat id (oc_*)"},page_size:{type:"number",description:"Max messages (default 20)"}},required:["chat_id"]}},{name:"lark_lookup_user_by_email",description:"Resolve an email address to a Lark user id (open_id). Returns { ok:true, user:{open_id,email,name} } on hit, { ok:false } if no Lark user has that email. Use the open_id as `receive_id` in lark_send_message to DM.",input_schema:{type:"object",properties:{email:{type:"string",description:"Email address to look up"}},required:["email"]}},{name:"lark_search_users",description:'Fuzzy-search users by name across chats the bot is a member of. Lark has no public org-wide user search API for bots \u2014 this walks the bot\'s chat memberships and matches names client-side. Best for "send to Sam" style routing where you have a name but no email. Returns up to `limit` ranked matches { open_id, name }.',input_schema:{type:"object",properties:{query:{type:"string",description:"Substring to match against user names (case-insensitive)"},limit:{type:"number",description:"Max matches to return (default 5, max 25)"}},required:["query"]}}],async handleToolCall(s,t){try{switch(s){case"lark_send_message":{if(!t.receive_id||!t.text)return JSON.stringify({error:"receive_id and text are required"});let e=Si(t.receive_id),r=await re("POST",`/open-apis/im/v1/messages?receive_id_type=${e}`,{receive_id:t.receive_id,msg_type:"text",content:Tt(t.text)});return JSON.stringify({ok:!0,message_id:r.message_id})}case"lark_reply":{if(!t.message_id||!t.text)return JSON.stringify({error:"message_id and text are required"});let e=await re("POST",`/open-apis/im/v1/messages/${encodeURIComponent(t.message_id)}/reply`,{msg_type:"text",content:Tt(t.text)});return JSON.stringify({ok:!0,message_id:e.message_id})}case"lark_list_chats":{let e=t.page_size||50,i=((await re("GET",`/open-apis/im/v1/chats?page_size=${e}`)).items||[]).map(n=>({chat_id:n.chat_id,name:n.name,description:n.description,owner_id:n.owner_id,chat_mode:n.chat_mode}));return JSON.stringify({chats:i})}case"lark_get_chat_history":{if(!t.chat_id)return JSON.stringify({error:"chat_id is required"});let e=t.page_size||20,i=((await re("GET",`/open-apis/im/v1/messages?container_id_type=chat&container_id=${encodeURIComponent(t.chat_id)}&page_size=${e}&sort_type=ByCreateTimeDesc`)).items||[]).map(n=>({message_id:n.message_id,sender_id:n.sender?.id,sender_type:n.sender?.sender_type,msg_type:n.msg_type,content:n.body?.content,create_time:n.create_time}));return JSON.stringify({messages:i})}case"lark_lookup_user_by_email":{if(!t.email)return JSON.stringify({error:"email is required"});let r=((await re("POST","/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id",{emails:[t.email]})).user_list||[]).find(i=>i.email===t.email&&i.user_id);return JSON.stringify(r?{ok:!0,user:{open_id:r.user_id,email:r.email,name:r.name||void 0}}:{ok:!1,reason:"no_lark_user_for_email"})}case"lark_search_users":{if(!t.query||typeof t.query!="string")return JSON.stringify({error:"query is required"});let e=t.query.trim().toLowerCase();if(!e)return JSON.stringify({ok:!0,matches:[]});let r=Math.max(1,Math.min(Number(t.limit)||5,25)),i=200,o=((await re("GET","/open-apis/im/v1/chats?page_size=100")).items||[]).map(l=>l.chat_id),a=new Set,c=[];for(let l of o){if(c.length>=i)break;try{let p=await re("GET",`/open-apis/im/v1/chats/${encodeURIComponent(l)}/members?member_id_type=open_id&page_size=100`);for(let u of p.items||[])if(!(!u.member_id||a.has(u.member_id))&&(a.add(u.member_id),c.push({open_id:u.member_id,name:u.name||""}),c.length>=i))break}catch(p){console.warn(`[lark] member scan failed for ${l}: ${p.message}`)}}let d=[];for(let l of c){let p=(l.name||"").toLowerCase();if(!p)continue;let u=0;p.includes(e)&&(u+=100-Math.abs(p.length-e.length)),p===e&&(u+=200),u>0&&d.push({open_id:l.open_id,name:l.name,_score:u})}return d.sort((l,p)=>p._score-l._score),JSON.stringify({ok:!0,matches:d.slice(0,r).map(({_score:l,...p})=>p),scanned:c.length})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}}};import{existsSync as vi}from"fs";import{fileURLToPath as Ni}from"url";import{dirname as Ii,resolve as Ri}from"path";import{resolveIntegrationToken as Oi,clearTokenCache as Ai}from"@zibby/core/backend-client.js";function ji(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=Ii(Ni(import.meta.url)),t=Ri(s,"..","bin","mcp-skill.mjs");return vi(t)?t:null}var Ti="2022-06-28",$i="https://api.notion.com/v1",Ie=2e4,$t=25,Ei=25;function Et(s){if(!s||typeof s!="string")return null;let e=s.trim().split(/[?#]/)[0],r=e.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);if(r)return r[0].toLowerCase();let i=e.match(/[0-9a-fA-F]{32}/g);if(i&&i.length){let n=i[i.length-1].toLowerCase();return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return null}async function Fe(s,t={}){let e=async()=>{let{token:r}=await Oi("notion");if(typeof r!="string"||!r)throw new Error(`Invalid notion token type: ${typeof r}`);let i=await fetch(`${$i}${s}`,{method:t.method||"GET",headers:{Authorization:`Bearer ${r}`,"Notion-Version":Ti,Accept:"application/json",...t.body?{"Content-Type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Notion API ${i.status}: ${o.slice(0,300)}`)}let n=await i.text().catch(()=>"");if(!n||!n.trim())return{};try{return JSON.parse(n)}catch{return{raw:n}}};try{return await e()}catch(r){let i=String(r?.message||r||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("unauthorized")))throw r;return Ai("notion"),e()}}function ye(s){if(!Array.isArray(s))return"";let t="";for(let e of s){let r=e?.plain_text??e?.text?.content??"";if(!r)continue;let i=e.annotations||{};i.code&&(r=`\`${r}\``),i.bold&&(r=`**${r}**`),i.italic&&(r=`_${r}_`),i.strikethrough&&(r=`~~${r}~~`);let n=e?.href||e?.text?.link?.url;n&&(r=`[${r}](${n})`),t+=r}return t}function Li(s,t,e){let r=s?.type,i=s?.[r]||{},n=" ".repeat(Math.max(0,t)),o=(d="rich_text")=>ye(i[d]),a;switch(r){case"paragraph":a=o();break;case"heading_1":a=`# ${o()}`;break;case"heading_2":a=`## ${o()}`;break;case"heading_3":a=`### ${o()}`;break;case"bulleted_list_item":a=`${n}- ${o()}`;break;case"numbered_list_item":a=`${n}1. ${o()}`;break;case"to_do":a=`${n}- [${i.checked?"x":" "}] ${o()}`;break;case"toggle":a=`${n}- ${o()}`;break;case"quote":a=`> ${o()}`;break;case"callout":{a=`> ${i.icon?.emoji?`${i.icon.emoji} `:""}${o()}`;break}case"code":{a=`\`\`\`${i.language||""}
320
320
  ${o()}
321
321
  \`\`\``;break}case"divider":a="---";break;case"child_page":a=`[child page: ${i.title||""}]`;break;case"child_database":a=`[child database: ${i.title||""}]`;break;case"bookmark":case"embed":case"link_preview":a=i.url?`<${i.url}>`:"";break;case"equation":a=i.expression?`$${i.expression}$`:"";break;case"table":case"column_list":case"column":a="";break;case"table_row":{let d=(i.cells||[]).map(l=>ye(l).trim());a=`${n}| ${d.join(" | ")} |`;break}default:a=o();break}let c=[];return a&&a.trim()&&c.push(a),e&&e.trim()&&c.push(e),c.join(`
322
- `)}async function Lt(s,t,e){let r=[],i,n=0;do{if(e.used>=Ie)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await Fe(`/blocks/${s}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await Lt(d.id,t+1,e));let p=xi(d,t,l);if(p&&(r.push(p),e.used+=p.length+1),e.used>=Ie)break}i=a.has_more?a.next_cursor:void 0,n+=1}while(i&&n<Ei);return r.join(`
323
- `)}function xt(s){let t=s?.properties||{};for(let e of Object.values(t))if(e?.type==="title"){let r=ye(e.title).trim();if(r)return r}return""}function Li(s){if(!s||!s.type)return"";switch(s.type){case"title":return ye(s.title).trim();case"rich_text":return ye(s.rich_text).trim();case"number":return s.number==null?"":String(s.number);case"select":return s.select?.name||"";case"status":return s.status?.name||"";case"multi_select":return(s.multi_select||[]).map(e=>e.name).join(", ");case"checkbox":return s.checkbox?"true":"false";case"url":return s.url||"";case"email":return s.email||"";case"phone_number":return s.phone_number||"";case"date":return s.date?.start||"";case"people":return(s.people||[]).map(e=>e.name||e.id).join(", ");default:return""}}var Ct={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:N.NOTION,description:"Notion read-only context (pull a page/database as markdown)",promptFragment:`## Notion (connected, read-only context)
322
+ `)}async function xt(s,t,e){let r=[],i,n=0;do{if(e.used>=Ie)break;let o=new URLSearchParams({page_size:"100"});i&&o.set("start_cursor",i);let a=await Fe(`/blocks/${s}/children?${o.toString()}`),c=Array.isArray(a.results)?a.results:[];for(let d of c){let l="";d.has_children&&(l=await xt(d.id,t+1,e));let p=Li(d,t,l);if(p&&(r.push(p),e.used+=p.length+1),e.used>=Ie)break}i=a.has_more?a.next_cursor:void 0,n+=1}while(i&&n<Ei);return r.join(`
323
+ `)}function Lt(s){let t=s?.properties||{};for(let e of Object.values(t))if(e?.type==="title"){let r=ye(e.title).trim();if(r)return r}return""}function xi(s){if(!s||!s.type)return"";switch(s.type){case"title":return ye(s.title).trim();case"rich_text":return ye(s.rich_text).trim();case"number":return s.number==null?"":String(s.number);case"select":return s.select?.name||"";case"status":return s.status?.name||"";case"multi_select":return(s.multi_select||[]).map(e=>e.name).join(", ");case"checkbox":return s.checkbox?"true":"false";case"url":return s.url||"";case"email":return s.email||"";case"phone_number":return s.phone_number||"";case"date":return s.date?.start||"";case"people":return(s.people||[]).map(e=>e.name||e.id).join(", ");default:return""}}var Ct={id:"notion",serverName:"notion",allowedTools:["mcp__notion__*"],requiresIntegration:N.NOTION,description:"Notion read-only context (pull a page/database as markdown)",promptFragment:`## Notion (connected, read-only context)
324
324
  You can pull a referenced Notion page in as extra context. This is OPTIONAL \u2014 only use it when the task references a Notion page/URL (e.g. an engineering-standards or design doc to review against).
325
325
  - notion_get_page: pass a Notion page id OR a full Notion URL; returns { id, title, url, text } where text is the page flattened to markdown (truncated to ~20k chars). Use the text as reference context.
326
326
  - notion_query_database: pass a database id/URL; returns a small list of rows ({ id, title, url, props }). Use to find a specific page, then notion_get_page it.
327
- Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" and continue.`,resolve(){let s=ji();return s?{type:"stdio",command:"node",args:[s,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(s,t){try{switch(s){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,r=Et(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await Fe(`/pages/${r}`),n=xt(i),o=i?.url||`https://www.notion.so/${r.replace(/-/g,"")}`,c=await Lt(r,0,{used:0}),d=!1;return c.length>Ie&&(c=c.slice(0,Ie),d=!0),JSON.stringify({ok:!0,id:r,title:n,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,r=Et(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let n={page_size:Math.max(1,Math.min(Number(t?.maxResults)||Tt,Tt))};t?.filter&&typeof t.filter=="object"&&(n.filter=t.filter);let o=await Fe(`/databases/${r}/query`,{method:"POST",body:n}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=Li(u);m&&(l[p]=m)}return{id:d.id,title:xt(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:r,count:c.length,hasMore:!!o.has_more,rows:c})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}}]};var Pt={id:"chat_notify",description:"Chat notification meta-skill \u2014 routes to whichever messaging integration (Slack OR Lark) the user has configured for this project.",envKeys:[...D.envKeys||[],...K.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return D.serverName;if(process.env.LARK_RECEIVE_ID)return K.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?D.allowedTools||[]:process.env.LARK_RECEIVE_ID?K.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
328
- You can post chat messages via either:
329
- - slack_post_message (channel, text) \u2014 Slack, when SLACK_CHANNEL is set
330
- - lark_send_message (receive_id, text) \u2014 Lark, when LARK_RECEIVE_ID is set
331
- Use whichever the user has configured.`,resolve(s){return process.env.SLACK_CHANNEL&&typeof D.resolve=="function"?D.resolve(s):process.env.LARK_RECEIVE_ID&&typeof K.resolve=="function"?K.resolve(s):null},async handleToolCall(s,t,e){return typeof s=="string"&&s.startsWith("slack_")?D.handleToolCall(s,t,e):typeof s=="string"&&s.startsWith("lark_")?K.handleToolCall(s,t,e):JSON.stringify({error:`chat_notify: unknown tool "${s}". Expected slack_* or lark_*.`})},get tools(){return[...D.tools||[],...K.tools||[]]}};import{createRequire as Ci}from"module";import{execFileSync as Pi}from"child_process";import{join as qt}from"path";import{existsSync as qi}from"fs";var Ji=Ci(import.meta.url);function Ui(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Ji.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var Jt={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:s}=await import("@zibby/ui-memory");return s()}catch{return null}},promptFragment:`BEFORE executing browser actions:
327
+ Do not block the task if Notion is unavailable \u2014 these tools return { ok:false, error } on failure; treat a missing page as "no extra context" and continue.`,resolve(){let s=ji();return s?{type:"stdio",command:"node",args:[s,"../dist/notion.js","notionSkill"],env:{},description:this.description,alwaysLoad:!0}:null},async handleToolCall(s,t){try{switch(s){case"notion_get_page":{let e=t?.pageId||t?.page||t?.url||t?.id,r=Et(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion page id or URL is required"});let i=await Fe(`/pages/${r}`),n=Lt(i),o=i?.url||`https://www.notion.so/${r.replace(/-/g,"")}`,c=await xt(r,0,{used:0}),d=!1;return c.length>Ie&&(c=c.slice(0,Ie),d=!0),JSON.stringify({ok:!0,id:r,title:n,url:o,text:c,...d?{truncated:!0}:{}})}case"notion_query_database":{let e=t?.databaseId||t?.database||t?.url||t?.id,r=Et(e);if(!r)return JSON.stringify({ok:!1,error:"A valid Notion database id or URL is required"});let n={page_size:Math.max(1,Math.min(Number(t?.maxResults)||$t,$t))};t?.filter&&typeof t.filter=="object"&&(n.filter=t.filter);let o=await Fe(`/databases/${r}/query`,{method:"POST",body:n}),c=(Array.isArray(o.results)?o.results:[]).map(d=>{let l={};for(let[p,u]of Object.entries(d.properties||{})){let m=xi(u);m&&(l[p]=m)}return{id:d.id,title:Lt(d),url:d.url||`https://www.notion.so/${String(d.id||"").replace(/-/g,"")}`,props:l}});return JSON.stringify({ok:!0,id:r,count:c.length,hasMore:!!o.has_more,rows:c})}default:return JSON.stringify({ok:!1,error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({ok:!1,error:e.message})}},tools:[{name:"notion_get_page",description:"Fetch a Notion page and its content flattened to markdown, for use as read-only context. Accepts a raw page id OR a full Notion URL. Returns { ok, id, title, url, text }. Text is truncated to ~20k chars.",input_schema:{type:"object",properties:{pageId:{type:"string",description:"Notion page id (dashed UUID or 32-char) OR a full Notion page URL."}},required:["pageId"]}},{name:"notion_query_database",description:"Query a Notion database and return a bounded list of rows (id, title, url, key props). Accepts a database id OR full Notion URL. Optional Notion filter object. Returns at most 25 rows.",input_schema:{type:"object",properties:{databaseId:{type:"string",description:"Notion database id (dashed UUID or 32-char) OR a full Notion database URL."},filter:{type:"object",description:"Optional Notion filter object (Notion query filter syntax).",additionalProperties:!0},maxResults:{type:"number",description:"Max rows to return (default 25, max 25)."}},required:["databaseId"]}}]};var Pt={id:"chat_notify",description:"Chat notification meta-skill \u2014 routes to whichever messaging integration (Slack OR Lark) the user has configured for this project.",envKeys:[...x.envKeys||[],...K.envKeys||[]],get serverName(){if(process.env.SLACK_CHANNEL)return x.serverName;if(process.env.LARK_RECEIVE_ID)return K.serverName;if(process.env.SLACK_BOT_TOKEN)return x.serverName},get allowedTools(){return process.env.SLACK_CHANNEL?x.allowedTools||[]:process.env.LARK_RECEIVE_ID?K.allowedTools||[]:process.env.SLACK_BOT_TOKEN?x.allowedTools||[]:[]},promptFragment:`## Chat notifications (Slack OR Lark \u2014 at least one connected)
328
+ You can post chat messages via:
329
+ - slack_post_message (channel, text[, blocks]) \u2014 Slack. The \`channel\` is REQUIRED on every call.
330
+ - lark_send_message (receive_id, text) \u2014 Lark.
331
+ Where to post:
332
+ - If SLACK_CHANNEL / LARK_RECEIVE_ID is set, that is the default destination \u2014 use it.
333
+ - If NO destination env var is set but your instructions name a channel (e.g. "post to #bla"), post to THAT channel \u2014 pass it as the \`channel\` arg (a "#name" or "C0123" id both work).
334
+ - If neither an env var NOR an instruction gives you a channel, do NOT post \u2014 there is nowhere to send it.`,resolve(s){return process.env.SLACK_CHANNEL&&typeof x.resolve=="function"?x.resolve(s):process.env.LARK_RECEIVE_ID&&typeof K.resolve=="function"?K.resolve(s):process.env.SLACK_BOT_TOKEN&&typeof x.resolve=="function"?x.resolve(s):null},async handleToolCall(s,t,e){return typeof s=="string"&&s.startsWith("slack_")?x.handleToolCall(s,t,e):typeof s=="string"&&s.startsWith("lark_")?K.handleToolCall(s,t,e):JSON.stringify({error:`chat_notify: unknown tool "${s}". Expected slack_* or lark_*.`})},get tools(){return[...x.tools||[],...K.tools||[]]}};import{createRequire as Ci}from"module";import{execFileSync as Pi}from"child_process";import{join as qt}from"path";import{existsSync as qi}from"fs";var Ji=Ci(import.meta.url);function Ui(){if(process.env.MCP_MEMORY_PATH)return process.env.MCP_MEMORY_PATH;try{return Ji.resolve("@zibby/ui-memory/mcp-server")}catch{return null}}var Jt={id:"memory",serverName:"memory",allowedTools:["mcp__memory__*"],envKeys:[],description:"Zibby Memory MCP Server (test history, selectors, page model)",async middleware(){try{let{createMemoryMiddleware:s}=await import("@zibby/ui-memory");return s()}catch{return null}},promptFragment:`BEFORE executing browser actions:
332
335
  - Review any test memory/history above. Prefer selectors proven to work.
333
336
  - If a previous run failed, avoid the same approach.
334
337
  - After setup/login completes, navigate directly to the target page instead of clicking through menus.
@@ -369,9 +372,9 @@ AFTER completing the test, you MUST call memory_save_insight at least once:
369
372
  You have access to the user's Sentry. Use these tools:
370
373
  - sentry_list_projects: List projects in the organization
371
374
  - sentry_list_issues: List errors/issues (supports Sentry search query, project filter, sort)
372
- - sentry_get_issue: Get detailed info about a specific issue (requires issueId)`,resolve(){let s=fn();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t={}){try{switch(s){case"sentry_list_projects":{let e=await hn();return JSON.stringify({projects:e.map(r=>({slug:r.slug,name:r.name,platform:r.platform}))})}case"sentry_list_issues":{let e=await yn({query:t.query,sort:t.sort,project:t.project,limit:t.limit});return JSON.stringify({issues:e.map(r=>({id:r.id,title:r.title,culprit:r.culprit,count:r.count,firstSeen:r.firstSeen,lastSeen:r.lastSeen,level:r.level,status:r.status}))})}case"sentry_get_issue":{let e=await gn(t.issueId);return JSON.stringify({id:e.id,title:e.title,culprit:e.culprit,metadata:e.metadata,count:e.count,userCount:e.userCount,firstSeen:e.firstSeen,lastSeen:e.lastSeen,level:e.level,status:e.status,project:{slug:e.project?.slug,name:e.project?.name}})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}}]};Oe.tools=Oe.toolsForAssistant;import{spawn as sr}from"child_process";import{writeFileSync as _n,mkdirSync as Wt,existsSync as G,readdirSync as Te,readFileSync as $e,unlinkSync as bn,createWriteStream as kn,statSync as wn}from"fs";import{resolve as ie,join as B}from"path";import{resolveMaxParallelRuns as ir}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Sn}from"@zibby/core/constants/zibby-scratch.js";var Ye="sessions",Ze=".zibby/output",Ae=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",vn=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",nr=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",C=new Map,Q=[],Nn=0,ze=0,Yt=3e3;function or(){return`run_${++Nn}_${Date.now().toString(36)}`}function Zt(s){let t=Math.floor(s/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function ar(s){return s.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function L(s,t,e){if(!vn)return;let r=`
375
+ - sentry_get_issue: Get detailed info about a specific issue (requires issueId)`,resolve(){let s=fn();if(!s)return null;let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_USER_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","PROGRESS_API_URL","EXECUTION_ID","PROJECT_ID","STAGE"])process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[s],env:t,alwaysLoad:!0}},async handleToolCall(s,t={}){try{switch(s){case"sentry_list_projects":{let e=await hn();return JSON.stringify({projects:e.map(r=>({slug:r.slug,name:r.name,platform:r.platform}))})}case"sentry_list_issues":{let e=await yn({query:t.query,sort:t.sort,project:t.project,limit:t.limit});return JSON.stringify({issues:e.map(r=>({id:r.id,title:r.title,culprit:r.culprit,count:r.count,firstSeen:r.firstSeen,lastSeen:r.lastSeen,level:r.level,status:r.status}))})}case"sentry_get_issue":{let e=await gn(t.issueId);return JSON.stringify({id:e.id,title:e.title,culprit:e.culprit,metadata:e.metadata,count:e.count,userCount:e.userCount,firstSeen:e.firstSeen,lastSeen:e.lastSeen,level:e.level,status:e.status,project:{slug:e.project?.slug,name:e.project?.name}})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},toolsForAssistant:[{name:"sentry_list_projects",description:"List Sentry projects",input_schema:{type:"object",properties:{}}},{name:"sentry_list_issues",description:"List Sentry issues (errors)",input_schema:{type:"object",properties:{project:{type:"string",description:"Project slug (optional)"},query:{type:"string",description:"Sentry search query (default: is:unresolved)"},sort:{type:"string",description:"Sort order: date, new, priority, freq, user (default: date)"},limit:{type:"number",description:"Max issues to return (default 25)"}}}},{name:"sentry_get_issue",description:"Get details of a specific Sentry issue",input_schema:{type:"object",properties:{issueId:{type:"string",description:"Sentry issue ID"}},required:["issueId"]}}]};Oe.tools=Oe.toolsForAssistant;import{spawn as sr}from"child_process";import{writeFileSync as _n,mkdirSync as Wt,existsSync as G,readdirSync as $e,readFileSync as Te,unlinkSync as bn,createWriteStream as kn,statSync as wn}from"fs";import{resolve as ie,join as B}from"path";import{resolveMaxParallelRuns as ir}from"@zibby/core/utils/parallel-config.js";import{zibbyScratchSpecsDir as Sn}from"@zibby/core/constants/zibby-scratch.js";var Ye="sessions",Ze=".zibby/output",Ae=process.env.ZIBBY_RUNNER_NODE_PROGRESS==="1",vn=process.env.ZIBBY_RUNNER_STATUS_STREAM==="1",nr=process.env.ZIBBY_RUNNER_SPAWN_LOGS==="1",P=new Map,Q=[],Nn=0,ze=0,Yt=3e3;function or(){return`run_${++Nn}_${Date.now().toString(36)}`}function Zt(s){let t=Math.floor(s/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function ar(s){return s.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function C(s,t,e){if(!vn)return;let r=`
373
376
  ${t} [${s}] ${e}
374
- `;try{process.stderr.write(r)}catch{}}function Ve(){Q.length=0;for(let[,s]of C)if(s.status==="queued"&&(s.status="cancelled"),s.status==="running"&&s._child)try{s._child.kill("SIGTERM")}catch{}}process.on("exit",Ve);process.on("SIGINT",()=>{Ve(),process.exit(0)});process.on("SIGTERM",()=>{Ve(),process.exit(0)});var cr={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
377
+ `;try{process.stderr.write(r)}catch{}}function Ve(){Q.length=0;for(let[,s]of P)if(s.status==="queued"&&(s.status="cancelled"),s.status==="running"&&s._child)try{s._child.kill("SIGTERM")}catch{}}process.on("exit",Ve);process.on("SIGINT",()=>{Ve(),process.exit(0)});process.on("SIGTERM",()=>{Ve(),process.exit(0)});var cr={id:"runner",description:"Run zibby test workflows from chat (parallel supported)",envKeys:[],promptFragment:`## Test Runner
375
378
  You can run zibby test workflows directly from chat:
376
379
 
377
380
  **CRITICAL: When user asks to test a ticket:**
@@ -508,8 +511,8 @@ Each run generates:
508
511
  - events.json: All browser events
509
512
  - raw_stream_output.txt: Agent log
510
513
 
511
- Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"run_generate":return await In(t,r);case"run_test":return await Tn(t,r,e);case"run_status":return En(t);case"run_cancel":return xn(t);case"run_artifacts":return Pn(t,r);case"run_diagnose":return qn(t,r);case"list_specs":return Jn(t,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function We(){let s=0;for(let[,t]of C)t.status==="running"&&s++;return s}function Vt(){for(;Q.length>0;){let s=ir(Q[0]?.context?.options?.config);if(We()>=s)break;let{args:t,cwd:e,context:r}=Q.shift();lr(t,e,r)}}async function In(s,t){let{ticket:e,description:r,input:i,repo:n,agent:o,output:a}=s,c=["generate"];e&&c.push("--ticket",e),r&&c.push("--description",r),i&&c.push("--input",i),n&&c.push("--repo",n),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=e||"generate";return L(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{nr&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(g=>/\s/.test(g)?JSON.stringify(g):g).join(" ")} cwd=${t}`);let f=sr("zibby",c,{cwd:t,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",_="";f.stdout.on("data",g=>{let b=g.toString();h+=b;for(let y of b.split(`
512
- `)){let S=ar(y).trim();S.startsWith("\u2705")?L(u,"\u2705",S.slice(2).trim()):S.startsWith("\u2713")&&L(u,"\u2714",S.slice(2).trim())}}),f.stderr.on("data",g=>{_+=g.toString()}),f.on("close",g=>{if(g!==0){L(u,"\u274C",`Generation failed (exit ${g})`),m(JSON.stringify({error:`zibby generate failed with exit code ${g}`,stderr:_.slice(-1e3)}));return}let b=ie(t,a||"test-specs"),y=[];try{let S=e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=Te(b).filter(j=>j.endsWith(".txt")&&(!S||j.startsWith(S))).map(j=>B(b,j))}catch{}L(u,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:e||null,specFiles:y.map(S=>S.replace(`${t}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",g=>{L(u,"\u274C",`Spawn error: ${g.message}`),m(JSON.stringify({error:g.message}))})})}var Qt=1e5,Xt=/^[A-Z][A-Z0-9]+-\d+$/,Rn=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function On(s,t){if(!t||!t.length)return s;let e=s;for(let r of t)r.type==="strong"?e=`**${e}**`:r.type==="em"?e=`_${e}_`:r.type==="code"?e=`\`${e}\``:r.type==="strike"?e=`~~${e}~~`:r.type==="link"&&r.attrs?.href&&(e=`[${e}](${r.attrs.href})`);return e}function je(s,t=0){if(!Array.isArray(s))return"";let e=[];for(let r of s){if(r.type==="text"){e.push(On(r.text||"",r.marks));continue}if(r.type==="hardBreak"){e.push(`
514
+ Use run_artifacts({ runId, type }) and run_diagnose({ runId }) to inspect and explain failures.`,resolve(){return null},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd();try{switch(s){case"run_generate":return await In(t,r);case"run_test":return await $n(t,r,e);case"run_status":return En(t);case"run_cancel":return Ln(t);case"run_artifacts":return Pn(t,r);case"run_diagnose":return qn(t,r);case"list_specs":return Jn(t,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(i){return JSON.stringify({error:i.message})}},tools:[{name:"run_generate",description:"Generate specs from codebase. CRITICAL: DO NOT USE if ticket has test steps in comments. Only use when: (1) NO steps in ticket AND (2) local codebase exists (not external URLs). For tickets with steps, use run_test with inline format.",input_schema:{type:"object",properties:{ticket:{type:"string",description:"Jira ticket key (e.g. SCRUM-123). Auto-fetches ticket details."},description:{type:"string",description:"Ticket description text (use if no Jira key available)"},input:{type:"string",description:"Path to a file containing ticket/requirements text"},repo:{type:"string",description:"Path to the codebase (default: current directory)"},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},output:{type:"string",description:"Output directory for spec files (default: test-specs)"}}}},{name:"run_test",description:"Start a test (async, returns runId). spec = file path, or inline:+steps, or a Jira-shaped issue key (e.g. PROJ-123): when Jira is connected, the runner loads that issue's description+comments into an inline spec. After starting, tell the user and let them ask for progress via run_status.",input_schema:{type:"object",properties:{spec:{type:"string",description:"Workspace file path; or inline:+steps; or Jira issue key (KEY-123) to auto-fetch from Jira when the jira skill is active."},ticketKey:{type:"string",description:"Optional label (e.g. SCRUM-123). If spec is an issue key, this defaults to that key."},agent:{type:"string",description:"Optional agent override (cursor, gemini, claude, codex, assistant). Omit to use configured agent."},headless:{type:"boolean",description:"Run browser headless (default false)"},workflow:{type:"string",description:"Workflow override (e.g. quick-smoke)"}},required:["spec"]}},{name:"run_status",description:'Instant progress check \u2014 returns immediately. Use this whenever user asks about test progress. ALWAYS use runId="all".',input_schema:{type:"object",properties:{runId:{type:"string",description:'Use "all" to see all runs in this session (recommended). Or a specific run ID if known.'}},required:["runId"]}},{name:"run_cancel",description:'Cancel/kill a running test. ONLY use when the USER explicitly asks to cancel or stop a run. NEVER auto-cancel \u2014 tests take 1-5 minutes and "running" is normal. Use runId="all" to cancel all active runs.',input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID to cancel, or "all" to cancel all active runs'}},required:["runId"]}},{name:"run_artifacts",description:"Read artifacts from a test run session. Can list files, read results/events/logs, or search across all sessions.",input_schema:{type:"object",properties:{runId:{type:"string",description:"Run ID from run_test. Omit to search across all sessions."},type:{type:"string",enum:["list","result","events","log","search"],description:'What to retrieve: "list" = all files in session, "result" = result.json, "events" = events.json, "log" = raw output tail, "search" = search text across sessions'},node:{type:"string",description:'Node name to read from (e.g. "execute_live", "generate_script"). Default: "execute_live"'},query:{type:"string",description:'Search text (only for type="search"). Searches across all session logs/events.'},tail:{type:"number",description:"Number of characters from end of log to return (default: 3000)"}},required:["type"]}},{name:"run_diagnose",description:"Diagnose one or all runs, especially failed ones. Uses run logs + known error patterns and returns likely root cause with suggested next action.",input_schema:{type:"object",properties:{runId:{type:"string",description:'Run ID from run_test, or "all" (default) to diagnose all known runs'},tail:{type:"number",description:"Characters of run log tail to inspect (default: 2000)"}}}},{name:"list_specs",description:"List available test spec files in the project",input_schema:{type:"object",properties:{directory:{type:"string",description:'Directory to scan (default: "test-specs")'}}}}]};function We(){let s=0;for(let[,t]of P)t.status==="running"&&s++;return s}function Vt(){for(;Q.length>0;){let s=ir(Q[0]?.context?.options?.config);if(We()>=s)break;let{args:t,cwd:e,context:r}=Q.shift();lr(t,e,r)}}async function In(s,t){let{ticket:e,description:r,input:i,repo:n,agent:o,output:a}=s,c=["generate"];e&&c.push("--ticket",e),r&&c.push("--description",r),i&&c.push("--input",i),n&&c.push("--repo",n),a&&c.push("--output",a);let d=["assistant","cursor","claude","codex","gemini"],l=o||process.env.AGENT_TYPE,p=l&&d.includes(l)?l:null;p&&c.push("--agent",p);let u=e||"generate";return C(u,"\u{1F9EA}","Starting test spec generation (real agent with codebase access)..."),new Promise(m=>{nr&&console.error(`[zibby:spawn] skill=run_generate parentPid=${process.pid} \u2192 child zibby ${c.map(g=>/\s/.test(g)?JSON.stringify(g):g).join(" ")} cwd=${t}`);let f=sr("zibby",c,{cwd:t,env:{...process.env},stdio:["ignore","pipe","pipe"],detached:!1}),h="",_="";f.stdout.on("data",g=>{let b=g.toString();h+=b;for(let y of b.split(`
515
+ `)){let S=ar(y).trim();S.startsWith("\u2705")?C(u,"\u2705",S.slice(2).trim()):S.startsWith("\u2713")&&C(u,"\u2714",S.slice(2).trim())}}),f.stderr.on("data",g=>{_+=g.toString()}),f.on("close",g=>{if(g!==0){C(u,"\u274C",`Generation failed (exit ${g})`),m(JSON.stringify({error:`zibby generate failed with exit code ${g}`,stderr:_.slice(-1e3)}));return}let b=ie(t,a||"test-specs"),y=[];try{let S=e?e.toLowerCase().replace(/[^a-z0-9]+/g,"-"):"";y=$e(b).filter(j=>j.endsWith(".txt")&&(!S||j.startsWith(S))).map(j=>B(b,j))}catch{}C(u,"\u2705",`Generated ${y.length} test spec files`),m(JSON.stringify({success:!0,ticketKey:e||null,specFiles:y.map(S=>S.replace(`${t}/`,"")),total:y.length,message:`Generated ${y.length} specs. Now call run_test for each file.`}))}),f.on("error",g=>{C(u,"\u274C",`Spawn error: ${g.message}`),m(JSON.stringify({error:g.message}))})})}var Qt=1e5,Xt=/^[A-Z][A-Z0-9]+-\d+$/,Rn=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function On(s,t){if(!t||!t.length)return s;let e=s;for(let r of t)r.type==="strong"?e=`**${e}**`:r.type==="em"?e=`_${e}_`:r.type==="code"?e=`\`${e}\``:r.type==="strike"?e=`~~${e}~~`:r.type==="link"&&r.attrs?.href&&(e=`[${e}](${r.attrs.href})`);return e}function je(s,t=0){if(!Array.isArray(s))return"";let e=[];for(let r of s){if(r.type==="text"){e.push(On(r.text||"",r.marks));continue}if(r.type==="hardBreak"){e.push(`
513
516
  `);continue}if(r.type==="rule"){e.push(`
514
517
  ---
515
518
  `);continue}let i=r.content?je(r.content,t+1):"";if(r.type==="listItem")e.push(i);else if(r.type==="bulletList"){let n=(r.content||[]).map(o=>`- ${je(o.content||[],t+1).trim()}`);e.push(`
@@ -533,10 +536,10 @@ ${i}
533
536
 
534
537
  `).trim();return l?(l.length>Qt&&(l=`${l.slice(0,Qt)}
535
538
 
536
- ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:s}):null}catch{return null}}function $n(s,t){try{let e=JSON.parse(s);return JSON.stringify({...e,...t})}catch{return s}}async function Tn(s,t,e){let r={...s},i=String(r.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let n=null;if(Xt.test(i)&&!i.startsWith("inline:")){let l=await jn(i);l&&(i=l.inlineSpec,r.spec=i,String(r.ticketKey||"").trim()||(r.ticketKey=l.issueKey),n=l.issueKey)}let o=String(r.ticketKey||"").trim();if(o){for(let[l,p]of C.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=ie(t,i);if(!G(l))return Xt.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=ir(e?.options?.config);if(We()>=a){let l=or(),p=r.ticketKey||l,u={runId:l,spec:r.ticketKey?`${r.ticketKey}: ${r.spec}`:r.spec,ticketKey:r.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};C.set(l,u),Q.push({args:{...r,_queuedRunId:l},cwd:t,context:e}),L(p,"\u23F3",`Queued (${We()}/${a} running, ${Q.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return n&&(m.resolvedFromJiraIssue=n,m.message+=` (spec built from Jira ${n})`),JSON.stringify(m)}let c=Date.now()-ze;c<Yt&&ze>0&&await new Promise(l=>setTimeout(l,Yt-c)),ze=Date.now();let d=lr(r,t,e);return n?$n(d,{resolvedFromJiraIssue:n,message:`Spec was loaded from Jira issue ${n} (description + comments).`}):d}function lr(s,t,e){let{spec:r,ticketKey:i,agent:n,headless:o,workflow:a,_queuedRunId:c}=s,d=c||or(),l=r,p=!1;if(r.startsWith("inline:")){p=!0;let A=Sn(t);Wt(A,{recursive:!0}),l=B(A,`${d}.txt`),_n(l,r.slice(7).trim(),"utf-8")}let u=ie(t,".zibby","output","runs");Wt(u,{recursive:!0});let m=B(u,`${d}.log`),f=kn(m,{flags:"a"}),_=n&&["assistant","cursor","claude","codex","gemini"].includes(n)?n:null,g=["test",l];_&&g.push("--agent",_),o&&g.push("--headless"),a&&g.push("--workflow",a),nr&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(A=>/\s/.test(A)?JSON.stringify(A):A).join(" ")} cwd=${t}`);let b=sr("zibby",g,{cwd:t,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${r}`:r,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},S=i||d,j="";function Y(A){let R=ar(A).trim();if(!R)return;if(R.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let E=JSON.parse(R.slice(22));E.phase==="node_begin"?y.currentNode=E.node:E.phase==="node_end"&&(E.node&&!y.completedNodes.includes(E.node)&&y.completedNodes.push(E.node),y.currentNode===E.node&&(y.currentNode=null))}catch{}return}let U=R.match(/Session\s+(\S+)/);if(U&&!y.sessionId&&(y.sessionId=U[1],y.sessionPath=ie(t,Ze,Ye,y.sessionId)),R.startsWith("\u250C ")||R.startsWith("\u250C ")){let E=R.slice(2).trim();y.currentNode=E,Ae&&L(S,"\u25B6",`${E}`)}else if(R.startsWith("\u2514 ")||R.startsWith("\u2514 ")){let E=R.slice(2).trim();E.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),Ae&&L(S,"\u2714",`${y.currentNode||"node"} done ${E.replace("done","").trim()}`),y.currentNode=null):E.startsWith("failed")&&(Ae&&L(S,"\u2718",`${y.currentNode||"node"} failed ${E.replace("failed","").trim()}`),y.currentNode=null)}else R.includes("Workflow completed")&&(y.currentNode=null,Ae&&L(S,"\u2714",`Workflow completed (${Zt(Date.now()-y.startTime)})`))}function De(A){let R=A.toString();y.output+=R,f.write(R),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),j+=R;let U=j.split(`
537
- `);j=U.pop();for(let E of U)Y(E)}return b.stdout.on("data",De),b.stderr.on("data",A=>{let R=A.toString();y.error+=R,f.write(R),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),b.on("close",A=>{y.status=A===0?"passed":"failed",y.exitCode=A,y.endTime=Date.now(),j&&Y(j),f.end();let R=Zt(Date.now()-y.startTime);if(A===0?L(S,"\u2705",`Passed (${R})`):L(S,"\u274C",`Failed (${R})`),y.isInline)try{bn(y.specPath)}catch{}Vt()}),b.on("error",A=>{y.status="error",y.error+=`
538
- Spawn error: ${A.message}`,L(S,"\u274C",`Spawn error: ${A.message}`),f.end(),Vt()}),y._child=b,C.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:b.pid,logFile:m})}function er(s){let t=Math.round(((s.endTime||Date.now())-s.startTime)/1e3),e=s.completedNodes||[],r=s.currentNode||null;if(s.status!=="running")return{elapsed:t,stage:s.status,completedNodes:e,currentNode:null};let i;return r?(i=`Actively executing node "${r}"`,e.length&&(i+=` (completed: ${e.join(", ")})`)):e.length?i=`Between nodes (completed: ${e.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${t}s. This is normal progress \u2014 do not cancel.`,{elapsed:t,stage:"running",currentNode:r,completedNodes:e,progress:i}}function En(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let n=[...C.entries()].map(([l,p])=>{let u=er(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=n.filter(l=>l.status==="running").length,a=n.filter(l=>l.status==="passed").length,c=n.filter(l=>l.status==="failed").length,d={total:n.length,running:o,passed:a,failed:c,runs:n};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let e=C.get(t);if(!e)return JSON.stringify({error:`Run not found: ${t}`});let r=er(e),i={runId:t,spec:e.spec,ticketKey:e.ticketKey,status:e.status,elapsed:r.elapsed,exitCode:e.exitCode,sessionId:e.sessionId||null};return e.status==="running"?(i.currentNode=r.currentNode,i.completedNodes=r.completedNodes,i.progress=r.progress):(i.outputTail=e.output.slice(-1e3),i.errorTail=e.error.slice(-500)),e.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function tr(s,t){if(t.status==="queued"){let e=Q.findIndex(r=>r.args._queuedRunId===s);return e>=0&&Q.splice(e,1),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}if(t.status!=="running")return{ok:!1,runId:s,error:`Run is not active (status: ${t.status})`};try{return t._child.kill("SIGTERM"),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}catch(e){return{ok:!1,runId:s,error:`Failed to cancel: ${e.message}`}}}function xn(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let r=[];for(let[i,n]of C.entries())(n.status==="running"||n.status==="queued")&&r.push(tr(i,n));return r.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:r.length,results:r})}let e=C.get(t);return JSON.stringify(e?tr(t,e):{error:`Run not found: ${t}`})}function Ln(s,t){let e=C.get(s);if(e?.sessionPath&&G(e.sessionPath))return e.sessionPath;if(e?.sessionId){let r=ie(t,Ze,Ye,e.sessionId);if(G(r))return r}return null}function dr(s,t=""){let e=[];if(!G(s))return e;for(let r of Te(s,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;if(r.isDirectory())e.push(...dr(B(s,r.name),i));else{let n=wn(B(s,r.name));e.push({path:i,size:n.size})}}return e}function rr(s){if(!G(s))return null;try{return JSON.parse($e(s,"utf-8"))}catch{return null}}function pr(s,t=2e3){if(!s||!G(s))return"";try{return $e(s,"utf-8").slice(-Math.max(200,Number(t)||2e3))}catch{return""}}function Cn({run:s,logTail:t,errorTail:e}){let i=`${t||""}
539
- ${e||""}`.toLowerCase(),n={runId:s?.runId||null,status:s?.status||null,exitCode:s?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return s?.status==="running"||s?.status==="queued"?{...n,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:i.includes("test spec not found")?{...n,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:i.includes("unknown command")&&i.includes("'run'")?{...n,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:i.includes("missing openai_api_key")||i.includes("didn't provide an api key")||i.includes("401")?{...n,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:i.includes("spawn error")||i.includes("enoent")?{...n,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:i.includes("security command failed")||i.includes("security process exited with code: 45")||i.includes("password not found for account")?{...n,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:n}function Pn(s,t){let{runId:e,type:r,node:i="execute_live",query:n,tail:o=3e3}=s;if(r==="search"){if(!n)return JSON.stringify({error:'query is required for type="search"'});let c=ie(t,Ze,Ye);if(!G(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=n.toLowerCase();for(let p of Te(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=B(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let _=B(u,f);if(G(_))try{let g=$e(_,"utf-8");if(g.toLowerCase().includes(l)){let b=g.toLowerCase().indexOf(l),y=Math.max(0,b-100),S=Math.min(g.length,b+n.length+100);d.push({sessionId:p.name,artifact:h,snippet:g.slice(y,S)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:n,matches:d,total:d.length})}if(!e)return JSON.stringify({error:"runId is required for this type"});if(r==="log"){let c=C.get(e),d=pr(c?.logPath,o);if(d)return JSON.stringify({runId:e,source:"run-log",totalLength:d.length,tail:d})}let a=Ln(e,t);if(!a)return JSON.stringify({error:`No session found for run ${e}. The run may still be starting.`});switch(r){case"list":{let c=dr(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=rr(B(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=rr(B(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=B(a,i,"raw_stream_output.txt");if(!G(c))return JSON.stringify({error:`No log found in ${i}`});let d=$e(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${r}. Use: list, result, events, log, search`})}}function qn(s,t){let e=String(s?.runId||"all"),r=Number(s?.tail||2e3),i=e==="all"?[...C.keys()]:[e];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let n=i.map(c=>{let d=C.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=pr(d.logPath,r),p=String(d.error||"").slice(-Math.max(200,r));return{...Cn({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=n.filter(c=>c.status==="failed"||c.status==="error"),a=n.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:n.length,failed:o.length,active:a.length,diagnoses:n})}function Jn(s,t){let e=s?.directory||"test-specs",r=ie(t,e);if(!G(r))return JSON.stringify({specs:[],directory:e,message:`Directory not found: ${e}`});try{let n=function(o,a){for(let c of Te(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?n(B(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return n(r,""),JSON.stringify({specs:i.map(o=>`${e}/${o}`),total:i.length,directory:e})}catch(i){return JSON.stringify({error:i.message})}}import{spawn as Un}from"child_process";import{existsSync as F,mkdirSync as Mn,readdirSync as ur,statSync as Dn,readFileSync as Bn}from"fs";import{resolve as Qe,join as H,basename as Kn}from"path";var Xe=".zibby/repos";function Ee(s,t,e={}){return new Promise((r,i)=>{let n=Un(s,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),o="",a="";n.stdout.on("data",c=>{o+=c.toString()}),n.stderr.on("data",c=>{a+=c.toString()}),n.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):r(o.trim())}),n.on("error",c=>i(c))})}var X={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
539
+ ...[truncated]`),{inlineSpec:`inline:${l}`,issueKey:s}):null}catch{return null}}function Tn(s,t){try{let e=JSON.parse(s);return JSON.stringify({...e,...t})}catch{return s}}async function $n(s,t,e){let r={...s},i=String(r.spec??"").trim();if(!i)return JSON.stringify({error:"spec is required"});let n=null;if(Xt.test(i)&&!i.startsWith("inline:")){let l=await jn(i);l&&(i=l.inlineSpec,r.spec=i,String(r.ticketKey||"").trim()||(r.ticketKey=l.issueKey),n=l.issueKey)}let o=String(r.ticketKey||"").trim();if(o){for(let[l,p]of P.entries())if(p?.ticketKey===o&&!(p?.status!=="running"&&p?.status!=="queued"))return JSON.stringify({runId:l,ticketKey:o,status:p.status,reused:!0,message:`A run for ${o} is already ${p.status}. Reusing existing run instead of starting a duplicate.`})}if(!i.startsWith("inline:")){let l=ie(t,i);if(!G(l))return Xt.test(i)?JSON.stringify({error:`Invalid run_test spec: "${i}" is an issue id, not a spec.`,reason:"Jira auto-load was attempted but did not return usable text, or Jira is not configured.",doNext:["Confirm the jira skill is active and authenticated.",'Or call tracker tools yourself, then run_test with spec: "inline:" + steps.'],validExample:{spec:"inline:1. Open https://example.com \u2026 2. Verify \u2026",ticketKey:i},invalidExample:{spec:i,ticketKey:i}}):JSON.stringify({error:`Test spec not found: ${i}`,hint:'If this should be issue steps, load the issue with your tracker tools first, then run_test with spec: "inline:" + steps. Otherwise use a real file path.'})}let a=ir(e?.options?.config);if(We()>=a){let l=or(),p=r.ticketKey||l,u={runId:l,spec:r.ticketKey?`${r.ticketKey}: ${r.spec}`:r.spec,ticketKey:r.ticketKey||null,status:"queued",startTime:Date.now(),exitCode:null,output:"",error:""};P.set(l,u),Q.push({args:{...r,_queuedRunId:l},cwd:t,context:e}),C(p,"\u23F3",`Queued (${We()}/${a} running, ${Q.length} queued)`);let m={runId:l,spec:u.spec,ticketKey:u.ticketKey,status:"queued",message:`Queued \u2014 will start when a slot opens (max ${a} concurrent).`};return n&&(m.resolvedFromJiraIssue=n,m.message+=` (spec built from Jira ${n})`),JSON.stringify(m)}let c=Date.now()-ze;c<Yt&&ze>0&&await new Promise(l=>setTimeout(l,Yt-c)),ze=Date.now();let d=lr(r,t,e);return n?Tn(d,{resolvedFromJiraIssue:n,message:`Spec was loaded from Jira issue ${n} (description + comments).`}):d}function lr(s,t,e){let{spec:r,ticketKey:i,agent:n,headless:o,workflow:a,_queuedRunId:c}=s,d=c||or(),l=r,p=!1;if(r.startsWith("inline:")){p=!0;let A=Sn(t);Wt(A,{recursive:!0}),l=B(A,`${d}.txt`),_n(l,r.slice(7).trim(),"utf-8")}let u=ie(t,".zibby","output","runs");Wt(u,{recursive:!0});let m=B(u,`${d}.log`),f=kn(m,{flags:"a"}),_=n&&["assistant","cursor","claude","codex","gemini"].includes(n)?n:null,g=["test",l];_&&g.push("--agent",_),o&&g.push("--headless"),a&&g.push("--workflow",a),nr&&console.error(`[zibby:spawn] skill=run_test parentPid=${process.pid} \u2192 child zibby ${g.map(A=>/\s/.test(A)?JSON.stringify(A):A).join(" ")} cwd=${t}`);let b=sr("zibby",g,{cwd:t,env:{...process.env,ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS:"1"},stdio:["ignore","pipe","pipe"],detached:!1}),y={runId:d,spec:i?`${i}: ${r}`:r,ticketKey:i||null,specPath:l,logPath:m,isInline:p,pid:b.pid,status:"running",output:"",error:"",startTime:Date.now(),exitCode:null,currentNode:null,completedNodes:[]},S=i||d,j="";function Y(A){let R=ar(A).trim();if(!R)return;if(R.startsWith("__WORKFLOW_GRAPH_LOG__")){try{let E=JSON.parse(R.slice(22));E.phase==="node_begin"?y.currentNode=E.node:E.phase==="node_end"&&(E.node&&!y.completedNodes.includes(E.node)&&y.completedNodes.push(E.node),y.currentNode===E.node&&(y.currentNode=null))}catch{}return}let M=R.match(/Session\s+(\S+)/);if(M&&!y.sessionId&&(y.sessionId=M[1],y.sessionPath=ie(t,Ze,Ye,y.sessionId)),R.startsWith("\u250C ")||R.startsWith("\u250C ")){let E=R.slice(2).trim();y.currentNode=E,Ae&&C(S,"\u25B6",`${E}`)}else if(R.startsWith("\u2514 ")||R.startsWith("\u2514 ")){let E=R.slice(2).trim();E.startsWith("done")?(y.currentNode&&!y.completedNodes.includes(y.currentNode)&&y.completedNodes.push(y.currentNode),Ae&&C(S,"\u2714",`${y.currentNode||"node"} done ${E.replace("done","").trim()}`),y.currentNode=null):E.startsWith("failed")&&(Ae&&C(S,"\u2718",`${y.currentNode||"node"} failed ${E.replace("failed","").trim()}`),y.currentNode=null)}else R.includes("Workflow completed")&&(y.currentNode=null,Ae&&C(S,"\u2714",`Workflow completed (${Zt(Date.now()-y.startTime)})`))}function De(A){let R=A.toString();y.output+=R,f.write(R),y.output.length>5e4&&(y.output=y.output.slice(-3e4)),j+=R;let M=j.split(`
540
+ `);j=M.pop();for(let E of M)Y(E)}return b.stdout.on("data",De),b.stderr.on("data",A=>{let R=A.toString();y.error+=R,f.write(R),y.error.length>2e4&&(y.error=y.error.slice(-1e4))}),b.on("close",A=>{y.status=A===0?"passed":"failed",y.exitCode=A,y.endTime=Date.now(),j&&Y(j),f.end();let R=Zt(Date.now()-y.startTime);if(A===0?C(S,"\u2705",`Passed (${R})`):C(S,"\u274C",`Failed (${R})`),y.isInline)try{bn(y.specPath)}catch{}Vt()}),b.on("error",A=>{y.status="error",y.error+=`
541
+ Spawn error: ${A.message}`,C(S,"\u274C",`Spawn error: ${A.message}`),f.end(),Vt()}),y._child=b,P.set(d,y),JSON.stringify({runId:d,spec:y.spec,ticketKey:y.ticketKey,status:"running",pid:b.pid,logFile:m})}function er(s){let t=Math.round(((s.endTime||Date.now())-s.startTime)/1e3),e=s.completedNodes||[],r=s.currentNode||null;if(s.status!=="running")return{elapsed:t,stage:s.status,completedNodes:e,currentNode:null};let i;return r?(i=`Actively executing node "${r}"`,e.length&&(i+=` (completed: ${e.join(", ")})`)):e.length?i=`Between nodes (completed: ${e.join(", ")})`:i="Starting up (initializing workflow)",i+=`. Elapsed: ${t}s. This is normal progress \u2014 do not cancel.`,{elapsed:t,stage:"running",currentNode:r,completedNodes:e,progress:i}}function En(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let n=[...P.entries()].map(([l,p])=>{let u=er(p),m={runId:l,spec:p.spec,ticketKey:p.ticketKey,status:p.status,elapsed:u.elapsed,exitCode:p.exitCode,sessionId:p.sessionId||null};return p.status==="running"?(m.currentNode=u.currentNode,m.completedNodes=u.completedNodes,m.progress=u.progress):m.outputTail=p.output.slice(-500),m}),o=n.filter(l=>l.status==="running").length,a=n.filter(l=>l.status==="passed").length,c=n.filter(l=>l.status==="failed").length,d={total:n.length,running:o,passed:a,failed:c,runs:n};return o>0&&(d._hint="All running tests are progressing normally through their workflow nodes. Do NOT cancel, diagnose, or interpret as stuck. Just tell the user they are still running."),JSON.stringify(d)}let e=P.get(t);if(!e)return JSON.stringify({error:`Run not found: ${t}`});let r=er(e),i={runId:t,spec:e.spec,ticketKey:e.ticketKey,status:e.status,elapsed:r.elapsed,exitCode:e.exitCode,sessionId:e.sessionId||null};return e.status==="running"?(i.currentNode=r.currentNode,i.completedNodes=r.completedNodes,i.progress=r.progress):(i.outputTail=e.output.slice(-1e3),i.errorTail=e.error.slice(-500)),e.status==="running"&&(i._hint="This run is actively progressing. Do NOT cancel, diagnose, or assume stuck. Just tell the user it is still running."),JSON.stringify(i)}function tr(s,t){if(t.status==="queued"){let e=Q.findIndex(r=>r.args._queuedRunId===s);return e>=0&&Q.splice(e,1),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}if(t.status!=="running")return{ok:!1,runId:s,error:`Run is not active (status: ${t.status})`};try{return t._child.kill("SIGTERM"),t.status="cancelled",t.endTime=Date.now(),{ok:!0,runId:s,status:"cancelled"}}catch(e){return{ok:!1,runId:s,error:`Failed to cancel: ${e.message}`}}}function Ln(s){let{runId:t}=s;if(!t)return JSON.stringify({error:"runId is required"});if(t==="all"){let r=[];for(let[i,n]of P.entries())(n.status==="running"||n.status==="queued")&&r.push(tr(i,n));return r.length===0?JSON.stringify({ok:!0,message:"No active runs to cancel"}):JSON.stringify({ok:!0,cancelled:r.length,results:r})}let e=P.get(t);return JSON.stringify(e?tr(t,e):{error:`Run not found: ${t}`})}function xn(s,t){let e=P.get(s);if(e?.sessionPath&&G(e.sessionPath))return e.sessionPath;if(e?.sessionId){let r=ie(t,Ze,Ye,e.sessionId);if(G(r))return r}return null}function dr(s,t=""){let e=[];if(!G(s))return e;for(let r of $e(s,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;if(r.isDirectory())e.push(...dr(B(s,r.name),i));else{let n=wn(B(s,r.name));e.push({path:i,size:n.size})}}return e}function rr(s){if(!G(s))return null;try{return JSON.parse(Te(s,"utf-8"))}catch{return null}}function pr(s,t=2e3){if(!s||!G(s))return"";try{return Te(s,"utf-8").slice(-Math.max(200,Number(t)||2e3))}catch{return""}}function Cn({run:s,logTail:t,errorTail:e}){let i=`${t||""}
542
+ ${e||""}`.toLowerCase(),n={runId:s?.runId||null,status:s?.status||null,exitCode:s?.exitCode??null,likelyCause:"Unknown failure",confidence:"low",nextStep:'Call run_artifacts({ runId, type: "log" }) with larger tail and inspect full logs.'};return s?.status==="running"||s?.status==="queued"?{...n,likelyCause:"Run is still active; no terminal failure to diagnose yet.",confidence:"high",nextStep:'Call run_status({ runId: "all" }) to check progress.'}:i.includes("test spec not found")?{...n,likelyCause:"Invalid spec input: run_test received a non-existent spec path.",confidence:"high",nextStep:"Use spec as inline:... or a real file path from list_specs. For ticket keys, fetch steps first via Jira then build inline spec."}:i.includes("unknown command")&&i.includes("'run'")?{...n,likelyCause:"CLI command mismatch (`zibby run` unsupported in current CLI).",confidence:"high",nextStep:"Use `zibby test ...` spawn path (runner should already do this)."}:i.includes("missing openai_api_key")||i.includes("didn't provide an api key")||i.includes("401")?{...n,likelyCause:"Provider authentication/config issue (API key/proxy auth missing or rejected).",confidence:"medium",nextStep:"Verify proxy/token env and auth mode, then retry once configuration is valid."}:i.includes("spawn error")||i.includes("enoent")?{...n,likelyCause:"Failed to spawn CLI process (binary/path/environment issue).",confidence:"medium",nextStep:"Confirm `zibby` is installed and available in PATH for the chat process."}:i.includes("security command failed")||i.includes("security process exited with code: 45")||i.includes("password not found for account")?{...n,likelyCause:"Cursor agent keychain/auth failed during preflight (often transient, more common under parallel starts).",confidence:"high",nextStep:'Retry failed ticket sequentially (not parallel), or run with a different agent via run_test({ ..., agent: "codex" }).'}:n}function Pn(s,t){let{runId:e,type:r,node:i="execute_live",query:n,tail:o=3e3}=s;if(r==="search"){if(!n)return JSON.stringify({error:'query is required for type="search"'});let c=ie(t,Ze,Ye);if(!G(c))return JSON.stringify({matches:[],message:"No sessions found"});let d=[],l=n.toLowerCase();for(let p of $e(c,{withFileTypes:!0})){if(!p.isDirectory())continue;let u=B(c,p.name),m=[{file:"execute_live/result.json",label:"result"},{file:"execute_live/events.json",label:"events"},{file:"execute_live/raw_stream_output.txt",label:"log"},{file:"generate_script/raw_stream_output.txt",label:"script_log"},{file:"title.txt",label:"title"}];for(let{file:f,label:h}of m){let _=B(u,f);if(G(_))try{let g=Te(_,"utf-8");if(g.toLowerCase().includes(l)){let b=g.toLowerCase().indexOf(l),y=Math.max(0,b-100),S=Math.min(g.length,b+n.length+100);d.push({sessionId:p.name,artifact:h,snippet:g.slice(y,S)})}}catch{}}if(d.length>=20)break}return JSON.stringify({query:n,matches:d,total:d.length})}if(!e)return JSON.stringify({error:"runId is required for this type"});if(r==="log"){let c=P.get(e),d=pr(c?.logPath,o);if(d)return JSON.stringify({runId:e,source:"run-log",totalLength:d.length,tail:d})}let a=xn(e,t);if(!a)return JSON.stringify({error:`No session found for run ${e}. The run may still be starting.`});switch(r){case"list":{let c=dr(a);return JSON.stringify({sessionId:a.split("/").pop(),files:c,total:c.length})}case"result":{let c=rr(B(a,i,"result.json"));return JSON.stringify(c?{sessionId:a.split("/").pop(),node:i,result:c}:{error:`No result.json found in ${i}`})}case"events":{let c=rr(B(a,i,"events.json"));if(!c)return JSON.stringify({error:`No events.json found in ${i}`});let d=Array.isArray(c)?c:c.events||[];return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalEvents:d.length,events:d.slice(-50)})}case"log":{let c=B(a,i,"raw_stream_output.txt");if(!G(c))return JSON.stringify({error:`No log found in ${i}`});let d=Te(c,"utf-8");return JSON.stringify({sessionId:a.split("/").pop(),node:i,totalLength:d.length,tail:d.slice(-o)})}default:return JSON.stringify({error:`Unknown artifact type: ${r}. Use: list, result, events, log, search`})}}function qn(s,t){let e=String(s?.runId||"all"),r=Number(s?.tail||2e3),i=e==="all"?[...P.keys()]:[e];if(i.length===0)return JSON.stringify({error:"No runs available to diagnose. Call run_test first."});let n=i.map(c=>{let d=P.get(c);if(!d)return{runId:c,error:`Run not found: ${c}`};let l=pr(d.logPath,r),p=String(d.error||"").slice(-Math.max(200,r));return{...Cn({run:d,logTail:l,errorTail:p}),ticketKey:d.ticketKey||null,spec:d.spec,logTail:l,errorTail:p}}),o=n.filter(c=>c.status==="failed"||c.status==="error"),a=n.filter(c=>c.status==="running"||c.status==="queued");return JSON.stringify({total:n.length,failed:o.length,active:a.length,diagnoses:n})}function Jn(s,t){let e=s?.directory||"test-specs",r=ie(t,e);if(!G(r))return JSON.stringify({specs:[],directory:e,message:`Directory not found: ${e}`});try{let n=function(o,a){for(let c of $e(o,{withFileTypes:!0})){let d=a?`${a}/${c.name}`:c.name;c.isDirectory()?n(B(o,c.name),d):(c.name.endsWith(".txt")||c.name.endsWith(".md"))&&i.push(d)}},i=[];return n(r,""),JSON.stringify({specs:i.map(o=>`${e}/${o}`),total:i.length,directory:e})}catch(i){return JSON.stringify({error:i.message})}}import{spawn as Un}from"child_process";import{existsSync as F,mkdirSync as Mn,readdirSync as ur,statSync as Dn,readFileSync as Bn}from"fs";import{resolve as Qe,join as H,basename as Kn}from"path";var Xe=".zibby/repos";function Ee(s,t,e={}){return new Promise((r,i)=>{let n=Un(s,{cwd:t,shell:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...e}}),o="",a="";n.stdout.on("data",c=>{o+=c.toString()}),n.stderr.on("data",c=>{a+=c.toString()}),n.on("close",c=>{c!==0?i(new Error(`Exit ${c}: ${a.trim()||o.trim()}`)):r(o.trim())}),n.on("error",c=>i(c))})}var X={id:"git",description:"Clone and manage git repositories for codebase analysis",envKeys:["GITHUB_TOKEN","GITLAB_TOKEN"],promptFragment:`## Git Repositories
540
543
  You can clone and explore git repositories locally for codebase analysis:
541
544
  - git_checkout: Clone a repo (or pull if already cloned). Supports GitHub and GitLab with auto-auth.
542
545
  - git_list_repos: List locally cloned repos
@@ -559,7 +562,7 @@ After you have pushed a branch, OPEN the PR/MR with the provider-agnostic tool:
559
562
  To MERGE an open PR/MR, use the provider-agnostic tool:
560
563
  - git_merge_pr: Merge a pull request (GitHub) or accept a merge request (GitLab) by number. Provider is auto-detected from \`repoUrl\`. Args:
561
564
  { repoUrl, number (the PR/MR number; GitLab alias: iid), mergeMethod? ('merge'|'squash'|'rebase', GitHub only; default 'squash') }
562
- Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(s,t,e){if(s!=="git_open_pr"&&s!=="git_merge_pr")return X.handleToolCall(s,t,e);try{let r=t||{},i=r.repoUrl||r.repo_url||r.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(s==="git_merge_pr"){let l=r.number??r.iid??r.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=mr(i);return p?p.provider==="github"?ae.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:r.mergeMethod},e):ce.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let n=r.head||r.source_branch||r.sourceBranch||r.branch,o=r.base||r.target_branch||r.targetBranch,{title:a,body:c}=r;if(!n||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=mr(i);return d?d.provider==="github"?ae.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:n,base:o,title:a,body:c},e):ce.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:n,target_branch:o,title:a,description:c},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(r){return JSON.stringify({error:r.message})}},tools:[...X.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};import{execFileSync as br}from"child_process";import{existsSync as nt,mkdirSync as kr}from"fs";import{join as z,basename as zn}from"path";import{randomBytes as Wn}from"crypto";import{pathToFileURL as _e}from"url";import{createRequire as wr}from"module";var rt=".zibby/memory",Sr="dolt",vr={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},st="mem0",et=new Map,xe=new Map,Le=!1,Yn=wr(import.meta.url),Je=()=>Wn(8).toString("hex"),ne=()=>new Date().toISOString(),Zn=[`CREATE TABLE IF NOT EXISTS chat_memory (
565
+ Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) come back as { success:false, skippedReason } \u2014 a normal "not mergeable yet", not a hard failure.`,async handleToolCall(s,t,e){if(s!=="git_open_pr"&&s!=="git_merge_pr")return X.handleToolCall(s,t,e);try{let r=t||{},i=r.repoUrl||r.repo_url||r.url;if(!i)return JSON.stringify({error:"repoUrl is required (the github.com/gitlab.com repo to open/merge the PR/MR against)"});if(s==="git_merge_pr"){let l=r.number??r.iid??r.prNumber;if(l==null)return JSON.stringify({error:"number (the PR/MR number to merge; GitLab alias: iid) is required"});let p=mr(i);return p?p.provider==="github"?ae.handleToolCall("github_merge_pr",{owner:p.owner,repo:p.repo,number:l,mergeMethod:r.mergeMethod},e):ce.handleToolCall("gitlab_accept_mr",{project:`${p.owner}/${p.repo}`,iid:l},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_merge_pr supports github.com and gitlab.com.`})}let n=r.head||r.source_branch||r.sourceBranch||r.branch,o=r.base||r.target_branch||r.targetBranch,{title:a,body:c}=r;if(!n||!a)return JSON.stringify({error:"head (the pushed source branch) and title are required"});let d=mr(i);return d?d.provider==="github"?ae.handleToolCall("github_create_pr",{owner:d.owner,repo:d.repo,head:n,base:o,title:a,body:c},e):ce.handleToolCall("gitlab_create_mr",{project:`${d.owner}/${d.repo}`,source_branch:n,target_branch:o,title:a,description:c},e):JSON.stringify({success:!1,skippedReason:`Unrecognized repo host: ${i}. git_open_pr supports github.com and gitlab.com.`})}catch(r){return JSON.stringify({error:r.message})}},tools:[...X.tools||[],{name:"git_open_pr",description:"Open a pull request (GitHub) or merge request (GitLab) from an already-pushed branch. The provider is auto-detected from repoUrl. Returns the REAL provider-returned url (pr_url = GitHub html_url / GitLab web_url) \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR/MR already exists, base==head) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR is opened against (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},head:{type:"string",description:"Source branch to merge FROM (must already be pushed). GitLab alias: source_branch."},base:{type:"string",description:"Target branch to merge INTO (default: the repo/project default branch). GitLab alias: target_branch."},title:{type:"string",description:"PR/MR title"},body:{type:"string",description:"PR/MR description (markdown)"}},required:["repoUrl","head","title"]}},{name:"git_merge_pr",description:"Merge a pull request (GitHub) or accept a merge request (GitLab) by number. The provider is auto-detected from repoUrl. Returns { success:true, merged:true, sha } with the REAL merge SHA from the provider \u2014 never fabricate it. Expected non-mergeable states (draft, failing checks, conflicts, head sha moved, pipeline not done) return { success:false, skippedReason } rather than erroring. Delegates to the github/gitlab provider APIs (the same auth path the github_*/gitlab_* tools use).",input_schema:{type:"object",properties:{repoUrl:{type:"string",description:'The repo URL the PR/MR belongs to (e.g. "https://github.com/org/repo" or "https://gitlab.com/group/repo"). Provider is detected from the host.'},number:{type:"number",description:"The PR (GitHub) / MR (GitLab) number to merge. GitLab alias: iid."},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (GitHub only; default: squash). Ignored for GitLab."}},required:["repoUrl","number"]}}]};import{execFileSync as br}from"child_process";import{existsSync as nt,mkdirSync as kr}from"fs";import{join as z,basename as zn}from"path";import{randomBytes as Wn}from"crypto";import{pathToFileURL as _e}from"url";import{createRequire as wr}from"module";var rt=".zibby/memory",Sr="dolt",vr={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},st="mem0",et=new Map,Le=new Map,xe=!1,Yn=wr(import.meta.url),Je=()=>Wn(8).toString("hex"),ne=()=>new Date().toISOString(),Zn=[`CREATE TABLE IF NOT EXISTS chat_memory (
563
566
  id VARCHAR(64) PRIMARY KEY,
564
567
  memory_key VARCHAR(160),
565
568
  category VARCHAR(32) NOT NULL,
@@ -590,10 +593,10 @@ To MERGE an open PR/MR, use the provider-agnostic tool:
590
593
  tasks_failed INT DEFAULT 0,
591
594
  key_facts TEXT,
592
595
  created_at VARCHAR(32) NOT NULL
593
- )`],hr=new Set;function P(s,t){return br(Sr,t,{...vr,cwd:s})}function ee(s,t){try{let e=P(s,["sql","-q",t,"-r","json"]);return JSON.parse(e.trim()).rows||[]}catch{return[]}}function q(s,t){P(s,["sql","-q",t])}function Ce(s){if(hr.has(s))return!0;if(!nt(z(s,".dolt"))){if(!Vn())return!1;kr(s,{recursive:!0}),P(s,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let t=`${Zn.join(`;
594
- `)};`;q(s,t);try{q(s,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{q(s,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return hr.add(s),!0}function Vn(){try{return br(Sr,["version"],{...vr,timeout:5e3}),!0}catch{return!1}}function w(s){return s==null?"NULL":`'${String(s).replace(/'/g,"''")}'`}function it(s){return String(s||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function le(s){return s==="long"?3:s==="mid"?2:s==="short"?1:0}function ot(s,t){let e=["short","mid","long"].includes(s)?s:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(t||"").toLowerCase())&&e==="short"?"mid":e}function Nr(s){let t=new Map;for(let e of s||[]){let r=it(e.content),i=e.memory_key?`key:${e.memory_key}`:r?`norm:${r}`:"";if(!i)continue;let n=t.get(i);if(!n){t.set(i,e);continue}let o=le(n.tier),a=le(e.tier);if(a>o){t.set(i,e);continue}a===o&&Number(e.relevance||0)>Number(n.relevance||0)&&t.set(i,e)}return[...t.values()]}function qe(s,t){let e=String(s??"");return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}\u2026`}function ge(s,t){let e={recentSessions:Array.isArray(s?.recentSessions)?s.recentSessions:[],topMemories:Array.isArray(s?.topMemories)?s.topMemories:[],taskStats:Array.isArray(s?.taskStats)?s.taskStats:[],ticketFilter:s?.ticketFilter||null,backend:t||String(s?.backend||st),error:s?.error||null};return e.backend==="mem0"?{...e,recentSessions:[],taskStats:[]}:e}function yr(s){let t=[];if(s.recentSessions?.length>0){t.push("Recent sessions:");for(let e of s.recentSessions.slice(0,3))e?.summary?.trim()&&t.push(`- ${qe(e.summary,150)}${e.tickets?` [${e.tickets}]`:""}`)}if(s.topMemories?.length>0){t.push("Known facts:");for(let e of s.topMemories.slice(0,10)){let r=e.tier==="long"?"\u2605":"\xB7";t.push(`${r} [${e.category}] ${qe(e.content,120)}`)}}return t.length===0?"":`## Memory Context
596
+ )`],hr=new Set;function q(s,t){return br(Sr,t,{...vr,cwd:s})}function ee(s,t){try{let e=q(s,["sql","-q",t,"-r","json"]);return JSON.parse(e.trim()).rows||[]}catch{return[]}}function J(s,t){q(s,["sql","-q",t])}function Ce(s){if(hr.has(s))return!0;if(!nt(z(s,".dolt"))){if(!Vn())return!1;kr(s,{recursive:!0}),q(s,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let t=`${Zn.join(`;
597
+ `)};`;J(s,t);try{J(s,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{J(s,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return hr.add(s),!0}function Vn(){try{return br(Sr,["version"],{...vr,timeout:5e3}),!0}catch{return!1}}function w(s){return s==null?"NULL":`'${String(s).replace(/'/g,"''")}'`}function it(s){return String(s||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function le(s){return s==="long"?3:s==="mid"?2:s==="short"?1:0}function ot(s,t){let e=["short","mid","long"].includes(s)?s:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(t||"").toLowerCase())&&e==="short"?"mid":e}function Nr(s){let t=new Map;for(let e of s||[]){let r=it(e.content),i=e.memory_key?`key:${e.memory_key}`:r?`norm:${r}`:"";if(!i)continue;let n=t.get(i);if(!n){t.set(i,e);continue}let o=le(n.tier),a=le(e.tier);if(a>o){t.set(i,e);continue}a===o&&Number(e.relevance||0)>Number(n.relevance||0)&&t.set(i,e)}return[...t.values()]}function qe(s,t){let e=String(s??"");return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}\u2026`}function ge(s,t){let e={recentSessions:Array.isArray(s?.recentSessions)?s.recentSessions:[],topMemories:Array.isArray(s?.topMemories)?s.topMemories:[],taskStats:Array.isArray(s?.taskStats)?s.taskStats:[],ticketFilter:s?.ticketFilter||null,backend:t||String(s?.backend||st),error:s?.error||null};return e.backend==="mem0"?{...e,recentSessions:[],taskStats:[]}:e}function yr(s){let t=[];if(s.recentSessions?.length>0){t.push("Recent sessions:");for(let e of s.recentSessions.slice(0,3))e?.summary?.trim()&&t.push(`- ${qe(e.summary,150)}${e.tickets?` [${e.tickets}]`:""}`)}if(s.topMemories?.length>0){t.push("Known facts:");for(let e of s.topMemories.slice(0,10)){let r=e.tier==="long"?"\u2605":"\xB7";t.push(`${r} [${e.category}] ${qe(e.content,120)}`)}}return t.length===0?"":`## Memory Context
595
598
  ${t.join(`
596
- `)}`}function Pe(s){return{backend:s.backend,recentSessions:s.recentSessions.slice(0,3).map(t=>({summary:qe(String(t?.summary||""),160),tickets:t?.tickets||null,created_at:t?.created_at||null})),topMemories:s.topMemories.slice(0,8).map(t=>({category:t?.category||null,tier:t?.tier||null,content:qe(String(t?.content||""),140),source:t?.source||null})),taskStats:s.taskStats,error:s.error||null}}async function Qn(s,t){let e=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(e==="mem0"||e==="dolt")return e;let r=String(t?.options?.memoryBackend||t?.options?.config?.memory?.backend||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;if(xe.has(s))return xe.get(s);try{let i=z(s,".zibby.config.mjs");if(nt(i)){let n=await import(_e(i).href),o=String(n?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return xe.set(s,o),o}}catch{}return xe.set(s,st),st}function Ir(s){let t=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return t||`workspace:${zn(s||process.cwd())}`}var Xn="mem0";function Rr(s){let t=z(s,rt,Xn);return{dir:t,vectorDbPath:z(t,"vectors.db"),historyDbPath:z(t,"history.db")}}function eo(s){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),r=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),n=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=Rr(s||process.cwd());return{llm:{provider:"openai",config:{model:r,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:n,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:n,dbPath:o}},historyDbPath:a}}async function Or(s){let t=s||process.cwd();if(et.has(t))return et.get(t);let e;try{let a=wr(_e(z(t,"package.json")).href).resolve("mem0ai/oss");e=await import(_e(a).href)}catch{try{let o=Yn.resolve("mem0ai/oss");e=await import(_e(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${t}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let r=e?.Memory;if(!r)throw new Error("mem0ai/oss does not export Memory");let i=eo(t);if(i)try{kr(Rr(t).dir,{recursive:!0})}catch{}let n=i?new r(i):new r;return et.set(t,n),n}function gr(s,t="mid"){return(Array.isArray(s)?s:Array.isArray(s?.results)?s.results:[]).map(r=>({id:r?.id||Je(),memory_key:r?.metadata?.memoryKey||r?.metadata?.memory_key||null,category:r?.metadata?.category||"fact",content:r?.memory||r?.content||"",source:r?.metadata?.source||"mem0",ticket_key:r?.metadata?.ticketKey||r?.metadata?.ticket_key||null,tier:ot(r?.metadata?.tier||t,r?.metadata?.category||"fact"),relevance:Number(r?.score??r?.metadata?.relevance??.8),created_at:r?.created_at||r?.metadata?.created_at||ne()})).filter(r=>String(r.content||"").trim().length>0)}var de={id:"dolt",store:(s,t)=>jr(s,t),recall:(s,t)=>oo(s,t),brief:(s,t)=>ao(s,t),endSession:(s,t)=>Tr(s,t),logTask:(s,t)=>Er(s,t),taskHistory:(s,t)=>xr(s,t)},to={id:"mem0",store:(s,t,e)=>no(s,t,e),recall:(s,t,e)=>$r(s,t,e),brief:(s,t,e)=>co(s,t,e),endSession:(s,t)=>Tr(s,t),logTask:(s,t)=>Er(s,t),taskHistory:(s,t)=>xr(s,t)},ro={dolt:de,mem0:to};async function _r(s,t){let e=await Qn(s,t);return ro[e]||de}var Ar={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
599
+ `)}`}function Pe(s){return{backend:s.backend,recentSessions:s.recentSessions.slice(0,3).map(t=>({summary:qe(String(t?.summary||""),160),tickets:t?.tickets||null,created_at:t?.created_at||null})),topMemories:s.topMemories.slice(0,8).map(t=>({category:t?.category||null,tier:t?.tier||null,content:qe(String(t?.content||""),140),source:t?.source||null})),taskStats:s.taskStats,error:s.error||null}}async function Qn(s,t){let e=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(e==="mem0"||e==="dolt")return e;let r=String(t?.options?.memoryBackend||t?.options?.config?.memory?.backend||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;if(Le.has(s))return Le.get(s);try{let i=z(s,".zibby.config.mjs");if(nt(i)){let n=await import(_e(i).href),o=String(n?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return Le.set(s,o),o}}catch{}return Le.set(s,st),st}function Ir(s){let t=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return t||`workspace:${zn(s||process.cwd())}`}var Xn="mem0";function Rr(s){let t=z(s,rt,Xn);return{dir:t,vectorDbPath:z(t,"vectors.db"),historyDbPath:z(t,"history.db")}}function eo(s){let t=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!t)return null;let e=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),r=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),i=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),n=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:a}=Rr(s||process.cwd());return{llm:{provider:"openai",config:{model:r,baseURL:t,...e?{apiKey:e}:{}}},embedder:{provider:"openai",config:{model:i,embeddingDims:n,baseURL:t,...e?{apiKey:e}:{}}},vectorStore:{provider:"memory",config:{dimension:n,dbPath:o}},historyDbPath:a}}async function Or(s){let t=s||process.cwd();if(et.has(t))return et.get(t);let e;try{let a=wr(_e(z(t,"package.json")).href).resolve("mem0ai/oss");e=await import(_e(a).href)}catch{try{let o=Yn.resolve("mem0ai/oss");e=await import(_e(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${t}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let r=e?.Memory;if(!r)throw new Error("mem0ai/oss does not export Memory");let i=eo(t);if(i)try{kr(Rr(t).dir,{recursive:!0})}catch{}let n=i?new r(i):new r;return et.set(t,n),n}function gr(s,t="mid"){return(Array.isArray(s)?s:Array.isArray(s?.results)?s.results:[]).map(r=>({id:r?.id||Je(),memory_key:r?.metadata?.memoryKey||r?.metadata?.memory_key||null,category:r?.metadata?.category||"fact",content:r?.memory||r?.content||"",source:r?.metadata?.source||"mem0",ticket_key:r?.metadata?.ticketKey||r?.metadata?.ticket_key||null,tier:ot(r?.metadata?.tier||t,r?.metadata?.category||"fact"),relevance:Number(r?.score??r?.metadata?.relevance??.8),created_at:r?.created_at||r?.metadata?.created_at||ne()})).filter(r=>String(r.content||"").trim().length>0)}var de={id:"dolt",store:(s,t)=>jr(s,t),recall:(s,t)=>oo(s,t),brief:(s,t)=>ao(s,t),endSession:(s,t)=>$r(s,t),logTask:(s,t)=>Er(s,t),taskHistory:(s,t)=>Lr(s,t)},to={id:"mem0",store:(s,t,e)=>no(s,t,e),recall:(s,t,e)=>Tr(s,t,e),brief:(s,t,e)=>co(s,t,e),endSession:(s,t)=>$r(s,t),logTask:(s,t)=>Er(s,t),taskHistory:(s,t)=>Lr(s,t)},ro={dolt:de,mem0:to};async function _r(s,t){let e=await Qn(s,t);return ro[e]||de}var Ar={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
597
600
  You have persistent memory across sessions. Use it to avoid losing context:
598
601
  - **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
599
602
  - **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
@@ -609,13 +612,13 @@ You have persistent memory across sessions. Use it to avoid losing context:
609
612
  - When the user's request is complete: call memory_end_session
610
613
 
611
614
  ### Categories for memory_store
612
- fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(s,t={}){let e=s?.options?.workspace||process.cwd(),r=z(e,rt),i=await _r(e,s),n=i.id;if(n==="dolt"&&!Ce(r)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:n,brief:ge({backend:n,error:o},n),promptContext:"",debugPreview:Pe(ge({backend:n,error:o},n)),error:o}}try{let o=await i.brief(t,r,e),a=JSON.parse(o||"{}"),c=ge({...a,backend:n},n);return{backend:n,brief:c,promptContext:yr(c),debugPreview:Pe(c),error:c.error||null}}catch(o){if(n==="mem0"&&i!==de&&Ce(r)){if(!Le){Le=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
613
- `)}catch{}}try{let d=await de.brief(t,r,e),l=JSON.parse(d||"{}"),p=ge({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:yr(p),debugPreview:Pe(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=ge({backend:n,error:a},n);return{backend:n,brief:c,promptContext:"",debugPreview:Pe(c),error:a}}},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd(),i=z(r,rt),n=await _r(r,e),o=n.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(s))&&!Ce(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(s){case"memory_store":return d.store(t,i,r);case"memory_recall":return d.recall(t,i,r);case"memory_brief":return d.brief(t,i,r);case"memory_end_session":return d.endSession(t,i,r);case"task_log":return d.logTask(t,i,r);case"task_history":return d.taskHistory(t,i,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}};try{return await c(n)}catch(d){if(o==="mem0"&&n!==de){if(Ce(i)){if(!Le){Le=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
615
+ fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(s,t={}){let e=s?.options?.workspace||process.cwd(),r=z(e,rt),i=await _r(e,s),n=i.id;if(n==="dolt"&&!Ce(r)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:n,brief:ge({backend:n,error:o},n),promptContext:"",debugPreview:Pe(ge({backend:n,error:o},n)),error:o}}try{let o=await i.brief(t,r,e),a=JSON.parse(o||"{}"),c=ge({...a,backend:n},n);return{backend:n,brief:c,promptContext:yr(c),debugPreview:Pe(c),error:c.error||null}}catch(o){if(n==="mem0"&&i!==de&&Ce(r)){if(!xe){xe=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
616
+ `)}catch{}}try{let d=await de.brief(t,r,e),l=JSON.parse(d||"{}"),p=ge({...l,backend:"dolt"},"dolt");return{backend:"dolt",brief:p,promptContext:yr(p),debugPreview:Pe(p),error:p.error||null,degradedFrom:"mem0"}}catch{}}let a=String(o?.message||o),c=ge({backend:n,error:a},n);return{backend:n,brief:c,promptContext:"",debugPreview:Pe(c),error:a}}},async handleToolCall(s,t,e){let r=e?.options?.workspace||process.cwd(),i=z(r,rt),n=await _r(r,e),o=n.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(s))&&!Ce(i))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let c=d=>{switch(s){case"memory_store":return d.store(t,i,r);case"memory_recall":return d.recall(t,i,r);case"memory_brief":return d.brief(t,i,r);case"memory_end_session":return d.endSession(t,i,r);case"task_log":return d.logTask(t,i,r);case"task_history":return d.taskHistory(t,i,r);default:return JSON.stringify({error:`Unknown tool: ${s}`})}};try{return await c(n)}catch(d){if(o==="mem0"&&n!==de){if(Ce(i)){if(!xe){xe=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${d.message}); degrading to dolt for this run
614
617
  `)}catch{}}try{return await c(de)}catch(l){return JSON.stringify({error:l.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${d.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:d.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function jr(s,t){let{content:e,category:r,source:i,ticketKey:n,tier:o,memoryKey:a}=s;if(!e||!r)return JSON.stringify({error:"content and category are required"});let c=it(e);if(!c)return JSON.stringify({error:"content is empty after normalization"});let d=ot(o,r),l=d==="long"?1:d==="mid"?.8:.5,p=String(a||"").trim().slice(0,160);if(p){let g=ee(t,`SELECT id, tier, relevance
615
618
  FROM chat_memory
616
619
  WHERE memory_key = ${w(p)}
617
620
  ORDER BY created_at DESC
618
- LIMIT 1`)[0];if(g){let b=String(g.tier||"mid"),y=Number(g.relevance||0),S=le(d)>le(b)?d:b,j=Math.max(l,y);q(t,`UPDATE chat_memory
621
+ LIMIT 1`)[0];if(g){let b=String(g.tier||"mid"),y=Number(g.relevance||0),S=le(d)>le(b)?d:b,j=Math.max(l,y);J(t,`UPDATE chat_memory
619
622
  SET content = ${w(e)},
620
623
  category = ${w(r)},
621
624
  source = ${w(i)},
@@ -623,26 +626,26 @@ fact, decision, context, insight, credential, url, error, workaround`,resolve(){
623
626
  tier = ${w(S)},
624
627
  relevance = ${j},
625
628
  created_at = ${w(ne())}
626
- WHERE id = ${w(g.id)}`);try{P(t,["add","."]),P(t,["commit","-m",`memory upsert: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:g.id,category:r,tier:S,memoryKey:p,upserted:!0})}}let m=ee(t,`SELECT id, content, tier, relevance
629
+ WHERE id = ${w(g.id)}`);try{q(t,["add","."]),q(t,["commit","-m",`memory upsert: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:g.id,category:r,tier:S,memoryKey:p,upserted:!0})}}let m=ee(t,`SELECT id, content, tier, relevance
627
630
  FROM chat_memory
628
631
  WHERE category = ${w(r)}
629
632
  ORDER BY created_at DESC
630
- LIMIT 200`).find(_=>it(_.content)===c);if(m){let _=String(m.tier||"mid"),g=Number(m.relevance||0),b=le(d)>le(_),y=l>g;if(b||y){q(t,`UPDATE chat_memory
633
+ LIMIT 200`).find(_=>it(_.content)===c);if(m){let _=String(m.tier||"mid"),g=Number(m.relevance||0),b=le(d)>le(_),y=l>g;if(b||y){J(t,`UPDATE chat_memory
631
634
  SET tier = ${w(b?d:_)},
632
635
  relevance = ${Math.max(l,g)}
633
- WHERE id = ${w(m.id)}`);try{P(t,["add","."]),P(t,["commit","-m",`memory promote: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:r,tier:b?d:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:r,tier:_,deduped:!0,promoted:!1})}let f=Je(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;q(t,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
634
- VALUES (${w(f)}, ${w(p||null)}, ${w(r)}, ${w(e)}, ${w(i)}, ${w(n)}, ${w(h)}, ${w(d)}, ${l}, ${w(ne())})`);try{P(t,["add","."]),P(t,["commit","-m",`memory: ${r} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:r,tier:d,memoryKey:p||null,stored:e.slice(0,100)})}function so(s){let t=String(s||"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var tt=new Map;async function io(s,t){if(typeof s=="boolean")return s;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return so(process.env.ZIBBY_MEM0_INFER);let e=t||process.cwd();if(tt.has(e))return tt.get(e);let r=!1;try{let i=z(e,".zibby.config.mjs");nt(i)&&(r=(await import(_e(i).href))?.default?.memory?.infer===!0)}catch{}return tt.set(e,r),r}async function no(s,t,e){let{content:r,category:i,source:n,ticketKey:o,tier:a,memoryKey:c,infer:d}=s;if(!r||!i)return JSON.stringify({error:"content and category are required"});try{let l=await Or(e),p=Ir(e),u=ot(a,i),m=await io(d,e);return await l.add([{role:"user",content:String(r)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:i,tier:u,source:n||"zibby-chat",ticketKey:o||null,created_at:ne()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:i,tier:u,infer:m,memoryKey:c||null,stored:String(r).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function oo(s,t){let{query:e,category:r,ticketKey:i,tier:n,limit:o=20}=s,a=[];e&&a.push(`content LIKE ${w(`%${e}%`)}`),r&&a.push(`category = ${w(r)}`),i&&a.push(`ticket_key = ${w(i)}`),n&&a.push(`tier = ${w(n)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
636
+ WHERE id = ${w(m.id)}`);try{q(t,["add","."]),q(t,["commit","-m",`memory promote: ${r} \u2014 ${String(e).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:m.id,category:r,tier:b?d:_,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:m.id,category:r,tier:_,deduped:!0,promoted:!1})}let f=Je(),h=process.env.ZIBBY_CHAT_SESSION_ID||null;J(t,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
637
+ VALUES (${w(f)}, ${w(p||null)}, ${w(r)}, ${w(e)}, ${w(i)}, ${w(n)}, ${w(h)}, ${w(d)}, ${l}, ${w(ne())})`);try{q(t,["add","."]),q(t,["commit","-m",`memory: ${r} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:f,category:r,tier:d,memoryKey:p||null,stored:e.slice(0,100)})}function so(s){let t=String(s||"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var tt=new Map;async function io(s,t){if(typeof s=="boolean")return s;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return so(process.env.ZIBBY_MEM0_INFER);let e=t||process.cwd();if(tt.has(e))return tt.get(e);let r=!1;try{let i=z(e,".zibby.config.mjs");nt(i)&&(r=(await import(_e(i).href))?.default?.memory?.infer===!0)}catch{}return tt.set(e,r),r}async function no(s,t,e){let{content:r,category:i,source:n,ticketKey:o,tier:a,memoryKey:c,infer:d}=s;if(!r||!i)return JSON.stringify({error:"content and category are required"});try{let l=await Or(e),p=Ir(e),u=ot(a,i),m=await io(d,e);return await l.add([{role:"user",content:String(r)}],{userId:p,infer:m,metadata:{memoryKey:c||null,category:i,tier:u,source:n||"zibby-chat",ticketKey:o||null,created_at:ne()}}),JSON.stringify({ok:!0,backend:"mem0",userId:p,category:i,tier:u,infer:m,memoryKey:c||null,stored:String(r).slice(0,100)})}catch(l){throw new Error(`mem0 store failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function oo(s,t){let{query:e,category:r,ticketKey:i,tier:n,limit:o=20}=s,a=[];e&&a.push(`content LIKE ${w(`%${e}%`)}`),r&&a.push(`category = ${w(r)}`),i&&a.push(`ticket_key = ${w(i)}`),n&&a.push(`tier = ${w(n)}`);let d=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
635
638
  FROM chat_memory ${a.length>0?`WHERE ${a.join(" AND ")}`:""}
636
639
  ORDER BY relevance DESC, created_at DESC
637
- LIMIT ${o}`,l=ee(t,d);return JSON.stringify({total:l.length,memories:l})}async function $r(s,t,e){let{query:r,category:i,ticketKey:n,tier:o,limit:a=20}=s;try{let c=await Or(e),d=Ir(e),l=[];if(r&&String(r).trim()){let p=await c.search(String(r),{filters:{user_id:d},topK:a});l=gr(p)}else{let p=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=gr(p)}return i&&(l=l.filter(p=>p.category===i)),n&&(l=l.filter(p=>p.ticket_key===n)),o&&(l=l.filter(p=>p.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function ao(s,t){let{ticketKey:e}=s;po(t);let i=ee(t,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
640
+ LIMIT ${o}`,l=ee(t,d);return JSON.stringify({total:l.length,memories:l})}async function Tr(s,t,e){let{query:r,category:i,ticketKey:n,tier:o,limit:a=20}=s;try{let c=await Or(e),d=Ir(e),l=[];if(r&&String(r).trim()){let p=await c.search(String(r),{filters:{user_id:d},topK:a});l=gr(p)}else{let p=await c.getAll({filters:{user_id:d},topK:Math.max(a,50)});l=gr(p)}return i&&(l=l.filter(p=>p.category===i)),n&&(l=l.filter(p=>p.ticket_key===n)),o&&(l=l.filter(p=>p.tier===o)),l=l.slice(0,a),JSON.stringify({total:l.length,memories:l,backend:"mem0"})}catch(c){throw new Error(`mem0 recall failed: ${c.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:c})}}function ao(s,t){let{ticketKey:e}=s;po(t);let i=ee(t,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
638
641
  FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),n=e?`AND ticket_key = ${w(e)}`:"",o=ee(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
639
642
  WHERE tier = 'long' ${n} ORDER BY relevance DESC, created_at DESC LIMIT 10`),a=ee(t,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
640
643
  WHERE tier = 'mid' ${n} ORDER BY relevance DESC, created_at DESC LIMIT 8`),d=ee(t,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
641
- GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Nr([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:e||null})}async function co(s,t,e){let{ticketKey:r}=s,i=await $r({limit:80},t,e),n=JSON.parse(i||"{}"),o=Array.isArray(n.memories)?n.memories:[];r&&(o=o.filter(u=>u.ticket_key===r));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),d=o.filter(u=>u.tier==="long").sort(c).slice(0,10),l=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=Nr([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:r||null,backend:"mem0"})}function Tr(s,t){let{summary:e,tickets:r,tasksRun:i=0,tasksPassed:n=0,tasksFailed:o=0,keyFacts:a}=s;if(!e)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Je()}`;if(q(t,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
642
- VALUES (${w(c)}, ${w(e)}, ${w(r)}, ${i}, ${n}, ${o}, ${w(a)}, ${w(ne())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))jr({content:d,category:"fact",source:"session_summary",tier:"mid"},t);lo(t);try{P(t,["add","."]),P(t,["commit","-m",`session end: ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:e.slice(0,200)})}function Er(s,t){let{title:e,type:r,status:i,ticketKey:n,specPath:o,resultSummary:a}=s;if(!e||!r||!i)return JSON.stringify({error:"title, type, and status are required"});let c=Je(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;q(t,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
643
- VALUES (${w(c)}, ${w(n)}, ${w(r)}, ${w(e)}, ${w(i)}, ${w(o)}, ${w(d)}, ${w(a)}, ${w(ne())}, ${w(ne())})`);try{P(t,["add","."]),P(t,["commit","-m",`task: ${i} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:e,type:r,status:i})}function xr(s,t){let{ticketKey:e,type:r,status:i,limit:n=20}=s,o=[];e&&o.push(`ticket_key = ${w(e)}`),r&&o.push(`type = ${w(r)}`),i&&o.push(`status = ${w(i)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
644
+ GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),l=Nr([...o,...a]);return JSON.stringify({recentSessions:i,topMemories:l,taskStats:d,ticketFilter:e||null})}async function co(s,t,e){let{ticketKey:r}=s,i=await Tr({limit:80},t,e),n=JSON.parse(i||"{}"),o=Array.isArray(n.memories)?n.memories:[];r&&(o=o.filter(u=>u.ticket_key===r));let a=u=>{let m=Date.parse(String(u?.created_at||""))||0;return Number(u?.relevance||0)*1e12+m},c=(u,m)=>a(m)-a(u),d=o.filter(u=>u.tier==="long").sort(c).slice(0,10),l=o.filter(u=>u.tier==="mid").sort(c).slice(0,8),p=Nr([...d,...l]);return JSON.stringify({recentSessions:[],topMemories:p,taskStats:[],ticketFilter:r||null,backend:"mem0"})}function $r(s,t){let{summary:e,tickets:r,tasksRun:i=0,tasksPassed:n=0,tasksFailed:o=0,keyFacts:a}=s;if(!e)return JSON.stringify({error:"summary is required"});let c=process.env.ZIBBY_CHAT_SESSION_ID||`session_${Je()}`;if(J(t,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
645
+ VALUES (${w(c)}, ${w(e)}, ${w(r)}, ${i}, ${n}, ${o}, ${w(a)}, ${w(ne())})`),a)for(let d of a.split(";").map(l=>l.trim()).filter(Boolean))jr({content:d,category:"fact",source:"session_summary",tier:"mid"},t);lo(t);try{q(t,["add","."]),q(t,["commit","-m",`session end: ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:c,summary:e.slice(0,200)})}function Er(s,t){let{title:e,type:r,status:i,ticketKey:n,specPath:o,resultSummary:a}=s;if(!e||!r||!i)return JSON.stringify({error:"title, type, and status are required"});let c=Je(),d=process.env.ZIBBY_CHAT_SESSION_ID||null;J(t,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
646
+ VALUES (${w(c)}, ${w(n)}, ${w(r)}, ${w(e)}, ${w(i)}, ${w(o)}, ${w(d)}, ${w(a)}, ${w(ne())}, ${w(ne())})`);try{q(t,["add","."]),q(t,["commit","-m",`task: ${i} \u2014 ${e.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:c,title:e,type:r,status:i})}function Lr(s,t){let{ticketKey:e,type:r,status:i,limit:n=20}=s,o=[];e&&o.push(`ticket_key = ${w(e)}`),r&&o.push(`type = ${w(r)}`),i&&o.push(`status = ${w(i)}`);let c=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
644
647
  FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
645
- ORDER BY created_at DESC LIMIT ${n}`,d=ee(t,c);return JSON.stringify({total:d.length,tasks:d})}function lo(s){try{q(s,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),q(s,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),q(s,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),q(s,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function po(s){try{let t=new Date(Date.now()-864e5).toISOString();q(s,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${w(t)}`)}catch{}}import{existsSync as Lr,readFileSync as uo}from"node:fs";import{homedir as mo}from"node:os";import{join as fo,dirname as ho,resolve as yo}from"node:path";import{fileURLToPath as go}from"node:url";function _o(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=ho(go(import.meta.url)),t=yo(s,"..","bin","mcp-skill.mjs");return Lr(t)?t:null}function bo(){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 s=fo(mo(),".zibby","config.json");return Lr(s)&&JSON.parse(uo(s,"utf-8")).sessionToken||null}catch{return null}}function ko(){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 wo(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function at(s){return`${wo()}:${s}`}async function ct(s,t){let e=bo();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let r=`${ko()}/credits/review-memory`,i=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:s,...t})});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`KV memory ${s} failed (${i.status}): ${n.slice(0,300)}`)}return i.json()}var Cr={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
648
+ ORDER BY created_at DESC LIMIT ${n}`,d=ee(t,c);return JSON.stringify({total:d.length,tasks:d})}function lo(s){try{J(s,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),J(s,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),J(s,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),J(s,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function po(s){try{let t=new Date(Date.now()-864e5).toISOString();J(s,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${w(t)}`)}catch{}}import{existsSync as xr,readFileSync as uo}from"node:fs";import{homedir as mo}from"node:os";import{join as fo,dirname as ho,resolve as yo}from"node:path";import{fileURLToPath as go}from"node:url";function _o(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let s=ho(go(import.meta.url)),t=yo(s,"..","bin","mcp-skill.mjs");return xr(t)?t:null}function bo(){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 s=fo(mo(),".zibby","config.json");return xr(s)&&JSON.parse(uo(s,"utf-8")).sessionToken||null}catch{return null}}function ko(){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 wo(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function at(s){return`${wo()}:${s}`}async function ct(s,t){let e=bo();if(!e)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let r=`${ko()}/credits/review-memory`,i=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({op:s,...t})});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`KV memory ${s} failed (${i.status}): ${n.slice(0,300)}`)}return i.json()}var Cr={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
646
649
  You have a PRIVATE per-agent key-value memory that survives across your
647
650
  stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
648
651
  agents cannot see or collide with your entries, and you don't need to prefix
@@ -670,7 +673,7 @@ relationships, or "where does X live / what depends on Y":
670
673
  - index_status / list_projects: confirm the index is present before querying.
671
674
  The repo is indexed for you at the start of the run; if a query comes back
672
675
  empty, call index_status, and only re-index (index_repository) if needed.`,resolve(){let s=Jr();try{Pr(s,{recursive:!0})}catch{}let t={CBM_CACHE_DIR:s};return process.env.WORKSPACE&&(t.WORKSPACE=process.env.WORKSPACE),{type:"stdio",command:qr(),args:[],env:t,description:this.description,alwaysLoad:!0}},invokeAgentOptions(){try{let s=Ro();if(!s)return{};let t=Jr();try{Pr(t,{recursive:!0})}catch{}let e=Me(t,`.cbm-indexed-${Oo(s)}`);if(Ue(e))return{};let r=qr();if(!Ue(r)&&!process.env.CBM_BIN)return{};let i=So(r,["cli","index_repository",JSON.stringify({repo_path:s})],{env:{...process.env,CBM_CACHE_DIR:t},encoding:"utf-8",timeout:300*1e3,maxBuffer:32*1024*1024});try{No(e,`${new Date().toISOString()} status=${i.status}
673
- `)}catch{}}catch{}return{}}};import{existsSync as W,readFileSync as ke,readdirSync as lt,mkdirSync as Ao,writeFileSync as pe,statSync as Br}from"fs";import{join as O,resolve as dt,relative as Kr,dirname as Gr}from"path";import{fileURLToPath as jo}from"url";import{createRequire as $o}from"module";var To=$o(import.meta.url),Eo=`## Workflow Builder
676
+ `)}catch{}}catch{}return{}}};import{existsSync as W,readFileSync as ke,readdirSync as lt,mkdirSync as Ao,writeFileSync as pe,statSync as Br}from"fs";import{join as O,resolve as dt,relative as Kr,dirname as Gr}from"path";import{fileURLToPath as jo}from"url";import{createRequire as To}from"module";var $o=To(import.meta.url),Eo=`## Workflow Builder
674
677
 
675
678
  You can help users build custom AI workflows using the Zibby workflow framework.
676
679
 
@@ -780,7 +783,7 @@ Call with no arguments to see all available topics.
780
783
  - Workflow names must be kebab-case (e.g., ticket-triage, pr-review).
781
784
  - State flows through: each node's validated output is stored under its name in state (e.g., state.classify_ticket).
782
785
  - Downstream nodes reference upstream outputs in their prompt function (e.g., \\\`\\\${JSON.stringify(state.classify_ticket, null, 2)}\\\`).
783
- - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Fr=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Hr(s){return`${s.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}Workflow`}function be(s){return`${s.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}Node`}function xo(s){let t=s?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function Lo(s){let t=dt(s,".zibby.config.mjs");if(!W(t))return{};try{return(await import(t)).default||{}}catch{return{}}}function Co(){try{let s=Gr(To.resolve("@zibby/core/package.json")),t=O(s,"templates","browser-test-automation"),e=ke(O(t,"nodes","preflight.mjs"),"utf-8"),r=ke(O(t,"graph.mjs"),"utf-8");return{preflight:e,graph:r}}catch{return null}}var Mr=Gr(jo(import.meta.url));function zr(){let s=dt(Mr,"..","..","..","docsite","docs");if(W(s))return s;let t=dt(Mr,"..","docs");return W(t)?t:null}function Dr(){let s=zr();if(!s)return[];try{let t=(e,r="")=>{let i=[];for(let n of lt(e)){let o=O(e,n);try{if(Br(o).isDirectory())i=i.concat(t(o,`${r}${n}/`));else if(n.endsWith(".md")){let a=`${r}${n.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return t(s)}catch{return[]}}function Wr(s){let t=zr();if(!t)return null;let e=O(t,`${s}.md`);if(!W(e))return null;try{return ke(e,"utf-8")}catch{return null}}function Po(s){let t=s.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
786
+ - Nodes can declare skills to get MCP tool access \u2014 the framework handles server lifecycle automatically.`,Fr=/^[a-z][a-z0-9-]{0,62}[a-z0-9]$/;function Hr(s){return`${s.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}Workflow`}function be(s){return`${s.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}Node`}function Lo(s){let t=s?.agent;return t?t.provider?t.provider:t.gemini?"gemini":t.codex?"codex":t.claude?"claude":t.cursor?"cursor":process.env.AGENT_TYPE||"cursor":process.env.AGENT_TYPE||"cursor"}async function xo(s){let t=dt(s,".zibby.config.mjs");if(!W(t))return{};try{return(await import(t)).default||{}}catch{return{}}}function Co(){try{let s=Gr($o.resolve("@zibby/core/package.json")),t=O(s,"templates","browser-test-automation"),e=ke(O(t,"nodes","preflight.mjs"),"utf-8"),r=ke(O(t,"graph.mjs"),"utf-8");return{preflight:e,graph:r}}catch{return null}}var Mr=Gr(jo(import.meta.url));function zr(){let s=dt(Mr,"..","..","..","docsite","docs");if(W(s))return s;let t=dt(Mr,"..","docs");return W(t)?t:null}function Dr(){let s=zr();if(!s)return[];try{let t=(e,r="")=>{let i=[];for(let n of lt(e)){let o=O(e,n);try{if(Br(o).isDirectory())i=i.concat(t(o,`${r}${n}/`));else if(n.endsWith(".md")){let a=`${r}${n.replace(/\.md$/,"")}`;i.push(a)}}catch{}}return i};return t(s)}catch{return[]}}function Wr(s){let t=zr();if(!t)return null;let e=O(t,`${s}.md`);if(!W(e))return null;try{return ke(e,"utf-8")}catch{return null}}function Po(s){let t=s.nodes.map(o=>{let a=o.inputFields?.length?`Input fields: ${o.inputFields.join(", ")}`:"Input: receives full state",c=o.outputFields?.length?`Output fields: ${o.outputFields.join(", ")}`:"Output: determined by task",d=o.skills?.length?`Skills: ${o.skills.join(", ")}`:"";return`- ${o.name}: ${o.description}. ${a}. ${c}.${d?` ${d}`:""}`}).join(`
784
787
  `),e=s.edges.map(o=>o.condition?`- ${o.from} \u2192 ${o.to} (conditional: ${o.condition})`:`- ${o.from} \u2192 ${o.to}`).join(`
785
788
  `),r=Co(),i=Wr("custom-workflows"),n="";return r&&(n+=`
786
789
  ## Real working examples from the Zibby framework
@@ -859,7 +862,7 @@ Return a JSON object with this exact structure:
859
862
  }
860
863
  }
861
864
 
862
- IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Yr(s,t){let e=await Lo(t),r=xo(e);try{let{invokeAgent:i}=await import("@zibby/core"),n=Po(s),o=await i(n,{state:{agentType:r,config:e,cwd:t,workspace:t}},{model:e?.agent?.[r]?.model||"auto",workspace:t,config:e,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),qo(s)}}function qo(s){let t={};for(let e of s.nodes){let r=be(e.name),i=`${e.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,n=e.outputFields?.length?e.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
865
+ IMPORTANT: Return ONLY valid JSON. No markdown fences, no explanation outside the JSON.`}async function Yr(s,t){let e=await xo(t),r=Lo(e);try{let{invokeAgent:i}=await import("@zibby/core"),n=Po(s),o=await i(n,{state:{agentType:r,config:e,cwd:t,workspace:t}},{model:e?.agent?.[r]?.model||"auto",workspace:t,config:e,timeout:12e4}),c=(typeof o=="string"?o:o?.raw||JSON.stringify(o?.structured||o)).match(/\{[\s\S]*\}/);if(!c)throw new Error("Agent did not return valid JSON");return JSON.parse(c[0])}catch(i){return console.warn(`Agent code generation failed (${i.message}), using templates`),qo(s)}}function qo(s){let t={};for(let e of s.nodes){let r=be(e.name),i=`${e.name.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}OutputSchema`,n=e.outputFields?.length?e.outputFields.map(c=>` ${c}: z.string().describe('${c}'),`).join(`
863
866
  `):` summary: z.string().describe('Summary of the result'),
864
867
  status: z.enum(['ok', 'warn', 'error']).describe('Overall status'),`,o=s.edges.filter(c=>c.to===e.name&&c.from!=="START").map(c=>`Previous step (${c.from}): \${JSON.stringify(state.${c.from} || {}, null, 2)}`).join(`
865
868
  `),a=o?`${e.description}
@@ -918,4 +921,4 @@ _${a.sub}_`:""}${a.severity?` ${te[a.severity]}`:""}`}));for(let a=0;a<o.length;
918
921
  `+t.headline.summary),e.push({tag:"div",text:{tag:"lark_md",content:i}});for(let o of t.sections)switch(e.push({tag:"hr"}),o.title&&e.push({tag:"div",text:{tag:"lark_md",content:`**${o.title}**`}}),o.kind){case"trend":{let a=Math.max(...o.values),c=o.labels.map((d,l)=>{let p=o.values[l],u=ss(p,a),f=(o.highlight==="last"&&l===o.labels.length-1||o.highlight==="max"&&p===a||o.highlight==="min"&&p===Math.min(...o.values))&&o.severity?` ${te[o.severity]}`:"";return`${yt(d,10)} ${is(p.toLocaleString(),8)} ${u}${f}`});e.push({tag:"div",text:{tag:"lark_md",content:"```\n"+c.join(`
919
922
  `)+"\n```"}});break}case"table":{e.push({tag:"div",text:{tag:"lark_md",content:ns(o)}});break}case"callouts":{let a=te[o.tone||"info"];e.push({tag:"div",text:{tag:"lark_md",content:o.items.map(c=>`${a} ${c}`).join(`
920
923
  `)}});break}case"breakdown":{let a=o.rows.map(c=>{let d=c.severity?` ${te[c.severity]}`:"",l=c.sub?` *${c.sub}*`:"";return`**${c.label}** ${c.value}${l}${d}`});e.push({tag:"div",text:{tag:"lark_md",content:a.join(`
921
- `)}});break}case"paragraph":{e.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let o=[];t.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:t.footer.viewUrl,type:"primary"}),t.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:t.footer.rerunUrl,type:"default"}),e.push({tag:"hr"}),e.push({tag:"action",actions:o})}let n="blue";return t.headline.delta?.severity&&(n=sa[t.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:t.title.slice(0,200)},subtitle:t.subtitle?{tag:"plain_text",content:t.subtitle.slice(0,200)}:void 0,template:n},elements:e}}var jl=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),$l=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});import{createRequire as oa}from"module";import{fileURLToPath as aa}from"url";import{registerHandlers as ca}from"@zibby/core/function-skill-registry.js";import{registerSkill as la}from"@zibby/agent-workflow";var da=oa(import.meta.url);function pa(){try{return da.resolve("@zibby/core/function-bridge.js")}catch{return null}}var ua=import.meta.url;function ma(){let s=Error.prepareStackTrace;try{Error.prepareStackTrace=(r,i)=>i;let e=new Error().stack;for(let r=2;r<e.length;r++){let i=e[r].getFileName();if(i&&i!==ua&&!i.startsWith("node:"))return i.startsWith("file://")?aa(i):i}return null}finally{Error.prepareStackTrace=s}}function fa(s){if(!s||typeof s!="object")return{type:"object",properties:{},required:[]};let t={},e=[];for(let[r,i]of Object.entries(s))if(typeof i=="string")t[r]={type:i},e.push(r);else{let{required:n,...o}=i;t[r]=o,n!==!1&&e.push(r)}return{type:"object",properties:t,required:e}}function ha(s,t,e){if(typeof e.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r={[s]:e.handler},i=[{name:s,description:e.description||"",input_schema:fa(e.input)}];return ca(s,r,i),{id:s,type:"function",serverName:s,allowedTools:[`mcp__${s}__*`],description:e.description||`Function skill: ${s}`,envKeys:[],tools:i,resolve(){let n=pa();return n?{command:"node",args:[n,t,s]}:null}}}function ya(s,t){return{id:s,type:"mcp",serverName:t.serverName||s,allowedTools:t.allowedTools||[`mcp__${t.serverName||s}__*`],description:t.description||`MCP skill: ${s}`,envKeys:t.envKeys||[],tools:t.tools||[],resolve:t.resolve,...t.cursorKey&&{cursorKey:t.cursorKey},...t.sessionEnvKey&&{sessionEnvKey:t.sessionEnvKey}}}function os(s,t){let e;if("handler"in t){if(typeof t.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r=ma();if(!r)throw new Error(`Could not resolve caller file for skill "${s}".`);e=ha(s,r,t)}else if(typeof t.resolve=="function")e=ya(s,t);else throw new Error(`Skill "${s}" must have either a handler (function skill) or resolve (MCP skill).`);return la(e),e}var ga=os;import{registerSkill as fd,getSkill as hd,hasSkill as yd,getAllSkills as gd,listSkillIds as _d}from"@zibby/agent-workflow";I(gt);I(kt);I(ae);I(ce);I(vt);I(It);I(Rt);I(jt);I(D);I(K);I(Ct);I(Pt);I(Oe);I(Jt);I(cr);I(X);I(fr);I(Mt);I(Ft);I(Ar);I(Cr);I(Ur);I(Zr);I(ut);I(mt);I(ft);I({...D,id:"slack_notify"});var cd={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",LINEAR:"linear",PLANE:"plane",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",NOTION:"notion",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",CODEBASE_MEMORY:"codebase-memory",WORKFLOW_BUILDER:"workflow-builder",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin"};export{N as INTEGRATIONS,hs as INTEGRATION_REGISTRY,Se as REPORT_SEVERITIES,cd as SKILLS,mt as anthropicBillingSkill,gt as browserSkill,Ar as chatMemorySkill,Pt as chatNotifySkill,Ur as codebaseMemorySkill,Ft as coreToolsSkill,ft as cursorAdminSkill,zo as fetchAllProviders,es as fetchAnthropicCosts,Ho as fetchAnthropicWorkspaces,ts as fetchCursorSpend,Xr as fetchOpenAICosts,Fo as fetchOpenAIProjects,vt as figmaSkill,ga as functionSkill,gd as getAllSkills,hd as getSkill,X as gitSkill,fr as gitWriteSkill,ae as githubSkill,ce as gitlabSkill,Wo as groupByKey,yd as hasSkill,kt as jiraSkill,Cr as kvMemorySkill,K as larkSkill,It as linearSkill,_d as listSkillIds,Yo as meanStddev,Jt as memorySkill,Ct as notionSkill,ut as openaiBillingSkill,jt as opendesignSkill,Rt as planeSkill,fd as registerSkill,ht as reportObjectSchema,ia as reportToBlockKit,na as reportToLarkCard,cr as runnerSkill,Oe as sentrySkill,os as skill,Mt as skillInstallerSkill,D as slackSkill,cr as testRunnerSkill,Zr as workflowBuilderSkill};
924
+ `)}});break}case"paragraph":{e.push({tag:"div",text:{tag:"lark_md",content:o.text}});break}}if(t.footer&&(t.footer.viewUrl||t.footer.rerunUrl)){let o=[];t.footer.viewUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"View in Zibby"},url:t.footer.viewUrl,type:"primary"}),t.footer.rerunUrl&&o.push({tag:"button",text:{tag:"plain_text",content:"Run again"},url:t.footer.rerunUrl,type:"default"}),e.push({tag:"hr"}),e.push({tag:"action",actions:o})}let n="blue";return t.headline.delta?.severity&&(n=sa[t.headline.delta.severity]||"blue"),{config:{wide_screen_mode:!0},header:{title:{tag:"plain_text",content:t.title.slice(0,200)},subtitle:t.subtitle?{tag:"plain_text",content:t.subtitle.slice(0,200)}:void 0,template:n},elements:e}}var jl=Object.freeze({ok:"green_background",info:"blue_background",warn:"orange_background",critical:"red_background"}),Tl=Object.freeze({ok:"\u{1F7E2}",info:"\u2139\uFE0F",warn:"\u26A0\uFE0F",critical:"\u{1F6A8}"});import{createRequire as oa}from"module";import{fileURLToPath as aa}from"url";import{registerHandlers as ca}from"@zibby/core/function-skill-registry.js";import{registerSkill as la}from"@zibby/agent-workflow";var da=oa(import.meta.url);function pa(){try{return da.resolve("@zibby/core/function-bridge.js")}catch{return null}}var ua=import.meta.url;function ma(){let s=Error.prepareStackTrace;try{Error.prepareStackTrace=(r,i)=>i;let e=new Error().stack;for(let r=2;r<e.length;r++){let i=e[r].getFileName();if(i&&i!==ua&&!i.startsWith("node:"))return i.startsWith("file://")?aa(i):i}return null}finally{Error.prepareStackTrace=s}}function fa(s){if(!s||typeof s!="object")return{type:"object",properties:{},required:[]};let t={},e=[];for(let[r,i]of Object.entries(s))if(typeof i=="string")t[r]={type:i},e.push(r);else{let{required:n,...o}=i;t[r]=o,n!==!1&&e.push(r)}return{type:"object",properties:t,required:e}}function ha(s,t,e){if(typeof e.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r={[s]:e.handler},i=[{name:s,description:e.description||"",input_schema:fa(e.input)}];return ca(s,r,i),{id:s,type:"function",serverName:s,allowedTools:[`mcp__${s}__*`],description:e.description||`Function skill: ${s}`,envKeys:[],tools:i,resolve(){let n=pa();return n?{command:"node",args:[n,t,s]}:null}}}function ya(s,t){return{id:s,type:"mcp",serverName:t.serverName||s,allowedTools:t.allowedTools||[`mcp__${t.serverName||s}__*`],description:t.description||`MCP skill: ${s}`,envKeys:t.envKeys||[],tools:t.tools||[],resolve:t.resolve,...t.cursorKey&&{cursorKey:t.cursorKey},...t.sessionEnvKey&&{sessionEnvKey:t.sessionEnvKey}}}function os(s,t){let e;if("handler"in t){if(typeof t.handler!="function")throw new Error(`Skill "${s}" must have a handler function`);let r=ma();if(!r)throw new Error(`Could not resolve caller file for skill "${s}".`);e=ha(s,r,t)}else if(typeof t.resolve=="function")e=ya(s,t);else throw new Error(`Skill "${s}" must have either a handler (function skill) or resolve (MCP skill).`);return la(e),e}var ga=os;import{registerSkill as fd,getSkill as hd,hasSkill as yd,getAllSkills as gd,listSkillIds as _d}from"@zibby/agent-workflow";I(gt);I(kt);I(ae);I(ce);I(vt);I(It);I(Rt);I(jt);I(x);I(K);I(Ct);I(Pt);I(Oe);I(Jt);I(cr);I(X);I(fr);I(Mt);I(Ft);I(Ar);I(Cr);I(Ur);I(Zr);I(ut);I(mt);I(ft);I({...x,id:"slack_notify"});var cd={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",LINEAR:"linear",PLANE:"plane",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",NOTION:"notion",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",CODEBASE_MEMORY:"codebase-memory",WORKFLOW_BUILDER:"workflow-builder",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin"};export{N as INTEGRATIONS,hs as INTEGRATION_REGISTRY,Se as REPORT_SEVERITIES,cd as SKILLS,mt as anthropicBillingSkill,gt as browserSkill,Ar as chatMemorySkill,Pt as chatNotifySkill,Ur as codebaseMemorySkill,Ft as coreToolsSkill,ft as cursorAdminSkill,zo as fetchAllProviders,es as fetchAnthropicCosts,Ho as fetchAnthropicWorkspaces,ts as fetchCursorSpend,Xr as fetchOpenAICosts,Fo as fetchOpenAIProjects,vt as figmaSkill,ga as functionSkill,gd as getAllSkills,hd as getSkill,X as gitSkill,fr as gitWriteSkill,ae as githubSkill,ce as gitlabSkill,Wo as groupByKey,yd as hasSkill,kt as jiraSkill,Cr as kvMemorySkill,K as larkSkill,It as linearSkill,_d as listSkillIds,Yo as meanStddev,Jt as memorySkill,Ct as notionSkill,ut as openaiBillingSkill,jt as opendesignSkill,Rt as planeSkill,fd as registerSkill,ht as reportObjectSchema,ia as reportToBlockKit,na as reportToLarkCard,cr as runnerSkill,Oe as sentrySkill,os as skill,Mt as skillInstallerSkill,x as slackSkill,cr as testRunnerSkill,Zr as workflowBuilderSkill};