import{createRequire as T}from"module";import{resolveIntegrationToken as J,clearTokenCache as $}from"@zibby/core/backend-client.js";var O=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"}),U=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 q=T(import.meta.url);function K(){if(process.env.MCP_JIRA_PATH)return process.env.MCP_JIRA_PATH;try{return q.resolve("@zibby/mcp-jira/index.js")}catch{return null}}var C=new Set(["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","rule","table","tableRow","tableCell","tableHeader","mediaSingle","panel"]);function L(c,o){if(!o||!o.length)return c;let e=c;for(let t of o)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 S(c,o=0){if(!Array.isArray(c))return"";let e=[];for(let t of c){if(t.type==="text"){e.push(L(t.text||"",t.marks));continue}if(t.type==="hardBreak"){e.push(`
`);continue}if(t.type==="rule"){e.push(`
---
`);continue}let r=t.content?S(t.content,o+1):"";if(t.type==="listItem")e.push(r);else if(t.type==="bulletList"){let i=(t.content||[]).map(a=>`- ${S(a.content||[],o+1).trim()}`);e.push(`
${i.join(`
`)}
`)}else if(t.type==="orderedList"){let i=(t.content||[]).map((a,s)=>`${s+1}. ${S(a.content||[],o+1).trim()}`);e.push(`
${i.join(`
`)}
`)}else if(t.type==="heading"){let i=t.attrs?.level||2;e.push(`

${"#".repeat(i)} ${r.trim()}

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

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

`)}function k(c){return String(c||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_:："'`]/g,"")}function N(c){return k(c).replace(/[a-z0-9]+/g,"")}function I(c,o){let e=k(c),t=k(o);if(!e||!t)return 0;if(e===t)return 1;if(e.length===1||t.length===1)return e===t?1:0;let r=p=>{let d=new Map;for(let m=0;m<p.length-1;m++){let g=p.slice(m,m+2);d.set(g,(d.get(g)||0)+1)}return d},i=r(e),a=r(t),s=0,n=0,u=0;for(let p of i.values())n+=p;for(let p of a.values())u+=p;for(let[p,d]of i.entries()){let m=a.get(p)||0;s+=Math.min(d,m)}return 2*s/Math.max(1,n+u)}function b(c){return String(c||"").toLowerCase().replace(/\s+/g,"").replace(/[()\-_:："'`]/g,"")}function x(c,o=[]){let e=Array.isArray(o)?o:[];if(e.length===0)return{requested:c||null,resolved:null,strategy:"none"};let t=e.filter(s=>!s.subtask),r=t.length>0?t:e,i=b(c);if(i){let s=r.find(p=>b(p.name)===i);if(s)return{requested:c,resolved:s,strategy:"exact"};let n={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 p of Object.values(n)){if(!p.some(m=>b(m)===i))continue;let d=r.find(m=>p.some(g=>b(g)===b(m.name)));if(d)return{requested:c,resolved:d,strategy:"alias"}}let u=r.map(p=>({t:p,score:I(c,p.name)})).sort((p,d)=>d.score-p.score);if(u[0]&&u[0].score>=.5)return{requested:c,resolved:u[0].t,strategy:"fuzzy"}}let a=["task","story","bug","improvement","epic"];for(let s of a){let n=r.find(u=>b(u.name)===s);if(n)return{requested:c||null,resolved:n,strategy:"default-preferred"}}return{requested:c||null,resolved:r[0],strategy:"default-first"}}async function A(c){let o=`projectKeys=${encodeURIComponent(c)}&expand=projects.issuetypes`,e=await f(`/rest/api/3/issue/createmeta?${o}`),t=Array.isArray(e?.projects)?e.projects:[],i=t.find(s=>String(s?.key||"").toUpperCase()===String(c||"").toUpperCase())||t[0]||null;return(Array.isArray(i?.issuetypes)?i.issuetypes:[]).map(s=>({id:s.id,name:s.name,subtask:!!s.subtask,description:s.description||null}))}async function R(c,o){if(!c)throw new Error("projectKey is required");let e="sprint is not EMPTY";o==="active"?e="sprint in openSprints()":o==="closed"?e="sprint in closedSprints()":o==="future"&&(e="sprint in futureSprints()");let t=`project = ${c} AND ${e} ORDER BY updated DESC`,r=`jql=${encodeURIComponent(t)}&maxResults=100&fields=customfield_10020`,i=await f(`/rest/api/3/search/jql?${r}`),a=new Map;for(let s of i.issues||[])for(let n of s.fields?.customfield_10020||[])n&&!a.has(n.id)&&a.set(n.id,{id:n.id,name:n.name,state:n.state,boardId:n.boardId||null,startDate:n.startDate||null,endDate:n.endDate||null,goal:n.goal||null});return[...a.values()].sort((s,n)=>{let u={active:0,future:1,closed:2},p=(u[s.state]??3)-(u[n.state]??3);return p!==0?p:String(n.startDate||"").localeCompare(String(s.startDate||""))})}function D(c,{sprintId:o,sprintName:e,target:t}={}){let r=Array.isArray(c)?c:[];if(!r.length)return{sprint:null,selectedBy:"none"};if(o!=null&&String(o).trim()!=="")return{sprint:r.find(s=>String(s.id)===String(o))||null,selectedBy:"id"};if(e&&String(e).trim()){let a=String(e).trim(),s=r.find(u=>String(u.name||"").toLowerCase()===a.toLowerCase());if(s)return{sprint:s,selectedBy:"name-exact"};let n=r.map(u=>({s:u,score:I(a,u.name||"")})).sort((u,p)=>p.score-u.score);return n[0]&&n[0].score>=.5?{sprint:n[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:r[0],selectedBy:i}:{sprint:r[0],selectedBy:"default"}}function E(c,o){let e=c?.fields?.customfield_10020;return Array.isArray(e)?e.some(t=>String(t?.id)===String(o)):!1}async function B({issueKey:c,projectKey:o,sprintId:e,attempts:t=3,delayMs:r=450}){let i=[];for(let a=0;a<t;a++){try{let s=`project = ${o} AND key = ${c} AND sprint = ${e}`,n=`jql=${encodeURIComponent(s)}&maxResults=1&fields=key,status`,u=await f(`/rest/api/3/search/jql?${n}`);if(Number(u?.total||0)>0)return i.push({attempt:a+1,jql:!0,issueField:null}),{ok:!0,method:"jql",traces:i};let d=await f(`/rest/api/3/issue/${c}?fields=customfield_10020,status`),m=E(d,e);if(i.push({attempt:a+1,jql:!1,issueField:m}),m)return{ok:!0,method:"issue_field",traces:i}}catch(s){i.push({attempt:a+1,error:String(s?.message||s)})}a<t-1&&await new Promise(s=>setTimeout(s,r))}return{ok:!1,method:"none",traces:i}}async function w({issueKey:c,projectKey:o,sprintId:e,sprintName:t,target:r}){if(!c)return{ok:!1,error:"issueKey is required"};let i=o;if(!i&&(i=(await f(`/rest/api/3/issue/${c}?fields=project`))?.fields?.project?.key||null,!i))return{ok:!1,error:`Could not resolve project for ${c}`};let a=await R(i,"active");if(!a.length)return{ok:!1,error:`No assignable active sprint found for project ${i}`};let{sprint:s,selectedBy:n}=D(a,{sprintId:e,sprintName:t,target:r});if(!s)return{ok:!1,error:`No matching sprint found in ${i}`,requested:{sprintId:e??null,sprintName:t??null,target:r??"current"},availableSprints:a.map(d=>({id:d.id,name:d.name,state:d.state}))};await f(`/rest/api/3/issue/${c}`,{method:"PUT",body:{fields:{customfield_10020:Number(s.id)}}});let u=await B({issueKey:c,projectKey:i,sprintId:s.id}),p=u.ok;return{ok:p,issueKey:c,projectKey:i,sprintId:s.id,sprintName:s.name,selectedBy:n,verifiedBy:u.method,verified:p,verificationTrace:u.traces,warning:p?null:`Sprint assignment attempted but verification did not find ${c} in sprint ${s.id}`}}async function f(c,o={}){let e=async()=>{let{token:t,cloudId:r}=await J("jira");if(typeof t!="string"||!t)throw new Error(`Invalid jira token type: ${typeof t}`);if(!r)throw new Error("Invalid jira cloudId: missing");let i=`https://api.atlassian.com/ex/jira/${r}${c}`,a=await fetch(i,{method:o.method||"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json",...o.body?{"Content-Type":"application/json"}:{},...o.headers},body:o.body?JSON.stringify(o.body):void 0});if(!a.ok){let n=await a.text().catch(()=>"");throw new Error(`Jira API ${a.status}: ${n.slice(0,300)}`)}let s=await a.text().catch(()=>"");if(!s||!s.trim())return{};try{return JSON.parse(s)}catch{return{raw:s}}};try{return await e()}catch(t){let r=String(t?.message||t||"").toLowerCase();if(!(r.includes("token")||r.includes("401")||r.includes("403")||r.includes("substring")))throw t;return $("jira"),e()}}var z={id:"jira",serverName:"jira",allowedTools:["mcp__jira__*"],requiresIntegration:O.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 c=K();if(!c)return null;let o={};for(let e of this.envKeys)process.env[e]&&(o[e]=process.env[e]);return process.env.ATLASSIAN_INSTANCE_URL&&(o.ATLASSIAN_INSTANCE_URL=process.env.ATLASSIAN_INSTANCE_URL),{command:"node",args:[c],env:o,description:this.description}},async handleToolCall(c,o){try{switch(c){case"jira_list_projects":{let e=await f("/rest/api/3/project"),t=(Array.isArray(e)?e:[]).map(r=>({id:r.id,key:r.key,name:r.name,style:r.style}));return JSON.stringify({count:t.length,projects:t})}case"jira_list_statuses":{let{projectKey:e}=o||{};if(e){let i=await f(`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),a=Array.isArray(i)?i:[],s=new Map;for(let u of a)for(let p of u.statuses||[])p?.id&&(s.has(p.id)||s.set(p.id,{id:p.id,name:p.name,category:p.statusCategory?.name||null}));let n=[...s.values()].sort((u,p)=>String(u.name).localeCompare(String(p.name)));return JSON.stringify({scope:"project",projectKey:e,count:n.length,statuses:n})}let t=await f("/rest/api/3/status"),r=(Array.isArray(t)?t:[]).map(i=>({id:i.id,name:i.name,category:i.statusCategory?.name||null})).sort((i,a)=>String(i.name).localeCompare(String(a.name)));return JSON.stringify({scope:"global",count:r.length,statuses:r})}case"jira_list_issue_types":{let{projectKey:e}=o||{};if(!e)return JSON.stringify({error:"projectKey is required"});let t=await A(e);return JSON.stringify({projectKey:e,count:t.length,issueTypes:t})}case"jira_search":{let e=o.jql||"",t=o.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`,s=((await f(`/rest/api/3/search/jql?${i}`)).issues||[]).map(n=>({key:n.key,project:n.fields?.project?.key,summary:n.fields?.summary,status:n.fields?.status?.name,assignee:n.fields?.assignee?.displayName||"Unassigned",priority:n.fields?.priority?.name,type:n.fields?.issuetype?.name}));return JSON.stringify({count:s.length,issues:s})}case"jira_get_issue":{let e=o.issueKey;if(!e)return JSON.stringify({error:"issueKey is required"});let t=await f(`/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:r,description:i,priority:a,labels:s,assigneeId:n,moveToSprint:u,moveToActiveSprint:p,sprintId:d,sprintName:m,target:g}=o;if(!e||!t)return JSON.stringify({error:"projectKey and summary are required"});let l={requested:r||null,resolved:null,strategy:"none"},h=[];try{h=await A(e),l=x(r,h)}catch{}let y={project:{key:e},summary:t,issuetype:l?.resolved?.id?{id:l.resolved.id}:{name:r||"Task"}};i&&(y.description={type:"doc",version:1,content:[{type:"paragraph",content:[{type:"text",text:i}]}]}),a&&(y.priority={name:a}),s?.length&&(y.labels=s),n&&(y.assignee={id:n});let j=await f("/rest/api/3/issue",{method:"POST",body:{fields:y}}),_={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(v=>v.name)),(u||p)&&(_.sprintMove=await w({issueKey:j.key,projectKey:e,sprintId:d,sprintName:m,target:g})),JSON.stringify(_)}case"jira_list_sprints":{let{projectKey:e,state:t}=o,r=await R(e,t);return JSON.stringify({count:r.length,sprints:r})}case"jira_move_to_active_sprint":{let{issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:a}=o||{},s=await w({issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:a||"current"});return JSON.stringify(s)}case"jira_move_issue_to_sprint":{let{issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:a}=o||{},s=await w({issueKey:e,projectKey:t,sprintId:r,sprintName:i,target:a});return JSON.stringify(s)}case"jira_get_sprint_issues":{let{sprintName:e,sprintId:t,projectKey:r,status:i,maxResults:a}=o;if(!e&&!t)return JSON.stringify({error:"sprintName or sprintId is required"});let s=a||50,n=t?`sprint = ${t}`:`sprint = "${e}"`,u=r?`project = ${r} AND `:"",p=i?` AND status = "${i}"`:"",d=`${u}${n}${p} ORDER BY status ASC, priority DESC`,m=`jql=${encodeURIComponent(d)}&maxResults=${s}&fields=summary,status,assignee,priority,issuetype,project`,g=await f(`/rest/api/3/search/jql?${m}`),l=(g.issues||[]).map(y=>({key:y.key,project:y.fields?.project?.key,summary:y.fields?.summary,status:y.fields?.status?.name,assignee:y.fields?.assignee?.displayName||"Unassigned",priority:y.fields?.priority?.name,type:y.fields?.issuetype?.name})),h={};for(let y of l)h[y.status]=(h[y.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}=o;if(!e)return JSON.stringify({error:"issueKey is required"});let i=await f(`/rest/api/3/issue/${e}/comment?maxResults=${t||50}&orderBy=-created`),a=(i.comments||[]).map(s=>{let n="";return s.body?.content&&(n=S(s.body.content)),{id:s.id,author:s.author?.displayName||"Unknown",body:n,created:s.created,updated:s.updated}});return JSON.stringify({count:a.length,total:i.total||a.length,comments:a})}case"jira_add_comment":{let{issueKey:e,body:t}=o;return!e||!t?JSON.stringify({error:"issueKey and body are required"}):(await f(`/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}=o;return!e||!t?JSON.stringify({error:"issueKey and fields are required"}):(await f(`/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:r,statusName:i,status:a}=o;if(!e)return JSON.stringify({error:"issueKey is required"});let s=String(r||i||a||"").trim();if(!t&&!s){let d=((await f(`/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 n=t;if(!n){let d=(await f(`/rest/api/3/issue/${e}/transitions`)).transitions||[],m=k(s),g=d.find(l=>k(l?.name||"")===m||k(l?.to?.name||"")===m);if(!g){let l=N(s);l.length>=2&&(g=d.find(h=>{let y=N(h?.name||""),j=N(h?.to?.name||""),_=y.length>=2&&(y.includes(l)||l.includes(y)),v=j.length>=2&&(j.includes(l)||l.includes(j));return _||v}))}if(!g){let l=d.map(_=>{let v=I(s,_?.name||""),P=I(s,_?.to?.name||"");return{t:_,score:Math.max(v,P)}}).sort((_,v)=>v.score-_.score),h=l[0],y=l[1];h&&h.score>=.45&&(!y||h.score-y.score>=.12)&&(g=h.t)}if(!g?.id)return JSON.stringify({ok:!1,error:`No transition matches target status: "${s}"`,issueKey:e,availableTransitions:d.map(l=>({id:l.id,name:l.name,to:l.to?.name}))});n=g.id}await f(`/rest/api/3/issue/${e}/transitions`,{method:"POST",body:{transition:{id:n}}});let u=await f(`/rest/api/3/issue/${e}?fields=status`);return JSON.stringify({ok:!0,issueKey:e,transitionId:n,statusAfter:u?.fields?.status?.name||null})}default:return JSON.stringify({error:`Unknown tool: ${c}`})}}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"]}}]};export{f as jiraFetch,z as jiraSkill};
