@zibby/skills 2.0.25 → 2.0.27
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/agentMessaging.d.ts +46 -6
- package/dist/agentMessaging.js +59 -29
- package/dist/artifact.d.ts +19 -0
- package/dist/artifact.js +3 -3
- package/dist/codebaseMemory.d.ts +7 -12
- package/dist/codebaseMemory.js +14 -6
- package/dist/git-write.js +9 -9
- package/dist/git.js +2 -2
- package/dist/github.js +5 -5
- package/dist/gitlab.js +5 -5
- package/dist/graphMemory.d.ts +59 -0
- package/dist/graphMemory.js +17 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +242 -186
- package/dist/jira.d.ts +1 -1
- package/dist/jira.js +20 -18
- package/dist/lib/checkout-rules.d.ts +18 -0
- package/dist/lib/checkout-rules.js +1 -0
- package/dist/lib/markup.d.ts +3 -1
- package/dist/lib/markup.js +18 -16
- package/dist/lib/repo-access.d.ts +143 -0
- package/dist/lib/repo-access.js +1 -0
- package/dist/localWorkspace.js +2 -2
- package/dist/package.json +5 -4
- package/dist/personVerification.d.ts +100 -0
- package/dist/personVerification.js +1 -0
- package/dist/report.d.ts +1 -1
- package/dist/trackers/github-adapter.js +5 -5
- package/dist/trackers/index.js +41 -39
- package/dist/trackers/jira-adapter.js +19 -17
- package/dist/triggerAgent.js +1 -1
- package/dist/vikunja.js +21 -19
- package/package.json +5 -4
package/dist/trackers/index.js
CHANGED
|
@@ -1,24 +1,26 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as Dt}from"fs";import{dirname as Ht,resolve as Ft}from"path";import{fileURLToPath as zt}from"url";import{resolveIntegrationToken as Wt,clearTokenCache as Yt}from"@zibby/core/backend-client.js";var B=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"}),Hr=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 te={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 St(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 At(n="api",r=process.env){let e=te[n]||te.api;return St(e.knob,e.fallback,r)}function ae(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function It(n){try{return new URL(String(n?.url??n)).host||"unknown host"}catch{return"unknown host"}}function Rt(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 j(n,r={},e={}){let t=e.kind||"api",i=(te[t]||te.api).knob,s=e.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(e.timeoutMs))):At(t),o=r?.signal;if(o?.aborted)throw o.reason??new DOMException("This operation was aborted","AbortError");let a=AbortSignal.timeout(s),c=Rt(o,a);try{return await fetch(n,{...r,signal:c})}catch(u){throw a.aborted&&ae(u)?new Error(`${e.what||"request"} TIMED OUT after ${s}ms against ${It(n)} (${i})`):u}}var $t={NOTE:"info",TIP:"success",IMPORTANT:"note",WARNING:"warning",CAUTION:"error"},ze={info:"NOTE",success:"TIP",note:"IMPORTANT",warning:"WARNING",error:"CAUTION"},vt={info:{bg:"rgba(88, 140, 245, 0.16)",rgb:[88,140,245],icon:"\u2139\uFE0F"},note:{bg:"rgba(160, 120, 240, 0.16)",rgb:[160,120,240],icon:"\u{1F4DD}"},warning:{bg:"rgba(236, 170, 60, 0.15)",rgb:[236,170,60],icon:"\u26A0\uFE0F"},success:{bg:"rgba(70, 190, 125, 0.16)",rgb:[70,190,125],icon:"\u2705"},error:{bg:"rgba(235, 90, 80, 0.15)",rgb:[235,90,80],icon:"\u26D4"}},Wr=Object.keys(vt),Tt=2e5,We=6,Nt=/^```([A-Za-z0-9_+.-]{0,32})\s*$/,Ot=/^(#{1,6})[ \t]+(.*?)\s*$/,Et=/^(?:-{3,}|\*{3,}|_{3,})\s*$/,Je=/^>(?: ?(.*))?$/,ce=/^[-*][ \t]+\[([ xX])\][ \t]+(.*)$/,Ge=/^[-*][ \t]+(.*)$/,Me=/^(\d{1,3})[.)][ \t]+(.*)$/,Ke=/^\|.*\|\s*$/,jt=/^\|?\s*:?-{1,}:?\s*(?:\|\s*:?-{1,}:?\s*)*\|?\s*$/,Lt=/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i;function Be(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 Ye(n){let e=String(n??"").slice(0,Tt).replace(/\r\n?/g,`
|
|
2
2
|
`).split(`
|
|
3
|
-
`);return
|
|
4
|
-
`)});continue}if(
|
|
5
|
-
`).
|
|
6
|
-
|
|
7
|
-
`;break;case"
|
|
8
|
-
|
|
9
|
-
`;break;case"
|
|
10
|
-
|
|
11
|
-
`;break;case"
|
|
12
|
-
${
|
|
3
|
+
`);return ue(e,0)}function ue(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:I(i)}),t++;continue}let s;if(s=Nt.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(Et.test(i)){e.push({t:"rule"}),t++;continue}if(s=Ot.exec(i)){let o=Math.min(We,s[1].length);e.push({t:"heading",level:o,c:I(s[2])}),t++;continue}if(Je.test(i)&&r<3){let o=[];for(;t<n.length&&(s=Je.exec(n[t]));)o.push(s[1]??""),t++;let a=o.findIndex(u=>u.trim()!==""),c=a>=0?Lt.exec(o[a].trim()):null;if(c){let u=$t[c[1].toUpperCase()];e.push({t:"panel",kind:u,c:ue(o.slice(a+1),r+1)})}else e.push({t:"quote",c:ue(o,r+1)});continue}if(ce.test(i)){let o=[];for(;t<n.length&&(s=ce.exec(n[t]));)o.push({checked:s[1]!==" ",c:I(s[2])}),t++;e.push({t:"task",items:o});continue}if(Ge.test(i)){let o=[];for(;t<n.length&&!ce.test(n[t])&&(s=Ge.exec(n[t]));)o.push([{t:"paragraph",c:I(s[1])}]),t++;e.push({t:"bullet",items:o});continue}if(s=Me.exec(i)){let o=Math.max(1,parseInt(s[1],10)||1),a=[];for(;t<n.length&&(s=Me.exec(n[t]));)a.push([{t:"paragraph",c:I(s[2])}]),t++;e.push({t:"ordered",start:o,items:a});continue}if(Ke.test(i)&&t+1<n.length&&jt.test(n[t+1])){let o=Be(i).map(I);t+=2;let a=[];for(;t<n.length&&Ke.test(n[t]);)a.push(Be(n[t]).map(I)),t++;e.push({t:"table",header:o,rows:a});continue}e.push({t:"paragraph",c:I(i)}),t++}return e}var xt=/^https?:\/\/[^\s<>()[\]]+/,Ct=/^\[([^\]\n]{1,300})\]\((https?:\/\/[^\s)]{1,2000})\)/,Pt=/[.,;:!?'"]+$/;function qt(n,r){return r<=0?!0:/[\s([{"'“‘>:—–-]/.test(n[r-1])}function Ut(n,r){return r>=n.length?!0:/[\s)\]}"'”’.,;:!?—–-]/.test(n[r])}function Jt(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&&Ut(n,i+e.length))return i;t=i+1}return-1}function I(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=Ct.exec(r.slice(s));if(a){i(),e.push({t:"link",href:a[2],c:I(a[1])}),s+=a[0].length;continue}}if((o==="*"||o==="_"||o==="~")&&qt(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=Jt(r,u,c);if(l>u){i();let p=I(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=xt.exec(r.slice(s));if(a){let c=a[0],u=Pt.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 U(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(...U(t.c,re(r,{type:"strong"})));break;case"em":e.push(...U(t.c,re(r,{type:"em"})));break;case"strike":e.push(...U(t.c,re(r,{type:"strike"})));break;case"link":e.push(...U(t.c,re(r,{type:"link",attrs:{href:t.href}})));break}return e}function re(n,r){return n.some(e=>e.type===r.type)?n:[...n,r]}var le=0;function De(){return le=(le+1)%1e6,`m${Date.now().toString(36)}-${le}`}var D=n=>{let r=U(n);return r.length?{type:"paragraph",content:r}:{type:"paragraph"}};function q(n,r){let e=[];for(let t of n)switch(t.t){case"paragraph":e.push(D(t.c));break;case"heading":if(r==="quote"||r==="item")e.push(D([{t:"strong",c:t.c}]));else{let i=U(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:ne(q(i,"item"))}))});break;case"ordered":e.push({type:"orderedList",attrs:{order:t.start},content:t.items.map(i=>({type:"listItem",content:ne(q(i,"item"))}))});break;case"task":r==="quote"||r==="item"?e.push({type:"bulletList",content:t.items.map(i=>({type:"listItem",content:[D([{t:"text",v:i.checked?"\u2611 ":"\u2610 "},...i.c])]}))}):e.push({type:"taskList",attrs:{localId:De()},content:t.items.map(i=>({type:"taskItem",attrs:{localId:De(),state:i.checked?"DONE":"TODO"},content:Gt(U(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(...q(t.c,r)):r==="panel"?e.push(...He(t).map(i=>({type:"paragraph",content:[{type:"text",text:i}]}))):e.push({type:"blockquote",content:ne(q(t.c,"quote"))});break;case"panel":r==="panel"?e.push(...He(t).map(i=>({type:"paragraph",content:[{type:"text",text:i}]}))):r!=="doc"?e.push(...q(t.c,r)):e.push({type:"panel",attrs:{panelType:t.kind},content:ne(q(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(D(Mt(s)));break}let i=[];t.header&&i.push({type:"tableRow",content:t.header.map(s=>({type:"tableHeader",attrs:{},content:[D(s)]}))});for(let s of t.rows)i.push({type:"tableRow",content:s.map(o=>({type:"tableCell",attrs:{},content:[D(o)]}))});i.length&&e.push({type:"table",attrs:{isNumberColumnEnabled:!1,layout:"default"},content:i});break}}return e}function ne(n){return n.length?n:[{type:"paragraph"}]}function He(n){return J([n]).replace(/\n$/,"").split(`
|
|
5
|
+
`).filter(r=>r!=="")}function Gt(n){return n.length?n:[{type:"text",text:" "}]}function Mt(n){let r=[];return n.forEach((e,t)=>{t&&r.push({t:"text",v:" \xB7 "}),r.push(...e)}),r}function pe(n){return{type:"doc",version:1,content:String(n??"").split(`
|
|
6
|
+
`).map(r=>({type:"paragraph",...r?{content:[{type:"text",text:r}]}:{}}))}}function Qe(n){try{let r=q(Ye(n),"doc");return{type:"doc",version:1,content:r.length?r:[{type:"paragraph"}]}}catch{return pe(n)}}function L(n){let r="";for(let e of n)switch(e.t){case"text":r+=e.v;break;case"br":r+=`
|
|
7
|
+
`;break;case"code":r+=`\`${e.v}\``;break;case"strong":r+=`**${L(e.c)}**`;break;case"em":r+=`_${L(e.c)}_`;break;case"strike":r+=`~~${L(e.c)}~~`;break;case"link":{let t=L(e.c);r+=!t||t===e.href?e.href:`[${t}](${e.href})`;break}}return r}function J(n){let r="",e=!1;for(let t of n){let i=t.t==="quote"||t.t==="panel";switch(i&&e&&(r+=`
|
|
8
|
+
`),e=i,t.t){case"paragraph":r+=`${L(t.c)}
|
|
9
|
+
`;break;case"heading":r+=`${"#".repeat(Math.max(1,Math.min(We,t.level)))} ${L(t.c)}
|
|
10
|
+
`;break;case"bullet":for(let s of t.items)r+=`- ${J(s).trim()}
|
|
11
|
+
`;break;case"ordered":t.items.forEach((s,o)=>{r+=`${t.start+o}. ${J(s).trim()}
|
|
12
|
+
`});break;case"task":for(let s of t.items)r+=`- [${s.checked?"x":" "}] ${L(s.c)}
|
|
13
|
+
`;break;case"code":r+=`\`\`\`${t.lang}
|
|
14
|
+
${t.v}
|
|
13
15
|
\`\`\`
|
|
14
|
-
`;break;case"quote":r+=
|
|
15
|
-
${
|
|
16
|
-
`;break;case"table":{let
|
|
17
|
-
`;
|
|
18
|
-
`);for(let
|
|
16
|
+
`;break;case"quote":r+=Fe(J(t.c));break;case"panel":r+=`> [!${ze[t.kind]}]
|
|
17
|
+
${Fe(J(t.c))}`;break;case"rule":r+=`---
|
|
18
|
+
`;break;case"table":{let s=o=>`| ${o.map(a=>L(a).replace(/\|/g,"\\|")).join(" | ")} |
|
|
19
|
+
`;t.header&&(r+=s(t.header)+`|${t.header.map(()=>" --- |").join("")}
|
|
20
|
+
`);for(let o of t.rows)r+=s(o);break}}}return r}function Kt(n){return n.replace(/^\n+/,"").replace(/\s+$/,"")}function Fe(n){return n.replace(/\n$/,"").split(`
|
|
19
21
|
`).map(r=>r?`> ${r}`:">").join(`
|
|
20
22
|
`)+`
|
|
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
|
|
23
|
+
`}function H(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(...H(e.content)):typeof e.text=="string"&&r.push({t:"text",v:e.text})}return r}function v(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"paragraph":r.push({t:"paragraph",c:H(e.content)});break;case"heading":r.push({t:"heading",level:Number(e.attrs?.level)||1,c:H(e.content)});break;case"bulletList":r.push({t:"bullet",items:(e.content||[]).map(t=>v(t?.content))});break;case"orderedList":r.push({t:"ordered",start:Number(e.attrs?.order)||1,items:(e.content||[]).map(t=>v(t?.content))});break;case"taskList":r.push({t:"task",items:(e.content||[]).map(t=>({checked:t?.attrs?.state==="DONE",c:H(t?.content)}))});break;case"decisionList":r.push({t:"bullet",items:(e.content||[]).map(t=>[{t:"paragraph",c:H(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:v(e.content)});break;case"panel":{let t=String(e.attrs?.panelType||"info");r.push({t:"panel",kind:t in ze?t:"info",c:v(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=v(c?.content);return I(J(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(...v(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:H(t)}):t.length?r.push(...v(t)):typeof e.text=="string"&&e.text&&r.push({t:"paragraph",c:[{t:"text",v:e.text}]})}}return r}function Bt(n){try{if(Array.isArray(n))return v(n);if(n&&typeof n=="object"){let r=n;return r.type==="doc"||!r.type&&Array.isArray(r.content)?v(r.content):v([r])}if(typeof n=="string")return Ye(n)}catch{}return[]}function de(n){try{return Kt(J(Bt(n)))}catch{return""}}function Qt(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Ht(zt(import.meta.url)),r=Ft(n,"..","bin","mcp-skill.mjs");return Dt(r)?r:null}function Vt(n){return Qe(n)}async function me(n,r){try{return await n(Vt(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(pe(r))}}function F(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function fe(n){return F(n).replace(/[a-z0-9]+/g,"")}function se(n,r){let e=F(n),t=F(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 x(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Zt(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=x(n);if(s){let a=i.find(l=>x(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=>x(m)===s))continue;let p=i.find(m=>l.some(g=>x(g)===x(m.name)));if(p)return{requested:n,resolved:p,strategy:"alias"}}let u=i.map(l=>({t:l,score:se(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=>x(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 Ve(n){let r=`projectKeys=${encodeURIComponent(n)}&expand=projects.issuetypes`,e=await k(`/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 Ze(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 k(`/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 Xt(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:se(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 er(n,r){let e=n?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(r)):!1}async function tr({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 k(`/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 k(`/rest/api/3/issue/${n}?fields=customfield_10020,status`),m=er(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 ge({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 k(`/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 Ze(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=Xt(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 k(`/rest/api/3/issue/${n}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let u=await tr({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 rr(){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 Wt("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 nr(n,r,e={}){let t=n||{},i={Accept:"application/json",...e.body&&!e.form?{"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 k(n,r={}){let e=async()=>{let t=await rr(),{url:i,headers:s}=nr(t,n,r),o=await j(i,{method:r.method||"GET",headers:s,body:r.form?r.form: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(ae(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 Yt("jira"),e()}}var Y={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:B.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
|
|
22
24
|
You have direct access to the user's Jira. Use these tools proactively:
|
|
23
25
|
|
|
24
26
|
### Issue tools
|
|
@@ -68,9 +70,9 @@ When user asks to move/transition ticket status:
|
|
|
68
70
|
3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
|
|
69
71
|
4. Call jira_get_issue(issueKey) to verify final status before claiming success.
|
|
70
72
|
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=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?
|
|
73
|
-
`),r}function
|
|
73
|
+
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let n=Qt();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 k("/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 k(`/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 k("/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 Ve(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 k(`/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 k(`/rest/api/3/issue/${e}`);return JSON.stringify({key:t.key,project:t.fields?.project?.key,summary:t.fields?.summary,description:t.fields?.description?de(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 Ve(e),d=Zt(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 me(w=>k("/rest/api/3/issue",{method:"POST",body:{fields:{...h,description:w}}}),s):await k("/rest/api/3/issue",{method:"POST",body:{fields:h}}),f={ok:!0,key:S.key,id:S.id,self:S.self};return d?.resolved&&(f.issueType=d.resolved.name,f.issueTypeResolution=d.strategy,d.strategy!=="exact"&&d.requested&&x(d.requested)!==x(d.resolved.name)&&(f.issueTypeWarning=`Requested "${d.requested}" is not available in ${e}; used "${d.resolved.name}" instead.`)),b.length>0&&(f.availableIssueTypes=b.map(w=>w.name)),(u||l)&&(f.sprintMove=await ge({issueKey:S.key,projectKey:e,sprintId:p,sprintName:m,target:g})),JSON.stringify(f)}case"jira_list_sprints":{let{projectKey:e,state:t}=r,i=await Ze(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 ge({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 ge({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 k(`/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 k(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c=a.body?.content?de(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 me(i=>k(`/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 me(o=>k(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:{...s,description:o}}}),i)}else await k(`/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 k(`/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 k(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=F(a),g=p.find(d=>F(d?.name||"")===m||F(d?.to?.name||"")===m);if(!g){let d=fe(a);d.length>=2&&(g=p.find(b=>{let h=fe(b?.name||""),S=fe(b?.to?.name||""),f=h.length>=2&&(h.includes(d)||d.includes(h)),w=S.length>=2&&(S.includes(d)||d.includes(S));return f||w}))}if(!g){let d=p.map(f=>{let w=se(a,f?.name||""),y=se(a,f?.to?.name||"");return{t:f,score:Math.max(w,y)}}).sort((f,w)=>w.score-f.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 k(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let u=await k(`/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 sr={new:"todo",indeterminate:"in_progress",done:"done"},ir=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function be(n){if(!n)return"unknown";if(n.name&&ir.test(n.name))return"blocked";let r=n.statusCategory?.key;return sr[r]||"unknown"}function _e(n){if(!n)return"";if(Array.isArray(n))return n.map(_e).join("");if(n.type==="text")return n.text||"";if(n.type==="hardBreak"||n.type==="rule")return`
|
|
74
|
+
`;let r=n.content?_e(n.content):"";return/^(paragraph|heading|listItem|blockquote|codeBlock|panel)$/.test(n.type)&&(r+=`
|
|
75
|
+
`),r}function ye(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:_e(e.description?.content).trim(),state:t?.name||null,stateCategory:be(t),assignee:e.assignee?.displayName||null,url:i,_raw:n}}function he(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}var we={id:"jira",toStateCategory:be,toNeutral:ye,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 k(`/rest/api/3/search/jql?${t}`)).issues||[]).map(s=>ye(s))},async getTicket(n){if(!n)throw new Error("key is required");let r=await k(`/rest/api/3/issue/${encodeURIComponent(n)}`);return!r||!r.key?null:ye(r)},async getComments(n){if(!n)throw new Error("key is required");return(he(await Y.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:!!he(await Y.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 Y.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:be(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 k(`/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:!!he(await Y.handleToolCall("jira_add_comment",{issueKey: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";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}var pr=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function dr(){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 R(n,r={}){let e=await j(pr,{method:"POST",headers:{Authorization:dr(),"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 V(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function mr(n,r){let e=V(n),t=V(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 fr(n,r){let e=Array.isArray(n)?n:[];if(!e.length)return{state:null,strategy:"no-states"};let t=V(r);if(!t)return{state:null,strategy:"no-target"};let i=e.find(a=>V(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=>V(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:mr(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 gr=`
|
|
74
76
|
id
|
|
75
77
|
identifier
|
|
76
78
|
number
|
|
@@ -84,7 +86,7 @@ When user asks to move/transition ticket status:
|
|
|
84
86
|
assignee { id name displayName email }
|
|
85
87
|
labels { nodes { id name color } }
|
|
86
88
|
team { id key name }
|
|
87
|
-
`,
|
|
89
|
+
`,C={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:B.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
|
|
88
90
|
You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
89
91
|
|
|
90
92
|
### Discovery
|
|
@@ -102,32 +104,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
102
104
|
|
|
103
105
|
### Notes
|
|
104
106
|
- 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=
|
|
107
|
+
- 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=ur();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 R(`
|
|
106
108
|
query Teams($first: Int) {
|
|
107
109
|
teams(first: $first) {
|
|
108
110
|
nodes { id key name description }
|
|
109
111
|
}
|
|
110
112
|
}
|
|
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
|
|
113
|
+
`,{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 Xe(t)),i){let c=(await R(`
|
|
112
114
|
query States($teamId: String!) {
|
|
113
115
|
team(id: $teamId) {
|
|
114
116
|
id key name
|
|
115
117
|
states { nodes { id name type color position } }
|
|
116
118
|
}
|
|
117
119
|
}
|
|
118
|
-
`,{teamId:i}))?.team,u=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:u.length,states:u})}let o=(await
|
|
120
|
+
`,{teamId:i}))?.team,u=(c?.states?.nodes||[]).slice().sort((l,p)=>(l.position||0)-(p.position||0));return JSON.stringify({team:c?{id:c.id,key:c.key,name:c.name}:null,count:u.length,states:u})}let o=(await R(`
|
|
119
121
|
query AllStates($first: Int) {
|
|
120
122
|
workflowStates(first: $first) {
|
|
121
123
|
nodes { id name type color team { id key name } }
|
|
122
124
|
}
|
|
123
125
|
}
|
|
124
|
-
`,{first:r?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=r||{},i=(await
|
|
126
|
+
`,{first:r?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=r||{},i=(await R(`
|
|
125
127
|
query Labels($first: Int, $filter: IssueLabelFilter) {
|
|
126
128
|
issueLabels(first: $first, filter: $filter) {
|
|
127
129
|
nodes { id name color team { id key } }
|
|
128
130
|
}
|
|
129
131
|
}
|
|
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
|
|
132
|
+
`,{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 Xe(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 R(`
|
|
131
133
|
query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
|
|
132
134
|
issues(first: $first, filter: $filter, orderBy: $orderBy) {
|
|
133
135
|
nodes {
|
|
@@ -139,55 +141,55 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
|
|
|
139
141
|
}
|
|
140
142
|
}
|
|
141
143
|
}
|
|
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
|
|
144
|
+
`,{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 Q(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 Q(e,`
|
|
143
145
|
id identifier
|
|
144
146
|
comments(first: ${Number(r?.limit)||50}) {
|
|
145
147
|
nodes { id body createdAt updatedAt user { id name displayName } }
|
|
146
148
|
}
|
|
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
|
|
149
|
+
`);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 Q(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await R(`
|
|
148
150
|
mutation AddComment($input: CommentCreateInput!) {
|
|
149
151
|
commentCreate(input: $input) {
|
|
150
152
|
success
|
|
151
153
|
comment { id url createdAt }
|
|
152
154
|
}
|
|
153
155
|
}
|
|
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
|
|
156
|
+
`,{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 Q(e,`
|
|
155
157
|
id identifier
|
|
156
158
|
state { id name type }
|
|
157
159
|
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=
|
|
160
|
+
`);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=fr(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 R(`
|
|
159
161
|
mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
|
|
160
162
|
issueUpdate(id: $id, input: $input) {
|
|
161
163
|
success
|
|
162
164
|
issue { id identifier state { id name type } }
|
|
163
165
|
}
|
|
164
166
|
}
|
|
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
|
|
167
|
+
`,{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 Q(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await R(`
|
|
166
168
|
mutation LinkAttachment($input: AttachmentCreateInput!) {
|
|
167
169
|
attachmentCreate(input: $input) {
|
|
168
170
|
success
|
|
169
171
|
attachment { id url title }
|
|
170
172
|
}
|
|
171
173
|
}
|
|
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
|
|
174
|
+
`,{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 Xe(n){return(await R(`
|
|
173
175
|
query TeamByKey($filter: TeamFilter) {
|
|
174
176
|
teams(first: 1, filter: $filter) { nodes { id key } }
|
|
175
177
|
}
|
|
176
|
-
`,{filter:{key:{eq:n}}}))?.teams?.nodes?.[0]?.id||null}async function
|
|
178
|
+
`,{filter:{key:{eq:n}}}))?.teams?.nodes?.[0]?.id||null}async function Q(n,r=gr){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 R(`
|
|
177
179
|
query IssueByIdentifier($filter: IssueFilter) {
|
|
178
180
|
issues(first: 1, filter: $filter) {
|
|
179
181
|
nodes { ${r} }
|
|
180
182
|
}
|
|
181
183
|
}
|
|
182
|
-
`,{filter:{number:{eq:o},team:{key:{eq:s}}}}))?.issues?.nodes?.[0]||null}return(await
|
|
184
|
+
`,{filter:{number:{eq:o},team:{key:{eq:s}}}}))?.issues?.nodes?.[0]||null}return(await R(`
|
|
183
185
|
query IssueById($id: String!) {
|
|
184
186
|
issue(id: $id) { ${r} }
|
|
185
187
|
}
|
|
186
|
-
`,{id:e}))?.issue||null}var
|
|
188
|
+
`,{id:e}))?.issue||null}var yr={triage:"todo",backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",canceled:"done"},hr=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function Se(n){return n?n.name&&hr.test(n.name)?"blocked":yr[n.type]||"unknown":"unknown"}function Z(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function ke(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:Se(r?{name:r,type:e}:null),assignee:n.assignee||null,url:n.url||null,_raw:n}}var Ae={id:"linear",toStateCategory:Se,toNeutral:ke,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(Z(await C.handleToolCall("linear_list_issues",e)).issues||[]).map(ke)},async getTicket(n){if(!n)throw new Error("key is required");let r=JSON.parse(await C.handleToolCall("linear_get_issue",{identifier:n}));return r.error?null:ke(r)},async getComments(n){if(!n)throw new Error("key is required");return(Z(await C.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=Z(await C.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 C.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:Se(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(Z(await C.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:!!Z(await C.handleToolCall("linear_add_comment",{identifier:n,body:i})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as $r}from"fs";import{fileURLToPath as vr}from"url";import{dirname as Tr,resolve as Nr}from"path";import{resolveIntegrationToken as ut}from"@zibby/core/backend-client.js";var br="REPO_ALLOWLIST",Ie="REPO_NOT_SELECTED",Re=Object.freeze(["github","gitlab"]),_r=Object.freeze({github:"GitHub",gitlab:"GitLab"});function $e(n){return String(n??"").trim().replace(/^\/+|\/+$/g,"").replace(/\.git$/i,"").replace(/\/+$/g,"").toLowerCase()}function z(n=process.env){let r=n?n[br]:void 0;if(r==null||String(r).trim()==="")return null;let e={github:new Set,gitlab:new Set,unreadable:!1},t;try{t=JSON.parse(String(r))}catch{return e.unreadable=!0,e}if(!t||typeof t!="object"||Array.isArray(t))return e.unreadable=!0,e;for(let i of Re){let s=t[i];if(Array.isArray(s))for(let o of s){let a=$e(o);a&&e[i].add(a)}}return e}function ve(n=process.env){return z(n)!==null}function Te(n,r,e){let t=_r[n]||n,i=e&&e[n]?[...e[n]].sort():[],s=String(r||"").trim()||"(unnamed repository)",o=i.length?`The ${t} repositories selected for this project are: ${i.join(", ")}.`:`This project has no ${t} repositories selected.`;return{error:`The ${t} repository "${s}" is not selected for this project, so this project's agents cannot use it. ${o} A project owner can change this in Project Settings \u2192 Repository access.`,code:Ie,provider:n,repo:s,allowedRepos:i,fix:i.length?"Work only with the selected repositories listed in allowedRepos. If the task needs this one, tell the person it has to be selected in Project Settings first. Do not retry the same repository under another spelling or id.":"Tell the person this project has no repositories selected, and that one has to be selected in Project Settings \u2192 Repository access before agents can use it. Do not retry."}}var X=class extends Error{constructor(r){super(r.error),this.name="RepoNotSelectedError",this.code=Ie,this.refusal=r}};function Ne(n){return!!(n&&n.code===Ie&&n.refusal)}function wr(n,r,e=process.env){let t=z(e);if(!t)return{allowed:!0};if(!Re.includes(n))return{allowed:!0};let i=$e(r);return i&&t[n].has(i)?{allowed:!0}:{allowed:!1,refusal:Te(n,r,t)}}function Oe(n,r,e=process.env){let t=wr(n,r,e);if(!t.allowed)throw new X(t.refusal)}function et(n,r,e,t=process.env){if(!Array.isArray(r))return r;let i=z(t);return!i||!Re.includes(n)?r:r.filter(s=>{let o=e(s);return o==null||o===""?!0:i[n].has($e(o))})}function tt(n,r=process.env){let e=z(r);return e?e[n]?[...e[n]].sort():[]:null}import{spawn as _n,execSync as wn}from"child_process";import{existsSync as Sn,mkdirSync as An,readdirSync as In,statSync as Rn,readFileSync as $n}from"fs";import{resolve as Tn,join as Nn,basename as On}from"path";async function kr(n){try{let r=await import("@zibby/agent-workflow");return typeof r.collectRepositoryRules!="function"||typeof r.renderRepositoryRules!="function"?"":r.renderRepositoryRules(r.collectRepositoryRules([{dir:n,declared:!0}]))||""}catch{return""}}async function Ee(n){let r=await kr(n);return r?{repositoryRules:r}:{}}function rt(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 Sr from"crypto";var nt=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,st=/<!--\s*zbreview-summary\s*-->/i;function Ar(n){return String(n||"").replace(nt,"").replace(st,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Ir(n,r){return Sr.createHash("sha256").update(`${String(n||"")}\0${Ar(r)}`).digest("hex").slice(0,12)}function Rr(n){return`
|
|
187
189
|
|
|
188
|
-
<!-- zbfp:${n} -->`}var
|
|
190
|
+
<!-- zbfp:${n} -->`}var it=`
|
|
189
191
|
|
|
190
|
-
<!-- zbreview-summary -->`;function
|
|
192
|
+
<!-- zbreview-summary -->`;function ot(n){let r=nt.exec(String(n||""));return r?r[1].toLowerCase():null}function at(n){return st.test(String(n||""))}function ct(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=Ir(s.path,s.body);if(e.has(o)){i+=1;continue}e.add(o),t.push({...s,_fp:o,body:`${String(s.body)}${Rr(o)}`})}return{toPost:t,skipped:i}}function Or(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Tr(vr(import.meta.url)),r=Nr(n,"..","bin","mcp-skill.mjs");return $r(r)?r:null}function lt(n){let r=String(n||"");if(/^https?:\/\//i.test(r))try{let t=new URL(r),i=t.hostname.toLowerCase();if(i!=="api.github.com"&&i!=="uploads.github.com")return{kind:"other"};r=t.pathname}catch{return{kind:"opaque"}}r=r.split("?")[0];let e=r.match(/^\/repos\/([^/]+)\/([^/]+)/);return e?{kind:"repo",repo:`${decodeURIComponent(e[1])}/${decodeURIComponent(e[2])}`}:/^\/(repositories|graphql)(\/|$)/.test(r)?{kind:"opaque"}:{kind:"other"}}function Er(n){if(!n||typeof n!="object")return null;if(typeof n.full_name=="string"&&n.full_name.includes("/"))return n.full_name;if(n.repository&&typeof n.repository.full_name=="string")return n.repository.full_name;if(typeof n.repository_url=="string"){let r=n.repository_url.match(/\/repos\/([^/]+\/[^/?#]+)/);if(r)return r[1]}return null}function jr(n){let r=t=>et("github",t,Er);if(Array.isArray(n))return r(n);if(!n||typeof n!="object")return n;let e=n;for(let t of["items","repositories"])if(Array.isArray(e[t])){let i=r(e[t]);i.length!==e[t].length&&(e={...e,[t]:i},typeof e.total_count=="number"&&(e.total_count=i.length))}return e}async function _(n,r={}){if(ve()){let a=lt(n);if(a.kind==="repo")Oe("github",a.repo);else if(a.kind==="opaque"){let c=Te("github",String(n).split("?")[0],z());throw c.error="This GitHub request cannot be matched to one of this project's selected repositories, so it is not allowed. Address the repository by owner/name instead. "+c.error,new X(c)}}let{token:e}=await ut("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 j(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 a=await s.text().catch(()=>""),c=new Error(`GitHub API ${s.status}: ${a.slice(0,300)}`);throw c.status=s.status,c}if(r.raw)return s.text();let o=await s.json();return ve()&<(n).kind==="other"?jr(o):o}var $={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:B.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","REPO_ALLOWLIST"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
|
|
191
193
|
You have access to the user's GitHub repositories. Available tools:
|
|
192
194
|
|
|
193
195
|
### Discovery
|
|
@@ -230,6 +232,6 @@ When user says "check out repo-name" or "clone repo-name":
|
|
|
230
232
|
3. STOP. Do not offer to inspect files or ask what to do next.
|
|
231
233
|
|
|
232
234
|
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=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(`
|
|
235
|
+
- Use github_get_file to read individual files via API`,resolve(){let n=Or();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(f=>f&&f.path&&f.body&&(f.line!=null||f.position!=null)).map(f=>{let w={path:f.path,body:String(f.body)};return f.line!=null?(w.line=Number(f.line),w.side=f.side==="LEFT"?"LEFT":"RIGHT"):w.position=Number(f.position),w}):[];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 f=1;f<=20;f+=1){let w=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100&page=${f}`);if(!Array.isArray(w)||w.length===0)break;for(let y of w){let A=ot(y.body);A&&l.add(A)}if(w.length<100)break}for(let f=1;f<=20&&p==null;f+=1){let w=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=100&page=${f}`);if(!Array.isArray(w)||w.length===0)break;for(let y of w)if(at(y.body)){p=y.id;break}if(w.length<100)break}}catch{}let m=!1,g=!1;if(s){let f=`${String(s)}${it}`;try{p!=null?(await _(`/repos/${e}/${t}/issues/comments/${p}`,{method:"PATCH",body:{body:f}}),m=!0):await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:f}}),g=!0}catch{}}let{toPost:d,skipped:b}=ct(u,l),h=d.map(({_fp:f,...w})=>w),S=null;if(h.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let f={event:c};h.length>0&&(f.comments=h),h.length===0&&c==="REQUEST_CHANGES"&&(f.body="Changes requested \u2014 see the review summary comment."),S=await _(`/repos/${e}/${t}/pulls/${i}/reviews`,{method:"POST",body:f})}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(f){let w=f.replace(/^~(?=$|\/|\\)/,g);return a(w)},{owner:e,repo:t,destination:i}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});Oe("github",`${e}/${t}`);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 ut("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 f=`https://github.com/${e}/${t}.git`;rt(s,h,f,m,"github_clone");let w=p()==="win32",y;return w?y=s(`dir "${h}"`,{encoding:"utf-8",shell:"cmd.exe"}):y=s(`ls -la "${h}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:h,message:`Cloned ${e}/${t} to ${h}`,contents:y.split(`
|
|
234
236
|
`).slice(0,30).join(`
|
|
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};
|
|
237
|
+
`),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing.",...await Ee(h)})}catch(f){let y=String(f.message||f).split(m).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${y}`})}}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=y=>({name:y.name,fullName:y.full_name,private:y.private,description:y.description,language:y.language,defaultBranch:y.default_branch,updatedAt:y.updated_at,stars:y.stargazers_count,url:y.html_url,fullPath:y.full_name,webUrl:y.html_url,visibility:y.visibility||(y.private?"private":"public")}),m=y=>{if(!a)return!0;let A=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(A)||y.fullName&&y.fullName.toLowerCase().includes(A)||y.description&&y.description.toLowerCase().includes(A)},g=tt("github");if(g){let y=e?String(e).toLowerCase():null,A=[];for(let O of g)if(!(y&&O.split("/")[0]!==y))try{A.push(p(await _(`/repos/${O}`)))}catch(N){A.push({name:O.split("/")[1],fullName:O,fullPath:O,error:`could not read: ${N?.status||N?.message||N}`})}let T=A.filter(m).slice(0,u);return JSON.stringify({count:T.length,repos:T,truncated:!1,message:`This project can use ${g.length} selected GitHub repositor${g.length===1?"y":"ies"}.`})}if(!e){let y=1,A=!0,T=!1;for(;A&&l.length<u;){let E=`/installation/repositories?per_page=${c}&page=${y}`,K;try{K=await _(E)}catch(oe){if((oe?.status===401||oe?.status===403)&&y===1){T=!0;break}throw oe}let ie=K.repositories||[];if(ie.length===0)break;l=l.concat(ie),A=ie.length===c,y++}if(T)for(y=1,A=!0;A&&l.length<u;){let E=await _(`/user/repos?per_page=${c}&page=${y}&affiliation=owner,collaborator,organization_member&sort=${i||"updated"}&direction=${s||"desc"}`),K=Array.isArray(E)?E:[];if(K.length===0)break;l=l.concat(K),A=K.length===c,y++}let O=l.map(p).filter(m),N=O.slice(0,u),kt=O.length>N.length,qe=N.filter(E=>E.private).length,Ue=N.filter(E=>!E.private).length;return JSON.stringify({count:N.length,repos:N,truncated:kt,privateCount:qe,publicCount:Ue,message:`Found ${qe} private and ${Ue} public repos`})}let d=await _(`/orgs/${e}`).then(()=>!0).catch(()=>!1),b=1,h=!0;for(;h&&l.length<u;){let y;d?y=`/orgs/${e}/repos?per_page=${c}&page=${b}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:y=`/users/${e}/repos?per_page=${c}&page=${b}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let A=await _(y),T=Array.isArray(A)?A:[];if(T.length===0)break;l=l.concat(T),h=T.length===c,b++}let S=l.map(p).filter(m),f=S.slice(0,u),w=S.length>f.length;return JSON.stringify({count:f.length,repos:f,truncated:w})}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 Ne(e)?JSON.stringify(e.refusal):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 ft=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,gt=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,Lr=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,xr=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,pt="in progress",dt="blocked";function yt(n,r=[]){if(n==="closed")return"done";if(n!=="open")return"unknown";let e=(r||[]).map(String);return e.some(t=>ft.test(t))?"blocked":e.some(t=>gt.test(t))?"in_progress":"todo"}function W(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 P(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function je(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:yt(n.state,e),assignee:n.assignee||n.assignees&&n.assignees[0]||null,url:n.url||null,_raw:n}}var Le={id:"github",toStateCategory:yt,toNeutral:je,IN_PROGRESS_LABEL:pt,BLOCKED_LABEL:dt,async listCandidates(n={}){let r=n.ctx||{},{owner:e,repo:t}=W(r);return(P(await $.handleToolCall("github_list_issues",{owner:e,repo:t,state:n.state||"open",labels:n.labels,since:n.updatedAfter,limit:n.limit})).issues||[]).map(s=>je(s,{owner:e,repo:t}))},async getTicket(n,r={}){let{owner:e,repo:t}=W(r),i=ee(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let s=JSON.parse(await $.handleToolCall("github_get_issue",{owner:e,repo:t,number:i}));return s.error?null:je(s,{owner:e,repo:t})},async getComments(n,r={}){let{owner:e,repo:t}=W(r),i=ee(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);return(P(await $.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}=W(e),s=ee(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("body is required");let o=P(await $.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}=W(e),s=ee(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let o=String(r||"");if(Lr.test(o)){let a=P(await $.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(ft.test(o)){await mt(t,i,s);let a=P(await $.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[dt],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:a}}if(gt.test(o)){await mt(t,i,s);let a=P(await $.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[pt],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:a}}if(xr.test(o)){let a=P(await $.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}=W(t),o=ee(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:!!P(await $.handleToolCall("github_add_issue_comment",{owner:i,repo:s,number:o,body:a})).ok,via:"comment"}}};async function mt(n,r,e){await $.handleToolCall("github_reopen_issue",{owner:n,repo:r,number:e})}function ee(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(/\/+$/,""),Pr=process.env.PLANE_WORKSPACE_SLUG||"",qr=process.env.PLANE_PROJECT_ID||"";function Ur(){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 M(n={}){let r=n.workspaceSlug||Pr,e=n.projectId||qr;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 G(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 j(e,{method:r.method||"GET",headers:{"X-API-Key":Ur(),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 Jr={backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",cancelled:"done"},Gr=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function Ce(n){return n?n.name&&Gr.test(n.name)?"blocked":Jr[n.group]||"unknown":"unknown"}var ht=new Map,Mr=300*1e3;async function _t(n){let{workspaceSlug:r,projectId:e}=M(n),t=ht.get(e);if(t&&Date.now()-t.fetchedAt<Mr)return t.states;let i=await G(`/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 ht.set(e,{fetchedAt:Date.now(),states:s}),s}function xe(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Kr(n,r){let e=xe(r);if(!e)return null;let t=n.find(s=>xe(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=>xe(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 bt(n,r){let t=(await _t(r).catch(()=>[])).find(c=>c.id===n.state)||null,{workspaceSlug:i,projectId:s}=M(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:Ce(t),assignee:a.length?String(a[0]):null,url:r.baseWebUrl?`${r.baseWebUrl}/${i}/projects/${s}/issues/${n.id}`:null,_raw:n}}var Pe={id:"plane",envKeys:["PLANE_API_KEY","PLANE_OAUTH_TOKEN","PLANE_API_URL","PLANE_WORKSPACE_SLUG","PLANE_PROJECT_ID"],planeFetch:G,toStateCategory:Ce,async listCandidates(n={}){let r=n.ctx||{},{workspaceSlug:e,projectId:t}=M(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 G(`/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=>bt(a,r)))},async getTicket(n,r={}){let{workspaceSlug:e,projectId:t}=M(r),i=await G(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/`);return!i||!i.id?null:bt(i,r)},async getComments(n,r={}){let{workspaceSlug:e,projectId:t}=M(r);return((await G(`/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}=M(e),o=/<[a-z][\s\S]*>/i.test(String(r||""))?String(r):`<p>${String(r||"")}</p>`,a=await G(`/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}=M(e),s=await _t(e),o=Kr(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 G(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/`,{method:"PATCH",body:{state:o.id}});return{ok:!!a.id,stateAfter:o.name,stateCategoryAfter:Ce(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 Br=["todo","in_progress","done","blocked","unknown"];var wt={jira:we,linear:Ae,github:Le,plane:Pe},Dr="jira";function rs(n){let r=String(n||process.env.TRACKER_PROVIDER||Dr).trim().toLowerCase(),e=wt[r];if(!e){let t=Object.keys(wt).join(", ");throw new Error(`Unknown tracker provider "${r}". Known providers: ${t}.`)}return e}export{Dr as DEFAULT_TRACKER_PROVIDER,wt as TRACKER_ADAPTERS,Br as TRACKER_STATE_CATEGORIES,rs as getAdapter,Le as githubAdapter,we as jiraAdapter,Ae as linearAdapter,Pe as planeAdapter};
|