import{createRequire as K}from"module";import{resolveIntegrationToken as x,clearTokenCache as L}from"@zibby/core/backend-client.js";var C=Object.freeze({SENTRY:"sentry",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",SLACK:"slack",LARK:"lark",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE:"google",PLANE:"plane",LINEAR:"linear",FIGMA:"figma",HUBSPOT:"hubspot",OPEN_DESIGN:"open_design",LINKEDIN_PERSONAL:"linkedin_personal",LINKEDIN_BUSINESS:"linkedin_business",DISCORD:"discord"}),Q=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",connectPath:"/integrations?provider=lark"},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"},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 E=K(import.meta.url);function D(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return E.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var B=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function U(s,i){if(!i||!i.length)return s;let e=s;for(let t of i)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 w(s,i=0){if(!Array.isArray(s))return"";let e=[];for(let t of s){if(t.type==="text"){e.push(U(t.text||"",t.marks));continue}if(t.type==="hardBreak"){e.push(`
`);continue}if(t.type==="rule"){e.push(`
---
`);continue}let a=t.content?w(t.content,i+1):"";if(t.type==="listItem")e.push(a);else if(t.type==="bulletList"){let n=(t.content||[]).map(o=>`- ${w(o.content||[],i+1).trim()}`);e.push(`
${n.join(`
`)}
`)}else if(t.type==="orderedList"){let n=(t.content||[]).map((o,r)=>`${r+1}. ${w(o.content||[],i+1).trim()}`);e.push(`
${n.join(`
`)}
`)}else if(t.type==="heading"){let n=t.attrs?.level||2;e.push(`

${"#".repeat(n)} ${a.trim()}

`)}else B.has(t.type)?e.push(`

${a}
`):e.push(a)}return e.join("").replace(/\n{3,}/g,`

`)}function S(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_:："'`]/g,"")}function N(s){return S(s).replace(/[a-z0-9]+/g,"")}function I(s,i){let e=S(s),t=S(i);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let a=u=>{let d=new Map;for(let m=0;m<u.length-1;m++){let g=u.slice(m,m+2);d.set(g,(d.get(g)||0)+1)}return d},n=a(e),o=a(t),r=0,c=0,p=0;for(let u of n.values())c+=u;for(let u of o.values())p+=u;for(let[u,d]of n.entries()){let m=o.get(u)||0;r+=Math.min(d,m)}return 2*r/Math.max(1,c+p)}function b(s){return String(s||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_:："'`]/g,"")}function M(s,i=[]){let e=Array.isArray(i)?i:[];if(e.length===0)return{requested:s||null,resolved:null,strategy:"none"};let t=e.filter(r=>!r.subtask),a=t.length>0?t:e,n=b(s);if(n){let r=a.find(u=>b(u.name)===n);if(r)return{requested:s,resolved:r,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 u of Object.values(c)){if(!u.some(m=>b(m)===n))continue;let d=a.find(m=>u.some(g=>b(g)===b(m.name)));if(d)return{requested:s,resolved:d,strategy:"alias"}}let p=a.map(u=>({t:u,score:I(s,u.name)})).sort((u,d)=>d.score-u.score);if(p[0]&&p[0].score>=.5)return{requested:s,resolved:p[0].t,strategy:"fuzzy"}}let o=["task","story","bug","improvement","epic"];for(let r of o){let c=a.find(p=>b(p.name)===r);if(c)return{requested:s||null,resolved:c,strategy:"default-preferred"}}return{requested:s||null,resolved:a[0],strategy:"default-first"}}async function q(s){let i=`projectKeys=${encodeURIComponent(s)}&expand=projects.issuetypes`,e=await y(`/rest/api/3/issue/createmeta?${i}`),t=Array.isArray(e?.projects)?e.projects:[],n=t.find(r=>String(r?.key||"").toUpperCase()===String(s||"").toUpperCase())||t[0]||null;return(Array.isArray(n?.issuetypes)?n.issuetypes:[]).map(r=>({id:r.id,name:r.name,subtask:!!r.subtask,description:r.description||null}))}async function P(s,i){if(!s)throw new Error("projectKey is required");let e="sprint is not EMPTY";i==="active"?e="sprint in openSprints()":i==="closed"?e="sprint in closedSprints()":i==="future"&&(e="sprint in futureSprints()");let t=`project = ${s} AND ${e} ORDER BY updated DESC`,a=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,n=await y(`/rest/api/3/search/jql?${a}`),o=new Map;for(let r of n.issues||[])for(let c of r.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((r,c)=>{let p={active:0,future:1,closed:2},u=(p[r.state]??3)-(p[c.state]??3);return u!==0?u:String(c.startDate||"").localeCompare(String(r.startDate||""))})}function G(s,{sprintId:i,sprintName:e,target:t}={}){let a=Array.isArray(s)?s:[];if(!a.length)return{sprint:null,selectedBy:"none"};if(i!=null&&String(i).trim()!=="")return{sprint:a.find(r=>String(r.id)===String(i))||null,selectedBy:"id"};if(e&&String(e).trim()){let o=String(e).trim(),r=a.find(p=>String(p.name||"").toLowerCase()===o.toLowerCase());if(r)return{sprint:r,selectedBy:"name-exact"};let c=a.map(p=>({s:p,score:I(o,p.name||"")})).sort((p,u)=>u.score-p.score);return c[0]&&c[0].score>=.5?{sprint:c[0].s,selectedBy:"name-fuzzy"}:{sprint:null,selectedBy:"name-none"}}let n=String(t||"current").trim().toLowerCase();return n==="active"||n==="current"||n==="latest"?{sprint:a[0],selectedBy:n}:{sprint:a[0],selectedBy:"default"}}function Y(s,i){let e=s?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(i)):!1}async function F({issueKey:s,projectKey:i,sprintId:e,attempts:t=3,delayMs:a=450}){let n=[];for(let o=0;o<t;o++){try{let r=`project = ${i} AND key = ${s} AND sprint = ${e}`,c=`jql=${encodeURIComponent(r)}&maxResults=1&fields=key,status`,p=await y(`/rest/api/3/search/jql?${c}`);if(Number(p?.total||0)>0)return n.push({attempt:o+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:n};let d=await y(`/rest/api/3/issue/${s}?fields=customfield_10020,status`),m=Y(d,e);if(n.push({attempt:o+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:n}}catch(r){n.push({attempt:o+1,error:String(r?.message||r)})}o<t-1&&await new Promise(r=>setTimeout(r,a))}return{ok:!1,method:"none",traces:n}}async function O({issueKey:s,projectKey:i,sprintId:e,sprintName:t,target:a}){if(!s)return{ok:!1,error:"issueKey is required"};let n=i;if(!n&&(n=(await y(`/rest/api/3/issue/${s}?fields=project`))?.fields?.project?.key||null,!n))return{ok:!1,error:`Could not resolve project for ${s}`};let o=await P(n,"active");if(!o.length)return{ok:!1,error:`No assignable active sprint found for project ${n}`};let{sprint:r,selectedBy:c}=G(o,{sprintId:e,sprintName:t,target:a});if(!r)return{ok:!1,error:`No matching sprint found in ${n}`,requested:{sprintId:e??null,sprintName:t??null,target:a??"current"},availableSprints:o.map(d=>({id:d.id,name:d.name,state:d.state}))};await y(`/rest/api/3/issue/${s}`,{method:"PUT",body:{fields:{customfield_10020:Number(r.id)}}});let p=await F({issueKey:s,projectKey:n,sprintId:r.id}),u=p.ok;return{ok:u,issueKey:s,projectKey:n,sprintId:r.id,sprintName:r.name,selectedBy:c,verifiedBy:p.method,verified:u,verificationTrace:p.traces,warning:u?null:`Sprint assignment attempted but verification did not find ${s} in sprint ${r.id}`}}async function y(s,i={}){let e=async()=>{let{token:t,cloudId:a}=await x("jira");if(typeof t!="string"||!t)throw new Error(`Invalid jira token type: ${typeof t}`);if(!a)throw new Error("Invalid jira cloudId: missing");let n=`https://api.atlassian.com/ex/jira/${a}${s}`,o=await fetch(n,{method:i.method||"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...i.body?{"Content-Type":"application/json"}:{},...i.headers},body:i.body?JSON.stringify(i.body):void 0});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Jira API ${o.status}: ${c.slice(0,300)}`)}let r=await o.text().catch(()=>"");if(!r||!r.trim())return{};try{return JSON.parse(r)}catch{return{raw:r}}};try{return await e()}catch(t){let a=String(t?.message||t||"").toLowerCase();if(!(a.includes("token")||a.includes("401")||a.includes("403")||a.includes("substring")))throw t;return L("jira"),e()}}var v={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:C.JIRA,envKeys:["ATLASSIAN_ACCESS_TOKEN","ATLASSIAN_CLOUD_ID"],description:"Zibby Jira MCP Server (OAuth Bearer)",promptFragment:`## Jira (connected)
You have direct access to the user's Jira. Use these tools proactively:

### Issue tools
- jira_search: Search issues with JQL (e.g. "project = PROJ AND status != Done ORDER BY updated DESC")
- jira_get_issue: Get full details of a ticket by key (e.g. PROJ-123)
- jira_list_statuses: List available Jira statuses (global or project-specific)
- jira_list_issue_types: List issue types allowed for issue creation in a project
- jira_create_issue: Create a new ticket (requires projectKey + summary)
- jira_get_comments: Get comments on a ticket (newest first) \u2014 use this to find testing steps, notes, etc.
- jira_add_comment: Add a comment to a ticket
- jira_edit_issue: Update fields (summary, labels, priority, story points)
- jira_transition_issue: Move a ticket to a different status (pass transitionId or toStatus)

### Project & sprint tools
- jira_list_projects: List all projects
- jira_list_sprints: List sprints for a project (filter by state: active/closed/future)
- jira_get_sprint_issues: Get all issues in a sprint \u2014 filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "In Progress"). Returns status breakdown.
- jira_move_issue_to_sprint: Move an issue to a sprint (current/active/latest/by-id/by-name) and verify membership.

### Sprint membership updates
- To move an issue into a sprint, use jira_edit_issue with fields.customfield_10020 set to sprint numeric id.
- Example: jira_edit_issue({ issueKey: "PROJ-123", fields: { customfield_10020: 10 } })
- Always verify by calling jira_get_sprint_issues(sprintId, projectKey) and checking the issue key is present.
- For "create and place into current sprint" requests, use a generic atomic flow:
  - Prefer jira_create_issue with moveToSprint=true (optionally sprintId/sprintName/target)
  - Or create first, then use jira_move_issue_to_sprint
  - Always report verified sprint membership result (not just status transition)

### Search strategy (important!)
1. **Board/sprint first**: When the user asks about "my board", "testing tickets", or "what's in progress", ALWAYS use the sprint path: jira_list_sprints (state: active) \u2192 jira_get_sprint_issues. This finds ALL tickets regardless of age.
2. **Project-scoped search**: If you know the project key, use "project = KEY AND status != Done ORDER BY updated DESC" \u2014 no date filter needed when scoped to a project.
3. **Global search (last resort)**: Only use broad JQL like "created >= -365d" when you genuinely don't know the project. Never use -90d \u2014 it misses older tickets still in testing.
4. **Remember the board**: After finding the user's project/board, store it in memory (memory_store) so you go straight there next time.
5. **Status discovery**: NEVER use jira_search with guessed status keywords to determine whether a status exists. Use jira_list_statuses (project-scoped when possible) and/or jira_transition_issue(issueKey) without transitionId.

When the user asks about "my tickets" or "my board" and you know their project from memory, go directly to that project's active sprint.
When the user asks about projects or boards, call jira_list_projects.
When the user asks about sprints: jira_list_sprints \u2192 jira_get_sprint_issues.
When user asks to move ticket into a sprint, do NOT use status transition. Use jira_move_issue_to_sprint(issueKey, projectKey?, sprintId|sprintName|target) and report verified result.
When the user asks about testing steps, test cases, or wants to run tests for a ticket: call jira_get_comments \u2014 testing steps are typically written in the ticket's comments, not the description.
JQL must be bounded (Jira rejects unbounded queries). Use "project = KEY AND status != Done" for project queries. Use "created >= -365d ORDER BY updated DESC" for global queries.

### Transition workflow (MANDATORY)
When user asks to move/transition ticket status:
1. If user explicitly gives a target status (e.g. "move to \u8FDB\u884C\u4E2D", "move that in progress", "move to AI \u9A8C\u6536"), call jira_transition_issue with issueKey + toStatus directly. Do NOT call list-only mode first.
2. If target is ambiguous or missing, call jira_transition_issue({ issueKey }) with no transitionId to list available transitions.
3. Pick the correct transition from returned list (match by "to" status name, not guesswork), then call jira_transition_issue with transitionId.
4. Call jira_get_issue(issueKey) to verify final status before claiming success.
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.
6. IMPORTANT: When target is clear, complete transition + verification in SAME turn. Do NOT stop after listing options.`,resolve(){let s=D();if(!s)return null;let i={};for(let e of this.envKeys)process.env[e]&&(i[e]=process.env[e]);return process.env.ATLASSIAN_INSTANCE_URL&&(i.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[s],env:i,description:this.description}},async handleToolCall(s,i){try{switch(s){case"jira_list_projects":{let e=await y("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(a=>({id:a.id,key:a.key,name:a.name,style:a.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=i||{};if(e){let n=await y(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),o=Array.isArray(n)?n:[],r=new Map;for(let p of o)for(let u of p.statuses||[])u?.id&&(r.has(u.id)||r.set(u.id,{id:u.id,name:u.name,category:u.statusCategory?.name||null}));let c=[...r.values()].sort((p,u)=>String(p.name).localeCompare(String(u.name)));return JSON.stringify({scope:"project",projectKey:e,count:c.length,statuses:c})}let t=await y("/rest/api/3/status"),a=(Array.isArray(t)?t:[]).map(n=>({id:n.id,name:n.name,category:n.statusCategory?.name||null})).sort((n,o)=>String(n.name).localeCompare(String(o.name)));return JSON.stringify({scope:"global",count:a.length,statuses:a})}case"jira_list_issue_types":{let{projectKey:e}=i||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await q(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=i.jql||"",t=i.maxResults||20;e.replace(/\s*ORDER\s+BY\s+.*/i,"").trim()||(e=`created >= -365d ${e}`.trim());let n=`jql=${encodeURIComponent(e)}&maxResults=${t}&fields=summary,status,assignee,priority,updated,issuetype,project`,r=((await y(`/rest/api/3/search/jql?${n}`)).issues||[]).map(c=>({key:c.key,project:c.fields?.project?.key,summary:c.fields?.summary,status:c.fields?.status?.name,assignee:c.fields?.assignee?.displayName||"Unassigned",priority:c.fields?.priority?.name,type:c.fields?.issuetype?.name}));return JSON.stringify({count:r.length,issues:r})}case"jira_get_issue":{let e=i.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await y(`/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:a,description:n,priority:o,labels:r,assigneeId:c,moveToSprint:p,moveToActiveSprint:u,sprintId:d,sprintName:m,target:g}=i;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let l={requested:a||null,resolved:null,strategy:"none"},h=[];try{h=await q(e),l=M(a,h)}catch{}let f={project:{key:e},summary:t,issuetype:l?.resolved?.id?{id:l.resolved.id}:{name:a||"Task"}};n&&(f.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:n}]}]}),o&&(f.priority={name:o}),r?.length&&(f.labels=r),c&&(f.assignee={id:c});let j=await y("/rest/api/3/issue",{method:"POST",body:{fields:f}}),_={ok:!0,key:j.key,id:j.id,self:j.self};return l?.resolved&&(_.issueType=l.resolved.name,_.issueTypeResolution=l.strategy,l.strategy!=="exact"&&l.requested&&b(l.requested)!==b(l.resolved.name)&&(_.issueTypeWarning=`Requested "${l.requested}" is not available in ${e}; used "${l.resolved.name}" instead.`)),h.length>0&&(_.availableIssueTypes=h.map(k=>k.name)),(p||u)&&(_.sprintMove=await O({issueKey:j.key,projectKey:e,sprintId:d,sprintName:m,target:g})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:e,state:t}=i,a=await P(e,t);return JSON.stringify({count:a.length,sprints:a})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:a,sprintName:n,target:o}=i||{},r=await O({issueKey:e,projectKey:t,sprintId:a,sprintName:n,target:o||"current"});return JSON.stringify(r)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:a,sprintName:n,target:o}=i||{},r=await O({issueKey:e,projectKey:t,sprintId:a,sprintName:n,target:o});return JSON.stringify(r)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:a,status:n,maxResults:o}=i;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let r=o||50,c=t?`sprint = ${t}`:`sprint = "${e}"`,p=a?`project = ${a} AND `:"",u=n?` AND status = "${n}"`:"",d=`${p}${c}${u} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(d)}&maxResults=${r}&fields=summary,status,assignee,priority,issuetype,project`,g=await y(`/rest/api/3/search/jql?${m}`),l=(g.issues||[]).map(f=>({key:f.key,project:f.fields?.project?.key,summary:f.fields?.summary,status:f.fields?.status?.name,assignee:f.fields?.assignee?.displayName||"Unassigned",priority:f.fields?.priority?.name,type:f.fields?.issuetype?.name})),h={};for(let f of l)h[f.status]=(h[f.status]||0)+1;return JSON.stringify({count:l.length,total:g.total||l.length,statusCounts:h,issues:l})}case"jira_get_comments":{let{issueKey:e,maxResults:t}=i;if(!e)return JSON.stringify({error:"issueKey is required"});let n=await y(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),o=(n.comments||[]).map(r=>{let c="";return r.body?.content&&(c=w(r.body.content)),{id:r.id,author:r.author?.displayName||"Unknown",body:c,created:r.created,updated:r.updated}});return JSON.stringify({count:o.length,total:n.total||o.length,comments:o})}case"jira_add_comment":{let{issueKey:e,body:t}=i;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await y(`/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}=i;return!e||!t?JSON.stringify({error:"issueKey and fields are required"}):(await y(`/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:a,statusName:n,status:o}=i;if(!e)return JSON.stringify({error:"issueKey is required"});let r=String(a||n||o||"").trim();if(!t&&!r){let d=((await y(`/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:d})}let c=t;if(!c){let d=(await y(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=S(r),g=d.find(l=>S(l?.name||"")===m||S(l?.to?.name||"")===m);if(!g){let l=N(r);l.length>=2&&(g=d.find(h=>{let f=N(h?.name||""),j=N(h?.to?.name||""),_=f.length>=2&&(f.includes(l)||l.includes(f)),k=j.length>=2&&(j.includes(l)||l.includes(j));return _||k}))}if(!g){let l=d.map(_=>{let k=I(r,_?.name||""),J=I(r,_?.to?.name||"");return{t:_,score:Math.max(k,J)}}).sort((_,k)=>k.score-_.score),h=l[0],f=l[1];h&&h.score>=.45&&(!f||h.score-f.score>=.12)&&(g=h.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${r}"`,issueKey:e,availableTransitions:d.map(l=>({id:l.id,name:l.name,to:l.to?.name}))});c=g.id}await y(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:c}}});let p=await y(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:c,statusAfter:p?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${s}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"jira_list_projects",description:"List all Jira projects accessible to the user",input_schema:{type:"object",properties:{}}},{name:"jira_list_statuses",description:"List Jira statuses. Use projectKey to get statuses applicable in that project workflow.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Optional project key (e.g. PROJ). If omitted, returns global status catalog."}}}},{name:"jira_list_issue_types",description:"List issue types allowed for issue creation in the given project.",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"}},required:["projectKey"]}},{name:"jira_search",description:"Search Jira issues using JQL",input_schema:{type:"object",properties:{jql:{type:"string",description:'JQL query string, e.g. "project = PROJ AND status = Open"'},maxResults:{type:"number",description:"Max results to return (default 20)"}},required:["jql"]}},{name:"jira_get_issue",description:"Get details of a specific Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"}},required:["issueKey"]}},{name:"jira_create_issue",description:"Create a new Jira issue",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},summary:{type:"string",description:"Issue title/summary"},issueType:{type:"string",description:"Issue type (default: Task). Common: Task, Bug, Story, Epic"},description:{type:"string",description:"Issue description (plain text)"},priority:{type:"string",description:"Priority name, e.g. High, Medium, Low"},labels:{type:"array",items:{type:"string"},description:"Array of label strings"},assigneeId:{type:"string",description:"Atlassian account ID to assign to"},moveToSprint:{type:"boolean",description:"If true, move created issue to a sprint and verify."},moveToActiveSprint:{type:"boolean",description:"Backward-compatible alias for moveToSprint."},sprintId:{type:"number",description:"Optional sprint id for placement."},sprintName:{type:"string",description:"Optional sprint name for placement."},target:{type:"string",description:"Placement target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["projectKey","summary"]}},{name:"jira_list_sprints",description:"List sprints for a Jira project (returns sprint names, IDs, states, dates)",input_schema:{type:"object",properties:{projectKey:{type:"string",description:"Project key, e.g. PROJ"},state:{type:"string",description:"Filter: active, closed, future. Omit for all."}},required:["projectKey"]}},{name:"jira_get_sprint_issues",description:"Get all issues in a sprint, optionally filtered by status column name",input_schema:{type:"object",properties:{sprintName:{type:"string",description:"Sprint name (from jira_list_sprints). Use this OR sprintId."},sprintId:{type:"number",description:"Sprint ID (from jira_list_sprints). Use this OR sprintName."},projectKey:{type:"string",description:"Project key to scope the search (optional)"},status:{type:"string",description:'Filter by status name (e.g. "\u8FDB\u884C\u4E2D", "\u6D4B\u8BD5", "Done")'},maxResults:{type:"number",description:"Max issues to return (default 50)"}}}},{name:"jira_move_to_active_sprint",description:"Backward-compatible alias: move issue to sprint target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_move_issue_to_sprint",description:"Move an issue to a sprint by id/name/target and verify membership.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},projectKey:{type:"string",description:"Optional project key. If omitted, inferred from issue."},sprintId:{type:"number",description:"Optional sprint id."},sprintName:{type:"string",description:"Optional sprint name."},target:{type:"string",description:"Target when sprintId/sprintName omitted: current|active|latest (default: current)."}},required:["issueKey"]}},{name:"jira_get_comments",description:"Get comments on a Jira issue (newest first)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},maxResults:{type:"number",description:"Max comments to return (default 50)"}},required:["issueKey"]}},{name:"jira_add_comment",description:"Add a comment to a Jira issue",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},body:{type:"string",description:"Comment text (plain text)"}},required:["issueKey","body"]}},{name:"jira_edit_issue",description:"Update fields on a Jira issue (summary, story points, labels, priority)",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},fields:{type:"object",description:"Object of field names to values",additionalProperties:!0}},required:["issueKey","fields"]}},{name:"jira_transition_issue",description:"Move a Jira issue to a different status. Always pass toStatus when user gave a target; only pass issueKey alone when you explicitly need to list transitions.",input_schema:{type:"object",properties:{issueKey:{type:"string",description:"Issue key, e.g. PROJ-123"},transitionId:{type:"string",description:"Transition ID to perform (optional if toStatus is provided)"},toStatus:{type:"string",description:'Target status/column name (e.g. "\u5DF2\u7ECF\u9A8C\u6536", "Done", "In Progress"). If provided, tool resolves matching transition automatically.'}},required:["issueKey"]}}]};var z={new:"todo",indeterminate:"in_progress",done:"done"},H=/\b(blocked|on[\s-]?hold|waiting|stuck)\b/i;function $(s){if(!s)return"unknown";if(s.name&&H.test(s.name))return"blocked";let i=s.statusCategory?.key;return z[i]||"unknown"}function T(s){if(!s)return"";if(Array.isArray(s))return s.map(T).join("");if(s.type==="text")return s.text||"";if(s.type==="hardBreak"||s.type==="rule")return`
`;let i=s.content?T(s.content):"";return/^(paragraph|heading|listItem|blockquote|codeBlock|panel)$/.test(s.type)&&(i+=`
`),i}function A(s,i){let e=s.fields||{},t=e.status||null,a=null;if(s.self&&s.key)try{a=`${new URL(s.self).origin}/browse/${s.key}`}catch{a=null}return!a&&i&&s.key&&(a=`${String(i).replace(/\/+$/,"")}/browse/${s.key}`),{id:String(s.id??s.key??""),key:s.key,title:e.summary||"",body:typeof e.description=="string"?e.description:T(e.description?.content).trim(),state:t?.name||null,stateCategory:$(t),assignee:e.assignee?.displayName||null,url:a,_raw:s}}function R(s){let i=JSON.parse(s);if(i&&i.error)throw new Error(i.error);return i}var W={id:"jira",toStateCategory:$,toNeutral:A,async listCandidates(s={}){let i=s.query||"";if(!i.trim()){let n=[];if(s.state&&n.push(`status = "${s.state}"`),s.labels){let o=Array.isArray(s.labels)?s.labels:[s.labels];for(let r of o)n.push(`labels = "${r}"`)}s.updatedAfter&&n.push(`updated >= "${s.updatedAfter}"`),i=n.length?`${n.join(" AND ")} ORDER BY updated DESC`:"ORDER BY updated DESC"}let e=Number(s.limit)||30,t=`jql=${encodeURIComponent(i)}&maxResults=${e}&fields=summary,description,status,assignee,labels,project,updated,created`;return((await y(`/rest/api/3/search/jql?${t}`)).issues||[]).map(n=>A(n))},async getTicket(s){if(!s)throw new Error("key is required");let i=await y(`/rest/api/3/issue/${encodeURIComponent(s)}`);return!i||!i.key?null:A(i)},async getComments(s){if(!s)throw new Error("key is required");return(R(await v.handleToolCall("jira_get_comments",{issueKey:s})).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(s,i){if(!s||!i)throw new Error("key and body are required");return{ok:!!R(await v.handleToolCall("jira_add_comment",{issueKey:s,body:i})).ok,id:null}},async transition(s,i){if(!s)throw new Error("key is required");let e=JSON.parse(await v.handleToolCall("jira_transition_issue",{issueKey:s,toStatus:i}));if(!e.ok)return{ok:!1,error:e.error||"transition failed",_raw:e};let t=e.statusAfter||null;return{ok:!0,stateAfter:t,stateCategoryAfter:$(t?{name:t}:null),_raw:e}},async linkPullRequest(s,i,e){if(!s||!i)throw new Error("key and prUrl are required");try{return await y(`/rest/api/3/issue/${encodeURIComponent(s)}/remotelink`,{method:"POST",body:{object:{url:i,title:e||i,icon:{url16x16:"https://github.com/favicon.ico",title:"GitHub"}}}}),{ok:!0,via:"remotelink"}}catch(t){let a=`${e?`${e}: `:"Linked PR: "}${i}`;return{ok:!!R(await v.handleToolCall("jira_add_comment",{issueKey:s,body:a})).ok,via:"comment",error:String(t?.message||t)}}}},ie=W;export{ie as default,W as jiraAdapter};
