@zibby/skills 2.0.4 → 2.0.6

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.
Files changed (55) hide show
  1. package/dist/artifact.js +7 -7
  2. package/dist/chat-notify.js +4 -4
  3. package/dist/chatProgress.js +4 -4
  4. package/dist/datasetStore.js +2 -2
  5. package/dist/discord.js +3 -3
  6. package/dist/figma.js +2 -2
  7. package/dist/git-write.js +9 -9
  8. package/dist/github.js +5 -5
  9. package/dist/gitlab.js +5 -5
  10. package/dist/googleDocs.js +9 -9
  11. package/dist/hubspot.js +1 -1
  12. package/dist/index.js +179 -181
  13. package/dist/jira.d.ts +36 -1
  14. package/dist/jira.js +22 -20
  15. package/dist/kvMemory.js +2 -2
  16. package/dist/lark.js +2 -2
  17. package/dist/larkAttendance.js +1 -1
  18. package/dist/larkDocs.js +3 -3
  19. package/dist/lib/http-deadline.d.ts +117 -0
  20. package/dist/lib/http-deadline.js +1 -0
  21. package/dist/lib/markup.d.ts +158 -0
  22. package/dist/lib/markup.js +22 -0
  23. package/dist/linear.js +15 -15
  24. package/dist/linkedin.js +2 -2
  25. package/dist/llm-billing.js +1 -1
  26. package/dist/notion.js +7 -7
  27. package/dist/opendesign.js +2 -2
  28. package/dist/package.json +6 -5
  29. package/dist/report.d.ts +42 -42
  30. package/dist/review.js +4 -4
  31. package/dist/reviewMemoryIo.js +1 -1
  32. package/dist/sentry.js +2 -2
  33. package/dist/skill-installer.js +3 -3
  34. package/dist/slack.js +2 -2
  35. package/dist/trackers/github-adapter.js +5 -5
  36. package/dist/trackers/index.js +46 -44
  37. package/dist/trackers/jira-adapter.js +24 -22
  38. package/dist/trackers/linear-adapter.js +19 -19
  39. package/dist/trackers/plane-adapter.js +1 -1
  40. package/dist/triggerAgent.js +1 -1
  41. package/dist/vikunja.d.ts +8 -1
  42. package/dist/vikunja.js +22 -7
  43. package/docs/templates/catalog-metadata.md +101 -0
  44. package/docs/templates/composition.md +97 -0
  45. package/docs/templates/deploy-time-config.md +228 -0
  46. package/docs/templates/index.md +138 -0
  47. package/docs/templates/models.md +157 -0
  48. package/docs/templates/node-declarations.md +149 -0
  49. package/docs/templates/remote-mcp.md +105 -0
  50. package/docs/templates/requires.md +183 -0
  51. package/docs/templates/sidecars.md +163 -0
  52. package/docs/templates/stores.md +113 -0
  53. package/docs/templates/surfaces.md +184 -0
  54. package/docs/templates/update-behavior.md +108 -0
  55. package/package.json +6 -5
@@ -1,22 +1,24 @@
1
- import{createRequire as Oe}from"module";import{resolveIntegrationToken as je,clearTokenCache as Te}from"@zibby/core/backend-client.js";var T=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"}),Rt=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 Ee=Oe(import.meta.url);function Ce(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Ee.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var Pe=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function Le(r,s){if(!s||!s.length)return r;let e=r;for(let t of s)t.type==="strong"?e=`**${e}**`:t.type==="em"?e=`_${e}_`:t.type==="code"?e=`\`${e}\``:t.type==="strike"?e=`~~${e}~~`:t.type==="link"&&t.attrs?.href&&(e=`[${e}](${t.attrs.href})`);return e}function K(r,s=0){if(!Array.isArray(r))return"";let e=[];for(let t of r){if(t.type==="text"){e.push(Le(t.text||"",t.marks));continue}if(t.type==="hardBreak"){e.push(`
2
- `);continue}if(t.type==="rule"){e.push(`
3
- ---
4
- `);continue}let n=t.content?K(t.content,s+1):"";if(t.type==="listItem")e.push(n);else if(t.type==="bulletList"){let i=(t.content||[]).map(o=>`- ${K(o.content||[],s+1).trim()}`);e.push(`
5
- ${i.join(`
6
- `)}
7
- `)}else if(t.type==="orderedList"){let i=(t.content||[]).map((o,a)=>`${a+1}. ${K(o.content||[],s+1).trim()}`);e.push(`
8
- ${i.join(`
9
- `)}
10
- `)}else if(t.type==="heading"){let i=t.attrs?.level||2;e.push(`
11
-
12
- ${"#".repeat(i)} ${n.trim()}
13
-
14
- `)}else Pe.has(t.type)?e.push(`
15
-
16
- ${n}
17
- `):e.push(n)}return e.join("").replace(/\n{3,}/g,`
18
-
19
- `)}function E(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function H(r){return E(r).replace(/[a-z0-9]+/g,"")}function M(r,s){let e=E(r),t=E(s);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let n=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},i=n(e),o=n(t),a=0,c=0,u=0;for(let l of i.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of i.entries()){let m=o.get(l)||0;a+=Math.min(p,m)}return 2*a/Math.max(1,c+u)}function v(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function qe(r,s=[]){let e=Array.isArray(s)?s:[];if(e.length===0)return{requested:r||null,resolved:null,strategy:"none"};let t=e.filter(a=>!a.subtask),n=t.length>0?t:e,i=v(r);if(i){let a=n.find(l=>v(l.name)===i);if(a)return{requested:r,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=>v(m)===i))continue;let p=n.find(m=>l.some(g=>v(g)===v(m.name)));if(p)return{requested:r,resolved:p,strategy:"alias"}}let u=n.map(l=>({t:l,score:M(r,l.name)})).sort((l,p)=>p.score-l.score);if(u[0]&&u[0].score>=.5)return{requested:r,resolved:u[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=n.find(u=>v(u.name)===a);if(c)return{requested:r||null,resolved:c,strategy:"default-preferred"}}return{requested:r||null,resolved:n[0],strategy:"default-first"}}async function ae(r){let s=`projectKeys=${encodeURIComponent(r)}&expand=projects.issuetypes`,e=await w(`/rest/api/3/issue/createmeta?${s}`),t=Array.isArray(e?.projects)?e.projects:[],i=t.find(a=>String(a?.key||"").toUpperCase()===String(r||"").toUpperCase())||t[0]||null;return(Array.isArray(i?.issuetypes)?i.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function ce(r,s){if(!r)throw new Error("projectKey is required");let e="sprint is not EMPTY";s==="active"?e="sprint in openSprints()":s==="closed"?e="sprint in closedSprints()":s==="future"&&(e="sprint in futureSprints()");let t=`project = ${r} AND ${e} ORDER BY updated DESC`,n=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,i=await w(`/rest/api/3/search/jql?${n}`),o=new Map;for(let a of i.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 Je(r,{sprintId:s,sprintName:e,target:t}={}){let n=Array.isArray(r)?r:[];if(!n.length)return{sprint:null,selectedBy:"none"};if(s!=null&&String(s).trim()!=="")return{sprint:n.find(a=>String(a.id)===String(s))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=n.find(u=>String(u.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=n.map(u=>({s:u,score:M(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 i=String(t||"current").trim().toLowerCase();return i==="active"||i==="current"||i==="latest"?{sprint:n[0],selectedBy:i}:{sprint:n[0],selectedBy:"default"}}function xe(r,s){let e=r?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(s)):!1}async function Ue({issueKey:r,projectKey:s,sprintId:e,attempts:t=3,delayMs:n=450}){let i=[];for(let o=0;o<t;o++){try{let a=`project = ${s} AND key = ${r} 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 i.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let p=await w(`/rest/api/3/issue/${r}?fields=customfield_10020,status`),m=xe(p,e);if(i.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:i}}catch(a){i.push({attempt:o+1,error:String(a?.message||a)})}o<t-1&&await new Promise(a=>setTimeout(a,n))}return{ok:!1,method:"none",traces:i}}async function B({issueKey:r,projectKey:s,sprintId:e,sprintName:t,target:n}){if(!r)return{ok:!1,error:"issueKey is required"};let i=s;if(!i&&(i=(await w(`/rest/api/3/issue/${r}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${r}`};let o=await ce(i,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:a,selectedBy:c}=Je(o,{sprintId:e,sprintName:t,target:n});if(!a)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:e??null,sprintName:t??null,target:n??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await w(`/rest/api/3/issue/${r}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let u=await Ue({issueKey:r,projectKey:i,sprintId:a.id}),l=u.ok;return{ok:l,issueKey:r,projectKey:i,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 ${r} in sprint ${a.id}`}}async function Ge(){let r=process.env.JIRA_API_TOKEN,s=process.env.JIRA_EMAIL,e=process.env.JIRA_BASE_URL;if(r&&s&&e)return{authType:"token",apiToken:r,email:s,baseUrl:e};let t=await je("jira");return t?.cloudId?{authType:"oauth",accessToken:t.token,cloudId:t.cloudId}:{authType:"token",apiToken:t?.token,email:s||t?.email||"",baseUrl:e||t?.instanceUrl||t?.baseUrl||process.env.ATLASSIAN_INSTANCE_URL||""}}function Ke(r,s,e={}){let t=r||{},n={Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers};if(t.authType==="token"){let i=String(t.baseUrl||t.instanceUrl||"").trim().replace(/\/+$/,""),o=t.apiToken||t.accessToken||"";if(!i)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:`${i}${s}`,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${o}`).toString("base64"),...n}}}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}${s}`,headers:{Authorization:`Bearer ${t.accessToken}`,...n}}}async function w(r,s={}){let e=async()=>{let t=await Ge(),{url:n,headers:i}=Ke(t,r,s),o=await fetch(n,{method:s.method||"GET",headers:i,body:s.body?JSON.stringify(s.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let a=await o.text().catch(()=>"");if(!a||!a.trim())return{};try{return JSON.parse(a)}catch{return{raw:a}}};try{return await e()}catch(t){let n=String(t?.message||t||"").toLowerCase();if(!(n.includes("token")||n.includes("401")||n.includes("403")||n.includes("substring")))throw t;return Te("jira"),e()}}var q={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:T.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
1
+ import{createRequire as vt}from"module";import{resolveIntegrationToken as Rt,clearTokenCache as $t}from"@zibby/core/backend-client.js";var q=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"}),_r=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 Q={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 it(n="api",r=process.env){let e=Q[n]||Q.api;return st(e.knob,e.fallback,r)}function te(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function ot(n){try{return new URL(String(n?.url??n)).host||"unknown host"}catch{return"unknown host"}}function at(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 N(n,r={},e={}){let t=e.kind||"api",i=(Q[t]||Q.api).knob,s=e.timeoutMs?Math.min(6e5,Math.max(1e3,Math.floor(e.timeoutMs))):it(t),o=r?.signal;if(o?.aborted)throw o.reason??new DOMException("This operation was aborted","AbortError");let a=AbortSignal.timeout(s),c=at(o,a);try{return await fetch(n,{...r,signal:c})}catch(u){throw a.aborted&&te(u)?new Error(`${e.what||"request"} TIMED OUT after ${s}ms against ${ot(n)} (${i})`):u}}var ct={NOTE:"info",TIP:"success",IMPORTANT:"note",WARNING:"warning",CAUTION:"error"},je={info:"NOTE",success:"TIP",note:"IMPORTANT",warning:"WARNING",error:"CAUTION"},lt=2e5,xe=6,ut=/^```([A-Za-z0-9_+.-]{0,32})\s*$/,pt=/^(#{1,6})[ \t]+(.*?)\s*$/,dt=/^(?:-{3,}|\*{3,}|_{3,})\s*$/,ve=/^>(?: ?(.*))?$/,re=/^[-*][ \t]+\[([ xX])\][ \t]+(.*)$/,Re=/^[-*][ \t]+(.*)$/,$e=/^(\d{1,3})[.)][ \t]+(.*)$/,Ne=/^\|.*\|\s*$/,mt=/^\|?\s*:?-{1,}:?\s*(?:\|\s*:?-{1,}:?\s*)*\|?\s*$/,ft=/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i;function Te(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 Ce(n){let e=String(n??"").slice(0,lt).replace(/\r\n?/g,`
2
+ `).split(`
3
+ `);return se(e,0)}function se(n,r){let e=[],t=0;for(;t<n.length;){let i=n[t];if(i.trim()===""){t++;continue}if(/^[ \t]/.test(i)){e.push({t:"paragraph",c:A(i)}),t++;continue}let s;if(s=ut.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(dt.test(i)){e.push({t:"rule"}),t++;continue}if(s=pt.exec(i)){let o=Math.min(xe,s[1].length);e.push({t:"heading",level:o,c:A(s[2])}),t++;continue}if(ve.test(i)&&r<3){let o=[];for(;t<n.length&&(s=ve.exec(n[t]));)o.push(s[1]??""),t++;let a=o.findIndex(u=>u.trim()!==""),c=a>=0?ft.exec(o[a].trim()):null;if(c){let u=ct[c[1].toUpperCase()];e.push({t:"panel",kind:u,c:se(o.slice(a+1),r+1)})}else e.push({t:"quote",c:se(o,r+1)});continue}if(re.test(i)){let o=[];for(;t<n.length&&(s=re.exec(n[t]));)o.push({checked:s[1]!==" ",c:A(s[2])}),t++;e.push({t:"task",items:o});continue}if(Re.test(i)){let o=[];for(;t<n.length&&!re.test(n[t])&&(s=Re.exec(n[t]));)o.push([{t:"paragraph",c:A(s[1])}]),t++;e.push({t:"bullet",items:o});continue}if(s=$e.exec(i)){let o=Math.max(1,parseInt(s[1],10)||1),a=[];for(;t<n.length&&(s=$e.exec(n[t]));)a.push([{t:"paragraph",c:A(s[2])}]),t++;e.push({t:"ordered",start:o,items:a});continue}if(Ne.test(i)&&t+1<n.length&&mt.test(n[t+1])){let o=Te(i).map(A);t+=2;let a=[];for(;t<n.length&&Ne.test(n[t]);)a.push(Te(n[t]).map(A)),t++;e.push({t:"table",header:o,rows:a});continue}e.push({t:"paragraph",c:A(i)}),t++}return e}var yt=/^https?:\/\/[^\s<>()[\]]+/,gt=/^\[([^\]\n]{1,300})\]\((https?:\/\/[^\s)]{1,2000})\)/,ht=/[.,;:!?'"]+$/;function bt(n,r){return r<=0?!0:/[\s([{"'“‘>:—–-]/.test(n[r-1])}function _t(n,r){return r>=n.length?!0:/[\s)\]}"'”’.,;:!?—–-]/.test(n[r])}function wt(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&&_t(n,i+e.length))return i;t=i+1}return-1}function A(n){let r=String(n??""),e=[],t="",i=()=>{t&&(e.push({t:"text",v:t}),t="")},s=0;for(;s<r.length;){let o=r[s];if(o==="`"){let a=1;for(;r[s+a]==="`";)a++;let c="`".repeat(a),u=r.indexOf(c,s+a);if(u>s+a-1&&u!==-1){let l=r.slice(s+a,u);if(l.trim()){i(),e.push({t:"code",v:l.length>1&&l.startsWith(" ")&&l.endsWith(" ")?l.slice(1,-1):l}),s=u+a;continue}}t+=c,s+=a;continue}if(o==="["){let a=gt.exec(r.slice(s));if(a){i(),e.push({t:"link",href:a[2],c:A(a[1])}),s+=a[0].length;continue}}if((o==="*"||o==="_"||o==="~")&&bt(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=wt(r,u,c);if(l>u){i();let p=A(r.slice(u,l));e.push(o==="~"?{t:"strike",c:p}:a?{t:"strong",c:p}:{t:"em",c:p}),s=l+c.length;continue}}}if(o==="h"&&(s===0||/[\s(<]/.test(r[s-1]))){let a=yt.exec(r.slice(s));if(a){let c=a[0],u=ht.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 C(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(...C(t.c,V(r,{type:"strong"})));break;case"em":e.push(...C(t.c,V(r,{type:"em"})));break;case"strike":e.push(...C(t.c,V(r,{type:"strike"})));break;case"link":e.push(...C(t.c,V(r,{type:"link",attrs:{href:t.href}})));break}return e}function V(n,r){return n.some(e=>e.type===r.type)?n:[...n,r]}var ne=0;function Oe(){return ne=(ne+1)%1e6,`m${Date.now().toString(36)}-${ne}`}var J=n=>{let r=C(n);return r.length?{type:"paragraph",content:r}:{type:"paragraph"}};function x(n,r){let e=[];for(let t of n)switch(t.t){case"paragraph":e.push(J(t.c));break;case"heading":if(r==="quote"||r==="item")e.push(J([{t:"strong",c:t.c}]));else{let i=C(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:Z(x(i,"item"))}))});break;case"ordered":e.push({type:"orderedList",attrs:{order:t.start},content:t.items.map(i=>({type:"listItem",content:Z(x(i,"item"))}))});break;case"task":r==="quote"||r==="item"?e.push({type:"bulletList",content:t.items.map(i=>({type:"listItem",content:[J([{t:"text",v:i.checked?"\u2611 ":"\u2610 "},...i.c])]}))}):e.push({type:"taskList",attrs:{localId:Oe()},content:t.items.map(i=>({type:"taskItem",attrs:{localId:Oe(),state:i.checked?"DONE":"TODO"},content:kt(C(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(...x(t.c,r)):e.push({type:"blockquote",content:Z(x(t.c,"quote"))});break;case"panel":r!=="doc"?e.push(...x(t.c,r)):e.push({type:"panel",attrs:{panelType:t.kind},content:Z(x(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(J(St(s)));break}let i=[];t.header&&i.push({type:"tableRow",content:t.header.map(s=>({type:"tableHeader",attrs:{},content:[J(s)]}))});for(let s of t.rows)i.push({type:"tableRow",content:s.map(o=>({type:"tableCell",attrs:{},content:[J(o)]}))});i.length&&e.push({type:"table",attrs:{isNumberColumnEnabled:!1,layout:"default"},content:i});break}}return e}function Z(n){return n.length?n:[{type:"paragraph"}]}function kt(n){return n.length?n:[{type:"text",text:" "}]}function St(n){let r=[];return n.forEach((e,t)=>{t&&r.push({t:"text",v:" \xB7 "}),r.push(...e)}),r}function ie(n){return{type:"doc",version:1,content:String(n??"").split(`
5
+ `).map(r=>({type:"paragraph",...r?{content:[{type:"text",text:r}]}:{}}))}}function Le(n){try{let r=x(Ce(n),"doc");return{type:"doc",version:1,content:r.length?r:[{type:"paragraph"}]}}catch{return ie(n)}}function T(n){let r="";for(let e of n)switch(e.t){case"text":r+=e.v;break;case"br":r+=`
6
+ `;break;case"code":r+=`\`${e.v}\``;break;case"strong":r+=`**${T(e.c)}**`;break;case"em":r+=`_${T(e.c)}_`;break;case"strike":r+=`~~${T(e.c)}~~`;break;case"link":{let t=T(e.c);r+=!t||t===e.href?e.href:`[${t}](${e.href})`;break}}return r}function M(n){let r="";for(let e of n)switch(e.t){case"paragraph":r+=`${T(e.c)}
7
+ `;break;case"heading":r+=`${"#".repeat(Math.max(1,Math.min(xe,e.level)))} ${T(e.c)}
8
+ `;break;case"bullet":for(let t of e.items)r+=`- ${M(t).trim()}
9
+ `;break;case"ordered":e.items.forEach((t,i)=>{r+=`${e.start+i}. ${M(t).trim()}
10
+ `});break;case"task":for(let t of e.items)r+=`- [${t.checked?"x":" "}] ${T(t.c)}
11
+ `;break;case"code":r+=`\`\`\`${e.lang}
12
+ ${e.v}
13
+ \`\`\`
14
+ `;break;case"quote":r+=Ee(M(e.c));break;case"panel":r+=`> [!${je[e.kind]}]
15
+ ${Ee(M(e.c))}`;break;case"rule":r+=`---
16
+ `;break;case"table":{let t=i=>`| ${i.map(s=>T(s).replace(/\|/g,"\\|")).join(" | ")} |
17
+ `;e.header&&(r+=t(e.header)+`|${e.header.map(()=>" --- |").join("")}
18
+ `);for(let i of e.rows)r+=t(i);break}}return r}function At(n){return n.replace(/^\n+/,"").replace(/\s+$/,"")}function Ee(n){return n.replace(/\n$/,"").split(`
19
+ `).map(r=>r?`> ${r}`:">").join(`
20
+ `)+`
21
+ `}function U(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"text":{let t={t:"text",v:String(e.text??"")},i=Array.isArray(e.marks)?e.marks:[];i.some(s=>s?.type==="code")&&(t={t:"code",v:String(e.text??"")});for(let s of i)!s||s.type==="code"||(s.type==="strong"?t={t:"strong",c:[t]}:s.type==="em"?t={t:"em",c:[t]}:s.type==="strike"?t={t:"strike",c:[t]}:s.type==="link"&&s.attrs?.href&&(t={t:"link",href:String(s.attrs.href),c:[t]}));r.push(t);break}case"hardBreak":r.push({t:"br"});break;case"mention":r.push({t:"text",v:String(e.attrs?.text||(e.attrs?.id?`@${e.attrs.id}`:"@someone"))});break;case"emoji":r.push({t:"text",v:String(e.attrs?.text||e.attrs?.shortName||"")});break;case"status":r.push({t:"text",v:String(e.attrs?.text||"")});break;case"date":r.push({t:"text",v:e.attrs?.timestamp?new Date(Number(e.attrs.timestamp)).toISOString().slice(0,10):""});break;case"inlineCard":{let t=String(e.attrs?.url||"");t&&r.push({t:"link",href:t,c:[{t:"text",v:t}]});break}default:Array.isArray(e.content)?r.push(...U(e.content)):typeof e.text=="string"&&r.push({t:"text",v:e.text})}return r}function R(n){let r=[];for(let e of n||[])if(!(!e||typeof e!="object"))switch(e.type){case"paragraph":r.push({t:"paragraph",c:U(e.content)});break;case"heading":r.push({t:"heading",level:Number(e.attrs?.level)||1,c:U(e.content)});break;case"bulletList":r.push({t:"bullet",items:(e.content||[]).map(t=>R(t?.content))});break;case"orderedList":r.push({t:"ordered",start:Number(e.attrs?.order)||1,items:(e.content||[]).map(t=>R(t?.content))});break;case"taskList":r.push({t:"task",items:(e.content||[]).map(t=>({checked:t?.attrs?.state==="DONE",c:U(t?.content)}))});break;case"decisionList":r.push({t:"bullet",items:(e.content||[]).map(t=>[{t:"paragraph",c:U(t?.content)}])});break;case"codeBlock":r.push({t:"code",lang:String(e.attrs?.language||""),v:(e.content||[]).map(t=>String(t?.text??"")).join("")});break;case"blockquote":r.push({t:"quote",c:R(e.content)});break;case"panel":{let t=String(e.attrs?.panelType||"info");r.push({t:"panel",kind:t in je?t:"info",c:R(e.content)});break}case"rule":r.push({t:"rule"});break;case"table":{let t=(e.content||[]).filter(a=>a?.type==="tableRow"),i=a=>(a.content||[]).map(c=>{let u=R(c?.content);return A(M(u).trim().replace(/\n+/g," "))}),s=a=>(a.content||[]).length>0&&(a.content||[]).every(c=>c?.type==="tableHeader"),o=t.length&&s(t[0])?i(t[0]):null;r.push({t:"table",header:o,rows:t.slice(o?1:0).map(i)});break}case"mediaSingle":case"mediaGroup":case"media":case"mediaInline":r.push({t:"paragraph",c:[{t:"text",v:"[attachment]"}]});break;case"expand":case"nestedExpand":{let t=String(e.attrs?.title||"").trim();t&&r.push({t:"paragraph",c:[{t:"strong",c:[{t:"text",v:t}]}]}),r.push(...R(e.content));break}default:{let t=Array.isArray(e.content)?e.content:[];t.some(i=>i?.type==="text"||i?.type==="hardBreak")?r.push({t:"paragraph",c:U(t)}):t.length?r.push(...R(t)):typeof e.text=="string"&&e.text&&r.push({t:"paragraph",c:[{t:"text",v:e.text}]})}}return r}function It(n){try{if(Array.isArray(n))return R(n);if(n&&typeof n=="object"){let r=n;return r.type==="doc"||!r.type&&Array.isArray(r.content)?R(r.content):R([r])}if(typeof n=="string")return Ce(n)}catch{}return[]}function oe(n){try{return At(M(It(n)))}catch{return""}}var Nt=vt(import.meta.url);function Tt(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return Nt.resolve("@zibby/mcp-jira/index.js")}catch{return null}}function Ot(n){return Le(n)}async function ae(n,r){try{return await n(Ot(r))}catch(e){let t=Number(e?.status);if(!(t>=400&&t<500))throw e;return console.warn(`[jira] rich body rejected (${t}) \u2014 retrying as plain text: ${String(e?.message||e).slice(0,200)}`),await n(ie(r))}}function G(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function ce(n){return G(n).replace(/[a-z0-9]+/g,"")}function X(n,r){let e=G(n),t=G(r);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let i=l=>{let p=new Map;for(let m=0;m<l.length-1;m++){let g=l.slice(m,m+2);p.set(g,(p.get(g)||0)+1)}return p},s=i(e),o=i(t),a=0,c=0,u=0;for(let l of s.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of s.entries()){let m=o.get(l)||0;a+=Math.min(p,m)}return 2*a/Math.max(1,c+u)}function O(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Et(n,r=[]){let e=Array.isArray(r)?r:[];if(e.length===0)return{requested:n||null,resolved:null,strategy:"none"};let t=e.filter(a=>!a.subtask),i=t.length>0?t:e,s=O(n);if(s){let a=i.find(l=>O(l.name)===s);if(a)return{requested:n,resolved:a,strategy:"exact"};let c={task:["task","\u4EFB\u52A1","\u4E8B\u9879","to do","todo"],story:["story","\u7528\u6237\u6545\u4E8B","\u9700\u6C42"],bug:["bug","\u7F3A\u9677","\u95EE\u9898"],improvement:["improvement","\u4F18\u5316","\u6539\u8FDB"],epic:["epic","\u53F2\u8BD7"]};for(let l of Object.values(c)){if(!l.some(m=>O(m)===s))continue;let p=i.find(m=>l.some(g=>O(g)===O(m.name)));if(p)return{requested:n,resolved:p,strategy:"alias"}}let u=i.map(l=>({t:l,score:X(n,l.name)})).sort((l,p)=>p.score-l.score);if(u[0]&&u[0].score>=.5)return{requested:n,resolved:u[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let a of o){let c=i.find(u=>O(u.name)===a);if(c)return{requested:n||null,resolved:c,strategy:"default-preferred"}}return{requested:n||null,resolved:i[0],strategy:"default-first"}}async function Pe(n){let r=`projectKeys=${encodeURIComponent(n)}&expand=projects.issuetypes`,e=await w(`/rest/api/3/issue/createmeta?${r}`),t=Array.isArray(e?.projects)?e.projects:[],s=t.find(a=>String(a?.key||"").toUpperCase()===String(n||"").toUpperCase())||t[0]||null;return(Array.isArray(s?.issuetypes)?s.issuetypes:[]).map(a=>({id:a.id,name:a.name,subtask:!!a.subtask,description:a.description||null}))}async function qe(n,r){if(!n)throw new Error("projectKey is required");let e="sprint is not EMPTY";r==="active"?e="sprint in openSprints()":r==="closed"?e="sprint in closedSprints()":r==="future"&&(e="sprint in futureSprints()");let t=`project = ${n} AND ${e} ORDER BY updated DESC`,i=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,s=await w(`/rest/api/3/search/jql?${i}`),o=new Map;for(let a of s.issues||[])for(let c of a.fields?.customfield_10020||[])c&&!o.has(c.id)&&o.set(c.id,{id:c.id,name:c.name,state:c.state,boardId:c.boardId||null,startDate:c.startDate||null,endDate:c.endDate||null,goal:c.goal||null});return[...o.values()].sort((a,c)=>{let u={active:0,future:1,closed:2},l=(u[a.state]??3)-(u[c.state]??3);return l!==0?l:String(c.startDate||"").localeCompare(String(a.startDate||""))})}function jt(n,{sprintId:r,sprintName:e,target:t}={}){let i=Array.isArray(n)?n:[];if(!i.length)return{sprint:null,selectedBy:"none"};if(r!=null&&String(r).trim()!=="")return{sprint:i.find(a=>String(a.id)===String(r))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),a=i.find(u=>String(u.name||"").toLowerCase()===o.toLowerCase());if(a)return{sprint:a,selectedBy:"name-exact"};let c=i.map(u=>({s:u,score:X(o,u.name||"")})).sort((u,l)=>l.score-u.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let s=String(t||"current").trim().toLowerCase();return s==="active"||s==="current"||s==="latest"?{sprint:i[0],selectedBy:s}:{sprint:i[0],selectedBy:"default"}}function xt(n,r){let e=n?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(r)):!1}async function Ct({issueKey:n,projectKey:r,sprintId:e,attempts:t=3,delayMs:i=450}){let s=[];for(let o=0;o<t;o++){try{let a=`project = ${r} AND key = ${n} AND sprint = ${e}`,c=`jql=${encodeURIComponent(a)}&maxResults=1&fields=key,status`,u=await w(`/rest/api/3/search/jql?${c}`);if(Number(u?.total||0)>0)return s.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:s};let p=await w(`/rest/api/3/issue/${n}?fields=customfield_10020,status`),m=xt(p,e);if(s.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:s}}catch(a){s.push({attempt:o+1,error:String(a?.message||a)})}o<t-1&&await new Promise(a=>setTimeout(a,i))}return{ok:!1,method:"none",traces:s}}async function le({issueKey:n,projectKey:r,sprintId:e,sprintName:t,target:i}){if(!n)return{ok:!1,error:"issueKey is required"};let s=r;if(!s&&(s=(await w(`/rest/api/3/issue/${n}?fields=project`))?.fields?.project?.key||null,!s))return{ok:!1,error:`Could not resolve project for ${n}`};let o=await qe(s,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${s}`};let{sprint:a,selectedBy:c}=jt(o,{sprintId:e,sprintName:t,target:i});if(!a)return{ok:!1,error:`No matching sprint found in ${s}`,requested:{sprintId:e??null,sprintName:t??null,target:i??"current"},availableSprints:o.map(p=>({id:p.id,name:p.name,state:p.state}))};await w(`/rest/api/3/issue/${n}`,{method:"PUT",body:{fields:{customfield_10020:Number(a.id)}}});let u=await Ct({issueKey:n,projectKey:s,sprintId:a.id}),l=u.ok;return{ok:l,issueKey:n,projectKey:s,sprintId:a.id,sprintName:a.name,selectedBy:c,verifiedBy:u.method,verified:l,verificationTrace:u.traces,warning:l?null:`Sprint assignment attempted but verification did not find ${n} in sprint ${a.id}`}}async function Lt(){let n=process.env.JIRA_API_TOKEN,r=process.env.JIRA_EMAIL,e=process.env.JIRA_BASE_URL;if(n&&r&&e)return{authType:"token",apiToken:n,email:r,baseUrl:e};let t=await Rt("jira");return t?.cloudId?{authType:"oauth",accessToken:t.token,cloudId:t.cloudId}:{authType:"token",apiToken:t?.token,email:r||t?.email||"",baseUrl:e||t?.instanceUrl||t?.baseUrl||process.env.ATLASSIAN_INSTANCE_URL||""}}function Pt(n,r,e={}){let t=n||{},i={Accept:"application/json",...e.body?{"Content-Type":"application/json"}:{},...e.headers};if(t.authType==="token"){let s=String(t.baseUrl||t.instanceUrl||"").trim().replace(/\/+$/,""),o=t.apiToken||t.accessToken||"";if(!s)throw new Error("Jira token connection has no base URL \u2014 reconnect Jira with its instance URL, or set JIRA_BASE_URL.");if(!t.email)throw new Error("Jira token connection has no account email \u2014 reconnect Jira with the account email, or set JIRA_EMAIL.");if(!o)throw new Error("Jira token connection has no API token \u2014 reconnect Jira, or set JIRA_API_TOKEN.");return{url:`${s}${r}`,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${o}`).toString("base64"),...i}}}if(typeof t.accessToken!="string"||!t.accessToken)throw new Error(`Invalid jira token type: ${typeof t.accessToken}`);if(!t.cloudId)throw new Error("Invalid jira cloudId: missing");return{url:`https://api.atlassian.com/ex/jira/${t.cloudId}${r}`,headers:{Authorization:`Bearer ${t.accessToken}`,...i}}}async function w(n,r={}){let e=async()=>{let t=await Lt(),{url:i,headers:s}=Pt(t,n,r),o=await N(i,{method:r.method||"GET",headers:s,body:r.body?JSON.stringify(r.body):void 0,signal:r.signal},{kind:/\/search\b/.test(String(n))?"job":"api",what:`Jira ${r.method||"GET"} ${n}`}),a=()=>o.text().catch(u=>{if(te(u)||r.signal?.aborted)throw u;return""});if(!o.ok){let u=await a(),l=new Error(`Jira API ${o.status}: ${u.slice(0,300)}`);throw l.status=o.status,l}let c=await a();if(!c||!c.trim())return{};try{return JSON.parse(c)}catch{return{raw:c}}};try{return await e()}catch(t){if(r.signal?.aborted)throw t;let i=String(t?.message||t||"").toLowerCase();if(!(i.includes("token")||i.includes("401")||i.includes("403")||i.includes("substring")))throw t;return $t("jira"),e()}}var H={id:"jira",callsBackend:!0,serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:q.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira
20
22
  You have direct access to the user's Jira. Use these tools proactively:
21
23
 
22
24
  ### Issue tools
@@ -66,9 +68,9 @@ When user asks to move/transition ticket status:
66
68
  3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
67
69
  4. Call jira_get_issue(issueKey) to verify final status before claiming success.
68
70
  5. If target wording differs (e.g. \u5DF2\u7ECF\u9A8C\u6536 vs \u5DF2\u9A8C\u6536), try toStatus first; only ask user to confirm when no reasonable match exists.
69
- 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let r=Ce();if(!r)return null;let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(s.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(s[e]=process.env[e]);return{command:"node",args:[r],env:s,description:this.description}},async handleToolCall(r,s){try{switch(r){case"jira_list_projects":{let e=await w("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(n=>({id:n.id,key:n.key,name:n.name,style:n.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=s||{};if(e){let i=await w(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(i)?i:[],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"),n=(Array.isArray(t)?t:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,o)=>String(i.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:n.length,statuses:n})}case"jira_list_issue_types":{let{projectKey:e}=s||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await ae(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=s.jql||"",t=s.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let i=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await w(`/rest/api/3/search/jql?${i}`)).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=s.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,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:n,description:i,priority:o,labels:a,assigneeId:c,moveToSprint:u,moveToActiveSprint:l,sprintId:p,sprintName:m,target:g}=s;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let d={requested:n||null,resolved:null,strategy:"none"},b=[];try{b=await ae(e),d=qe(n,b)}catch{}let h={project:{key:e},summary:t,issuetype:d?.resolved?.id?{id:d.resolved.id}:{name:n||"Task"}};i&&(h.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),o&&(h.priority={name:o}),a?.length&&(h.labels=a),c&&(h.assignee={id:c});let S=await w("/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&&v(d.requested)!==v(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(y=>y.name)),(u||l)&&(f.sprintMove=await B({issueKey:S.key,projectKey:e,sprintId:p,sprintName:m,target:g})),JSON.stringify(f)}case"jira_list_sprints":{let{projectKey:e,state:t}=s,n=await ce(e,t);return JSON.stringify({count:n.length,sprints:n})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:n,sprintName:i,target:o}=s||{},a=await B({issueKey:e,projectKey:t,sprintId:n,sprintName:i,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:n,sprintName:i,target:o}=s||{},a=await B({issueKey:e,projectKey:t,sprintId:n,sprintName:i,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:n,status:i,maxResults:o}=s;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=t?`sprint = ${t}`:`sprint = "${e}"`,u=n?`project = ${n} AND `:"",l=i?` AND status = "${i}"`:"",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}=s;if(!e)return JSON.stringify({error:"issueKey is required"});let i=await w(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(i.comments||[]).map(a=>{let c="";return a.body?.content&&(c=K(a.body.content)),{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:i.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=s;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await w(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:{type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:t}]}]}}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:t}=s;return!e||!t?JSON.stringify({error:"issueKey and fields are required"}):(await w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:t}}),JSON.stringify({ok:!0,issueKey:e}))}case"jira_transition_issue":{let{issueKey:e,transitionId:t,toStatus:n,statusName:i,status:o}=s;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(n||i||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=E(a),g=p.find(d=>E(d?.name||"")===m||E(d?.to?.name||"")===m);if(!g){let d=H(a);d.length>=2&&(g=p.find(b=>{let h=H(b?.name||""),S=H(b?.to?.name||""),f=h.length>=2&&(h.includes(d)||d.includes(h)),y=S.length>=2&&(S.includes(d)||d.includes(S));return f||y}))}if(!g){let d=p.map(f=>{let y=M(a,f?.name||""),k=M(a,f?.to?.name||"");return{t:f,score:Math.max(y,k)}}).sort((f,y)=>y.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 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: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};var Me={new:"todo",indeterminate:"in_progress",done:"done"},De=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function Y(r){if(!r)return"unknown";if(r.name&&De.test(r.name))return"blocked";let s=r.statusCategory?.key;return Me[s]||"unknown"}function W(r){if(!r)return"";if(Array.isArray(r))return r.map(W).join("");if(r.type==="text")return r.text||"";if(r.type==="hardBreak"||r.type==="rule")return`
70
- `;let s=r.content?W(r.content):"";return/^(paragraph|heading|listItem|blockquote|codeBlock|panel)$/.test(r.type)&&(s+=`
71
- `),s}function F(r,s){let e=r.fields||{},t=e.status||null,n=null;if(r.self&&r.key)try{n=`${new URL(r.self).origin}/browse/${r.key}`}catch{n=null}return!n&&s&&r.key&&(n=`${String(s).replace(/\/+$/,"")}/browse/${r.key}`),{id:String(r.id??r.key??""),key:r.key,title:e.summary||"",body:typeof e.description=="string"?e.description:W(e.description?.content).trim(),state:t?.name||null,stateCategory:Y(t),assignee:e.assignee?.displayName||null,url:n,_raw:r}}function z(r){let s=JSON.parse(r);if(s&&s.error)throw new Error(s.error);return s}var Q={id:"jira",toStateCategory:Y,toNeutral:F,async listCandidates(r={}){let s=r.query||"";if(!s.trim()){let i=[];if(r.state&&i.push(`status = "${r.state}"`),r.labels){let o=Array.isArray(r.labels)?r.labels:[r.labels];for(let a of o)i.push(`labels = "${a}"`)}r.updatedAfter&&i.push(`updated >= "${r.updatedAfter}"`),s=i.length?`${i.join(" AND ")} ORDER BY updated DESC`:"ORDER BY updated DESC"}let e=Number(r.limit)||30,t=`jql=${encodeURIComponent(s)}&maxResults=${e}&fields=summary,description,status,assignee,labels,project,updated,created`;return((await w(`/rest/api/3/search/jql?${t}`)).issues||[]).map(i=>F(i))},async getTicket(r){if(!r)throw new Error("key is required");let s=await w(`/rest/api/3/issue/${encodeURIComponent(r)}`);return!s||!s.key?null:F(s)},async getComments(r){if(!r)throw new Error("key is required");return(z(await q.handleToolCall("jira_get_comments",{issueKey:r})).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(r,s){if(!r||!s)throw new Error("key and body are required");return{ok:!!z(await q.handleToolCall("jira_add_comment",{issueKey:r,body:s})).ok,id:null}},async transition(r,s){if(!r)throw new Error("key is required");let e=JSON.parse(await q.handleToolCall("jira_transition_issue",{issueKey:r,toStatus:s}));if(!e.ok)return{ok:!1,error:e.error||"transition failed",_raw:e};let t=e.statusAfter||null;return{ok:!0,stateAfter:t,stateCategoryAfter:Y(t?{name:t}:null),_raw:e}},async linkPullRequest(r,s,e){if(!r||!s)throw new Error("key and prUrl are required");try{return await w(`/rest/api/3/issue/${encodeURIComponent(r)}/remotelink`,{method:"POST",body:{object:{url:s,title:e||s,icon:{url16x16:"https://github.com/favicon.ico",title:"GitHub"}}}}),{ok:!0,via:"remotelink"}}catch(t){let n=`${e?`${e}: `:"Linked PR: "}${s}`;return{ok:!!z(await q.handleToolCall("jira_add_comment",{issueKey:r,body:n})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as He}from"fs";import{fileURLToPath as Be}from"url";import{dirname as Fe,resolve as ze}from"path";function Ye(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=Fe(Be(import.meta.url)),s=ze(r,"..","bin","mcp-skill.mjs");return He(s)?s:null}var We=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Qe(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let r=process.env.LINEAR_API_KEY;if(!r)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return r}async function A(r,s={}){let e=await fetch(We,{method:"POST",headers:{Authorization:Qe(),"Content-Type":"application/json"},body:JSON.stringify({query:r,variables:s})});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`Linear API ${e.status}: ${n.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 n=t.errors.map(i=>i?.message||String(i)).join("; ");throw new Error(`Linear GraphQL error: ${n.slice(0,300)}`)}return t.data}function x(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ve(r,s){let e=x(r),t=x(s);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let n=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},i=n(e),o=n(t),a=0,c=0,u=0;for(let l of i.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of i.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+u)}function Ze(r,s){let e=Array.isArray(r)?r:[];if(!e.length)return{state:null,strategy:"no-states"};let t=x(s);if(!t)return{state:null,strategy:"no-target"};let n=e.find(a=>x(a.name)===t);if(n)return{state:n,strategy:"exact"};let i={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(i)){if(!c.some(l=>x(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:Ve(s,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 Xe=`
71
+ 6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let n=Tt();if(!n)return null;let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);process.env.ATLASSIAN_INSTANCE_URL&&(r.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL);for(let e of["JIRA_API_TOKEN","JIRA_EMAIL","JIRA_BASE_URL"])process.env[e]&&(r[e]=process.env[e]);return{command:"node",args:[n],env:r,description:this.description}},async handleToolCall(n,r){try{switch(n){case"jira_list_projects":{let e=await w("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(i=>({id:i.id,key:i.key,name:i.name,style:i.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=r||{};if(e){let s=await w(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(s)?s:[],a=new Map;for(let u of o)for(let l of u.statuses||[])l?.id&&(a.has(l.id)||a.set(l.id,{id:l.id,name:l.name,category:l.statusCategory?.name||null}));let c=[...a.values()].sort((u,l)=>String(u.name).localeCompare(String(l.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let t=await w("/rest/api/3/status"),i=(Array.isArray(t)?t:[]).map(s=>({id:s.id,name:s.name,category:s.statusCategory?.name||null})).sort((s,o)=>String(s.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:i.length,statuses:i})}case"jira_list_issue_types":{let{projectKey:e}=r||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await Pe(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=r.jql||"",t=r.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let s=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,a=((await w(`/rest/api/3/search/jql?${s}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:a.length,issues:a})}case"jira_get_issue":{let e=r.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await w(`/rest/api/3/issue/${e}`);return JSON.stringify({key:t.key,project:t.fields?.project?.key,summary:t.fields?.summary,description:t.fields?.description?oe(t.fields.description):t.fields?.description??null,status:t.fields?.status?.name,assignee:t.fields?.assignee?.displayName||"Unassigned",priority:t.fields?.priority?.name,type:t.fields?.issuetype?.name,labels:t.fields?.labels,created:t.fields?.created,updated:t.fields?.updated})}case"jira_create_issue":{let{projectKey:e,summary:t,issueType:i,description:s,priority:o,labels:a,assigneeId:c,moveToSprint:u,moveToActiveSprint:l,sprintId:p,sprintName:m,target:g}=r;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let d={requested:i||null,resolved:null,strategy:"none"},b=[];try{b=await Pe(e),d=Et(i,b)}catch{}let h={project:{key:e},summary:t,issuetype:d?.resolved?.id?{id:d.resolved.id}:{name:i||"Task"}};o&&(h.priority={name:o}),a?.length&&(h.labels=a),c&&(h.assignee={id:c});let k=s?await ae(f=>w("/rest/api/3/issue",{method:"POST",body:{fields:{...h,description:f}}}),s):await w("/rest/api/3/issue",{method:"POST",body:{fields:h}}),y={ok:!0,key:k.key,id:k.id,self:k.self};return d?.resolved&&(y.issueType=d.resolved.name,y.issueTypeResolution=d.strategy,d.strategy!=="exact"&&d.requested&&O(d.requested)!==O(d.resolved.name)&&(y.issueTypeWarning=`Requested "${d.requested}" is not available in ${e}; used "${d.resolved.name}" instead.`)),b.length>0&&(y.availableIssueTypes=b.map(f=>f.name)),(u||l)&&(y.sprintMove=await le({issueKey:k.key,projectKey:e,sprintId:p,sprintName:m,target:g})),JSON.stringify(y)}case"jira_list_sprints":{let{projectKey:e,state:t}=r,i=await qe(e,t);return JSON.stringify({count:i.length,sprints:i})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o}=r||{},a=await le({issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o||"current"});return JSON.stringify(a)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o}=r||{},a=await le({issueKey:e,projectKey:t,sprintId:i,sprintName:s,target:o});return JSON.stringify(a)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:i,status:s,maxResults:o}=r;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let a=o||50,c=t?`sprint = ${t}`:`sprint = "${e}"`,u=i?`project = ${i} AND `:"",l=s?` AND status = "${s}"`:"",p=`${u}${c}${l} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(p)}&maxResults=${a}&fields=summary,status,assignee,priority,issuetype,project`,g=await w(`/rest/api/3/search/jql?${m}`),d=(g.issues||[]).map(h=>({key:h.key,project:h.fields?.project?.key,summary:h.fields?.summary,status:h.fields?.status?.name,assignee:h.fields?.assignee?.displayName||"Unassigned",priority:h.fields?.priority?.name,type:h.fields?.issuetype?.name})),b={};for(let h of d)b[h.status]=(b[h.status]||0)+1;return JSON.stringify({count:d.length,total:g.total||d.length,statusCounts:b,issues:d})}case"jira_get_comments":{let{issueKey:e,maxResults:t}=r;if(!e)return JSON.stringify({error:"issueKey is required"});let s=await w(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(s.comments||[]).map(a=>{let c=a.body?.content?oe(a.body):"";return{id:a.id,author:a.author?.displayName||"Unknown",body:c,created:a.created,updated:a.updated}});return JSON.stringify({count:o.length,total:s.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=r;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await ae(i=>w(`/rest/api/3/issue/${e}/comment`,{method:"POST",body:{body:i}}),t),JSON.stringify({ok:!0,issueKey:e}))}case"jira_edit_issue":{let{issueKey:e,fields:t}=r;if(!e||!t)return JSON.stringify({error:"issueKey and fields are required"});if(typeof t.description=="string"){let{description:i,...s}=t;await ae(o=>w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:{...s,description:o}}}),i)}else await w(`/rest/api/3/issue/${e}`,{method:"PUT",body:{fields:t}});return JSON.stringify({ok:!0,issueKey:e})}case"jira_transition_issue":{let{issueKey:e,transitionId:t,toStatus:i,statusName:s,status:o}=r;if(!e)return JSON.stringify({error:"issueKey is required"});let a=String(i||s||o||"").trim();if(!t&&!a){let p=((await w(`/rest/api/3/issue/${e}/transitions`)).transitions||[]).map(m=>({id:m.id,name:m.name,to:m.to?.name}));return JSON.stringify({ok:!1,error:"transitionId or toStatus is required",issueKey:e,availableTransitions:p})}let c=t;if(!c){let p=(await w(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=G(a),g=p.find(d=>G(d?.name||"")===m||G(d?.to?.name||"")===m);if(!g){let d=ce(a);d.length>=2&&(g=p.find(b=>{let h=ce(b?.name||""),k=ce(b?.to?.name||""),y=h.length>=2&&(h.includes(d)||d.includes(h)),f=k.length>=2&&(k.includes(d)||d.includes(k));return y||f}))}if(!g){let d=p.map(y=>{let f=X(a,y?.name||""),S=X(a,y?.to?.name||"");return{t:y,score:Math.max(f,S)}}).sort((y,f)=>f.score-y.score),b=d[0],h=d[1];b&&b.score>=.45&&(!h||b.score-h.score>=.12)&&(g=b.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${a}"`,issueKey:e,availableTransitions:p.map(d=>({id:d.id,name:d.name,to:d.to?.name}))});c=g.id}await w(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let u=await w(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:u?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description. Markdown is rendered (headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels)."},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text. Markdown is rendered: headings, **bold**, `code`, lists, - [ ] tasks, links, tables, > quotes, > [!NOTE]/[!TIP]/[!WARNING]/[!CAUTION] panels."}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, description, story points, labels, priority). A string `description` is Markdown and is rendered.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};var qt={new:"todo",indeterminate:"in_progress",done:"done"},Jt=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function de(n){if(!n)return"unknown";if(n.name&&Jt.test(n.name))return"blocked";let r=n.statusCategory?.key;return qt[r]||"unknown"}function me(n){if(!n)return"";if(Array.isArray(n))return n.map(me).join("");if(n.type==="text")return n.text||"";if(n.type==="hardBreak"||n.type==="rule")return`
72
+ `;let r=n.content?me(n.content):"";return/^(paragraph|heading|listItem|blockquote|codeBlock|panel)$/.test(n.type)&&(r+=`
73
+ `),r}function ue(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:me(e.description?.content).trim(),state:t?.name||null,stateCategory:de(t),assignee:e.assignee?.displayName||null,url:i,_raw:n}}function pe(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}var fe={id:"jira",toStateCategory:de,toNeutral:ue,async listCandidates(n={}){let r=n.query||"";if(!r.trim()){let s=[];if(n.state&&s.push(`status = "${n.state}"`),n.labels){let o=Array.isArray(n.labels)?n.labels:[n.labels];for(let a of o)s.push(`labels = "${a}"`)}n.updatedAfter&&s.push(`updated >= "${n.updatedAfter}"`),r=s.length?`${s.join(" AND ")} ORDER BY updated DESC`:"ORDER BY updated DESC"}let e=Number(n.limit)||30,t=`jql=${encodeURIComponent(r)}&maxResults=${e}&fields=summary,description,status,assignee,labels,project,updated,created`;return((await w(`/rest/api/3/search/jql?${t}`)).issues||[]).map(s=>ue(s))},async getTicket(n){if(!n)throw new Error("key is required");let r=await w(`/rest/api/3/issue/${encodeURIComponent(n)}`);return!r||!r.key?null:ue(r)},async getComments(n){if(!n)throw new Error("key is required");return(pe(await H.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:!!pe(await H.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 H.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:de(t?{name:t}:null),_raw:e}},async linkPullRequest(n,r,e){if(!n||!r)throw new Error("key and prUrl are required");try{return await w(`/rest/api/3/issue/${encodeURIComponent(n)}/remotelink`,{method:"POST",body:{object:{url:r,title:e||r,icon:{url16x16:"https://github.com/favicon.ico",title:"GitHub"}}}}),{ok:!0,via:"remotelink"}}catch(t){let i=`${e?`${e}: `:"Linked PR: "}${r}`;return{ok:!!pe(await H.handleToolCall("jira_add_comment",{issueKey:n,body:i})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as Ut}from"fs";import{fileURLToPath as Mt}from"url";import{dirname as Gt,resolve as Kt}from"path";function Dt(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=Gt(Mt(import.meta.url)),r=Kt(n,"..","bin","mcp-skill.mjs");return Ut(r)?r:null}var Bt=process.env.LINEAR_API_URL||"https://api.linear.app/graphql";function Ht(){if(process.env.LINEAR_OAUTH_TOKEN)return`Bearer ${process.env.LINEAR_OAUTH_TOKEN}`;let n=process.env.LINEAR_API_KEY;if(!n)throw new Error("Linear is not connected: set LINEAR_API_KEY (personal API key) or LINEAR_OAUTH_TOKEN.");return n}async function I(n,r={}){let e=await N(Bt,{method:"POST",headers:{Authorization:Ht(),"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 z(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function Ft(n,r){let e=z(n),t=z(r);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let i=l=>{let p=new Map;for(let m=0;m<l.length-1;m++){let g=l.slice(m,m+2);p.set(g,(p.get(g)||0)+1)}return p},s=i(e),o=i(t),a=0,c=0,u=0;for(let l of s.values())c+=l;for(let l of o.values())u+=l;for(let[l,p]of s.entries())a+=Math.min(p,o.get(l)||0);return 2*a/Math.max(1,c+u)}function zt(n,r){let e=Array.isArray(n)?n:[];if(!e.length)return{state:null,strategy:"no-states"};let t=z(r);if(!t)return{state:null,strategy:"no-target"};let i=e.find(a=>z(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=>z(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:Ft(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 Wt=`
72
74
  id
73
75
  identifier
74
76
  number
@@ -82,7 +84,7 @@ When user asks to move/transition ticket status:
82
84
  assignee { id name displayName email }
83
85
  labels { nodes { id name color } }
84
86
  team { id key name }
85
- `,$={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:T.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
87
+ `,E={id:"linear",serverName:"linear",allowedTools:["mcp__linear__*"],requiresIntegration:q.LINEAR,envKeys:["LINEAR_API_KEY","LINEAR_OAUTH_TOKEN"],description:"Linear \u2014 issues, comments, workflow states (GraphQL API key)",promptFragment:`## Linear
86
88
  You have direct access to the user's Linear workspace (GraphQL API). Tools:
87
89
 
88
90
  ### Discovery
@@ -100,32 +102,32 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
100
102
 
101
103
  ### Notes
102
104
  - Always resolve a team first when you need states or want to create/move issues by state name \u2014 states only make sense within their team.
103
- - Issue identifier (ENG-123) and internal id (uuid) are both accepted by get/update tools.`,resolve(){let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);process.env.LINEAR_API_URL&&(r.LINEAR_API_URL=process.env.LINEAR_API_URL);let s=Ye();return s?{type:"stdio",command:"node",args:[s,"../dist/linear.js","linearSkill"],env:r,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:r,description:this.description}},async handleToolCall(r,s){try{switch(r){case"linear_list_teams":{let t=(await A(`
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=Dt();return r?{type:"stdio",command:"node",args:[r,"../dist/linear.js","linearSkill"],env:n,description:this.description,alwaysLoad:!0}:{command:null,args:[],env:n,description:this.description}},async handleToolCall(n,r){try{switch(n){case"linear_list_teams":{let t=(await I(`
104
106
  query Teams($first: Int) {
105
107
  teams(first: $first) {
106
108
  nodes { id key name description }
107
109
  }
108
110
  }
109
- `,{first:s?.limit||50}))?.teams?.nodes||[];return JSON.stringify({count:t.length,teams:t})}case"linear_list_states":{let{teamId:e,teamKey:t}=s||{},n=e;if(!n&&t&&(n=await le(t)),n){let c=(await A(`
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 Je(t)),i){let c=(await I(`
110
112
  query States($teamId: String!) {
111
113
  team(id: $teamId) {
112
114
  id key name
113
115
  states { nodes { id name type color position } }
114
116
  }
115
117
  }
116
- `,{teamId:n}))?.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 A(`
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 I(`
117
119
  query AllStates($first: Int) {
118
120
  workflowStates(first: $first) {
119
121
  nodes { id name type color team { id key name } }
120
122
  }
121
123
  }
122
- `,{first:s?.limit||200}))?.workflowStates?.nodes||[];return JSON.stringify({scope:"workspace",count:o.length,states:o})}case"linear_list_labels":{let{teamId:e}=s||{},n=(await A(`
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 I(`
123
125
  query Labels($first: Int, $filter: IssueLabelFilter) {
124
126
  issueLabels(first: $first, filter: $filter) {
125
127
  nodes { id name color team { id key } }
126
128
  }
127
129
  }
128
- `,{first:s?.limit||100,filter:e?{team:{id:{eq:e}}}:void 0}))?.issueLabels?.nodes||[];return JSON.stringify({count:n.length,labels:n})}case"linear_list_issues":{let{teamId:e,teamKey:t,stateId:n,stateName:i,label:o,assigneeId:a,updatedAfter:c,limit:u}=s||{},l={},p=e;!p&&t&&(p=await le(t)),p&&(l.team={id:{eq:p}}),n?l.state={id:{eq:n}}:i&&(l.state={name:{eqIgnoreCase:i}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let g=((await A(`
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 Je(t)),p&&(l.team={id:{eq:p}}),i?l.state={id:{eq:i}}:s&&(l.state={name:{eqIgnoreCase:s}}),o&&(l.labels={name:{eqIgnoreCase:o}}),a&&(l.assignee={id:{eq:a}}),c&&(l.updatedAt={gt:c});let g=((await I(`
129
131
  query Issues($first: Int, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
130
132
  issues(first: $first, filter: $filter, orderBy: $orderBy) {
131
133
  nodes {
@@ -137,55 +139,55 @@ You have direct access to the user's Linear workspace (GraphQL API). Tools:
137
139
  }
138
140
  }
139
141
  }
140
- `,{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=s?.issueId||s?.identifier||s?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let t=await J(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(n=>n.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=s?.issueId||s?.identifier||s?.issueKey;if(!e)return JSON.stringify({error:"issueId or identifier is required"});let t=await J(e,`
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 F(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 F(e,`
141
143
  id identifier
142
- comments(first: ${Number(s?.limit)||50}) {
144
+ comments(first: ${Number(r?.limit)||50}) {
143
145
  nodes { id body createdAt updatedAt user { id name displayName } }
144
146
  }
145
- `);if(!t)return JSON.stringify({error:`Issue not found: ${e}`});let n=(t.comments?.nodes||[]).map(i=>({id:i.id,author:i.user?.displayName||i.user?.name||"Unknown",body:i.body||"",createdAt:i.createdAt,updatedAt:i.updatedAt})).sort((i,o)=>String(o.createdAt).localeCompare(String(i.createdAt)));return JSON.stringify({count:n.length,issue:t.identifier,comments:n})}case"linear_add_comment":{let e=s?.issueId||s?.identifier||s?.issueKey,t=s?.body;if(!e||!t)return JSON.stringify({error:"issueId/identifier and body are required"});let n=await J(e,"id identifier");if(!n)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await A(`
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 F(e,"id identifier");if(!i)return JSON.stringify({error:`Issue not found: ${e}`});let o=(await I(`
146
148
  mutation AddComment($input: CommentCreateInput!) {
147
149
  commentCreate(input: $input) {
148
150
  success
149
151
  comment { id url createdAt }
150
152
  }
151
153
  }
152
- `,{input:{issueId:n.id,body:t}}))?.commentCreate;return JSON.stringify({ok:!!o?.success,commentId:o?.comment?.id,url:o?.comment?.url})}case"linear_update_state":{let e=s?.issueId||s?.identifier||s?.issueKey,{stateId:t,stateName:n,toStatus:i,status:o}=s||{};if(!e)return JSON.stringify({error:"issueId or identifier is required"});let a=await J(e,`
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 F(e,`
153
155
  id identifier
154
156
  state { id name type }
155
157
  team { id key states { nodes { id name type position } } }
156
- `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=t,u=t?{strategy:"explicit-id"}:null;if(!c){let m=String(n||i||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=Ze(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 A(`
158
+ `);if(!a)return JSON.stringify({error:`Issue not found: ${e}`});let c=t,u=t?{strategy:"explicit-id"}:null;if(!c){let m=String(i||s||o||"").trim(),g=(a.team?.states?.nodes||[]).slice().sort((b,h)=>(b.position||0)-(h.position||0));if(!m)return JSON.stringify({ok:!1,error:"stateId or stateName/toStatus is required",issue:a.identifier,availableStates:g.map(b=>({id:b.id,name:b.name,type:b.type}))});let d=zt(g,m);if(!d.state)return JSON.stringify({ok:!1,error:`No workflow state matches "${m}" in team ${a.team?.key}`,issue:a.identifier,availableStates:g.map(b=>({id:b.id,name:b.name,type:b.type}))});c=d.state.id,u={strategy:d.strategy,matchedName:d.state.name}}let p=(await I(`
157
159
  mutation MoveIssue($id: String!, $input: IssueUpdateInput!) {
158
160
  issueUpdate(id: $id, input: $input) {
159
161
  success
160
162
  issue { id identifier state { id name type } }
161
163
  }
162
164
  }
163
- `,{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=s?.issueId||s?.identifier||s?.issueKey,{url:t,title:n,subtitle:i}=s||{};if(!e||!t)return JSON.stringify({error:"issueId/identifier and url are required"});let o=await J(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await A(`
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 F(e,"id identifier");if(!o)return JSON.stringify({error:`Issue not found: ${e}`});let c=(await I(`
164
166
  mutation LinkAttachment($input: AttachmentCreateInput!) {
165
167
  attachmentCreate(input: $input) {
166
168
  success
167
169
  attachment { id url title }
168
170
  }
169
171
  }
170
- `,{input:{issueId:o.id,url:t,title:n||t,subtitle:i||void 0}}))?.attachmentCreate;return JSON.stringify({ok:!!c?.success,attachmentId:c?.attachment?.id,url:c?.attachment?.url})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}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 le(r){return(await A(`
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 Je(n){return(await I(`
171
173
  query TeamByKey($filter: TeamFilter) {
172
174
  teams(first: 1, filter: $filter) { nodes { id key } }
173
175
  }
174
- `,{filter:{key:{eq:r}}}))?.teams?.nodes?.[0]?.id||null}async function J(r,s=Xe){let e=String(r).trim(),t=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(t){let i=t[1].toUpperCase(),o=Number(t[2]);return(await A(`
176
+ `,{filter:{key:{eq:n}}}))?.teams?.nodes?.[0]?.id||null}async function F(n,r=Wt){let e=String(n).trim(),t=/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(e);if(t){let s=t[1].toUpperCase(),o=Number(t[2]);return(await I(`
175
177
  query IssueByIdentifier($filter: IssueFilter) {
176
178
  issues(first: 1, filter: $filter) {
177
- nodes { ${s} }
179
+ nodes { ${r} }
178
180
  }
179
181
  }
180
- `,{filter:{number:{eq:o},team:{key:{eq:i}}}}))?.issues?.nodes?.[0]||null}return(await A(`
182
+ `,{filter:{number:{eq:o},team:{key:{eq:s}}}}))?.issues?.nodes?.[0]||null}return(await I(`
181
183
  query IssueById($id: String!) {
182
- issue(id: $id) { ${s} }
184
+ issue(id: $id) { ${r} }
183
185
  }
184
- `,{id:e}))?.issue||null}var et={triage:"todo",backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",canceled:"done"},tt=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function Z(r){return r?r.name&&tt.test(r.name)?"blocked":et[r.type]||"unknown":"unknown"}function U(r){let s=JSON.parse(r);if(s&&s.error)throw new Error(s.error);return s}function V(r){let s=r.state||null,e=r.stateType||null;return{id:String(r.id||r.identifier||""),key:r.identifier||String(r.id||""),title:r.title||"",body:r.description||"",state:s,stateCategory:Z(s?{name:s,type:e}:null),assignee:r.assignee||null,url:r.url||null,_raw:r}}var X={id:"linear",toStateCategory:Z,toNeutral:V,async listCandidates(r={}){let s=r.ctx||{},e={teamId:s.teamId,teamKey:s.teamKey,stateName:r.state,label:Array.isArray(r.labels)?r.labels[0]:r.labels,assigneeId:s.assigneeId,updatedAfter:r.updatedAfter,limit:r.limit};return(U(await $.handleToolCall("linear_list_issues",e)).issues||[]).map(V)},async getTicket(r){if(!r)throw new Error("key is required");let s=JSON.parse(await $.handleToolCall("linear_get_issue",{identifier:r}));return s.error?null:V(s)},async getComments(r){if(!r)throw new Error("key is required");return(U(await $.handleToolCall("linear_get_comments",{identifier:r})).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(r,s){if(!r||!s)throw new Error("key and body are required");let e=U(await $.handleToolCall("linear_add_comment",{identifier:r,body:s}));return{ok:!!e.ok,id:e.commentId||null}},async transition(r,s){if(!r)throw new Error("key is required");let e=JSON.parse(await $.handleToolCall("linear_update_state",{identifier:r,toStatus:s}));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:Z(t?{name:t,type:e.stateTypeAfter}:null),_raw:e}},async linkPullRequest(r,s,e){if(!r||!s)throw new Error("key and prUrl are required");try{if(U(await $.handleToolCall("linear_link_attachment",{identifier:r,url:s,title:e||s})).ok)return{ok:!0,via:"attachment"};throw new Error("attachmentCreate returned ok:false")}catch(t){let n=`${e?`${e}: `:"Linked PR: "}${s}`;return{ok:!!U(await $.handleToolCall("linear_add_comment",{identifier:r,body:n})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as ot}from"fs";import{fileURLToPath as at}from"url";import{dirname as ct,resolve as lt}from"path";import{resolveIntegrationToken as he}from"@zibby/core/backend-client.js";import{spawn as Gt,execSync as Kt}from"child_process";import{existsSync as Dt,mkdirSync as Ht,readdirSync as Bt,statSync as Ft,readFileSync as zt}from"fs";import{resolve as Wt,join as Qt,basename as Vt}from"path";function pe(r,s,e,t,n="clone"){try{r(`git -C "${s}" remote set-url origin "${e}"`,{stdio:"pipe"})}catch(i){let o=String(i?.message||i);t&&(o=o.split(t).join("***")),console.error(`[${n}] WARNING: failed to strip token from .git/config: ${o}`)}}import rt from"crypto";var ue=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,de=/<!--\s*zbreview-summary\s*-->/i;function st(r){return String(r||"").replace(ue,"").replace(de,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function it(r,s){return rt.createHash("sha256").update(`${String(r||"")}\0${st(s)}`).digest("hex").slice(0,12)}function nt(r){return`
186
+ `,{id:e}))?.issue||null}var Yt={triage:"todo",backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",canceled:"done"},Qt=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function ge(n){return n?n.name&&Qt.test(n.name)?"blocked":Yt[n.type]||"unknown":"unknown"}function W(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function ye(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:ge(r?{name:r,type:e}:null),assignee:n.assignee||null,url:n.url||null,_raw:n}}var he={id:"linear",toStateCategory:ge,toNeutral:ye,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(W(await E.handleToolCall("linear_list_issues",e)).issues||[]).map(ye)},async getTicket(n){if(!n)throw new Error("key is required");let r=JSON.parse(await E.handleToolCall("linear_get_issue",{identifier:n}));return r.error?null:ye(r)},async getComments(n){if(!n)throw new Error("key is required");return(W(await E.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=W(await E.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 E.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:ge(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(W(await E.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:!!W(await E.handleToolCall("linear_add_comment",{identifier:n,body:i})).ok,via:"comment",error:String(t?.message||t)}}}};import{existsSync as tr}from"fs";import{fileURLToPath as rr}from"url";import{dirname as nr,resolve as sr}from"path";import{resolveIntegrationToken as Fe}from"@zibby/core/backend-client.js";import{spawn as Mr,execSync as Gr}from"child_process";import{existsSync as Dr,mkdirSync as Br,readdirSync as Hr,statSync as Fr,readFileSync as zr}from"fs";import{resolve as Yr,join as Qr,basename as Vr}from"path";function Ue(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 Vt from"crypto";var Me=/<!--\s*zbfp:([a-f0-9]{8,20})\s*-->/i,Ge=/<!--\s*zbreview-summary\s*-->/i;function Zt(n){return String(n||"").replace(Me,"").replace(Ge,"").replace(/\b(?:lines?|L)\s*#?\d+(?:\s*[-–]\s*\d+)?/gi,"").replace(/[`*_>#~]/g,"").replace(/\s+/g," ").trim().toLowerCase().slice(0,400)}function Xt(n,r){return Vt.createHash("sha256").update(`${String(n||"")}\0${Zt(r)}`).digest("hex").slice(0,12)}function er(n){return`
185
187
 
186
- <!-- zbfp:${r} -->`}var me=`
188
+ <!-- zbfp:${n} -->`}var Ke=`
187
189
 
188
- <!-- zbreview-summary -->`;function ye(r){let s=ue.exec(String(r||""));return s?s[1].toLowerCase():null}function fe(r){return de.test(String(r||""))}function ge(r,s){let e=new Set([...s||[]].map(i=>String(i).toLowerCase())),t=[],n=0;for(let i of Array.isArray(r)?r:[]){if(!i||!i.body)continue;let o=it(i.path,i.body);if(e.has(o)){n+=1;continue}e.add(o),t.push({...i,_fp:o,body:`${String(i.body)}${nt(o)}`})}return{toPost:t,skipped:n}}function pt(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=ct(at(import.meta.url)),s=lt(r,"..","bin","mcp-skill.mjs");return ot(s)?s:null}async function _(r,s={}){let{token:e}=await he("github"),t=r.startsWith("https://")?r:`https://api.github.com${r}`,n={Authorization:`Bearer ${e}`,Accept:s.accept||"application/vnd.github.v3+json","User-Agent":"Zibby-App",...s.body?{"Content-Type":"application/json"}:{}},i=await fetch(t,{method:s.method||"GET",headers:n,body:s.body?JSON.stringify(s.body):void 0});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`GitHub API ${i.status}: ${o.slice(0,300)}`)}return s.raw?i.text():i.json()}var R={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:T.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
190
+ <!-- zbreview-summary -->`;function De(n){let r=Me.exec(String(n||""));return r?r[1].toLowerCase():null}function Be(n){return Ge.test(String(n||""))}function He(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=Xt(s.path,s.body);if(e.has(o)){i+=1;continue}e.add(o),t.push({...s,_fp:o,body:`${String(s.body)}${er(o)}`})}return{toPost:t,skipped:i}}function ir(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let n=nr(rr(import.meta.url)),r=sr(n,"..","bin","mcp-skill.mjs");return tr(r)?r:null}async function _(n,r={}){let{token:e}=await Fe("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 N(t,{method:r.method||"GET",headers:i,body:r.body?JSON.stringify(r.body):void 0},{kind:"api",what:`GitHub ${r.method||"GET"} ${n}`});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`GitHub API ${s.status}: ${o.slice(0,300)}`)}return r.raw?s.text():s.json()}var v={id:"github",callsBackend:!0,serverName:"github",allowedTools:["mcp__github__*"],requiresIntegration:q.GITHUB,envKeys:["GITHUB_TOKEN","PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV"],description:"GitHub \u2014 issues, PRs, commits, code search, file reading",promptFragment:`## GitHub
189
191
  You have access to the user's GitHub repositories. Available tools:
190
192
 
191
193
  ### Discovery
@@ -228,6 +230,6 @@ When user says "check out repo-name" or "clone repo-name":
228
230
  3. STOP. Do not offer to inspect files or ask what to do next.
229
231
 
230
232
  When user just wants to "look at" or "read" files (not clone):
231
- - Use github_get_file to read individual files via API`,resolve(){let r=pt();if(!r)return{command:null,args:[],env:{},description:this.description};let s={};for(let e of this.envKeys)process.env[e]&&(s[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/github.js","githubSkill"],env:s,description:this.description,alwaysLoad:!0}},async handleToolCall(r,s){try{switch(r){case"github_search_issues":{let e=s.query;if(!e)return JSON.stringify({error:"query is required"});let t=await _(`/search/issues?q=${encodeURIComponent(e)}&per_page=${s.limit||20}`),n=(t.items||[]).map(i=>({number:i.number,title:i.title,state:i.state,repo:i.repository_url?.split("/").slice(-2).join("/"),url:i.html_url,user:i.user?.login,isPR:!!i.pull_request,labels:(i.labels||[]).map(o=>o.name),createdAt:i.created_at}));return JSON.stringify({total:t.total_count,items:n})}case"github_search_code":{let e=s.query;if(!e)return JSON.stringify({error:"query is required"});let t=s.repo?`+repo:${s.repo}`:"",n=s.language?`+language:${s.language}`:"",i=await _(`/search/code?q=${encodeURIComponent(e)}${t}${n}&per_page=${s.limit||15}`),o=(i.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:i.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:t,number:n}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await _(`/repos/${e}/${t}/pulls/${n}`);return JSON.stringify({number:i.number,title:i.title,state:i.state,merged:i.merged,body:i.body?.slice(0,5e3),user:i.user?.login,branch:i.head?.ref,headSha:i.head?.sha,base:i.base?.ref,changedFiles:i.changed_files,additions:i.additions,deletions:i.deletions,createdAt:i.created_at,mergedAt:i.merged_at,url:i.html_url,labels:(i.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:t,number:n}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await _(`/repos/${e}/${t}/pulls/${n}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=i.length>15e3;return JSON.stringify({number:n,diff:o?i.slice(0,15e3):i,truncated:o,totalLength:i.length})}case"github_list_pr_files":{let{owner:e,repo:t,number:n}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await _(`/repos/${e}/${t}/pulls/${n}/files?per_page=100`);return JSON.stringify({total:i.length,files:i.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:n}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await _(`/repos/${e}/${t}/pulls/${n}/comments?per_page=50`),o=await _(`/repos/${e}/${t}/issues/${n}/comments?per_page=50`),a=[...i.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:n,commentId:i}=s||{};if(!e||!t||!n||!i)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await _(`/repos/${e}/${t}/pulls/comments/${i}`),a=o.in_reply_to_id||o.id,c=[];try{c=await _(`/repos/${e}/${t}/pulls/${n}/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:n,commentId:i,body:o}=s||{};if(!e||!t||!n||!i||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await _(`/repos/${e}/${t}/pulls/${n}/comments/${i}/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:n,body:i}=s||{};if(!e||!t||!n||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${n}/comments`,{method:"POST",body:{body:String(i)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:t,number:n,body:i,event:o,comments:a}=s||{};if(!e||!t||!n)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 y={path:f.path,body:String(f.body)};return f.line!=null?(y.line=Number(f.line),y.side=f.side==="LEFT"?"LEFT":"RIGHT"):y.position=Number(f.position),y}):[];if(c!=="APPROVE"&&!i&&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 y=await _(`/repos/${e}/${t}/pulls/${n}/comments?per_page=100&page=${f}`);if(!Array.isArray(y)||y.length===0)break;for(let k of y){let I=ye(k.body);I&&l.add(I)}if(y.length<100)break}for(let f=1;f<=20&&p==null;f+=1){let y=await _(`/repos/${e}/${t}/issues/${n}/comments?per_page=100&page=${f}`);if(!Array.isArray(y)||y.length===0)break;for(let k of y)if(fe(k.body)){p=k.id;break}if(y.length<100)break}}catch{}let m=!1,g=!1;if(i){let f=`${String(i)}${me}`;try{p!=null?(await _(`/repos/${e}/${t}/issues/comments/${p}`,{method:"PATCH",body:{body:f}}),m=!0):await _(`/repos/${e}/${t}/issues/${n}/comments`,{method:"POST",body:{body:f}}),g=!0}catch{}}let{toPost:d,skipped:b}=ge(u,l),h=d.map(({_fp:f,...y})=>y),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/${n}/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:n,path:i,limit:o,since:a,until:c,page:u}=s;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}`;n&&(p+=`&sha=${encodeURIComponent(n)}`),i&&(p+=`&path=${encodeURIComponent(i)}`),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:n,includePrs:i}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await _(`/repos/${e}/${t}/commits/${n}`),a;if(i)try{let c=await _(`/repos/${e}/${t}/commits/${n}/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:n,ref:i}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${t}/contents/${encodeURIComponent(n)}`;i&&(o+=`?ref=${encodeURIComponent(i)}`);let a=await _(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:n,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],n=t.owner.login,i=t.owner.type,o=i==="Organization"?`/orgs/${n}`:`/users/${n}`,a=await _(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:i,isOrg:i==="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||[],n=new Map;for(let o of t)o.owner.type==="Organization"&&(n.has(o.owner.login)||n.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let i=Array.from(n.values());return JSON.stringify({count:i.length,orgs:i,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 y=f.replace(/^~(?=$|\/|\\)/,g);return a(y)},{owner:e,repo:t,destination:n}=s;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let{execSync:i}=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 he("github"),g=l(),b=n?d(n):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{i(`git clone ${S} "${h}"`,{stdio:"pipe"});let f=`https://github.com/${e}/${t}.git`;pe(i,h,f,m,"github_clone");let y=p()==="win32",k;return y?k=i(`dir "${h}"`,{encoding:"utf-8",shell:"cmd.exe"}):k=i(`ls -la "${h}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:h,message:`Cloned ${e}/${t} to ${h}`,contents:k.split(`
233
+ - Use github_get_file to read individual files via API`,resolve(){let n=ir();if(!n)return{command:null,args:[],env:{},description:this.description};let r={};for(let e of this.envKeys)process.env[e]&&(r[e]=process.env[e]);return{type:"stdio",command:"node",args:[n,"../dist/github.js","githubSkill"],env:r,description:this.description,alwaysLoad:!0}},async handleToolCall(n,r){try{switch(n){case"github_search_issues":{let e=r.query;if(!e)return JSON.stringify({error:"query is required"});let t=await _(`/search/issues?q=${encodeURIComponent(e)}&per_page=${r.limit||20}`),i=(t.items||[]).map(s=>({number:s.number,title:s.title,state:s.state,repo:s.repository_url?.split("/").slice(-2).join("/"),url:s.html_url,user:s.user?.login,isPR:!!s.pull_request,labels:(s.labels||[]).map(o=>o.name),createdAt:s.created_at}));return JSON.stringify({total:t.total_count,items:i})}case"github_search_code":{let e=r.query;if(!e)return JSON.stringify({error:"query is required"});let t=r.repo?`+repo:${r.repo}`:"",i=r.language?`+language:${r.language}`:"",s=await _(`/search/code?q=${encodeURIComponent(e)}${t}${i}&per_page=${r.limit||15}`),o=(s.items||[]).map(a=>({name:a.name,path:a.path,repo:a.repository?.full_name,url:a.html_url,score:a.score}));return JSON.stringify({total:s.total_count,items:o})}case"github_get_pr":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}`);return JSON.stringify({number:s.number,title:s.title,state:s.state,merged:s.merged,body:s.body?.slice(0,5e3),user:s.user?.login,branch:s.head?.ref,headSha:s.head?.sha,base:s.base?.ref,changedFiles:s.changed_files,additions:s.additions,deletions:s.deletions,createdAt:s.created_at,mergedAt:s.merged_at,url:s.html_url,labels:(s.labels||[]).map(o=>o.name)})}case"github_get_pr_diff":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}`,{accept:"application/vnd.github.v3.diff",raw:!0}),o=s.length>15e3;return JSON.stringify({number:i,diff:o?s.slice(0,15e3):s,truncated:o,totalLength:s.length})}case"github_list_pr_files":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}/files?per_page=100`);return JSON.stringify({total:s.length,files:s.map(o=>({filename:o.filename,status:o.status,additions:o.additions,deletions:o.deletions,patch:o.patch?.slice(0,3e3)}))})}case"github_list_pr_comments":{let{owner:e,repo:t,number:i}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=50`),o=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=50`),a=[...s.map(c=>({type:"review",user:c.user?.login,body:c.body?.slice(0,1e3),path:c.path,line:c.line,createdAt:c.created_at})),...o.map(c=>({type:"issue",user:c.user?.login,body:c.body?.slice(0,1e3),createdAt:c.created_at}))].sort((c,u)=>new Date(c.createdAt)-new Date(u.createdAt));return JSON.stringify({total:a.length,comments:a})}case"github_get_review_thread":{let{owner:e,repo:t,number:i,commentId:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and commentId are required"});let o=await _(`/repos/${e}/${t}/pulls/comments/${s}`),a=o.in_reply_to_id||o.id,c=[];try{c=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100`)}catch{c=[o]}(!Array.isArray(c)||c.length===0)&&(c=[o]);let u=c.filter(m=>m.id===a||m.in_reply_to_id===a).sort((m,g)=>new Date(m.created_at)-new Date(g.created_at)),l=u.length?u:[o],p=l.find(m=>m.id===a)||l[0];return JSON.stringify({rootCommentId:a,path:p.path,line:p.line??p.original_line??null,side:p.side||"RIGHT",diffHunk:typeof p.diff_hunk=="string"?p.diff_hunk.slice(0,3e3):null,commitId:p.commit_id||p.original_commit_id||null,notes:l.map(m=>({id:m.id,user:m.user?.login,body:(m.body||"").slice(0,4e3),createdAt:m.created_at,isRoot:m.id===a,url:m.html_url}))})}case"github_reply_review_thread":{let{owner:e,repo:t,number:i,commentId:s,body:o}=r||{};if(!e||!t||!i||!s||!o)return JSON.stringify({error:"owner, repo, number, commentId, and body are required"});let a=await _(`/repos/${e}/${t}/pulls/${i}/comments/${s}/replies`,{method:"POST",body:{body:String(o)}});return JSON.stringify({ok:!0,id:a.id,url:a.html_url,inReplyTo:a.in_reply_to_id})}case"github_reply_issue_comment":{let{owner:e,repo:t,number:i,body:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:String(s)}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_create_review":{let{owner:e,repo:t,number:i,body:s,event:o,comments:a}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let c=(o||"COMMENT").toUpperCase();if(!["COMMENT","APPROVE","REQUEST_CHANGES"].includes(c))return JSON.stringify({error:`event must be COMMENT, APPROVE, or REQUEST_CHANGES (got ${o})`});let u=Array.isArray(a)?a.filter(y=>y&&y.path&&y.body&&(y.line!=null||y.position!=null)).map(y=>{let f={path:y.path,body:String(y.body)};return y.line!=null?(f.line=Number(y.line),f.side=y.side==="LEFT"?"LEFT":"RIGHT"):f.position=Number(y.position),f}):[];if(c!=="APPROVE"&&!s&&u.length===0)return JSON.stringify({error:"a COMMENT or REQUEST_CHANGES review needs a body and/or inline comments"});let l=new Set,p=null;try{for(let y=1;y<=20;y+=1){let f=await _(`/repos/${e}/${t}/pulls/${i}/comments?per_page=100&page=${y}`);if(!Array.isArray(f)||f.length===0)break;for(let S of f){let $=De(S.body);$&&l.add($)}if(f.length<100)break}for(let y=1;y<=20&&p==null;y+=1){let f=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=100&page=${y}`);if(!Array.isArray(f)||f.length===0)break;for(let S of f)if(Be(S.body)){p=S.id;break}if(f.length<100)break}}catch{}let m=!1,g=!1;if(s){let y=`${String(s)}${Ke}`;try{p!=null?(await _(`/repos/${e}/${t}/issues/comments/${p}`,{method:"PATCH",body:{body:y}}),m=!0):await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:y}}),g=!0}catch{}}let{toPost:d,skipped:b}=He(u,l),h=d.map(({_fp:y,...f})=>f),k=null;if(h.length>0||c==="APPROVE"||c==="REQUEST_CHANGES"){let y={event:c};h.length>0&&(y.comments=h),h.length===0&&c==="REQUEST_CHANGES"&&(y.body="Changes requested \u2014 see the review summary comment."),k=await _(`/repos/${e}/${t}/pulls/${i}/reviews`,{method:"POST",body:y})}return JSON.stringify({ok:!0,id:k?k.id:void 0,state:k?k.state:void 0,event:c,notePosted:g,summaryUpdated:m,commentsPosted:h.length,inlineSkipped:b||void 0,url:k?k.html_url:void 0})}case"github_list_commits":{let{owner:e,repo:t,branch:i,path:s,limit:o,since:a,until:c,page:u}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let l=Math.min(Number(o)||20,100),p=`/repos/${e}/${t}/commits?per_page=${l}&page=${Number(u)||1}`;i&&(p+=`&sha=${encodeURIComponent(i)}`),s&&(p+=`&path=${encodeURIComponent(s)}`),a&&(p+=`&since=${encodeURIComponent(a)}`),c&&(p+=`&until=${encodeURIComponent(c)}`);let m=await _(p);return JSON.stringify({total:m.length,page:Number(u)||1,hasMore:m.length>=l,commits:m.map(g=>({sha:g.sha?.slice(0,8),fullSha:g.sha,message:g.commit?.message?.slice(0,300),author:g.commit?.author?.name,authorEmail:g.commit?.author?.email,date:g.commit?.author?.date,url:g.html_url}))})}case"github_get_commit":{let{owner:e,repo:t,sha:i,includePrs:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and sha are required"});let o=await _(`/repos/${e}/${t}/commits/${i}`),a;if(s)try{let c=await _(`/repos/${e}/${t}/commits/${i}/pulls`);a=(Array.isArray(c)?c:[]).map(u=>({number:u.number,title:u.title,state:u.state,merged:!!u.merged_at,webUrl:u.html_url}))}catch{a=[]}return JSON.stringify({sha:o.sha?.slice(0,8),message:o.commit?.message,author:o.commit?.author?.name,date:o.commit?.author?.date,stats:o.stats,files:(o.files||[]).map(c=>({filename:c.filename,status:c.status,additions:c.additions,deletions:c.deletions,patch:c.patch?.slice(0,3e3)})),...a?{pullRequests:a}:{}})}case"github_get_file":{let{owner:e,repo:t,path:i,ref:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and path are required"});let o=`/repos/${e}/${t}/contents/${encodeURIComponent(i)}`;s&&(o+=`?ref=${encodeURIComponent(s)}`);let a=await _(o);if(a.type!=="file")return Array.isArray(a)?JSON.stringify({type:"directory",path:i,entries:a.map(l=>({name:l.name,type:l.type,size:l.size,path:l.path}))}):JSON.stringify({error:`Not a file: ${a.type}`});let c=Buffer.from(a.content||"","base64").toString("utf-8"),u=c.length>2e4;return JSON.stringify({path:a.path,size:a.size,sha:a.sha?.slice(0,8),content:u?c.slice(0,2e4):c,truncated:u})}case"github_get_user":try{let e=await _("/installation/repositories?per_page=1");if(e.repositories&&e.repositories.length>0){let t=e.repositories[0],i=t.owner.login,s=t.owner.type,o=s==="Organization"?`/orgs/${i}`:`/users/${i}`,a=await _(o);return JSON.stringify({login:a.login,name:a.name||a.login,avatar:a.avatar_url,bio:a.bio||a.description,type:s,isOrg:s==="Organization",publicRepos:a.public_repos,message:"Showing GitHub App installation owner (GitHub Apps cannot access /user endpoint)"})}return JSON.stringify({error:"No repositories accessible to this GitHub App installation"})}catch(e){return JSON.stringify({error:`GitHub App cannot access /user endpoint. Use github_list_repos instead. (${e.message})`})}case"github_list_orgs":try{let t=(await _("/installation/repositories?per_page=100")).repositories||[],i=new Map;for(let o of t)o.owner.type==="Organization"&&(i.has(o.owner.login)||i.set(o.owner.login,{login:o.owner.login,description:null,url:o.owner.url}));let s=Array.from(i.values());return JSON.stringify({count:s.length,orgs:s,message:"Extracted from accessible repositories (GitHub Apps cannot access /user/orgs directly)"})}catch(e){return JSON.stringify({error:`GitHub App cannot list orgs via /user/orgs. Error: ${e.message}`})}case"github_clone":{let d=function(y){let f=y.replace(/^~(?=$|\/|\\)/,g);return a(f)},{owner:e,repo:t,destination:i}=r;if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let{execSync:s}=await import("child_process"),{join:o,resolve:a}=await import("path"),{existsSync:c,mkdirSync:u}=await import("fs"),{homedir:l,platform:p}=await import("os"),{token:m}=await Fe("github"),g=l(),b=i?d(i):o(g,"zibby-repos"),h=o(b,t);if(u(b,{recursive:!0}),c(h))return JSON.stringify({error:`Directory ${h} already exists. Remove it first or use a different destination.`,existingPath:h});let k=`https://x-access-token:${m}@github.com/${e}/${t}.git`;try{s(`git clone ${k} "${h}"`,{stdio:"pipe"});let y=`https://github.com/${e}/${t}.git`;Ue(s,h,y,m,"github_clone");let f=p()==="win32",S;return f?S=s(`dir "${h}"`,{encoding:"utf-8",shell:"cmd.exe"}):S=s(`ls -la "${h}"`,{encoding:"utf-8"}),JSON.stringify({success:!0,path:h,message:`Cloned ${e}/${t} to ${h}`,contents:S.split(`
232
234
  `).slice(0,30).join(`
233
- `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(f){let k=String(f.message||f).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}=s;if(!e)return JSON.stringify({error:"query is required"});let n=await this.handleToolCall("github_list_repos",{limit:200},{}),i=JSON.parse(n);if(i.error)return JSON.stringify(i);let o=e.toLowerCase(),a=i.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:n,direction:i,limit:o,query:a}=s,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 k=String(a).toLowerCase();return y.name&&y.name.toLowerCase().includes(k)||y.fullName&&y.fullName.toLowerCase().includes(k)||y.description&&y.description.toLowerCase().includes(k)};if(!e){let y=1,k=!0;for(;k&&l.length<u;){let L=`/installation/repositories?per_page=${c}&page=${y}`,D=(await _(L)).repositories||[];if(D.length===0)break;l=l.concat(D),k=D.length===c,y++}let I=l.map(p).filter(m),P=I.slice(0,u),Ne=I.length>P.length,ne=P.filter(L=>L.private).length,oe=P.filter(L=>!L.private).length;return JSON.stringify({count:P.length,repos:P,truncated:Ne,privateCount:ne,publicCount:oe,message:`Found ${ne} private and ${oe} public repos`})}let g=await _(`/orgs/${e}`).then(()=>!0).catch(()=>!1),d=1,b=!0;for(;b&&l.length<u;){let y;g?y=`/orgs/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${n||"updated"}&direction=${i||"desc"}`:y=`/users/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${n||"updated"}&direction=${i||"desc"}`;let k=await _(y),I=Array.isArray(k)?k:[];if(I.length===0)break;l=l.concat(I),b=I.length===c,d++}let h=l.map(p).filter(m),S=h.slice(0,u),f=h.length>S.length;return JSON.stringify({count:S.length,repos:S,truncated:f})}case"github_create_pr":{let{owner:e,repo:t,head:n,title:i}=s||{};if(!e||!t||!n||!i)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=s.base;if(!o)try{o=(await _(`/repos/${e}/${t}`)).default_branch||"main"}catch{o="main"}let a={title:String(i),head:String(n),base:String(o),body:s.body?String(s.body):"",draft:!!s.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:n,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:n,base:o,repo:`${e}/${t}`,provider:"github",skippedReason:u});throw c}}case"github_merge_pr":{let{owner:e,repo:t,number:n}=s||{};if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=s.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(i))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${i})`});let o={merge_method:i};s.commitTitle&&(o.commit_title=String(s.commitTitle)),s.commitMessage&&(o.commit_message=String(s.commitMessage));try{let a=await _(`/repos/${e}/${t}/pulls/${n}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:n,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:n,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:e,repo:t,title:n,body:i}=s;if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and title are required"});let o=await _(`/repos/${e}/${t}/issues`,{method:"POST",body:{title:n,body:i||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:t,state:n,labels:i,since:o,assignee:a,sort:c,direction:u,limit:l}=s||{};if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",n||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",u||"desc"),i&&p.set("labels",Array.isArray(i)?i.join(","):i),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:n}=s||{};if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await _(`/repos/${e}/${t}/issues/${n}`);return i.pull_request?JSON.stringify({error:`#${n} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:i.number,title:i.title,body:i.body||"",state:i.state,stateReason:i.state_reason||null,labels:(i.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:i.assignee?.login||null,assignees:(i.assignees||[]).map(o=>o.login),user:i.user?.login,milestone:i.milestone?.title||null,comments:i.comments,url:i.html_url,createdAt:i.created_at,updatedAt:i.updated_at,closedAt:i.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:t,number:n,limit:i}=s||{};if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let o=await _(`/repos/${e}/${t}/issues/${n}/comments?per_page=${i||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:n,body:i}=s||{};if(!e||!t||!n||!i)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${n}/comments`,{method:"POST",body:{body:i}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:t,number:n,stateReason:i}=s||{};if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};i&&(o.state_reason=i);let a=await _(`/repos/${e}/${t}/issues/${n}`,{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:n}=s||{};if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let i=await _(`/repos/${e}/${t}/issues/${n}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:i.number,state:i.state,url:i.html_url})}case"github_label_issue":{let{owner:e,repo:t,number:n,labels:i,mode:o}=s||{};if(!e||!t||!n)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(i)?i:i?[i]:[];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/${n}`,{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/${n}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await _(`/repos/${e}/${t}/issues/${n}`);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/${n}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:n,labels:(Array.isArray(u)?u:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}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 Se=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,ke=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,ut=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,dt=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,be="in progress",_e="blocked";function Ae(r,s=[]){if(r==="closed")return"done";if(r!=="open")return"unknown";let e=(s||[]).map(String);return e.some(t=>Se.test(t))?"blocked":e.some(t=>ke.test(t))?"in_progress":"todo"}function C(r={}){let s=r.owner||process.env.GITHUB_OWNER,e=r.repo||process.env.GITHUB_REPO;if(!s||!e)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:s,repo:e}}function N(r){let s=JSON.parse(r);if(s&&s.error)throw new Error(s.error);return s}function ee(r,s={}){let e=r.labels||[],t=r.number,n=s.owner&&s.repo?`${s.owner}/${s.repo}#${t}`:`#${t}`;return{id:String(t),key:n,title:r.title||"",body:r.body||"",state:r.state||null,stateCategory:Ae(r.state,e),assignee:r.assignee||r.assignees&&r.assignees[0]||null,url:r.url||null,_raw:r}}var te={id:"github",toStateCategory:Ae,toNeutral:ee,IN_PROGRESS_LABEL:be,BLOCKED_LABEL:_e,async listCandidates(r={}){let s=r.ctx||{},{owner:e,repo:t}=C(s);return(N(await R.handleToolCall("github_list_issues",{owner:e,repo:t,state:r.state||"open",labels:r.labels,since:r.updatedAfter,limit:r.limit})).issues||[]).map(i=>ee(i,{owner:e,repo:t}))},async getTicket(r,s={}){let{owner:e,repo:t}=C(s),n=G(r);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${r}"`);let i=JSON.parse(await R.handleToolCall("github_get_issue",{owner:e,repo:t,number:n}));return i.error?null:ee(i,{owner:e,repo:t})},async getComments(r,s={}){let{owner:e,repo:t}=C(s),n=G(r);if(n==null)throw new Error(`Cannot parse GitHub issue number from "${r}"`);return(N(await R.handleToolCall("github_get_issue_comments",{owner:e,repo:t,number:n})).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(r,s,e={}){let{owner:t,repo:n}=C(e),i=G(r);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${r}"`);if(!s)throw new Error("body is required");let o=N(await R.handleToolCall("github_add_issue_comment",{owner:t,repo:n,number:i,body:s}));return{ok:!!o.ok,id:o.id?String(o.id):null}},async transition(r,s,e={}){let{owner:t,repo:n}=C(e),i=G(r);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${r}"`);let o=String(s||"");if(ut.test(o)){let a=N(await R.handleToolCall("github_close_issue",{owner:t,repo:n,number:i,stateReason:"completed"}));return{ok:!!a.ok,stateAfter:a.state||"closed",stateCategoryAfter:"done",_raw:a}}if(Se.test(o)){await we(t,n,i);let a=N(await R.handleToolCall("github_label_issue",{owner:t,repo:n,number:i,labels:[_e],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:a}}if(ke.test(o)){await we(t,n,i);let a=N(await R.handleToolCall("github_label_issue",{owner:t,repo:n,number:i,labels:[be],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:a}}if(dt.test(o)){let a=N(await R.handleToolCall("github_reopen_issue",{owner:t,repo:n,number:i}));return{ok:!!a.ok,stateAfter:a.state||"open",stateCategoryAfter:"todo",_raw:a}}return{ok:!1,error:`GitHub issues have no "${s}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(r,s,e,t={}){let{owner:n,repo:i}=C(t),o=G(r);if(o==null)throw new Error(`Cannot parse GitHub issue number from "${r}"`);if(!s)throw new Error("prUrl is required");let a=`${e?`${e}: `:"Linked PR: "}${s}`;return{ok:!!N(await R.handleToolCall("github_add_issue_comment",{owner:n,repo:i,number:o,body:a})).ok,via:"comment"}}};async function we(r,s,e){await R.handleToolCall("github_reopen_issue",{owner:r,repo:s,number:e})}function G(r){if(r==null)return null;if(typeof r=="number")return r;let s=/(\d+)\s*$/.exec(String(r));return s?Number(s[1]):null}var mt=(process.env.PLANE_API_URL||"https://api.plane.so/api/v1").replace(/\/+$/,""),yt=process.env.PLANE_WORKSPACE_SLUG||"",ft=process.env.PLANE_PROJECT_ID||"";function gt(){let r=process.env.PLANE_API_KEY||process.env.PLANE_OAUTH_TOKEN;if(!r)throw new Error("Plane is not connected: set PLANE_API_KEY (personal access token).");return r}function j(r={}){let s=r.workspaceSlug||yt,e=r.projectId||ft;if(!s||!e)throw new Error("Plane scope missing: provide workspaceSlug + projectId (env PLANE_WORKSPACE_SLUG / PLANE_PROJECT_ID or per-call ctx).");return{workspaceSlug:s,projectId:e}}async function O(r,s={}){let e=`${mt}${r}`;if(s.query&&Object.keys(s.query).length){let i=new URLSearchParams;for(let[a,c]of Object.entries(s.query))c!=null&&c!==""&&i.set(a,String(c));let o=i.toString();o&&(e+=(e.includes("?")?"&":"?")+o)}let t=await fetch(e,{method:s.method||"GET",headers:{"X-API-Key":gt(),Accept:"application/json",...s.body?{"Content-Type":"application/json"}:{},...s.headers},body:s.body?JSON.stringify(s.body):void 0});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Plane API ${t.status}: ${i.slice(0,300)}`)}let n=await t.text().catch(()=>"");if(!n||!n.trim())return{};try{return JSON.parse(n)}catch{return{raw:n}}}var ht={backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",cancelled:"done"},bt=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function se(r){return r?r.name&&bt.test(r.name)?"blocked":ht[r.group]||"unknown":"unknown"}var Re=new Map,_t=300*1e3;async function ve(r){let{workspaceSlug:s,projectId:e}=j(r),t=Re.get(e);if(t&&Date.now()-t.fetchedAt<_t)return t.states;let n=await O(`/workspaces/${encodeURIComponent(s)}/projects/${encodeURIComponent(e)}/states/`,{query:{per_page:100}}),i=(n.results||n||[]).map(o=>({id:o.id,name:o.name,group:o.group,color:o.color}));return Re.set(e,{fetchedAt:Date.now(),states:i}),i}function re(r){return String(r||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function wt(r,s){let e=re(s);if(!e)return null;let t=r.find(i=>re(i.name)===e);if(t)return t;let n={todo:["todo","backlog","open","unstarted"],inprogress:["inprogress","started","doing","wip"],done:["done","completed","closed","resolved","cancelled","canceled"],blocked:["blocked","onhold","waiting"]};for(let[,i]of Object.entries(n)){if(!i.some(c=>re(c)===e))continue;let o=e==="done"?"completed":e==="inprogress"?"started":"unstarted",a=r.find(c=>c.group===o);if(a)return a}return null}async function Ie(r,s){let t=(await ve(s).catch(()=>[])).find(c=>c.id===r.state)||null,{workspaceSlug:n,projectId:i}=j(s),o=s.projectIdentifier&&r.sequence_id!=null?`${s.projectIdentifier}-${r.sequence_id}`:r.sequence_id!=null?String(r.sequence_id):r.id,a=r.assignees||[];return{id:r.id,key:o,title:r.name||"",body:r.description_html||r.description_stripped||r.description||"",state:t?t.name:null,stateCategory:se(t),assignee:a.length?String(a[0]):null,url:s.baseWebUrl?`${s.baseWebUrl}/${n}/projects/${i}/issues/${r.id}`:null,_raw:r}}var ie={id:"plane",envKeys:["PLANE_API_KEY","PLANE_OAUTH_TOKEN","PLANE_API_URL","PLANE_WORKSPACE_SLUG","PLANE_PROJECT_ID"],planeFetch:O,toStateCategory:se,async listCandidates(r={}){let s=r.ctx||{},{workspaceSlug:e,projectId:t}=j(s),n={per_page:Math.min(Number(r.limit)||50,100),cursor:r.cursor};r.state&&(n.state=r.state),r.updatedAfter&&(n.updated_at__gte=r.updatedAfter);let o=(await O(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/`,{query:n})).results||[];return r.updatedAfter&&(o=o.filter(a=>String(a.updated_at)>String(r.updatedAfter))),Promise.all(o.map(a=>Ie(a,s)))},async getTicket(r,s={}){let{workspaceSlug:e,projectId:t}=j(s),n=await O(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(r)}/`);return!n||!n.id?null:Ie(n,s)},async getComments(r,s={}){let{workspaceSlug:e,projectId:t}=j(s);return((await O(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(r)}/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(r,s,e={}){let{workspaceSlug:t,projectId:n}=j(e),o=/<[a-z][\s\S]*>/i.test(String(s||""))?String(s):`<p>${String(s||"")}</p>`,a=await O(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(n)}/work-items/${encodeURIComponent(r)}/comments/`,{method:"POST",body:{comment_html:o}});return{ok:!!a.id,id:a.id||null,_raw:a}},async transition(r,s,e={}){let{workspaceSlug:t,projectId:n}=j(e),i=await ve(e),o=wt(i,s);if(!o)return{ok:!1,error:`No Plane state matches "${s}" in this project`,availableStates:i.map(c=>({id:c.id,name:c.name,group:c.group}))};let a=await O(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(n)}/work-items/${encodeURIComponent(r)}/`,{method:"PATCH",body:{state:o.id}});return{ok:!!a.id,stateAfter:o.name,stateCategoryAfter:se(o),_raw:a}},async linkPullRequest(r,s,e,t={}){let n=e?`${e}: `:"Linked PR: ";return{ok:!!(await this.addComment(r,`<p>${n}<a href="${s}">${s}</a></p>`,t)).ok,via:"comment"}}};var St=["todo","in_progress","done","blocked","unknown"];var $e={jira:Q,linear:X,github:te,plane:ie},kt="jira";function hr(r){let s=String(r||process.env.TRACKER_PROVIDER||kt).trim().toLowerCase(),e=$e[s];if(!e){let t=Object.keys($e).join(", ");throw new Error(`Unknown tracker provider "${s}". Known providers: ${t}.`)}return e}export{kt as DEFAULT_TRACKER_PROVIDER,$e as TRACKER_ADAPTERS,St as TRACKER_STATE_CATEGORIES,hr as getAdapter,te as githubAdapter,Q as jiraAdapter,X as linearAdapter,ie as planeAdapter};
235
+ `),instructions:"IMPORTANT: Show the contents field to the user - it contains the directory listing."})}catch(y){let S=String(y.message||y).split(m).join("***").replace(/x-access-token:[^@]*@/g,"x-access-token:***@");return JSON.stringify({error:`Clone failed: ${S}`})}}case"github_search_repos":{let{query:e,limit:t}=r;if(!e)return JSON.stringify({error:"query is required"});let i=await this.handleToolCall("github_list_repos",{limit:200},{}),s=JSON.parse(i);if(s.error)return JSON.stringify(s);let o=e.toLowerCase(),a=s.repos.filter(c=>c.name.toLowerCase().includes(o)||c.fullName.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o));return JSON.stringify({query:e,count:a.length,repos:a.slice(0,t||20)})}case"github_list_repos":{let{owner:e,type:t,sort:i,direction:s,limit:o,query:a}=r,c=100,u=o||200,l=[],p=f=>({name:f.name,fullName:f.full_name,private:f.private,description:f.description,language:f.language,defaultBranch:f.default_branch,updatedAt:f.updated_at,stars:f.stargazers_count,url:f.html_url,fullPath:f.full_name,webUrl:f.html_url,visibility:f.visibility||(f.private?"private":"public")}),m=f=>{if(!a)return!0;let S=String(a).toLowerCase();return f.name&&f.name.toLowerCase().includes(S)||f.fullName&&f.fullName.toLowerCase().includes(S)||f.description&&f.description.toLowerCase().includes(S)};if(!e){let f=1,S=!0;for(;S&&l.length<u;){let B=`/installation/repositories?per_page=${c}&page=${f}`,ee=(await _(B)).repositories||[];if(ee.length===0)break;l=l.concat(ee),S=ee.length===c,f++}let $=l.map(p).filter(m),D=$.slice(0,u),nt=$.length>D.length,Ae=D.filter(B=>B.private).length,Ie=D.filter(B=>!B.private).length;return JSON.stringify({count:D.length,repos:D,truncated:nt,privateCount:Ae,publicCount:Ie,message:`Found ${Ae} private and ${Ie} public repos`})}let g=await _(`/orgs/${e}`).then(()=>!0).catch(()=>!1),d=1,b=!0;for(;b&&l.length<u;){let f;g?f=`/orgs/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`:f=`/users/${e}/repos?per_page=${c}&page=${d}&type=${t||"all"}&sort=${i||"updated"}&direction=${s||"desc"}`;let S=await _(f),$=Array.isArray(S)?S:[];if($.length===0)break;l=l.concat($),b=$.length===c,d++}let h=l.map(p).filter(m),k=h.slice(0,u),y=h.length>k.length;return JSON.stringify({count:k.length,repos:k,truncated:y})}case"github_create_pr":{let{owner:e,repo:t,head:i,title:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, head (source branch), and title are required"});let o=r.base;if(!o)try{o=(await _(`/repos/${e}/${t}`)).default_branch||"main"}catch{o="main"}let a={title:String(s),head:String(i),base:String(o),body:r.body?String(r.body):"",draft:!!r.draft};try{let c=await _(`/repos/${e}/${t}/pulls`,{method:"POST",body:a});return JSON.stringify({success:!0,pr_url:c.html_url,number:c.number,branch:i,base:o,repo:`${e}/${t}`,provider:"github",draft:!!c.draft,state:c.state})}catch(c){let u=String(c.message||c);if(/GitHub API 422/.test(u))return JSON.stringify({success:!1,branch:i,base:o,repo:`${e}/${t}`,provider:"github",skippedReason:u});throw c}}case"github_merge_pr":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=r.mergeMethod||"squash";if(!["merge","squash","rebase"].includes(s))return JSON.stringify({error:`mergeMethod must be merge, squash, or rebase (got ${s})`});let o={merge_method:s};r.commitTitle&&(o.commit_title=String(r.commitTitle)),r.commitMessage&&(o.commit_message=String(r.commitMessage));try{let a=await _(`/repos/${e}/${t}/pulls/${i}/merge`,{method:"PUT",body:o});return JSON.stringify({success:!0,merged:!0,sha:a.sha,number:i,provider:"github"})}catch(a){let c=String(a.message||a);if(/GitHub API (405|409|404)/.test(c))return JSON.stringify({success:!1,number:i,provider:"github",skippedReason:c});throw a}}case"github_create_issue":{let{owner:e,repo:t,title:i,body:s}=r;if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and title are required"});let o=await _(`/repos/${e}/${t}/issues`,{method:"POST",body:{title:i,body:s||""}});return JSON.stringify({number:o.number,url:o.html_url,title:o.title})}case"github_list_issues":{let{owner:e,repo:t,state:i,labels:s,since:o,assignee:a,sort:c,direction:u,limit:l}=r||{};if(!e||!t)return JSON.stringify({error:"owner and repo are required"});let p=new URLSearchParams;p.set("state",i||"open"),p.set("per_page",String(l||30)),p.set("sort",c||"updated"),p.set("direction",u||"desc"),s&&p.set("labels",Array.isArray(s)?s.join(","):s),o&&p.set("since",o),a&&p.set("assignee",a);let m=await _(`/repos/${e}/${t}/issues?${p.toString()}`),g=(Array.isArray(m)?m:[]).filter(d=>!d.pull_request).map(d=>({number:d.number,title:d.title,state:d.state,labels:(d.labels||[]).map(b=>typeof b=="string"?b:b.name),assignee:d.assignee?.login||null,assignees:(d.assignees||[]).map(b=>b.login),user:d.user?.login,comments:d.comments,url:d.html_url,createdAt:d.created_at,updatedAt:d.updated_at}));return JSON.stringify({count:g.length,issues:g})}case"github_get_issue":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/issues/${i}`);return s.pull_request?JSON.stringify({error:`#${i} is a pull request, not an issue`,isPR:!0}):JSON.stringify({number:s.number,title:s.title,body:s.body||"",state:s.state,stateReason:s.state_reason||null,labels:(s.labels||[]).map(o=>typeof o=="string"?o:o.name),assignee:s.assignee?.login||null,assignees:(s.assignees||[]).map(o=>o.login),user:s.user?.login,milestone:s.milestone?.title||null,comments:s.comments,url:s.html_url,createdAt:s.created_at,updatedAt:s.updated_at,closedAt:s.closed_at})}case"github_get_issue_comments":{let{owner:e,repo:t,number:i,limit:s}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments?per_page=${s||100}`),a=(Array.isArray(o)?o:[]).map(c=>({id:c.id,user:c.user?.login,body:c.body||"",createdAt:c.created_at,updatedAt:c.updated_at,url:c.html_url}));return JSON.stringify({count:a.length,comments:a})}case"github_add_issue_comment":{let{owner:e,repo:t,number:i,body:s}=r||{};if(!e||!t||!i||!s)return JSON.stringify({error:"owner, repo, number, and body are required"});let o=await _(`/repos/${e}/${t}/issues/${i}/comments`,{method:"POST",body:{body:s}});return JSON.stringify({ok:!0,id:o.id,url:o.html_url})}case"github_close_issue":{let{owner:e,repo:t,number:i,stateReason:s}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let o={state:"closed"};s&&(o.state_reason=s);let a=await _(`/repos/${e}/${t}/issues/${i}`,{method:"PATCH",body:o});return JSON.stringify({ok:!0,number:a.number,state:a.state,stateReason:a.state_reason||null,url:a.html_url})}case"github_reopen_issue":{let{owner:e,repo:t,number:i}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let s=await _(`/repos/${e}/${t}/issues/${i}`,{method:"PATCH",body:{state:"open"}});return JSON.stringify({ok:!0,number:s.number,state:s.state,url:s.html_url})}case"github_label_issue":{let{owner:e,repo:t,number:i,labels:s,mode:o}=r||{};if(!e||!t||!i)return JSON.stringify({error:"owner, repo, and number are required"});let a=Array.isArray(s)?s:s?[s]:[];if(!a.length)return JSON.stringify({error:"labels (string or array) is required"});let c=o||"add";if(c==="set"){let l=await _(`/repos/${e}/${t}/issues/${i}`,{method:"PATCH",body:{labels:a}});return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}if(c==="remove"){for(let p of a)await _(`/repos/${e}/${t}/issues/${i}/labels/${encodeURIComponent(p)}`,{method:"DELETE"});let l=await _(`/repos/${e}/${t}/issues/${i}`);return JSON.stringify({ok:!0,number:l.number,labels:(l.labels||[]).map(p=>typeof p=="string"?p:p.name)})}let u=await _(`/repos/${e}/${t}/issues/${i}/labels`,{method:"POST",body:{labels:a}});return JSON.stringify({ok:!0,number:i,labels:(Array.isArray(u)?u:[]).map(l=>typeof l=="string"?l:l.name)})}default:return JSON.stringify({error:`Unknown tool: ${n}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"github_get_user",description:"Get the authenticated GitHub user profile and their organizations",input_schema:{type:"object",properties:{}}},{name:"github_list_orgs",description:"List GitHub organizations the authenticated user belongs to",input_schema:{type:"object",properties:{}}},{name:"github_list_repos",description:"List the repositories this token/installation can access (omit owner) \u2014 or a specific user/org's repos (pass owner). Use this to discover a RELATED repo worth cloning when a change's correctness depends on another accessible repo. Each repo carries a normalized { fullPath, name, webUrl, defaultBranch, visibility } shape (identical to gitlab_list_projects) alongside legacy fields, plus a truncated flag.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Org or user login. Omit to list every repo your token/installation can access."},query:{type:"string",description:"Optional term matched against repo name/full-name/description"},type:{type:"string",enum:["all","public","private","forks","sources","member"],description:"Filter by type (default: all)"},sort:{type:"string",enum:["created","updated","pushed","full_name"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max repos to return (default: 200, hard-capped at the fetch ceiling)"}}}},{name:"github_clone",description:'Clone a GitHub repository to the local filesystem. Use when user says "check out" or "clone" a repo.',input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner (user or org name)"},repo:{type:"string",description:"Repository name"},destination:{type:"string",description:"Destination directory. Accepts absolute paths, ~-prefixed paths, or relative names. Defaults to ~/zibby-repos/<repo>."}},required:["owner","repo"]}},{name:"github_search_repos",description:"Search accessible repositories by name or description. Use this when the user asks to find a specific repo.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search term to match against repo name or description (e.g., "electron", "my-app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_issues",description:"Search GitHub issues and pull requests",input_schema:{type:"object",properties:{query:{type:"string",description:'GitHub search query (e.g. "SCRUM-123", "login bug repo:org/app")'},limit:{type:"number",description:"Max results (default: 20)"}},required:["query"]}},{name:"github_search_code",description:"Search code across GitHub repositories by keyword",input_schema:{type:"object",properties:{query:{type:"string",description:'Code search query (e.g. "handleLogin", "class AuthService")'},repo:{type:"string",description:'Scope to a specific repo (e.g. "org/app"). Optional.'},language:{type:"string",description:'Filter by language (e.g. "javascript", "python"). Optional.'},limit:{type:"number",description:"Max results (default: 15)"}},required:["query"]}},{name:"github_get_pr",description:"Get details of a pull request \u2014 title, description, branch, stats",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_pr_diff",description:"Get the unified diff of a pull request \u2014 the actual code changes",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_files",description:"List files changed in a PR with per-file patches",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_list_pr_comments",description:"Get all review and issue comments on a PR",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"}},required:["owner","repo","number"]}},{name:"github_get_review_thread",description:"Read a PR review-comment THREAD given any comment id in it: the root review comment + all its replies, plus the anchored diff context (file, line, the original diff hunk). Use this to understand a human's reply to a previous review comment before replying in-thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread (the root or any reply)"}},required:["owner","repo","number","commentId"]}},{name:"github_reply_review_thread",description:"Reply IN-THREAD to an existing PR review-comment thread (a conversational reply nested under the thread the human commented on \u2014 NOT a fresh full review). Pass any comment id in the thread.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},commentId:{type:"number",description:"Any review-comment id in the thread to reply to"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","commentId","body"]}},{name:"github_reply_issue_comment",description:"Post a reply on a PR's top-level conversation (a new issue comment on the PR). Use when the human replied to a non-inline/summary comment rather than an inline review thread. Quote or @-mention for context since issue comments are not threaded.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The reply text (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_create_review",description:"Post a review on a pull request: a summary body plus optional inline comments anchored to file/line, with an event (COMMENT, APPROVE, or REQUEST_CHANGES). Use this to deliver a code review back to the PR.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number"},body:{type:"string",description:"The review summary (markdown). Shown as the top-level review comment."},event:{type:"string",enum:["COMMENT","APPROVE","REQUEST_CHANGES"],description:"Review verdict. Default COMMENT (no approval state). Use REQUEST_CHANGES for blocking issues."},comments:{type:"array",description:"Optional inline comments, each anchored to a changed line.",items:{type:"object",properties:{path:{type:"string",description:"File path as it appears in the diff"},line:{type:"number",description:"Line number in the file's NEW version (the right side of the diff)"},side:{type:"string",enum:["LEFT","RIGHT"],description:"RIGHT (new) or LEFT (old). Default RIGHT."},body:{type:"string",description:"The inline comment text (markdown)"}},required:["path","line","body"]}}},required:["owner","repo","number"]}},{name:"github_list_commits",description:"List commits on a branch \u2014 optionally bounded by since/until ISO dates (date-window listing) and paginated (keep calling with page+1 while hasMore is true). Optionally filtered by file path.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},branch:{type:"string",description:"Branch name (default: repo default branch)"},path:{type:"string",description:"Filter commits touching this file path"},limit:{type:"number",description:"Commits per page, max 100 (default: 20)"},since:{type:"string",description:'Only commits after this ISO-8601 date/time, e.g. "2026-01-01T00:00:00Z"'},until:{type:"string",description:"Only commits before this ISO-8601 date/time"},page:{type:"number",description:"Page number, 1-based (default 1)"}},required:["owner","repo"]}},{name:"github_get_commit",description:"Get details of a specific commit \u2014 message, stats, file diffs",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},sha:{type:"string",description:"Commit SHA (full or short)"},includePrs:{type:"boolean",description:"Also return the pull request(s) containing this commit ({number,title,state,merged,webUrl}) \u2014 the evidence link for contribution records (default false)"}},required:["owner","repo","sha"]}},{name:"github_get_file",description:"Read a file (or list a directory) from a GitHub repo. Works on any branch/ref.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},path:{type:"string",description:'File or directory path (e.g. "src/auth/login.ts")'},ref:{type:"string",description:"Branch, tag, or commit SHA (default: repo default branch)"}},required:["owner","repo","path"]}},{name:"github_create_pr",description:"Open a pull request on GitHub (POST /repos/{owner}/{repo}/pulls). The head (source) branch must already be pushed. Returns the REAL pr_url from GitHub \u2014 never fabricate a PR url. Expected business outcomes (no commits between base and head, a PR already exists for this branch, base==head, missing head) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},head:{type:"string",description:'Source branch to merge FROM (must already be pushed). For a cross-fork PR use "fork-owner:branch".'},base:{type:"string",description:"Target branch to merge INTO (default: the repo's default branch)"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description (markdown)"},draft:{type:"boolean",description:"Open as a draft PR (default: false)"}},required:["owner","repo","head","title"]}},{name:"github_merge_pr",description:"Merge a pull request on GitHub (PUT /repos/{owner}/{repo}/pulls/{number}/merge). mergeMethod is merge | squash | rebase (default squash). Returns { success:true, merged:true, sha } with the REAL merge SHA from GitHub. Expected non-mergeable outcomes (405 = draft / failing checks / branch protection, 409 = head sha moved / conflict, 404 = not found) return { success:false, skippedReason } rather than erroring.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"PR number to merge"},mergeMethod:{type:"string",enum:["merge","squash","rebase"],description:"How to merge (default: squash)"},commitTitle:{type:"string",description:"Title for the merge/squash commit (optional)"},commitMessage:{type:"string",description:"Body for the merge/squash commit (optional)"}},required:["owner","repo","number"]}},{name:"github_create_issue",description:"Create a GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},title:{type:"string",description:"Issue title"},body:{type:"string",description:"Issue body (markdown)"}},required:["owner","repo","title"]}},{name:"github_list_issues",description:"List issues in a repo (excludes pull requests). Filter by state, labels, and an updated-since cursor for polling.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},state:{type:"string",enum:["open","closed","all"],description:"Filter by state (default: open)"},labels:{type:"array",items:{type:"string"},description:"Only issues carrying ALL of these labels"},since:{type:"string",description:"ISO-8601 timestamp; only issues updated at/after this (polling cursor)"},assignee:{type:"string",description:'Filter by assignee login, "none", or "*"'},sort:{type:"string",enum:["created","updated","comments"],description:"Sort field (default: updated)"},direction:{type:"string",enum:["asc","desc"],description:"Sort direction (default: desc)"},limit:{type:"number",description:"Max issues (default: 30, max 100 per page)"}},required:["owner","repo"]}},{name:"github_get_issue",description:"Get a single GitHub issue with full detail (title, body, state, labels, assignee, url)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_get_issue_comments",description:"Get the comment thread on a GitHub issue (chronological)",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},limit:{type:"number",description:"Max comments (default: 100)"}},required:["owner","repo","number"]}},{name:"github_add_issue_comment",description:"Add a comment to a GitHub issue. Also the way to record a PR link on an issue (post a markdown link).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},body:{type:"string",description:"Comment body (markdown)"}},required:["owner","repo","number","body"]}},{name:"github_close_issue",description:"Close a GitHub issue. Optionally set the close reason (completed or not_planned).",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},stateReason:{type:"string",enum:["completed","not_planned"],description:"Why the issue was closed (optional)"}},required:["owner","repo","number"]}},{name:"github_reopen_issue",description:"Reopen a closed GitHub issue",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"}},required:["owner","repo","number"]}},{name:"github_label_issue",description:"Add, set (replace all), or remove labels on a GitHub issue. Labels back state-like transitions on GitHub.",input_schema:{type:"object",properties:{owner:{type:"string",description:"Repository owner"},repo:{type:"string",description:"Repository name"},number:{type:"number",description:"Issue number"},labels:{type:"array",items:{type:"string"},description:"Label name(s)"},mode:{type:"string",enum:["add","set","remove"],description:"add appends, set replaces all, remove deletes (default: add)"}},required:["owner","repo","number","labels"]}}]};var Qe=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i,Ve=/\b(in[\s-]?progress|wip|doing|started|in[\s-]?review|review)\b/i,or=/\b(done|closed|complete|completed|resolved|fixed|merged|shipped)\b/i,ar=/\b(todo|to[\s-]?do|open|backlog|reopen|new)\b/i,ze="in progress",We="blocked";function Ze(n,r=[]){if(n==="closed")return"done";if(n!=="open")return"unknown";let e=(r||[]).map(String);return e.some(t=>Qe.test(t))?"blocked":e.some(t=>Ve.test(t))?"in_progress":"todo"}function K(n={}){let r=n.owner||process.env.GITHUB_OWNER,e=n.repo||process.env.GITHUB_REPO;if(!r||!e)throw new Error("GitHub scope missing: provide {owner, repo} via ctx or env GITHUB_OWNER / GITHUB_REPO.");return{owner:r,repo:e}}function j(n){let r=JSON.parse(n);if(r&&r.error)throw new Error(r.error);return r}function be(n,r={}){let e=n.labels||[],t=n.number,i=r.owner&&r.repo?`${r.owner}/${r.repo}#${t}`:`#${t}`;return{id:String(t),key:i,title:n.title||"",body:n.body||"",state:n.state||null,stateCategory:Ze(n.state,e),assignee:n.assignee||n.assignees&&n.assignees[0]||null,url:n.url||null,_raw:n}}var _e={id:"github",toStateCategory:Ze,toNeutral:be,IN_PROGRESS_LABEL:ze,BLOCKED_LABEL:We,async listCandidates(n={}){let r=n.ctx||{},{owner:e,repo:t}=K(r);return(j(await v.handleToolCall("github_list_issues",{owner:e,repo:t,state:n.state||"open",labels:n.labels,since:n.updatedAfter,limit:n.limit})).issues||[]).map(s=>be(s,{owner:e,repo:t}))},async getTicket(n,r={}){let{owner:e,repo:t}=K(r),i=Y(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let s=JSON.parse(await v.handleToolCall("github_get_issue",{owner:e,repo:t,number:i}));return s.error?null:be(s,{owner:e,repo:t})},async getComments(n,r={}){let{owner:e,repo:t}=K(r),i=Y(n);if(i==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);return(j(await v.handleToolCall("github_get_issue_comments",{owner:e,repo:t,number:i})).comments||[]).map(o=>({id:String(o.id),author:o.user||"Unknown",body:o.body||"",createdAt:o.createdAt||null,updatedAt:o.updatedAt||null,_raw:o})).sort((o,a)=>String(a.createdAt).localeCompare(String(o.createdAt)))},async addComment(n,r,e={}){let{owner:t,repo:i}=K(e),s=Y(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("body is required");let o=j(await v.handleToolCall("github_add_issue_comment",{owner:t,repo:i,number:s,body:r}));return{ok:!!o.ok,id:o.id?String(o.id):null}},async transition(n,r,e={}){let{owner:t,repo:i}=K(e),s=Y(n);if(s==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);let o=String(r||"");if(or.test(o)){let a=j(await v.handleToolCall("github_close_issue",{owner:t,repo:i,number:s,stateReason:"completed"}));return{ok:!!a.ok,stateAfter:a.state||"closed",stateCategoryAfter:"done",_raw:a}}if(Qe.test(o)){await Ye(t,i,s);let a=j(await v.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[We],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"blocked",via:"label",_raw:a}}if(Ve.test(o)){await Ye(t,i,s);let a=j(await v.handleToolCall("github_label_issue",{owner:t,repo:i,number:s,labels:[ze],mode:"add"}));return{ok:!!a.ok,stateAfter:"open",stateCategoryAfter:"in_progress",via:"label",_raw:a}}if(ar.test(o)){let a=j(await v.handleToolCall("github_reopen_issue",{owner:t,repo:i,number:s}));return{ok:!!a.ok,stateAfter:a.state||"open",stateCategoryAfter:"todo",_raw:a}}return{ok:!1,error:`GitHub issues have no "${r}" state. Representable targets: open/todo, in progress, blocked, done/closed.`}},async linkPullRequest(n,r,e,t={}){let{owner:i,repo:s}=K(t),o=Y(n);if(o==null)throw new Error(`Cannot parse GitHub issue number from "${n}"`);if(!r)throw new Error("prUrl is required");let a=`${e?`${e}: `:"Linked PR: "}${r}`;return{ok:!!j(await v.handleToolCall("github_add_issue_comment",{owner:i,repo:s,number:o,body:a})).ok,via:"comment"}}};async function Ye(n,r,e){await v.handleToolCall("github_reopen_issue",{owner:n,repo:r,number:e})}function Y(n){if(n==null)return null;if(typeof n=="number")return n;let r=/(\d+)\s*$/.exec(String(n));return r?Number(r[1]):null}var cr=(process.env.PLANE_API_URL||"https://api.plane.so/api/v1").replace(/\/+$/,""),lr=process.env.PLANE_WORKSPACE_SLUG||"",ur=process.env.PLANE_PROJECT_ID||"";function pr(){let n=process.env.PLANE_API_KEY||process.env.PLANE_OAUTH_TOKEN;if(!n)throw new Error("Plane is not connected: set PLANE_API_KEY (personal access token).");return n}function P(n={}){let r=n.workspaceSlug||lr,e=n.projectId||ur;if(!r||!e)throw new Error("Plane scope missing: provide workspaceSlug + projectId (env PLANE_WORKSPACE_SLUG / PLANE_PROJECT_ID or per-call ctx).");return{workspaceSlug:r,projectId:e}}async function L(n,r={}){let e=`${cr}${n}`;if(r.query&&Object.keys(r.query).length){let s=new URLSearchParams;for(let[a,c]of Object.entries(r.query))c!=null&&c!==""&&s.set(a,String(c));let o=s.toString();o&&(e+=(e.includes("?")?"&":"?")+o)}let t=await N(e,{method:r.method||"GET",headers:{"X-API-Key":pr(),Accept:"application/json",...r.body?{"Content-Type":"application/json"}:{},...r.headers},body:r.body?JSON.stringify(r.body):void 0},{kind:"api",what:`Plane ${r.method||"GET"} ${n}`});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Plane API ${t.status}: ${s.slice(0,300)}`)}let i=await t.text().catch(()=>"");if(!i||!i.trim())return{};try{return JSON.parse(i)}catch{return{raw:i}}}var dr={backlog:"todo",unstarted:"todo",started:"in_progress",completed:"done",cancelled:"done"},mr=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function ke(n){return n?n.name&&mr.test(n.name)?"blocked":dr[n.group]||"unknown":"unknown"}var Xe=new Map,fr=300*1e3;async function tt(n){let{workspaceSlug:r,projectId:e}=P(n),t=Xe.get(e);if(t&&Date.now()-t.fetchedAt<fr)return t.states;let i=await L(`/workspaces/${encodeURIComponent(r)}/projects/${encodeURIComponent(e)}/states/`,{query:{per_page:100}}),s=(i.results||i||[]).map(o=>({id:o.id,name:o.name,group:o.group,color:o.color}));return Xe.set(e,{fetchedAt:Date.now(),states:s}),s}function we(n){return String(n||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_::"'`]/g,"")}function yr(n,r){let e=we(r);if(!e)return null;let t=n.find(s=>we(s.name)===e);if(t)return t;let i={todo:["todo","backlog","open","unstarted"],inprogress:["inprogress","started","doing","wip"],done:["done","completed","closed","resolved","cancelled","canceled"],blocked:["blocked","onhold","waiting"]};for(let[,s]of Object.entries(i)){if(!s.some(c=>we(c)===e))continue;let o=e==="done"?"completed":e==="inprogress"?"started":"unstarted",a=n.find(c=>c.group===o);if(a)return a}return null}async function et(n,r){let t=(await tt(r).catch(()=>[])).find(c=>c.id===n.state)||null,{workspaceSlug:i,projectId:s}=P(r),o=r.projectIdentifier&&n.sequence_id!=null?`${r.projectIdentifier}-${n.sequence_id}`:n.sequence_id!=null?String(n.sequence_id):n.id,a=n.assignees||[];return{id:n.id,key:o,title:n.name||"",body:n.description_html||n.description_stripped||n.description||"",state:t?t.name:null,stateCategory:ke(t),assignee:a.length?String(a[0]):null,url:r.baseWebUrl?`${r.baseWebUrl}/${i}/projects/${s}/issues/${n.id}`:null,_raw:n}}var Se={id:"plane",envKeys:["PLANE_API_KEY","PLANE_OAUTH_TOKEN","PLANE_API_URL","PLANE_WORKSPACE_SLUG","PLANE_PROJECT_ID"],planeFetch:L,toStateCategory:ke,async listCandidates(n={}){let r=n.ctx||{},{workspaceSlug:e,projectId:t}=P(r),i={per_page:Math.min(Number(n.limit)||50,100),cursor:n.cursor};n.state&&(i.state=n.state),n.updatedAfter&&(i.updated_at__gte=n.updatedAfter);let o=(await L(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/`,{query:i})).results||[];return n.updatedAfter&&(o=o.filter(a=>String(a.updated_at)>String(n.updatedAfter))),Promise.all(o.map(a=>et(a,r)))},async getTicket(n,r={}){let{workspaceSlug:e,projectId:t}=P(r),i=await L(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/`);return!i||!i.id?null:et(i,r)},async getComments(n,r={}){let{workspaceSlug:e,projectId:t}=P(r);return((await L(`/workspaces/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/work-items/${encodeURIComponent(n)}/comments/`,{query:{per_page:100}})).results||[]).map(o=>({id:o.id,author:o.actor||o.actor_detail?.display_name||"Unknown",body:o.comment_html||o.comment_stripped||"",createdAt:o.created_at||null,updatedAt:o.updated_at||null,_raw:o})).sort((o,a)=>String(a.createdAt).localeCompare(String(o.createdAt)))},async addComment(n,r,e={}){let{workspaceSlug:t,projectId:i}=P(e),o=/<[a-z][\s\S]*>/i.test(String(r||""))?String(r):`<p>${String(r||"")}</p>`,a=await L(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/comments/`,{method:"POST",body:{comment_html:o}});return{ok:!!a.id,id:a.id||null,_raw:a}},async transition(n,r,e={}){let{workspaceSlug:t,projectId:i}=P(e),s=await tt(e),o=yr(s,r);if(!o)return{ok:!1,error:`No Plane state matches "${r}" in this project`,availableStates:s.map(c=>({id:c.id,name:c.name,group:c.group}))};let a=await L(`/workspaces/${encodeURIComponent(t)}/projects/${encodeURIComponent(i)}/work-items/${encodeURIComponent(n)}/`,{method:"PATCH",body:{state:o.id}});return{ok:!!a.id,stateAfter:o.name,stateCategoryAfter:ke(o),_raw:a}},async linkPullRequest(n,r,e,t={}){let i=e?`${e}: `:"Linked PR: ";return{ok:!!(await this.addComment(n,`<p>${i}<a href="${r}">${r}</a></p>`,t)).ok,via:"comment"}}};var gr=["todo","in_progress","done","blocked","unknown"];var rt={jira:fe,linear:he,github:_e,plane:Se},hr="jira";function wn(n){let r=String(n||process.env.TRACKER_PROVIDER||hr).trim().toLowerCase(),e=rt[r];if(!e){let t=Object.keys(rt).join(", ");throw new Error(`Unknown tracker provider "${r}". Known providers: ${t}.`)}return e}export{hr as DEFAULT_TRACKER_PROVIDER,rt as TRACKER_ADAPTERS,gr as TRACKER_STATE_CATEGORIES,wn as getAdapter,_e as githubAdapter,fe as jiraAdapter,he as linearAdapter,Se as planeAdapter};