@zibby/skills 2.0.8 → 2.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/artifact.js +1 -1
- package/dist/chartRender.js +1 -1
- package/dist/chat-notify.js +3 -3
- package/dist/chatProgress.js +3 -3
- package/dist/code-scan.js +1 -1
- package/dist/codeStats.js +2 -2
- package/dist/codebaseMemory.js +1 -1
- package/dist/discord.js +1 -1
- package/dist/figma.js +1 -1
- package/dist/gbrain.js +2 -2
- package/dist/git-write.js +9 -9
- package/dist/github.js +5 -5
- package/dist/gitlab.js +1 -1
- package/dist/googleDocs.js +1 -1
- package/dist/hubspot.js +1 -1
- package/dist/index.js +130 -130
- package/dist/jira.js +7 -7
- package/dist/kvMemory.js +1 -1
- package/dist/lark.js +1 -1
- package/dist/larkAttendance.js +1 -1
- package/dist/larkDocs.js +1 -1
- package/dist/linear.js +1 -1
- package/dist/linkedin.js +2 -2
- package/dist/notion.js +3 -3
- package/dist/opendesign.js +2 -2
- package/dist/package.json +4 -4
- package/dist/reportCheck.js +1 -1
- package/dist/sentry.js +2 -2
- package/dist/slack.js +1 -1
- package/dist/socialCard.js +1 -1
- package/dist/trackers/github-adapter.js +5 -5
- package/dist/trackers/index.js +33 -33
- package/dist/trackers/jira-adapter.js +7 -7
- package/dist/trackers/linear-adapter.js +3 -3
- package/dist/vikunja.js +1 -1
- package/package.json +4 -4
package/dist/trackers/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync as Nt}from"fs";import{dirname as Tt,resolve as Ot}from"path";import{fileURLToPath as Et}from"url";import{resolveIntegrationToken as jt,clearTokenCache as xt}from"@zibby/core/backend-client.js";var U=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",LARK_DOCS:"lark_docs",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",VIKUNJA:"vikunja",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Ar=Object.freeze({sentry:{id:"sentry",name:"Sentry",connectPath:"/integrations?provider=sentry"},jira:{id:"jira",name:"Jira",connectPath:"/integrations?provider=jira"},github:{id:"github",name:"GitHub",connectPath:"/integrations?provider=github"},gitlab:{id:"gitlab",name:"GitLab",connectPath:"/integrations?provider=gitlab"},slack:{id:"slack",name:"Slack",connectPath:"/integrations?provider=slack"},lark:{id:"lark",name:"Lark Chat",connectPath:"/integrations?provider=lark"},lark_docs:{id:"lark_docs",name:"Lark App",connectPath:"/integrations?provider=lark_docs"},openai_billing:{id:"openai_billing",name:"OpenAI Admin",connectPath:"/integrations?provider=openai_billing"},anthropic_billing:{id:"anthropic_billing",name:"Anthropic Admin",connectPath:"/integrations?provider=anthropic_billing"},cursor_admin:{id:"cursor_admin",name:"Cursor Admin",connectPath:"/integrations?provider=cursor_admin"},notion:{id:"notion",name:"Notion",connectPath:"/integrations?provider=notion"},google:{id:"google",name:"Google Docs",connectPath:"/integrations?provider=google"},plane:{id:"plane",name:"Plane",connectPath:"/integrations?provider=plane"},linear:{id:"linear",name:"Linear",connectPath:"/integrations?provider=linear"},vikunja:{id:"vikunja",name:"Vikunja",connectPath:"/integrations?provider=vikunja"},figma:{id:"figma",name:"Figma",connectPath:"/integrations?provider=figma"},hubspot:{id:"hubspot",name:"HubSpot",connectPath:"/integrations?provider=hubspot"},open_design:{id:"open_design",name:"OpenDesign",connectPath:"/integrations?provider=open_design"},linkedin_personal:{id:"linkedin_personal",name:"LinkedIn (Personal)",connectPath:"/integrations?provider=linkedin_personal"},linkedin_business:{id:"linkedin_business",name:"LinkedIn (Business)",connectPath:"/integrations?provider=linkedin_business"},discord:{id:"discord",name:"Discord",connectPath:"/integrations?provider=discord"}});var V={api:{knob:"SKILL_API_TIMEOUT_MS",fallback:3e4},transfer:{knob:"SKILL_TRANSFER_TIMEOUT_MS",fallback:12e4},job:{knob:"SKILL_JOB_TIMEOUT_MS",fallback:3e5}};function at(n,r,e=process.env){let t=Number(e?.[n]);return Number.isFinite(t)&&t>0?Math.min(6e5,Math.max(1e3,Math.floor(t))):r}function ct(n="api",r=process.env){let e=V[n]||V.api;return at(e.knob,e.fallback,r)}function ne(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function lt(n){try{return new URL(String(n?.url??n)).host||"unknown host"}catch{return"unknown host"}}function ut(n,r){if(!n)return r;let e=new AbortController,t=o=>{e.signal.aborted||e.abort(o)},i=()=>t(n.reason),s=()=>t(r.reason);return e.signal.addEventListener("abort",()=>{n.removeEventListener("abort",i),r.removeEventListener("abort",s)},{once:!0}),n.aborted?t(n.reason):r.aborted?t(r.reason):(n.addEventListener("abort",i,{once:!0}),r.addEventListener("abort",s,{once:!0})),e.signal}async function T(n,r={},e={}){let t=e.kind||"api",i=(V[t]||V.api).knob,s=e.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(e.timeoutMs))):ct(t),o=r?.signal;if(o?.aborted)throw o.reason??new DOMException("This operation was aborted","AbortError");let a=AbortSignal.timeout(s),c=ut(o,a);try{return await fetch(n,{...r,signal:c})}catch(u){throw a.aborted&&ne(u)?new Error(`${e.what||"request"} TIMED OUT after ${s}ms against ${lt(n)} (${i})`):u}}var pt={NOTE:"info",TIP:"success",IMPORTANT:"note",WARNING:"warning",CAUTION:"error"},Le={info:"NOTE",success:"TIP",note:"IMPORTANT",warning:"WARNING",error:"CAUTION"},dt=2e5,Pe=6,mt=/^```([A-Za-z0-9_+.-]{0,32})\s*$/,ft=/^(#{1,6})[ \t]+(.*?)\s*$/,yt=/^(?:-{3,}|\*{3,}|_{3,})\s*$/,Ne=/^>(?: ?(.*))?$/,se=/^[-*][ \t]+\[([ xX])\][ \t]+(.*)$/,Te=/^[-*][ \t]+(.*)$/,Oe=/^(\d{1,3})[.)][ \t]+(.*)$/,Ee=/^\|.*\|\s*$/,gt=/^\|?\s*:?-{1,}:?\s*(?:\|\s*:?-{1,}:?\s*)*\|?\s*$/,ht=/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i;function je(n){let r=n.trim().replace(/^\|/,"").replace(/\|$/,""),e=[],t="";for(let i=0;i<r.length;i++){let s=r[i];if(s==="\\"&&r[i+1]==="|"){t+="|",i++;continue}if(s==="|"){e.push(t.trim()),t="";continue}t+=s}return e.push(t.trim()),e}function qe(n){let e=String(n??"").slice(0,dt).replace(/\r\n?/g,`
|
|
2
2
|
`).split(`
|
|
3
|
-
`);return
|
|
4
|
-
`)});continue}if(
|
|
5
|
-
`).map(r=>({type:"paragraph",...r?{content:[{type:"text",text:r}]}:{}}))}}function
|
|
6
|
-
`;break;case"code":r+=`\`${e.v}\``;break;case"strong":r+=`**${
|
|
7
|
-
`;break;case"heading":r+=`${"#".repeat(Math.max(1,Math.min(
|
|
8
|
-
`;break;case"bullet":for(let t of e.items)r+=`- ${
|
|
9
|
-
`;break;case"ordered":e.items.forEach((t,i)=>{r+=`${e.start+i}. ${
|
|
10
|
-
`});break;case"task":for(let t of e.items)r+=`- [${t.checked?"x":" "}] ${
|
|
3
|
+
`);return oe(e,0)}function oe(n,r){let e=[],t=0;for(;t<n.length;){let i=n[t];if(i.trim()===""){t++;continue}if(/^[ \t]/.test(i)){e.push({t:"paragraph",c:A(i)}),t++;continue}let s;if(s=mt.exec(i)){let o=s[1]||"",a=[];for(t++;t<n.length&&!/^```\s*$/.test(n[t]);)a.push(n[t]),t++;t++,e.push({t:"code",lang:o,v:a.join(`
|
|
4
|
+
`)});continue}if(yt.test(i)){e.push({t:"rule"}),t++;continue}if(s=ft.exec(i)){let o=Math.min(Pe,s[1].length);e.push({t:"heading",level:o,c:A(s[2])}),t++;continue}if(Ne.test(i)&&r<3){let o=[];for(;t<n.length&&(s=Ne.exec(n[t]));)o.push(s[1]??""),t++;let a=o.findIndex(u=>u.trim()!==""),c=a>=0?ht.exec(o[a].trim()):null;if(c){let u=pt[c[1].toUpperCase()];e.push({t:"panel",kind:u,c:oe(o.slice(a+1),r+1)})}else e.push({t:"quote",c:oe(o,r+1)});continue}if(se.test(i)){let o=[];for(;t<n.length&&(s=se.exec(n[t]));)o.push({checked:s[1]!==" ",c:A(s[2])}),t++;e.push({t:"task",items:o});continue}if(Te.test(i)){let o=[];for(;t<n.length&&!se.test(n[t])&&(s=Te.exec(n[t]));)o.push([{t:"paragraph",c:A(s[1])}]),t++;e.push({t:"bullet",items:o});continue}if(s=Oe.exec(i)){let o=Math.max(1,parseInt(s[1],10)||1),a=[];for(;t<n.length&&(s=Oe.exec(n[t]));)a.push([{t:"paragraph",c:A(s[2])}]),t++;e.push({t:"ordered",start:o,items:a});continue}if(Ee.test(i)&&t+1<n.length&>.test(n[t+1])){let o=je(i).map(A);t+=2;let a=[];for(;t<n.length&&Ee.test(n[t]);)a.push(je(n[t]).map(A)),t++;e.push({t:"table",header:o,rows:a});continue}e.push({t:"paragraph",c:A(i)}),t++}return e}var bt=/^https?:\/\/[^\s<>()[\]]+/,_t=/^\[([^\]\n]{1,300})\]\((https?:\/\/[^\s)]{1,2000})\)/,wt=/[.,;:!?'"]+$/;function kt(n,r){return r<=0?!0:/[\s([{"'“‘>:—–-]/.test(n[r-1])}function St(n,r){return r>=n.length?!0:/[\s)\]}"'”’.,;:!?—–-]/.test(n[r])}function At(n,r,e){let t=r;for(;t<n.length;){let i=n.indexOf(e,t);if(i<0)return-1;let s=n[i-1],o=n[i+e.length],a=e.length===1&&(s===e||o===e);if(i>r&&s&&!/\s/.test(s)&&!a&&St(n,i+e.length))return i;t=i+1}return-1}function A(n){let r=String(n??""),e=[],t="",i=()=>{t&&(e.push({t:"text",v:t}),t="")},s=0;for(;s<r.length;){let o=r[s];if(o==="`"){let a=1;for(;r[s+a]==="`";)a++;let c="`".repeat(a),u=r.indexOf(c,s+a);if(u>s+a-1&&u!==-1){let l=r.slice(s+a,u);if(l.trim()){i(),e.push({t:"code",v:l.length>1&&l.startsWith(" ")&&l.endsWith(" ")?l.slice(1,-1):l}),s=u+a;continue}}t+=c,s+=a;continue}if(o==="["){let a=_t.exec(r.slice(s));if(a){i(),e.push({t:"link",href:a[2],c:A(a[1])}),s+=a[0].length;continue}}if((o==="*"||o==="_"||o==="~")&&kt(r,s)){let a=r[s+1]===o;if(o==="~"&&!a){t+=o,s++;continue}let c=a?o+o:o,u=s+c.length;if(u<r.length&&!/\s/.test(r[u])){let l=At(r,u,c);if(l>u){i();let p=A(r.slice(u,l));e.push(o==="~"?{t:"strike",c:p}:a?{t:"strong",c:p}:{t:"em",c:p}),s=l+c.length;continue}}}if(o==="h"&&(s===0||/[\s(<]/.test(r[s-1]))){let a=bt.exec(r.slice(s));if(a){let c=a[0],u=wt.exec(c);if(u&&(c=c.slice(0,-u[0].length)),c.length>8){i(),e.push({t:"link",href:c,c:[{t:"text",v:c}]}),s+=c.length;continue}}}t+=o,s++}return i(),e}function L(n,r=[]){let e=[];for(let t of n)switch(t.t){case"text":t.v&&e.push({type:"text",text:t.v,...r.length?{marks:r}:{}});break;case"br":e.push({type:"hardBreak"});break;case"code":e.push({type:"text",text:t.v,marks:[{type:"code"},...r.filter(i=>i.type==="link")]});break;case"strong":e.push(...L(t.c,Z(r,{type:"strong"})));break;case"em":e.push(...L(t.c,Z(r,{type:"em"})));break;case"strike":e.push(...L(t.c,Z(r,{type:"strike"})));break;case"link":e.push(...L(t.c,Z(r,{type:"link",attrs:{href:t.href}})));break}return e}function Z(n,r){return n.some(e=>e.type===r.type)?n:[...n,r]}var ie=0;function xe(){return ie=(ie+1)%1e6,`m${Date.now().toString(36)}-${ie}`}var M=n=>{let r=L(n);return r.length?{type:"paragraph",content:r}:{type:"paragraph"}};function C(n,r){let e=[];for(let t of n)switch(t.t){case"paragraph":e.push(M(t.c));break;case"heading":if(r==="quote"||r==="item")e.push(M([{t:"strong",c:t.c}]));else{let i=L(t.c);i.length&&e.push({type:"heading",attrs:{level:t.level},content:i})}break;case"bullet":e.push({type:"bulletList",content:t.items.map(i=>({type:"listItem",content:X(C(i,"item"))}))});break;case"ordered":e.push({type:"orderedList",attrs:{order:t.start},content:t.items.map(i=>({type:"listItem",content:X(C(i,"item"))}))});break;case"task":r==="quote"||r==="item"?e.push({type:"bulletList",content:t.items.map(i=>({type:"listItem",content:[M([{t:"text",v:i.checked?"\u2611 ":"\u2610 "},...i.c])]}))}):e.push({type:"taskList",attrs:{localId:xe()},content:t.items.map(i=>({type:"taskItem",attrs:{localId:xe(),state:i.checked?"DONE":"TODO"},content:It(L(i.c))}))});break;case"code":e.push({type:"codeBlock",attrs:t.lang?{language:t.lang}:{},...t.v?{content:[{type:"text",text:t.v}]}:{}});break;case"quote":r==="quote"||r==="item"?e.push(...C(t.c,r)):e.push({type:"blockquote",content:X(C(t.c,"quote"))});break;case"panel":r!=="doc"?e.push(...C(t.c,r)):e.push({type:"panel",attrs:{panelType:t.kind},content:X(C(t.c,"panel"))});break;case"rule":if(r==="quote"||r==="item")break;e.push({type:"rule"});break;case"table":{if(r!=="doc"){for(let s of[...t.header?[t.header]:[],...t.rows])e.push(M(vt(s)));break}let i=[];t.header&&i.push({type:"tableRow",content:t.header.map(s=>({type:"tableHeader",attrs:{},content:[M(s)]}))});for(let s of t.rows)i.push({type:"tableRow",content:s.map(o=>({type:"tableCell",attrs:{},content:[M(o)]}))});i.length&&e.push({type:"table",attrs:{isNumberColumnEnabled:!1,layout:"default"},content:i});break}}return e}function X(n){return n.length?n:[{type:"paragraph"}]}function It(n){return n.length?n:[{type:"text",text:" "}]}function vt(n){let r=[];return n.forEach((e,t)=>{t&&r.push({t:"text",v:" \xB7 "}),r.push(...e)}),r}function ae(n){return{type:"doc",version:1,content:String(n??"").split(`
|
|
5
|
+
`).map(r=>({type:"paragraph",...r?{content:[{type:"text",text:r}]}:{}}))}}function Je(n){try{let r=C(qe(n),"doc");return{type:"doc",version:1,content:r.length?r:[{type:"paragraph"}]}}catch{return ae(n)}}function O(n){let r="";for(let e of n)switch(e.t){case"text":r+=e.v;break;case"br":r+=`
|
|
6
|
+
`;break;case"code":r+=`\`${e.v}\``;break;case"strong":r+=`**${O(e.c)}**`;break;case"em":r+=`_${O(e.c)}_`;break;case"strike":r+=`~~${O(e.c)}~~`;break;case"link":{let t=O(e.c);r+=!t||t===e.href?e.href:`[${t}](${e.href})`;break}}return r}function K(n){let r="";for(let e of n)switch(e.t){case"paragraph":r+=`${O(e.c)}
|
|
7
|
+
`;break;case"heading":r+=`${"#".repeat(Math.max(1,Math.min(Pe,e.level)))} ${O(e.c)}
|
|
8
|
+
`;break;case"bullet":for(let t of e.items)r+=`- ${K(t).trim()}
|
|
9
|
+
`;break;case"ordered":e.items.forEach((t,i)=>{r+=`${e.start+i}. ${K(t).trim()}
|
|
10
|
+
`});break;case"task":for(let t of e.items)r+=`- [${t.checked?"x":" "}] ${O(t.c)}
|
|
11
11
|
`;break;case"code":r+=`\`\`\`${e.lang}
|
|
12
12
|
${e.v}
|
|
13
13
|
\`\`\`
|
|
14
|
-
`;break;case"quote":r+=
|
|
15
|
-
${
|
|
16
|
-
`;break;case"table":{let t=i=>`| ${i.map(s=>
|
|
14
|
+
`;break;case"quote":r+=Ce(K(e.c));break;case"panel":r+=`> [!${Le[e.kind]}]
|
|
15
|
+
${Ce(K(e.c))}`;break;case"rule":r+=`---
|
|
16
|
+
`;break;case"table":{let t=i=>`| ${i.map(s=>O(s).replace(/\|/g,"\\|")).join(" | ")} |
|
|
17
17
|
`;e.header&&(r+=t(e.header)+`|${e.header.map(()=>" --- |").join("")}
|
|
18
|
-
`);for(let i of e.rows)r+=t(i);break}}return r}function
|
|
18
|
+
`);for(let i of e.rows)r+=t(i);break}}return r}function Rt(n){return n.replace(/^\n+/,"").replace(/\s+$/,"")}function Ce(n){return n.replace(/\n$/,"").split(`
|
|
19
19
|
`).map(r=>r?`> ${r}`:">").join(`
|
|
20
20
|
`)+`
|
|
21
|
-
`}function U(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"text":{let t={t:"text",v:String(e.text??"")},i=Array.isArray(e.marks)?e.marks:[];i.some(s=>s?.type==="code")&&(t={t:"code",v:String(e.text??"")});for(let s of i)!s||s.type==="code"||(s.type==="strong"?t={t:"strong",c:[t]}:s.type==="em"?t={t:"em",c:[t]}:s.type==="strike"?t={t:"strike",c:[t]}:s.type==="link"&&s.attrs?.href&&(t={t:"link",href:String(s.attrs.href),c:[t]}));r.push(t);break}case"hardBreak":r.push({t:"br"});break;case"mention":r.push({t:"text",v:String(e.attrs?.text||(e.attrs?.id?`@${e.attrs.id}`:"@someone"))});break;case"emoji":r.push({t:"text",v:String(e.attrs?.text||e.attrs?.shortName||"")});break;case"status":r.push({t:"text",v:String(e.attrs?.text||"")});break;case"date":r.push({t:"text",v:e.attrs?.timestamp?new Date(Number(e.attrs.timestamp)).toISOString().slice(0,10):""});break;case"inlineCard":{let t=String(e.attrs?.url||"");t&&r.push({t:"link",href:t,c:[{t:"text",v:t}]});break}default:Array.isArray(e.content)?r.push(...U(e.content)):typeof e.text=="string"&&r.push({t:"text",v:e.text})}return r}function R(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"paragraph":r.push({t:"paragraph",c:U(e.content)});break;case"heading":r.push({t:"heading",level:Number(e.attrs?.level)||1,c:U(e.content)});break;case"bulletList":r.push({t:"bullet",items:(e.content||[]).map(t=>R(t?.content))});break;case"orderedList":r.push({t:"ordered",start:Number(e.attrs?.order)||1,items:(e.content||[]).map(t=>R(t?.content))});break;case"taskList":r.push({t:"task",items:(e.content||[]).map(t=>({checked:t?.attrs?.state==="DONE",c:U(t?.content)}))});break;case"decisionList":r.push({t:"bullet",items:(e.content||[]).map(t=>[{t:"paragraph",c:U(t?.content)}])});break;case"codeBlock":r.push({t:"code",lang:String(e.attrs?.language||""),v:(e.content||[]).map(t=>String(t?.text??"")).join("")});break;case"blockquote":r.push({t:"quote",c:R(e.content)});break;case"panel":{let t=String(e.attrs?.panelType||"info");r.push({t:"panel",kind:t in je?t:"info",c:R(e.content)});break}case"rule":r.push({t:"rule"});break;case"table":{let t=(e.content||[]).filter(a=>a?.type==="tableRow"),i=a=>(a.content||[]).map(c=>{let u=R(c?.content);return A(M(u).trim().replace(/\n+/g," "))}),s=a=>(a.content||[]).length>0&&(a.content||[]).every(c=>c?.type==="tableHeader"),o=t.length&&s(t[0])?i(t[0]):null;r.push({t:"table",header:o,rows:t.slice(o?1:0).map(i)});break}case"mediaSingle":case"mediaGroup":case"media":case"mediaInline":r.push({t:"paragraph",c:[{t:"text",v:"[attachment]"}]});break;case"expand":case"nestedExpand":{let t=String(e.attrs?.title||"").trim();t&&r.push({t:"paragraph",c:[{t:"strong",c:[{t:"text",v:t}]}]}),r.push(...R(e.content));break}default:{let t=Array.isArray(e.content)?e.content:[];t.some(i=>i?.type==="text"||i?.type==="hardBreak")?r.push({t:"paragraph",c:U(t)}):t.length?r.push(...R(t)):typeof e.text=="string"&&e.text&&r.push({t:"paragraph",c:[{t:"text",v:e.text}]})}}return r}function It(n){try{if(Array.isArray(n))return R(n);if(n&&typeof n=="object"){let r=n;return r.type==="doc"||!r.type&&Array.isArray(r.content)?R(r.content):R([r])}if(typeof n=="string")return Ce(n)}catch{}return[]}function oe(n){try{return At(M(It(n)))}catch{return""}}var Nt=vt(import.meta.url);function Tt(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Nt.resolve("@zibby/mcp-jira/index.js")}catch{return null}}function Ot(n){return Le(n)}async function ae(n,r){try{return await n(Ot(r))}catch(e){let t=Number(e?.status);if(!(t>=400&&t<500))throw e;return console.warn(`[jira] rich body rejected (${t}) \u2014 retrying as plain text: ${String(e?.message||e).slice(0,200)}`),await n(ie(r))}}function G(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ce(n){return G(n).replace(/[a-z0-9]+/g,"")}function X(n,r){let e=G(n),t=G(r);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let i=l=>{let p=new Map;for(let m=0;m<l.length-1;m++){let g=l.slice(m,m+2);p.set(g,(p.get(g)||0)+1)}return p},s=i(e),o=i(t),a=0,c=0,u=0;for(let l of s.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of s.entries()){let m=o.get(l)||0;a+=Math.min(p,m)}return 2*a/Math.max(1,c+u)}function O(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Et(n,r=[]){let e=Array.isArray(r)?r:[];if(e.length===0)return{requested:n||null,resolved:null,strategy:"none"};let t=e.filter(a=>!a.subtask),i=t.length>0?t:e,s=O(n);if(s){let a=i.find(l=>O(l.name)===s);if(a)return{requested:n,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(m=>O(m)===s))continue;let p=i.find(m=>l.some(g=>O(g)===O(m.name)));if(p)return{requested:n,resolved:p,strategy:"alias"}}let u=i.map(l=>({t:l,score:X(n,l.name)})).sort((l,p)=>p.score-l.score);if(u[0]&&u[0].score>=.5)return{requested:n,resolved:u[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(u=>O(u.name)===a);if(c)return{requested:n||null,resolved:c,strategy:"default-preferred"}}return{requested:n||null,resolved:i[0],strategy:"default-first"}}async function Pe(n){let r=`projectKeys=${encodeURIComponent(n)}&expand=projects.issuetypes`,e=await w(`/rest/api/3/issue/createmeta?${r}`),t=Array.isArray(e?.projects)?e.projects:[],s=t.find(a=>String(a?.key||"").toUpperCase()===String(n||"").toUpperCase())||t[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function qe(n,r){if(!n)throw new Error("projectKey is required");let e="sprint is not EMPTY";r==="active"?e="sprint in openSprints()":r==="closed"?e="sprint in closedSprints()":r==="future"&&(e="sprint in futureSprints()");let t=`project = ${n} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,s=await w(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.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 u={active:0,future:1,closed:2},l=(u[a.state]??3)-(u[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function jt(n,{sprintId:r,sprintName:e,target:t}={}){let i=Array.isArray(n)?n:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(r!=null&&String(r).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(r))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=i.find(u=>String(u.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(u=>({s:u,score:X(o,u.name||"")})).sort((u,l)=>l.score-u.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let s=String(t||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:i[0],selectedBy:s}:{sprint:i[0],selectedBy:"default"}}function xt(n,r){let e=n?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(r)):!1}async function Ct({issueKey:n,projectKey:r,sprintId:e,attempts:t=3,delayMs:i=450}){let s=[];for(let o=0;o<t;o++){try{let a=`project = ${r} AND key = ${n} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,u=await w(`/rest/api/3/search/jql?${c}`);if(Number(u?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await w(`/rest/api/3/issue/${n}?fields=customfield_10020,status`),m=xt(p,e);if(s.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<t-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function le({issueKey:n,projectKey:r,sprintId:e,sprintName:t,target:i}){if(!n)return{ok:!1,error:"issueKey is required"};let s=r;if(!s&&(s=(await w(`/rest/api/3/issue/${n}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${n}`};let o=await qe(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=jt(o,{sprintId:e,sprintName:t,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:e??null,sprintName:t??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await w(`/rest/api/3/issue/${n}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let u=await Ct({issueKey:n,projectKey:s,sprintId:a.id}),l=u.ok;return{ok:l,issueKey:n,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:u.method,verified:l,verificationTrace:u.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${n} in sprint ${a.id}`}}async function Lt(){let n=process.env.JIRA_API_TOKEN,r=process.env.JIRA_EMAIL,e=process.env.JIRA_BASE_URL;if(n&&r&&e)return{authType:"token",apiToken:n,email:r,baseUrl:e};let t=await Rt("jira");return t?.cloudId?{authType:"oauth",accessToken:t.token,cloudId:t.cloudId}:{authType:"token",apiToken:t?.token,email:r||t?.email||"",baseUrl:e||t?.instanceUrl||t?.baseUrl||process.env.ATLASSIAN_INSTANCE_URL||""}}function Pt(n,r,e={}){let t=n||{},i={Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers};if(t.authType==="token"){let s=String(t.baseUrl||t.instanceUrl||"").trim().replace(/\/+$/,""),o=t.apiToken||t.accessToken||"";if(!s)throw new Error("Jira token connection has no base URL \u2014 reconnect Jira with its instance URL, or set JIRA_BASE_URL.");if(!t.email)throw new Error("Jira token connection has no account email \u2014 reconnect Jira with the account email, or set JIRA_EMAIL.");if(!o)throw new Error("Jira token connection has no API token \u2014 reconnect Jira, or set JIRA_API_TOKEN.");return{url:`${s}${r}`,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${o}`).toString("base64"),...i}}}if(typeof t.accessToken!="string"||!t.accessToken)throw new Error(`Invalid jira token type: ${typeof t.accessToken}`);if(!t.cloudId)throw new Error("Invalid jira cloudId: missing");return{url:`https://api.atlassian.com/ex/jira/${t.cloudId}${r}`,headers:{Authorization:`Bearer ${t.accessToken}`,...i}}}async function w(n,r={}){let e=async()=>{let t=await Lt(),{url:i,headers:s}=Pt(t,n,r),o=await N(i,{method:r.method||"GET",headers:s,body:r.body?JSON.stringify(r.body):void 0,signal:r.signal},{kind:/\/search\b/.test(String(n))?"job":"api",what:`Jira ${r.method||"GET"} ${n}`}),a=()=>o.text().catch(u=>{if(te(u)||r.signal?.aborted)throw u;return""});if(!o.ok){let u=await a(),l=new Error(`Jira API ${o.status}: ${u.slice(0,300)}`);throw l.status=o.status,l}let c=await a();if(!c||!c.trim())return{};try{return JSON.parse(c)}catch{return{raw:c}}};try{return await e()}catch(t){if(r.signal?.aborted)throw t;let i=String(t?.message||t||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw t;return $t("jira"),e()}}var H={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:q.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
|
|
21
|
+
`}function G(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"text":{let t={t:"text",v:String(e.text??"")},i=Array.isArray(e.marks)?e.marks:[];i.some(s=>s?.type==="code")&&(t={t:"code",v:String(e.text??"")});for(let s of i)!s||s.type==="code"||(s.type==="strong"?t={t:"strong",c:[t]}:s.type==="em"?t={t:"em",c:[t]}:s.type==="strike"?t={t:"strike",c:[t]}:s.type==="link"&&s.attrs?.href&&(t={t:"link",href:String(s.attrs.href),c:[t]}));r.push(t);break}case"hardBreak":r.push({t:"br"});break;case"mention":r.push({t:"text",v:String(e.attrs?.text||(e.attrs?.id?`@${e.attrs.id}`:"@someone"))});break;case"emoji":r.push({t:"text",v:String(e.attrs?.text||e.attrs?.shortName||"")});break;case"status":r.push({t:"text",v:String(e.attrs?.text||"")});break;case"date":r.push({t:"text",v:e.attrs?.timestamp?new Date(Number(e.attrs.timestamp)).toISOString().slice(0,10):""});break;case"inlineCard":{let t=String(e.attrs?.url||"");t&&r.push({t:"link",href:t,c:[{t:"text",v:t}]});break}default:Array.isArray(e.content)?r.push(...G(e.content)):typeof e.text=="string"&&r.push({t:"text",v:e.text})}return r}function R(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"paragraph":r.push({t:"paragraph",c:G(e.content)});break;case"heading":r.push({t:"heading",level:Number(e.attrs?.level)||1,c:G(e.content)});break;case"bulletList":r.push({t:"bullet",items:(e.content||[]).map(t=>R(t?.content))});break;case"orderedList":r.push({t:"ordered",start:Number(e.attrs?.order)||1,items:(e.content||[]).map(t=>R(t?.content))});break;case"taskList":r.push({t:"task",items:(e.content||[]).map(t=>({checked:t?.attrs?.state==="DONE",c:G(t?.content)}))});break;case"decisionList":r.push({t:"bullet",items:(e.content||[]).map(t=>[{t:"paragraph",c:G(t?.content)}])});break;case"codeBlock":r.push({t:"code",lang:String(e.attrs?.language||""),v:(e.content||[]).map(t=>String(t?.text??"")).join("")});break;case"blockquote":r.push({t:"quote",c:R(e.content)});break;case"panel":{let t=String(e.attrs?.panelType||"info");r.push({t:"panel",kind:t in Le?t:"info",c:R(e.content)});break}case"rule":r.push({t:"rule"});break;case"table":{let t=(e.content||[]).filter(a=>a?.type==="tableRow"),i=a=>(a.content||[]).map(c=>{let u=R(c?.content);return A(K(u).trim().replace(/\n+/g," "))}),s=a=>(a.content||[]).length>0&&(a.content||[]).every(c=>c?.type==="tableHeader"),o=t.length&&s(t[0])?i(t[0]):null;r.push({t:"table",header:o,rows:t.slice(o?1:0).map(i)});break}case"mediaSingle":case"mediaGroup":case"media":case"mediaInline":r.push({t:"paragraph",c:[{t:"text",v:"[attachment]"}]});break;case"expand":case"nestedExpand":{let t=String(e.attrs?.title||"").trim();t&&r.push({t:"paragraph",c:[{t:"strong",c:[{t:"text",v:t}]}]}),r.push(...R(e.content));break}default:{let t=Array.isArray(e.content)?e.content:[];t.some(i=>i?.type==="text"||i?.type==="hardBreak")?r.push({t:"paragraph",c:G(t)}):t.length?r.push(...R(t)):typeof e.text=="string"&&e.text&&r.push({t:"paragraph",c:[{t:"text",v:e.text}]})}}return r}function $t(n){try{if(Array.isArray(n))return R(n);if(n&&typeof n=="object"){let r=n;return r.type==="doc"||!r.type&&Array.isArray(r.content)?R(r.content):R([r])}if(typeof n=="string")return qe(n)}catch{}return[]}function ce(n){try{return Rt(K($t(n)))}catch{return""}}function Ct(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Tt(Et(import.meta.url)),r=Ot(n,"..","bin","mcp-skill.mjs");return Nt(r)?r:null}function Lt(n){return Je(n)}async function le(n,r){try{return await n(Lt(r))}catch(e){let t=Number(e?.status);if(!(t>=400&&t<500))throw e;return console.warn(`[jira] rich body rejected (${t}) \u2014 retrying as plain text: ${String(e?.message||e).slice(0,200)}`),await n(ae(r))}}function D(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ue(n){return D(n).replace(/[a-z0-9]+/g,"")}function ee(n,r){let e=D(n),t=D(r);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let i=l=>{let p=new Map;for(let m=0;m<l.length-1;m++){let g=l.slice(m,m+2);p.set(g,(p.get(g)||0)+1)}return p},s=i(e),o=i(t),a=0,c=0,u=0;for(let l of s.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of s.entries()){let m=o.get(l)||0;a+=Math.min(p,m)}return 2*a/Math.max(1,c+u)}function E(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Pt(n,r=[]){let e=Array.isArray(r)?r:[];if(e.length===0)return{requested:n||null,resolved:null,strategy:"none"};let t=e.filter(a=>!a.subtask),i=t.length>0?t:e,s=E(n);if(s){let a=i.find(l=>E(l.name)===s);if(a)return{requested:n,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(m=>E(m)===s))continue;let p=i.find(m=>l.some(g=>E(g)===E(m.name)));if(p)return{requested:n,resolved:p,strategy:"alias"}}let u=i.map(l=>({t:l,score:ee(n,l.name)})).sort((l,p)=>p.score-l.score);if(u[0]&&u[0].score>=.5)return{requested:n,resolved:u[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(u=>E(u.name)===a);if(c)return{requested:n||null,resolved:c,strategy:"default-preferred"}}return{requested:n||null,resolved:i[0],strategy:"default-first"}}async function Ue(n){let r=`projectKeys=${encodeURIComponent(n)}&expand=projects.issuetypes`,e=await w(`/rest/api/3/issue/createmeta?${r}`),t=Array.isArray(e?.projects)?e.projects:[],s=t.find(a=>String(a?.key||"").toUpperCase()===String(n||"").toUpperCase())||t[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function Me(n,r){if(!n)throw new Error("projectKey is required");let e="sprint is not EMPTY";r==="active"?e="sprint in openSprints()":r==="closed"?e="sprint in closedSprints()":r==="future"&&(e="sprint in futureSprints()");let t=`project = ${n} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,s=await w(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.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 u={active:0,future:1,closed:2},l=(u[a.state]??3)-(u[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function qt(n,{sprintId:r,sprintName:e,target:t}={}){let i=Array.isArray(n)?n:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(r!=null&&String(r).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(r))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=i.find(u=>String(u.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(u=>({s:u,score:ee(o,u.name||"")})).sort((u,l)=>l.score-u.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let s=String(t||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:i[0],selectedBy:s}:{sprint:i[0],selectedBy:"default"}}function Jt(n,r){let e=n?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(r)):!1}async function Ut({issueKey:n,projectKey:r,sprintId:e,attempts:t=3,delayMs:i=450}){let s=[];for(let o=0;o<t;o++){try{let a=`project = ${r} AND key = ${n} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,u=await w(`/rest/api/3/search/jql?${c}`);if(Number(u?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await w(`/rest/api/3/issue/${n}?fields=customfield_10020,status`),m=Jt(p,e);if(s.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<t-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function pe({issueKey:n,projectKey:r,sprintId:e,sprintName:t,target:i}){if(!n)return{ok:!1,error:"issueKey is required"};let s=r;if(!s&&(s=(await w(`/rest/api/3/issue/${n}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${n}`};let o=await Me(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=qt(o,{sprintId:e,sprintName:t,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:e??null,sprintName:t??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await w(`/rest/api/3/issue/${n}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let u=await Ut({issueKey:n,projectKey:s,sprintId:a.id}),l=u.ok;return{ok:l,issueKey:n,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:u.method,verified:l,verificationTrace:u.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${n} in sprint ${a.id}`}}async function Mt(){let n=process.env.JIRA_API_TOKEN,r=process.env.JIRA_EMAIL,e=process.env.JIRA_BASE_URL;if(n&&r&&e)return{authType:"token",apiToken:n,email:r,baseUrl:e};let t=await jt("jira");return(t?.authType?t.authType!=="token":!!t?.cloudId)?{authType:"oauth",accessToken:t.token,cloudId:t.cloudId}:{authType:"token",apiToken:t?.token,email:r||t?.email||"",baseUrl:e||t?.baseUrl||t?.instanceUrl||process.env.ATLASSIAN_INSTANCE_URL||""}}function Gt(n,r,e={}){let t=n||{},i={Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers};if(t.authType==="token"){let s=String(t.baseUrl||t.instanceUrl||"").trim().replace(/\/+$/,""),o=t.apiToken||t.accessToken||"";if(!s)throw new Error("Jira token connection has no base URL \u2014 reconnect Jira with its instance URL, or set JIRA_BASE_URL.");if(!t.email)throw new Error("Jira token connection has no account email \u2014 reconnect Jira with the account email, or set JIRA_EMAIL.");if(!o)throw new Error("Jira token connection has no API token \u2014 reconnect Jira, or set JIRA_API_TOKEN.");return{url:`${s}${r}`,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${o}`).toString("base64"),...i}}}if(typeof t.accessToken!="string"||!t.accessToken)throw new Error(`Invalid jira token type: ${typeof t.accessToken}`);if(!t.cloudId)throw new Error("Invalid jira cloudId: missing");return{url:`https://api.atlassian.com/ex/jira/${t.cloudId}${r}`,headers:{Authorization:`Bearer ${t.accessToken}`,...i}}}async function w(n,r={}){let e=async()=>{let t=await Mt(),{url:i,headers:s}=Gt(t,n,r),o=await T(i,{method:r.method||"GET",headers:s,body:r.body?JSON.stringify(r.body):void 0,signal:r.signal},{kind:/\/search\b/.test(String(n))?"job":"api",what:`Jira ${r.method||"GET"} ${n}`}),a=()=>o.text().catch(u=>{if(ne(u)||r.signal?.aborted)throw u;return""});if(!o.ok){let u=await a(),l=new Error(`Jira API ${o.status}: ${u.slice(0,300)}`);throw l.status=o.status,l}let c=await a();if(!c||!c.trim())return{};try{return JSON.parse(c)}catch{return{raw:c}}};try{return await e()}catch(t){if(r.signal?.aborted)throw t;let i=String(t?.message||t||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw t;return xt("jira"),e()}}var F={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:U.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
|
|
22
22
|
You have direct access to the user's Jira. Use these tools proactively:
|
|
23
23
|
|
|
24
24
|
### Issue tools
|
|
@@ -68,9 +68,9 @@ When user asks to move/transition ticket status:
|
|
|
68
68
|
3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
|
|
69
69
|
4. Call jira_get_issue(issueKey) to verify final status before claiming success.
|
|
70
70
|
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.
|
|
71
|
-
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let n=Tt();if(!n)return null;let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(r.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(r[e]=process.env[e]);return{command:"node",args:[n],env:r,description:this.description}},async handleToolCall(n,r){try{switch(n){case"jira_list_projects":{let e=await w("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=r||{};if(e){let s=await w(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let u of o)for(let l of u.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((u,l)=>String(u.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let t=await w("/rest/api/3/status"),i=(Array.isArray(t)?t:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:e}=r||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await Pe(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=r.jql||"",t=r.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let s=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await w(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let e=r.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await w(`/rest/api/3/issue/${e}`);return JSON.stringify({key:t.key,project:t.fields?.project?.key,summary:t.fields?.summary,description:t.fields?.description?oe(t.fields.description):t.fields?.description??null,status:t.fields?.status?.name,assignee:t.fields?.assignee?.displayName||"Unassigned",priority:t.fields?.priority?.name,type:t.fields?.issuetype?.name,labels:t.fields?.labels,created:t.fields?.created,updated:t.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:t,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:u,moveToActiveSprint:l,sprintId:p,sprintName:m,target:g}=r;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let d={requested:i||null,resolved:null,strategy:"none"},b=[];try{b=await Pe(e),d=Et(i,b)}catch{}let h={project:{key:e},summary:t,issuetype:d?.resolved?.id?{id:d.resolved.id}:{name:i||"Task"}};o&&(h.priority={name:o}),a?.length&&(h.labels=a),c&&(h.assignee={id:c});let k=s?await ae(f=>w("/rest/api/3/issue",{method:"POST",body:{fields:{...h,description:f}}}),s):await w("/rest/api/3/issue",{method:"POST",body:{fields:h}}),y={ok:!0,key:k.key,id:k.id,self:k.self};return d?.resolved&&(y.issueType=d.resolved.name,y.issueTypeResolution=d.strategy,d.strategy!=="exact"&&d.requested&&O(d.requested)!==O(d.resolved.name)&&(y.issueTypeWarning=`Requested "${d.requested}" is not available in ${e}; used "${d.resolved.name}" instead.`)),b.length>0&&(y.availableIssueTypes=b.map(f=>f.name)),(u||l)&&(y.sprintMove=await le({issueKey:k.key,projectKey:e,sprintId:p,sprintName:m,target:g})),JSON.stringify(y)}case"jira_list_sprints":{let{projectKey:e,state:t}=r,i=await qe(e,t);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o}=r||{},a=await le({issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o}=r||{},a=await le({issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:i,status:s,maxResults:o}=r;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=t?`sprint = ${t}`:`sprint = "${e}"`,u=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${u}${c}${l} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,g=await w(`/rest/api/3/search/jql?${m}`),d=(g.issues||[]).map(h=>({key:h.key,project:h.fields?.project?.key,summary:h.fields?.summary,status:h.fields?.status?.name,assignee:h.fields?.assignee?.displayName||"Unassigned",priority:h.fields?.priority?.name,type:h.fields?.issuetype?.name})),b={};for(let h of d)b[h.status]=(b[h.status]||0)+1;return JSON.stringify({count:d.length,total:g.total||d.length,statusCounts:b,issues:d})}case"jira_get_comments":{let{issueKey:e,maxResults:t}=r;if(!e)return JSON.stringify({error:"issueKey is required"});let s=await w(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c=a.body?.content?oe(a.body):"";return{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=r;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await ae(i=>w(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:i}}),t),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:t}=r;if(!e||!t)return JSON.stringify({error:"issueKey and fields are required"});if(typeof t.description=="string"){let{description:i,...s}=t;await ae(o=>w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:{...s,description:o}}}),i)}else await w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:t}});return JSON.stringify({ok:!0,issueKey:e})}case"jira_transition_issue":{let{issueKey:e,transitionId:t,toStatus:i,statusName:s,status:o}=r;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!t&&!a){let p=((await w(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(m=>({id:m.id,name:m.name,to:m.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=t;if(!c){let p=(await w(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=G(a),g=p.find(d=>G(d?.name||"")===m||G(d?.to?.name||"")===m);if(!g){let d=ce(a);d.length>=2&&(g=p.find(b=>{let h=ce(b?.name||""),k=ce(b?.to?.name||""),y=h.length>=2&&(h.includes(d)||d.includes(h)),f=k.length>=2&&(k.includes(d)||d.includes(k));return y||f}))}if(!g){let d=p.map(y=>{let f=X(a,y?.name||""),S=X(a,y?.to?.name||"");return{t:y,score:Math.max(f,S)}}).sort((y,f)=>f.score-y.score),b=d[0],h=d[1];b&&b.score>=.45&&(!h||b.score-h.score>=.12)&&(g=b.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(d=>({id:d.id,name:d.name,to:d.to?.name}))});c=g.id}await w(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let u=await w(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:u?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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. Markdown is rendered (headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels)."},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. Markdown is rendered: headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels."}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, description, story points, labels, priority). A string `description` is Markdown and is rendered.",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"]}}]};var qt={new:"todo",indeterminate:"in_progress",done:"done"},Jt=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function de(n){if(!n)return"unknown";if(n.name&&Jt.test(n.name))return"blocked";let r=n.statusCategory?.key;return qt[r]||"unknown"}function me(n){if(!n)return"";if(Array.isArray(n))return n.map(me).join("");if(n.type==="text")return n.text||"";if(n.type==="hardBreak"||n.type==="rule")return`
|
|
72
|
-
`;let r=n.content?
|
|
73
|
-
`),r}function
|
|
71
|
+
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let n=Ct();if(!n)return{command:null,args:[],env:{},description:this.description};let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(r.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"node",args:[n,"../dist/jira.js","jiraSkill"],env:r,description:this.description}},async handleToolCall(n,r){try{switch(n){case"jira_list_projects":{let e=await w("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=r||{};if(e){let s=await w(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let u of o)for(let l of u.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((u,l)=>String(u.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let t=await w("/rest/api/3/status"),i=(Array.isArray(t)?t:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:e}=r||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await Ue(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=r.jql||"",t=r.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let s=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await w(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let e=r.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await w(`/rest/api/3/issue/${e}`);return JSON.stringify({key:t.key,project:t.fields?.project?.key,summary:t.fields?.summary,description:t.fields?.description?ce(t.fields.description):t.fields?.description??null,status:t.fields?.status?.name,assignee:t.fields?.assignee?.displayName||"Unassigned",priority:t.fields?.priority?.name,type:t.fields?.issuetype?.name,labels:t.fields?.labels,created:t.fields?.created,updated:t.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:t,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:u,moveToActiveSprint:l,sprintId:p,sprintName:m,target:g}=r;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let d={requested:i||null,resolved:null,strategy:"none"},b=[];try{b=await Ue(e),d=Pt(i,b)}catch{}let h={project:{key:e},summary:t,issuetype:d?.resolved?.id?{id:d.resolved.id}:{name:i||"Task"}};o&&(h.priority={name:o}),a?.length&&(h.labels=a),c&&(h.assignee={id:c});let S=s?await le(f=>w("/rest/api/3/issue",{method:"POST",body:{fields:{...h,description:f}}}),s):await w("/rest/api/3/issue",{method:"POST",body:{fields:h}}),y={ok:!0,key:S.key,id:S.id,self:S.self};return d?.resolved&&(y.issueType=d.resolved.name,y.issueTypeResolution=d.strategy,d.strategy!=="exact"&&d.requested&&E(d.requested)!==E(d.resolved.name)&&(y.issueTypeWarning=`Requested "${d.requested}" is not available in ${e}; used "${d.resolved.name}" instead.`)),b.length>0&&(y.availableIssueTypes=b.map(f=>f.name)),(u||l)&&(y.sprintMove=await pe({issueKey:S.key,projectKey:e,sprintId:p,sprintName:m,target:g})),JSON.stringify(y)}case"jira_list_sprints":{let{projectKey:e,state:t}=r,i=await Me(e,t);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o}=r||{},a=await pe({issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o}=r||{},a=await pe({issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:i,status:s,maxResults:o}=r;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=t?`sprint = ${t}`:`sprint = "${e}"`,u=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${u}${c}${l} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,g=await w(`/rest/api/3/search/jql?${m}`),d=(g.issues||[]).map(h=>({key:h.key,project:h.fields?.project?.key,summary:h.fields?.summary,status:h.fields?.status?.name,assignee:h.fields?.assignee?.displayName||"Unassigned",priority:h.fields?.priority?.name,type:h.fields?.issuetype?.name})),b={};for(let h of d)b[h.status]=(b[h.status]||0)+1;return JSON.stringify({count:d.length,total:g.total||d.length,statusCounts:b,issues:d})}case"jira_get_comments":{let{issueKey:e,maxResults:t}=r;if(!e)return JSON.stringify({error:"issueKey is required"});let s=await w(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c=a.body?.content?ce(a.body):"";return{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=r;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await le(i=>w(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:i}}),t),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:t}=r;if(!e||!t)return JSON.stringify({error:"issueKey and fields are required"});if(typeof t.description=="string"){let{description:i,...s}=t;await le(o=>w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:{...s,description:o}}}),i)}else await w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:t}});return JSON.stringify({ok:!0,issueKey:e})}case"jira_transition_issue":{let{issueKey:e,transitionId:t,toStatus:i,statusName:s,status:o}=r;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!t&&!a){let p=((await w(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(m=>({id:m.id,name:m.name,to:m.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=t;if(!c){let p=(await w(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=D(a),g=p.find(d=>D(d?.name||"")===m||D(d?.to?.name||"")===m);if(!g){let d=ue(a);d.length>=2&&(g=p.find(b=>{let h=ue(b?.name||""),S=ue(b?.to?.name||""),y=h.length>=2&&(h.includes(d)||d.includes(h)),f=S.length>=2&&(S.includes(d)||d.includes(S));return y||f}))}if(!g){let d=p.map(y=>{let f=ee(a,y?.name||""),k=ee(a,y?.to?.name||"");return{t:y,score:Math.max(f,k)}}).sort((y,f)=>f.score-y.score),b=d[0],h=d[1];b&&b.score>=.45&&(!h||b.score-h.score>=.12)&&(g=b.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(d=>({id:d.id,name:d.name,to:d.to?.name}))});c=g.id}await w(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let u=await w(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:u?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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. Markdown is rendered (headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels)."},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. Markdown is rendered: headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels."}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, description, story points, labels, priority). A string `description` is Markdown and is rendered.",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"]}}]};var Kt={new:"todo",indeterminate:"in_progress",done:"done"},Dt=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function fe(n){if(!n)return"unknown";if(n.name&&Dt.test(n.name))return"blocked";let r=n.statusCategory?.key;return Kt[r]||"unknown"}function ye(n){if(!n)return"";if(Array.isArray(n))return n.map(ye).join("");if(n.type==="text")return n.text||"";if(n.type==="hardBreak"||n.type==="rule")return`
|
|
72
|
+
`;let r=n.content?ye(n.content):"";return/^(paragraph|heading|listItem|blockquote|codeBlock|panel)$/.test(n.type)&&(r+=`
|
|
73
|
+
`),r}function de(n,r){let e=n.fields||{},t=e.status||null,i=null;if(n.self&&n.key)try{i=`${new URL(n.self).origin}/browse/${n.key}`}catch{i=null}return!i&&r&&n.key&&(i=`${String(r).replace(/\/+$/,"")}/browse/${n.key}`),{id:String(n.id??n.key??""),key:n.key,title:e.summary||"",body:typeof e.description=="string"?e.description:ye(e.description?.content).trim(),state:t?.name||null,stateCategory:fe(t),assignee:e.assignee?.displayName||null,url:i,_raw:n}}function me(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}var ge={id:"jira",toStateCategory:fe,toNeutral:de,async listCandidates(n={}){let r=n.query||"";if(!r.trim()){let s=[];if(n.state&&s.push(`status = "${n.state}"`),n.labels){let o=Array.isArray(n.labels)?n.labels:[n.labels];for(let a of o)s.push(`labels = "${a}"`)}n.updatedAfter&&s.push(`updated >= "${n.updatedAfter}"`),r=s.length?`${s.join(" AND ")} ORDER BY updated DESC`:"ORDER BY updated DESC"}let e=Number(n.limit)||30,t=`jql=${encodeURIComponent(r)}&maxResults=${e}&fields=summary,description,status,assignee,labels,project,updated,created`;return((await w(`/rest/api/3/search/jql?${t}`)).issues||[]).map(s=>de(s))},async getTicket(n){if(!n)throw new Error("key is required");let r=await w(`/rest/api/3/issue/${encodeURIComponent(n)}`);return!r||!r.key?null:de(r)},async getComments(n){if(!n)throw new Error("key is required");return(me(await F.handleToolCall("jira_get_comments",{issueKey:n})).comments||[]).map(e=>({id:String(e.id),author:e.author||"Unknown",body:e.body||"",createdAt:e.created||null,updatedAt:e.updated||null,_raw:e}))},async addComment(n,r){if(!n||!r)throw new Error("key and body are required");return{ok:!!me(await F.handleToolCall("jira_add_comment",{issueKey:n,body:r})).ok,id:null}},async transition(n,r){if(!n)throw new Error("key is required");let e=JSON.parse(await F.handleToolCall("jira_transition_issue",{issueKey:n,toStatus:r}));if(!e.ok)return{ok:!1,error:e.error||"transition failed",_raw:e};let t=e.statusAfter||null;return{ok:!0,stateAfter:t,stateCategoryAfter:fe(t?{name:t}:null),_raw:e}},async linkPullRequest(n,r,e){if(!n||!r)throw new Error("key and prUrl are required");try{return await w(`/rest/api/3/issue/${encodeURIComponent(n)}/remotelink`,{method:"POST",body:{object:{url:r,title:e||r,icon:{url16x16:"https://github.com/favicon.ico",title:"GitHub"}}}}),{ok:!0,via:"remotelink"}}catch(t){let i=`${e?`${e}: `:"Linked PR: "}${r}`;return{ok:!!me(await F.handleToolCall("jira_add_comment",{issueKey:n,body:i})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as Bt}from"fs";import{fileURLToPath as Ht}from"url";import{dirname as Ft,resolve as zt}from"path";function Wt(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Ft(Ht(import.meta.url)),r=zt(n,"..","bin","mcp-skill.mjs");return Bt(r)?r:null}var Yt=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Qt(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let n=process.env.LINEAR_API_KEY;if(!n)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return n}async function I(n,r={}){let e=await T(Yt,{method:"POST",headers:{Authorization:Qt(),"Content-Type":"application/json"},body:JSON.stringify({query:n,variables:r})},{kind:"api",what:"Linear GraphQL"});if(!e.ok){let i=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${i.slice(0,300)}`)}let t=await e.json().catch(()=>null);if(!t)throw new Error("Linear API returned a non-JSON body");if(Array.isArray(t.errors)&&t.errors.length){let i=t.errors.map(s=>s?.message||String(s)).join("; ");throw new Error(`Linear GraphQL error: ${i.slice(0,300)}`)}return t.data}function W(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Vt(n,r){let e=W(n),t=W(r);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let i=l=>{let p=new Map;for(let m=0;m<l.length-1;m++){let g=l.slice(m,m+2);p.set(g,(p.get(g)||0)+1)}return p},s=i(e),o=i(t),a=0,c=0,u=0;for(let l of s.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of s.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+u)}function Zt(n,r){let e=Array.isArray(n)?n:[];if(!e.length)return{state:null,strategy:"no-states"};let t=W(r);if(!t)return{state:null,strategy:"no-target"};let i=e.find(a=>W(a.name)===t);if(i)return{state:i,strategy:"exact"};let s={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(s)){if(!c.some(l=>W(l)===t))continue;let u=e.find(l=>l.type===a);if(u)return{state:u,strategy:"type-alias"}}let o=e.map(a=>({s:a,score:Vt(r,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 Xt=`
|
|
74
74
|
id
|
|
75
75
|
identifier
|
|
76
76
|
number
|
|
@@ -84,7 +84,7 @@ When user asks to move/transition ticket status:
|
|
|
84
84
|
assignee { id name displayName email }
|
|
85
85
|
labels { nodes { id name color } }
|
|
86
86
|
team { id key name }
|
|
87
|
-
`,
|
|
87
|
+
`,j={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:U.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
|
|
88
88
|
You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
89
89
|
|
|
90
90
|
### Discovery
|
|
@@ -102,13 +102,13 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
102
102
|
|
|
103
103
|
### Notes
|
|
104
104
|
- 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.
|
|
105
|
-
- Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);process.env.LINEAR_API_URL&&(n.LINEAR_API_URL=process.env.LINEAR_API_URL);let r=
|
|
105
|
+
- Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let n={};for(let e of this.envKeys)process.env[e]&&(n[e]=process.env[e]);process.env.LINEAR_API_URL&&(n.LINEAR_API_URL=process.env.LINEAR_API_URL);let r=Wt();return r?{type:"stdio",command:"node",args:[r,"../dist/linear.js","linearSkill"],env:n,description:this.description}:{command:null,args:[],env:n,description:this.description}},async handleToolCall(n,r){try{switch(n){case"linear_list_teams":{let t=(await I(`
|
|
106
106
|
query Teams($first: Int) {
|
|
107
107
|
teams(first: $first) {
|
|
108
108
|
nodes { id key name description }
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
|
-
`,{first:r?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:t.length,teams:t})}case"linear_list_states":{let{teamId:e,teamKey:t}=r||{},i=e;if(!i&&t&&(i=await
|
|
111
|
+
`,{first:r?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:t.length,teams:t})}case"linear_list_states":{let{teamId:e,teamKey:t}=r||{},i=e;if(!i&&t&&(i=await Ge(t)),i){let c=(await I(`
|
|
112
112
|
query States($teamId: String!) {
|
|
113
113
|
team(id: $teamId) {
|
|
114
114
|
id key name
|
|
@@ -127,7 +127,7 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
127
127
|
nodes { id name color team { id key } }
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
|
-
`,{first:r?.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:t,stateId:i,stateName:s,label:o,assigneeId:a,updatedAfter:c,limit:u}=r||{},l={},p=e;!p&&t&&(p=await
|
|
130
|
+
`,{first:r?.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:t,stateId:i,stateName:s,label:o,assigneeId:a,updatedAfter:c,limit:u}=r||{},l={},p=e;!p&&t&&(p=await Ge(t)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:s&&(l.state={name:{eqIgnoreCase:s}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let g=((await I(`
|
|
131
131
|
query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
|
|
132
132
|
issues(first: $first, filter: $filter, orderBy: $orderBy) {
|
|
133
133
|
nodes {
|
|
@@ -139,41 +139,41 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
|
-
`,{first:u||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(d=>({id:d.id,identifier:d.identifier,number:d.number,title:d.title,url:d.url,priority:d.priority,state:d.state?.name,stateType:d.state?.type,assignee:d.assignee?.displayName||null,labels:(d.labels?.nodes||[]).map(b=>b.name),team:d.team?.key,createdAt:d.createdAt,updatedAt:d.updatedAt}));return JSON.stringify({count:g.length,issues:g})}case"linear_get_issue":{let e=r?.issueId||r?.identifier||r?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let t=await
|
|
142
|
+
`,{first:u||30,filter:Object.keys(l).length?l:void 0,orderBy:"updatedAt"}))?.issues?.nodes||[]).map(d=>({id:d.id,identifier:d.identifier,number:d.number,title:d.title,url:d.url,priority:d.priority,state:d.state?.name,stateType:d.state?.type,assignee:d.assignee?.displayName||null,labels:(d.labels?.nodes||[]).map(b=>b.name),team:d.team?.key,createdAt:d.createdAt,updatedAt:d.updatedAt}));return JSON.stringify({count:g.length,issues:g})}case"linear_get_issue":{let e=r?.issueId||r?.identifier||r?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let t=await z(e);return JSON.stringify(t?{id:t.id,identifier:t.identifier,number:t.number,title:t.title,description:t.description||"",url:t.url,priority:t.priority,state:t.state?.name,stateId:t.state?.id,stateType:t.state?.type,assignee:t.assignee?.displayName||t.assignee?.name||null,assigneeId:t.assignee?.id||null,labels:(t.labels?.nodes||[]).map(i=>i.name),team:t.team?{id:t.team.id,key:t.team.key,name:t.team.name}:null,createdAt:t.createdAt,updatedAt:t.updatedAt}:{error:`Issue not found: ${e}`})}case"linear_get_comments":{let e=r?.issueId||r?.identifier||r?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let t=await z(e,`
|
|
143
143
|
id identifier
|
|
144
144
|
comments(first: ${Number(r?.limit)||50}) {
|
|
145
145
|
nodes { id body createdAt updatedAt user { id name displayName } }
|
|
146
146
|
}
|
|
147
|
-
`);if(!t)return JSON.stringify({error:`Issue not found: ${e}`});let i=(t.comments?.nodes||[]).map(s=>({id:s.id,author:s.user?.displayName||s.user?.name||"Unknown",body:s.body||"",createdAt:s.createdAt,updatedAt:s.updatedAt})).sort((s,o)=>String(o.createdAt).localeCompare(String(s.createdAt)));return JSON.stringify({count:i.length,issue:t.identifier,comments:i})}case"linear_add_comment":{let e=r?.issueId||r?.identifier||r?.issueKey,t=r?.body;if(!e||!t)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await
|
|
147
|
+
`);if(!t)return JSON.stringify({error:`Issue not found: ${e}`});let i=(t.comments?.nodes||[]).map(s=>({id:s.id,author:s.user?.displayName||s.user?.name||"Unknown",body:s.body||"",createdAt:s.createdAt,updatedAt:s.updatedAt})).sort((s,o)=>String(o.createdAt).localeCompare(String(s.createdAt)));return JSON.stringify({count:i.length,issue:t.identifier,comments:i})}case"linear_add_comment":{let e=r?.issueId||r?.identifier||r?.issueKey,t=r?.body;if(!e||!t)return JSON.stringify({error:"issueId/identifier and body are required"});let i=await z(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await I(`
|
|
148
148
|
mutation AddComment($input: CommentCreateInput!) {
|
|
149
149
|
commentCreate(input: $input) {
|
|
150
150
|
success
|
|
151
151
|
comment { id url createdAt }
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
|
-
`,{input:{issueId:i.id,body:t}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let e=r?.issueId||r?.identifier||r?.issueKey,{stateId:t,stateName:i,toStatus:s,status:o}=r||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let a=await
|
|
154
|
+
`,{input:{issueId:i.id,body:t}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let e=r?.issueId||r?.identifier||r?.issueKey,{stateId:t,stateName:i,toStatus:s,status:o}=r||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let a=await z(e,`
|
|
155
155
|
id identifier
|
|
156
156
|
state { id name type }
|
|
157
157
|
team { id key states { nodes { id name type position } } }
|
|
158
|
-
`);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=t,u=t?{strategy:"explicit-id"}:null;if(!c){let m=String(i||s||o||"").trim(),g=(a.team?.states?.nodes||[]).slice().sort((b,h)=>(b.position||0)-(h.position||0));if(!m)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:g.map(b=>({id:b.id,name:b.name,type:b.type}))});let d=
|
|
158
|
+
`);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=t,u=t?{strategy:"explicit-id"}:null;if(!c){let m=String(i||s||o||"").trim(),g=(a.team?.states?.nodes||[]).slice().sort((b,h)=>(b.position||0)-(h.position||0));if(!m)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:g.map(b=>({id:b.id,name:b.name,type:b.type}))});let d=Zt(g,m);if(!d.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${m}" in team ${a.team?.key}`,issue:a.identifier,availableStates:g.map(b=>({id:b.id,name:b.name,type:b.type}))});c=d.state.id,u={strategy:d.strategy,matchedName:d.state.name}}let p=(await I(`
|
|
159
159
|
mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
|
|
160
160
|
issueUpdate(id: $id, input: $input) {
|
|
161
161
|
success
|
|
162
162
|
issue { id identifier state { id name type } }
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
|
-
`,{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:u})}case"linear_link_attachment":{let e=r?.issueId||r?.identifier||r?.issueKey,{url:t,title:i,subtitle:s}=r||{};if(!e||!t)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await
|
|
165
|
+
`,{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:u})}case"linear_link_attachment":{let e=r?.issueId||r?.identifier||r?.issueKey,{url:t,title:i,subtitle:s}=r||{};if(!e||!t)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await z(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await I(`
|
|
166
166
|
mutation LinkAttachment($input: AttachmentCreateInput!) {
|
|
167
167
|
attachmentCreate(input: $input) {
|
|
168
168
|
success
|
|
169
169
|
attachment { id url title }
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
`,{input:{issueId:o.id,url:t,title:i||t,subtitle:s||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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
|
|
172
|
+
`,{input:{issueId:o.id,url:t,title:i||t,subtitle:s||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 Ge(n){return(await I(`
|
|
173
173
|
query TeamByKey($filter: TeamFilter) {
|
|
174
174
|
teams(first: 1, filter: $filter) { nodes { id key } }
|
|
175
175
|
}
|
|
176
|
-
`,{filter:{key:{eq:n}}}))?.teams?.nodes?.[0]?.id||null}async function
|
|
176
|
+
`,{filter:{key:{eq:n}}}))?.teams?.nodes?.[0]?.id||null}async function z(n,r=Xt){let e=String(n).trim(),t=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(t){let s=t[1].toUpperCase(),o=Number(t[2]);return(await I(`
|
|
177
177
|
query IssueByIdentifier($filter: IssueFilter) {
|
|
178
178
|
issues(first: 1, filter: $filter) {
|
|
179
179
|
nodes { ${r} }
|
|
@@ -183,11 +183,11 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
183
183
|
query IssueById($id: String!) {
|
|
184
184
|
issue(id: $id) { ${r} }
|
|
185
185
|
}
|
|
186
|
-
`,{id:e}))?.issue||null}var
|
|
186
|
+
`,{id:e}))?.issue||null}var er={triage:"todo",backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",canceled:"done"},tr=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function be(n){return n?n.name&&tr.test(n.name)?"blocked":er[n.type]||"unknown":"unknown"}function Y(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function he(n){let r=n.state||null,e=n.stateType||null;return{id:String(n.id||n.identifier||""),key:n.identifier||String(n.id||""),title:n.title||"",body:n.description||"",state:r,stateCategory:be(r?{name:r,type:e}:null),assignee:n.assignee||null,url:n.url||null,_raw:n}}var _e={id:"linear",toStateCategory:be,toNeutral:he,async listCandidates(n={}){let r=n.ctx||{},e={teamId:r.teamId,teamKey:r.teamKey,stateName:n.state,label:Array.isArray(n.labels)?n.labels[0]:n.labels,assigneeId:r.assigneeId,updatedAfter:n.updatedAfter,limit:n.limit};return(Y(await j.handleToolCall("linear_list_issues",e)).issues||[]).map(he)},async getTicket(n){if(!n)throw new Error("key is required");let r=JSON.parse(await j.handleToolCall("linear_get_issue",{identifier:n}));return r.error?null:he(r)},async getComments(n){if(!n)throw new Error("key is required");return(Y(await j.handleToolCall("linear_get_comments",{identifier:n})).comments||[]).map(e=>({id:String(e.id),author:e.author||"Unknown",body:e.body||"",createdAt:e.createdAt||null,updatedAt:e.updatedAt||null,_raw:e}))},async addComment(n,r){if(!n||!r)throw new Error("key and body are required");let e=Y(await j.handleToolCall("linear_add_comment",{identifier:n,body:r}));return{ok:!!e.ok,id:e.commentId||null}},async transition(n,r){if(!n)throw new Error("key is required");let e=JSON.parse(await j.handleToolCall("linear_update_state",{identifier:n,toStatus:r}));if(!e.ok)return{ok:!1,error:e.error||"state update failed",_raw:e};let t=e.stateAfter||null;return{ok:!0,stateAfter:t,stateCategoryAfter:be(t?{name:t,type:e.stateTypeAfter}:null),_raw:e}},async linkPullRequest(n,r,e){if(!n||!r)throw new Error("key and prUrl are required");try{if(Y(await j.handleToolCall("linear_link_attachment",{identifier:n,url:r,title:e||r})).ok)return{ok:!0,via:"attachment"};throw new Error("attachmentCreate returned ok:false")}catch(t){let i=`${e?`${e}: `:"Linked PR: "}${r}`;return{ok:!!Y(await j.handleToolCall("linear_add_comment",{identifier:n,body:i})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as or}from"fs";import{fileURLToPath as ar}from"url";import{dirname as cr,resolve as lr}from"path";import{resolveIntegrationToken as Ye}from"@zibby/core/backend-client.js";import{spawn as Fr,execSync as zr}from"child_process";import{existsSync as Yr,mkdirSync as Qr,readdirSync as Vr,statSync as Zr,readFileSync as Xr}from"fs";import{resolve as tn,join as rn,basename as nn}from"path";function Ke(n,r,e,t,i="clone"){try{n(`git -C "${r}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(s){let o=String(s?.message||s);t&&(o=o.split(t).join("***")),console.error(`[${i}] WARNING: failed to strip token from .git/config: ${o}`)}}import rr from"crypto";var De=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Be=/<!--\s*zbreview-summary\s*-->/i;function nr(n){return String(n||"").replace(De,"").replace(Be,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function sr(n,r){return rr.createHash("sha256").update(`${String(n||"")}\0${nr(r)}`).digest("hex").slice(0,12)}function ir(n){return`
|
|
187
187
|
|
|
188
|
-
<!-- zbfp:${n} -->`}var
|
|
188
|
+
<!-- zbfp:${n} -->`}var He=`
|
|
189
189
|
|
|
190
|
-
<!-- zbreview-summary -->`;function
|
|
190
|
+
<!-- zbreview-summary -->`;function Fe(n){let r=De.exec(String(n||""));return r?r[1].toLowerCase():null}function ze(n){return Be.test(String(n||""))}function We(n,r){let e=new Set([...r||[]].map(s=>String(s).toLowerCase())),t=[],i=0;for(let s of Array.isArray(n)?n:[]){if(!s||!s.body)continue;let o=sr(s.path,s.body);if(e.has(o)){i+=1;continue}e.add(o),t.push({...s,_fp:o,body:`${String(s.body)}${ir(o)}`})}return{toPost:t,skipped:i}}function ur(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=cr(ar(import.meta.url)),r=lr(n,"..","bin","mcp-skill.mjs");return or(r)?r:null}async function _(n,r={}){let{token:e}=await Ye("github"),t=n.startsWith("https://")?n:`https://api.github.com${n}`,i={Authorization:`Bearer ${e}`,Accept:r.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...r.body?{"Content-Type":"application/json"}:{}},s=await T(t,{method:r.method||"GET",headers:i,body:r.body?JSON.stringify(r.body):void 0},{kind:"api",what:`GitHub ${r.method||"GET"} ${n}`});if(!s.ok){let o=await s.text().catch(()=>""),a=new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`);throw a.status=s.status,a}return r.raw?s.text():s.json()}var v={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:U.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
|
|
191
191
|
You have access to the user's GitHub repositories. Available tools:
|
|
192
192
|
|
|
193
193
|
### Discovery
|
|
@@ -230,6 +230,6 @@ When user says "check out repo-name" or "clone repo-name":
|
|
|
230
230
|
3. STOP. Do not offer to inspect files or ask what to do next.
|
|
231
231
|
|
|
232
232
|
When user just wants to "look at" or "read" files (not clone):
|
|
233
|
-
- Use github_get_file to read individual files via API`,resolve(){let n=ir();if(!n)return{command:null,args:[],env:{},description:this.description};let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"node",args:[n,"../dist/github.js","githubSkill"],env:r,description:this.description,alwaysLoad:!0}},async handleToolCall(n,r){try{switch(n){case"github_search_issues":{let e=r.query;if(!e)return JSON.stringify({error:"query is required"});let t=await _(`/search/issues?q=${encodeURIComponent(e)}&per_page=${r.limit||20}`),i=(t.items||[]).map(s=>({number:s.number,title:s.title,state:s.state,repo:s.repository_url?.split("/").slice(-2).join("/"),url:s.html_url,user:s.user?.login,isPR:!!s.pull_request,labels:(s.labels||[]).map(o=>o.name),createdAt:s.created_at}));return JSON.stringify({total:t.total_count,items:i})}case"github_search_code":{let e=r.query;if(!e)return JSON.stringify({error:"query is required"});let t=r.repo?`+repo:${r.repo}`:"",i=r.language?`+language:${r.language}`:"",s=await _(`/search/code?q=${encodeURIComponent(e)}${t}${i}&per_page=${r.limit||15}`),o=(s.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:s.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}`);return JSON.stringify({number:s.number,title:s.title,state:s.state,merged:s.merged,body:s.body?.slice(0,5e3),user:s.user?.login,branch:s.head?.ref,headSha:s.head?.sha,base:s.base?.ref,changedFiles:s.changed_files,additions:s.additions,deletions:s.deletions,createdAt:s.created_at,mergedAt:s.merged_at,url:s.html_url,labels:(s.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=s.length>15e3;return JSON.stringify({number:i,diff:o?s.slice(0,15e3):s,truncated:o,totalLength:s.length})}case"github_list_pr_files":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:s.length,files:s.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:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=50`),o=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=50`),a=[...s.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,u)=>new Date(c.createdAt)-new Date(u.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:t,number:i,commentId:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await _(`/repos/${e}/${t}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let u=c.filter(m=>m.id===a||m.in_reply_to_id===a).sort((m,g)=>new Date(m.created_at)-new Date(g.created_at)),l=u.length?u:[o],p=l.find(m=>m.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(m=>({id:m.id,user:m.user?.login,body:(m.body||"").slice(0,4e3),createdAt:m.created_at,isRoot:m.id===a,url:m.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:t,number:i,commentId:s,body:o}=r||{};if(!e||!t||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await _(`/repos/${e}/${t}/pulls/${i}/comments/${s}/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:t,number:i,body:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:t,number:i,body:s,event:o,comments:a}=r||{};if(!e||!t||!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 u=Array.isArray(a)?a.filter(y=>y&&y.path&&y.body&&(y.line!=null||y.position!=null)).map(y=>{let f={path:y.path,body:String(y.body)};return y.line!=null?(f.line=Number(y.line),f.side=y.side==="LEFT"?"LEFT":"RIGHT"):f.position=Number(y.position),f}):[];if(c!=="APPROVE"&&!s&&u.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l=new Set,p=null;try{for(let y=1;y<=20;y+=1){let f=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100&page=${y}`);if(!Array.isArray(f)||f.length===0)break;for(let S of f){let $=De(S.body);$&&l.add($)}if(f.length<100)break}for(let y=1;y<=20&&p==null;y+=1){let f=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=100&page=${y}`);if(!Array.isArray(f)||f.length===0)break;for(let S of f)if(Be(S.body)){p=S.id;break}if(f.length<100)break}}catch{}let m=!1,g=!1;if(s){let y=`${String(s)}${Ke}`;try{p!=null?(await _(`/repos/${e}/${t}/issues/comments/${p}`,{method:"PATCH",body:{body:y}}),m=!0):await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:y}}),g=!0}catch{}}let{toPost:d,skipped:b}=He(u,l),h=d.map(({_fp:y,...f})=>f),k=null;if(h.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let y={event:c};h.length>0&&(y.comments=h),h.length===0&&c==="REQUEST_CHANGES"&&(y.body="Changes requested \u2014 see the review summary comment."),k=await _(`/repos/${e}/${t}/pulls/${i}/reviews`,{method:"POST",body:y})}return JSON.stringify({ok:!0,id:k?k.id:void 0,state:k?k.state:void 0,event:c,notePosted:g,summaryUpdated:m,commentsPosted:h.length,inlineSkipped:b||void 0,url:k?k.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:t,branch:i,path:s,limit:o,since:a,until:c,page:u}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let l=Math.min(Number(o)||20,100),p=`/repos/${e}/${t}/commits?per_page=${l}&page=${Number(u)||1}`;i&&(p+=`&sha=${encodeURIComponent(i)}`),s&&(p+=`&path=${encodeURIComponent(s)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let m=await _(p);return JSON.stringify({total:m.length,page:Number(u)||1,hasMore:m.length>=l,commits:m.map(g=>({sha:g.sha?.slice(0,8),fullSha:g.sha,message:g.commit?.message?.slice(0,300),author:g.commit?.author?.name,authorEmail:g.commit?.author?.email,date:g.commit?.author?.date,url:g.html_url}))})}case"github_get_commit":{let{owner:e,repo:t,sha:i,includePrs:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await _(`/repos/${e}/${t}/commits/${i}`),a;if(s)try{let c=await _(`/repos/${e}/${t}/commits/${i}/pulls`);a=(Array.isArray(c)?c:[]).map(u=>({number:u.number,title:u.title,state:u.state,merged:!!u.merged_at,webUrl:u.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:t,path:i,ref:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${t}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await _(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"),u=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:u?c.slice(0,2e4):c,truncated:u})}case"github_get_user":try{let e=await _("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let t=e.repositories[0],i=t.owner.login,s=t.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await _(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="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 t=(await _("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of t)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 s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,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 d=function(y){let f=y.replace(/^~(?=$|\/|\\)/,g);return a(f)},{owner:e,repo:t,destination:i}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:u}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:m}=await Fe("github"),g=l(),b=i?d(i):o(g,"zibby-repos"),h=o(b,t);if(u(b,{recursive:!0}),c(h))return JSON.stringify({error:`Directory ${h} already exists. Remove it first or use a different destination.`,existingPath:h});let k=`https://x-access-token:${m}@github.com/${e}/${t}.git`;try{s(`git clone ${k} "${h}"`,{stdio:"pipe"});let y=`https://github.com/${e}/${t}.git`;Ue(s,h,y,m,"github_clone");let f=p()==="win32",S;return f?S=s(`dir "${h}"`,{encoding:"utf-8",shell:"cmd.exe"}):S=s(`ls -la "${h}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:h,message:`Cloned ${e}/${t} to ${h}`,contents:S.split(`
|
|
233
|
+
- Use github_get_file to read individual files via API`,resolve(){let n=ur();if(!n)return{command:null,args:[],env:{},description:this.description};let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"node",args:[n,"../dist/github.js","githubSkill"],env:r,description:this.description}},async handleToolCall(n,r){try{switch(n){case"github_search_issues":{let e=r.query;if(!e)return JSON.stringify({error:"query is required"});let t=await _(`/search/issues?q=${encodeURIComponent(e)}&per_page=${r.limit||20}`),i=(t.items||[]).map(s=>({number:s.number,title:s.title,state:s.state,repo:s.repository_url?.split("/").slice(-2).join("/"),url:s.html_url,user:s.user?.login,isPR:!!s.pull_request,labels:(s.labels||[]).map(o=>o.name),createdAt:s.created_at}));return JSON.stringify({total:t.total_count,items:i})}case"github_search_code":{let e=r.query;if(!e)return JSON.stringify({error:"query is required"});let t=r.repo?`+repo:${r.repo}`:"",i=r.language?`+language:${r.language}`:"",s=await _(`/search/code?q=${encodeURIComponent(e)}${t}${i}&per_page=${r.limit||15}`),o=(s.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:s.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}`);return JSON.stringify({number:s.number,title:s.title,state:s.state,merged:s.merged,body:s.body?.slice(0,5e3),user:s.user?.login,branch:s.head?.ref,headSha:s.head?.sha,base:s.base?.ref,changedFiles:s.changed_files,additions:s.additions,deletions:s.deletions,createdAt:s.created_at,mergedAt:s.merged_at,url:s.html_url,labels:(s.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=s.length>15e3;return JSON.stringify({number:i,diff:o?s.slice(0,15e3):s,truncated:o,totalLength:s.length})}case"github_list_pr_files":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:s.length,files:s.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:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=50`),o=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=50`),a=[...s.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,u)=>new Date(c.createdAt)-new Date(u.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:t,number:i,commentId:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await _(`/repos/${e}/${t}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let u=c.filter(m=>m.id===a||m.in_reply_to_id===a).sort((m,g)=>new Date(m.created_at)-new Date(g.created_at)),l=u.length?u:[o],p=l.find(m=>m.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(m=>({id:m.id,user:m.user?.login,body:(m.body||"").slice(0,4e3),createdAt:m.created_at,isRoot:m.id===a,url:m.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:t,number:i,commentId:s,body:o}=r||{};if(!e||!t||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await _(`/repos/${e}/${t}/pulls/${i}/comments/${s}/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:t,number:i,body:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:t,number:i,body:s,event:o,comments:a}=r||{};if(!e||!t||!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 u=Array.isArray(a)?a.filter(y=>y&&y.path&&y.body&&(y.line!=null||y.position!=null)).map(y=>{let f={path:y.path,body:String(y.body)};return y.line!=null?(f.line=Number(y.line),f.side=y.side==="LEFT"?"LEFT":"RIGHT"):f.position=Number(y.position),f}):[];if(c!=="APPROVE"&&!s&&u.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l=new Set,p=null;try{for(let y=1;y<=20;y+=1){let f=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100&page=${y}`);if(!Array.isArray(f)||f.length===0)break;for(let k of f){let $=Fe(k.body);$&&l.add($)}if(f.length<100)break}for(let y=1;y<=20&&p==null;y+=1){let f=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=100&page=${y}`);if(!Array.isArray(f)||f.length===0)break;for(let k of f)if(ze(k.body)){p=k.id;break}if(f.length<100)break}}catch{}let m=!1,g=!1;if(s){let y=`${String(s)}${He}`;try{p!=null?(await _(`/repos/${e}/${t}/issues/comments/${p}`,{method:"PATCH",body:{body:y}}),m=!0):await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:y}}),g=!0}catch{}}let{toPost:d,skipped:b}=We(u,l),h=d.map(({_fp:y,...f})=>f),S=null;if(h.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let y={event:c};h.length>0&&(y.comments=h),h.length===0&&c==="REQUEST_CHANGES"&&(y.body="Changes requested \u2014 see the review summary comment."),S=await _(`/repos/${e}/${t}/pulls/${i}/reviews`,{method:"POST",body:y})}return JSON.stringify({ok:!0,id:S?S.id:void 0,state:S?S.state:void 0,event:c,notePosted:g,summaryUpdated:m,commentsPosted:h.length,inlineSkipped:b||void 0,url:S?S.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:t,branch:i,path:s,limit:o,since:a,until:c,page:u}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let l=Math.min(Number(o)||20,100),p=`/repos/${e}/${t}/commits?per_page=${l}&page=${Number(u)||1}`;i&&(p+=`&sha=${encodeURIComponent(i)}`),s&&(p+=`&path=${encodeURIComponent(s)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let m=await _(p);return JSON.stringify({total:m.length,page:Number(u)||1,hasMore:m.length>=l,commits:m.map(g=>({sha:g.sha?.slice(0,8),fullSha:g.sha,message:g.commit?.message?.slice(0,300),author:g.commit?.author?.name,authorEmail:g.commit?.author?.email,date:g.commit?.author?.date,url:g.html_url}))})}case"github_get_commit":{let{owner:e,repo:t,sha:i,includePrs:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await _(`/repos/${e}/${t}/commits/${i}`),a;if(s)try{let c=await _(`/repos/${e}/${t}/commits/${i}/pulls`);a=(Array.isArray(c)?c:[]).map(u=>({number:u.number,title:u.title,state:u.state,merged:!!u.merged_at,webUrl:u.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:t,path:i,ref:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${t}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await _(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"),u=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:u?c.slice(0,2e4):c,truncated:u})}case"github_get_user":try{let e=await _("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let t=e.repositories[0],i=t.owner.login,s=t.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await _(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="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 t=(await _("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of t)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 s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,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 d=function(y){let f=y.replace(/^~(?=$|\/|\\)/,g);return a(f)},{owner:e,repo:t,destination:i}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:u}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:m}=await Ye("github"),g=l(),b=i?d(i):o(g,"zibby-repos"),h=o(b,t);if(u(b,{recursive:!0}),c(h))return JSON.stringify({error:`Directory ${h} already exists. Remove it first or use a different destination.`,existingPath:h});let S=`https://x-access-token:${m}@github.com/${e}/${t}.git`;try{s(`git clone ${S} "${h}"`,{stdio:"pipe"});let y=`https://github.com/${e}/${t}.git`;Ke(s,h,y,m,"github_clone");let f=p()==="win32",k;return f?k=s(`dir "${h}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=s(`ls -la "${h}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:h,message:`Cloned ${e}/${t} to ${h}`,contents:k.split(`
|
|
234
234
|
`).slice(0,30).join(`
|
|
235
|
-
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(y){let S=String(y.message||y).split(m).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"github_search_repos":{let{query:e,limit:t}=r;if(!e)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=e.toLowerCase(),a=s.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,t||20)})}case"github_list_repos":{let{owner:e,type:t,sort:i,direction:s,limit:o,query:a}=r,c=100,u=o||200,l=[],p=f=>({name:f.name,fullName:f.full_name,private:f.private,description:f.description,language:f.language,defaultBranch:f.default_branch,updatedAt:f.updated_at,stars:f.stargazers_count,url:f.html_url,fullPath:f.full_name,webUrl:f.html_url,visibility:f.visibility||(f.private?"private":"public")}),m=f=>{if(!a)return!0;let S=String(a).toLowerCase();return f.name&&f.name.toLowerCase().includes(S)||f.fullName&&f.fullName.toLowerCase().includes(S)||f.description&&f.description.toLowerCase().includes(S)};if(!e){let f=1,S=!0;for(;S&&l.length<u;){let B=`/installation/repositories?per_page=${c}&page=${f}`,ee=(await _(B)).repositories||[];if(ee.length===0)break;l=l.concat(ee),S=ee.length===c,f++}let $=l.map(p).filter(m),D=$.slice(0,u),nt=$.length>D.length,Ae=D.filter(B=>B.private).length,Ie=D.filter(B=>!B.private).length;return JSON.stringify({count:D.length,repos:D,truncated:nt,privateCount:Ae,publicCount:Ie,message:`Found ${Ae} private and ${Ie} public repos`})}let g=await _(`/orgs/${e}`).then(()=>!0).catch(()=>!1),d=1,b=!0;for(;b&&l.length<u;){let f;g?f=`/orgs/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:f=`/users/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let S=await _(f),$=Array.isArray(S)?S:[];if($.length===0)break;l=l.concat($),b=$.length===c,d++}let h=l.map(p).filter(m),k=h.slice(0,u),y=h.length>k.length;return JSON.stringify({count:k.length,repos:k,truncated:y})}case"github_create_pr":{let{owner:e,repo:t,head:i,title:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=r.base;if(!o)try{o=(await _(`/repos/${e}/${t}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:r.body?String(r.body):"",draft:!!r.draft};try{let c=await _(`/repos/${e}/${t}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${t}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let u=String(c.message||c);if(/GitHub API 422/.test(u))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${t}`,provider:"github",skippedReason:u});throw c}}case"github_merge_pr":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=r.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};r.commitTitle&&(o.commit_title=String(r.commitTitle)),r.commitMessage&&(o.commit_message=String(r.commitMessage));try{let a=await _(`/repos/${e}/${t}/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:t,title:i,body:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await _(`/repos/${e}/${t}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:t,state:i,labels:s,since:o,assignee:a,sort:c,direction:u,limit:l}=r||{};if(!e||!t)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",u||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let m=await _(`/repos/${e}/${t}/issues?${p.toString()}`),g=(Array.isArray(m)?m:[]).filter(d=>!d.pull_request).map(d=>({number:d.number,title:d.title,state:d.state,labels:(d.labels||[]).map(b=>typeof b=="string"?b:b.name),assignee:d.assignee?.login||null,assignees:(d.assignees||[]).map(b=>b.login),user:d.user?.login,comments:d.comments,url:d.html_url,createdAt:d.created_at,updatedAt:d.updated_at}));return JSON.stringify({count:g.length,issues:g})}case"github_get_issue":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:t,number:i,limit:s}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=${s||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:t,number:i,body:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:t,number:i,stateReason:s}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await _(`/repos/${e}/${t}/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:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:e,repo:t,number:i,labels:s,mode:o}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await _(`/repos/${e}/${t}/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 _(`/repos/${e}/${t}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await _(`/repos/${e}/${t}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let u=await _(`/repos/${e}/${t}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(u)?u:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};var Qe=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,Ve=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,or=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,ar=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,ze="in progress",We="blocked";function Ze(n,r=[]){if(n==="closed")return"done";if(n!=="open")return"unknown";let e=(r||[]).map(String);return e.some(t=>Qe.test(t))?"blocked":e.some(t=>Ve.test(t))?"in_progress":"todo"}function K(n={}){let r=n.owner||process.env.GITHUB_OWNER,e=n.repo||process.env.GITHUB_REPO;if(!r||!e)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:r,repo:e}}function j(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function be(n,r={}){let e=n.labels||[],t=n.number,i=r.owner&&r.repo?`${r.owner}/${r.repo}#${t}`:`#${t}`;return{id:String(t),key:i,title:n.title||"",body:n.body||"",state:n.state||null,stateCategory:Ze(n.state,e),assignee:n.assignee||n.assignees&&n.assignees[0]||null,url:n.url||null,_raw:n}}var _e={id:"github",toStateCategory:Ze,toNeutral:be,IN_PROGRESS_LABEL:ze,BLOCKED_LABEL:We,async listCandidates(n={}){let r=n.ctx||{},{owner:e,repo:t}=K(r);return(j(await v.handleToolCall("github_list_issues",{owner:e,repo:t,state:n.state||"open",labels:n.labels,since:n.updatedAfter,limit:n.limit})).issues||[]).map(s=>be(s,{owner:e,repo:t}))},async getTicket(n,r={}){let{owner:e,repo:t}=K(r),i=Y(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let s=JSON.parse(await v.handleToolCall("github_get_issue",{owner:e,repo:t,number:i}));return s.error?null:be(s,{owner:e,repo:t})},async getComments(n,r={}){let{owner:e,repo:t}=K(r),i=Y(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);return(j(await v.handleToolCall("github_get_issue_comments",{owner:e,repo:t,number:i})).comments||[]).map(o=>({id:String(o.id),author:o.user||"Unknown",body:o.body||"",createdAt:o.createdAt||null,updatedAt:o.updatedAt||null,_raw:o})).sort((o,a)=>String(a.createdAt).localeCompare(String(o.createdAt)))},async addComment(n,r,e={}){let{owner:t,repo:i}=K(e),s=Y(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("body is required");let o=j(await v.handleToolCall("github_add_issue_comment",{owner:t,repo:i,number:s,body:r}));return{ok:!!o.ok,id:o.id?String(o.id):null}},async transition(n,r,e={}){let{owner:t,repo:i}=K(e),s=Y(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let o=String(r||"");if(or.test(o)){let a=j(await v.handleToolCall("github_close_issue",{owner:t,repo:i,number:s,stateReason:"completed"}));return{ok:!!a.ok,stateAfter:a.state||"closed",stateCategoryAfter:"done",_raw:a}}if(Qe.test(o)){await Ye(t,i,s);let a=j(await v.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[We],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:a}}if(Ve.test(o)){await Ye(t,i,s);let a=j(await v.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[ze],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:a}}if(ar.test(o)){let a=j(await v.handleToolCall("github_reopen_issue",{owner:t,repo:i,number:s}));return{ok:!!a.ok,stateAfter:a.state||"open",stateCategoryAfter:"todo",_raw:a}}return{ok:!1,error:`GitHub issues have no "${r}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(n,r,e,t={}){let{owner:i,repo:s}=K(t),o=Y(n);if(o==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("prUrl is required");let a=`${e?`${e}: `:"Linked PR: "}${r}`;return{ok:!!j(await v.handleToolCall("github_add_issue_comment",{owner:i,repo:s,number:o,body:a})).ok,via:"comment"}}};async function Ye(n,r,e){await v.handleToolCall("github_reopen_issue",{owner:n,repo:r,number:e})}function Y(n){if(n==null)return null;if(typeof n=="number")return n;let r=/(\d+)\s*$/.exec(String(n));return r?Number(r[1]):null}var cr=(process.env.PLANE_API_URL||"https://api.plane.so/api/v1").replace(/\/+$/,""),lr=process.env.PLANE_WORKSPACE_SLUG||"",ur=process.env.PLANE_PROJECT_ID||"";function pr(){let n=process.env.PLANE_API_KEY||process.env.PLANE_OAUTH_TOKEN;if(!n)throw new Error("Plane is not connected: set PLANE_API_KEY (personal access token).");return n}function P(n={}){let r=n.workspaceSlug||lr,e=n.projectId||ur;if(!r||!e)throw new Error("Plane scope missing: provide workspaceSlug + projectId (env PLANE_WORKSPACE_SLUG / PLANE_PROJECT_ID or per-call ctx).");return{workspaceSlug:r,projectId:e}}async function L(n,r={}){let e=`${cr}${n}`;if(r.query&&Object.keys(r.query).length){let s=new URLSearchParams;for(let[a,c]of Object.entries(r.query))c!=null&&c!==""&&s.set(a,String(c));let o=s.toString();o&&(e+=(e.includes("?")?"&":"?")+o)}let t=await N(e,{method:r.method||"GET",headers:{"X-API-Key":pr(),Accept:"application/json",...r.body?{"Content-Type":"application/json"}:{},...r.headers},body:r.body?JSON.stringify(r.body):void 0},{kind:"api",what:`Plane ${r.method||"GET"} ${n}`});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Plane API ${t.status}: ${s.slice(0,300)}`)}let i=await t.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}}var dr={backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",cancelled:"done"},mr=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function ke(n){return n?n.name&&mr.test(n.name)?"blocked":dr[n.group]||"unknown":"unknown"}var Xe=new Map,fr=300*1e3;async function tt(n){let{workspaceSlug:r,projectId:e}=P(n),t=Xe.get(e);if(t&&Date.now()-t.fetchedAt<fr)return t.states;let i=await L(`/workspaces/${encodeURIComponent(r)}/projects/${encodeURIComponent(e)}/states/`,{query:{per_page:100}}),s=(i.results||i||[]).map(o=>({id:o.id,name:o.name,group:o.group,color:o.color}));return Xe.set(e,{fetchedAt:Date.now(),states:s}),s}function we(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function yr(n,r){let e=we(r);if(!e)return null;let t=n.find(s=>we(s.name)===e);if(t)return t;let i={todo:["todo","backlog","open","unstarted"],inprogress:["inprogress","started","doing","wip"],done:["done","completed","closed","resolved","cancelled","canceled"],blocked:["blocked","onhold","waiting"]};for(let[,s]of Object.entries(i)){if(!s.some(c=>we(c)===e))continue;let o=e==="done"?"completed":e==="inprogress"?"started":"unstarted",a=n.find(c=>c.group===o);if(a)return a}return null}async function et(n,r){let t=(await tt(r).catch(()=>[])).find(c=>c.id===n.state)||null,{workspaceSlug:i,projectId:s}=P(r),o=r.projectIdentifier&&n.sequence_id!=null?`${r.projectIdentifier}-${n.sequence_id}`:n.sequence_id!=null?String(n.sequence_id):n.id,a=n.assignees||[];return{id:n.id,key:o,title:n.name||"",body:n.description_html||n.description_stripped||n.description||"",state:t?t.name:null,stateCategory:ke(t),assignee:a.length?String(a[0]):null,url:r.baseWebUrl?`${r.baseWebUrl}/${i}/projects/${s}/issues/${n.id}`:null,_raw:n}}var Se={id:"plane",envKeys:["PLANE_API_KEY","PLANE_OAUTH_TOKEN","PLANE_API_URL","PLANE_WORKSPACE_SLUG","PLANE_PROJECT_ID"],planeFetch:L,toStateCategory:ke,async listCandidates(n={}){let r=n.ctx||{},{workspaceSlug:e,projectId:t}=P(r),i={per_page:Math.min(Number(n.limit)||50,100),cursor:n.cursor};n.state&&(i.state=n.state),n.updatedAfter&&(i.updated_at__gte=n.updatedAfter);let o=(await L(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/`,{query:i})).results||[];return n.updatedAfter&&(o=o.filter(a=>String(a.updated_at)>String(n.updatedAfter))),Promise.all(o.map(a=>et(a,r)))},async getTicket(n,r={}){let{workspaceSlug:e,projectId:t}=P(r),i=await L(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/`);return!i||!i.id?null:et(i,r)},async getComments(n,r={}){let{workspaceSlug:e,projectId:t}=P(r);return((await L(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/comments/`,{query:{per_page:100}})).results||[]).map(o=>({id:o.id,author:o.actor||o.actor_detail?.display_name||"Unknown",body:o.comment_html||o.comment_stripped||"",createdAt:o.created_at||null,updatedAt:o.updated_at||null,_raw:o})).sort((o,a)=>String(a.createdAt).localeCompare(String(o.createdAt)))},async addComment(n,r,e={}){let{workspaceSlug:t,projectId:i}=P(e),o=/<[a-z][\s\S]*>/i.test(String(r||""))?String(r):`<p>${String(r||"")}</p>`,a=await L(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/comments/`,{method:"POST",body:{comment_html:o}});return{ok:!!a.id,id:a.id||null,_raw:a}},async transition(n,r,e={}){let{workspaceSlug:t,projectId:i}=P(e),s=await tt(e),o=yr(s,r);if(!o)return{ok:!1,error:`No Plane state matches "${r}" in this project`,availableStates:s.map(c=>({id:c.id,name:c.name,group:c.group}))};let a=await L(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/`,{method:"PATCH",body:{state:o.id}});return{ok:!!a.id,stateAfter:o.name,stateCategoryAfter:ke(o),_raw:a}},async linkPullRequest(n,r,e,t={}){let i=e?`${e}: `:"Linked PR: ";return{ok:!!(await this.addComment(n,`<p>${i}<a href="${r}">${r}</a></p>`,t)).ok,via:"comment"}}};var gr=["todo","in_progress","done","blocked","unknown"];var rt={jira:fe,linear:he,github:_e,plane:Se},hr="jira";function wn(n){let r=String(n||process.env.TRACKER_PROVIDER||hr).trim().toLowerCase(),e=rt[r];if(!e){let t=Object.keys(rt).join(", ");throw new Error(`Unknown tracker provider "${r}". Known providers: ${t}.`)}return e}export{hr as DEFAULT_TRACKER_PROVIDER,rt as TRACKER_ADAPTERS,gr as TRACKER_STATE_CATEGORIES,wn as getAdapter,_e as githubAdapter,fe as jiraAdapter,he as linearAdapter,Se as planeAdapter};
|
|
235
|
+
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(y){let k=String(y.message||y).split(m).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${k}`})}}case"github_search_repos":{let{query:e,limit:t}=r;if(!e)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=e.toLowerCase(),a=s.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,t||20)})}case"github_list_repos":{let{owner:e,type:t,sort:i,direction:s,limit:o,query:a}=r,c=100,u=o||200,l=[],p=f=>({name:f.name,fullName:f.full_name,private:f.private,description:f.description,language:f.language,defaultBranch:f.default_branch,updatedAt:f.updated_at,stars:f.stargazers_count,url:f.html_url,fullPath:f.full_name,webUrl:f.html_url,visibility:f.visibility||(f.private?"private":"public")}),m=f=>{if(!a)return!0;let k=String(a).toLowerCase();return f.name&&f.name.toLowerCase().includes(k)||f.fullName&&f.fullName.toLowerCase().includes(k)||f.description&&f.description.toLowerCase().includes(k)};if(!e){let f=1,k=!0,$=!1;for(;k&&l.length<u;){let N=`/installation/repositories?per_page=${c}&page=${f}`,J;try{J=await _(N)}catch(re){if((re?.status===401||re?.status===403)&&f===1){$=!0;break}throw re}let te=J.repositories||[];if(te.length===0)break;l=l.concat(te),k=te.length===c,f++}if($)for(f=1,k=!0;k&&l.length<u;){let N=await _(`/user/repos?per_page=${c}&page=${f}&affiliation=owner,collaborator,organization_member&sort=${i||"updated"}&direction=${s||"desc"}`),J=Array.isArray(N)?N:[];if(J.length===0)break;l=l.concat(J),k=J.length===c,f++}let ve=l.map(p).filter(m),H=ve.slice(0,u),ot=ve.length>H.length,Re=H.filter(N=>N.private).length,$e=H.filter(N=>!N.private).length;return JSON.stringify({count:H.length,repos:H,truncated:ot,privateCount:Re,publicCount:$e,message:`Found ${Re} private and ${$e} public repos`})}let g=await _(`/orgs/${e}`).then(()=>!0).catch(()=>!1),d=1,b=!0;for(;b&&l.length<u;){let f;g?f=`/orgs/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:f=`/users/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let k=await _(f),$=Array.isArray(k)?k:[];if($.length===0)break;l=l.concat($),b=$.length===c,d++}let h=l.map(p).filter(m),S=h.slice(0,u),y=h.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:y})}case"github_create_pr":{let{owner:e,repo:t,head:i,title:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=r.base;if(!o)try{o=(await _(`/repos/${e}/${t}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:r.body?String(r.body):"",draft:!!r.draft};try{let c=await _(`/repos/${e}/${t}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${t}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let u=String(c.message||c);if(/GitHub API 422/.test(u))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${t}`,provider:"github",skippedReason:u});throw c}}case"github_merge_pr":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=r.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};r.commitTitle&&(o.commit_title=String(r.commitTitle)),r.commitMessage&&(o.commit_message=String(r.commitMessage));try{let a=await _(`/repos/${e}/${t}/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:t,title:i,body:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await _(`/repos/${e}/${t}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:t,state:i,labels:s,since:o,assignee:a,sort:c,direction:u,limit:l}=r||{};if(!e||!t)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",u||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let m=await _(`/repos/${e}/${t}/issues?${p.toString()}`),g=(Array.isArray(m)?m:[]).filter(d=>!d.pull_request).map(d=>({number:d.number,title:d.title,state:d.state,labels:(d.labels||[]).map(b=>typeof b=="string"?b:b.name),assignee:d.assignee?.login||null,assignees:(d.assignees||[]).map(b=>b.login),user:d.user?.login,comments:d.comments,url:d.html_url,createdAt:d.created_at,updatedAt:d.updated_at}));return JSON.stringify({count:g.length,issues:g})}case"github_get_issue":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:t,number:i,limit:s}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=${s||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:t,number:i,body:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:t,number:i,stateReason:s}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await _(`/repos/${e}/${t}/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:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:e,repo:t,number:i,labels:s,mode:o}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await _(`/repos/${e}/${t}/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 _(`/repos/${e}/${t}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await _(`/repos/${e}/${t}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let u=await _(`/repos/${e}/${t}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(u)?u:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}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 commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};var Xe=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,et=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,pr=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,dr=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,Qe="in progress",Ve="blocked";function tt(n,r=[]){if(n==="closed")return"done";if(n!=="open")return"unknown";let e=(r||[]).map(String);return e.some(t=>Xe.test(t))?"blocked":e.some(t=>et.test(t))?"in_progress":"todo"}function B(n={}){let r=n.owner||process.env.GITHUB_OWNER,e=n.repo||process.env.GITHUB_REPO;if(!r||!e)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:r,repo:e}}function x(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function we(n,r={}){let e=n.labels||[],t=n.number,i=r.owner&&r.repo?`${r.owner}/${r.repo}#${t}`:`#${t}`;return{id:String(t),key:i,title:n.title||"",body:n.body||"",state:n.state||null,stateCategory:tt(n.state,e),assignee:n.assignee||n.assignees&&n.assignees[0]||null,url:n.url||null,_raw:n}}var ke={id:"github",toStateCategory:tt,toNeutral:we,IN_PROGRESS_LABEL:Qe,BLOCKED_LABEL:Ve,async listCandidates(n={}){let r=n.ctx||{},{owner:e,repo:t}=B(r);return(x(await v.handleToolCall("github_list_issues",{owner:e,repo:t,state:n.state||"open",labels:n.labels,since:n.updatedAfter,limit:n.limit})).issues||[]).map(s=>we(s,{owner:e,repo:t}))},async getTicket(n,r={}){let{owner:e,repo:t}=B(r),i=Q(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let s=JSON.parse(await v.handleToolCall("github_get_issue",{owner:e,repo:t,number:i}));return s.error?null:we(s,{owner:e,repo:t})},async getComments(n,r={}){let{owner:e,repo:t}=B(r),i=Q(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);return(x(await v.handleToolCall("github_get_issue_comments",{owner:e,repo:t,number:i})).comments||[]).map(o=>({id:String(o.id),author:o.user||"Unknown",body:o.body||"",createdAt:o.createdAt||null,updatedAt:o.updatedAt||null,_raw:o})).sort((o,a)=>String(a.createdAt).localeCompare(String(o.createdAt)))},async addComment(n,r,e={}){let{owner:t,repo:i}=B(e),s=Q(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("body is required");let o=x(await v.handleToolCall("github_add_issue_comment",{owner:t,repo:i,number:s,body:r}));return{ok:!!o.ok,id:o.id?String(o.id):null}},async transition(n,r,e={}){let{owner:t,repo:i}=B(e),s=Q(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let o=String(r||"");if(pr.test(o)){let a=x(await v.handleToolCall("github_close_issue",{owner:t,repo:i,number:s,stateReason:"completed"}));return{ok:!!a.ok,stateAfter:a.state||"closed",stateCategoryAfter:"done",_raw:a}}if(Xe.test(o)){await Ze(t,i,s);let a=x(await v.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[Ve],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:a}}if(et.test(o)){await Ze(t,i,s);let a=x(await v.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[Qe],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:a}}if(dr.test(o)){let a=x(await v.handleToolCall("github_reopen_issue",{owner:t,repo:i,number:s}));return{ok:!!a.ok,stateAfter:a.state||"open",stateCategoryAfter:"todo",_raw:a}}return{ok:!1,error:`GitHub issues have no "${r}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(n,r,e,t={}){let{owner:i,repo:s}=B(t),o=Q(n);if(o==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("prUrl is required");let a=`${e?`${e}: `:"Linked PR: "}${r}`;return{ok:!!x(await v.handleToolCall("github_add_issue_comment",{owner:i,repo:s,number:o,body:a})).ok,via:"comment"}}};async function Ze(n,r,e){await v.handleToolCall("github_reopen_issue",{owner:n,repo:r,number:e})}function Q(n){if(n==null)return null;if(typeof n=="number")return n;let r=/(\d+)\s*$/.exec(String(n));return r?Number(r[1]):null}var mr=(process.env.PLANE_API_URL||"https://api.plane.so/api/v1").replace(/\/+$/,""),fr=process.env.PLANE_WORKSPACE_SLUG||"",yr=process.env.PLANE_PROJECT_ID||"";function gr(){let n=process.env.PLANE_API_KEY||process.env.PLANE_OAUTH_TOKEN;if(!n)throw new Error("Plane is not connected: set PLANE_API_KEY (personal access token).");return n}function q(n={}){let r=n.workspaceSlug||fr,e=n.projectId||yr;if(!r||!e)throw new Error("Plane scope missing: provide workspaceSlug + projectId (env PLANE_WORKSPACE_SLUG / PLANE_PROJECT_ID or per-call ctx).");return{workspaceSlug:r,projectId:e}}async function P(n,r={}){let e=`${mr}${n}`;if(r.query&&Object.keys(r.query).length){let s=new URLSearchParams;for(let[a,c]of Object.entries(r.query))c!=null&&c!==""&&s.set(a,String(c));let o=s.toString();o&&(e+=(e.includes("?")?"&":"?")+o)}let t=await T(e,{method:r.method||"GET",headers:{"X-API-Key":gr(),Accept:"application/json",...r.body?{"Content-Type":"application/json"}:{},...r.headers},body:r.body?JSON.stringify(r.body):void 0},{kind:"api",what:`Plane ${r.method||"GET"} ${n}`});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Plane API ${t.status}: ${s.slice(0,300)}`)}let i=await t.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}}var hr={backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",cancelled:"done"},br=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function Ae(n){return n?n.name&&br.test(n.name)?"blocked":hr[n.group]||"unknown":"unknown"}var rt=new Map,_r=300*1e3;async function st(n){let{workspaceSlug:r,projectId:e}=q(n),t=rt.get(e);if(t&&Date.now()-t.fetchedAt<_r)return t.states;let i=await P(`/workspaces/${encodeURIComponent(r)}/projects/${encodeURIComponent(e)}/states/`,{query:{per_page:100}}),s=(i.results||i||[]).map(o=>({id:o.id,name:o.name,group:o.group,color:o.color}));return rt.set(e,{fetchedAt:Date.now(),states:s}),s}function Se(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function wr(n,r){let e=Se(r);if(!e)return null;let t=n.find(s=>Se(s.name)===e);if(t)return t;let i={todo:["todo","backlog","open","unstarted"],inprogress:["inprogress","started","doing","wip"],done:["done","completed","closed","resolved","cancelled","canceled"],blocked:["blocked","onhold","waiting"]};for(let[,s]of Object.entries(i)){if(!s.some(c=>Se(c)===e))continue;let o=e==="done"?"completed":e==="inprogress"?"started":"unstarted",a=n.find(c=>c.group===o);if(a)return a}return null}async function nt(n,r){let t=(await st(r).catch(()=>[])).find(c=>c.id===n.state)||null,{workspaceSlug:i,projectId:s}=q(r),o=r.projectIdentifier&&n.sequence_id!=null?`${r.projectIdentifier}-${n.sequence_id}`:n.sequence_id!=null?String(n.sequence_id):n.id,a=n.assignees||[];return{id:n.id,key:o,title:n.name||"",body:n.description_html||n.description_stripped||n.description||"",state:t?t.name:null,stateCategory:Ae(t),assignee:a.length?String(a[0]):null,url:r.baseWebUrl?`${r.baseWebUrl}/${i}/projects/${s}/issues/${n.id}`:null,_raw:n}}var Ie={id:"plane",envKeys:["PLANE_API_KEY","PLANE_OAUTH_TOKEN","PLANE_API_URL","PLANE_WORKSPACE_SLUG","PLANE_PROJECT_ID"],planeFetch:P,toStateCategory:Ae,async listCandidates(n={}){let r=n.ctx||{},{workspaceSlug:e,projectId:t}=q(r),i={per_page:Math.min(Number(n.limit)||50,100),cursor:n.cursor};n.state&&(i.state=n.state),n.updatedAfter&&(i.updated_at__gte=n.updatedAfter);let o=(await P(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/`,{query:i})).results||[];return n.updatedAfter&&(o=o.filter(a=>String(a.updated_at)>String(n.updatedAfter))),Promise.all(o.map(a=>nt(a,r)))},async getTicket(n,r={}){let{workspaceSlug:e,projectId:t}=q(r),i=await P(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/`);return!i||!i.id?null:nt(i,r)},async getComments(n,r={}){let{workspaceSlug:e,projectId:t}=q(r);return((await P(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/comments/`,{query:{per_page:100}})).results||[]).map(o=>({id:o.id,author:o.actor||o.actor_detail?.display_name||"Unknown",body:o.comment_html||o.comment_stripped||"",createdAt:o.created_at||null,updatedAt:o.updated_at||null,_raw:o})).sort((o,a)=>String(a.createdAt).localeCompare(String(o.createdAt)))},async addComment(n,r,e={}){let{workspaceSlug:t,projectId:i}=q(e),o=/<[a-z][\s\S]*>/i.test(String(r||""))?String(r):`<p>${String(r||"")}</p>`,a=await P(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/comments/`,{method:"POST",body:{comment_html:o}});return{ok:!!a.id,id:a.id||null,_raw:a}},async transition(n,r,e={}){let{workspaceSlug:t,projectId:i}=q(e),s=await st(e),o=wr(s,r);if(!o)return{ok:!1,error:`No Plane state matches "${r}" in this project`,availableStates:s.map(c=>({id:c.id,name:c.name,group:c.group}))};let a=await P(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/`,{method:"PATCH",body:{state:o.id}});return{ok:!!a.id,stateAfter:o.name,stateCategoryAfter:Ae(o),_raw:a}},async linkPullRequest(n,r,e,t={}){let i=e?`${e}: `:"Linked PR: ";return{ok:!!(await this.addComment(n,`<p>${i}<a href="${r}">${r}</a></p>`,t)).ok,via:"comment"}}};var kr=["todo","in_progress","done","blocked","unknown"];var it={jira:ge,linear:_e,github:ke,plane:Ie},Sr="jira";function Rn(n){let r=String(n||process.env.TRACKER_PROVIDER||Sr).trim().toLowerCase(),e=it[r];if(!e){let t=Object.keys(it).join(", ");throw new Error(`Unknown tracker provider "${r}". Known providers: ${t}.`)}return e}export{Sr as DEFAULT_TRACKER_PROVIDER,it as TRACKER_ADAPTERS,kr as TRACKER_STATE_CATEGORIES,Rn as getAdapter,ke as githubAdapter,ge as jiraAdapter,_e as linearAdapter,Ie as planeAdapter};
|